glapp
Class GLApp

java.lang.Object
  extended by glapp.GLApp

public class GLApp
extends java.lang.Object

Collection of functions to init and run an OpenGL app using LWJGL.

Includes functions to handle:
Setup display mode, keyboard, mouse, handle events
Run main loop of application
Buffer allocation -- manage IntBuffer, ByteBuffer calls.
OpenGL functions -- convert screen/world coords, set modes, lights, etc.
Utility functions -- load images, convert pixels, getTimeInMillis, etc.

Has a main() function to run as an application, though this class has only minimal placeholder functionality. It is meant to be subclassed, and the subclass will define setup() draw() mouseMove() functions, etc.

GLApp initializes the LWJGL environment for OpenGL rendering, ie. creates a window, sets the display mode, inits mouse and keyboard, then runs a loop.

Uses GLImage to load and hold image pixels.

napier -at- potatoland -dot- org

See Also:
GLImage

Field Summary
static java.net.URL appletBaseURL
           
static float aspectRatio
           
static java.nio.FloatBuffer bufferModelviewMatrix
           
static java.nio.FloatBuffer bufferProjectionMatrix
           
static java.nio.IntBuffer bufferViewport
           
static float[] colorBlack
           
static float[] colorBlue
           
static float[] colorClear
           
static float[] colorGray
           
static float[] colorGreen
           
static float[] colorRed
           
static float[] colorWhite
           
static java.lang.String configFilename
           
static int cursorX
           
static int cursorY
           
static int depthBufferBits
           
static boolean disableNativeCursor
           
static int displayColorBits
           
static int displayFrequency
           
static int displayHeight
           
static java.util.ArrayList displayLists
           
static DisplayMode displayMode
           
static int displayWidth
           
static DisplayMode DM
           
static boolean finished
           
static int finishedKey
           
static int frameCount
           
static boolean fullScreen
           
static java.lang.String GLAPP_VERSION
           
static boolean hideNativeCursor
           
static double lastFrameTime
           
static java.nio.FloatBuffer mtlambient
           
static java.nio.FloatBuffer mtldiffuse
           
static java.nio.FloatBuffer mtlemissive
           
static java.nio.FloatBuffer mtlshininess
           
static java.nio.FloatBuffer mtlspecular
           
static DisplayMode origDM
           
static float PIOVER180
           
static float PIUNDER180
           
static java.lang.Class rootClass
           
static float rotation
           
static int screenTextureSize
           
static double secondsSinceLastFrame
           
static java.util.Properties settings
           
static boolean showMessages
           
static int SIZE_BYTE
           
static int SIZE_DOUBLE
           
static int SIZE_FLOAT
           
static int SIZE_INT
           
static long ticksPerSecond
           
static java.nio.ByteBuffer tmpByte
           
static java.nio.ByteBuffer tmpFloat
           
static java.nio.FloatBuffer tmpFloats
           
static java.nio.ByteBuffer tmpInt
           
static java.nio.IntBuffer tmpInts
           
static java.nio.FloatBuffer tmpResult
           
static boolean useCurrentDisplay
           
static int viewportH
           
static int viewportW
           
static int viewportX
           
static int viewportY
           
static boolean VSyncEnabled
           
static java.lang.String window_title
           
 
Constructor Summary
GLApp()
           
 
Method Summary
static void activateMask(int maskvalue)
          Restrict rendering to the masked area.
static void activateTexture(int textureHandle)
          "Select" the given texture for further texture operations.
static int allocateTexture()
          Allocate a texture (glGenTextures) and return the handle to it.
static java.nio.ByteBuffer allocBytes(byte[] bytearray)
           
static java.nio.ByteBuffer allocBytes(int howmany)
           
static java.nio.DoubleBuffer allocDoubles(double[] darray)
           
static java.nio.DoubleBuffer allocDoubles(int howmany)
           
static java.nio.FloatBuffer allocFloats(float[] floatarray)
           
static java.nio.FloatBuffer allocFloats(int howmany)
           
static java.nio.IntBuffer allocInts(int howmany)
           
static java.nio.IntBuffer allocInts(int[] intarray)
           
static void applyMaterial()
          Call glMaterial() to activate these material properties in the OpenGL environment.
static int beginDisplayList()
          Begin a display list.
static void beginMask(int maskvalue)
          Begin creating a mask.
static void buildFont(int fontTxtrHandle, int fontWidth)
          Build the character set display list from the given texture.
static boolean buildFont(java.lang.String charSetImage, int fontWidth)
          Build a character set from the given texture image.
static void callDisplayList(int displayListID)
          Render the geometry stored in a display list.
 void cleanup()
          Run() calls this right before exit.
static void clearMask()
          clear the stencil buffer
static void copyImageToTexture(GLImage img, int textureHandle)
          Calls glTexSubImage2D() to copy pixels from an image into a texture.
static void copyPixelsToTexture(java.nio.ByteBuffer bb, int w, int h, int textureHandle)
          Copy pixels from a ByteBuffer to a texture.
static void deleteTexture(int textureHandle)
          De-allocate the given texture (glDeleteTextures()).
static void destroyDisplayList(int DL_ID)
          Delete the given display list ID.
static void destroyDisplayLists()
          Clean up the allocated display lists.
static void destroyFont()
          Clean up the allocated display lists for the character set.
static void disableMask()
          turn off the stencil test so stencil has no further affect on rendering.
static void disableNativeCursor(boolean off)
          If the param is true, turn off the hardware cursor.
 void draw()
          Called by run() to draw one frame.
static void drawCircle(float innerRadius, float outerRadius, int numSegments)
          Draws a circle centered at 0,0,0.
static void drawCircle(int x, int y, int radius, int linewidth)
          Draws a circle with the given radius centered at the given world position.
static void drawCircleZ(int x, int y, int z, int radius, int linewidth)
          Draws a circle with the given radius centered at the given world position.
static void drawCursor(int cursorTextureHandle)
          Draw a cursor image textured onto a quad at cursorX,cursorY.
static void drawCursorOLD(int cursorTextureHandle)
          OLD function: this drew the cursor only into the current viewport, and could not handle difffent ortho coordinate systems (ortho had to be exactly mapped to screen size).
static void drawImage(GLImage img, int x, int y, float w, float h)
          Draw an image in whichever projection mode is current (does not switch to ortho mode).
static void drawImageFullScreen(GLImage img)
          Draw an image in ortho mode (2D) over the entire viewport area.
static void drawQuad(int textureHandle, int x, int y, float w, float h)
          Draw a textured quad in Ortho mode (2D) at the given xy, scaled to the given width and height.
static void drawQuadZ(int textureHandle, float x, float y, float z, float w, float h)
          Draw a textured quad at the given xyz position in 3D space.
static void drawRect(int x, int y, float w, float h)
          Draw a rectangle outline in ortho mode (draws in 2D over the scene).
static void drawRectZ(int x, int y, int z, float w, float h)
          Draw a rectangle outline in world space.
static void endDisplayList()
          Finish display list creation.
static void endMask()
          End the mask.
static void err(java.lang.String text)
          Show an error message on the system console (calls System.out.println()).
 void exit()
          Shutdown the application.
static boolean extensionExists(java.lang.String extensionName)
          Return true if the OpenGL context supports the given OpenGL extension.
static void frameCopy(int txtrHandle)
          Save entire screen image to a texture.
static void frameCopy(int txtrHandle, int x, int y, int w, int h)
          Save a region of the screen to a texture.
static void frameCopy(Pbuffer pbuff, int textureHandle)
          Copy the pbuffer contents to a texture.
static void frameDraw(int txtrHandle)
          Draw the screen-sized image over entire screen area.
static java.nio.ByteBuffer framePixels()
          Return a ByteBuffer containing ARGB pixels of the entire screen area.
static java.nio.ByteBuffer framePixels(int x, int y, int w, int h)
          Return a ByteBuffer containing ARGB pixels from the given screen area.
static int[] framePixelsInt(int x, int y, int w, int h)
          Return an int array containing ARGB pixels from the given screen area.
static void frameSave()
          Save the current frame buffer to a PNG image.
static void get(java.nio.ByteBuffer b, int[] values)
          copy ints from the given byteBuffer into the given int array.
static void get(java.nio.IntBuffer b, int[] values)
          copy ints from the given IntBuffer into the given int array.
static byte[] getBytesFromFile(java.lang.String filename)
          Return an array of bytes read from a file.
static byte[] getBytesFromStream(java.io.InputStream is)
          Return an array of bytes read from an InputStream.
static DisplayMode getDisplayMode(int w, int h, int colorBits, int freq)
          Retrieve a DisplayMode object with the given params
static double getFramesPerSecond()
          Return the moving average of the frames per second for the last 50 frames.
static int getHeight()
          return the height of the Viewport (the screen area that OpenGL will draw into).
static int getHeightWindow()
          return the Display height (the height of the full window).
static java.io.InputStream getInputStream(java.lang.String filename)
          Open the given file and return the InputStream.
static int[] getInts(java.nio.ByteBuffer b)
          return the contents of the byteBuffer as an array of ints.
static int getMaskValue(int x, int y)
          Return the stencil buffer value at the given screen position.
static float[][] getMatrixAsArray(java.nio.FloatBuffer fb)
          Convert a FloatBuffer matrix to a 4x4 float array.
static java.nio.FloatBuffer getModelviewMatrix()
           
static java.lang.String[] getPathAndFile(java.lang.String filename)
          Return a String array containing the path portion of a filename (result[0]), and the fileame (result[1]).
static byte[] getPixelColor(int x, int y)
          Return the color buffer RGB value at the given screen position as byte[3].
static float getPixelDepth(int x, int y)
          Return the depth buffer value at the given screen position.
static int getPixelStencil(int x, int y)
          Return the stencil buffer value at the given screen position.
static int getPowerOfTwoBiggerThan(int n)
          Find a power of two equal to or greater than the given value.
static java.nio.FloatBuffer getProjectionMatrix()
           
static java.lang.String getProperty(java.util.Properties props, java.lang.String propName)
           
static java.lang.String getProperty(java.lang.String propertyName)
          Return a property from the application configuration file (the filename given in the configFilename variable).
static boolean getPropertyBool(java.util.Properties props, java.lang.String propName)
           
static float getPropertyFloat(java.util.Properties props, java.lang.String propName)
           
static int getPropertyInt(java.util.Properties props, java.lang.String propName)
           
static double getSecondsPerFrame()
          Return the moving average of the seconds per frame for the last 50 frames.
static int getSettingInt(int whichSetting)
          retrieve a setting from OpenGL (calls glGetInteger())
static double getTimeInMillis()
           
static double getTimeInSeconds()
           
static java.nio.IntBuffer getViewport()
           
static int getWidth()
          return the width of the Viewport (the screen area that OpenGL will draw into).
static int getWidthWindow()
          return the Display width (the width of the full window).
static float[] getWorldCoordsAtScreen(int x, int y)
          For given screen xy, return the world xyz coords in a float array.
static float[] getWorldCoordsAtScreen(int x, int y, float z)
          For given screen xy and z depth, return the world xyz coords in a float array.
static float getZDepth(int x, int y)
          Return the Z depth of the single pixel at the given screen position.
static float getZDepthAtOrigin()
          Find the Z depth of the origin in the projected world view.
 void handleEvents()
          Called by the run() loop.
static void hideNativeCursor(boolean hide)
          If param is true, make the native cursor transparent.
 void init()
          Called only once when app is first started, init() prepares the display, mouse and OpenGL context for use.
static boolean initDisplay()
          Initialize the Display mode, viewport size, and open a Window.
 void initGL()
          Initialize the OpenGL context.
static void initInput()
          Initialize the Keyboard and Mouse.
 void invoke(java.lang.reflect.Method method)
          Similar to the static invoke() function, this execute a method on the GLApp class or subclass.
static void invoke(java.lang.Object object, java.lang.reflect.Method method)
          Execute a method on the given object.
static boolean isPowerOf2(int n)
          Returns true if n is a power of 2.
 char keyChar()
          Return the character associatated with the last key event.
 void keyDown(int keycode)
          Called when key is pressed.
 void keyUp(int keycode)
          Called when key is released.
static GLImage loadImage(java.lang.String imgFilename)
          Load an image from the given file and return a GLImage object.
static java.nio.ByteBuffer loadImagePixels(java.lang.String imgFilename)
          Load an image from the given file and return a ByteBuffer containing ARGB pixels.
Can be used to create textures.
static java.util.Properties loadPropertiesFile(java.lang.String configFilename)
          Load configuration settings from a properties file.
 void loadSettings(java.lang.String configFilename)
          Load configuration settings from optional properties file.
static void lookAt(float lookatX, float lookatY, float lookatZ, float distance)
          A simple way to set eye position.
static void main(java.lang.String[] args)
           
static GLImage makeImage(int w, int h)
          Make a blank image of the given size.
static Pbuffer makePbuffer(int width, int height)
          Create a Pbuffer for use as an offscreen buffer, with the given width and height.
static int makeTexture(java.nio.ByteBuffer pixels, int w, int h, boolean anisotropic)
          Create a texture from the given pixels in the default OpenGL RGBA pixel format.
static int makeTexture(GLImage textureImg)
          Create a texture from the given image.
static int makeTexture(int w)
          Create a blank square texture with the given size.
static int makeTexture(int[] pixelsARGB, int w, int h, boolean anisotropic)
          Create a texture from the given pixels in the default Java ARGB int format.
Configure the texture to repeat in both directions and use LINEAR for magnification.
static int makeTexture(java.lang.String textureImagePath)
          Create a texture and mipmap from the given image file.
static int makeTexture(java.lang.String textureImagePath, boolean mipmap, boolean anisotropic)
          Create a texture and optional mipmap with the given parameters.
static int makeTextureARGB(java.nio.ByteBuffer pixels, int w, int h)
          Create a texture from the given pixels in ARGB format.
static int makeTextureForScreen(int screenSize)
          Create a texture large enough to hold the screen image.
static int makeTextureMipMap(int textureHandle, GLImage textureImg)
          Build Mipmaps for currently bound texture (builds a set of textures at various levels of detail so that texture will scale up and down gracefully)
static java.lang.String makeTimestamp()
          make a time stamp for filename
static java.lang.reflect.Method method(java.lang.Object object, java.lang.String methodName)
          Find a method in the given class with the given method name.
 java.lang.reflect.Method method(java.lang.String methodName)
          Similar to the static method() function, this looks for the method in the GLApp class (or it's subclass).
 boolean mouseButtonDown(int whichButton)
          Return true if the given mousebutton is down.
 void mouseDown(int x, int y)
           
 void mouseMove(int x, int y)
          Called by handleEvents() when mouse moves
 void mouseUp(int x, int y)
           
 void mouseWheel(int wheelMoved)
           
static void msg(java.lang.String text)
          Show a debug message on the system console (calls System.out.println()).
static void popAttrib()
          return to the OpenGL settings that were preserved by the previous pushAttrib() call.
static void print(int x, int y, java.lang.String msg)
          Render a text string in 2D over the scene, using the character set created by buildFont().
static void print(int x, int y, java.lang.String msg, int set)
          Render a text string in 2D over the scene, using the character set created by buildFont().
static void printZ(float x, float y, float z, int set, float scale, java.lang.String msg)
          Render a text string in model space, using the character set created by buildFont().
static void project(float x, float y, float z, float[] resultf)
          Return screen coordinates for a given point in world space.
static void pushAttrib()
          preserve all OpenGL settings that can be preserved.
static void pushAttrib(int attribute_bits)
          preserve the specified OpenGL setting.
static void pushAttribOrtho()
          preserve the OpenGL settings that will be affected when we draw in ortho mode over the scene.
static void pushAttribViewport()
          preserve the OpenGL viewport settings.
static void put(java.nio.ByteBuffer b, byte[] values)
           
static void put(java.nio.DoubleBuffer b, double[] values)
           
static void put(java.nio.FloatBuffer b, float[] values)
           
static void put(java.nio.IntBuffer b, int[] values)
           
static float random()
          Return a random floating point value between 0 and 1
static float random(float upperbound)
          Return a random floating point value between 0 and upperbound (not including upperbound)
static int random(int upperbound)
          Return a random integer value between 0 and upperbound (not including upperbound)
 void render()
          Same as draw().
static void renderCube()
          Render a 2 unit cube centered at origin.
static void renderCube(float size, int segments)
          draw a cube with the given size, centered at origin.
static void renderPlane(float length, float height, int length_segments, int height_segments)
          draw a rectangular plane in the X,Y axis, centered at origin.
static void renderPlane(float size, int segments)
          draw a square plane in the X,Y axis, centered at origin.
static void renderSphere()
          draw a sphere with 48 facets (pretty smooth) with normals and texture coords
static void renderSphere(int facets)
          call the LWJGL Sphere class to draw sphere geometry with texture coordinates and normals
static void resetViewport()
          Reset the viewport to full screen (displayWidth x displayHeight).
static int round(float f)
          Round a float value to the nearest int.
 void run()
          Runs the application.
static void savePixelsToPNG(java.nio.ByteBuffer framebytes, int width, int height, java.lang.String imageFilename, boolean flipY)
          Save a ByteBuffer of ARGB pixels to a PNG file.
static void screenShot()
          Save the current frame buffer to a PNG image.
static void screenShot(int x, int y, int width, int height, java.lang.String imageFilename)
          Save a region of the current render buffer to a PNG image.
static void screenShot(java.lang.String imageFilename)
          Save the current frame buffer to a PNG image.
static void screenShotRGB(int width, int height, java.lang.String saveFilename)
          Save the contents of the current render buffer to a PNG image.
static void selectDisplay()
          Make the Display the current context for OpenGL commands.
static Pbuffer selectPbuffer(Pbuffer pb)
          Make the pbuffer the current context for opengl commands.
static void setAmbientLight(float[] ambientLightColor)
          Set the color of the Global Ambient Light.
static void setBackgroundColor(float R, float G, float B)
          Set the background color of the screen.
static void setColor(float[] rgba)
          Set the current color to the given RGB or RGBA float array.
static void setColor(float R, float G, float B, float A)
          Set the current color with RGBA floats in range 0-1.
static void setColorB(int R, int G, int B, int A)
          Set the current color with RGBA bytes in range 0-255.
static void setColorMaterial(boolean on)
          Enable/disable the color-material setting.
static void setCursorPosition(int screenX, int screenY)
          Set the cursorX,cursorY position.
static void setFog(boolean on)
          Enable/disable fog effect.
static void setFog(float[] fogColor, float fogdensity)
          Enable atmospheric fog effect, with the given color and density.
static void setLight(int GLLightHandle, boolean on)
          enable/disable the given light.
static void setLight(int GLLightHandle, float[] diffuseLightColor, float[] ambientLightColor, float[] specularLightColor, float[] position)
          Set the color of a 'positional' light (a light that has a specific position within the scene).
static void setLighting(boolean on)
          Enable/disable lighting.
static void setLightPosition(int GLLightHandle, float[] position)
          Set the position (or direction) of a light to the given xyz.
static void setLightPosition(int GLLightHandle, float x, float y, float z)
          Set the position of a light to the given xyz.
static void setLineWidth(int width)
          Sets glLineWidth() and glPointSize() to the given width.
static void setMaterial(float[] surfaceColor, float shiny)
          A simple way to set the current material properties to approximate a "real" surface.
static void setMaterial(float[] diffuseColor, float[] ambientColor, float[] specularColor, float[] emissiveColor, float shininess)
          Set the four material colors and calls glMaterial() to change the current material color in OpenGL.
static void setMaterialAlpha(float alpha)
          Alter the material opacity by setting the diffuse material color alpha value to the given value
static void setOrtho()
          Set OpenGL to render in flat 2D (no perspective) with a one-to-one relation between screen pixels and world coordinates, ie.
static void setOrtho(int width, int height)
           
static void setOrthoOff()
          Turn 2D mode off.
static void setOrthoOn()
          Set OpenGL to render in flat 2D (no perspective) on top of current scene.
static void setPerspective()
          Set OpenGL to render in 3D perspective.
 void setRootClass()
          Hold onto this Class for later class.getResource() calls (to load resources from JAR files, see getInputStream()) and also to get class name for use in screenshot filenames (see screenShot()).
static void setSpotLight(int GLLightHandle, float[] diffuseLightColor, float[] ambientLightColor, float[] position, float[] direction, float cutoffAngle)
           
 void setup()
          Setup can be overridden by the subclass to initialize the application ie load textures, models, and create data structures used by the app.
static void setViewport(int x, int y, int width, int height)
          Define the position and size of the screen area in which the OpenGL context will draw.
static void unProject(float x, float y, float z, float[] resultf)
          Return world coordinates for a given point on the screen.
 void update()
          Update can be overridden by the subclass
static void updateTimer()
          Calculate time since we last called updateTimer().
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

GLAPP_VERSION

public static final java.lang.String GLAPP_VERSION
See Also:
Constant Field Values

SIZE_DOUBLE

public static final int SIZE_DOUBLE
See Also:
Constant Field Values

SIZE_FLOAT

public static final int SIZE_FLOAT
See Also:
Constant Field Values

SIZE_INT

public static final int SIZE_INT
See Also:
Constant Field Values

SIZE_BYTE

public static final int SIZE_BYTE
See Also:
Constant Field Values

finishedKey

public static int finishedKey

window_title

public static java.lang.String window_title

configFilename

public static java.lang.String configFilename

hideNativeCursor

public static boolean hideNativeCursor

disableNativeCursor

public static boolean disableNativeCursor

VSyncEnabled

public static boolean VSyncEnabled

useCurrentDisplay

public static boolean useCurrentDisplay

fullScreen

public static boolean fullScreen

showMessages

public static boolean showMessages

aspectRatio

public static float aspectRatio

displayWidth

public static int displayWidth

displayHeight

public static int displayHeight

displayColorBits

public static int displayColorBits

displayFrequency

public static int displayFrequency

depthBufferBits

public static int depthBufferBits

viewportX

public static int viewportX

viewportY

public static int viewportY

viewportW

public static int viewportW

viewportH

public static int viewportH

DM

public static DisplayMode DM

origDM

public static DisplayMode origDM

displayMode

public static DisplayMode displayMode

settings

public static java.util.Properties settings

finished

public static boolean finished

cursorX

public static int cursorX

cursorY

public static int cursorY

lastFrameTime

public static double lastFrameTime

secondsSinceLastFrame

public static double secondsSinceLastFrame

ticksPerSecond

public static long ticksPerSecond

frameCount

public static int frameCount

screenTextureSize

public static int screenTextureSize

bufferViewport

public static java.nio.IntBuffer bufferViewport

bufferModelviewMatrix

public static java.nio.FloatBuffer bufferModelviewMatrix

bufferProjectionMatrix

public static java.nio.FloatBuffer bufferProjectionMatrix

tmpResult

public static java.nio.FloatBuffer tmpResult

tmpFloats

public static java.nio.FloatBuffer tmpFloats

tmpFloat

public static java.nio.ByteBuffer tmpFloat

tmpInts

public static java.nio.IntBuffer tmpInts

tmpByte

public static java.nio.ByteBuffer tmpByte

tmpInt

public static java.nio.ByteBuffer tmpInt

mtldiffuse

public static java.nio.FloatBuffer mtldiffuse

mtlambient

public static java.nio.FloatBuffer mtlambient

mtlspecular

public static java.nio.FloatBuffer mtlspecular

mtlemissive

public static java.nio.FloatBuffer mtlemissive

mtlshininess

public static java.nio.FloatBuffer mtlshininess

rotation

public static float rotation

PIOVER180

public static final float PIOVER180
See Also:
Constant Field Values

PIUNDER180

public static final float PIUNDER180
See Also:
Constant Field Values

colorClear

public static final float[] colorClear

colorBlack

public static final float[] colorBlack

colorWhite

public static final float[] colorWhite

colorGray

public static final float[] colorGray

colorRed

public static final float[] colorRed

colorGreen

public static final float[] colorGreen

colorBlue

public static final float[] colorBlue

displayLists

public static java.util.ArrayList displayLists

appletBaseURL

public static java.net.URL appletBaseURL

rootClass

public static java.lang.Class rootClass
Constructor Detail

GLApp

public GLApp()
Method Detail

main

public static void main(java.lang.String[] args)

run

public void run()
Runs the application. Calls init() function to setup OpenGL, input and display. Runs the main loop of the application, which handles mouse and keyboard input.

Calls init(), handleEvents(), update() and draw().
handleEvents() calls: mouseMove(), mouseDown(), mouseUp(), keyDown(), keyUp()


init

public void init()
Called only once when app is first started, init() prepares the display, mouse and OpenGL context for use. Override init() only if you want to substantially alter the app startup behavior. Otherwise just override initGL() to tweak the OpenGL context and setup() to load textures, models, etc..


handleEvents

public void handleEvents()
Called by the run() loop. Handles animation and input for each frame.


loadSettings

public void loadSettings(java.lang.String configFilename)
Load configuration settings from optional properties file. File format is:
 # Comment
 displayWidth=1024
 displayHeight=768
 

Parameters:
configFilename -

initDisplay

public static boolean initDisplay()
Initialize the Display mode, viewport size, and open a Window. By default the window is fullscreen, the viewport is the same dimensions as the window.


getDisplayMode

public static DisplayMode getDisplayMode(int w,
                                         int h,
                                         int colorBits,
                                         int freq)
Retrieve a DisplayMode object with the given params


initInput

public static void initInput()
Initialize the Keyboard and Mouse.

Disable or hide the native cursor. Set the initial cursor position. Get the timer resolution (ticks per second).

See Also:
handleEvents()

initGL

public void initGL()
Initialize the OpenGL context. The subclass can override this function to customize the OpenGL settings. This function is called by init() once when app starts, but may be called again to restore settings to a default state, or to initialize a PBuffer object to the exact same state as the display.


setup

public void setup()
Setup can be overridden by the subclass to initialize the application ie load textures, models, and create data structures used by the app. This function is called only once, when application starts. It is called after initDisplay and initOpenGL(), so the OpenGL context is already created.

See Also:
init()

update

public void update()
Update can be overridden by the subclass

See Also:
run()

draw

public void draw()
Called by run() to draw one frame. Subclass will override this. This is an alias function just to be follow Processing and OpenFrameworks function naming conventions.


render

public void render()
Same as draw(). Subclass can override render() instead of draw(). Same thing, just a matter of taste.


cleanup

public void cleanup()
Run() calls this right before exit. Free up allocated resources (display lists) and gracefully shut down OpenGL context.


exit

public void exit()
Shutdown the application. This will call cleanup() before exiting from the application.

See Also:
cleanup()

mouseMove

public void mouseMove(int x,
                      int y)
Called by handleEvents() when mouse moves


mouseDown

public void mouseDown(int x,
                      int y)

mouseUp

public void mouseUp(int x,
                    int y)

mouseWheel

public void mouseWheel(int wheelMoved)

mouseButtonDown

public boolean mouseButtonDown(int whichButton)
Return true if the given mousebutton is down. Typically mouse buttons are 0=left, 1=right. This function can be called inside mouse events such as mouseDown() and mouseMove() to see which button is activated.

Parameters:
whichButton - number of mouse button (0=left button)

keyDown

public void keyDown(int keycode)
Called when key is pressed. Keycode will be the key ID value as defined in the LWJGL Keyboard class.

Parameters:
keycode -
See Also:
class in the LWJGL documentation

keyUp

public void keyUp(int keycode)
Called when key is released. Keycode will be the key ID value as defined in the LWJGL Keyboard class.

Parameters:
keycode -
See Also:
class in the LWJGL documentation

keyChar

public char keyChar()
Return the character associatated with the last key event. When called inside keyDown() or keyUp() this function will return the character equivalent of the keycode that was passed to keyDown() or keyUp().


loadPropertiesFile

public static java.util.Properties loadPropertiesFile(java.lang.String configFilename)
Load configuration settings from a properties file. File format is:
 # Comment
 displayWidth=1024
 displayHeight=768
 

Parameters:
configFilename -

getProperty

public static java.lang.String getProperty(java.util.Properties props,
                                           java.lang.String propName)

getPropertyInt

public static int getPropertyInt(java.util.Properties props,
                                 java.lang.String propName)

getPropertyFloat

public static float getPropertyFloat(java.util.Properties props,
                                     java.lang.String propName)

getPropertyBool

public static boolean getPropertyBool(java.util.Properties props,
                                      java.lang.String propName)

getProperty

public static java.lang.String getProperty(java.lang.String propertyName)
Return a property from the application configuration file (the filename given in the configFilename variable). This file is optional, so properties may be empty.

See Also:
loadSettings()

getWidth

public static int getWidth()
return the width of the Viewport (the screen area that OpenGL will draw into). By default the viewport is the same size as the Display (see getWidthWindow()), however the setViewport() function can set the viewport to a sub-region of the screen.

This function is only valid after app is running and Display has been initialized.

See Also:
setViewport(int,int,int,int)

getHeight

public static int getHeight()
return the height of the Viewport (the screen area that OpenGL will draw into). By default the viewport is the same size as the Display (see getHeightWindow()), however the setViewport() function can set the viewport to a sub-region of the screen.

This function is only valid after app is running and Display has been initialized.

See Also:
setViewport(int,int,int,int)

getWidthWindow

public static int getWidthWindow()
return the Display width (the width of the full window). Only valid after app is running and Display has been initialized.


getHeightWindow

public static int getHeightWindow()
return the Display height (the height of the full window). Only valid after app is running and Display has been initialized.


setBackgroundColor

public static void setBackgroundColor(float R,
                                      float G,
                                      float B)
Set the background color of the screen. The red,green,blue color components are floats in the range 0-1. Black is 0,0,0 and white is 1,1,1. Color will take effect the next time the screen is cleared.


disableNativeCursor

public static void disableNativeCursor(boolean off)
If the param is true, turn off the hardware cursor. The application can decide how to respond to mouse events and whether to draw a position indicator on screen or not. If running in a window (not fullscreen), there will be no hardware cursor visible and the user cannot move or click outside the window area.

If the param is false, the hardware cursor will behave normally. Use hideHardwareCursor() to show or hide the hardware cursor.

See Also:
hideHardwareCursor()

hideNativeCursor

public static void hideNativeCursor(boolean hide)
If param is true, make the native cursor transparent. Cursor will be hidden in the window area, but will be visible outside the window (assuming you're not in fullscreen mode). I also used this approach with touch screens because the touch screen drivers needed to read the hardware mouse position, so I couldn't disable the hardware cursor, but I wanted to hide it.

If param is false, reset the cursor to the default.

See Also:
disableHardwareCursor()

setCursorPosition

public static void setCursorPosition(int screenX,
                                     int screenY)
Set the cursorX,cursorY position. This will set the screen position of the native cursor also, unless hideCursor() was called.

Parameters:
screenX -
screenY -

getSettingInt

public static int getSettingInt(int whichSetting)
retrieve a setting from OpenGL (calls glGetInteger())

Parameters:
whichSetting - the id number of the value to be returned (same constants as for glGetInteger())

getModelviewMatrix

public static java.nio.FloatBuffer getModelviewMatrix()

getProjectionMatrix

public static java.nio.FloatBuffer getProjectionMatrix()

getViewport

public static java.nio.IntBuffer getViewport()

getMatrixAsArray

public static float[][] getMatrixAsArray(java.nio.FloatBuffer fb)
Convert a FloatBuffer matrix to a 4x4 float array.

Parameters:
fb - FloatBuffer containing 16 values of 4x4 matrix
Returns:
2 dimensional float array

getZDepth

public static float getZDepth(int x,
                              int y)
Return the Z depth of the single pixel at the given screen position.


getZDepthAtOrigin

public static float getZDepthAtOrigin()
Find the Z depth of the origin in the projected world view. Used by getWorldCoordsAtScreen() Projection matrix must be active for this to return correct results (GL.glMatrixMode(GL.GL_PROJECTION)). For some reason I have to chop this to four decimals or I get bizarre results when I use the value in project().


project

public static void project(float x,
                           float y,
                           float z,
                           float[] resultf)
Return screen coordinates for a given point in world space. The world point xyz is 'projected' into screen coordinates using the current model and projection matrices, and the current viewport settings.

Parameters:
x - world coordinates
y -
z -
resultf - the screen coordinate as an array of 3 floats

unProject

public static void unProject(float x,
                             float y,
                             float z,
                             float[] resultf)
Return world coordinates for a given point on the screen. The screen point xyz is 'un-projected' back into world coordinates using the current model and projection matrices, and the current viewport settings.

Parameters:
x - screen x position
y - screen y position
z - z-buffer depth position
resultf - the world coordinate as an array of 3 floats
See Also:
getWorldCoordsAtScreen()

getWorldCoordsAtScreen

public static float[] getWorldCoordsAtScreen(int x,
                                             int y)
For given screen xy, return the world xyz coords in a float array. Assume Z position is 0.


getWorldCoordsAtScreen

public static float[] getWorldCoordsAtScreen(int x,
                                             int y,
                                             float z)
For given screen xy and z depth, return the world xyz coords in a float array.


allocateTexture

public static int allocateTexture()
Allocate a texture (glGenTextures) and return the handle to it.


activateTexture

public static void activateTexture(int textureHandle)
"Select" the given texture for further texture operations.


makeTexture

public static int makeTexture(java.lang.String textureImagePath)
Create a texture and mipmap from the given image file.


makeTexture

public static int makeTexture(java.lang.String textureImagePath,
                              boolean mipmap,
                              boolean anisotropic)
Create a texture and optional mipmap with the given parameters.

Parameters:
mipmap: - if true, create mipmaps for the texture
anisotropic: - if true, enable anisotropic filtering

makeTexture

public static int makeTexture(GLImage textureImg)
Create a texture from the given image.


deleteTexture

public static void deleteTexture(int textureHandle)
De-allocate the given texture (glDeleteTextures()).


isPowerOf2

public static boolean isPowerOf2(int n)
Returns true if n is a power of 2. If n is 0 return zero.


makeTexture

public static int makeTexture(int w)
Create a blank square texture with the given size.

Returns:
the texture handle

makeTexture

public static int makeTexture(int[] pixelsARGB,
                              int w,
                              int h,
                              boolean anisotropic)
Create a texture from the given pixels in the default Java ARGB int format.
Configure the texture to repeat in both directions and use LINEAR for magnification.

Returns:
the texture handle

makeTexture

public static int makeTexture(java.nio.ByteBuffer pixels,
                              int w,
                              int h,
                              boolean anisotropic)
Create a texture from the given pixels in the default OpenGL RGBA pixel format. Configure the texture to repeat in both directions and use LINEAR for magnification.

Returns:
the texture handle

makeTextureARGB

public static int makeTextureARGB(java.nio.ByteBuffer pixels,
                                  int w,
                                  int h)
Create a texture from the given pixels in ARGB format. The pixels buffer contains 4 bytes per pixel, in ARGB order. ByteBuffers are created with native hardware byte orders, so the pixels can be in big-endian (ARGB) order, or little-endian (BGRA) order. Set the pixel_byte_order accordingly when creating the texture.

Configure the texture to repeat in both directions and use LINEAR for magnification.

NOTE: I'm having problems creating mipmaps when image pixel data is in GL_BGRA format. Looks like GLU type param doesn't recognize GL_UNSIGNED_INT_8_8_8_8 and GL_UNSIGNED_INT_8_8_8_8_REV so I can't specify endian byte order. Mipmaps look right on PC but colors are reversed on Mac. Have to stick with GL_RGBA byte order for now.

Returns:
the texture handle

makeTextureMipMap

public static int makeTextureMipMap(int textureHandle,
                                    GLImage textureImg)
Build Mipmaps for currently bound texture (builds a set of textures at various levels of detail so that texture will scale up and down gracefully)

Parameters:
textureImg - the texture image
Returns:
error code of buildMipMap call

makeTextureForScreen

public static int makeTextureForScreen(int screenSize)
Create a texture large enough to hold the screen image. Use RGBA8 format to insure colors are copied exactly. Use GL_NEAREST for magnification to prevent slight blurring of image when screen is drawn back.

See Also:
frameCopy(), frameDraw()

getPowerOfTwoBiggerThan

public static int getPowerOfTwoBiggerThan(int n)
Find a power of two equal to or greater than the given value. Ie. getPowerOfTwoBiggerThan(800) will return 1024.

Parameters:
dimension -
Returns:
a power of two equal to or bigger than the given dimension
See Also:
makeTextureForScreen()

copyPixelsToTexture

public static void copyPixelsToTexture(java.nio.ByteBuffer bb,
                                       int w,
                                       int h,
                                       int textureHandle)
Copy pixels from a ByteBuffer to a texture. The buffer pixels are integers in ARGB format (this is the Java default format you get from a BufferedImage) or BGRA format (this is the native order of Intel systems. The glTexSubImage2D() call treats the incoming pixels as integers in either big-endian (ARGB) or little-endian (BGRA) formats based on the setting of the bytebuffer (pixel_byte_order).

Parameters:
bb - ByteBuffer of pixels stored as ARGB or BGRA integers
w - width of source image
h - height of source image
textureHandle - texture to copy pixels into

copyImageToTexture

public static void copyImageToTexture(GLImage img,
                                      int textureHandle)
Calls glTexSubImage2D() to copy pixels from an image into a texture.


setPerspective

public static void setPerspective()
Set OpenGL to render in 3D perspective. Set the projection matrix using GLU.gluPerspective(). The projection matrix controls how the scene is "projected" onto the screen. Think of it as the lens on a camera, which defines how wide the field of vision is, how deep the scene is, and how what the aspect ratio will be.


setOrtho

public static void setOrtho()
Set OpenGL to render in flat 2D (no perspective) with a one-to-one relation between screen pixels and world coordinates, ie. if you draw a 10x10 quad at 100,100 it will appear as a 10x10 pixel square on screen at pixel position 100,100.

ABOUT Ortho and Viewport:
Let's say we're drawing in 2D and want to have a cinema proportioned viewport (16x9), and want to bound our 2D rendering into that area ie.

          ___________1024,576
         |           |
         |  Scene    |      Set the bounds on the scene geometry
         |___________|      to the viewport size and shape
      0,0

          ___________1024,576
         |           |
         |  Ortho    |      Set the projection to cover the same
         |___________|      area as the scene
      0,0

          ___________ 1024,768
         |___________|
         |           |1024,672
         |  Viewport |      Set the viewport to the same shape
     0,96|___________|      as scene and ortho, but centered on
         |___________|      screen.
      0,0


setOrtho

public static void setOrtho(int width,
                            int height)

setOrthoOn

public static void setOrthoOn()
Set OpenGL to render in flat 2D (no perspective) on top of current scene. Preserve current projection and model views, and disable depth testing. Ortho world size will be same as viewport size, so any ortho drawing (drawQuad(), drawImageFullscreen(), etc.) will be scaled to fit viewport.

NOTE: if the viewport is the same size as the window (by default it is), then setOrtho() will make the world coordinates exactly match the screen pixel positions. This is convenient for mouse interaction, but be warned: if you setViewport() to something other than fullscreen, then you need to use getWorldCoordsAtScreen() to convert screen xy to world xy.

Once Ortho is on, glTranslate() will take pixel coords as arguments, with the lower left corner 0,0 and the upper right corner 1024,768 (or whatever your screen size is). !!!

See Also:
setOrthoOff(), setViewport(int,int,int,int)

setOrthoOff

public static void setOrthoOff()
Turn 2D mode off. Return the projection and model views to their preserved state that was saved when setOrthoOn() was called, and re-enable depth testing.

See Also:
setOrthoOn()

setViewport

public static void setViewport(int x,
                               int y,
                               int width,
                               int height)
Define the position and size of the screen area in which the OpenGL context will draw. Position and size of the area are given in exact pixel sizes. By default the viewport is the same size as the window (displayWidth,displayHeight).

NOTE: by default the window size, viewport size and setOrtho() size are all the same, so in ortho mode screen pixel positions exactly match to world coordinates. THIS IS NO LONGER TRUE if you setViewport() to some other size. With a custom viewport you need to use getWorldCoordsAtScreen() to convert screen xy to world xy.

Parameters:
x - position of the lower left of viewport area, in pixels
y -
width - size of the viewport area, in pixels
height -
See Also:
setPerspective(), setOrtho(), setOrthoDimensions(int,int)

resetViewport

public static void resetViewport()
Reset the viewport to full screen (displayWidth x displayHeight).

See Also:
setViewport(int,int,int,int)

lookAt

public static void lookAt(float lookatX,
                          float lookatY,
                          float lookatZ,
                          float distance)
A simple way to set eye position. Calls gluLookat() to place the viewpoint units up the Z axis from the given target position, looking at the target position. The camera is oriented vertically (Y axis is up). away.


pushAttrib

public static void pushAttrib()
preserve all OpenGL settings that can be preserved. Use this function to isolate settings changes. Call pushAttrib() before calling glEnable(), glDisable(), glMatrixMode() etc. After your code executes, call popAttrib() to return to the previous settings. For better performance, call pushAttrib() with specific settings flags to preserve only specific settings.

See Also:
popAttrib()

pushAttrib

public static void pushAttrib(int attribute_bits)
preserve the specified OpenGL setting. Call popAttrib() to return to the preserved state.

See Also:
popAttrib()

pushAttribOrtho

public static void pushAttribOrtho()
preserve the OpenGL settings that will be affected when we draw in ortho mode over the scene. For example if we're drawing an interface layer, buttons, popup menus, cursor, text, etc. we need to turn off lighting, turn on blending, set color to white and turn off depth test.

call pushAttribOverlay(), enable settings that you need, when done call popAttrib()

See Also:
popAttrib()

pushAttribViewport

public static void pushAttribViewport()
preserve the OpenGL viewport settings.
       pushAttribViewport();
           setViewport(0,0,displaymode.getWidth(),displaymode.getHeight());
           ... do some drawing outside of previous viewport area
       popAttrib();
 

See Also:
popAttrib()

popAttrib

public static void popAttrib()
return to the OpenGL settings that were preserved by the previous pushAttrib() call.

See Also:
pushAttrib()

setLight

public static void setLight(int GLLightHandle,
                            float[] diffuseLightColor,
                            float[] ambientLightColor,
                            float[] specularLightColor,
                            float[] position)
Set the color of a 'positional' light (a light that has a specific position within the scene).
Pass in an OpenGL light number (GL11.GL_LIGHT1), the 'Diffuse' and 'Ambient' colors (direct light and reflected light), and the position.

Parameters:
GLLightHandle -
diffuseLightColor -
ambientLightColor -
position -

setSpotLight

public static void setSpotLight(int GLLightHandle,
                                float[] diffuseLightColor,
                                float[] ambientLightColor,
                                float[] position,
                                float[] direction,
                                float cutoffAngle)

setAmbientLight

public static void setAmbientLight(float[] ambientLightColor)
Set the color of the Global Ambient Light. Affects all objects in scene regardless of their placement.


setLightPosition

public static void setLightPosition(int GLLightHandle,
                                    float x,
                                    float y,
                                    float z)
Set the position of a light to the given xyz. NOTE: Positional light only, not directional.


setLightPosition

public static void setLightPosition(int GLLightHandle,
                                    float[] position)
Set the position (or direction) of a light to the given xyz.


setLight

public static void setLight(int GLLightHandle,
                            boolean on)
enable/disable the given light. The light handle parameter is one of the predefined OpenGL light handle numbers (GL_LIGHT1, GL_LIGHT2 ... GL_LIGHT7).


setLighting

public static void setLighting(boolean on)
Enable/disable lighting. If parameter value is false, this will turn off all lights and ambient lighting. NOTE: When lighting is disabled, material colors are disabled as well. Use glColor() to set color properties when ligthing is off.


setMaterial

public static void setMaterial(float[] surfaceColor,
                               float shiny)
A simple way to set the current material properties to approximate a "real" surface. Provide the surface color (float[4]]) and shininess value (range 0-1).

Sets diffuse material color to the surfaceColor and ambient material color to surfaceColor/2. Based on the shiny value (0-1), sets the specular property to a color between black (0) and white (1), and sets the shininess property to a value between 0 and 127.

Lighting must be enabled for material colors to take effect.

Parameters:
surfaceColor - - must be float[4] {R,G,B,A}
reflection - - a float from 0-1 (0=very matte, 1=very shiny)

setMaterial

public static void setMaterial(float[] diffuseColor,
                               float[] ambientColor,
                               float[] specularColor,
                               float[] emissiveColor,
                               float shininess)
Set the four material colors and calls glMaterial() to change the current material color in OpenGL. Lighting must be enabled for material colors to take effect.

Parameters:
shininess: - size of reflection (0 is matte, 127 is pinpoint reflection)

setMaterialAlpha

public static void setMaterialAlpha(float alpha)
Alter the material opacity by setting the diffuse material color alpha value to the given value


applyMaterial

public static void applyMaterial()
Call glMaterial() to activate these material properties in the OpenGL environment. These properties will stay in effect until you change them or disable lighting.


setFog

public static void setFog(float[] fogColor,
                          float fogdensity)
Enable atmospheric fog effect, with the given color and density.
      setFog(new float[] {.5f,.5f,.5f,1f}, .3f);
 

Parameters:
fogColor - float[4] specifies the RGB fog color value
fogDensity - float in range 0-1 specifies how opaque the fog will be

setFog

public static void setFog(boolean on)
Enable/disable fog effect. Does not change the fog settings.


getTimeInSeconds

public static double getTimeInSeconds()

getTimeInMillis

public static double getTimeInMillis()

updateTimer

public static void updateTimer()
Calculate time since we last called updateTimer(). Updates secondsSinceLastFrame and sets lastFrameTime to the current Sys.getTime().

Called by run() at the beginning of each loop.

See Also:
run(), getSecondsPerFrame()

getSecondsPerFrame

public static double getSecondsPerFrame()
Return the moving average of the seconds per frame for the last 50 frames. Useful when animating in real time. Will provide smoother time deltas than the secondsSinceLastFrame variable, which holds the exact time elapsed during the last frame (but may jump or lag as processor load varies).

See Also:
updateTimer()

getFramesPerSecond

public static double getFramesPerSecond()
Return the moving average of the frames per second for the last 50 frames.

See Also:
updateTimer()

makeImage

public static GLImage makeImage(int w,
                                int h)
Make a blank image of the given size.

Returns:
the new GLImage

loadImage

public static GLImage loadImage(java.lang.String imgFilename)
Load an image from the given file and return a GLImage object.

Parameters:
image - filename
Returns:
the loaded GLImage

loadImagePixels

public static java.nio.ByteBuffer loadImagePixels(java.lang.String imgFilename)
Load an image from the given file and return a ByteBuffer containing ARGB pixels.
Can be used to create textures.

Parameters:
imgFilename -
Returns:

drawCursor

public static void drawCursor(int cursorTextureHandle)
Draw a cursor image textured onto a quad at cursorX,cursorY. The cursor image must be loaded into a 32x32 texture. This function can be called after scene is drawn to place a cursor on top of scene.

NOTE: the cursor is drawn in screen space, at an absolute screen pixel location without regard for viewport (temporarily zets viewport to entire screen).

See handleEvents() for cursorX cursorY and mouse motion handling.

Example:

    int cursorTxtr;

    public void setup() {
        cursorTxtr = makeTexture("images/cursorCrosshair32.gif"); // image must be 32x32
    }

    public void draw() {
        // render scene
        ...
        drawCursor(cursorTxtr);
    }
 

Parameters:
cursorTextureHandle - handle to texture containing 32x32 cursor image

drawCursorOLD

public static void drawCursorOLD(int cursorTextureHandle)
OLD function: this drew the cursor only into the current viewport, and could not handle difffent ortho coordinate systems (ortho had to be exactly mapped to screen size). Draw a cursor image textured onto a quad at cursor position. The cursor image must be loaded into a texture, then this function can be called after scene is drawn. Uses glPushAttrib() to preserve the current drawing state. glPushAttrib() may slow performance down, so in your app you may want to set the states yourself before calling drawCursor() and take the push/pop out of here.

See handleEvents() for cursorX cursorY and mouse motion handling.

Example:

    int cursorTxtr;

    public void setup() {
        cursorTxtr = makeTexture("images/cursorCrosshair32.gif"); // image must be 32x32
    }

    public void draw() {
        // render scene
        ...
        drawCursor(cursorTxtr);
    }
 

Parameters:
cursorTextureHandle - handle to texture containing 32x32 cursor image

drawImageFullScreen

public static void drawImageFullScreen(GLImage img)
Draw an image in ortho mode (2D) over the entire viewport area. Converts the image to a texture and maps onto a viewport-sized quad. Depth test is turned off, lighting is off, color is set to white. Alpha blending is on, so transparent areas will be respected.

NOTE: By default the viewport is the same size as the window so this function will draw the image over the entire window. If you setViewport() to a custom size the image will be drawn into the custom viewport area. To insure that the image is drawn truly full screen, call resetViewport() before drawImageFullScreen().

See Also:
loadImage(String), setViewport(int,int,int,int), resetViewport()

drawImage

public static void drawImage(GLImage img,
                             int x,
                             int y,
                             float w,
                             float h)
Draw an image in whichever projection mode is current (does not switch to ortho mode). Convert the image to a texture and draw onto quad. Will draw with current settings (light, material, depth, blend, etc.)

See Also:
loadImage(), drawQuad(), drawImageFullScreen()

drawQuad

public static void drawQuad(int textureHandle,
                            int x,
                            int y,
                            float w,
                            float h)
Draw a textured quad in Ortho mode (2D) at the given xy, scaled to the given width and height. Depth test is turned off so quad will be drawn on top of the current scene. Quad will be drawn with current light and material if any are active.


drawQuadZ

public static void drawQuadZ(int textureHandle,
                             float x,
                             float y,
                             float z,
                             float w,
                             float h)
Draw a textured quad at the given xyz position in 3D space. Quad will be drawn with current settings (ie. light, material, depth test, projection, etc.)


framePixels

public static java.nio.ByteBuffer framePixels()
Return a ByteBuffer containing ARGB pixels of the entire screen area.


framePixels

public static java.nio.ByteBuffer framePixels(int x,
                                              int y,
                                              int w,
                                              int h)
Return a ByteBuffer containing ARGB pixels from the given screen area.


framePixelsInt

public static int[] framePixelsInt(int x,
                                   int y,
                                   int w,
                                   int h)
Return an int array containing ARGB pixels from the given screen area.


getPixelColor

public static byte[] getPixelColor(int x,
                                   int y)
Return the color buffer RGB value at the given screen position as byte[3].

Parameters:
x - screen position
y -
Returns:
rgb byte array

getPixelDepth

public static float getPixelDepth(int x,
                                  int y)
Return the depth buffer value at the given screen position.

Parameters:
x - screen position
y -
Returns:
float Z depth value

getPixelStencil

public static int getPixelStencil(int x,
                                  int y)
Return the stencil buffer value at the given screen position. Stencil values are typically bytes (0-255). The value will be returned as an integer.

Parameters:
x - screen position
y -
Returns:
int stencil value

frameCopy

public static void frameCopy(int txtrHandle)
Save entire screen image to a texture. Will copy entire screen even if a viewport is in use. Texture param must be large enough to hold screen image (see makeTextureForScreen()).

Parameters:
txtrHandle - texture where screen image will be stored
See Also:
frameDraw(), makeTextureForScreen()

frameCopy

public static void frameCopy(int txtrHandle,
                             int x,
                             int y,
                             int w,
                             int h)
Save a region of the screen to a texture. Texture must be large enough to hold screen image.

Parameters:
txtrHandle - texture where screen region will be stored
See Also:
frameDraw(), makeTextureForScreen()

frameDraw

public static void frameDraw(int txtrHandle)
Draw the screen-sized image over entire screen area. The screen image is stored in the given texture at 0,0 (see frameCopy()) and has the same dimensions as the current display mode (DM.getWidth(), DM.getHeight()).

Reset the viewport and ortho mode to full screen (viewport may be different proportion than screen if custom aspectRatio is set). Draw the quad the same size as texture so no stretching or compression of image.

Parameters:
txtrHandle -

frameSave

public static void frameSave()
Save the current frame buffer to a PNG image. Exactly the same as screenShot().

See Also:
screenShot()

drawRect

public static void drawRect(int x,
                            int y,
                            float w,
                            float h)
Draw a rectangle outline in ortho mode (draws in 2D over the scene).

See Also:
setLineWidth(), drawRectZ()

drawRectZ

public static void drawRectZ(int x,
                             int y,
                             int z,
                             float w,
                             float h)
Draw a rectangle outline in world space. Uses opengl line_strip to make the rectangle.

See Also:
setLineWidth(), drawRect()

drawCircle

public static void drawCircle(int x,
                              int y,
                              int radius,
                              int linewidth)
Draws a circle with the given radius centered at the given world position.


drawCircleZ

public static void drawCircleZ(int x,
                               int y,
                               int z,
                               int radius,
                               int linewidth)
Draws a circle with the given radius centered at the given world position.


drawCircle

public static void drawCircle(float innerRadius,
                              float outerRadius,
                              int numSegments)
Draws a circle centered at 0,0,0. Use translate() to place circle at desired coords. Inner and outer radius specify width, stepsize is number of degrees for each segment.


renderCube

public static void renderCube()
Render a 2 unit cube centered at origin. Includes texture coordinates and normals.


renderCube

public static void renderCube(float size,
                              int segments)
draw a cube with the given size, centered at origin. Include texture coordinates.

Parameters:
size - length of each side
segments - # segments to divide each side into

renderPlane

public static void renderPlane(float size,
                               int segments)
draw a square plane in the X,Y axis, centered at origin. Include texture coordinates.

Parameters:
size - length of each side
segments - number of segments to divide each side into

renderPlane

public static void renderPlane(float length,
                               float height,
                               int length_segments,
                               int height_segments)
draw a rectangular plane in the X,Y axis, centered at origin. Include texture coordinates. Scale the UV coordinates to same proportion as plane dimensions.

Parameters:
length - length on X axis
depth - length on Y axis
segments - number of segments to divide each side into

renderSphere

public static void renderSphere(int facets)
call the LWJGL Sphere class to draw sphere geometry with texture coordinates and normals

Parameters:
facets - number of divisions around longitude and latitude

renderSphere

public static void renderSphere()
draw a sphere with 48 facets (pretty smooth) with normals and texture coords


setLineWidth

public static void setLineWidth(int width)
Sets glLineWidth() and glPointSize() to the given width. This will affect geometry drawn using glBegin(GL_LINES), GL_LINE_STRIP, and GL_POINTS. May only work with widths up to 10 (depends on hardware).


setColor

public static void setColor(float R,
                            float G,
                            float B,
                            float A)
Set the current color with RGBA floats in range 0-1. The current color is disabled when lighting is enabled. When lighting is enabled (glEnable(GL_LIGHTING)) then material colors are in effect and the current color is ignored.


setColorB

public static void setColorB(int R,
                             int G,
                             int B,
                             int A)
Set the current color with RGBA bytes in range 0-255. The current color is disabled when lighting is enabled. When lighting is enabled (glEnable(GL_LIGHTING)) then material colors are in effect and the current color is ignored.


setColor

public static void setColor(float[] rgba)
Set the current color to the given RGB or RGBA float array. Floats are in range 0-1. The current color is disabled when lighting is enabled. When lighting is enabled (glEnable(GL_LIGHTING)) then material colors are in effect and the current color is ignored.


setColorMaterial

public static void setColorMaterial(boolean on)
Enable/disable the color-material setting. When enabled, the glColor() command will change the current material color. This provides a convenient and efficient way to change material colors without having to call glMaterial(). When disabled, the glColor() command functions normally (has no affect on material colors).

Parameters:
on - when true, glColor() will set the current material color

buildFont

public static boolean buildFont(java.lang.String charSetImage,
                                int fontWidth)
Build a character set from the given texture image.

Parameters:
charSetImage - texture image containing 256 characters in a 16x16 grid
fontWidth - how many pixels to allow per character on screen
See Also:
destroyFont()

buildFont

public static void buildFont(int fontTxtrHandle,
                             int fontWidth)
Build the character set display list from the given texture. Creates one quad for each character, with one letter textured onto each quad. Assumes the texture is a 256x256 image containing every character of the charset arranged in a 16x16 grid. Each character is 16x16 pixels. Call destroyFont() to release the display list memory. Should be in ORTHO (2D) mode to render text (see setOrtho()). Special thanks to NeHe and Giuseppe D'Agata for the "2D Texture Font" tutorial (http://nehe.gamedev.net).

Parameters:
charSetImage - texture image containing 256 characters in a 16x16 grid
fontWidth - how many pixels to allow per character on screen
See Also:
destroyFont()

destroyFont

public static void destroyFont()
Clean up the allocated display lists for the character set.


print

public static void print(int x,
                         int y,
                         java.lang.String msg)
Render a text string in 2D over the scene, using the character set created by buildFont().

Parameters:
x - screen pixel position of the string
y -
msg - text string to draw

print

public static void print(int x,
                         int y,
                         java.lang.String msg,
                         int set)
Render a text string in 2D over the scene, using the character set created by buildFont().

Parameters:
x - screen pixel position of the string
y -
msg - text string to draw
set - which of the two character sets: 0 or 1

printZ

public static void printZ(float x,
                          float y,
                          float z,
                          int set,
                          float scale,
                          java.lang.String msg)
Render a text string in model space, using the character set created by buildFont().


makePbuffer

public static Pbuffer makePbuffer(int width,
                                  int height)
Create a Pbuffer for use as an offscreen buffer, with the given width and height. Use selectPbuffer() to make the pbuffer the context for all subsequent opengl commands. Use selectDisplay() to make the Display the context for opengl commands.

Parameters:
width -
height -
Returns:
Pbuffer
See Also:
selectPbuffer(), selectDisplay()

selectPbuffer

public static Pbuffer selectPbuffer(Pbuffer pb)
Make the pbuffer the current context for opengl commands. All following gl functions will operate on this buffer instead of the display.

NOTE: the Pbuffer may be recreated if it was lost since last used. It's a good idea to use:

         pbuff = selectPbuffer(pbuff);
 
to hold onto the new Pbuffer reference if Pbuffer was recreated.

Parameters:
pb - pbuffer to make current
Returns:
Pbuffer
See Also:
selectDisplay(), makePbuffer()

selectDisplay

public static void selectDisplay()
Make the Display the current context for OpenGL commands. Subsequent gl functions will operate on the Display.

See Also:
selectPbuffer()

frameCopy

public static void frameCopy(Pbuffer pbuff,
                             int textureHandle)
Copy the pbuffer contents to a texture. (Should this use glCopyTexSubImage2D()? Is RGB the fastest format?)


screenShot

public static void screenShot()
Save the current frame buffer to a PNG image. Same as screenShot(filename) but the screenshot filename will be automatically set to -.png


screenShot

public static void screenShot(java.lang.String imageFilename)
Save the current frame buffer to a PNG image. Can also be used with the PBuffer class to copy large images or textures that have been rendered into the offscreen pbuffer.


screenShot

public static void screenShot(int x,
                              int y,
                              int width,
                              int height,
                              java.lang.String imageFilename)
Save a region of the current render buffer to a PNG image. If the current buffer is the framebuffer then this will work as a screen capture. Can also be used with the PBuffer class to copy large images or textures that have been rendered into the offscreen pbuffer.

WARNING: this function hogs memory! Call java with more memory (java -Xms128m -Xmx128m)

See Also:
selectPbuffer(Pbuffer), selectDisplay(), savePixelsToPNG()

savePixelsToPNG

public static void savePixelsToPNG(java.nio.ByteBuffer framebytes,
                                   int width,
                                   int height,
                                   java.lang.String imageFilename,
                                   boolean flipY)
Save a ByteBuffer of ARGB pixels to a PNG file. If flipY is true, flip the pixels on the Y axis before saving.


screenShotRGB

public static void screenShotRGB(int width,
                                 int height,
                                 java.lang.String saveFilename)
Save the contents of the current render buffer to a PNG image. This is an older version of screenShot() that used the default OpenGL GL_RGBA pixel format which had to be swizzled into an ARGB format. I'm keeping the function here for reference.

If the current buffer is the framebuffer then this will work as a screen capture. Can also be used with the PBuffer class to copy large images or textures that have been rendered into the offscreen pbuffer.

WARNING: this function hogs memory! Call java with more memory (java -Xms128m -Xmx128)

See Also:
selectPbuffer(), selectDisplay()

clearMask

public static void clearMask()
clear the stencil buffer


beginMask

public static void beginMask(int maskvalue)
Begin creating a mask. This function turns off the color and depth buffers so all subsequent drawing will go only into the stencil buffer. To use: beginMask(1); renderModel(); // draw some geometry endMask();


endMask

public static void endMask()
End the mask. Freeze the stencil buffer and activate the color and depth buffers.


activateMask

public static void activateMask(int maskvalue)
Restrict rendering to the masked area. To use: GLStencil.beginMask(1); renderModel(); GLStencil.endMask();


disableMask

public static void disableMask()
turn off the stencil test so stencil has no further affect on rendering.


getMaskValue

public static int getMaskValue(int x,
                               int y)
Return the stencil buffer value at the given screen position.


beginDisplayList

public static int beginDisplayList()
Begin a display list. All following OpenGL geometry commands (up to endDisplayList()) will be stored in a display list, not drawn to screen.

To use, create a display list in setup():

      int teapotID = beginDisplayList();
      ... // run teapot render code here
      endDisplayList();
 
Then call the display list later in render():
      callDisplayList(teapotID);
 

Returns:
integer display list id
See Also:
endDisplayList(), callDisplayList(), destroyDisplayList()

endDisplayList

public static void endDisplayList()
Finish display list creation. Use this function only after calling beginDisplayList()

See Also:
beginDisplayList()

callDisplayList

public static void callDisplayList(int displayListID)
Render the geometry stored in a display list. Use this function after calling beginDisplayList() and endDisplayList() to create a display list.

See Also:
beginDisplayList(), endDisplayList()

destroyDisplayList

public static void destroyDisplayList(int DL_ID)
Delete the given display list ID. Frees up resources on the graphics card.


destroyDisplayLists

public static void destroyDisplayLists()
Clean up the allocated display lists. Called by cleanUp() when app exits.

See Also:
cleanUp();

allocBytes

public static java.nio.ByteBuffer allocBytes(int howmany)

allocInts

public static java.nio.IntBuffer allocInts(int howmany)

allocFloats

public static java.nio.FloatBuffer allocFloats(int howmany)

allocDoubles

public static java.nio.DoubleBuffer allocDoubles(int howmany)

allocBytes

public static java.nio.ByteBuffer allocBytes(byte[] bytearray)

allocInts

public static java.nio.IntBuffer allocInts(int[] intarray)

allocFloats

public static java.nio.FloatBuffer allocFloats(float[] floatarray)

allocDoubles

public static java.nio.DoubleBuffer allocDoubles(double[] darray)

put

public static void put(java.nio.ByteBuffer b,
                       byte[] values)

put

public static void put(java.nio.IntBuffer b,
                       int[] values)

put

public static void put(java.nio.FloatBuffer b,
                       float[] values)

put

public static void put(java.nio.DoubleBuffer b,
                       double[] values)

get

public static void get(java.nio.ByteBuffer b,
                       int[] values)
copy ints from the given byteBuffer into the given int array.

Parameters:
b - source ByteBuffer
values - target integer array, must be same length as ByteBuffer capacity/4

get

public static void get(java.nio.IntBuffer b,
                       int[] values)
copy ints from the given IntBuffer into the given int array.

Parameters:
b - source IntBuffer
values - target integer array, must be same length as IntBuffer

getInts

public static int[] getInts(java.nio.ByteBuffer b)
return the contents of the byteBuffer as an array of ints.

Parameters:
b - source ByteBuffer

getInputStream

public static java.io.InputStream getInputStream(java.lang.String filename)
Open the given file and return the InputStream. This function assumes 1) that we're running an application and the file is in the local filesystem. If not found, then assume 2) we're in a jar file and look for the file in the current jar. If not found, then assume 3) we're running an applet and look for the file relative to the applet code base.

Parameters:
filename - to open

getBytesFromStream

public static byte[] getBytesFromStream(java.io.InputStream is)
Return an array of bytes read from an InputStream. Reads all bytes until the end of stream. Can read an arbitrary number of bytes. NOTE: Does not close the inputStream!


getBytesFromFile

public static byte[] getBytesFromFile(java.lang.String filename)
Return an array of bytes read from a file.


getPathAndFile

public static java.lang.String[] getPathAndFile(java.lang.String filename)
Return a String array containing the path portion of a filename (result[0]), and the fileame (result[1]). If there is no path, then result[0] will be "" and result[1] will be the full filename.


setRootClass

public void setRootClass()
Hold onto this Class for later class.getResource() calls (to load resources from JAR files, see getInputStream()) and also to get class name for use in screenshot filenames (see screenShot()).

To load files from a jar we need to access a class in the root folder of the installation. It's not good to use GLApp.class because that class is in the glapp package folder, and the getResource() function will not find model, image and sound files because they're a level higher in the folder tree. Below we call this.getClass() to record the class of the application that subclasses GLApp, ie. assume we create an app MyGame that extends GLApp, and MyGame.class is in the root folder of the installation:

      MyGame.class
      models (folder)
      images (folder)
      sounds (folder)
  
In this case setRootClass() will set the rootClass to MyGame. If MyGame and subfolders are packaged in a jar file, then getInputStream() should be able to do a rootClass.getResource("models/some_model.obj") and correctly retrieve the file from the JAR.

See Also:
getInputStream()

makeTimestamp

public static java.lang.String makeTimestamp()
make a time stamp for filename

Returns:
a string with format "YYYYMMDD-hhmmss"

random

public static float random()
Return a random floating point value between 0 and 1


random

public static float random(float upperbound)
Return a random floating point value between 0 and upperbound (not including upperbound)


random

public static int random(int upperbound)
Return a random integer value between 0 and upperbound (not including upperbound)


round

public static int round(float f)
Round a float value to the nearest int.


extensionExists

public static boolean extensionExists(java.lang.String extensionName)
Return true if the OpenGL context supports the given OpenGL extension.


msg

public static void msg(java.lang.String text)
Show a debug message on the system console (calls System.out.println()). If showMessages flag is false, does nothing.

Parameters:
text -

err

public static void err(java.lang.String text)
Show an error message on the system console (calls System.out.println()). Does not check showMessages flag.

Parameters:
text -

method

public static java.lang.reflect.Method method(java.lang.Object object,
                                              java.lang.String methodName)
Find a method in the given class with the given method name. Assumes the method takes no parameters. The returned Method can be executed later using invoke() (similar to a callback function in C/C++).

NOTE: method invocation is very fast for methods that take no parameters. If the method takes parameters then invoking is much slower than calling the function directly through code. For this reason and for simplicity I assume there are no parameters on the function.

Parameters:
object - object that has the method we want to invoke
methodName - name of function that we want to invoke
Returns:
the Method object
See Also:
invoke()

method

public java.lang.reflect.Method method(java.lang.String methodName)
Similar to the static method() function, this looks for the method in the GLApp class (or it's subclass).

Parameters:
methodName - name of function that we want to invoke
Returns:
the Method object
See Also:
invoke()

invoke

public static void invoke(java.lang.Object object,
                          java.lang.reflect.Method method)
Execute a method on the given object. Assumes the method takes no parameters. Useful as a callback function.

Parameters:
object - (the object to call the method on)
method - (the method that will be executed)
See Also:
method()

invoke

public void invoke(java.lang.reflect.Method method)
Similar to the static invoke() function, this execute a method on the GLApp class or subclass. Assumes the method takes no parameters. Useful as a callback function.

Parameters:
method - (the method that will be executed)
See Also:
method()