com.sun.opengl.util.awt
Class TextRenderer

java.lang.Object
  extended by com.sun.opengl.util.awt.TextRenderer

public class TextRenderer
extends Object

Renders bitmapped Java 2D text into an OpenGL window with high performance, full Unicode support, and a simple API. Performs appropriate caching of text rendering results in an OpenGL texture internally to avoid repeated font rasterization. The caching is completely automatic, does not require any user intervention, and has no visible controls in the public API.

Using the TextRenderer is simple. Add a "TextRenderer renderer;" field to your GLEventListener. In your init method, add:

    renderer = new TextRenderer(new Font("SansSerif", Font.BOLD, 36));
    

In the display method of your GLEventListener, add:

    renderer.beginRendering(drawable.getWidth(), drawable.getHeight());
    // optionally set the color
    renderer.setColor(1.0f, 0.2f, 0.2f, 0.8f);
    renderer.draw("Text to draw", xPosition, yPosition);
    // ... more draw commands, color changes, etc.
    renderer.endRendering();
    
Unless you are sharing textures and display lists between OpenGL contexts, you do not need to call the dispose method of the TextRenderer; the OpenGL resources it uses internally will be cleaned up automatically when the OpenGL context is destroyed.

Note that the TextRenderer may cause the vertex and texture coordinate array buffer bindings to change, or to be unbound. This is important to note if you are using Vertex Buffer Objects (VBOs) in your application.

Internally, the renderer uses a rectangle packing algorithm to pack both glyphs and full Strings' rendering results (which are variable size) onto a larger OpenGL texture. The internal backing store is maintained using a TextureRenderer. A least recently used (LRU) algorithm is used to discard previously rendered strings; the specific algorithm is undefined, but is currently implemented by flushing unused Strings' rendering results every few hundred rendering cycles, where a rendering cycle is defined as a pair of calls to beginRendering / endRendering.

Author:
John Burkey, Kenneth Russell

Nested Class Summary
static class TextRenderer.DefaultRenderDelegate
           
static interface TextRenderer.RenderDelegate
          Class supporting more full control over the process of rendering the bitmapped text.
 
Constructor Summary
TextRenderer(Font font)
          Creates a new TextRenderer with the given font, using no antialiasing or fractional metrics, and the default RenderDelegate.
TextRenderer(Font font, boolean mipmap)
          Creates a new TextRenderer with the given font, using no antialiasing or fractional metrics, and the default RenderDelegate.
TextRenderer(Font font, boolean antialiased, boolean useFractionalMetrics)
          Creates a new TextRenderer with the given Font, specified font properties, and default RenderDelegate.
TextRenderer(Font font, boolean antialiased, boolean useFractionalMetrics, TextRenderer.RenderDelegate renderDelegate)
          Creates a new TextRenderer with the given Font, specified font properties, and given RenderDelegate.
TextRenderer(Font font, boolean antialiased, boolean useFractionalMetrics, TextRenderer.RenderDelegate renderDelegate, boolean mipmap)
          Creates a new TextRenderer with the given Font, specified font properties, and given RenderDelegate.
 
Method Summary
 void begin3DRendering()
          Begins rendering of 2D text in 3D with this TextRenderer into the current OpenGL drawable.
 void beginRendering(int width, int height)
          Begins rendering with this TextRenderer into the current OpenGL drawable, pushing the projection and modelview matrices and some state bits and setting up a two-dimensional orthographic projection with (0, 0) as the lower-left coordinate and (width, height) as the upper-right coordinate.
 void beginRendering(int width, int height, boolean disableDepthTest)
          Begins rendering with this TextRenderer into the current OpenGL drawable, pushing the projection and modelview matrices and some state bits and setting up a two-dimensional orthographic projection with (0, 0) as the lower-left coordinate and (width, height) as the upper-right coordinate.
 void dispose()
          Disposes of all resources this TextRenderer is using.
 void draw(CharSequence str, int x, int y)
          Draws the supplied CharSequence at the desired location using the renderer's current color.
 void draw(String str, int x, int y)
          Draws the supplied String at the desired location using the renderer's current color.
 void draw3D(CharSequence str, float x, float y, float z, float scaleFactor)
          Draws the supplied CharSequence at the desired 3D location using the renderer's current color.
 void draw3D(String str, float x, float y, float z, float scaleFactor)
          Draws the supplied String at the desired 3D location using the renderer's current color.
 void end3DRendering()
          Ends a 3D render cycle with this TextRenderer.
 void endRendering()
          Ends a render cycle with this TextRenderer.
 void flush()
          Causes the TextRenderer to flush any internal caches it may be maintaining and draw its rendering results to the screen.
 Rectangle2D getBounds(CharSequence str)
          Returns the bounding rectangle of the given CharSequence, assuming it was rendered at the origin.
 Rectangle2D getBounds(String str)
          Returns the bounding rectangle of the given String, assuming it was rendered at the origin.
 float getCharWidth(char inChar)
          Returns the pixel width of the given character.
 Font getFont()
          Returns the Font this renderer is using.
 FontRenderContext getFontRenderContext()
          Returns a FontRenderContext which can be used for external text-related size computations.
 boolean getSmoothing()
          Indicates whether smoothing is enabled in the backing TextureRenderer of this TextRenderer.
 boolean getUseVertexArrays()
          Indicates whether vertex arrays are being used internally for rendering, or whether text is rendered using the OpenGL immediate mode commands.
 void setColor(Color color)
          Changes the current color of this TextRenderer to the supplied one.
 void setColor(float r, float g, float b, float a)
          Changes the current color of this TextRenderer to the supplied one, where each component ranges from 0.0f - 1.0f.
 void setSmoothing(boolean smoothing)
          Sets whether smoothing (i.e., GL_LINEAR filtering) is enabled in the backing TextureRenderer of this TextRenderer.
 void setUseVertexArrays(boolean useVertexArrays)
          Sets whether vertex arrays are being used internally for rendering, or whether text is rendered using the OpenGL immediate mode commands.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

TextRenderer

public TextRenderer(Font font)
Creates a new TextRenderer with the given font, using no antialiasing or fractional metrics, and the default RenderDelegate. Equivalent to TextRenderer(font, false, false).

Parameters:
font - the font to render with

TextRenderer

public TextRenderer(Font font,
                    boolean mipmap)
Creates a new TextRenderer with the given font, using no antialiasing or fractional metrics, and the default RenderDelegate. If mipmap is true, attempts to use OpenGL's automatic mipmap generation for better smoothing when rendering the TextureRenderer's contents at a distance. Equivalent to TextRenderer(font, false, false).

Parameters:
font - the font to render with
mipmap - whether to attempt use of automatic mipmap generation

TextRenderer

public TextRenderer(Font font,
                    boolean antialiased,
                    boolean useFractionalMetrics)
Creates a new TextRenderer with the given Font, specified font properties, and default RenderDelegate. The antialiased and useFractionalMetrics flags provide control over the same properties at the Java 2D level. No mipmap support is requested. Equivalent to TextRenderer(font, antialiased, useFractionalMetrics, null).

Parameters:
font - the font to render with
antialiased - whether to use antialiased fonts
useFractionalMetrics - whether to use fractional font metrics at the Java 2D level

TextRenderer

public TextRenderer(Font font,
                    boolean antialiased,
                    boolean useFractionalMetrics,
                    TextRenderer.RenderDelegate renderDelegate)
Creates a new TextRenderer with the given Font, specified font properties, and given RenderDelegate. The antialiased and useFractionalMetrics flags provide control over the same properties at the Java 2D level. The renderDelegate provides more control over the text rendered. No mipmap support is requested.

Parameters:
font - the font to render with
antialiased - whether to use antialiased fonts
useFractionalMetrics - whether to use fractional font metrics at the Java 2D level
renderDelegate - the render delegate to use to draw the text's bitmap, or null to use the default one

TextRenderer

public TextRenderer(Font font,
                    boolean antialiased,
                    boolean useFractionalMetrics,
                    TextRenderer.RenderDelegate renderDelegate,
                    boolean mipmap)
Creates a new TextRenderer with the given Font, specified font properties, and given RenderDelegate. The antialiased and useFractionalMetrics flags provide control over the same properties at the Java 2D level. The renderDelegate provides more control over the text rendered. If mipmap is true, attempts to use OpenGL's automatic mipmap generation for better smoothing when rendering the TextureRenderer's contents at a distance.

Parameters:
font - the font to render with
antialiased - whether to use antialiased fonts
useFractionalMetrics - whether to use fractional font metrics at the Java 2D level
renderDelegate - the render delegate to use to draw the text's bitmap, or null to use the default one
mipmap - whether to attempt use of automatic mipmap generation
Method Detail

getBounds

public Rectangle2D getBounds(String str)
Returns the bounding rectangle of the given String, assuming it was rendered at the origin. See getBounds(CharSequence).


getBounds

public Rectangle2D getBounds(CharSequence str)
Returns the bounding rectangle of the given CharSequence, assuming it was rendered at the origin. The coordinate system of the returned rectangle is Java 2D's, with increasing Y coordinates in the downward direction. The relative coordinate (0, 0) in the returned rectangle corresponds to the baseline of the leftmost character of the rendered string, in similar fashion to the results returned by, for example, GlyphVector.getVisualBounds(). Most applications will use only the width and height of the returned Rectangle for the purposes of centering or justifying the String. It is not specified which Java 2D bounds (getVisualBounds, getPixelBounds, etc.) the returned bounds correspond to, although every effort is made to ensure an accurate bound.


getFont

public Font getFont()
Returns the Font this renderer is using.


getFontRenderContext

public FontRenderContext getFontRenderContext()
Returns a FontRenderContext which can be used for external text-related size computations. This object should be considered transient and may become invalidated between beginRendering / endRendering pairs.


beginRendering

public void beginRendering(int width,
                           int height)
                    throws GLException
Begins rendering with this TextRenderer into the current OpenGL drawable, pushing the projection and modelview matrices and some state bits and setting up a two-dimensional orthographic projection with (0, 0) as the lower-left coordinate and (width, height) as the upper-right coordinate. Binds and enables the internal OpenGL texture object, sets the texture environment mode to GL_MODULATE, and changes the current color to the last color set with this TextRenderer via setColor. This method disables the depth test and is equivalent to beginRendering(width, height, true).

Parameters:
width - the width of the current on-screen OpenGL drawable
height - the height of the current on-screen OpenGL drawable
Throws:
GLException - If an OpenGL context is not current when this method is called

beginRendering

public void beginRendering(int width,
                           int height,
                           boolean disableDepthTest)
                    throws GLException
Begins rendering with this TextRenderer into the current OpenGL drawable, pushing the projection and modelview matrices and some state bits and setting up a two-dimensional orthographic projection with (0, 0) as the lower-left coordinate and (width, height) as the upper-right coordinate. Binds and enables the internal OpenGL texture object, sets the texture environment mode to GL_MODULATE, and changes the current color to the last color set with this TextRenderer via setColor. Disables the depth test if the disableDepthTest argument is true.

Parameters:
width - the width of the current on-screen OpenGL drawable
height - the height of the current on-screen OpenGL drawable
disableDepthTest - whether to disable the depth test
Throws:
GLException - If an OpenGL context is not current when this method is called

begin3DRendering

public void begin3DRendering()
                      throws GLException
Begins rendering of 2D text in 3D with this TextRenderer into the current OpenGL drawable. Assumes the end user is responsible for setting up the modelview and projection matrices, and will render text using the draw3D method. This method pushes some OpenGL state bits, binds and enables the internal OpenGL texture object, sets the texture environment mode to GL_MODULATE, and changes the current color to the last color set with this TextRenderer via setColor.

Throws:
GLException - If an OpenGL context is not current when this method is called

setColor

public void setColor(Color color)
              throws GLException
Changes the current color of this TextRenderer to the supplied one. The default color is opaque white.

Parameters:
color - the new color to use for rendering text
Throws:
GLException - If an OpenGL context is not current when this method is called

setColor

public void setColor(float r,
                     float g,
                     float b,
                     float a)
              throws GLException
Changes the current color of this TextRenderer to the supplied one, where each component ranges from 0.0f - 1.0f. The alpha component, if used, does not need to be premultiplied into the color channels as described in the documentation for Texture, although premultiplied colors are used internally. The default color is opaque white.

Parameters:
r - the red component of the new color
g - the green component of the new color
b - the blue component of the new color
a - the alpha component of the new color, 0.0f = completely transparent, 1.0f = completely opaque
Throws:
GLException - If an OpenGL context is not current when this method is called

draw

public void draw(CharSequence str,
                 int x,
                 int y)
          throws GLException
Draws the supplied CharSequence at the desired location using the renderer's current color. The baseline of the leftmost character is at position (x, y) specified in OpenGL coordinates, where the origin is at the lower-left of the drawable and the Y coordinate increases in the upward direction.

Parameters:
str - the string to draw
x - the x coordinate at which to draw
y - the y coordinate at which to draw
Throws:
GLException - If an OpenGL context is not current when this method is called

draw

public void draw(String str,
                 int x,
                 int y)
          throws GLException
Draws the supplied String at the desired location using the renderer's current color. See draw(CharSequence, int, int).

Throws:
GLException

draw3D

public void draw3D(CharSequence str,
                   float x,
                   float y,
                   float z,
                   float scaleFactor)
Draws the supplied CharSequence at the desired 3D location using the renderer's current color. The baseline of the leftmost character is placed at position (x, y, z) in the current coordinate system.

Parameters:
str - the string to draw
x - the x coordinate at which to draw
y - the y coordinate at which to draw
z - the z coordinate at which to draw
scaleFactor - a uniform scale factor applied to the width and height of the drawn rectangle
Throws:
GLException - If an OpenGL context is not current when this method is called

draw3D

public void draw3D(String str,
                   float x,
                   float y,
                   float z,
                   float scaleFactor)
Draws the supplied String at the desired 3D location using the renderer's current color. See draw3D(CharSequence, float, float, float, float).


getCharWidth

public float getCharWidth(char inChar)
Returns the pixel width of the given character.


flush

public void flush()
Causes the TextRenderer to flush any internal caches it may be maintaining and draw its rendering results to the screen. This should be called after each call to draw() if you are setting OpenGL state such as the modelview matrix between calls to draw().


endRendering

public void endRendering()
                  throws GLException
Ends a render cycle with this TextRenderer. Restores the projection and modelview matrices as well as several OpenGL state bits. Should be paired with beginRendering.

Throws:
GLException - If an OpenGL context is not current when this method is called

end3DRendering

public void end3DRendering()
                    throws GLException
Ends a 3D render cycle with this TextRenderer. Restores several OpenGL state bits. Should be paired with begin3DRendering.

Throws:
GLException - If an OpenGL context is not current when this method is called

dispose

public void dispose()
             throws GLException
Disposes of all resources this TextRenderer is using. It is not valid to use the TextRenderer after this method is called.

Throws:
GLException - If an OpenGL context is not current when this method is called

setUseVertexArrays

public void setUseVertexArrays(boolean useVertexArrays)
Sets whether vertex arrays are being used internally for rendering, or whether text is rendered using the OpenGL immediate mode commands. This is provided as a concession for certain graphics cards which have poor vertex array performance. Defaults to true.


getUseVertexArrays

public boolean getUseVertexArrays()
Indicates whether vertex arrays are being used internally for rendering, or whether text is rendered using the OpenGL immediate mode commands. Defaults to true.


setSmoothing

public void setSmoothing(boolean smoothing)
Sets whether smoothing (i.e., GL_LINEAR filtering) is enabled in the backing TextureRenderer of this TextRenderer. A few graphics cards do not behave well when this is enabled, resulting in fuzzy text. Defaults to true.


getSmoothing

public boolean getSmoothing()
Indicates whether smoothing is enabled in the backing TextureRenderer of this TextRenderer. A few graphics cards do not behave well when this is enabled, resulting in fuzzy text. Defaults to true.



Copyright 2005 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms.