diff options
Diffstat (limited to 'src/classes/javax/media/opengl')
18 files changed, 3476 insertions, 0 deletions
diff --git a/src/classes/javax/media/opengl/ComponentEvents.java b/src/classes/javax/media/opengl/ComponentEvents.java new file mode 100644 index 000000000..bfbbb957b --- /dev/null +++ b/src/classes/javax/media/opengl/ComponentEvents.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +import java.awt.event.*; +import java.beans.PropertyChangeListener; + +/** Factors out the listener manipulation for the events supported by + all of the {@link GLDrawable} implementations. Provided to reduce + clutter in the documentation for GLDrawable. */ + +public interface ComponentEvents { + public void addComponentListener(ComponentListener l); + public void removeComponentListener(ComponentListener l); + public void addFocusListener(FocusListener l); + public void removeFocusListener(FocusListener l); + public void addHierarchyBoundsListener(HierarchyBoundsListener l); + public void removeHierarchyBoundsListener(HierarchyBoundsListener l); + public void addHierarchyListener(HierarchyListener l); + public void removeHierarchyListener(HierarchyListener l); + public void addInputMethodListener(InputMethodListener l); + public void removeInputMethodListener(InputMethodListener l); + public void addKeyListener(KeyListener l); + public void removeKeyListener(KeyListener l); + public void addMouseListener(MouseListener l); + public void removeMouseListener(MouseListener l); + public void addMouseMotionListener(MouseMotionListener l); + public void removeMouseMotionListener(MouseMotionListener l); + public void addMouseWheelListener(MouseWheelListener l); + public void removeMouseWheelListener(MouseWheelListener l); + public void addPropertyChangeListener(PropertyChangeListener listener); + public void removePropertyChangeListener(PropertyChangeListener listener); + public void addPropertyChangeListener(String propertyName, + PropertyChangeListener listener); + public void removePropertyChangeListener(String propertyName, + PropertyChangeListener listener); +} diff --git a/src/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java b/src/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java new file mode 100644 index 000000000..391787a01 --- /dev/null +++ b/src/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +import com.sun.opengl.impl.Debug; + +/** <P> The default implementation of the {@link + GLCapabilitiesChooser} interface, which provides consistent visual + selection behavior across platforms. The precise algorithm is + deliberately left loosely specified. Some properties are: </P> + + <UL> + + <LI> As long as there is at least one available non-null + GLCapabilities which matches the "stereo" option, will return a + valid index. + + <LI> Attempts to match as closely as possible the given + GLCapabilities, but will select one with fewer capabilities (i.e., + lower color depth) if necessary. + + <LI> Prefers hardware-accelerated visuals to + non-hardware-accelerated. + + <LI> If there is no exact match, prefers a more-capable visual to + a less-capable one. + + <LI> If there is more than one exact match, chooses an arbitrary + one. + + <LI> May select the opposite of a double- or single-buffered + visual (based on the user's request) in dire situations. + + <LI> Color depth (including alpha) mismatches are weighted higher + than depth buffer mismatches, which are in turn weighted higher + than accumulation buffer (including alpha) and stencil buffer + depth mismatches. + + <LI> If a valid windowSystemRecommendedChoice parameter is + supplied, chooses that instead of using the cross-platform code. + + </UL> +*/ + +public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { + private static final boolean DEBUG = Debug.debug("DefaultGLCapabilitiesChooser"); + + public int chooseCapabilities(GLCapabilities desired, + GLCapabilities[] available, + int windowSystemRecommendedChoice) { + if (DEBUG) { + for (int i = 0; i < available.length; i++) { + System.err.println("Available " + i + ": " + available[i]); + } + } + + if (windowSystemRecommendedChoice >= 0 && + windowSystemRecommendedChoice < available.length && + available[windowSystemRecommendedChoice] != null) { + if (DEBUG) { + System.err.println("Choosing window system's recommended choice of " + windowSystemRecommendedChoice); + System.err.println(available[windowSystemRecommendedChoice]); + } + return windowSystemRecommendedChoice; + } + + // Create score array + int[] scores = new int[available.length]; + int NO_SCORE = -9999999; + int DOUBLE_BUFFER_MISMATCH_PENALTY = 1000; + int STENCIL_MISMATCH_PENALTY = 500; + // Pseudo attempt to keep equal rank penalties scale-equivalent + // (e.g., stencil mismatch is 3 * accum because there are 3 accum + // components) + int COLOR_MISMATCH_PENALTY_SCALE = 36; + int DEPTH_MISMATCH_PENALTY_SCALE = 6; + int ACCUM_MISMATCH_PENALTY_SCALE = 1; + int STENCIL_MISMATCH_PENALTY_SCALE = 3; + for (int i = 0; i < scores.length; i++) { + scores[i] = NO_SCORE; + } + // Compute score for each + for (int i = 0; i < scores.length; i++) { + GLCapabilities cur = available[i]; + if (cur == null) { + continue; + } + if (desired.getStereo() != cur.getStereo()) { + continue; + } + int score = 0; + // Compute difference in color depth + // (Note that this decides the direction of all other penalties) + score += (COLOR_MISMATCH_PENALTY_SCALE * + ((cur.getRedBits() + cur.getGreenBits() + cur.getBlueBits() + cur.getAlphaBits()) - + (desired.getRedBits() + desired.getGreenBits() + desired.getBlueBits() + desired.getAlphaBits()))); + // Compute difference in depth buffer depth + score += (DEPTH_MISMATCH_PENALTY_SCALE * sign(score) * + Math.abs(cur.getDepthBits() - desired.getDepthBits())); + // Compute difference in accumulation buffer depth + score += (ACCUM_MISMATCH_PENALTY_SCALE * sign(score) * + Math.abs((cur.getAccumRedBits() + cur.getAccumGreenBits() + cur.getAccumBlueBits() + cur.getAccumAlphaBits()) - + (desired.getAccumRedBits() + desired.getAccumGreenBits() + desired.getAccumBlueBits() + desired.getAccumAlphaBits()))); + // Compute difference in stencil bits + score += STENCIL_MISMATCH_PENALTY_SCALE * sign(score) * (cur.getStencilBits() - desired.getStencilBits()); + if (cur.getDoubleBuffered() != desired.getDoubleBuffered()) { + score += sign(score) * DOUBLE_BUFFER_MISMATCH_PENALTY; + } + if ((desired.getStencilBits() > 0) && (cur.getStencilBits() == 0)) { + score += sign(score) * STENCIL_MISMATCH_PENALTY; + } + scores[i] = score; + } + // Now prefer hardware-accelerated visuals by pushing scores of + // non-hardware-accelerated visuals out + boolean gotHW = false; + int maxAbsoluteHWScore = 0; + for (int i = 0; i < scores.length; i++) { + int score = scores[i]; + if (score == NO_SCORE) { + continue; + } + GLCapabilities cur = available[i]; + if (cur.getHardwareAccelerated()) { + int absScore = Math.abs(score); + if (!gotHW || + (absScore > maxAbsoluteHWScore)) { + gotHW = true; + maxAbsoluteHWScore = absScore; + } + } + } + if (gotHW) { + for (int i = 0; i < scores.length; i++) { + int score = scores[i]; + if (score == NO_SCORE) { + continue; + } + GLCapabilities cur = available[i]; + if (!cur.getHardwareAccelerated()) { + if (score <= 0) { + score -= maxAbsoluteHWScore; + } else if (score > 0) { + score += maxAbsoluteHWScore; + } + scores[i] = score; + } + } + } + + if (DEBUG) { + System.err.print("Scores: ["); + for (int i = 0; i < available.length; i++) { + if (i > 0) { + System.err.print(","); + } + System.err.print(" " + scores[i]); + } + System.err.println(" ]"); + } + + // Ready to select. Choose score closest to 0. + int scoreClosestToZero = NO_SCORE; + int chosenIndex = -1; + for (int i = 0; i < scores.length; i++) { + int score = scores[i]; + if (score == NO_SCORE) { + continue; + } + // Don't substitute a positive score for a smaller negative score + if ((scoreClosestToZero == NO_SCORE) || + (Math.abs(score) < Math.abs(scoreClosestToZero) && + ((sign(scoreClosestToZero) < 0) || (sign(score) > 0)))) { + scoreClosestToZero = score; + chosenIndex = i; + } + } + if (chosenIndex < 0) { + throw new GLException("Unable to select one of the provided GLCapabilities"); + } + if (DEBUG) { + System.err.println("Chosen index: " + chosenIndex); + System.err.println("Chosen capabilities:"); + System.err.println(available[chosenIndex]); + } + + return chosenIndex; + } + + private static int sign(int score) { + if (score < 0) { + return -1; + } + return 1; + } +} diff --git a/src/classes/javax/media/opengl/GLAutoDrawable.java b/src/classes/javax/media/opengl/GLAutoDrawable.java new file mode 100644 index 000000000..18adfde54 --- /dev/null +++ b/src/classes/javax/media/opengl/GLAutoDrawable.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +import javax.media.opengl.glu.*; + +/** A higher-level abstraction than {@link GLDrawable} which supplies + an event based mechanism ({@link GLEventListener}) for performing + OpenGL rendering. A GLAutoDrawable automatically creates a primary + rendering context which is associated with the GLAutoDrawable for + the lifetime of the object. This context has the {@link + GLContext#setSynchronized synchronized} property enabled so that + calls to {@link GLContext#makeCurrent makeCurrent} will block if + the context is current on another thread. This allows the internal + GLContext for the GLAutoDrawable to be used both by the event + based rendering mechanism as well by end users directly. */ + +public interface GLAutoDrawable extends GLDrawable, ComponentEvents { + /** + * Returns the context associated with this drawable. The returned + * context will be synchronized. + */ + public GLContext getContext(); + + /** Adds a {@link GLEventListener} to this drawable. If multiple + listeners are added to a given drawable, they are notified of + events in an arbitrary order. */ + public void addGLEventListener(GLEventListener listener); + + /** Removes a {@link GLEventListener} from this drawable. Note that + if this is done from within a particular drawable's {@link + GLEventListener} handler (reshape, display, etc.) that it is not + guaranteed that all other listeners will be evaluated properly + during this update cycle. */ + public void removeGLEventListener(GLEventListener listener); + + /** Causes OpenGL rendering to be performed for this GLAutoDrawable + by calling {@link GLEventListener#display display} for all + registered {@link GLEventListener}s. Called automatically by the + window system toolkit upon receiving a repaint() request. this + routine may be called manually for better control over the + rendering process. It is legal to call another GLAutoDrawable's + display method from within the {@link GLEventListener#display + display} callback. */ + public void display(); + + /** Schedules a repaint of the component at some point in the + future. */ + public void repaint(); + + /** Enables or disables automatic buffer swapping for this drawable. + By default this property is set to true; when true, after all + GLEventListeners have been called for a display() event, the + front and back buffers are swapped, displaying the results of + the render. When disabled, the user is responsible for calling + {@link #swapBuffers} manually. */ + public void setAutoSwapBufferMode(boolean onOrOff); + + /** Indicates whether automatic buffer swapping is enabled for this + drawable. See {@link #setAutoSwapBufferMode}. */ + public boolean getAutoSwapBufferMode(); + + /** Returns the {@link GL} pipeline object this GLAutoDrawable uses. + If this method is called outside of the {@link + GLEventListener}'s callback methods (init, display, etc.) it may + return null. Users should not rely on the identity of the + returned GL object; for example, users should not maintain a + hash table with the GL object as the key. Additionally, the GL + object should not be cached in client code, but should be + re-fetched from the GLAutoDrawable at the beginning of each call + to init, display, etc. */ + public GL getGL(); + + /** Sets the {@link GL} pipeline object this GLAutoDrawable uses. + This should only be called from within the GLEventListener's + callback methods, and usually only from within the init() + method, in order to install a composable pipeline. See the JOGL + demos for examples. */ + public void setGL(GL gl); +} diff --git a/src/classes/javax/media/opengl/GLCanvas.java b/src/classes/javax/media/opengl/GLCanvas.java new file mode 100644 index 000000000..f2ca1bf80 --- /dev/null +++ b/src/classes/javax/media/opengl/GLCanvas.java @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +import java.awt.Canvas; +import java.awt.EventQueue; +import java.awt.Graphics; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsDevice; +import com.sun.opengl.impl.*; + +// FIXME: Subclasses need to call resetGLFunctionAvailability() on their +// context whenever the displayChanged() function is called on our +// GLEventListeners + +/** A heavyweight AWT component which provides OpenGL rendering + support. This is the primary implementation of {@link GLDrawable}; + {@link GLJPanel} is provided for compatibility with Swing user + interfaces when adding a heavyweight doesn't work either because + of Z-ordering or LayoutManager problems. This class can not be + instantiated directly; use {@link GLDrawableFactory} to construct + them. */ + +public class GLCanvas extends Canvas implements GLAutoDrawable { + + private static final boolean DEBUG = Debug.debug("GLCanvas"); + + private GLDrawableHelper drawableHelper = new GLDrawableHelper(); + private GLDrawable drawable; + private GLContextImpl context; + private boolean autoSwapBufferMode = true; + private boolean sendReshape = false; + + /** Creates a new GLCanvas component. The passed GLCapabilities must + be non-null and specifies the OpenGL capabilities for the + component. The GLCapabilitiesChooser must be non-null and + specifies the algorithm for selecting one of the available + GLCapabilities for the component; the GLDrawableFactory uses a + DefaultGLCapabilitesChooser if the user does not provide + one. The passed GLContext may be null and specifies an OpenGL + context with which to share textures, display lists and other + OpenGL state. The passed GraphicsDevice must be non-null and + indicates the screen on which to create the GLCanvas; the + GLDrawableFactory uses the default screen device of the local + GraphicsEnvironment if the user does not provide one. */ + protected GLCanvas(GLCapabilities capabilities, + GLCapabilitiesChooser chooser, + GLContext shareWith, + GraphicsDevice device) { + // The platform-specific GLDrawableFactory will only provide a + // non-null GraphicsConfiguration on platforms where this is + // necessary (currently only X11, as Windows allows the pixel + // format of the window to be set later and Mac OS X seems to + // handle this very differently than all other platforms). On + // other platforms this method returns null; it is the case (at + // least in the Sun AWT implementation) that this will result in + // equivalent behavior to calling the no-arg super() constructor + // for Canvas. + super(GLDrawableFactory.getFactory().chooseGraphicsConfiguration(capabilities, chooser, device)); + drawable = GLDrawableFactory.getFactory().getGLDrawable(this, capabilities, chooser); + context = (GLContextImpl) drawable.createContext(shareWith); + context.setSynchronized(true); + } + + public GLContext createContext(GLContext shareWith) { + return drawable.createContext(shareWith); + } + + public void setRealized(boolean realized) { + } + + public void display() { + maybeDoSingleThreadedWorkaround(displayOnEventDispatchThreadAction, + displayAction); + } + + /** Overridden from Canvas; calls {@link #display}. Should not be + invoked by applications directly. */ + public void paint(Graphics g) { + display(); + } + + /** Overridden from Canvas; used to indicate when it's safe to + create an OpenGL context for the component. */ + public void addNotify() { + super.addNotify(); + drawable.setRealized(true); + if (DEBUG) { + System.err.println("GLCanvas.addNotify()"); + } + } + + /** Overridden from Canvas; used to indicate that it's no longer + safe to have an OpenGL context for the component. */ + public void removeNotify() { + context.destroy(); + drawable.setRealized(false); + super.removeNotify(); + if (DEBUG) { + System.err.println("GLCanvas.removeNotify()"); + } + } + + /** Overridden from Canvas; causes {@link GLDrawableHelper#reshape} + to be called on all registered {@link GLEventListener}s. Called + automatically by the AWT; should not be invoked by applications + directly. */ + public void reshape(int x, int y, int width, int height) { + super.reshape(x, y, width, height); + sendReshape = true; + } + + /** Overridden from Canvas to prevent Java2D's clearing of the + canvas from interfering with the OpenGL rendering. */ + public void update(Graphics g) { + paint(g); + } + + public void addGLEventListener(GLEventListener listener) { + drawableHelper.addGLEventListener(listener); + } + + public void removeGLEventListener(GLEventListener listener) { + drawableHelper.removeGLEventListener(listener); + } + + public GLContext getContext() { + return context; + } + + public GL getGL() { + return getContext().getGL(); + } + + public void setGL(GL gl) { + getContext().setGL(gl); + } + + public void setAutoSwapBufferMode(boolean onOrOff) { + drawableHelper.setAutoSwapBufferMode(onOrOff); + } + + public boolean getAutoSwapBufferMode() { + return drawableHelper.getAutoSwapBufferMode(); + } + + public void swapBuffers() { + maybeDoSingleThreadedWorkaround(swapBuffersOnEventDispatchThreadAction, swapBuffersAction); + } + + //---------------------------------------------------------------------- + // Internals only below this point + // + + private void maybeDoSingleThreadedWorkaround(Runnable eventDispatchThreadAction, + Runnable invokeGLAction) { + if (Threading.isSingleThreaded() && + !Threading.isOpenGLThread()) { + Threading.invokeOnOpenGLThread(eventDispatchThreadAction); + } else { + drawableHelper.invokeGL(drawable, context, invokeGLAction, initAction); + } + } + + class InitAction implements Runnable { + public void run() { + drawableHelper.init(GLCanvas.this); + } + } + private InitAction initAction = new InitAction(); + + class DisplayAction implements Runnable { + public void run() { + if (sendReshape) { + // Note: we ignore the given x and y within the parent component + // since we are drawing directly into this heavyweight component. + int width = getWidth(); + int height = getHeight(); + getGL().glViewport(0, 0, width, height); + drawableHelper.reshape(GLCanvas.this, 0, 0, width, height); + sendReshape = false; + } + + drawableHelper.display(GLCanvas.this); + } + } + private DisplayAction displayAction = new DisplayAction(); + + class SwapBuffersAction implements Runnable { + public void run() { + drawable.swapBuffers(); + } + } + private SwapBuffersAction swapBuffersAction = new SwapBuffersAction(); + + // Workaround for ATI driver bugs related to multithreading issues + // like simultaneous rendering via Animators to canvases that are + // being resized on the AWT event dispatch thread + class DisplayOnEventDispatchThreadAction implements Runnable { + public void run() { + drawableHelper.invokeGL(drawable, context, displayAction, initAction); + } + } + private DisplayOnEventDispatchThreadAction displayOnEventDispatchThreadAction = + new DisplayOnEventDispatchThreadAction(); + class SwapBuffersOnEventDispatchThreadAction implements Runnable { + public void run() { + drawableHelper.invokeGL(drawable, context, swapBuffersAction, initAction); + } + } + private SwapBuffersOnEventDispatchThreadAction swapBuffersOnEventDispatchThreadAction = + new SwapBuffersOnEventDispatchThreadAction(); +} diff --git a/src/classes/javax/media/opengl/GLCapabilities.java b/src/classes/javax/media/opengl/GLCapabilities.java new file mode 100644 index 000000000..77ada1b1a --- /dev/null +++ b/src/classes/javax/media/opengl/GLCapabilities.java @@ -0,0 +1,342 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +/** Specifies a set of OpenGL capabilities that a rendering context + must support, such as color depth and whether stereo is enabled. + It currently contains the minimal number of routines which allow + configuration on all supported window systems. */ + +public class GLCapabilities implements Cloneable { + private boolean doubleBuffered = true; + private boolean stereo = false; + private boolean hardwareAccelerated = true; + private int depthBits = 24; + private int stencilBits = 0; + private int redBits = 8; + private int greenBits = 8; + private int blueBits = 8; + private int alphaBits = 0; + private int accumRedBits = 0; + private int accumGreenBits = 0; + private int accumBlueBits = 0; + private int accumAlphaBits = 0; + // Shift bits from PIXELFORMATDESCRIPTOR not present because they + // are unlikely to be supported on Windows anyway + + // Support for full-scene antialiasing (FSAA) + private boolean sampleBuffers = false; + private int numSamples = 2; + + // Bits for pbuffer creation + private boolean offscreenFloatingPointBuffers; + private boolean offscreenRenderToTexture; + private boolean offscreenRenderToTextureRectangle; + + /** Creates a GLCapabilities object. All attributes are in a default + state. + */ + public GLCapabilities() {} + + public Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + throw new GLException(e); + } + } + + /** Indicates whether double-buffering is enabled. */ + public boolean getDoubleBuffered() { + return doubleBuffered; + } + + /** Enables or disables double buffering. */ + public void setDoubleBuffered(boolean onOrOff) { + doubleBuffered = onOrOff; + } + + /** Indicates whether stereo is enabled. */ + public boolean getStereo() { + return stereo; + } + + /** Enables or disables stereo viewing. */ + public void setStereo(boolean onOrOff) { + stereo = onOrOff; + } + + /** Indicates whether hardware acceleration is enabled. */ + public boolean getHardwareAccelerated() { + return hardwareAccelerated; + } + + /** Enables or disables hardware acceleration. */ + public void setHardwareAccelerated(boolean onOrOff) { + hardwareAccelerated = onOrOff; + } + + /** Returns the number of bits requested for the depth buffer. */ + public int getDepthBits() { + return depthBits; + } + + /** Sets the number of bits requested for the depth buffer. */ + public void setDepthBits(int depthBits) { + this.depthBits = depthBits; + } + + /** Returns the number of bits requested for the stencil buffer. */ + public int getStencilBits() { + return stencilBits; + } + + /** Sets the number of bits requested for the stencil buffer. */ + public void setStencilBits(int stencilBits) { + this.stencilBits = stencilBits; + } + + /** Returns the number of bits requested for the color buffer's red + component. On some systems only the color depth, which is the + sum of the red, green, and blue bits, is considered. */ + public int getRedBits() { + return redBits; + } + + /** Sets the number of bits requested for the color buffer's red + component. On some systems only the color depth, which is the + sum of the red, green, and blue bits, is considered. */ + public void setRedBits(int redBits) { + this.redBits = redBits; + } + + /** Returns the number of bits requested for the color buffer's + green component. On some systems only the color depth, which is + the sum of the red, green, and blue bits, is considered. */ + public int getGreenBits() { + return greenBits; + } + + /** Sets the number of bits requested for the color buffer's green + component. On some systems only the color depth, which is the + sum of the red, green, and blue bits, is considered. */ + public void setGreenBits(int greenBits) { + this.greenBits = greenBits; + } + + /** Returns the number of bits requested for the color buffer's blue + component. On some systems only the color depth, which is the + sum of the red, green, and blue bits, is considered. */ + public int getBlueBits() { + return blueBits; + } + + /** Sets the number of bits requested for the color buffer's blue + component. On some systems only the color depth, which is the + sum of the red, green, and blue bits, is considered. */ + public void setBlueBits(int blueBits) { + this.blueBits = blueBits; + } + + /** Returns the number of bits requested for the color buffer's + alpha component. On some systems only the color depth, which is + the sum of the red, green, and blue bits, is considered. */ + public int getAlphaBits() { + return alphaBits; + } + + /** Sets the number of bits requested for the color buffer's alpha + component. On some systems only the color depth, which is the + sum of the red, green, and blue bits, is considered. */ + public void setAlphaBits(int alphaBits) { + this.alphaBits = alphaBits; + } + + /** Returns the number of bits requested for the accumulation + buffer's red component. On some systems only the accumulation + buffer depth, which is the sum of the red, green, and blue bits, + is considered. */ + public int getAccumRedBits() { + return accumRedBits; + } + + /** Sets the number of bits requested for the accumulation buffer's + red component. On some systems only the accumulation buffer + depth, which is the sum of the red, green, and blue bits, is + considered. */ + public void setAccumRedBits(int accumRedBits) { + this.accumRedBits = accumRedBits; + } + + /** Returns the number of bits requested for the accumulation + buffer's green component. On some systems only the accumulation + buffer depth, which is the sum of the red, green, and blue bits, + is considered. */ + public int getAccumGreenBits() { + return accumGreenBits; + } + + /** Sets the number of bits requested for the accumulation buffer's + green component. On some systems only the accumulation buffer + depth, which is the sum of the red, green, and blue bits, is + considered. */ + public void setAccumGreenBits(int accumGreenBits) { + this.accumGreenBits = accumGreenBits; + } + + /** Returns the number of bits requested for the accumulation + buffer's blue component. On some systems only the accumulation + buffer depth, which is the sum of the red, green, and blue bits, + is considered. */ + public int getAccumBlueBits() { + return accumBlueBits; + } + + /** Sets the number of bits requested for the accumulation buffer's + blue component. On some systems only the accumulation buffer + depth, which is the sum of the red, green, and blue bits, is + considered. */ + public void setAccumBlueBits(int accumBlueBits) { + this.accumBlueBits = accumBlueBits; + } + + /** Returns the number of bits requested for the accumulation + buffer's alpha component. On some systems only the accumulation + buffer depth, which is the sum of the red, green, and blue bits, + is considered. */ + public int getAccumAlphaBits() { + return accumAlphaBits; + } + + /** Sets number of bits requested for accumulation buffer's alpha + component. On some systems only the accumulation buffer depth, + which is the sum of the red, green, and blue bits, is + considered. */ + public void setAccumAlphaBits(int accumAlphaBits) { + this.accumAlphaBits = accumAlphaBits; + } + + /** Indicates whether sample buffers for full-scene antialiasing + (FSAA) should be allocated for this drawable. Defaults to + false. */ + public void setSampleBuffers(boolean onOrOff) { + sampleBuffers = onOrOff; + } + + /** Returns whether sample buffers for full-scene antialiasing + (FSAA) should be allocated for this drawable. Defaults to + false. */ + public boolean getSampleBuffers() { + return sampleBuffers; + } + + /** If sample buffers are enabled, indicates the number of buffers + to be allocated. Defaults to 2. */ + public void setNumSamples(int numSamples) { + this.numSamples = numSamples; + } + + /** Returns the number of sample buffers to be allocated if sample + buffers are enabled. Defaults to 2. */ + public int getNumSamples() { + return numSamples; + } + + /** For offscreen surfaces only (pbuffers), indicates whether + floating-point buffers should be used if available. Defaults to + false. */ + public void setOffscreenFloatingPointBuffers(boolean onOrOff) { + offscreenFloatingPointBuffers = onOrOff; + } + + /** For offscreen surfaces only (pbuffers), returns whether + floating-point buffers should be used if available. Defaults to + false. */ + public boolean getOffscreenFloatingPointBuffers() { + return offscreenFloatingPointBuffers; + } + + /** For offscreen surfaces only (pbuffers), indicates whether the + render-to-texture extension should be used if available. + Defaults to false. */ + public void setOffscreenRenderToTexture(boolean onOrOff) { + offscreenRenderToTexture = onOrOff; + } + + /** For offscreen surfaces only (pbuffers), returns whether the + render-to-texture extension should be used if available. + Defaults to false. */ + public boolean getOffscreenRenderToTexture() { + return offscreenRenderToTexture; + } + + /** For offscreen surfaces only (pbuffers), indicates whether the + render-to-texture-rectangle extension should be used if + available. Defaults to false. */ + public void setOffscreenRenderToTextureRectangle(boolean onOrOff) { + offscreenRenderToTextureRectangle = onOrOff; + } + + /** For offscreen surfaces only (pbuffers), returns whether the + render-to-texture extension should be used. Defaults to false. */ + public boolean getOffscreenRenderToTextureRectangle() { + return offscreenRenderToTextureRectangle; + } + + /** Returns a textual representation of this GLCapabilities + object. */ + public String toString() { + return ("GLCapabilities [" + + "DoubleBuffered: " + doubleBuffered + + ", Stereo: " + stereo + + ", HardwareAccelerated: " + hardwareAccelerated + + ", DepthBits: " + depthBits + + ", StencilBits: " + stencilBits + + ", Red: " + redBits + + ", Green: " + greenBits + + ", Blue: " + blueBits + + ", Alpha: " + alphaBits + + ", Red Accum: " + accumRedBits + + ", Green Accum: " + accumGreenBits + + ", Blue Accum: " + accumBlueBits + + ", Alpha Accum: " + accumAlphaBits + + " ]"); + } +} diff --git a/src/classes/javax/media/opengl/GLCapabilitiesChooser.java b/src/classes/javax/media/opengl/GLCapabilitiesChooser.java new file mode 100644 index 000000000..9d970ff42 --- /dev/null +++ b/src/classes/javax/media/opengl/GLCapabilitiesChooser.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +/** Provides a mechanism by which applications can customize the + window type selection for a given {@link GLCapabilities}. + Developers can implement this interface and pass an instance into + the appropriate method of {@link GLDrawableFactory}; the chooser + will be called during the OpenGL context creation process. */ + +public interface GLCapabilitiesChooser { + /** Chooses the index (0..available.length - 1) of the {@link + GLCapabilities} most closely matching the desired one from the + list of all supported. Some of the entries in the + <code>available</code> array may be null; the chooser must + ignore these. The <em>windowSystemRecommendedChoice</em> + parameter may be provided to the chooser by the underlying + window system; if this index is valid, it is recommended, but + not necessarily required, that the chooser select that entry. + + <P> <em>Note:</em> this method is called automatically by the + {@link GLDrawableFactory} when an instance of this class is + passed in to one of its factory methods. It should generally not + be invoked by users directly, unless it is desired to delegate + the choice to some other GLCapabilitiesChooser object. + */ + public int chooseCapabilities(GLCapabilities desired, + GLCapabilities[] available, + int windowSystemRecommendedChoice); +} diff --git a/src/classes/javax/media/opengl/GLContext.java b/src/classes/javax/media/opengl/GLContext.java new file mode 100644 index 000000000..82997bc8f --- /dev/null +++ b/src/classes/javax/media/opengl/GLContext.java @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +/** Abstraction for an OpenGL rendering context. In order to perform + OpenGL rendering, a context must be "made current" on the current + thread. OpenGL rendering semantics specify that only one context + may be current on the current thread at any given time, and also + that a given context may be current on only one thread at any + given time. Because components can be added to and removed from + the component hierarchy at any time, it is possible that the + underlying OpenGL context may need to be destroyed and recreated + multiple times over the lifetime of a given component. This + process is handled by the implementation, and the GLContext + abstraction provides a stable object which clients can use to + refer to a given context. */ + +public abstract class GLContext { + /** Indicates that the context was not made current during the last call to {@link #makeCurrent makeCurrent}. */ + public static final int CONTEXT_NOT_CURRENT = 0; + /** Indicates that the context was made current during the last call to {@link #makeCurrent makeCurrent}. */ + public static final int CONTEXT_CURRENT = 1; + /** Indicates that a newly-created context was made current during the last call to {@link #makeCurrent makeCurrent}. */ + public static final int CONTEXT_CURRENT_NEW = 2; + + private static ThreadLocal currentContext = new ThreadLocal(); + + /** + * Returns the GLDrawable to which this context may be used to + * draw. + */ + public abstract GLDrawable getGLDrawable(); + + /** + * Makes this GLContext current on the calling thread. + * + * There are two return values that indicate success and one that + * indicates failure. A return value of CONTEXT_CURRENT_NEW + * indicates that that context has been made current, and that + * this is the first time this context has been made current, or + * that the state of the underlying context or drawable may have + * changed since the last time this context was made current. In + * this case, the application may wish to initialize the state. A + * return value of CONTEXT_CURRENT indicates that the context has + * been made currrent, with its previous state restored. + * + * If the context could not be made current (for example, because + * the underlying drawable has not ben realized on the display) , + * a value of CONTEXT_NOT_CURRENT is returned. + * + * If the context is in use by another thread at the time of the + * call, then if isSynchronized() is true the call will + * block. If isSynchronized() is false, an exception will be + * thrown and the context will remain current on the other thread. + * + * @return CONTEXT_CURRENT if the context was successfully made current + * @return CONTEXT_CURRENT_NEW if the context was successfully made + * current, but need to be initialized. + * + * @return CONTEXT_NOT_CURRENT if the context could not be made current. + * + * @throws GLException if synchronization is disabled and the + * context is current on another thread, or because the context + * could not be created or made current due to non-recoverable, + * window system-specific errors. + */ + public abstract int makeCurrent() throws GLException; + + /** + * Releases control of this GLContext from the current thread. + * + * @throws GLException if the context had not previously been made + * current on the current thread + */ + public abstract void release() throws GLException; + + /** + * Returns the context which is current on the current thread. If no + * context is current, returns null. + * + * @return the context current on this thread, or null if no context + * is current. + */ + public static GLContext getCurrent() { + return (GLContext) currentContext.get(); + } + + /** + * Sets the current context object on the current thread. This + * method is called by GLContext implementations during {@link + * #makeCurrent} and does not need to be called by end users. + * + */ + public static void setCurrent(GLContext cur) { + currentContext.set(cur); + } + + /** + * Destroys this OpenGL context and frees its associated resources. + */ + public abstract void destroy(); + + /** + * Returns true if 'makeCurrent' will exhibit synchronized behavior. + */ + public abstract boolean isSynchronized(); + + /** + * Determines whether 'makeCurrent' will exhibit synchronized behavior. + */ + public abstract void setSynchronized(boolean isSynchronized); + + /** + * Returns the GL pipeline object for this GLContext. + */ + public abstract GL getGL(); + + /** + * Sets the GL pipeline object for this GLContext. + */ + public abstract void setGL(GL gl); +} diff --git a/src/classes/javax/media/opengl/GLDrawable.java b/src/classes/javax/media/opengl/GLDrawable.java new file mode 100644 index 000000000..5b54bd369 --- /dev/null +++ b/src/classes/javax/media/opengl/GLDrawable.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +// FIXME: We need some way to tell when the device upon which the canvas is +// being displayed has changed (e.g., the user drags the canvas's parent +// window from one screen on multi-screen environment to another, when the +// user changes the display bit depth or screen resolution, etc). When this +// occurs, we need the canvas to reset the gl function pointer tables for the +// canvas, because the new device may have different capabilities (e.g., +// doesn't support as many opengl extensions) from the original device. This +// hook would also be useful in other GLDrawables (for example, offscreen +// buffers such as pbuffers, whose contents may or may not be invalidated when +// the display mode changes, depending on the vendor's GL implementation). +// +// Right now I'm not sure how hook into when this change occurs. There isn't +// any AWT event corresponding to a device change (as far as I can +// tell). We could constantly check the GraphicsConfiguration of the canvas's top-level +// parent to see if it has changed, but this would be very slow (we'd have to +// do it every time the context is made current). There has got to be a better +// solution, but I'm not sure what it is. + +// FIXME: Subclasses need to call resetGLFunctionAvailability() on their +// context whenever the displayChanged() function is called on our +// GLEventListeners + +/** An abstraction for an OpenGL rendering target. A GLDrawable's + primary functionality is to create OpenGL contexts which can be + used to perform rendering. A GLDrawable does not automatically + create an OpenGL context, but all implementations of {@link + GLAutoDrawable} do so upon creation. */ + +public interface GLDrawable { + /** + * Creates a new context for drawing to this drawable that will + * share display lists with the given GLContext. + * + * The GLContext <code>share</code> need not be associated with this + * GLDrawable. + */ + public GLContext createContext(GLContext shareWith); + + /** + + * Indicates to on-screen GLDrawable implementations whether the + * underlying window has been created and can be drawn into. This + * method must be called from GLDrawables obtained from the + * GLDrawableFactory via the {@link GLDrawableFactory#getGLDrawable + * GLDrawableFactory.getGLDrawable()} method. It must typically be + * called with an argument of <code>true</code> in the + * <code>addNotify</code> method of components performing OpenGL + * rendering and with an argument of <code>false</code> in the + * <code>removeNotify</code> method. Calling this method has no + * other effects. For example, if <code>removeNotify</code> is + * called on a Canvas implementation for which a GLDrawable has been + * created, it is also necessary to destroy all OpenGL contexts + * associated with that GLDrawable. This is not done automatically + * by the implementation. It is not necessary to call + * <code>setRealized</code> on a GLCanvas, a GLJPanel, or a + * GLPbuffer, as these perform the appropriate calls on their + * underlying GLDrawables internally.. + */ + public void setRealized(boolean realized); + + /** Requests a new width and height for this GLDrawable. Not all + drawables are able to respond to this request and may silently + ignore it. */ + public void setSize(int width, int height); + + /** Returns the current width of this GLDrawable. */ + public int getWidth(); + + /** Returns the current height of this GLDrawable. */ + public int getHeight(); + + /** Swaps the front and back buffers of this drawable. For {@link + GLAutoDrawable} implementations, when automatic buffer swapping + is enabled (as is the default), it is not necessary to call this + method and doing so may have undefined results. */ + public void swapBuffers() throws GLException; +} diff --git a/src/classes/javax/media/opengl/GLDrawableFactory.java b/src/classes/javax/media/opengl/GLDrawableFactory.java new file mode 100644 index 000000000..c45bb16e0 --- /dev/null +++ b/src/classes/javax/media/opengl/GLDrawableFactory.java @@ -0,0 +1,282 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsDevice; +import com.sun.opengl.impl.*; + +/** <P> Provides a virtual machine- and operating system-independent + mechanism for creating {@link GLDrawable}s. </P> + + <P> The {@link javax.media.opengl.GLCapabilities} objects passed in to the + various factory methods are used as a hint for the properties of + the returned drawable. The default capabilities selection + algorithm (equivalent to passing in a null {@link + GLCapabilitiesChooser}) is described in {@link + DefaultGLCapabilitiesChooser}. Sophisticated applications needing + to change the selection algorithm may pass in their own {@link + GLCapabilitiesChooser} which can select from the available pixel + formats. </P> + + <P> Because of the multithreaded nature of the Java platform's + window system toolkit, it is typically not possible to immediately + reject a given {@link GLCapabilities} as being unsupportable by + either returning <code>null</code> from the creation routines or + raising a {@link GLException}. The semantics of the rejection + process are (unfortunately) left unspecified for now. The current + implementation will cause a {@link GLException} to be raised + during the first repaint of the {@link GLCanvas} or {@link + GLJPanel} if the capabilities can not be met. Pbuffers are always + created immediately and their creation will fail with a {@link + GLException} if errors occur. </P> +*/ + +public abstract class GLDrawableFactory { + private static GLDrawableFactory factory; + + protected GLDrawableFactory() {} + + /** Returns the sole GLDrawableFactory instance. */ + public static GLDrawableFactory getFactory() { + if (factory == null) { + try { + String osName = System.getProperty("os.name"); + String osNameLowerCase = osName.toLowerCase(); + Class factoryClass = null; + + // Because there are some complications with generating all + // platforms' Java glue code on all platforms (among them that we + // would have to include jawt.h and jawt_md.h in the jogl + // sources, which we currently don't have to do) we break the only + // static dependencies with platform-specific code here using reflection. + + if (osNameLowerCase.startsWith("wind")) { + factoryClass = Class.forName("com.sun.opengl.impl.windows.WindowsGLDrawableFactory"); + } else if (osNameLowerCase.startsWith("mac os x")) { + factoryClass = Class.forName("com.sun.opengl.impl.macosx.MacOSXGLDrawableFactory"); + } else { + // Assume Linux, Solaris, etc. Should probably test for these explicitly. + factoryClass = Class.forName("com.sun.opengl.impl.x11.X11GLDrawableFactory"); + } + + if (factoryClass == null) { + throw new GLException("OS " + osName + " not yet supported"); + } + + factory = (GLDrawableFactory) factoryClass.newInstance(); + } catch (ClassNotFoundException e) { + throw new GLException(e); + } catch (InstantiationException e) { + throw new GLException(e); + } catch (IllegalAccessException e) { + throw new GLException(e); + } + } + + return factory; + } + + /** + * Selects an AWT GraphicsConfiguration on the specified + * GraphicsDevice compatible with the supplied GLCapabilities. This + * method is intended to be used by applications which do not use + * the supplied GLCanvas class but instead wrap their own Canvas + * with a GLDrawable. Some platforms (specifically X11) require the + * GraphicsConfiguration to be specified when the platform-specific + * window system object, such as a Canvas, is created. This method + * returns null on platforms on which the OpenGL pixel format + * selection process is performed later. + * + * @see java.awt.Canvas#Canvas(java.awt.GraphicsConfiguration) + */ + public abstract GraphicsConfiguration + chooseGraphicsConfiguration(GLCapabilities capabilities, + GLCapabilitiesChooser chooser, + GraphicsDevice device); + + /** + * Returns a GLDrawable that wraps a platform-specific window system + * object, such as an AWT or LCDUI Canvas. On platforms which + * support it, selects a pixel format compatible with the supplied + * GLCapabilities, or if the passed GLCapabilities object is null, + * uses a default set of capabilities. On these platforms, uses + * either the supplied GLCapabilitiesChooser object, or if the + * passed GLCapabilitiesChooser object is null, uses a + * DefaultGLCapabilitiesChooser instance. + * + * @throws IllegalArgumentException if the passed target is either + * null or its data type is not supported by this GLDrawableFactory. + * @throws GLException if any window system-specific errors caused + * the creation of the GLDrawable to fail. + */ + public abstract GLDrawable getGLDrawable(Object target, + GLCapabilities capabilities, + GLCapabilitiesChooser chooser) + throws IllegalArgumentException, GLException; + + //---------------------------------------------------------------------- + // Methods to create high-level objects + + /** Creates a {@link GLCanvas} on the default graphics device with + the specified capabilities using the default capabilities + selection algorithm. */ + public GLCanvas createGLCanvas(GLCapabilities capabilities) { + return createGLCanvas(capabilities, null, null, null); + } + + /** Creates a {@link GLCanvas} on the specified graphics device with + the specified capabilities using the supplied capabilities + selection algorithm. A null chooser is equivalent to using the + {@link DefaultGLCapabilitiesChooser}. The canvas will share + textures and display lists with the specified {@link GLContext}; + the context must either be null or have been fabricated by + classes in this package. A null context indicates no sharing. A + null GraphicsDevice is equivalent to using that returned from + <code>GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()</code>. */ + public GLCanvas createGLCanvas(GLCapabilities capabilities, + GLCapabilitiesChooser chooser, + GLContext shareWith, + GraphicsDevice device) { + return new GLCanvas(capabilities, + chooser, + shareWith, + device); + } + + /** Creates a {@link GLJPanel} with the specified capabilities using + the default capabilities selection algorithm. */ + public GLJPanel createGLJPanel(GLCapabilities capabilities) { + return createGLJPanel(capabilities, null, null); + } + + /** Creates a {@link GLJPanel} with the specified capabilities using + the supplied capabilities selection algorithm. A null chooser is + equivalent to using the {@link DefaultGLCapabilitiesChooser}. + The panel will share textures and display lists with the + specified {@link GLContext}; the context must either be null or + have been fabricated by classes in this package. A null context + indicates no sharing. */ + public GLJPanel createGLJPanel(GLCapabilities capabilities, + GLCapabilitiesChooser chooser, + GLContext shareWith) { + return new GLJPanel(capabilities, chooser, shareWith); + } + + /** + * Returns true if it is possible to create a GLPbuffer. Some older + * graphics cards do not have this capability. + */ + public abstract boolean canCreateGLPbuffer(); + + /** + * Creates a GLPbuffer with the given capabilites and dimensions. + */ + public abstract GLPbuffer createGLPbuffer(GLCapabilities capabilities, + int initialWidth, + int initialHeight, + GLContext shareWith); + + //---------------------------------------------------------------------- + // Methods for interacting with third-party OpenGL libraries + + /** + * <P> Creates a GLContext object representing an existing OpenGL + * context in an external (third-party) OpenGL-based library. This + * GLContext object may be used to draw into this preexisting + * context using its {@link GL} and {@link + * javax.media.opengl.glu.GLU} objects. New contexts created through + * {@link GLDrawable}s may share textures and display lists with + * this external context. </P> + * + * <P> The underlying OpenGL context must be current on the current + * thread at the time this method is called. The user is responsible + * for the maintenance of the underlying OpenGL context; calls to + * <code>makeCurrent</code> and <code>release</code> on the returned + * GLContext object have no effect. If the underlying OpenGL context + * is destroyed, the <code>destroy</code> method should be called on + * the <code>GLContext</code>. A new <code>GLContext</code> object + * should be created for each newly-created underlying OpenGL + * context. + */ + public abstract GLContext createExternalGLContext(); + + /** + * Returns true if it is possible to create an external GLDrawable + * object via {@link #createExternalGLDrawable}. + */ + public abstract boolean canCreateExternalGLDrawable(); + + /** + * <P> Creates a {@link GLDrawable} object representing an existing + * OpenGL drawable in an external (third-party) OpenGL-based + * library. This GLDrawable object may be used to create new, + * fully-functional {@link GLContext}s on the OpenGL drawable. This + * is useful when interoperating with a third-party OpenGL-based + * library and it is essential to not perturb the state of the + * library's existing context, even to the point of not sharing + * textures or display lists with that context. </P> + * + * <P> An underlying OpenGL context must be current on the desired + * drawable and the current thread at the time this method is + * called. The user is responsible for the maintenance of the + * underlying drawable. If one or more contexts are created on the + * drawable using {@link GLDrawable#createContext}, and the drawable + * is deleted by the third-party library, the user is responsible + * for calling {@link GLContext#destroy} on these contexts. </P> + * + * <P> Calls to <code>setSize</code>, <code>getWidth</code> and + * <code>getHeight</code> are illegal on the returned GLDrawable. If + * these operations are required by the user, they must be performed + * by the third-party library. </P> + * + * <P> It is legal to create both an external GLContext and + * GLDrawable representing the same third-party OpenGL entities. + * This can be used, for example, to query current state information + * using the external GLContext and then create and set up new + * GLContexts using the external GLDrawable. </P> + * + * <P> This functionality may not be available on all platforms and + * {@link #canCreateExternalGLDrawable} should be called first to + * see if it is present. For example, on X11 platforms, this API + * requires the presence of GLX 1.3 or later. + */ + public abstract GLDrawable createExternalGLDrawable(); +} diff --git a/src/classes/javax/media/opengl/GLEventListener.java b/src/classes/javax/media/opengl/GLEventListener.java new file mode 100644 index 000000000..3aadbf833 --- /dev/null +++ b/src/classes/javax/media/opengl/GLEventListener.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +import java.util.EventListener; + +/** Declares events which client code can use to manage OpenGL + rendering into a {@link GLAutoDrawable}. At the time any of these + methods is called, the drawable has made its associated OpenGL + context current, so it is valid to make OpenGL calls. */ + +public interface GLEventListener extends EventListener { + /** Called by the drawable immediately after the OpenGL context is + initialized. Can be used to perform one-time OpenGL + initialization such as setup of lights and display lists. Note + that this method may be called more than once if the underlying + OpenGL context for the GLAutoDrawable is destroyed and + recreated, for example if a GLCanvas is removed from the widget + hierarchy and later added again. + */ + public void init(GLAutoDrawable drawable); + + /** Called by the drawable to initiate OpenGL rendering by the + client. After all GLEventListeners have been notified of a + display event, the drawable will swap its buffers if {@link + GLAutoDrawable#setAutoSwapBufferMode setAutoSwapBufferMode} is + enabled. */ + public void display(GLAutoDrawable drawable); + + /** Called by the drawable during the first repaint after the + component has been resized. The client can update the viewport + and view volume of the window appropriately, for example by a + call to {@link javax.media.opengl.GL#glViewport}; note that for + convenience the component has already called <code>glViewport(x, + y, width, height)</code> when this method is called, so the + client may not have to do anything in this method. + */ + public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height); + + /** Called by the drawable when the display mode or the display device + associated with the GLAutoDrawable has changed. The two boolean parameters + indicate the types of change(s) that have occurred. (<b> !!! CURRENTLY + UNIMPLEMENTED !!! </b>) + <P> + + An example of a display <i>mode</i> change is when the bit depth changes (e.g., + from 32-bit to 16-bit color) on monitor upon which the GLAutoDrawable is + currently being displayed. <p> + + An example of a display <i>device</i> change is when the user drags the + window containing the GLAutoDrawable from one monitor to another in a + multiple-monitor setup. <p> + + The reason that this function handles both types of changes (instead of + handling mode and device changes in separate methods) is so that + applications have the opportunity to respond to display changes the most + efficient manner. For example, the application may need make fewer + adjustments to compensate for a device change if it knows that the mode + on the new device is identical the previous mode. + */ + public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged); +} diff --git a/src/classes/javax/media/opengl/GLException.java b/src/classes/javax/media/opengl/GLException.java new file mode 100644 index 000000000..644042e15 --- /dev/null +++ b/src/classes/javax/media/opengl/GLException.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +/** A generic exception for OpenGL errors used throughout the binding + as a substitute for {@link RuntimeException}. */ + +public class GLException extends RuntimeException { + /** Constructs a GLException object. */ + public GLException() { + super(); + } + + /** Constructs a GLException object with the specified detail + message. */ + public GLException(String message) { + super(message); + } + + /** Constructs a GLException object with the specified detail + message and root cause. */ + public GLException(String message, Throwable cause) { + super(message, cause); + } + + /** Constructs a GLException object with the specified root + cause. */ + public GLException(Throwable cause) { + super(cause); + } +} diff --git a/src/classes/javax/media/opengl/GLJPanel.java b/src/classes/javax/media/opengl/GLJPanel.java new file mode 100644 index 000000000..3d6f4e831 --- /dev/null +++ b/src/classes/javax/media/opengl/GLJPanel.java @@ -0,0 +1,877 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +import java.awt.*; +import java.awt.geom.*; +import java.awt.image.*; +import javax.swing.*; +import java.nio.*; +import java.security.*; +import javax.swing.JComponent; +import javax.swing.JPanel; +import com.sun.opengl.impl.*; + +// FIXME: Subclasses need to call resetGLFunctionAvailability() on their +// context whenever the displayChanged() function is called on their +// GLEventListeners + +/** A lightweight Swing component which provides OpenGL rendering + support. Provided for compatibility with Swing user interfaces + when adding a heavyweight doesn't work either because of + Z-ordering or LayoutManager problems. This component attempts to + use hardware-accelerated rendering via pbuffers and falls back on + to software rendering if problems occur. This class can not be + instantiated directly; use {@link GLDrawableFactory} to construct + them. <P> + + Note that because this component attempts to use pbuffers for + rendering, and because pbuffers can not be resized, somewhat + surprising behavior may occur during resize operations; the {@link + GLEventListener#init} method may be called multiple times as the + pbuffer is resized to be able to cover the size of the GLJPanel. + This behavior is correct, as the textures and display lists for + the GLJPanel will have been lost during the resize operation. The + application should attempt to make its GLEventListener.init() + methods as side-effect-free as possible. <P> + + The GLJPanel can be made transparent by creating it with a + GLCapabilities object with alpha bits specified and calling {@link + #setOpaque}(false). Pixels with resulting OpenGL alpha values less + than 1.0 will be overlaid on any underlying Java2D rendering. +*/ + +public class GLJPanel extends JPanel implements GLAutoDrawable { + private static final boolean DEBUG = Debug.debug("GLJPanel"); + private static final boolean VERBOSE = Debug.verbose(); + + private GLDrawableHelper drawableHelper = new GLDrawableHelper(); + private volatile boolean isInitialized; + private volatile boolean shouldInitialize = false; + + // Data used for either pbuffers or pixmap-based offscreen surfaces + private GLCapabilities offscreenCaps; + private GLCapabilitiesChooser chooser; + private GLContext shareWith; + // This image is exactly the correct size to render into the panel + private BufferedImage offscreenImage; + // One of these is used to store the read back pixels before storing + // in the BufferedImage + private ByteBuffer readBackBytes; + private IntBuffer readBackInts; + private int readBackWidthInPixels; + private int readBackHeightInPixels; + // Width of the actual GLJPanel + private int panelWidth = 0; + private int panelHeight = 0; + private Updater updater; + private int awtFormat; + private int glFormat; + private int glType; + // Lazy reshape notification + private boolean handleReshape = false; + private boolean sendReshape = true; + + // Implementation using pbuffers + private static boolean hardwareAccelerationDisabled = + Debug.isPropertyDefined("jogl.gljpanel.nohw"); + private static boolean softwareRenderingDisabled = + Debug.isPropertyDefined("jogl.gljpanel.nosw"); + private GLPbuffer pbuffer; + private int pbufferWidth = 256; + private int pbufferHeight = 256; + + // Implementation using software rendering + private GLDrawableImpl offscreenDrawable; + private GLContextImpl offscreenContext; + + // For handling reshape events lazily + private int reshapeX; + private int reshapeY; + private int reshapeWidth; + private int reshapeHeight; + + // For saving/restoring of OpenGL state during ReadPixels + private int[] swapbytes = new int[1]; + private int[] rowlength = new int[1]; + private int[] skiprows = new int[1]; + private int[] skippixels = new int[1]; + private int[] alignment = new int[1]; + + // Implementation using Java2D OpenGL pipeline's back buffer + private static boolean swingBufferPerWindow = + Debug.isPropertyDefined("swing.bufferPerWindow") ? + Debug.getBooleanProperty("swing.bufferPerWindow") : + true; + private boolean oglPipelineEnabled = + Java2D.isOGLPipelineActive() && + !Debug.isPropertyDefined("jogl.gljpanel.noogl"); + // Opaque Object identifier representing the Java2D surface we are + // drawing to; used to determine when to destroy and recreate JOGL + // context + private Object j2dSurface; + // Graphics object being used during Java2D update action + // (absolutely essential to cache this) + private Graphics cached2DGraphics; + // No-op context representing the Java2D OpenGL context + private GLContext j2dContext; + // Context associated with no-op drawable representing the JOGL + // OpenGL context + private GLDrawable joglDrawable; + // The real OpenGL context JOGL uses to render + private GLContext joglContext; + // State captured from Java2D OpenGL context necessary in order to + // properly render into Java2D back buffer + private int[] drawBuffer = new int[1]; + private int[] readBuffer = new int[1]; + // These are always set to (0, 0) except when the Java2D / OpenGL + // pipeline is active + private int viewportX; + private int viewportY; + + /** Creates a new GLJPanel component. The passed GLCapabilities must + be non-null and specifies the OpenGL capabilities for the + component. The GLCapabilitiesChooser must be non-null and + specifies the algorithm for selecting one of the available + GLCapabilities for the component; the GLDrawableFactory uses a + DefaultGLCapabilitiesChooser if the user does not provide + one. The passed GLContext may be null and specifies an OpenGL + context with which to share textures, display lists and other + OpenGL state. */ + protected GLJPanel(GLCapabilities capabilities, GLCapabilitiesChooser chooser, GLContext shareWith) { + super(); + + // Works around problems on many vendors' cards; we don't need a + // back buffer for the offscreen surface anyway + if (capabilities != null) { + offscreenCaps = (GLCapabilities) capabilities.clone(); + } else { + offscreenCaps = new GLCapabilities(); + } + offscreenCaps.setDoubleBuffered(false); + this.chooser = ((chooser != null) ? chooser : new DefaultGLCapabilitiesChooser()); + this.shareWith = shareWith; + } + + public void display() { + if (EventQueue.isDispatchThread()) { + // Want display() to be synchronous, so call paintImmediately() + paintImmediately(0, 0, getWidth(), getHeight()); + } else { + // Multithreaded redrawing of Swing components is not allowed, + // so do everything on the event dispatch thread + try { + EventQueue.invokeAndWait(paintImmediatelyAction); + } catch (Exception e) { + throw new GLException(e); + } + } + } + + private void captureJ2DState(GL gl) { + gl.glGetIntegerv(GL.GL_DRAW_BUFFER, drawBuffer, 0); + gl.glGetIntegerv(GL.GL_READ_BUFFER, readBuffer, 0); + } + + private boolean preGL(Graphics g) { + GL gl = joglContext.getGL(); + // Set up needed state in JOGL context from Java2D context + gl.glEnable(GL.GL_SCISSOR_TEST); + Rectangle r = Java2D.getOGLScissorBox(g); + if (r == null) { + return false; + } + gl.glScissor(r.x, r.y, r.width, r.height); + Rectangle oglViewport = Java2D.getOGLViewport(g, panelWidth, panelHeight); + // If the viewport X or Y changes, in addition to the panel's + // width or height, we need to send a reshape operation to the + // client + if ((viewportX != oglViewport.x) || + (viewportY != oglViewport.y)) { + sendReshape = true; + if (DEBUG) { + System.err.println("Sending reshape because viewport changed"); + System.err.println(" viewportX (" + viewportX + ") ?= oglViewport.x (" + oglViewport.x + ")"); + System.err.println(" viewportY (" + viewportY + ") ?= oglViewport.y (" + oglViewport.y + ")"); + } + } + viewportX = oglViewport.x; + viewportY = oglViewport.y; + + gl.glDrawBuffer(drawBuffer[0]); + gl.glReadBuffer(readBuffer[0]); + return true; + } + + /** Overridden from JComponent; calls event listeners' {@link + GLEventListener#display display} methods. Should not be invoked + by applications directly. */ + public void paintComponent(final Graphics g) { + if (shouldInitialize) { + initialize(); + } + + if (!isInitialized) { + return; + } + + // NOTE: must do this when the context is not current as it may + // involve destroying the pbuffer (current context) and + // re-creating it -- tricky to do properly while the context is + // current + if (handleReshape) { + handleReshape(); + } + + updater.setGraphics(g); + + if (oglPipelineEnabled) { + Java2D.invokeWithOGLContextCurrent(g, new Runnable() { + public void run() { + // Create no-op context representing Java2D context + if (j2dContext == null) { + j2dContext = GLDrawableFactory.getFactory().createExternalGLContext(); + + // Check to see whether we can support the requested + // capabilities or need to fall back to a pbuffer + // FIXME: add more checks? + + GL gl = j2dContext.getGL(); + if ((getGLInteger(gl, GL.GL_RED_BITS) < offscreenCaps.getRedBits()) || + (getGLInteger(gl, GL.GL_GREEN_BITS) < offscreenCaps.getGreenBits()) || + (getGLInteger(gl, GL.GL_BLUE_BITS) < offscreenCaps.getBlueBits()) || + // (getGLInteger(gl, GL.GL_ALPHA_BITS) < offscreenCaps.getAlphaBits()) || + (getGLInteger(gl, GL.GL_ACCUM_RED_BITS) < offscreenCaps.getAccumRedBits()) || + (getGLInteger(gl, GL.GL_ACCUM_GREEN_BITS) < offscreenCaps.getAccumGreenBits()) || + (getGLInteger(gl, GL.GL_ACCUM_BLUE_BITS) < offscreenCaps.getAccumBlueBits()) || + (getGLInteger(gl, GL.GL_ACCUM_ALPHA_BITS) < offscreenCaps.getAccumAlphaBits()) || + // (getGLInteger(gl, GL.GL_DEPTH_BITS) < offscreenCaps.getDepthBits()) || + (getGLInteger(gl, GL.GL_STENCIL_BITS) < offscreenCaps.getStencilBits())) { + if (DEBUG) { + System.err.println("GLJPanel: Falling back to pbuffer-based support because Java2D context insufficient"); + System.err.println(" Available Required"); + System.err.println("GL_RED_BITS " + getGLInteger(gl, GL.GL_RED_BITS) + " " + offscreenCaps.getRedBits()); + System.err.println("GL_GREEN_BITS " + getGLInteger(gl, GL.GL_GREEN_BITS) + " " + offscreenCaps.getGreenBits()); + System.err.println("GL_BLUE_BITS " + getGLInteger(gl, GL.GL_BLUE_BITS) + " " + offscreenCaps.getBlueBits()); + System.err.println("GL_ALPHA_BITS " + getGLInteger(gl, GL.GL_ALPHA_BITS) + " " + offscreenCaps.getAlphaBits()); + System.err.println("GL_ACCUM_RED_BITS " + getGLInteger(gl, GL.GL_ACCUM_RED_BITS) + " " + offscreenCaps.getAccumRedBits()); + System.err.println("GL_ACCUM_GREEN_BITS " + getGLInteger(gl, GL.GL_ACCUM_GREEN_BITS) + " " + offscreenCaps.getAccumGreenBits()); + System.err.println("GL_ACCUM_BLUE_BITS " + getGLInteger(gl, GL.GL_ACCUM_BLUE_BITS) + " " + offscreenCaps.getAccumBlueBits()); + System.err.println("GL_ACCUM_ALPHA_BITS " + getGLInteger(gl, GL.GL_ACCUM_ALPHA_BITS) + " " + offscreenCaps.getAccumAlphaBits()); + System.err.println("GL_DEPTH_BITS " + getGLInteger(gl, GL.GL_DEPTH_BITS) + " " + offscreenCaps.getDepthBits()); + System.err.println("GL_STENCIL_BITS " + getGLInteger(gl, GL.GL_STENCIL_BITS) + " " + offscreenCaps.getStencilBits()); + } + isInitialized = false; + shouldInitialize = true; + oglPipelineEnabled = false; + handleReshape = true; + j2dContext.destroy(); + j2dContext = null; + return; + } + } + + j2dContext.makeCurrent(); + try { + captureJ2DState(j2dContext.getGL()); + Object curSurface = Java2D.getOGLSurfaceIdentifier(g); + if (curSurface != null) { + if (j2dSurface != curSurface) { + if (joglContext != null) { + joglContext.destroy(); + joglContext = null; + joglDrawable = null; + sendReshape = true; + if (DEBUG) { + System.err.println("Sending reshape because surface changed"); + System.err.println("New surface = " + curSurface); + } + } + j2dSurface = curSurface; + } + if (joglContext == null) { + joglDrawable = GLDrawableFactory.getFactory().createExternalGLDrawable(); + joglContext = joglDrawable.createContext(shareWith); + } + drawableHelper.invokeGL(joglDrawable, joglContext, displayAction, initAction); + } + } finally { + j2dContext.release(); + } + } + }); + } else { + if (!hardwareAccelerationDisabled) { + pbuffer.display(); + } else { + drawableHelper.invokeGL(offscreenDrawable, offscreenContext, displayAction, initAction); + } + } + } + + /** Overridden from JPanel; used to indicate that an OpenGL context + may be created for the component. */ + public void addNotify() { + super.addNotify(); + shouldInitialize = true; + if (DEBUG) { + System.err.println("GLJPanel.addNotify()"); + } + } + + /** Overridden from JPanel; used to indicate that it's no longer + safe to have an OpenGL context for the component. */ + public void removeNotify() { + if (DEBUG) { + System.err.println("GLJPanel.removeNotify()"); + } + if (oglPipelineEnabled) { + Java2D.invokeWithOGLContextCurrent(null, new Runnable() { + public void run() { + if (joglContext != null) { + joglContext.destroy(); + joglContext = null; + } + joglDrawable = null; + if (j2dContext != null) { + j2dContext.destroy(); + j2dContext = null; + } + } + }); + } else { + if (!hardwareAccelerationDisabled) { + if (pbuffer != null) { + pbuffer.destroy(); + pbuffer = null; + } + } else { + if (offscreenContext != null) { + offscreenContext.destroy(); + offscreenContext = null; + } + if (offscreenDrawable != null) { + offscreenDrawable.destroy(); + offscreenDrawable = null; + } + } + } + isInitialized = false; + super.removeNotify(); + } + + /** Overridden from Canvas; causes {@link GLEventListener#reshape + reshape} to be called on all registered {@link + GLEventListener}s. Called automatically by the AWT; should not + be invoked by applications directly. */ + public void reshape(int x, int y, int width, int height) { + super.reshape(x, y, width, height); + + reshapeX = x; + reshapeY = y; + reshapeWidth = width; + reshapeHeight = height; + handleReshape = true; + } + + public void setOpaque(boolean opaque) { + if (opaque != isOpaque()) { + if (offscreenImage != null) { + offscreenImage.flush(); + offscreenImage = null; + } + } + super.setOpaque(opaque); + } + + public void addGLEventListener(GLEventListener listener) { + drawableHelper.addGLEventListener(listener); + } + + public void removeGLEventListener(GLEventListener listener) { + drawableHelper.removeGLEventListener(listener); + } + + public GLContext createContext(GLContext shareWith) { + if (!hardwareAccelerationDisabled) { + return pbuffer.createContext(shareWith); + } else { + return offscreenDrawable.createContext(shareWith); + } + } + + public void setRealized(boolean realized) { + } + + public GLContext getContext() { + if (oglPipelineEnabled) { + return joglContext; + } else { + if (!hardwareAccelerationDisabled) { + return pbuffer.getContext(); + } else { + return offscreenContext; + } + } + } + + public GL getGL() { + GLContext context = getContext(); + return (context == null) ? null : context.getGL(); + } + + public void setGL(GL gl) { + GLContext context = getContext(); + if (context != null) { + context.setGL(gl); + } + } + + public void setAutoSwapBufferMode(boolean onOrOff) { + if (!hardwareAccelerationDisabled) { + pbuffer.setAutoSwapBufferMode(onOrOff); + } else { + drawableHelper.setAutoSwapBufferMode(onOrOff); + } + } + + public boolean getAutoSwapBufferMode() { + if (!hardwareAccelerationDisabled) { + return pbuffer.getAutoSwapBufferMode(); + } else { + return drawableHelper.getAutoSwapBufferMode(); + } + } + + public void swapBuffers() { + if (!hardwareAccelerationDisabled) { + pbuffer.swapBuffers(); + } else { + drawableHelper.invokeGL(offscreenDrawable, offscreenContext, swapBuffersAction, initAction); + } + } + + /** For a translucent GLJPanel (one for which {@link #setOpaque + setOpaque}(false) has been called), indicates whether the + application should preserve the OpenGL color buffer + (GL_COLOR_BUFFER_BIT) for correct rendering of the GLJPanel and + underlying widgets which may show through portions of the + GLJPanel with alpha values less than 1. Most Swing + implementations currently expect the GLJPanel to be completely + cleared (e.g., by <code>glClear(GL_COLOR_BUFFER_BIT | + GL_DEPTH_BUFFER_BIT)</code>), but for certain optimized Java2D + and Swing implementations which use OpenGL internally, it may be + possible to perform OpenGL rendering using the GLJPanel into the + same OpenGL drawable as the Java2D implementation. */ + public boolean shouldPreserveColorBufferIfTranslucent() { + return oglPipelineEnabled; + } + + //---------------------------------------------------------------------- + // Internals only below this point + // + + private void initialize() { + if (panelWidth == 0 || + panelHeight == 0) { + // See whether we have a non-zero size yet and can go ahead with + // initialization + if (reshapeWidth == 0 || + reshapeHeight == 0) { + return; + } + + // Pull down reshapeWidth and reshapeHeight into panelWidth and + // panelHeight eagerly in order to complete initialization, and + // force a reshape later + panelWidth = reshapeWidth; + panelHeight = reshapeHeight; + } + + if (!oglPipelineEnabled) { + // Initialize either the hardware-accelerated rendering path or + // the lightweight rendering path + if (!hardwareAccelerationDisabled) { + if (GLDrawableFactory.getFactory().canCreateGLPbuffer()) { + if (pbuffer != null) { + throw new InternalError("Creating pbuffer twice without destroying it (memory leak / correctness bug)"); + } + try { + pbuffer = GLDrawableFactory.getFactory().createGLPbuffer(offscreenCaps, + pbufferWidth, + pbufferHeight, + shareWith); + updater = new Updater(); + pbuffer.addGLEventListener(updater); + shouldInitialize = false; + isInitialized = true; + return; + } catch (GLException e) { + if (DEBUG) { + e.printStackTrace(); + System.err.println("GLJPanel: Falling back on software rendering because of problems creating pbuffer"); + } + hardwareAccelerationDisabled = true; + } + } else { + if (DEBUG) { + System.err.println("GLJPanel: Falling back on software rendering because no pbuffer support"); + } + + // If the factory reports that it can't create a pbuffer, + // don't try again the next time, and fall through to the + // software rendering path + hardwareAccelerationDisabled = true; + } + } + + if (softwareRenderingDisabled) { + throw new GLException("Fallback to software rendering disabled by user"); + } + + // Fall-through path: create an offscreen context instead + offscreenDrawable = GLDrawableFactoryImpl.getFactoryImpl().createOffscreenDrawable(offscreenCaps, chooser); + offscreenDrawable.setSize(Math.max(1, panelWidth), Math.max(1, panelHeight)); + offscreenContext = (GLContextImpl) offscreenDrawable.createContext(shareWith); + offscreenContext.setSynchronized(true); + } + updater = new Updater(); + shouldInitialize = false; + isInitialized = true; + } + + private void handleReshape() { + readBackWidthInPixels = 0; + readBackHeightInPixels = 0; + + panelWidth = reshapeWidth; + panelHeight = reshapeHeight; + + if (DEBUG) { + System.err.println("GLJPanel.handleReshape: (w,h) = (" + + panelWidth + "," + panelHeight + ")"); + } + + sendReshape = true; + + if (!oglPipelineEnabled) { + if (!hardwareAccelerationDisabled) { + // Use factor larger than 2 during shrinks for some hysteresis + float shrinkFactor = 2.5f; + if ((panelWidth > pbufferWidth ) || (panelHeight > pbufferHeight) || + (panelWidth < (pbufferWidth / shrinkFactor)) || (panelHeight < (pbufferWidth / shrinkFactor))) { + if (DEBUG) { + System.err.println("Resizing pbuffer from (" + pbufferWidth + ", " + pbufferHeight + ") " + + " to fit (" + panelWidth + ", " + panelHeight + ")"); + } + // Must destroy and recreate pbuffer to fit + if (pbuffer != null) { + pbuffer.destroy(); + } + pbuffer = null; + isInitialized = false; + pbufferWidth = getNextPowerOf2(panelWidth); + pbufferHeight = getNextPowerOf2(panelHeight); + if (DEBUG) { + System.err.println("New pbuffer size is (" + pbufferWidth + ", " + pbufferHeight + ")"); + } + initialize(); + } + + // It looks like NVidia's drivers (at least the ones on my + // notebook) are buggy and don't allow a rectangle of less than + // the pbuffer's width to be read...this doesn't really matter + // because it's the Graphics.drawImage() calls that are the + // bottleneck. Should probably make the size of the offscreen + // image be the exact size of the pbuffer to save some work on + // resize operations... + readBackWidthInPixels = pbufferWidth; + readBackHeightInPixels = panelHeight; + } else { + offscreenContext.destroy(); + offscreenDrawable.setSize(Math.max(1, panelWidth), Math.max(1, panelHeight)); + readBackWidthInPixels = Math.max(1, panelWidth); + readBackHeightInPixels = Math.max(1, panelHeight); + } + + if (offscreenImage != null) { + offscreenImage.flush(); + offscreenImage = null; + } + } + + handleReshape = false; + } + + // FIXME: it isn't clear whether this works any more given that + // we're accessing the GLDrawable inside of the GLPbuffer directly + // up in reshape() -- need to rethink and clean this up + class Updater implements GLEventListener { + private Graphics g; + + public void setGraphics(Graphics g) { + this.g = g; + } + + public void init(GLAutoDrawable drawable) { + if (oglPipelineEnabled) { + if (!preGL(g)) { + return; + } + } + drawableHelper.init(GLJPanel.this); + } + + public void display(GLAutoDrawable drawable) { + if (oglPipelineEnabled) { + if (!preGL(g)) { + return; + } + } + + if (sendReshape) { + if (DEBUG) { + System.err.println("glViewport(" + viewportX + ", " + viewportY + ", " + panelWidth + ", " + panelHeight + ")"); + } + getGL().glViewport(viewportX, viewportY, panelWidth, panelHeight); + drawableHelper.reshape(GLJPanel.this, viewportX, viewportY, panelWidth, panelHeight); + sendReshape = false; + } + + drawableHelper.display(GLJPanel.this); + + if (!oglPipelineEnabled) { + // Must now copy pixels from offscreen context into surface + if (offscreenImage == null) { + if (panelWidth > 0 && panelHeight > 0) { + // It looks like NVidia's drivers (at least the ones on my + // notebook) are buggy and don't allow a sub-rectangle to be + // read from a pbuffer...this doesn't really matter because + // it's the Graphics.drawImage() calls that are the + // bottleneck + + int awtFormat = 0; + int hwGLFormat = 0; + if (!hardwareAccelerationDisabled) { + // This seems to be a good choice on all platforms + hwGLFormat = GL.GL_UNSIGNED_INT_8_8_8_8_REV; + } + + // Should be more flexible in these BufferedImage formats; + // perhaps see what the preferred image types are on the + // given platform + if (isOpaque()) { + awtFormat = BufferedImage.TYPE_INT_RGB; + } else { + awtFormat = BufferedImage.TYPE_INT_ARGB; + } + + offscreenImage = new BufferedImage(panelWidth, + panelHeight, + awtFormat); + switch (awtFormat) { + case BufferedImage.TYPE_3BYTE_BGR: + glFormat = GL.GL_BGR; + glType = GL.GL_UNSIGNED_BYTE; + readBackBytes = ByteBuffer.allocate(readBackWidthInPixels * readBackHeightInPixels * 3); + break; + + case BufferedImage.TYPE_INT_RGB: + case BufferedImage.TYPE_INT_ARGB: + glFormat = GL.GL_BGRA; + glType = (hardwareAccelerationDisabled + ? offscreenContext.getOffscreenContextPixelDataType() + : hwGLFormat); + readBackInts = IntBuffer.allocate(readBackWidthInPixels * readBackHeightInPixels); + break; + + default: + // FIXME: Support more off-screen image types (current + // offscreen context implementations don't use others, and + // some of the OpenGL formats aren't supported in the 1.1 + // headers, which we're currently using) + throw new GLException("Unsupported offscreen image type " + awtFormat); + } + } + } + + if (offscreenImage != null) { + GL gl = getGL(); + // Save current modes + gl.glGetIntegerv(GL.GL_PACK_SWAP_BYTES, swapbytes, 0); + gl.glGetIntegerv(GL.GL_PACK_ROW_LENGTH, rowlength, 0); + gl.glGetIntegerv(GL.GL_PACK_SKIP_ROWS, skiprows, 0); + gl.glGetIntegerv(GL.GL_PACK_SKIP_PIXELS, skippixels, 0); + gl.glGetIntegerv(GL.GL_PACK_ALIGNMENT, alignment, 0); + + gl.glPixelStorei(GL.GL_PACK_SWAP_BYTES, GL.GL_FALSE); + gl.glPixelStorei(GL.GL_PACK_ROW_LENGTH, readBackWidthInPixels); + gl.glPixelStorei(GL.GL_PACK_SKIP_ROWS, 0); + gl.glPixelStorei(GL.GL_PACK_SKIP_PIXELS, 0); + gl.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1); + + // Actually read the pixels. + gl.glReadBuffer(GL.GL_FRONT); + if (readBackBytes != null) { + gl.glReadPixels(0, 0, readBackWidthInPixels, readBackHeightInPixels, glFormat, glType, readBackBytes); + } else if (readBackInts != null) { + gl.glReadPixels(0, 0, readBackWidthInPixels, readBackHeightInPixels, glFormat, glType, readBackInts); + } + + // Restore saved modes. + gl.glPixelStorei(GL.GL_PACK_SWAP_BYTES, swapbytes[0]); + gl.glPixelStorei(GL.GL_PACK_ROW_LENGTH, rowlength[0]); + gl.glPixelStorei(GL.GL_PACK_SKIP_ROWS, skiprows[0]); + gl.glPixelStorei(GL.GL_PACK_SKIP_PIXELS, skippixels[0]); + gl.glPixelStorei(GL.GL_PACK_ALIGNMENT, alignment[0]); + + if (readBackBytes != null || readBackInts != null) { + // Copy temporary data into raster of BufferedImage for faster + // blitting Note that we could avoid this copy in the cases + // where !offscreenContext.offscreenImageNeedsVerticalFlip(), + // but that's the software rendering path which is very slow + // anyway + Object src = null; + Object dest = null; + int srcIncr = 0; + int destIncr = 0; + + if (readBackBytes != null) { + src = readBackBytes.array(); + dest = ((DataBufferByte) offscreenImage.getRaster().getDataBuffer()).getData(); + srcIncr = readBackWidthInPixels * 3; + destIncr = offscreenImage.getWidth() * 3; + } else { + src = readBackInts.array(); + dest = ((DataBufferInt) offscreenImage.getRaster().getDataBuffer()).getData(); + srcIncr = readBackWidthInPixels; + destIncr = offscreenImage.getWidth(); + } + + if (!hardwareAccelerationDisabled || + offscreenContext.offscreenImageNeedsVerticalFlip()) { + int srcPos = 0; + int destPos = (offscreenImage.getHeight() - 1) * destIncr; + for (; destPos >= 0; srcPos += srcIncr, destPos -= destIncr) { + System.arraycopy(src, srcPos, dest, destPos, destIncr); + } + } else { + int srcPos = 0; + int destEnd = destIncr * offscreenImage.getHeight(); + for (int destPos = 0; destPos < destEnd; srcPos += srcIncr, destPos += destIncr) { + System.arraycopy(src, srcPos, dest, destPos, destIncr); + } + } + + // Draw resulting image in one shot + g.drawImage(offscreenImage, 0, 0, offscreenImage.getWidth(), offscreenImage.getHeight(), GLJPanel.this); + } + } + } else { + // Cause OpenGL pipeline to flush its results because + // otherwise it's possible we will buffer up multiple frames' + // rendering results, resulting in apparent mouse lag + GL gl = getGL(); + gl.glFinish(); + } + } + + public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { + // This is handled above and dispatched directly to the appropriate context + } + + public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { + } + } + + class InitAction implements Runnable { + public void run() { + updater.init(GLJPanel.this); + } + } + private InitAction initAction = new InitAction(); + + class DisplayAction implements Runnable { + public void run() { + updater.display(GLJPanel.this); + } + } + private DisplayAction displayAction = new DisplayAction(); + + // This one is used exclusively in the non-hardware-accelerated case + class SwapBuffersAction implements Runnable { + public void run() { + offscreenDrawable.swapBuffers(); + } + } + private SwapBuffersAction swapBuffersAction = new SwapBuffersAction(); + + class PaintImmediatelyAction implements Runnable { + public void run() { + paintImmediately(0, 0, getWidth(), getHeight()); + } + } + private PaintImmediatelyAction paintImmediatelyAction = new PaintImmediatelyAction(); + + private int getNextPowerOf2(int number) { + // Workaround for problems where 0 width or height are transiently + // seen during layout + if (number == 0) { + return 2; + } + + if (((number-1) & number) == 0) { + //ex: 8 -> 0b1000; 8-1=7 -> 0b0111; 0b1000&0b0111 == 0 + return number; + } + int power = 0; + while (number > 0) { + number = number>>1; + power++; + } + return (1<<power); + } + + private int getGLInteger(GL gl, int which) { + int[] tmp = new int[1]; + gl.glGetIntegerv(which, tmp, 0); + return tmp[0]; + } +} diff --git a/src/classes/javax/media/opengl/GLPbuffer.java b/src/classes/javax/media/opengl/GLPbuffer.java new file mode 100644 index 000000000..607c5c9fa --- /dev/null +++ b/src/classes/javax/media/opengl/GLPbuffer.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +/** Provides offscreen rendering support via pbuffers. The principal + addition of this interface is a {@link #destroy} method to + deallocate the pbuffer and its associated resources. It also + contains experimental methods for accessing the pbuffer's contents + as a texture map and enabling rendering to floating-point frame + buffers. These methods are not guaranteed to be supported on all + platforms and may change or be removed in a future release. */ + +public interface GLPbuffer extends GLAutoDrawable { + /** Indicates the GL_APPLE_float_pixels extension is being used for this pbuffer. */ + public static final int APPLE_FLOAT = 1; + + /** Indicates the GL_ATI_texture_float extension is being used for this pbuffer. */ + public static final int ATI_FLOAT = 2; + + /** Indicates the GL_NV_float_buffer extension is being used for this pbuffer. */ + public static final int NV_FLOAT = 3; + + /** Binds this pbuffer to its internal texture target. Only valid to + call if offscreen render-to-texture has been specified in the + GLCapabilities for this GLPbuffer. If the + render-to-texture-rectangle capability has also been specified, + this will use e.g. wglBindTexImageARB as its implementation and + cause the texture to be bound to e.g. the + GL_TEXTURE_RECTANGLE_NV state; otherwise, during the display() + phase the pixels will have been copied into an internal texture + target and this will cause that to be bound to the GL_TEXTURE_2D + state. */ + public void bindTexture(); + + /** Unbinds the pbuffer from its internal texture target. */ + public void releaseTexture(); + + /** Destroys the native resources associated with this pbuffer. It + is not valid to call display() or any other routines on this + pbuffer after it has been destroyed. Before destroying the + pbuffer, the application must destroy any additional OpenGL + contexts which have been created for the pbuffer via {@link + #createContext}. */ + public void destroy(); + + /** Indicates which vendor's extension is being used to support + floating point channels in this pbuffer if that capability was + requested in the GLCapabilities during pbuffer creation. Returns + one of NV_FLOAT, ATI_FLOAT or APPLE_FLOAT, or throws GLException + if floating-point channels were not requested for this pbuffer. + This function may only be called once the init method for this + pbuffer's GLEventListener has been called. */ + public int getFloatingPointMode(); +} diff --git a/src/classes/javax/media/opengl/Threading.java b/src/classes/javax/media/opengl/Threading.java new file mode 100755 index 000000000..28dc00b9c --- /dev/null +++ b/src/classes/javax/media/opengl/Threading.java @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package javax.media.opengl; + +import java.awt.EventQueue; +import java.lang.reflect.InvocationTargetException; +import java.security.AccessController; +import java.security.PrivilegedAction; + +import com.sun.opengl.impl.*; + +/** Defines the threading model for the implementation of the classes + in this package. + + <P> + + OpenGL is specified as a thread-safe API, but in practice there + are multithreading-related issues on most, if not all, of the + platforms which support it. For example, some OpenGL + implementations do not behave well when one context is made + current first on one thread, released, and then made current on a + second thread, although this is legal according to the OpenGL + specification. On other platforms there are other problems. + + <P> + + Due to these limitations, and due to the inherent multithreading + in the Java platform (in particular, in the Abstract Window + Toolkit), it is necessary to limit the multithreading occurring in + the typical application using the JOGL API. This has been done by + forcing all OpenGL-related work for GLAutoDrawables on to a single + thread. In other words, if an application uses only the + GLAutoDrawable and GLEventListener callback mechanism, it is + guaranteed to have the most correct single-threaded behavior on + all platforms. + + <P> + + Applications using the GLContext makeCurrent/release API directly + will inherently break this single-threaded model, as these methods + require that the OpenGL context be made current on the current + thread immediately. For applications wishing to integrate better + with the single-threaded model, this class provides public access + to the mechanism used by the JOGL implementation. Users can + execute Runnables on the internal thread used for performing + OpenGL work, and query whether the current thread is already this + thread. Using these mechanisms the user can move work from the + current thread on to the internal OpenGL thread if desired. + + <P> + + This class also provides mechanisms for querying whether this + internal serialization of OpenGL work is in effect, and a + programmatic way of disabling it. Currently it is enabled by + default, although it could be disabled in the future if OpenGL + drivers become more robust on all platforms. + + <P> + + In addition to specifying programmatically whether the single + thread for OpenGL work is enabled, users may switch it on and off + using the system property <code>jogl.1thread</code>. Valid values + for this system property are: + + <PRE> + -Djogl.1thread=false Disable single-threading of OpenGL work + -Djogl.1thread=true Enable single-threading of OpenGL work (default) + -Djogl.1thread=auto Select default single-threading behavior (currently on) + </PRE> +*/ + +public class Threading { + private static boolean singleThreaded = true; + + static { + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + String workaround = System.getProperty("jogl.1thread"); + if (workaround != null && (!workaround.equals("auto"))) { + singleThreaded = Boolean.valueOf(workaround).booleanValue(); + } + printWorkaroundNotice(); + return null; + } + }); + } + + /** No reason to ever instantiate this class */ + private Threading() {} + + /** Provides a mechanism for end users to disable the default + single-threading of the JOGL implementation. Users are strongly + discouraged from calling this method unless they are aware of + all of the consequences and are prepared to enforce some amount + of threading restrictions in their applications. Disabling this + single-threading, for example, will have unintended consequences + on GLAutoDrawable implementations such as GLCanvas, GLJPanel and + GLPbuffer. Currently there is no supported way to re-enable it + once disabled, partly to discourage careless use of this + method. */ + public static void disableSingleThreading() { + singleThreaded = false; + if (Debug.verbose()) { + System.err.println("Application forced disabling of single-threading of JOGL implementation"); + } + } + + /** Indicates whether OpenGL work is being automatically forced to a + single thread by the JOGL implementation. */ + public static boolean isSingleThreaded() { + return singleThreaded; + } + + /** Indicates whether the current thread is the single thread on + which the JOGL implementation performs all of its OpenGL-related + work. This method should only be called if the single-thread + model is in effect. */ + public static boolean isOpenGLThread() throws GLException { + if (!isSingleThreaded()) { + throw new GLException("Should only call this in single-threaded mode"); + } + + if (Java2D.isOGLPipelineActive()) { + // FIXME: ideally only the QFT would be considered to be the + // "OpenGL thread", but we can not currently run all of JOGL's + // OpenGL work on that thread. For now, run the GLJPanel's + // Java2D/JOGL bridge on the QFT but everything else on the + // EDT, except when we're already on the QFT. + return (Java2D.isQueueFlusherThread() || + EventQueue.isDispatchThread()); + } else { + return EventQueue.isDispatchThread(); + } + } + + /** Executes the passed Runnable on the single thread used for all + OpenGL work in the JOGL implementation. It is not specified + exactly which thread is used for this purpose. This method + should only be called if the single-thread model is in use and + if the current thread is not the OpenGL thread (i.e., if + <code>isOpenGLThread()</code> returns false). It is up to the + end user to check to see whether the current thread is the + OpenGL thread and either execute the Runnable directly or + perform the work inside it. */ + public static void invokeOnOpenGLThread(Runnable r) throws GLException { + if (!isSingleThreaded()) { + throw new GLException ("Should only call this in single-threaded mode"); + } + + if (isOpenGLThread()) { + throw new GLException ("Should only call this from other threads than the OpenGL thread"); + } + + // FIXME: ideally should run all OpenGL work on the Java2D QFT + // thread when it's enabled, but there are issues with this when + // the GLJPanel is not using the Java2D bridge; would like to run + // its OpenGL work on the QFT, but do the image drawing from the + // EDT. Other issues still remain with the GLCanvas as well. + + // if (Java2D.isOGLPipelineActive()) { + // Java2D.invokeWithOGLContextCurrent(null, r); + // } else { + try { + EventQueue.invokeAndWait(r); + } catch (InvocationTargetException e) { + throw new GLException(e.getTargetException()); + } catch (InterruptedException e) { + throw new GLException(e); + } + // } + } + + private static void printWorkaroundNotice() { + if (singleThreaded && Debug.verbose()) { + System.err.println("Using single thread for performing OpenGL work in JOGL implementation"); + } + } +} diff --git a/src/classes/javax/media/opengl/glu/GLUquadric.java b/src/classes/javax/media/opengl/glu/GLUquadric.java new file mode 100755 index 000000000..bcb21fb90 --- /dev/null +++ b/src/classes/javax/media/opengl/glu/GLUquadric.java @@ -0,0 +1,8 @@ +package javax.media.opengl.glu; + +/** + * Wrapper for a GLU quadric object. + */ + +public interface GLUquadric { +} diff --git a/src/classes/javax/media/opengl/glu/GLUtessellator.java b/src/classes/javax/media/opengl/glu/GLUtessellator.java new file mode 100755 index 000000000..df42a8a82 --- /dev/null +++ b/src/classes/javax/media/opengl/glu/GLUtessellator.java @@ -0,0 +1,56 @@ +/* +* Portions Copyright (C) 2003 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package javax.media.opengl.glu; + +/** + * The <b>GLUtessellator</b> object is used to hold the data, such as the + * vertices, edges and callback objects, to describe and tessellate complex + * polygons. A <b>GLUtessellator</b> object is used with the + * {@link GLU GLU} tessellator methods and + * {@link GLUtessellatorCallback GLU callbacks}. + * + * @author Eric Veach, July 1994 + * @author Java Port: Pepijn Van Eechhoudt, July 2003 + * @author Java Port: Nathan Parker Burg, August 2003 + */ +public interface GLUtessellator {} diff --git a/src/classes/javax/media/opengl/glu/GLUtessellatorCallback.java b/src/classes/javax/media/opengl/glu/GLUtessellatorCallback.java new file mode 100755 index 000000000..9d4946b00 --- /dev/null +++ b/src/classes/javax/media/opengl/glu/GLUtessellatorCallback.java @@ -0,0 +1,346 @@ +/* +* Portions Copyright (C) 2003 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package javax.media.opengl.glu; + +/** + * <b>GLUtessellatorCallback</b> interface provides methods that the user will + * override to define the callbacks for a tessellation object. + * + * @author Eric Veach, July 1994 + * @author Java Port: Pepijn Van Eeckhoudt, July 2003 + * @author Java Port: Nathan Parker Burg, August 2003 + */ +public interface GLUtessellatorCallback { + /** + * The <b>begin</b> callback method is invoked like + * {@link javax.media.opengl.GL#glBegin glBegin} to indicate the start of a + * (triangle) primitive. The method takes a single argument of type int. If + * the <b>GLU_TESS_BOUNDARY_ONLY</b> property is set to <b>GL_FALSE</b>, then + * the argument is set to either <b>GL_TRIANGLE_FAN</b>, + * <b>GL_TRIANGLE_STRIP</b>, or <b>GL_TRIANGLES</b>. If the + * <b>GLU_TESS_BOUNDARY_ONLY</b> property is set to <b>GL_TRUE</b>, then the + * argument will be set to <b>GL_LINE_LOOP</b>. + * + * @param type + * Specifics the type of begin/end pair being defined. The following + * values are valid: <b>GL_TRIANGLE_FAN</b>, <b>GL_TRIANGLE_STRIP</b>, + * <b>GL_TRIANGLES</b> or <b>GL_LINE_LOOP</b>. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #end end + * @see #begin begin + */ + public void begin(int type); + + /** + * The same as the {@link #begin begin} callback method except that + * it takes an additional reference argument. This reference is + * identical to the opaque reference provided when {@link + * GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param type + * Specifics the type of begin/end pair being defined. The following + * values are valid: <b>GL_TRIANGLE_FAN</b>, <b>GL_TRIANGLE_STRIP</b>, + * <b>GL_TRIANGLES</b> or <b>GL_LINE_LOOP</b>. + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #endData endData + * @see #begin begin + */ + public void beginData(int type, Object polygonData); + + + /** + * The <b>edgeFlag</b> callback method is similar to + * {@link javax.media.opengl.GL#glEdgeFlag glEdgeFlag}. The method takes + * a single boolean boundaryEdge that indicates which edges lie on the + * polygon boundary. If the boundaryEdge is <b>GL_TRUE</b>, then each vertex + * that follows begins an edge that lies on the polygon boundary, that is, + * an edge that separates an interior region from an exterior one. If the + * boundaryEdge is <b>GL_FALSE</b>, then each vertex that follows begins an + * edge that lies in the polygon interior. The edge flag callback (if + * defined) is invoked before the first vertex callback.<P> + * + * Since triangle fans and triangle strips do not support edge flags, the + * begin callback is not called with <b>GL_TRIANGLE_FAN</b> or + * <b>GL_TRIANGLE_STRIP</b> if a non-null edge flag callback is provided. + * (If the callback is initialized to null, there is no impact on + * performance). Instead, the fans and strips are converted to independent + * triangles. + * + * @param boundaryEdge + * Specifics which edges lie on the polygon boundary. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #edgeFlagData edgeFlagData + */ + public void edgeFlag(boolean boundaryEdge); + + + /** + * The same as the {@link #edgeFlag edgeFlage} callback method + * except that it takes an additional reference argument. This + * reference is identical to the opaque reference provided when + * {@link GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param boundaryEdge + * Specifics which edges lie on the polygon boundary. + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #edgeFlag edgeFlag + */ + public void edgeFlagData(boolean boundaryEdge, Object polygonData); + + + /** + * The <b>vertex</b> callback method is invoked between the {@link + * #begin begin} and {@link #end end} callback methods. It is + * similar to {@link javax.media.opengl.GL#glVertex3f glVertex3f}, + * and it defines the vertices of the triangles created by the + * tessellation process. The method takes a reference as its only + * argument. This reference is identical to the opaque reference + * provided by the user when the vertex was described (see {@link + * GLU#gluTessVertex gluTessVertex}). + * + * @param vertexData + * Specifics a reference to the vertices of the triangles created + * byt the tessellatin process. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #vertexData vertexData + */ + public void vertex(Object vertexData); + + + /** + * The same as the {@link #vertex vertex} callback method except + * that it takes an additional reference argument. This reference is + * identical to the opaque reference provided when {@link + * GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param vertexData + * Specifics a reference to the vertices of the triangles created + * byt the tessellatin process. + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #vertex vertex + */ + public void vertexData(Object vertexData, Object polygonData); + + + /** + * The end callback serves the same purpose as + * {@link javax.media.opengl.GL#glEnd glEnd}. It indicates the end of a + * primitive and it takes no arguments. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #begin begin + * @see #endData endData + */ + public void end(); + + + /** + * The same as the {@link #end end} callback method except that it + * takes an additional reference argument. This reference is + * identical to the opaque reference provided when {@link + * GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #beginData beginData + * @see #end end + */ + public void endData(Object polygonData); + + + /** + * The <b>combine</b> callback method is called to create a new vertex when + * the tessellation detects an intersection, or wishes to merge features. The + * method takes four arguments: an array of three elements each of type + * double, an array of four references, an array of four elements each of + * type float, and a reference to a reference.<P> + * + * The vertex is defined as a linear combination of up to four existing + * vertices, stored in <i>data</i>. The coefficients of the linear combination + * are given by <i>weight</i>; these weights always add up to 1. All vertex + * pointers are valid even when some of the weights are 0. <i>coords</i> gives + * the location of the new vertex.<P> + * + * The user must allocate another vertex, interpolate parameters using + * <i>data</i> and <i>weight</i>, and return the new vertex pointer in + * <i>outData</i>. This handle is supplied during rendering callbacks. The + * user is responsible for freeing the memory some time after + * {@link GLU#gluTessEndPolygon gluTessEndPolygon} is + * called.<P> + * + * For example, if the polygon lies in an arbitrary plane in 3-space, and a + * color is associated with each vertex, the <b>GLU_TESS_COMBINE</b> + * callback might look like this: + * </UL> + * <PRE> + * void myCombine(double[] coords, Object[] data, + * float[] weight, Object[] outData) + * { + * MyVertex newVertex = new MyVertex(); + * + * newVertex.x = coords[0]; + * newVertex.y = coords[1]; + * newVertex.z = coords[2]; + * newVertex.r = weight[0]*data[0].r + + * weight[1]*data[1].r + + * weight[2]*data[2].r + + * weight[3]*data[3].r; + * newVertex.g = weight[0]*data[0].g + + * weight[1]*data[1].g + + * weight[2]*data[2].g + + * weight[3]*data[3].g; + * newVertex.b = weight[0]*data[0].b + + * weight[1]*data[1].b + + * weight[2]*data[2].b + + * weight[3]*data[3].b; + * newVertex.a = weight[0]*data[0].a + + * weight[1]*data[1].a + + * weight[2]*data[2].a + + * weight[3]*data[3].a; + * outData = newVertex; + * }</PRE> + * + * @param coords + * Specifics the location of the new vertex. + * @param data + * Specifics the vertices used to create the new vertex. + * @param weight + * Specifics the weights used to create the new vertex. + * @param outData + * Reference user the put the coodinates of the new vertex. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #combineData combineData + */ + public void combine(double[] coords, Object[] data, + float[] weight, Object[] outData); + + + /** + * The same as the {@link #combine combine} callback method except + * that it takes an additional reference argument. This reference is + * identical to the opaque reference provided when {@link + * GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param coords + * Specifics the location of the new vertex. + * @param data + * Specifics the vertices used to create the new vertex. + * @param weight + * Specifics the weights used to create the new vertex. + * @param outData + * Reference user the put the coodinates of the new vertex. + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #combine combine + */ + public void combineData(double[] coords, Object[] data, + float[] weight, Object[] outData, + Object polygonData); + + + /** + * The <b>error</b> callback method is called when an error is encountered. + * The one argument is of type int; it indicates the specific error that + * occurred and will be set to one of <b>GLU_TESS_MISSING_BEGIN_POLYGON</b>, + * <b>GLU_TESS_MISSING_END_POLYGON</b>, <b>GLU_TESS_MISSING_BEGIN_CONTOUR</b>, + * <b>GLU_TESS_MISSING_END_CONTOUR</b>, <b>GLU_TESS_COORD_TOO_LARGE</b>, + * <b>GLU_TESS_NEED_COMBINE_CALLBACK</b> or <b>GLU_OUT_OF_MEMORY</b>. + * Character strings describing these errors can be retrieved with the + * {@link GLU#gluErrorString gluErrorString} call.<P> + * + * The GLU library will recover from the first four errors by inserting the + * missing call(s). <b>GLU_TESS_COORD_TOO_LARGE</b> indicates that some + * vertex coordinate exceeded the predefined constant + * <b>GLU_TESS_MAX_COORD</b> in absolute value, and that the value has been + * clamped. (Coordinate values must be small enough so that two can be + * multiplied together without overflow.) + * <b>GLU_TESS_NEED_COMBINE_CALLBACK</b> indicates that the tessellation + * detected an intersection between two edges in the input data, and the + * <b>GLU_TESS_COMBINE</b> or <b>GLU_TESS_COMBINE_DATA</b> callback was not + * provided. No output is generated. <b>GLU_OUT_OF_MEMORY</b> indicates that + * there is not enough memory so no output is generated. + * + * @param errnum + * Specifics the error number code. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #errorData errorData + */ + public void error(int errnum); + + + /** + * The same as the {@link #error error} callback method except that + * it takes an additional reference argument. This reference is + * identical to the opaque reference provided when {@link + * GLU#gluTessBeginPolygon gluTessBeginPolygon} was called. + * + * @param errnum + * Specifics the error number code. + * @param polygonData + * Specifics a reference to user-defined data. + * + * @see GLU#gluTessCallback gluTessCallback + * @see #error error + */ + public void errorData(int errnum, Object polygonData); + + //void mesh(com.sun.opengl.impl.tessellator.GLUmesh mesh); +} diff --git a/src/classes/javax/media/opengl/glu/GLUtessellatorCallbackAdapter.java b/src/classes/javax/media/opengl/glu/GLUtessellatorCallbackAdapter.java new file mode 100755 index 000000000..eaccf0b15 --- /dev/null +++ b/src/classes/javax/media/opengl/glu/GLUtessellatorCallbackAdapter.java @@ -0,0 +1,74 @@ +/* +* Portions Copyright (C) 2003 Sun Microsystems, Inc. +* All rights reserved. +*/ + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: The application programming interfaces +** established by SGI in conjunction with the Original Code are The +** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released +** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version +** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X +** Window System(R) (Version 1.3), released October 19, 1998. This software +** was created using the OpenGL(R) version 1.2.1 Sample Implementation +** published by SGI, but has not been independently verified as being +** compliant with the OpenGL(R) version 1.2.1 Specification. +** +** Author: Eric Veach, July 1994 +** Java Port: Pepijn Van Eeckhoudt, July 2003 +** Java Port: Nathan Parker Burg, August 2003 +*/ +package javax.media.opengl.glu; + +/** + * The <b>GLUtessellatorCallbackAdapter</b> provides a default implementation of + * {@link GLUtessellatorCallback GLUtessellatorCallback} + * with empty callback methods. This class can be extended to provide user + * defined callback methods. + * + * @author Eric Veach, July 1994 + * @author Java Port: Pepijn Van Eechhoudt, July 2003 + * @author Java Port: Nathan Parker Burg, August 2003 + */ + +public class GLUtessellatorCallbackAdapter implements GLUtessellatorCallback { + public void begin(int type) {} + public void edgeFlag(boolean boundaryEdge) {} + public void vertex(Object vertexData) {} + public void end() {} +// public void mesh(com.sun.opengl.impl.tessellator.GLUmesh mesh) {} + public void error(int errnum) {} + public void combine(double[] coords, Object[] data, + float[] weight, Object[] outData) {} + public void beginData(int type, Object polygonData) {} + public void edgeFlagData(boolean boundaryEdge, + Object polygonData) {} + public void vertexData(Object vertexData, Object polygonData) {} + public void endData(Object polygonData) {} + public void errorData(int errnum, Object polygonData) {} + public void combineData(double[] coords, Object[] data, + float[] weight, Object[] outData, + Object polygonData) {} +} |