aboutsummaryrefslogtreecommitdiffstats
path: root/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java
blob: 9353479abd5699152693e89caa544239b380f40e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*
 * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
 * Copyright (c) 2010 JogAmp Community. 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 jogamp.opengl;

import java.util.*;
import javax.media.opengl.*;

/** Encapsulates the implementation of most of the GLAutoDrawable's
    methods to be able to share it between GLCanvas and GLJPanel. */

public class GLDrawableHelper {
  protected static final boolean DEBUG = GLDrawableImpl.DEBUG;
  private static final boolean VERBOSE = Debug.verbose();
  private Object listenersLock = new Object();
  private ArrayList<GLEventListener> listeners;
  private HashSet<GLEventListener> listenersToBeInit;
  private boolean autoSwapBufferMode;
  private Object glRunnablesLock = new Object();
  private ArrayList<GLRunnable> glRunnables;
  private GLAnimatorControl animatorCtrl;

  public GLDrawableHelper() {
    reset();
  }

  public final void reset() {
    synchronized(listenersLock) {
        listeners = new ArrayList<GLEventListener>();
        listenersToBeInit = new HashSet<GLEventListener>();
    }
    autoSwapBufferMode = true;
    synchronized(glRunnablesLock) {
        glRunnables = new ArrayList<GLRunnable>();
    }
    animatorCtrl = null;
  }

  @Override
  public final String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("GLAnimatorControl: "+animatorCtrl+", ");
    synchronized(listenersLock) {
        sb.append("GLEventListeners num "+listeners.size()+" [");
        for (int i=0; i < listeners.size(); i++) {
          Object l = listeners.get(i);
          sb.append(l);
          sb.append("[init ");
          sb.append( !listenersToBeInit.contains(l) );
          sb.append("], ");
        }
    }
    sb.append("]");
    return sb.toString();
  }

  public final void addGLEventListener(GLEventListener listener) {
    addGLEventListener(-1, listener);
  }

  public final void addGLEventListener(int index, GLEventListener listener) {
    synchronized(listenersLock) {
        if(0>index) {
            index = listeners.size();
        }
        // GLEventListener may be added after context is created,
        // hence we earmark initialization for the next display call.
        listenersToBeInit.add(listener);
        listeners.add(index, listener);
    }
  }
  
  public final void removeGLEventListener(GLEventListener listener) {
    synchronized(listenersLock) {
        listeners.remove(listener);
        listenersToBeInit.remove(listener);
    }
  }

  /**
   * Issues {@link javax.media.opengl.GLEventListener#dispose(javax.media.opengl.GLAutoDrawable)}
   * to all listeners.
   * @param drawable
   */
  public final void dispose(GLAutoDrawable drawable) {
    synchronized(listenersLock) {
        for (int i=0; i < listeners.size(); i++) {
          listeners.get(i).dispose(drawable);
        }
    }
  }

  private boolean init(GLEventListener l, GLAutoDrawable drawable, boolean sendReshape) {
      if(listenersToBeInit.remove(l)) {
          l.init(drawable);
          if(sendReshape) {
              reshape(l, drawable, 0, 0, drawable.getWidth(), drawable.getHeight(), true /* setViewport */);
          }
          return true;
      }
      return false;
  }

  public final void init(GLAutoDrawable drawable) {
    synchronized(listenersLock) {
        for (int i=0; i < listeners.size(); i++) {
          final GLEventListener listener = listeners.get(i) ;

          // If make current ctx, invoked by invokGL(..), results in a new ctx, init gets called.
          // This may happen not just for initial setup, but for ctx recreation due to resource change (drawable/window),
          // hence the must always be initialized unconditional.
          listenersToBeInit.add(listener);

          if ( ! init( listener, drawable, false ) ) {
            throw new GLException("GLEventListener "+listener+" already initialized: "+drawable);
          }
        }
    }
  }

  public final void display(GLAutoDrawable drawable) {
    displayImpl(drawable);
    if(!execGLRunnables(drawable)) {
        displayImpl(drawable);  
    }
  }
  private void displayImpl(GLAutoDrawable drawable) {
      synchronized(listenersLock) {
          for (int i=0; i < listeners.size(); i++) {
            final GLEventListener listener = listeners.get(i) ;
            // GLEventListener may need to be init, 
            // in case this one is added after the realization of the GLAutoDrawable
            init( listener, drawable, true ) ; 
            listener.display(drawable);
          }
      }
  }

  private void reshape(GLEventListener listener, GLAutoDrawable drawable,
                             int x, int y, int width, int height, boolean setViewport) {
    if(setViewport) {
        drawable.getGL().glViewport(x, y, width, height);
    }
    listener.reshape(drawable, x, y, width, height);
  }

  public final void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
    synchronized(listenersLock) {
        for (int i=0; i < listeners.size(); i++) {
          reshape((GLEventListener) listeners.get(i), drawable, x, y, width, height, 0==i);
        }
    }
  }

  private boolean execGLRunnables(GLAutoDrawable drawable) {
    boolean res = true;
    if(glRunnables.size()>0) {
        // swap one-shot list asap
        ArrayList<GLRunnable> _glRunnables = null;
        synchronized(glRunnablesLock) {
            if(glRunnables.size()>0) {
                _glRunnables = glRunnables;
                glRunnables = new ArrayList<GLRunnable>();
            }
        }
        
        if(null!=_glRunnables) {
            for (int i=0; i < _glRunnables.size(); i++) {
              res = _glRunnables.get(i).run(drawable) && res;
            }
        }
    }
    return res;
  }

  public final void setAnimator(GLAnimatorControl animator) throws GLException {
    synchronized(glRunnablesLock) {
        if(animatorCtrl!=animator && null!=animator && null!=animatorCtrl) {
            throw new GLException("Trying to register GLAnimatorControl "+animator+", where "+animatorCtrl+" is already registered. Unregister first.");
        }
        animatorCtrl = animator;
    }
  }

  public final GLAnimatorControl getAnimator() {
    synchronized(glRunnablesLock) {
        return animatorCtrl;
    }
  }

  public final boolean isExternalAnimatorRunning() {
    return ( null != animatorCtrl ) ? animatorCtrl.isStarted() && animatorCtrl.getThread() != Thread.currentThread() : false ;
  }

  public final boolean isExternalAnimatorAnimating() {
    return ( null != animatorCtrl ) ? animatorCtrl.isAnimating() && animatorCtrl.getThread() != Thread.currentThread() : false ;
  }

  public final void invoke(GLAutoDrawable drawable, boolean wait, GLRunnable glRunnable) {
    if( null == drawable || null == glRunnable ) {
        return;
    }
    Throwable throwable = null;
    GLRunnableTask rTask = null;
    Object rTaskLock = new Object();
    synchronized(rTaskLock) {
        boolean deferred;
        synchronized(glRunnablesLock) {
            deferred = isExternalAnimatorAnimating();
            if(!deferred) {
                wait = false; // don't wait if exec immediatly
            }
            rTask = new GLRunnableTask(glRunnable,
                                       wait ? rTaskLock : null,
                                       wait  /* catch Exceptions if waiting for result */);
            glRunnables.add(rTask);
        }
        if( !deferred ) {
            drawable.display();
        } else if( wait ) {
            try {
                rTaskLock.wait(); // free lock, allow execution of rTask
            } catch (InterruptedException ie) {
                throwable = ie;
            }
            if(null==throwable) {
                throwable = rTask.getThrowable();
            }
            if(null!=throwable) {
                throw new RuntimeException(throwable);
            }
        }
    }
  }

  public final void setAutoSwapBufferMode(boolean onOrOff) {
    autoSwapBufferMode = onOrOff;
  }

  public final boolean getAutoSwapBufferMode() {
    return autoSwapBufferMode;
  }

  private static final ThreadLocal perThreadInitAction = new ThreadLocal();

  /** Principal helper method which runs a Runnable with the context
      made current. This could have been made part of GLContext, but a
      desired goal is to be able to implement GLAutoDrawable's in terms of
      the GLContext's public APIs, and putting it into a separate
      class helps ensure that we don't inadvertently use private
      methods of the GLContext or its implementing classes.<br>
   * <br>
   * Remark: In case this method is called to dispose the GLDrawable/GLAutoDrawable,
   * <code>initAction</code> shall be <code>null</code> to mark this cause.<br>
   *
   * @param drawable
   * @param context
   * @param runnable
   * @param initAction
   */
  public final void invokeGL(GLDrawable drawable,
                             GLContext context,
                             Runnable  runnable,
                             Runnable  initAction) {
    if(null==context) {
        if (DEBUG) {
            Exception e = new GLException(Thread.currentThread().getName()+" Info: GLDrawableHelper " + this + ".invokeGL(): NULL GLContext");
            e.printStackTrace();
        }
        return;
    }

    if(null==initAction) {
        // disposal case
        if(!context.isCreated()) {
            throw new GLException(Thread.currentThread().getName()+" GLDrawableHelper " + this + ".invokeGL(): Dispose case (no init action given): Native context is not created: "+context);
        }
    }

    // Support for recursive makeCurrent() calls as well as calling
    // other drawables' display() methods from within another one's
    // FIXME: re-evaluate due to possible expensive TLS access ? 
    GLContext lastContext    = GLContext.getCurrent();
    Runnable  lastInitAction = (Runnable) perThreadInitAction.get();
    if (lastContext != null) {
      lastContext.release();
    }
  
    int res = 0;
    try {
      res = context.makeCurrent();
      if (res != GLContext.CONTEXT_NOT_CURRENT) {
        if(null!=initAction) {
            perThreadInitAction.set(initAction);
            if (res == GLContext.CONTEXT_CURRENT_NEW) {
              if (DEBUG) {
                System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running initAction");
              }
              initAction.run();
            }
        }
        if(null!=runnable) {
            if (DEBUG && VERBOSE) {
              System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running runnable");
            }
            runnable.run();
            if (autoSwapBufferMode && null != initAction) {
              if (drawable != null) {
                drawable.swapBuffers();
              }
            }
        }
      }
    } finally {
      try {
        if (res != GLContext.CONTEXT_NOT_CURRENT) {
          context.release();
        }
      } catch (Exception e) {
      }
      if (lastContext != null) {
        int res2 = lastContext.makeCurrent();
        if (res2 == GLContext.CONTEXT_CURRENT_NEW) {
          lastInitAction.run();
        }
      }
    }
  }

}
pan> AbstractGraphicsDevice device = getOrCreateSharedDevice(deviceReq); if(null == device) { throw new GLException("No shared device for requested: "+deviceReq); } if ( !canCreateGLPbuffer(device) ) { throw new GLException("Pbuffer not available with device: "+device); } final GLCapabilitiesImmutable capsChosen = GLGraphicsConfigurationUtil.fixGLPBufferGLCapabilities(capsRequested); GLDrawableImpl drawable = null; device.lock(); try { drawable = createOffscreenDrawableImpl( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, new UpstreamSurfaceHookMutableSize(width, height) ) ); if(null != drawable) { drawable.setRealized(true); } } finally { device.unlock(); } return new GLPbufferImpl( drawable, (GLContextImpl) drawable.createContext(shareWith) ); } //--------------------------------------------------------------------------- // // Offscreen GLDrawable construction // public final boolean canCreateFBO(AbstractGraphicsDevice deviceReq, GLProfile glp) { AbstractGraphicsDevice device = getOrCreateSharedDevice(deviceReq); if(null == device) { throw new GLException("No shared device for requested: "+deviceReq); } return GLContext.isFBOAvailable(device, glp); } @Override public GLOffscreenAutoDrawable createOffscreenAutoDrawable(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, int width, int height, GLContext shareWith) { final GLDrawable drawable = createOffscreenDrawable( deviceReq, capsRequested, chooser, width, height ); drawable.setRealized(true); final GLContext context = drawable.createContext(shareWith); if(drawable instanceof GLFBODrawableImpl) { return new GLOffscreenAutoDrawableImpl.FBOImpl( (GLFBODrawableImpl)drawable, context, null, null ); } return new GLOffscreenAutoDrawableImpl( drawable, context, null, null); } @Override public GLDrawable createOffscreenDrawable(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, int width, int height) { if(width<=0 || height<=0) { throw new GLException("initial size must be positive (were (" + width + " x " + height + "))"); } final AbstractGraphicsDevice device = getOrCreateSharedDevice(deviceReq); if(null == device) { throw new GLException("No shared device for requested: "+deviceReq); } final GLCapabilitiesImmutable capsChosen = GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(capsRequested, this, device); device.lock(); try { if( capsChosen.isFBO() ) { // Use minimum GLCapabilities for the dummy surface w/ same profile final ProxySurface dummySurface = createDummySurfaceImpl(device, true, new GLCapabilities(capsChosen.getGLProfile()), capsRequested, null, width, height); final GLDrawableImpl dummyDrawable = createOnscreenDrawableImpl(dummySurface); return new GLFBODrawableImpl.ResizeableImpl(this, dummyDrawable, dummySurface, capsChosen, 0); } return createOffscreenDrawableImpl( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, new UpstreamSurfaceHookMutableSize(width, height) ) ); } finally { device.unlock(); } } /** Creates a platform independent unrealized FBO offscreen GLDrawable */ protected GLFBODrawable createFBODrawableImpl(NativeSurface dummySurface, GLCapabilitiesImmutable fboCaps, int textureUnit) { final GLDrawableImpl dummyDrawable = createOnscreenDrawableImpl(dummySurface); return new GLFBODrawableImpl(this, dummyDrawable, dummySurface, fboCaps, textureUnit); } /** Creates a platform dependent unrealized offscreen pbuffer/pixmap GLDrawable instance */ protected abstract GLDrawableImpl createOffscreenDrawableImpl(NativeSurface target) ; /** * Creates a mutable {@link ProxySurface} w/o defined surface handle. * <p> * It's {@link AbstractGraphicsConfiguration} is properly set according to the given {@link GLCapabilitiesImmutable}. * </p> * <p> * Lifecycle (destruction) of the TBD surface handle shall be handled by the caller. * </p> * @param device a valid platform dependent target device. * @param createNewDevice if <code>true</code> a new device instance is created using <code>device</code> details, * otherwise <code>device</code> instance is used as-is. * @param capsChosen * @param capsRequested * @param chooser the custom chooser, may be null for default * @param upstreamHook surface size information and optional control of the surface's lifecycle * @return the created {@link MutableSurface} instance w/o defined surface handle */ protected abstract ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice device, boolean createNewDevice, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook); /** * A dummy surface is not visible on screen and will not be used to render directly to, * it maybe on- or offscreen. * <p> * It is used to allow the creation of a {@link GLDrawable} and {@link GLContext} to query information. * It also allows creation of framebuffer objects which are used for rendering. * </p> * @param deviceReq which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared device to be used, may be <code>null</code> for the platform's default device. * @param requestedCaps * @param chooser the custom chooser, may be null for default * @param width the initial width * @param height the initial height * * @return the created {@link ProxySurface} instance w/o defined surface handle but platform specific {@link UpstreamSurfaceHook}. */ public ProxySurface createDummySurface(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { final AbstractGraphicsDevice device = getOrCreateSharedDevice(deviceReq); if(null == device) { throw new GLException("No shared device for requested: "+deviceReq); } device.lock(); try { return createDummySurfaceImpl(device, true, requestedCaps, requestedCaps, chooser, width, height); } finally { device.unlock(); } } /** * A dummy surface is not visible on screen and will not be used to render directly to, * it maybe on- or offscreen. * <p> * It is used to allow the creation of a {@link GLDrawable} and {@link GLContext} to query information. * It also allows creation of framebuffer objects which are used for rendering. * </p> * @param device a valid platform dependent target device. * @param createNewDevice if <code>true</code> a new device instance is created using <code>device</code> details, * otherwise <code>device</code> instance is used as-is. * @param chosenCaps * @param requestedCaps * @param chooser the custom chooser, may be null for default * @param width the initial width as returned by {@link NativeSurface#getWidth()}, not the actual dummy surface width. * The latter is platform specific and small * @param height the initial height as returned by {@link NativeSurface#getHeight()}, not the actual dummy surface height, * The latter is platform specific and small * @return the created {@link ProxySurface} instance w/o defined surface handle but platform specific {@link UpstreamSurfaceHook}. */ public abstract ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice device, boolean createNewDevice, GLCapabilitiesImmutable chosenCaps, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height); //--------------------------------------------------------------------------- // // ProxySurface (Wrapped pre-existing native surface) construction // @Override public ProxySurface createProxySurface(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { final AbstractGraphicsDevice device = getOrCreateSharedDevice(deviceReq); if(null == device) { throw new GLException("No shared device for requested: "+deviceReq); } if(0 == windowHandle) { throw new IllegalArgumentException("Null windowHandle"); } device.lock(); try { return createProxySurfaceImpl(device, screenIdx, windowHandle, capsRequested, chooser, upstream); } finally { device.unlock(); } } /** * Creates a {@link ProxySurface} with a set surface handle. * <p> * Implementation is also required to allocate it's own {@link AbstractGraphicsDevice} instance. * </p> * @param upstream TODO */ protected abstract ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream); //--------------------------------------------------------------------------- // // External GLDrawable construction // protected abstract GLContext createExternalGLContextImpl(); @Override public GLContext createExternalGLContext() { return createExternalGLContextImpl(); } protected abstract GLDrawable createExternalGLDrawableImpl(); @Override public GLDrawable createExternalGLDrawable() { return createExternalGLDrawableImpl(); } //--------------------------------------------------------------------------- // // GLDrawableFactoryImpl details // /** * Returns the sole GLDrawableFactoryImpl instance. * * @param glProfile GLProfile to determine the factory type, ie EGLDrawableFactory, * or one of the native GLDrawableFactory's, ie X11/GLX, Windows/WGL or MacOSX/CGL. */ public static GLDrawableFactoryImpl getFactoryImpl(GLProfile glp) { return (GLDrawableFactoryImpl) getFactory(glp); } //---------------------------------------------------------------------- // Gamma adjustment support // Thanks to the LWJGL team for illustrating how to make these // adjustments on various OSs. /* * Portions Copyright (c) 2002-2004 LWJGL Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions 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 'LWJGL' nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Sets the gamma, brightness, and contrast of the current main * display. Returns true if the settings were changed, false if * not. If this method returns true, the display settings will * automatically be reset upon JVM exit (assuming the JVM does not * crash); if the user wishes to change the display settings back to * normal ahead of time, use resetDisplayGamma(). Throws * IllegalArgumentException if any of the parameters were * out-of-bounds. * * @param gamma The gamma value, typically > 1.0 (default value is * 1.0) * @param brightness The brightness value between -1.0 and 1.0, * inclusive (default value is 0) * @param contrast The contrast, greater than 0.0 (default value is 1) * @throws IllegalArgumentException if any of the parameters were * out-of-bounds */ public boolean setDisplayGamma(float gamma, float brightness, float contrast) throws IllegalArgumentException { if ((brightness < -1.0f) || (brightness > 1.0f)) { throw new IllegalArgumentException("Brightness must be between -1.0 and 1.0"); } if (contrast < 0) { throw new IllegalArgumentException("Contrast must be greater than 0.0"); } // FIXME: ensure gamma is > 1.0? Are smaller / negative values legal? int rampLength = getGammaRampLength(); if (rampLength == 0) { return false; } float[] gammaRamp = new float[rampLength]; for (int i = 0; i < rampLength; i++) { float intensity = (float) i / (float) (rampLength - 1); // apply gamma float rampEntry = (float) java.lang.Math.pow(intensity, gamma); // apply brightness rampEntry += brightness; // apply contrast rampEntry = (rampEntry - 0.5f) * contrast + 0.5f; // Clamp entry to [0, 1] if (rampEntry > 1.0f) rampEntry = 1.0f; else if (rampEntry < 0.0f) rampEntry = 0.0f; gammaRamp[i] = rampEntry; } registerGammaShutdownHook(); return setGammaRamp(gammaRamp); } public synchronized void resetDisplayGamma() { if (gammaShutdownHook == null) { throw new IllegalArgumentException("Should not call this unless setDisplayGamma called first"); } resetGammaRamp(originalGammaRamp); unregisterGammaShutdownHook(); } //------------------------------------------------------ // Gamma-related methods to be implemented by subclasses // /** Returns the length of the computed gamma ramp for this OS and hardware. Returns 0 if gamma changes are not supported. */ protected int getGammaRampLength() { return 0; } /** Sets the gamma ramp for the main screen. Returns false if gamma ramp changes were not supported. */ protected boolean setGammaRamp(float[] ramp) { return false; } /** Gets the current gamma ramp. This is basically an opaque value used only on some platforms to reset the gamma ramp to its original settings. */ protected Buffer getGammaRamp() { return null; } /** Resets the gamma ramp, potentially using the specified Buffer as data to restore the original values. */ protected void resetGammaRamp(Buffer originalGammaRamp) { } // Shutdown hook mechanism for resetting gamma private boolean gammaShutdownHookRegistered; private Thread gammaShutdownHook; private Buffer originalGammaRamp; private synchronized void registerGammaShutdownHook() { if (gammaShutdownHookRegistered) return; if (gammaShutdownHook == null) { gammaShutdownHook = new Thread(new Runnable() { @Override public void run() { synchronized (GLDrawableFactoryImpl.this) { resetGammaRamp(originalGammaRamp); } } }); originalGammaRamp = getGammaRamp(); } Runtime.getRuntime().addShutdownHook(gammaShutdownHook); gammaShutdownHookRegistered = true; } private synchronized void unregisterGammaShutdownHook() { if (!gammaShutdownHookRegistered) return; if (gammaShutdownHook == null) { throw new InternalError("Error in gamma shutdown hook logic"); } Runtime.getRuntime().removeShutdownHook(gammaShutdownHook); gammaShutdownHookRegistered = false; // Leave the original gamma ramp data alone } }