From 1c05c85e1ccc480da227cd6aa4718efd386e1e35 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 21 Jun 2012 20:14:46 +0200 Subject: JOGL CapabilitiesChooser-API and impl.: Cleanup using generics: 'List l' -> 'List l' --- .../classes/javax/media/nativewindow/CapabilitiesChooser.java | 2 +- .../classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java index a306363dc..e1fdf4938 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java +++ b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java @@ -65,6 +65,6 @@ public interface CapabilitiesChooser { choice to some other CapabilitiesChooser object. */ public int chooseCapabilities(CapabilitiesImmutable desired, - List /**/ available, + List available, int windowSystemRecommendedChoice); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java index 48c4d31ce..9d4b112b1 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java @@ -69,7 +69,7 @@ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { private static final boolean DEBUG = Debug.isPropertyDefined("nativewindow.debug.CapabilitiesChooser", true); public int chooseCapabilities(final CapabilitiesImmutable desired, - final List /**/ available, + final List available, final int windowSystemRecommendedChoice) { if (DEBUG) { System.err.println("Desired: " + desired); @@ -99,7 +99,7 @@ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { } // Compute score for each for (int i = 0; i < availnum; i++) { - CapabilitiesImmutable cur = (CapabilitiesImmutable) available.get(i); + final CapabilitiesImmutable cur = available.get(i); if (cur == null) { continue; } -- cgit v1.2.3 From a393e45613d87101dbb13763df263c2f9291d2d0 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 26 Jun 2012 10:44:08 +0200 Subject: Implement Bug #598 - JOGL ALL JAR File Change incl. it's Native Jar URL Derivation - Depends on GlueGen commit 9a71703904ebfec343fb2c7266343d37a2e4c3db JAR file name changes: ALL JARs: - jogl.all.jar -> jogl-all.jar - jogl.all-noawt.jar -> jogl-all-noawt.jar - jogl.all-mobile.jar -> jogl-all-mobile.jar - jogl.all-android.jar -> jogl-all-android.jar - jogl.all-android.apk -> jogl-all-android.apk Atomic JARs: - nativewindow.core.jar -> nativewindow-core.jar - nativewindow.awt.jar -> nativewindow-awt.jar - nativewindow.os.x11.jar -> nativewindow-os-x11.jar - nativewindow.os.win.jar -> nativewindow-os-win.jar - nativewindow.os.macosx.jar -> nativewindow-os-osx.jar - jogl.core.jar -> jogl-core.jar - jogl.sdk.jar -> jogl-sdk.jar - jogl.glmobile.jar -> jogl-glmobile.jar - jogl.glmobile.dbg.jar -> jogl-glmobile-dbg.jar - jogl.util.jar -> jogl-util.jar - jogl.glutess.jar -> jogl-glutess.jar - jogl.glumipmap.jar -> jogl-glumipmap.jar - jogl.util.fixedfuncemu.jar -> jogl-util-fixedfuncemu.jar - jogl.awt.jar -> jogl-awt.jar - jogl.swt.jar -> jogl-swt.jar - jogl.util.awt.jar -> jogl-util-awt.jar - jogl.os.x11.jar -> jogl-os-x11.jar - jogl.os.win.jar -> jogl-os-win.jar - jogl.os.osx.jar -> jogl-os-osx.jar - jogl.os.android.jar -> jogl-os-android.jar - jogl.gldesktop.jar -> jogl-gldesktop.jar - jogl.gldesktop.dbg.jar -> jogl-gldesktop-dbg.jar - jogl.glugldesktop.jar -> jogl-glu-gldesktop.jar - jogl.util.gldesktop.jar -> jogl-util-gldesktop.jar - jogl.omx.jar -> jogl-omx.jar - jogl.cg.jar -> jogl-cg.jar - newt.core.jar -> newt-core.jar - newt.ogl.jar -> newt-ogl.jar - newt.awt.jar -> newt-awt.jar - newt.event.jar -> newt-event.jar - newt.driver.x11.jar -> newt-driver-x11.jar - newt.driver.win.jar -> newt-driver-win.jar - newt.driver.macosx.jar -> newt-driver-osx.jar - newt.driver.android.jar -> newt-driver-android.jar - newt.driver.kd.jar -> newt-driver-kd.jar - newt.driver.intelgdl.jar -> newt-driver-intelgdl.jar - newt.driver.broadcomegl.jar -> newt-driver-broadcomegl.jar Test JARs: - jogl.test.jar -> jogl-test.jar - jogl.test-android.jar -> jogl-test-android.jar - jogl.test-android.apk -> jogl-test-android.apk --- etc/profile.jogl | 14 +- jnlp-files/atomic/jogl-awt.jnlp | 54 ++-- jnlp-files/atomic/jogl-noawt.jnlp | 50 ++-- jnlp-files/atomic/nativewindow-awt.jnlp | 19 +- jnlp-files/atomic/nativewindow-noawt.jnlp | 30 ++- jnlp-files/atomic/newt-awt-jogl.jnlp | 36 +-- jnlp-files/atomic/newt-awt.jnlp | 34 +-- jnlp-files/atomic/newt-noawt-jogl.jnlp | 36 +-- jnlp-files/atomic/newt-noawt.jnlp | 30 +-- jnlp-files/jogl-all-awt-cg.jnlp | 36 +-- jnlp-files/jogl-all-awt.jnlp | 2 +- jnlp-files/jogl-all-mobile.jnlp | 2 +- jnlp-files/jogl-all-noawt.jnlp | 2 +- ...nner-newt-ElektronenMultiplizierer-napplet.html | 8 +- ...pplet-runner-newt-ElektronenMultiplizierer.html | 8 +- ...applet-runner-newt-GraphTextDemo01-napplet.html | 8 +- .../jogl-applet-runner-newt-GraphTextDemo01.html | 8 +- ...let-runner-newt-GraphUISceneDemo01-napplet.html | 8 +- ...jogl-applet-runner-newt-GraphUISceneDemo01.html | 8 +- .../jogl-applet-runner-newt-MovieCube-napplet.html | 8 +- jnlp-files/jogl-applet-runner-newt-MovieCube.html | 8 +- ...plet-runner-newt-gears-normal-launcheronly.html | 16 +- ...gl-applet-runner-newt-gears-normal-napplet.html | 18 +- ...l-applet-runner-newt-gears-normal-napplet2.html | 18 +- .../jogl-applet-runner-newt-gears-normal.html | 20 +- ...l-applet-runner-newt-gears-special-napplet.html | 8 +- .../jogl-applet-runner-newt-gears-special.html | 8 +- jnlp-files/jogl-applet-runner-newt.jnlp | 2 +- jnlp-files/jogl-applet-version-lancheronly.html | 4 +- jnlp-files/jogl-applet-version-napplet.html | 8 +- jnlp-files/jogl-applet-version.html | 4 +- make/build-common.xml | 287 +++++++++++---------- make/build-jogl.xml | 50 ++-- make/build-nativewindow.xml | 10 +- make/build-newt.xml | 22 +- make/build-test.xml | 14 +- make/build.xml | 18 +- make/scripts/setenv-jogl.sh | 4 +- make/scripts/tests.sh | 16 +- .../opengl/cg/CgDynamicLibraryBundleInfo.java | 4 +- src/jogl/classes/javax/media/opengl/GLProfile.java | 28 +- .../jogamp/nativewindow/NWJNILibLoader.java | 4 +- src/newt/classes/jogamp/newt/NEWTJNILibLoader.java | 7 +- 43 files changed, 511 insertions(+), 468 deletions(-) (limited to 'src/nativewindow') diff --git a/etc/profile.jogl b/etc/profile.jogl index 1177aaa49..4402adde6 100755 --- a/etc/profile.jogl +++ b/etc/profile.jogl @@ -30,12 +30,12 @@ uname -a | grep -i LINUX && OSS=x11 uname -a | grep -i Darwin && OSS=osx uname -a | grep -i CYGWIN && OSS=win -JOGL_TEST="jogl.test.jar" +JOGL_TEST="jogl-test.jar" -JOGL_JAR_ALL="jogl.all.jar" -JOGL_JAR_ALL_NOAWT="jogl.all-noawt.jar" -JOGL_JAR_ALL_MOBILE="jogl.all-mobile.jar" -JOGL_JAR_SWT="atomic/jogl.swt.jar" +JOGL_JAR_ALL="jogl-all.jar" +JOGL_JAR_ALL_NOAWT="jogl-all-noawt.jar" +JOGL_JAR_ALL_MOBILE="jogl-all-mobile.jar" +JOGL_JAR_SWT="atomic/jogl-swt.jar" JOGL_LIB_ALL="libnativewindow_x11.so libnativewindow_awt.so libjogl_desktop.so libjogl_mobile.so libjogl_cg.so libnewt.so" JOGL_LIB_ALL_NOAWT="libnativewindow_x11.so libjogl_desktop.so libjogl_mobile.so libjogl_cg.so libnewt.so" @@ -76,8 +76,8 @@ export JOGL_LIB_DIR JOGL_ALL_AWT_CLASSPATH=$(concat_jogl_list $JOGL_BUILD_DIR $JOGL_JAR_ALL $JOGL_TEST) JOGL_ALL_NOAWT_CLASSPATH=$(concat_jogl_list $JOGL_BUILD_DIR $JOGL_JAR_ALL_NOAWT $JOGL_TEST) -JOGL_MOBILE_CLASSPATH=$(concat_jogl_list $JOGL_BUILD_DIR $JOGL_JAR_ALL_MOBILE) -JOGL_SWT_CLASSPATH=$(concat_jogl_list $JOGL_BUILD_DIR $JOGL_JAR_SWT) +JOGL_MOBILE_CLASSPATH=$(concat_jogl_list $JOGL_BUILD_DIR $JOGL_JAR_ALL_MOBILE $JOGL_TEST) +JOGL_SWT_CLASSPATH=$(concat_jogl_list $JOGL_BUILD_DIR $JOGL_JAR_SWT $JOGL_TEST) export JOGL_ALL_AWT_CLASSPATH JOGL_ALL_NOAWT_CLASSPATH JOGL_MOBILE_CLASSPATH JOGL_SWT_CLASSPATH if [ ! -z "$JOGL_PROFILE" ] ; then diff --git a/jnlp-files/atomic/jogl-awt.jnlp b/jnlp-files/atomic/jogl-awt.jnlp index a33eb35a6..8f15a6c58 100644 --- a/jnlp-files/atomic/jogl-awt.jnlp +++ b/jnlp-files/atomic/jogl-awt.jnlp @@ -14,83 +14,83 @@ - - - - - - - - - - - + + + + + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + diff --git a/jnlp-files/atomic/jogl-noawt.jnlp b/jnlp-files/atomic/jogl-noawt.jnlp index 3463a1965..91a1fe89b 100644 --- a/jnlp-files/atomic/jogl-noawt.jnlp +++ b/jnlp-files/atomic/jogl-noawt.jnlp @@ -14,81 +14,81 @@ - - - - - - - - - + + + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + diff --git a/jnlp-files/atomic/nativewindow-awt.jnlp b/jnlp-files/atomic/nativewindow-awt.jnlp index db80b644f..a993ab14a 100644 --- a/jnlp-files/atomic/nativewindow-awt.jnlp +++ b/jnlp-files/atomic/nativewindow-awt.jnlp @@ -14,57 +14,72 @@ - - + + + + + + + + + + + + + + + + + diff --git a/jnlp-files/atomic/nativewindow-noawt.jnlp b/jnlp-files/atomic/nativewindow-noawt.jnlp index fed731042..5cd4872dc 100644 --- a/jnlp-files/atomic/nativewindow-noawt.jnlp +++ b/jnlp-files/atomic/nativewindow-noawt.jnlp @@ -14,68 +14,72 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + + + + + diff --git a/jnlp-files/atomic/newt-awt-jogl.jnlp b/jnlp-files/atomic/newt-awt-jogl.jnlp index 69406e43c..0a43128bb 100644 --- a/jnlp-files/atomic/newt-awt-jogl.jnlp +++ b/jnlp-files/atomic/newt-awt-jogl.jnlp @@ -14,50 +14,50 @@ - - - + + + - + - + - + - + - + - + - + - + - + - + @@ -65,23 +65,23 @@ - + - + - + - + - + diff --git a/jnlp-files/atomic/newt-awt.jnlp b/jnlp-files/atomic/newt-awt.jnlp index 26e45e3fc..6e46b82a4 100644 --- a/jnlp-files/atomic/newt-awt.jnlp +++ b/jnlp-files/atomic/newt-awt.jnlp @@ -14,71 +14,73 @@ - - + + - + - + - + - + - + - + - + - + - + - + - + - + + + - + - + diff --git a/jnlp-files/atomic/newt-noawt-jogl.jnlp b/jnlp-files/atomic/newt-noawt-jogl.jnlp index ced8b29c7..5b671edcd 100644 --- a/jnlp-files/atomic/newt-noawt-jogl.jnlp +++ b/jnlp-files/atomic/newt-noawt-jogl.jnlp @@ -14,73 +14,73 @@ - - + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + diff --git a/jnlp-files/atomic/newt-noawt.jnlp b/jnlp-files/atomic/newt-noawt.jnlp index 1616dff88..1161d7a9c 100644 --- a/jnlp-files/atomic/newt-noawt.jnlp +++ b/jnlp-files/atomic/newt-noawt.jnlp @@ -14,56 +14,56 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -73,11 +73,11 @@ - + - + diff --git a/jnlp-files/jogl-all-awt-cg.jnlp b/jnlp-files/jogl-all-awt-cg.jnlp index 18f8f498e..24c22c290 100644 --- a/jnlp-files/jogl-all-awt-cg.jnlp +++ b/jnlp-files/jogl-all-awt-cg.jnlp @@ -14,75 +14,75 @@ - - + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + diff --git a/jnlp-files/jogl-all-awt.jnlp b/jnlp-files/jogl-all-awt.jnlp index 55ae21d2a..4e05f8dac 100644 --- a/jnlp-files/jogl-all-awt.jnlp +++ b/jnlp-files/jogl-all-awt.jnlp @@ -14,7 +14,7 @@ - + diff --git a/jnlp-files/jogl-all-mobile.jnlp b/jnlp-files/jogl-all-mobile.jnlp index 5f96137c2..43b9b3b09 100644 --- a/jnlp-files/jogl-all-mobile.jnlp +++ b/jnlp-files/jogl-all-mobile.jnlp @@ -14,7 +14,7 @@ - + diff --git a/jnlp-files/jogl-all-noawt.jnlp b/jnlp-files/jogl-all-noawt.jnlp index 63f558d38..eed6749c1 100644 --- a/jnlp-files/jogl-all-noawt.jnlp +++ b/jnlp-files/jogl-all-noawt.jnlp @@ -14,7 +14,7 @@ - + diff --git a/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer-napplet.html b/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer-napplet.html index 3b77157c6..19a3b2965 100644 --- a/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer-napplet.html +++ b/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer-napplet.html @@ -14,8 +14,8 @@ Demoscene Passivist's Elektronen-Multiplizierer width="640" height="480"> + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -28,8 +28,8 @@ Demoscene Passivist's Elektronen-Multiplizierer type="application/x-java-applet;version=1.6" pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" codebase_lookup" value="false" java_arguments="-Dsun.java2d.noddraw=true" gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.ElektronenMultiplizierer" diff --git a/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer.html b/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer.html index 2a500c9e6..71c9baff8 100644 --- a/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer.html +++ b/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer.html @@ -15,8 +15,8 @@ Demoscene Passivist's Elektronen-Multiplizierer + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -38,8 +38,8 @@ Demoscene Passivist's Elektronen-Multiplizierer pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" codebase_lookup" value="false" subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run" subapplet.displayname="ElektronenMultiplizierer" diff --git a/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01-napplet.html b/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01-napplet.html index 59115ca36..9648b57da 100644 --- a/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01-napplet.html +++ b/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01-napplet.html @@ -14,8 +14,8 @@ JOGL Graph Text Demo 01 width="800" height="400"> + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -31,8 +31,8 @@ JOGL Graph Text Demo 01 type="application/x-java-applet;version=1.6" pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" java_arguments="-Dsun.java2d.noddraw=true" gl_event_listener_class="com.jogamp.opengl.test.junit.graph.demos.GPUTextGLListener0A" gl_profile="GL2ES2" diff --git a/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01.html b/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01.html index 1c7d3472b..489984b4f 100644 --- a/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01.html +++ b/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01.html @@ -15,8 +15,8 @@ JOGL Graph Text Demo 01 + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -41,8 +41,8 @@ JOGL Graph Text Demo 01 pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" codebase_lookup" value="false" subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run" subapplet.displayname="JOGL Graph Text Demo01" diff --git a/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01-napplet.html b/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01-napplet.html index 6efeefc10..8f9783f03 100644 --- a/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01-napplet.html +++ b/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01-napplet.html @@ -14,8 +14,8 @@ JOGL Graph UI-Scene Demo 01 width="640" height="480"> + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -30,8 +30,8 @@ JOGL Graph UI-Scene Demo 01 type="application/x-java-applet;version=1.6" pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" java_arguments="-Dsun.java2d.noddraw=true" gl_event_listener_class="com.jogamp.opengl.test.junit.graph.demos.GPUUISceneGLListener0A" gl_profile="GL2ES2" diff --git a/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01.html b/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01.html index 6b32b11e7..429e80311 100644 --- a/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01.html +++ b/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01.html @@ -15,8 +15,8 @@ JOGL Graph UI-Scene Demo 01 + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -40,8 +40,8 @@ JOGL Graph UI-Scene Demo 01 pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" codebase_lookup" value="false" subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run" subapplet.displayname="JOGL Graph UI Demo01" diff --git a/jnlp-files/jogl-applet-runner-newt-MovieCube-napplet.html b/jnlp-files/jogl-applet-runner-newt-MovieCube-napplet.html index def7b72b9..f569c7c96 100644 --- a/jnlp-files/jogl-applet-runner-newt-MovieCube-napplet.html +++ b/jnlp-files/jogl-applet-runner-newt-MovieCube-napplet.html @@ -14,8 +14,8 @@ JogAmp's MovieCube - GLMediaPlayer Demo 01 width="510" height="300"> + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -28,8 +28,8 @@ JogAmp's MovieCube - GLMediaPlayer Demo 01 type="application/x-java-applet;version=1.6" pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" codebase_lookup" value="false" java_arguments="-Dsun.java2d.noddraw=true" gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube" diff --git a/jnlp-files/jogl-applet-runner-newt-MovieCube.html b/jnlp-files/jogl-applet-runner-newt-MovieCube.html index 6b1654ed7..7cb00244e 100644 --- a/jnlp-files/jogl-applet-runner-newt-MovieCube.html +++ b/jnlp-files/jogl-applet-runner-newt-MovieCube.html @@ -15,8 +15,8 @@ JogAmp's MovieCube - GLMediaPlayer Demo 01 + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -38,8 +38,8 @@ JogAmp's MovieCube - GLMediaPlayer Demo 01 pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" codebase_lookup" value="false" subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run" subapplet.displayname="MovieCube" diff --git a/jnlp-files/jogl-applet-runner-newt-gears-normal-launcheronly.html b/jnlp-files/jogl-applet-runner-newt-gears-normal-launcheronly.html index 91e989346..a9e42d342 100644 --- a/jnlp-files/jogl-applet-runner-newt-gears-normal-launcheronly.html +++ b/jnlp-files/jogl-applet-runner-newt-gears-normal-launcheronly.html @@ -21,8 +21,8 @@ JOGL NEWT JNLP Applet Runner Special Keys:
+ jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -43,8 +43,8 @@ JOGL NEWT JNLP Applet Runner Special Keys:
pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" codebase_lookup" value="false" subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run" subapplet.displayname="JOGL GearsES2 Applet" @@ -75,8 +75,8 @@ The applet above is instantiated with the following code: <param name="code" value="org.jdesktop.applet.util.JNLPAppletLauncher"> <param name="archive" value="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar"> + jar/jogl-all.jar, + jar/jogl-test.jar"> <param name="codebase_lookup" value="false"> <param name="subapplet.classname" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"> <param name="subapplet.displayname" value="JOGL GearsES2 Applet"> @@ -97,8 +97,8 @@ The applet above is instantiated with the following code: pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" codebase_lookup" value="false" subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run" subapplet.displayname="JOGL GearsES2 Applet" diff --git a/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet.html b/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet.html index 9db6d8cc2..37473befe 100644 --- a/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet.html +++ b/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet.html @@ -20,8 +20,8 @@ JOGL NEWT Applet Runner Special Keys:
width="200" height="200"> + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -34,8 +34,8 @@ JOGL NEWT Applet Runner Special Keys:
type="application/x-java-applet;version=1.6" pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" java_arguments="-Dsun.java2d.noddraw=true" gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2" gl_profile="GL2ES2" @@ -58,8 +58,8 @@ The applet above is instantiated with the following code: width="200" height="200"> <param name="code" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"> <param name="archive" value="jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar"> + jar/jogl-all.jar, + jar/jogl-test.jar"> <param name="java_arguments" value="-Dsun.java2d.noddraw=true"> <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2"> <param name="gl_profile" value="GL2ES2"> @@ -72,8 +72,8 @@ The applet above is instantiated with the following code: type="application/x-java-applet;version=1.6" pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" java_arguments="-Dsun.java2d.noddraw=true" gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2" gl_profile="GL2ES2" @@ -90,7 +90,7 @@ The applet above is instantiated with the following code:

-Note that the jogl.test.jar, which contains the test applet class, +Note that the jogl-test.jar, which contains the test applet class, does not need to be signed! JogAmp Community signs jogl.jar and gluegen-rt.jar, which contain JOGL's supporting classes; this is the only diff --git a/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet2.html b/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet2.html index ba2f69ef4..63df4ed60 100644 --- a/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet2.html +++ b/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet2.html @@ -21,8 +21,8 @@ If Applet is out of browser window, it is closeable. width="200" height="200"> + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -36,8 +36,8 @@ If Applet is out of browser window, it is closeable. type="application/x-java-applet;version=1.6" pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" java_arguments="-Dsun.java2d.noddraw=true" gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2" gl_profile="GL2ES2" @@ -61,8 +61,8 @@ The applet above is instantiated with the following code: width="200" height="200"> <param name="code" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"> <param name="archive" value="jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar"> + jar/jogl-all.jar, + jar/jogl-test.jar"> <param name="java_arguments" value="-Dsun.java2d.noddraw=true"> <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2"> <param name="gl_profile" value="GL2ES2"> @@ -76,8 +76,8 @@ The applet above is instantiated with the following code: type="application/x-java-applet;version=1.6" pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" java_arguments="-Dsun.java2d.noddraw=true" gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2" gl_profile="GL2ES2" @@ -95,7 +95,7 @@ The applet above is instantiated with the following code:

-Note that the jogl.test.jar, which contains the test applet class, +Note that the jogl-test.jar, which contains the test applet class, does not need to be signed! JogAmp Community signs jogl.jar and gluegen-rt.jar, which contain JOGL's supporting classes; this is the only diff --git a/jnlp-files/jogl-applet-runner-newt-gears-normal.html b/jnlp-files/jogl-applet-runner-newt-gears-normal.html index c8d654dbc..a6dd16a0c 100644 --- a/jnlp-files/jogl-applet-runner-newt-gears-normal.html +++ b/jnlp-files/jogl-applet-runner-newt-gears-normal.html @@ -35,8 +35,8 @@ JOGL NEWT JNLP Applet Runner Special Keys:
+ jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -58,8 +58,8 @@ JOGL NEWT JNLP Applet Runner Special Keys:
pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" codebase_lookup" value="false" subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run" subapplet.displayname="JOGL GearsES2 Applet" @@ -91,8 +91,8 @@ The applet above is instantiated with the following code: <param name="code" value="org.jdesktop.applet.util.JNLPAppletLauncher"> <param name="archive" value="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar"> + jar/jogl-all.jar, + jar/jogl-test.jar"> <param name="codebase_lookup" value="false"> <param name="subapplet.classname" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"> <param name="subapplet.displayname" value="JOGL GearsES2 Applet"> @@ -114,8 +114,8 @@ The applet above is instantiated with the following code: pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" codebase_lookup" value="false" subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run" subapplet.displayname="JOGL GearsES2 Applet" @@ -154,7 +154,7 @@ Where the referenced JNLP file jogl-applet-runner-newt.jnlp looks as fo <resources> <j2se href="http://java.sun.com/products/autodl/j2se" version="1.4+"/> <property name="sun.java2d.noddraw" value="true"/> - <jar href="jar/jogl.test.jar" main="true"/> + <jar href="jar/jogl-test.jar" main="true"/> <extension name="jogl-all-awt" href="http://jogamp.org/deployment/jogamp-current/jogl-all-awt.jnlp" /> </resources> @@ -170,7 +170,7 @@ Where the referenced JNLP file jogl-applet-runner-newt.jnlp looks as fo

-Note that the jogl.test.jar, which contains the test applet class, +Note that the jogl-test.jar, which contains the test applet class, does not need to be signed! JogAmp Community signs applet-launcher.jar, jogl.jar and gluegen-rt.jar, which contain the JNLPAppletLauncher and JOGL's supporting classes; this is the only diff --git a/jnlp-files/jogl-applet-runner-newt-gears-special-napplet.html b/jnlp-files/jogl-applet-runner-newt-gears-special-napplet.html index 3c1895b45..7df167844 100644 --- a/jnlp-files/jogl-applet-runner-newt-gears-special-napplet.html +++ b/jnlp-files/jogl-applet-runner-newt-gears-special-napplet.html @@ -11,8 +11,8 @@ JOGL NEWT JNLP Applet Runner Special Keys: width="1" height="1"> + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -32,8 +32,8 @@ JOGL NEWT JNLP Applet Runner Special Keys: type="application/x-java-applet;version=1.6" pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" java_arguments="-Dsun.java2d.noddraw=true" gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2" gl_profile="GL2ES2" diff --git a/jnlp-files/jogl-applet-runner-newt-gears-special.html b/jnlp-files/jogl-applet-runner-newt-gears-special.html index dcbe898e2..0f5911414 100644 --- a/jnlp-files/jogl-applet-runner-newt-gears-special.html +++ b/jnlp-files/jogl-applet-runner-newt-gears-special.html @@ -12,8 +12,8 @@ JOGL NEWT JNLP Applet Runner Special Keys: + jar/jogl-all.jar, + jar/jogl-test.jar"> @@ -42,8 +42,8 @@ JOGL NEWT JNLP Applet Runner Special Keys: pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar, - jar/jogl.test.jar" + jar/jogl-all.jar, + jar/jogl-test.jar" codebase_lookup" value="false" subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run" subapplet.displayname="JOGL GearsES2 Applet Transparent" diff --git a/jnlp-files/jogl-applet-runner-newt.jnlp b/jnlp-files/jogl-applet-runner-newt.jnlp index 259e39f18..c33e1b761 100644 --- a/jnlp-files/jogl-applet-runner-newt.jnlp +++ b/jnlp-files/jogl-applet-runner-newt.jnlp @@ -12,7 +12,7 @@ - + diff --git a/jnlp-files/jogl-applet-version-lancheronly.html b/jnlp-files/jogl-applet-version-lancheronly.html index 685d9115c..6880152fc 100644 --- a/jnlp-files/jogl-applet-version-lancheronly.html +++ b/jnlp-files/jogl-applet-version-lancheronly.html @@ -20,7 +20,7 @@ and your platform. + jar/jogl-all.jar"> @@ -36,7 +36,7 @@ and your platform. pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar" + jar/jogl-all.jar" codebase_lookup" value="false" subapplet.classname="jogamp.opengl.awt.VersionApplet" subapplet.displayname="JOGL Applet Version" diff --git a/jnlp-files/jogl-applet-version-napplet.html b/jnlp-files/jogl-applet-version-napplet.html index e8104cb60..aeccb710a 100644 --- a/jnlp-files/jogl-applet-version-napplet.html +++ b/jnlp-files/jogl-applet-version-napplet.html @@ -16,7 +16,7 @@ and your platform. width="800" height="600"> + jar/jogl-all.jar"> Sorry, no Java support detected. @@ -41,7 +41,7 @@ The applet above is instantiated with the following code: width="800" height="600"> <param name="code" value="jogamp.opengl.awt.VersionApplet"> <param name="archive" value="jar/gluegen-rt.jar, - jar/jogl.all.jar"> + jar/jogl-all.jar"> <param name="java_arguments" value="-Dsun.java2d.noddraw=true"> <comment> <embed code="jogamp.opengl.awt.VersionApplet" @@ -49,7 +49,7 @@ The applet above is instantiated with the following code: type="application/x-java-applet;version=1.6" pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/gluegen-rt.jar, - jar/jogl.all.jar" + jar/jogl-all.jar" java_arguments="-Dsun.java2d.noddraw=true"> <noembed>Sorry, no Java support detected.</noembed> </embed> diff --git a/jnlp-files/jogl-applet-version.html b/jnlp-files/jogl-applet-version.html index 5b738964e..948e63095 100644 --- a/jnlp-files/jogl-applet-version.html +++ b/jnlp-files/jogl-applet-version.html @@ -22,7 +22,7 @@ otherwise it shall fallback to + jar/jogl-all.jar"> @@ -39,7 +39,7 @@ otherwise it shall fallback to pluginspage="http://java.sun.com/javase/downloads/ea.jsp" archive="jar/applet-launcher.jar, jar/gluegen-rt.jar, - jar/jogl.all.jar" + jar/jogl-all.jar" codebase_lookup" value="false" subapplet.classname="jogamp.opengl.awt.VersionApplet" subapplet.displayname="JOGL Applet Version" diff --git a/make/build-common.xml b/make/build-common.xml index 93835e0f1..b2885c8af 100644 --- a/make/build-common.xml +++ b/make/build-common.xml @@ -250,167 +250,168 @@ - - - - - + + + + + - - - - - + + + + + - - - - + + + + - + - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - + + + + + + + + + - - - - - - - - - + + + + + + + + + - - - - - - - - - - - - + ${jogl-core.jar} ${jogl-glutess.jar} ${jogl-glumipmap.jar} ${jogl-glu-gldesktop.jar} ${jogl-os-x11.jar} ${jogl-os-win.jar} ${jogl-os-osx.jar} ${jogl-gldesktop.jar} ${jogl-gldesktop-dbg.jar} ${jogl-glmobile.jar} ${jogl-glmobile-dbg.jar} ${jogl-omx.jar} ${jogl-util.jar} ${jogl-util-gldesktop.jar} ${jogl-util-awt.jar} ${jogl-util-fixedfuncemu.jar} ${jogl-sdk.jar} --> + + + + + + + + + + + + - - - - - - + + + + + + - - - - - + + + + + - - - - + + + + - - - + + + - - - + + + - + - - - - + + + + @@ -477,7 +478,7 @@ - + @@ -486,12 +487,12 @@ - - + + - + value="${junit.jar}${path.separator}${ant.jar}${path.separator}${ant-junit.jar}${path.separator}${gluegen-rt.jar}${path.separator}${jogl-all.jar}${path.separator}${jogl-test.jar}"/> + @@ -499,12 +500,12 @@ - - + + - + value="${junit.jar}${path.separator}${ant.jar}${path.separator}${ant-junit.jar}${path.separator}${gluegen-rt.jar}${path.separator}${jogl-all-noawt.jar}${path.separator}${jogl-test.jar}"/> + @@ -513,11 +514,11 @@ - - + + + value="${junit.jar}${path.separator}${ant.jar}${path.separator}${ant-junit.jar}${path.separator}${gluegen-rt.jar}${path.separator}${swt.jar}${path.separator}${jogl-all.jar}${path.separator}${jogl-test.jar}"/> @@ -526,13 +527,13 @@ - - + + + value="${junit.jar}${path.separator}${ant.jar}${path.separator}${ant-junit.jar}${path.separator}${gluegen-rt-android.jar}${path.separator}${jogl-all-android.jar}${path.separator}${jogl-test.jar}"/> + value="${gluegen.root}/${rootrel.build}/jogamp.android-launcher.apk${path.separator}${ant-junit-all.apk}${path.separator}${gluegen.root}/${rootrel.build}/gluegen-rt-android-${android.abi}.apk${path.separator}${jogl-all-android.apk}${path.separator}${jogl-test.apk}"/> diff --git a/make/build-jogl.xml b/make/build-jogl.xml index 0c7328c4a..6845354f6 100644 --- a/make/build-jogl.xml +++ b/make/build-jogl.xml @@ -1550,7 +1550,7 @@ + includes="${jogl-util.jar} ${jogl-util-fixedfuncemu.jar}" /> @@ -1570,48 +1570,48 @@ - + - + - + - + - + - + - + - + - + @@ -1619,22 +1619,22 @@ - + - + - + - + @@ -1643,50 +1643,50 @@ - + - + - + - + - + - + - + - + - + - + - + diff --git a/make/build-nativewindow.xml b/make/build-nativewindow.xml index 233108823..c77558d6b 100644 --- a/make/build-nativewindow.xml +++ b/make/build-nativewindow.xml @@ -820,7 +820,7 @@ - + @@ -828,28 +828,28 @@ - + - + - + - + diff --git a/make/build-newt.xml b/make/build-newt.xml index 695c86d19..a6be5042e 100644 --- a/make/build-newt.xml +++ b/make/build-newt.xml @@ -701,52 +701,52 @@ - + - + - + - + - + - + - + - + - + - + @@ -759,7 +759,7 @@ - + diff --git a/make/build-test.xml b/make/build-test.xml index f5437902e..51eadfebd 100644 --- a/make/build-test.xml +++ b/make/build-test.xml @@ -51,7 +51,7 @@ - + @@ -85,7 +85,7 @@ - + @@ -121,7 +121,7 @@ - + @@ -134,7 +134,7 @@ assetsdir="resources/assets-test" jarsrcdir="${src}/test" jarbuilddir="${jar}" - jarbasename="jogl.test-android" + jarbasename="jogl-test-android" nativebuilddir="${lib}" nativebasename="non-existing" androidmanifest.path="resources/android/AndroidManifest-test.xml" @@ -149,8 +149,8 @@ - - + + @@ -159,7 +159,7 @@ - + diff --git a/make/build.xml b/make/build.xml index 9258df0e9..23aa218b4 100644 --- a/make/build.xml +++ b/make/build.xml @@ -99,7 +99,7 @@ - + @@ -111,7 +111,7 @@ - + @@ -120,7 +120,7 @@ - + @@ -129,7 +129,7 @@ - + @@ -147,8 +147,8 @@ - - + + @@ -158,7 +158,7 @@ assetsdir="resources/assets" jarsrcdir="${src}/jogl/classes" jarbuilddir="${jar}" - jarbasename="jogl.all-android" + jarbasename="jogl-all-android" nativebuilddir="${lib}" nativebasename="" android.abi="${android.abi}" @@ -173,12 +173,12 @@ - + - + diff --git a/make/scripts/setenv-jogl.sh b/make/scripts/setenv-jogl.sh index 2d91f278f..4067e65c9 100755 --- a/make/scripts/setenv-jogl.sh +++ b/make/scripts/setenv-jogl.sh @@ -93,8 +93,8 @@ CLASSPATH=.:$GLUEGEN_JAR:$JOGL_CLASSPATH:$SWT_CLASSPATH:$JUNIT_JAR:$ANT_JARS export CLASSPATH # We use TempJarCache per default now! -#export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$GLUEGEN_OS:$JOGL_LIB_DIR -#export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:$GLUEGEN_OS:$JOGL_LIB_DIR +export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$GLUEGEN_OS:$JOGL_LIB_DIR +export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:$GLUEGEN_OS:$JOGL_LIB_DIR echo JOGAMP_ALL_AWT_CLASSPATH: $CLASSPATH echo JOGAMP_ALL_NOAWT_CLASSPATH: $CLASSPATH diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 702b0dc8c..8f4237012 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -69,11 +69,11 @@ function jrun() { #D_ARGS="-Dnewt.test.Screen.disableScreenMode -Dnewt.debug.Screen" #D_ARGS="-Djogl.debug.ExtensionAvailabilityCache -Djogl.debug=all -Dnativewindow.debug=all -Djogamp.debug.ProcAddressHelper=true -Djogamp.debug.NativeLibrary=true -Djogamp.debug.NativeLibrary.Lookup=true" #D_ARGS="-Djogamp.debug=all -Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" + #D_ARGS="-Djogl.debug=all -Djogamp.debug.Lock -Djogamp.common.utils.locks.Lock.timeout=600000" #D_ARGS="-Dnewt.debug.MainThread" #D_ARGS="-Dnewt.debug.Window" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all" #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Dnativewindow.debug.NativeWindow" - #D_ARGS="-Djogl.debug=all" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Animator -Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.ExtensionAvailabilityCache" #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile -Djogl.debug.GLDrawable" @@ -120,11 +120,9 @@ function jrun() { #D_ARGS="-Dnativewindow.debug.ToolkitLock.TraceLock" #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLCode -Djogl.debug.TraceGL" #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLState" - #D_ARGS="-Djogamp.debug.JARUtil" - #D_ARGS="-Djogamp.debug.TempFileCache" - #D_ARGS="-Djogamp.debug.JNILibLoader -Djogamp.debug.TempFileCache -Djogamp.debug.JARUtil" - #D_ARGS="-Djogamp.debug.JNILibLoader" - #D_ARGS="-Djogamp.debug.JNILibLoader -Djogamp.gluegen.UseTempJarCache=false -Djogamp.debug.JARUtil" + #D_ARGS="-Djogamp.debug.JNILibLoader -Djogamp.debug.TempJarCache -Djogamp.debug.JarUtil" + #D_ARGS="-Djogamp.debug.JNILibLoader -Djogamp.debug.TempFileCache -Djogamp.debug.TempJarCache -Djogamp.debug.JarUtil" + #D_ARGS="-Djogamp.debug.JNILibLoader -Djogamp.debug.TempFileCache -Djogamp.debug.TempJarCache -Djogamp.debug.JarUtil -Djogamp.gluegen.UseTempJarCache=false" #D_ARGS="-Dnewt.test.EDTMainThread -Dnewt.debug.MainThread" #C_ARG="com.jogamp.newt.util.MainThread" #D_ARGS="-Dnewt.debug.MainThread" @@ -143,6 +141,8 @@ function jrun() { X_ARGS="-Djava.awt.headless=false $X_ARGS" else export CLASSPATH=$JOGAMP_ALL_NOAWT_CLASSPATH + #export CLASSPATH=$JOGAMP_MOBILE_CLASSPATH + #export CLASSPATH=.:$GLUEGEN_JAR:$JOGL_BUILD_DIR/jar/atomic/jogl-core.jar:$JOGL_BUILD_DIR/jar/atomic/jogl-gldesktop.jar:$JOGL_BUILD_DIR/jar/atomic/jogl-os-x11.jar:$JOGL_BUILD_DIR/jar/atomic/jogl-util.jar:$JOGL_BUILD_DIR/jar/atomic/nativewindow-core.jar:$JOGL_BUILD_DIR/jar/atomic/nativewindow-os-x11.jar:$JOGL_BUILD_DIR/jar/atomic/newt-core.jar:$JOGL_BUILD_DIR/jar/atomic/newt-driver-x11.jar:$JOGL_BUILD_DIR/jar/atomic/newt-ogl.jar:$JOGL_BUILD_DIR/jar/jogl-test.jar:$SWT_CLASSPATH:$JUNIT_JAR:$ANT_JARS X_ARGS="-Djava.awt.headless=true $X_ARGS" fi if [ $swton -eq 1 ] ; then @@ -332,8 +332,8 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestTexture01AWT #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGTextureFromFileAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGTextureFromFileNEWT $* -testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite01AWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite01NEWT $* +#testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite01AWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestTextureSequence01NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestTextureSequence01AWT $* diff --git a/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java b/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java index d901096bc..d160eccff 100644 --- a/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java @@ -47,8 +47,8 @@ public class CgDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { Platform.initSingleton(); if(TempJarCache.isInitialized()) { - // Cg class and natives are available in their single atomic JAR files only - JNILibLoaderBase.addNativeJarLibs(CgDynamicLibraryBundleInfo.class, "jogl_cg", null); + // only: jogl-cg.jar -> jogl-cg-natives-.jar [atomic JAR files only] + JNILibLoaderBase.addNativeJarLibs(new Class[] { CgDynamicLibraryBundleInfo.class }, null, null ); } return null; } diff --git a/src/jogl/classes/javax/media/opengl/GLProfile.java b/src/jogl/classes/javax/media/opengl/GLProfile.java index f85c6ba23..ed457b0ea 100644 --- a/src/jogl/classes/javax/media/opengl/GLProfile.java +++ b/src/jogl/classes/javax/media/opengl/GLProfile.java @@ -37,6 +37,7 @@ package javax.media.opengl; +import jogamp.nativewindow.NWJNILibLoader; import jogamp.opengl.Debug; import jogamp.opengl.GLDrawableFactoryImpl; import jogamp.opengl.DesktopGLDynamicLookupHelper; @@ -133,11 +134,17 @@ public class GLProfile { Platform.initSingleton(); if(TempJarCache.isInitialized()) { - String[] atomicNativeJarBaseNames = new String[] { "nativewindow", "jogl", null }; - if( ReflectionUtil.isClassAvailable("com.jogamp.newt.NewtFactory", GLProfile.class.getClassLoader()) ) { - atomicNativeJarBaseNames[2] = "newt"; + final ClassLoader cl = GLProfile.class.getClassLoader(); + // either: [jogl-all.jar, jogl-all-noawt.jar, jogl-all-mobile.jar] -> jogl-all-natives-.jar + // or: nativewindow-core.jar -> nativewindow-natives-.jar, + // jogl-core.jar -> jogl-natives-.jar, + // (newt-core.jar -> newt-natives-.jar)? (if available) + final String newtFactoryClassName = "com.jogamp.newt.NewtFactory"; + final Class[] classesFromJavaJars = new Class[] { NWJNILibLoader.class, GLProfile.class, null }; + if( ReflectionUtil.isClassAvailable(newtFactoryClassName, cl) ) { + classesFromJavaJars[2] = ReflectionUtil.getClass(newtFactoryClassName, false, cl); } - JNILibLoaderBase.addNativeJarLibs(GLProfile.class, "jogl-all", atomicNativeJarBaseNames); + JNILibLoaderBase.addNativeJarLibs(classesFromJavaJars, "-all", new String[] { "-noawt", "-mobile", "-core" } ); } initProfilesForDefaultDevices(firstUIActionOnProcess); return null; @@ -1497,8 +1504,10 @@ public class GLProfile { System.err.println("GLProfile.init hasGLES1Impl "+hasGLES1Impl); System.err.println("GLProfile.init hasGLES2Impl "+hasGLES2Impl); System.err.println("GLProfile.init defaultDevice "+defaultDevice); - System.err.println("GLProfile.init profile order "+array2String(GL_PROFILE_LIST_ALL)); - System.err.println(JoglVersion.getDefaultOpenGLInfo(null)); + System.err.println("GLProfile.init profile order "+array2String(GL_PROFILE_LIST_ALL)); + if(hasGL234Impl || hasGLES1Impl || hasGLES2Impl) { // avoid deadlock + System.err.println(JoglVersion.getDefaultOpenGLInfo(null)); + } } } @@ -1527,7 +1536,7 @@ public class GLProfile { boolean isSet = GLContext.getAvailableGLVersionsSet(device); if(DEBUG) { - System.err.println("Info: GLProfile.initProfilesForDevice: "+device+", isSet "+isSet); + System.err.println("Info: GLProfile.initProfilesForDevice: "+device+" ("+device.getClass().getName()+"), isSet "+isSet+", hasDesktopGLFactory "+hasDesktopGLFactory+", hasEGLFactory "+hasEGLFactory); } if(isSet) { // Avoid recursion and check whether impl. is sane! @@ -1901,9 +1910,14 @@ public class GLProfile { { initSingleton(); + if(null==defaultDevice) { // avoid NPE and notify of incomplete initialization + throw new GLException("No default device available"); + } + if(null==device) { device = defaultDevice; } + final String deviceKey = device.getUniqueID(); HashMap map = deviceConn2ProfileMap.get(deviceKey); if( null != map ) { diff --git a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java index 99bc71c4a..6c15f9a2b 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java @@ -44,7 +44,9 @@ public class NWJNILibLoader extends JNILibLoaderBase { Platform.initSingleton(); final String libName = "nativewindow_"+ossuffix ; if(TempJarCache.isInitialized() && null == TempJarCache.findLibrary(libName)) { - addNativeJarLibs(NWJNILibLoader.class, "jogl-all", new String[] { "nativewindow" } ); + // either: [jogl-all.jar, jogl-all-noawt.jar, jogl-all-mobile.jar] -> jogl-all-natives-.jar + // or: nativewindow-core.jar -> nativewindow-natives-.jar + addNativeJarLibs(new Class[] { NWJNILibLoader.class }, "-all", new String[] { "-noawt", "-mobile", "-core" } ); } return new Boolean(loadLibrary(libName, false, NWJNILibLoader.class.getClassLoader())); } diff --git a/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java b/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java index 2db9d8d05..bc0eb7531 100644 --- a/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java +++ b/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java @@ -42,6 +42,8 @@ package jogamp.newt; import java.security.AccessController; import java.security.PrivilegedAction; +import jogamp.nativewindow.NWJNILibLoader; + import com.jogamp.common.jvm.JNILibLoaderBase; import com.jogamp.common.os.Platform; import com.jogamp.common.util.cache.TempJarCache; @@ -54,7 +56,10 @@ public class NEWTJNILibLoader extends JNILibLoaderBase { Platform.initSingleton(); final String libName = "newt"; if(TempJarCache.isInitialized() && null == TempJarCache.findLibrary(libName)) { - addNativeJarLibs(NEWTJNILibLoader.class, "jogl-all", new String[] { "nativewindow", "newt" } ); + // either: [jogl-all.jar, jogl-all-noawt.jar, jogl-all-mobile.jar] -> jogl-all-natives-.jar + // or: nativewindow-core.jar -> nativewindow-natives-.jar, + // newt-core.jar -> newt-natives-.jar + JNILibLoaderBase.addNativeJarLibs(new Class[] { NWJNILibLoader.class, NEWTJNILibLoader.class }, "-all", new String[] { "-noawt", "-mobile", "-core" } ); } loadLibrary(libName, false, NEWTJNILibLoader.class.getClassLoader()); return null; -- cgit v1.2.3 From a06e40cce89615eb8c4b080842997c9c3ad1130b Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 27 Jun 2012 05:05:36 +0200 Subject: NativeSurface Cleanup (API Change) - Adapt to GlueGen Lock cleanup commit: 834b9e530e652b7ff7c5e222720bce3ad2b11c5f - adapt to GlueGen Lock cleanup - remove isSurfaceLocked(), use 'null != getSurfaceLockOwner()' instead Misc: - remove unused priv./impl. methods - add @Override --- src/jogl/classes/jogamp/opengl/GLContextImpl.java | 6 +- src/jogl/classes/jogamp/opengl/GLDrawableImpl.java | 4 - src/jogl/classes/jogamp/opengl/GLPbufferImpl.java | 4 - .../com/jogamp/nativewindow/awt/JAWTWindow.java | 139 ++++++++++++--------- .../javax/media/nativewindow/NativeSurface.java | 15 +-- .../javax/media/nativewindow/ProxySurface.java | 34 +++-- .../classes/com/jogamp/newt/opengl/GLWindow.java | 8 +- src/newt/classes/jogamp/newt/WindowImpl.java | 34 +++-- 8 files changed, 134 insertions(+), 110 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index 51201b3a9..ff1b65520 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -164,7 +164,7 @@ public abstract class GLContextImpl extends GLContext { if(null!=read && drawable!=read && !isGLReadDrawableAvailable()) { throw new GLException("GL Read Drawable not available"); } - boolean lockHeld = lock.isOwner(); + final boolean lockHeld = lock.isOwner(Thread.currentThread()); if(lockHeld) { release(); } @@ -224,8 +224,8 @@ public abstract class GLContextImpl extends GLContext { if(TRACE_SWITCH) { System.err.println(getThreadName() +": GLContext.ContextSwitch: - release() - force: "+force+", "+lock); } - if ( !lock.isOwner() ) { - throw new GLException("Context not current on current thread "+Thread.currentThread().getName()+": "+this); + if ( !lock.isOwner(Thread.currentThread()) ) { + throw new GLException("Context not current on current thread "+Thread.currentThread().getName()+": "+this); } final boolean actualRelease = force || lock.getHoldCount() == 1 ; try { diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java index 36f17e5a1..71624789d 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java @@ -199,10 +199,6 @@ public abstract class GLDrawableImpl implements GLDrawable { surface.unlockSurface(); } - public boolean isSurfaceLocked() { - return surface.isSurfaceLocked(); - } - public String toString() { return getClass().getSimpleName()+"[Realized "+isRealized()+ ",\n\tFactory "+getFactory()+ diff --git a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java index 0f4f7f8e2..9a4cf1f94 100644 --- a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java @@ -267,10 +267,6 @@ public class GLPbufferImpl implements GLPbuffer { recurLock.unlock(); } - public boolean isSurfaceLocked() { - return recurLock.isLocked(); - } - public int getFloatingPointMode() { if (floatMode == 0) { throw new GLException("Pbuffer not initialized, or floating-point support not requested"); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 02dd746a0..3437358de 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,7 +29,7 @@ * 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. @@ -67,7 +67,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, // user properties protected boolean shallUseOffscreenLayer = false; - + // lifetime: forever protected Component component; private AWTGraphicsConfiguration config; // control access due to delegation @@ -81,13 +81,13 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected long drawable; protected Rectangle bounds; protected Insets insets; - + private long drawable_old; - + /** * Constructed by {@link jogamp.nativewindow.NativeWindowFactoryImpl#getNativeWindow(Object, AbstractGraphicsConfiguration)} * via this platform's specialization (X11, OSX, Windows, ..). - * + * * @param comp * @param config */ @@ -107,19 +107,22 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, this.component = windowObject; this.isApplet = false; } - + + @Override public void setShallUseOffscreenLayer(boolean v) { shallUseOffscreenLayer = v; } - + + @Override public final boolean getShallUseOffscreenLayer() { return shallUseOffscreenLayer; } - - public final boolean isOffscreenLayerSurfaceEnabled() { + + @Override + public final boolean isOffscreenLayerSurfaceEnabled() { return isOffscreenLayerSurface; } - + protected synchronized void invalidate() { invalidateNative(); jawt = null; @@ -136,7 +139,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, bounds.setY(jawtBounds.getY()); bounds.setWidth(jawtBounds.getWidth()); bounds.setHeight(jawtBounds.getHeight()); - + if(component instanceof Container) { java.awt.Insets contInsets = ((Container)component).getInsets(); insets.setLeftWidth(contInsets.left); @@ -148,16 +151,17 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, /** @return the JAWT_DrawingSurfaceInfo's (JAWT_Rectangle) bounds, updated with lock */ public final RectangleImmutable getBounds() { return bounds; } - + + @Override public final InsetsImmutable getInsets() { return insets; } public final Component getAWTComponent() { return component; } - - /** - * Returns true if the AWT component is parented to an {@link java.applet.Applet}, - * otherwise false. This information is valid only after {@link #lockSurface()}. + + /** + * Returns true if the AWT component is parented to an {@link java.applet.Applet}, + * otherwise false. This information is valid only after {@link #lockSurface()}. */ public final boolean isApplet() { return isApplet; @@ -168,10 +172,11 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return jawt; } - /** + /** * {@inheritDoc} */ - public final void attachSurfaceLayer(final long layerHandle) throws NativeWindowException { + @Override + public final void attachSurfaceLayer(final long layerHandle) throws NativeWindowException { if( !isOffscreenLayerSurfaceEnabled() ) { throw new NativeWindowException("Not an offscreen layer surface"); } @@ -187,13 +192,14 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } finally { unlockSurface(); } - } + } protected abstract void attachSurfaceLayerImpl(final long layerHandle); - - /** + + /** * {@inheritDoc} */ - public final void detachSurfaceLayer(final long layerHandle) throws NativeWindowException { + @Override + public final void detachSurfaceLayer(final long layerHandle) throws NativeWindowException { if( !isOffscreenLayerSurfaceEnabled() ) { throw new java.lang.UnsupportedOperationException("Not an offscreen layer surface"); } @@ -209,29 +215,33 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } finally { unlockSurface(); } - } + } protected abstract void detachSurfaceLayerImpl(final long layerHandle); - + // // SurfaceUpdateListener // + @Override public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { surfaceUpdatedHelper.addSurfaceUpdatedListener(l); } + @Override public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); } + @Override public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); } + @Override public void surfaceUpdated(Object updater, NativeSurface ns, long when) { surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); - } - + } + // // NativeSurface // @@ -243,14 +253,14 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, c = c.getParent(); } } - + /** - * If JAWT offscreen layer is supported, + * If JAWT offscreen layer is supported, * implementation shall respect {@link #getShallUseOffscreenLayer()} * and may respect {@link #isApplet()}. - * + * * @return The JAWT instance reflecting offscreen layer support, etc. - * + * * @throws NativeWindowException */ protected abstract JAWT fetchJAWTImpl() throws NativeWindowException; @@ -266,7 +276,8 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } // Thread.dumpStack(); } - + + @Override public final int lockSurface() throws NativeWindowException { surfaceLock.lock(); int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? @@ -282,7 +293,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, res = lockSurfaceImpl(); if(LOCK_SUCCESS == res && drawable_old != drawable) { res = LOCK_SURFACE_CHANGED; - if(DEBUG) { + if(DEBUG) { System.err.println("JAWTWindow: surface change 0x"+Long.toHexString(drawable_old)+" -> 0x"+Long.toHexString(drawable)); // Thread.dumpStack(); } @@ -303,6 +314,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected abstract void unlockSurfaceImpl() throws NativeWindowException; + @Override public final void unlockSurface() { surfaceLock.validateLocked(); drawable_old = drawable; @@ -318,46 +330,51 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, surfaceLock.unlock(); } + @Override public final boolean isSurfaceLockedByOtherThread() { return surfaceLock.isLockedByOtherThread(); } - public final boolean isSurfaceLocked() { - return surfaceLock.isLocked(); - } - + @Override public final Thread getSurfaceLockOwner() { return surfaceLock.getOwner(); } + @Override public boolean surfaceSwap() { return false; } + @Override public long getSurfaceHandle() { return drawable; } - + public final AWTGraphicsConfiguration getPrivateGraphicsConfiguration() { return config; } - + + @Override public final AbstractGraphicsConfiguration getGraphicsConfiguration() { return config.getNativeGraphicsConfiguration(); } + @Override public final long getDisplayHandle() { return getGraphicsConfiguration().getScreen().getDevice().getHandle(); } + @Override public final int getScreenIndex() { return getGraphicsConfiguration().getScreen().getIndex(); } + @Override public int getWidth() { return component.getWidth(); } + @Override public int getHeight() { return component.getHeight(); } @@ -366,41 +383,47 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, // NativeWindow // + @Override public synchronized void destroy() { - invalidate(); - component = null; // don't dispose the AWT component, since we are merely an immutable uplink + invalidate(); + component = null; // don't dispose the AWT component, since we are merely an immutable uplink } + @Override public final NativeWindow getParent() { return null; } + @Override public long getWindowHandle() { return drawable; } - + + @Override public final int getX() { return component.getX(); } + @Override public final int getY() { return component.getY(); } - + /** * {@inheritDoc} - * + * *

- * This JAWT default implementation is currently still using + * This JAWT default implementation is currently still using * a blocking implementation. It first attempts to retrieve the location * via a native implementation. If this fails, it tries the blocking AWT implementation. - * If the latter fails due to an external AWT tree-lock, the non block + * If the latter fails due to an external AWT tree-lock, the non block * implementation {@link #getLocationOnScreenNonBlocking(Point, Component)} is being used. * The latter simply traverse up to the AWT component tree and sums the rel. position. * We have to determine whether the latter is good enough for all cases, * currently only OS X utilizes the non blocking method per default. - *

+ *

*/ + @Override public Point getLocationOnScreen(Point storage) { Point los = getLocationOnScreenNative(storage); if(null == los) { @@ -421,7 +444,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } return los; } - + protected Point getLocationOnScreenNative(Point storage) { int lockRes = lockSurface(); if(LOCK_SURFACE_NOT_READY == lockRes) { @@ -442,12 +465,12 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return d; } finally { unlockSurface(); - } + } } protected abstract Point getLocationOnScreenNativeImpl(int x, int y); - protected static Point getLocationOnScreenNonBlocking(Point storage, Component comp) { - int x = 0; + protected static Point getLocationOnScreenNonBlocking(Point storage, Component comp) { + int x = 0; int y = 0; while(null != comp) { x += comp.getX(); @@ -460,11 +483,12 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } return new Point(x, y); } - + + @Override public boolean hasFocus() { return component.hasFocus(); } - + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -487,5 +511,4 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return sb.toString(); } - } diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java index b7829cb6d..c58b34b18 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java @@ -104,15 +104,16 @@ public interface NativeSurface extends SurfaceUpdatedListener { public void unlockSurface() throws NativeWindowException ; /** - * Return if surface is locked by another thread, ie not the current one + * Query if surface is locked by another thread, i.e. not the current one. + *
+ * Convenient shortcut for: + *
+   *   final Thread o = getSurfaceLockOwner();
+   *   if( null != o && Thread.currentThread() != o ) { .. }
+   * 
*/ public boolean isSurfaceLockedByOtherThread(); - - /** - * Return if surface is locked - */ - public boolean isSurfaceLocked(); - + /** * Return the locking owner's Thread, or null if not locked. */ diff --git a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java index 6a36bb130..c8cd78d82 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java @@ -37,7 +37,7 @@ import com.jogamp.common.util.locks.RecursiveLock; public abstract class ProxySurface implements NativeSurface { public static final boolean DEBUG = Debug.debug("ProxySurface"); - + private SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); private AbstractGraphicsConfiguration config; // control access due to delegation protected RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); @@ -60,6 +60,7 @@ public abstract class ProxySurface implements NativeSurface { } protected abstract void invalidateImpl(); + @Override public final long getDisplayHandle() { return displayHandle; } @@ -67,21 +68,26 @@ public abstract class ProxySurface implements NativeSurface { protected final AbstractGraphicsConfiguration getPrivateGraphicsConfiguration() { return config; } - + + @Override public final AbstractGraphicsConfiguration getGraphicsConfiguration() { return config.getNativeGraphicsConfiguration(); } + @Override public final int getScreenIndex() { return getGraphicsConfiguration().getScreen().getIndex(); } + @Override public abstract long getSurfaceHandle(); + @Override public final int getWidth() { return width; } + @Override public final int getHeight() { return height; } @@ -91,26 +97,32 @@ public abstract class ProxySurface implements NativeSurface { this.height = height; } + @Override public boolean surfaceSwap() { return false; } + @Override public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { surfaceUpdatedHelper.addSurfaceUpdatedListener(l); } + @Override public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); } + @Override public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); } + @Override public void surfaceUpdated(Object updater, NativeSurface ns, long when) { surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); - } - + } + + @Override public int lockSurface() throws NativeWindowException { surfaceLock.lock(); int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? @@ -123,11 +135,11 @@ public abstract class ProxySurface implements NativeSurface { res = lockSurfaceImpl(); if(LOCK_SUCCESS == res && surfaceHandle_old != getSurfaceHandle()) { res = LOCK_SURFACE_CHANGED; - if(DEBUG) { + if(DEBUG) { System.err.println("ProxySurface: surface change 0x"+Long.toHexString(surfaceHandle_old)+" -> 0x"+Long.toHexString(getSurfaceHandle())); // Thread.dumpStack(); } - } + } } finally { if (LOCK_SURFACE_NOT_READY >= res) { adevice.unlock(); @@ -142,6 +154,7 @@ public abstract class ProxySurface implements NativeSurface { return res; } + @Override public final void unlockSurface() { surfaceLock.validateLocked(); surfaceHandle_old = getSurfaceHandle(); @@ -165,17 +178,16 @@ public abstract class ProxySurface implements NativeSurface { surfaceLock.validateLocked(); } - public final boolean isSurfaceLocked() { - return surfaceLock.isLocked(); - } - + @Override public final boolean isSurfaceLockedByOtherThread() { return surfaceLock.isLockedByOtherThread(); } + @Override public final Thread getSurfaceLockOwner() { return surfaceLock.getOwner(); } - public abstract String toString(); + @Override + public abstract String toString(); } diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index a3adf5090..1832d4e99 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -842,22 +842,22 @@ public class GLWindow implements GLAutoDrawable, Window, NEWTEventConsumer, FPSC // NativeWindow completion // + @Override public final int lockSurface() { return window.lockSurface(); } + @Override public final void unlockSurface() throws NativeWindowException { window.unlockSurface(); } + @Override public final boolean isSurfaceLockedByOtherThread() { return window.isSurfaceLockedByOtherThread(); } - public final boolean isSurfaceLocked() { - return window.isSurfaceLocked(); - } - + @Override public final Thread getSurfaceLockOwner() { return window.getSurfaceLockOwner(); diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index 73bd9ed1c..baad77ffb 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -562,6 +562,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // NativeSurface // + @Override public final int lockSurface() { windowLock.lock(); surfaceLock.lock(); @@ -590,6 +591,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer return res; } + @Override public final void unlockSurface() { surfaceLock.validateLocked(); windowLock.validateLocked(); @@ -606,30 +608,24 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer windowLock.unlock(); } - public final boolean isWindowLockedByOtherThread() { - return windowLock.isLockedByOtherThread(); - } - - public final boolean isWindowLocked() { - return windowLock.isLocked(); - } - - public final Thread getWindowLockOwner() { - return windowLock.getOwner(); - } - + @Override public final boolean isSurfaceLockedByOtherThread() { return surfaceLock.isLockedByOtherThread(); } - public final boolean isSurfaceLocked() { - return surfaceLock.isLocked(); - } - + @Override public final Thread getSurfaceLockOwner() { return surfaceLock.getOwner(); } + public final boolean isWindowLockedByOtherThread() { + return windowLock.isLockedByOtherThread(); + } + + public final Thread getWindowLockOwner() { + return windowLock.getOwner(); + } + public long getSurfaceHandle() { return windowHandle; // default: return window handle } @@ -1574,7 +1570,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } public void runOnEDTIfAvail(boolean wait, final Runnable task) { - if(windowLock.isOwner()) { + if(windowLock.isOwner(Thread.currentThread())) { task.run(); } else { Screen scrn = getScreen(); @@ -1913,7 +1909,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // special repaint treatment case WindowEvent.EVENT_WINDOW_REPAINT: // queue repaint event in case window is locked, ie in operation - if( isWindowLocked() ) { + if( null != getWindowLockOwner() ) { // make sure only one repaint event is queued if(!repaintQueued) { repaintQueued=true; @@ -1932,7 +1928,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // common treatment case WindowEvent.EVENT_WINDOW_RESIZED: // queue event in case window is locked, ie in operation - if( isWindowLocked() ) { + if( null != getWindowLockOwner() ) { final boolean discardTO = QUEUED_EVENT_TO <= System.currentTimeMillis()-e.getWhen(); if(DEBUG_IMPLEMENTATION) { System.err.println("Window.consumeEvent: "+Thread.currentThread().getName()+" - queued "+e+", discard-to "+discardTO); -- cgit v1.2.3 From 6bff43023b630d7e9f413e39821ebf89c40a399a Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 27 Jun 2012 05:06:07 +0200 Subject: Misc cleanup: add @Override --- .../com/jogamp/opengl/util/AnimatorBase.java | 2 +- .../com/jogamp/nativewindow/WrappedSurface.java | 14 +++- .../javax/media/nativewindow/NativeWindow.java | 60 +++++++-------- .../jogamp/nativewindow/windows/GDISurface.java | 5 ++ src/newt/classes/com/jogamp/newt/Window.java | 87 +++++++++++----------- 5 files changed, 90 insertions(+), 78 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java b/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java index d65967da1..46fc1d991 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java +++ b/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java @@ -208,6 +208,6 @@ public abstract class AnimatorBase implements GLAnimatorControl { } public String toString() { - return getClass().getName()+"[started "+isStarted()+", animating "+isAnimating()+", paused "+isPaused()+", drawable "+drawables.size()+"]"; + return getClass().getName()+"[started "+isStarted()+", animating "+isAnimating()+", paused "+isPaused()+", drawable "+drawables.size()+", totals[dt "+getTotalFPSDuration()+", frames "+getTotalFPSFrames()+", fps "+getTotalFPS()+"]]"; } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java b/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java index f2993abab..04f616daf 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java @@ -44,30 +44,36 @@ public class WrappedSurface extends ProxySurface implements SurfaceChangeable { super(cfg); surfaceHandle=handle; } - + + @Override protected final void invalidateImpl() { surfaceHandle = 0; } + @Override final public long getSurfaceHandle() { return surfaceHandle; } + @Override final public void setSurfaceHandle(long surfaceHandle) { this.surfaceHandle=surfaceHandle; } + @Override final protected int lockSurfaceImpl() { return LOCK_SUCCESS; } + @Override final protected void unlockSurfaceImpl() { } + @Override public String toString() { - return "WrappedSurface[config " + getPrivateGraphicsConfiguration()+ - ", displayHandle 0x" + Long.toHexString(getDisplayHandle()) + - ", surfaceHandle 0x" + Long.toHexString(getSurfaceHandle()) + + return "WrappedSurface[config " + getPrivateGraphicsConfiguration()+ + ", displayHandle 0x" + Long.toHexString(getDisplayHandle()) + + ", surfaceHandle 0x" + Long.toHexString(getSurfaceHandle()) + ", size " + getWidth() + "x" + getHeight() + ", surfaceLock "+surfaceLock+"]"; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java index 2bc352116..12e202975 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -52,8 +52,8 @@ import javax.media.nativewindow.util.Point; which can create NativeWindow objects for its components.

*/ public interface NativeWindow extends NativeSurface { - - /** + + /** * destroys the window and releases * windowing related resources. */ @@ -67,63 +67,63 @@ public interface NativeWindow extends NativeSurface { /** * Returns the window handle for this NativeWindow.

* - * The window handle shall reflect the platform one + * The window handle shall reflect the platform one * for all window related operations, e.g. open, close, resize.

* * On X11 this returns an entity of type Window.
- * On Microsoft Windows this returns an entity of type HWND. + * On Microsoft Windows this returns an entity of type HWND. */ public long getWindowHandle(); - /** + /** * Returns the insets defined as the width and height of the window decoration * on the left, right, top and bottom.
* Insets are zero if the window is undecorated, including child windows. - * + * *

* Insets are available only after the native window has been created, * ie. the native window has been made visible.
- * + * * The top-level window area's top-left corner is located at *

    *   getX() - getInsets().{@link InsetsImmutable#getLeftWidth() getLeftWidth()}
    *   getY() - getInsets().{@link InsetsImmutable#getTopHeight() getTopHeight()}
-   * 
- * + * + * * The top-level window size is *
-   *   getWidth()  + getInsets().{@link InsetsImmutable#getTotalWidth() getTotalWidth()} 
+   *   getWidth()  + getInsets().{@link InsetsImmutable#getTotalWidth() getTotalWidth()}
    *   getHeight() + getInsets().{@link InsetsImmutable#getTotalHeight() getTotalHeight()}
-   * 
- * + * + * * @return insets */ public InsetsImmutable getInsets(); - + /** Returns the current x position of this window, relative to it's parent. */ - - /** + + /** * @return the current x position of the top-left corner - * of the client area relative to it's parent. + * of the client area relative to it's parent. * Since the position reflects the client area, it does not include the insets. * @see #getInsets() */ public int getX(); - /** + /** * @return the current y position of the top-left corner - * of the client area relative to it's parent. + * of the client area relative to it's parent. * Since the position reflects the client area, it does not include the insets. * @see #getInsets() */ public int getY(); - /** - * Returns the current position of the top-left corner + /** + * Returns the current position of the top-left corner * of the client area in screen coordinates. *

* Since the position reflects the client area, it does not include the insets. - *

+ *

* @param point if not null, * {@link javax.media.nativewindow.util.Point#translate(javax.media.nativewindow.util.Point)} * the passed {@link javax.media.nativewindow.util.Point} by this location on the screen and return it. @@ -131,8 +131,8 @@ public interface NativeWindow extends NativeSurface { * or a new instance with the screen location of this NativeWindow. */ public Point getLocationOnScreen(Point point); - + /** Returns true if this native window owns the focus, otherwise false. */ boolean hasFocus(); - + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java index bc02ac5dc..4da48bdae 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java @@ -51,11 +51,13 @@ public class GDISurface extends ProxySurface { this.windowHandle=windowHandle; } + @Override protected final void invalidateImpl() { windowHandle=0; surfaceHandle=0; } + @Override final protected int lockSurfaceImpl() { if (0 != surfaceHandle) { throw new InternalError("surface not released"); @@ -70,6 +72,7 @@ public class GDISurface extends ProxySurface { return (0 != surfaceHandle) ? LOCK_SUCCESS : LOCK_SURFACE_NOT_READY; } + @Override final protected void unlockSurfaceImpl() { if (0 == surfaceHandle) { throw new InternalError("surface not acquired: "+this+", thread: "+Thread.currentThread().getName()); @@ -80,10 +83,12 @@ public class GDISurface extends ProxySurface { surfaceHandle=0; } + @Override final public long getSurfaceHandle() { return surfaceHandle; } + @Override final public String toString() { return "GDISurface[config "+getPrivateGraphicsConfiguration()+ ", displayHandle 0x"+Long.toHexString(getDisplayHandle())+ diff --git a/src/newt/classes/com/jogamp/newt/Window.java b/src/newt/classes/com/jogamp/newt/Window.java index 136c19ff8..71e86d520 100644 --- a/src/newt/classes/com/jogamp/newt/Window.java +++ b/src/newt/classes/com/jogamp/newt/Window.java @@ -71,7 +71,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { /** * Set the CapabilitiesChooser to help determine the native visual type. - * + * * @param chooser the new CapabilitiesChooser * @return the previous CapabilitiesChooser */ @@ -86,7 +86,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { /** * Gets an immutable set of chosen capabilities. - * + * * @return the chosen capabilities */ CapabilitiesImmutable getChosenCapabilities(); @@ -103,6 +103,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { * @see #destroy() * @see #setVisible(boolean) */ + @Override void destroy(); /** @@ -135,14 +136,14 @@ public interface Window extends NativeWindow, WindowClosingProtocol { boolean isVisible(); - /** - * If the implementation uses delegation, return the delegated {@link Window} instance, + /** + * If the implementation uses delegation, return the delegated {@link Window} instance, * otherwise return this instance. */ Window getDelegatedWindow(); - + // // Child Window Management - // + // boolean addChild(NativeWindow win); @@ -154,7 +155,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { /** * Sets the size of the window's client area, excluding decorations. - * + * *

* Zero size semantics are respected, see {@link #setVisible(boolean)}:
*

@@ -171,72 +172,72 @@ public interface Window extends NativeWindow, WindowClosingProtocol {
      *
      * @param width of the window's client area
      * @param height of the window's client area
-     * 
+     *
      * @see #getInsets()
      */
     void setSize(int width, int height);
 
     /**
      * Sets the size of the top-level window including insets (window decorations).
-     * 
+     *
      * 

* Note: Insets (if supported) are available only after the window is set visible and hence has been created. *

* * @param width of the top-level window area * @param height of the top-level window area - * + * * @see #setSize(int, int) * @see #getInsets() */ void setTopLevelSize(int width, int height); - + /** * Sets the location of the window's client area, excluding insets (window decorations).
- * + * * This call is ignored if in fullscreen mode.
* * @param x coord of the client-area's top left corner * @param y coord of the client-area's top left corner - * + * * @see #getInsets() */ void setPosition(int x, int y); - + /** * Sets the location of the top-level window inclusive insets (window decorations).
- * + * *

* Note: Insets (if supported) are available only after the window is set visible and hence has been created. *

- * + * * This call is ignored if in fullscreen mode.
* * @param x coord of the top-level left corner * @param y coord of the top-level left corner - * + * * @see #setPosition(int, int) * @see #getInsets() */ void setTopLevelPosition(int x, int y); void setUndecorated(boolean value); - + boolean isUndecorated(); - + void setAlwaysOnTop(boolean value); - + boolean isAlwaysOnTop(); - + void setTitle(String title); String getTitle(); boolean isPointerVisible(); - + /** * Makes the pointer visible or invisible. - * + * * @param pointerVisible defaults to true for platforms w/ visible pointer, * otherwise defaults to true, eg. Android. * @see #confinePointer(boolean) @@ -244,32 +245,32 @@ public interface Window extends NativeWindow, WindowClosingProtocol { void setPointerVisible(boolean pointerVisible); boolean isPointerConfined(); - + /** * Confine the pointer to this window, ie. pointer jail. *

- * Before jailing the mouse pointer, + * Before jailing the mouse pointer, * the window request the focus and the pointer is centered in the window. *

*

- * In combination w/ {@link #warpPointer(int, int)} + * In combination w/ {@link #warpPointer(int, int)} * and maybe {@link #setPointerVisible(boolean)} a simple mouse * navigation can be realized.

- * + * * @param confine defaults to false. */ void confinePointer(boolean confine); - + /** * Moves the pointer to x/y relative to this window's origin. - * + * * @param x relative pointer x position within this window * @param y relative pointer y position within this window - * + * * @see #confinePointer(boolean) */ void warpPointer(int x, int y); - + /** Reparenting operation types */ public enum ReparentOperation { /** No native reparenting valid */ @@ -285,7 +286,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { ACTION_NATIVE_CREATION, /** Change Window tree only, native creation is pending */ - ACTION_NATIVE_CREATION_PENDING; + ACTION_NATIVE_CREATION_PENDING; } /** @@ -305,7 +306,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { ReparentOperation reparentWindow(NativeWindow newParent, boolean forceDestroyCreate); boolean setFullscreen(boolean fullscreen); - + boolean isFullscreen(); static interface FocusRunnable { @@ -317,7 +318,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { } /** - * Sets a {@link FocusRunnable}, + * Sets a {@link FocusRunnable}, * which {@link FocusRunnable#run()} method is executed before the native focus is requested. *

* This allows notifying a covered window toolkit like AWT that the focus is requested, @@ -325,7 +326,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { *

*/ void setFocusAction(FocusRunnable focusAction); - + /** * Sets a {@link KeyListener} allowing focus traversal with a covered window toolkit like AWT. *

@@ -336,27 +337,27 @@ public interface Window extends NativeWindow, WindowClosingProtocol { */ void setKeyboardFocusHandler(KeyListener l); - /** + /** * Request focus for this native window *

* The request is handled on this Window EDT and blocked until finished. *

- * + * * @see #requestFocus(boolean) */ void requestFocus(); - /** + /** * Request focus for this native window *

- * The request is handled on this Window EDT. + * The request is handled on this Window EDT. *

- * + * * @param wait true if waiting until the request is executed, otherwise false * @see #requestFocus() */ void requestFocus(boolean wait); - + void windowRepaint(int x, int y, int width, int height); void enqueueEvent(boolean wait, com.jogamp.newt.event.NEWTEvent event); @@ -410,7 +411,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { */ void setKeyboardVisible(boolean visible); - /** + /** * Return true if the virtual on-screen keyboard is visible, otherwise false. *

* Currently on Android, the only supported platform right now, @@ -420,7 +421,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { * @see #setKeyboardVisible(boolean) */ boolean isKeyboardVisible(); - + /** * * Appends the given {@link com.jogamp.newt.event.KeyListener} to the end of -- cgit v1.2.3 From 914b522af26b6d779dc931bf4303be3c7e898eff Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 27 Jun 2012 06:16:09 +0200 Subject: Capabilities cleanup: make most get*() final, impl. Comparable to CapabilitiesImmutable, Misc .. - Comparable to CapabilitiesImmutable: "interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable" -> "interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable, Comparable" - CapabilitiesImmutable and GLCapabilitiesImmutable get-methods final (most) - GLCapabilitiesImmutable.compareTo: add doubleBuffered (between stereo and samples) Misc: - Add @Override - remove trailing whitespace, --- .../classes/javax/media/opengl/GLCapabilities.java | 135 ++++++++++++-------- .../jogamp/opengl/egl/EGLGLCapabilities.java | 25 ++-- .../opengl/windows/wgl/WGLGLCapabilities.java | 15 ++- .../jogamp/opengl/x11/glx/X11GLCapabilities.java | 7 +- .../javax/media/nativewindow/Capabilities.java | 142 ++++++++++++--------- .../media/nativewindow/CapabilitiesImmutable.java | 4 +- .../jogamp/nativewindow/x11/X11Capabilities.java | 7 +- 7 files changed, 198 insertions(+), 137 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilities.java b/src/jogl/classes/javax/media/opengl/GLCapabilities.java index 8b832b310..61ab2e58d 100644 --- a/src/jogl/classes/javax/media/opengl/GLCapabilities.java +++ b/src/jogl/classes/javax/media/opengl/GLCapabilities.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003-2009 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 @@ -29,11 +29,11 @@ * 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. */ @@ -41,6 +41,7 @@ package javax.media.opengl; import javax.media.nativewindow.Capabilities; +import javax.media.nativewindow.CapabilitiesImmutable; /** Specifies a set of OpenGL capabilities.
At creation time of a {@link GLDrawable} using {@link GLDrawableFactory}, @@ -86,10 +87,12 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil glProfile = (null!=glp)?glp:GLProfile.getDefault(GLProfile.getDefaultDevice()); } + @Override public Object cloneMutable() { return clone(); } + @Override public Object clone() { try { return super.clone(); @@ -98,6 +101,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil } } + @Override public int hashCode() { // 31 * x == (x << 5) - x int hash = 31 + this.glProfile.hashCode() ; @@ -119,6 +123,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil return hash; } + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(!(obj instanceof GLCapabilitiesImmutable)) { @@ -142,46 +147,52 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil other.getPbufferRenderToTextureRectangle()==pbufferRenderToTextureRectangle; if(sampleBuffers) { res = res && - other.getNumSamples()==numSamples && + other.getNumSamples()==numSamples && other.getSampleExtension().equals(sampleExtension) ; } return res; } /** comparing hw/sw, stereo, multisample, stencil, RGBA and depth only */ - public int compareTo(Object o) { - if ( ! ( o instanceof GLCapabilities ) ) { + @Override + public int compareTo(final CapabilitiesImmutable o) { + if ( ! ( o instanceof GLCapabilitiesImmutable ) ) { Class c = (null != o) ? o.getClass() : null ; - throw new ClassCastException("Not a GLCapabilities object: " + c); + throw new ClassCastException("Not a GLCapabilitiesImmutable object, but " + c); } + final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) o; - final GLCapabilities caps = (GLCapabilities) o; + if(hardwareAccelerated && !caps.getHardwareAccelerated()) { + return 1; + } else if(!hardwareAccelerated && caps.getHardwareAccelerated()) { + return -1; + } - if(hardwareAccelerated && !caps.hardwareAccelerated) { + if(stereo && !caps.getStereo()) { return 1; - } else if(!hardwareAccelerated && caps.hardwareAccelerated) { + } else if(!stereo && caps.getStereo()) { return -1; } - if(stereo && !caps.stereo) { + if(doubleBuffered && !caps.getDoubleBuffered()) { return 1; - } else if(!stereo && caps.stereo) { + } else if(!doubleBuffered && caps.getDoubleBuffered()) { return -1; } final int ms = sampleBuffers ? numSamples : 0; - final int xms = caps.sampleBuffers ? caps.numSamples : 0; + final int xms = caps.getSampleBuffers() ? caps.getNumSamples() : 0; if(ms > xms) { return 1; } else if( ms < xms ) { return -1; } - // ignore the sample extension + // ignore the sample extension - if(stencilBits > caps.stencilBits) { + if(stencilBits > caps.getStencilBits()) { return 1; - } else if(stencilBits < caps.stencilBits) { + } else if(stencilBits < caps.getStencilBits()) { return -1; } @@ -190,16 +201,17 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil return sc; } - if(depthBits > caps.depthBits) { + if(depthBits > caps.getDepthBits()) { return 1; - } else if(depthBits < caps.depthBits) { + } else if(depthBits < caps.getDepthBits()) { return -1; } return 0; // they are equal: hw/sw, stereo, multisample, stencil, RGBA and depth } - public GLProfile getGLProfile() { + @Override + public final GLProfile getGLProfile() { return glProfile; } @@ -208,11 +220,12 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil glProfile=profile; } - public boolean isPBuffer() { + @Override + public final boolean isPBuffer() { return pbuffer; } - /** + /** * Enables or disables pbuffer usage.
* If enabled this method also invokes {@link #setOnscreen(int) setOnscreen(false)}
* Defaults to false. @@ -229,6 +242,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil * If enabled this method also invokes {@link #setPBuffer(int) setPBuffer(false)}
* Defaults to true. */ + @Override public void setOnscreen(boolean onscreen) { if(onscreen) { setPBuffer(false); @@ -236,7 +250,8 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil super.setOnscreen(onscreen); } - public boolean getDoubleBuffered() { + @Override + public final boolean getDoubleBuffered() { return doubleBuffered; } @@ -245,25 +260,28 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil doubleBuffered = enable; } - public boolean getStereo() { + @Override + public final boolean getStereo() { return stereo; } - + /** Enables or disables stereo viewing. */ public void setStereo(boolean enable) { stereo = enable; } - public boolean getHardwareAccelerated() { + @Override + public final boolean getHardwareAccelerated() { return hardwareAccelerated; } - + /** Enables or disables hardware acceleration. */ public void setHardwareAccelerated(boolean enable) { hardwareAccelerated = enable; } - public int getDepthBits() { + @Override + public final int getDepthBits() { return depthBits; } @@ -271,8 +289,9 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil public void setDepthBits(int depthBits) { this.depthBits = depthBits; } - - public int getStencilBits() { + + @Override + public final int getStencilBits() { return stencilBits; } @@ -280,8 +299,9 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil public void setStencilBits(int stencilBits) { this.stencilBits = stencilBits; } - - public int getAccumRedBits() { + + @Override + public final int getAccumRedBits() { return accumRedBits; } @@ -293,7 +313,8 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil this.accumRedBits = accumRedBits; } - public int getAccumGreenBits() { + @Override + public final int getAccumGreenBits() { return accumGreenBits; } @@ -305,7 +326,8 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil this.accumGreenBits = accumGreenBits; } - public int getAccumBlueBits() { + @Override + public final int getAccumBlueBits() { return accumBlueBits; } @@ -317,7 +339,8 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil this.accumBlueBits = accumBlueBits; } - public int getAccumAlphaBits() { + @Override + public final int getAccumAlphaBits() { return accumAlphaBits; } @@ -333,14 +356,15 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil * Sets the desired extension for full-scene antialiasing * (FSAA), default is {@link #DEFAULT_SAMPLE_EXTENSION}. */ - public void setSampleExtension(String se) { - sampleExtension = se; + public void setSampleExtension(String se) { + sampleExtension = se; } - - public String getSampleExtension() { - return sampleExtension; + + @Override + public final String getSampleExtension() { + return sampleExtension; } - + /** * Defaults to false.
* Indicates whether sample buffers for full-scene antialiasing @@ -353,10 +377,11 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil sampleBuffers = enable; if(sampleBuffers && getAlphaBits()==0) { setAlphaBits(1); - } + } } - public boolean getSampleBuffers() { + @Override + public final boolean getSampleBuffers() { return sampleBuffers; } @@ -366,7 +391,8 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil this.numSamples = numSamples; } - public int getNumSamples() { + @Override + public final int getNumSamples() { return numSamples; } @@ -376,7 +402,8 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil pbufferFloatingPointBuffers = enable; } - public boolean getPbufferFloatingPointBuffers() { + @Override + public final boolean getPbufferFloatingPointBuffers() { return pbufferFloatingPointBuffers; } @@ -386,7 +413,8 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil pbufferRenderToTexture = enable; } - public boolean getPbufferRenderToTexture() { + @Override + public final boolean getPbufferRenderToTexture() { return pbufferRenderToTexture; } @@ -397,10 +425,12 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil pbufferRenderToTextureRectangle = enable; } - public boolean getPbufferRenderToTextureRectangle() { + @Override + public final boolean getPbufferRenderToTextureRectangle() { return pbufferRenderToTextureRectangle; } + @Override public StringBuilder toString(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); @@ -441,12 +471,13 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil sink.append(", pixmap"); } } - + return sink; } /** Returns a textual representation of this GLCapabilities - object. */ + object. */ + @Override public String toString() { StringBuilder msg = new StringBuilder(); msg.append("GLCaps["); diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java b/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java index f813edf86..70a570174 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java @@ -37,17 +37,17 @@ import javax.media.opengl.GLProfile; public class EGLGLCapabilities extends GLCapabilities { private long eglcfg; final private int eglcfgid; - final private int renderableType; + final private int renderableType; final private int nativeVisualID; - + /** - * + * * @param eglcfg * @param eglcfgid * @param visualID native visualID if valid, otherwise VisualIDHolder.VID_UNDEFINED * @param glp desired GLProfile, or null if determined by renderableType * @param renderableType actual EGL renderableType - * + * * May throw GLException if given GLProfile is not compatible w/ renderableType */ public EGLGLCapabilities(long eglcfg, int eglcfgid, int visualID, GLProfile glp, int renderableType) { @@ -62,10 +62,12 @@ public class EGLGLCapabilities extends GLCapabilities { this.nativeVisualID = visualID; } + @Override public Object cloneMutable() { return clone(); } + @Override public Object clone() { try { return super.clone(); @@ -73,13 +75,13 @@ public class EGLGLCapabilities extends GLCapabilities { throw new GLException(e); } } - + final protected void setEGLConfig(long v) { eglcfg=v; } final public long getEGLConfig() { return eglcfg; } final public int getEGLConfigID() { return eglcfgid; } final public int getRenderableType() { return renderableType; } final public int getNativeVisualID() { return nativeVisualID; } - + @Override final public int getVisualID(VIDType type) throws NativeWindowException { switch(type) { @@ -90,9 +92,9 @@ public class EGLGLCapabilities extends GLCapabilities { return getNativeVisualID(); default: throw new NativeWindowException("Invalid type <"+type+">"); - } + } } - + public static boolean isCompatible(GLProfile glp, int renderableType) { if(null == glp) { return true; @@ -121,7 +123,7 @@ public class EGLGLCapabilities extends GLCapabilities { } return null; } - + public static StringBuilder renderableTypeToString(StringBuilder sink, int renderableType) { if(null == sink) { sink = new StringBuilder(); @@ -139,9 +141,10 @@ public class EGLGLCapabilities extends GLCapabilities { if(0 != (renderableType & EGL.EGL_OPENVG_API)) { if(!first) sink.append(", "); sink.append("VG"); first=false; } - return sink; + return sink; } - + + @Override public StringBuilder toString(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java index 5ff63d93b..e255a0672 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java @@ -119,7 +119,7 @@ public class WGLGLCapabilities extends GLCapabilities { if (iresults[i] == WGLExt.WGL_TYPE_RGBA_FLOAT_ARB) { setPbufferFloatingPointBuffers(true); } - + // normal RGBA FB: WGLExt.WGL_TYPE_RGBA_ARB // ignore unknown results here break; @@ -177,10 +177,12 @@ public class WGLGLCapabilities extends GLCapabilities { return true; } + @Override public Object cloneMutable() { return clone(); } + @Override public Object clone() { try { return super.clone(); @@ -191,11 +193,11 @@ public class WGLGLCapabilities extends GLCapabilities { final public PIXELFORMATDESCRIPTOR getPFD() { return pfd; } final public int getPFDID() { return pfdID; } - + final public boolean isSetByARB() { return 0 < arb_pixelformat; } final public boolean isSetByGDI() { return 0 > arb_pixelformat; } final public boolean isSet() { return 0 != arb_pixelformat; } - + @Override final public int getVisualID(VIDType type) throws NativeWindowException { switch(type) { @@ -205,16 +207,17 @@ public class WGLGLCapabilities extends GLCapabilities { return getPFDID(); default: throw new NativeWindowException("Invalid type <"+type+">"); - } + } } - + + @Override public StringBuilder toString(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); } sink.append("wgl vid 0x").append(Integer.toHexString(pfdID)).append(" "); switch (arb_pixelformat) { - case -1: + case -1: sink.append("gdi"); break; case 0: diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLCapabilities.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLCapabilities.java index 96d4c7713..e0b69ffd4 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLCapabilities.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLCapabilities.java @@ -55,10 +55,12 @@ public class X11GLCapabilities extends GLCapabilities { this.fbcfgid = VisualIDHolder.VID_UNDEFINED; } + @Override public Object cloneMutable() { return clone(); } + @Override public Object clone() { try { return super.clone(); @@ -86,9 +88,10 @@ public class X11GLCapabilities extends GLCapabilities { return getFBConfigID(); default: throw new NativeWindowException("Invalid type <"+type+">"); - } + } } - + + @Override public StringBuilder toString(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); diff --git a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java index b422f50e6..196f23598 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java +++ b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -44,7 +44,7 @@ package javax.media.nativewindow; must support, such as color depth per channel. It currently contains the minimal number of routines which allow configuration on all supported window systems. */ -public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparable { +public class Capabilities implements CapabilitiesImmutable, Cloneable { protected final static String na_str = "----" ; private int redBits = 8; @@ -67,10 +67,12 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl */ public Capabilities() {} + @Override public Object cloneMutable() { return clone(); } - + + @Override public Object clone() { try { return super.clone(); @@ -79,6 +81,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl } } + @Override public int hashCode() { // 31 * x == (x << 5) - x int hash = 31 + this.redBits; @@ -94,6 +97,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl return hash; } + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(!(obj instanceof CapabilitiesImmutable)) { @@ -116,20 +120,23 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl return res; } - /** comparing RGBA values only */ - public int compareTo(Object o) { - if ( ! ( o instanceof Capabilities ) ) { + /** + * Comparing RGBA values only + **/ + @Override + public int compareTo(final CapabilitiesImmutable caps) { + /** + if ( ! ( o instanceof CapabilitiesImmutable ) ) { Class c = (null != o) ? o.getClass() : null ; - throw new ClassCastException("Not a Capabilities object: " + c); + throw new ClassCastException("Not a CapabilitiesImmutable object, but " + c); } - - final Capabilities caps = (Capabilities) o; - + final CapabilitiesImmutable caps = (CapabilitiesImmutable) o; */ + final int a = ( alphaBits > 0 ) ? alphaBits : 1; final int rgba = redBits * greenBits * blueBits * a; - final int xa = ( caps.alphaBits ) > 0 ? caps.alphaBits : 1; - final int xrgba = caps.redBits * caps.greenBits * caps.blueBits * xa; + final int xa = ( caps.getAlphaBits() ) > 0 ? caps.getAlphaBits() : 1; + final int xrgba = caps.getRedBits() * caps.getGreenBits() * caps.getBlueBits() * xa; if(rgba > xrgba) { return 1; @@ -148,13 +155,14 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl return VisualIDHolder.VID_UNDEFINED; default: throw new NativeWindowException("Invalid type <"+type+">"); - } + } } - + /** 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() { + @Override + public final int getRedBits() { return redBits; } @@ -168,7 +176,8 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl /** 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() { + @Override + public final int getGreenBits() { return greenBits; } @@ -182,7 +191,8 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl /** 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() { + @Override + public final int getBlueBits() { return blueBits; } @@ -192,11 +202,12 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl 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() { + @Override + public final int getAlphaBits() { return alphaBits; } @@ -207,36 +218,36 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl this.alphaBits = alphaBits; } - /** - * Defaults to true, ie. opaque surface. - *

- * On supported platforms, setting opaque to false may result in a translucent surface.

- * - *

- * Platform implementations may need an alpha component in the surface (eg. Windows), - * or expect pre-multiplied alpha values (eg. X11/XRender).
- * To unify the experience, this method also invokes {@link #setAlphaBits(int) setAlphaBits(1)} - * if {@link #getAlphaBits()} == 0.
- * Please note that in case alpha is required on the platform the - * clear color shall have an alpha lower than 1.0 to allow anything shining through. - *

- * - *

- * Mind that translucency may cause a performance penalty - * due to the composite work required by the window manager.

- * - *

- * The platform implementation may utilize the transparency RGBA values.
- * This is true for the original GLX transparency specification, which is no more used today.
- * Actually these values are currently not used by any implementation, - * so we may mark them deprecated soon, if this doesn't change.
- *

- */ + /** + * Defaults to true, ie. opaque surface. + *

+ * On supported platforms, setting opaque to false may result in a translucent surface.

+ * + *

+ * Platform implementations may need an alpha component in the surface (eg. Windows), + * or expect pre-multiplied alpha values (eg. X11/XRender).
+ * To unify the experience, this method also invokes {@link #setAlphaBits(int) setAlphaBits(1)} + * if {@link #getAlphaBits()} == 0.
+ * Please note that in case alpha is required on the platform the + * clear color shall have an alpha lower than 1.0 to allow anything shining through. + *

+ * + *

+ * Mind that translucency may cause a performance penalty + * due to the composite work required by the window manager.

+ * + *

+ * The platform implementation may utilize the transparency RGBA values.
+ * This is true for the original GLX transparency specification, which is no more used today.
+ * Actually these values are currently not used by any implementation, + * so we may mark them deprecated soon, if this doesn't change.
+ *

+ */ public void setBackgroundOpaque(boolean opaque) { - backgroundOpaque = opaque; - if(!opaque && getAlphaBits()==0) { - setAlphaBits(1); - } + backgroundOpaque = opaque; + if(!opaque && getAlphaBits()==0) { + setAlphaBits(1); + } } /** Indicates whether the background of this OpenGL context should @@ -244,7 +255,8 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl @see #setBackgroundOpaque */ - public boolean isBackgroundOpaque() { + @Override + public final boolean isBackgroundOpaque() { return backgroundOpaque; } @@ -258,7 +270,8 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl /** Indicates whether the drawable surface is onscreen. Defaults to true. */ - public boolean isOnscreen() { + @Override + public final boolean isOnscreen() { return onscreen; } @@ -266,25 +279,29 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl * This value is undefined if {@link #isBackgroundOpaque()} equals true. * @see #setTransparentRedValue */ - public int getTransparentRedValue() { return transparentValueRed; } + @Override + public final int getTransparentRedValue() { return transparentValueRed; } /** Gets the transparent green value for the frame buffer configuration. * This value is undefined if {@link #isBackgroundOpaque()} equals true. * @see #setTransparentGreenValue */ - public int getTransparentGreenValue() { return transparentValueGreen; } + @Override + public final int getTransparentGreenValue() { return transparentValueGreen; } /** Gets the transparent blue value for the frame buffer configuration. * This value is undefined if {@link #isBackgroundOpaque()} equals true. * @see #setTransparentBlueValue */ - public int getTransparentBlueValue() { return transparentValueBlue; } + @Override + public final int getTransparentBlueValue() { return transparentValueBlue; } /** Gets the transparent alpha value for the frame buffer configuration. * This value is undefined if {@link #isBackgroundOpaque()} equals true. * @see #setTransparentAlphaValue */ - public int getTransparentAlphaValue() { return transparentValueAlpha; } + @Override + public final int getTransparentAlphaValue() { return transparentValueAlpha; } /** Sets the transparent red value for the frame buffer configuration, ranging from 0 to the maximum frame buffer value for red. @@ -314,6 +331,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl A value of -1 is interpreted as any value. */ public void setTransparentAlphaValue(int transValueAlpha) { transparentValueAlpha=transValueAlpha; } + @Override public StringBuilder toString(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); @@ -334,7 +352,8 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl protected final String toHexString(int val) { return Integer.toHexString(val); } /** Returns a textual representation of this Capabilities - object. */ + object. */ + @Override public String toString() { StringBuilder msg = new StringBuilder(); msg.append("Caps["); @@ -342,5 +361,4 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl msg.append("]"); return msg.toString(); } - } diff --git a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java index 3d7362c40..b984a4626 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java @@ -33,10 +33,10 @@ import com.jogamp.common.type.WriteCloneable; /** * Specifies an immutable set of capabilities that a window's rendering context * must support, such as color depth per channel. - * + * * @see javax.media.nativewindow.Capabilities */ -public interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable { +public interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable, Comparable { /** * Returns the number of bits requested for the color buffer's red diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Capabilities.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Capabilities.java index 0e69c738f..4f8cff8c5 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Capabilities.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Capabilities.java @@ -40,10 +40,12 @@ public class X11Capabilities extends Capabilities { this.xVisualInfo = xVisualInfo; } + @Override public Object cloneMutable() { return clone(); } + @Override public Object clone() { try { return super.clone(); @@ -68,9 +70,10 @@ public class X11Capabilities extends Capabilities { return VisualIDHolder.VID_UNDEFINED; default: throw new NativeWindowException("Invalid type <"+type+">"); - } + } } - + + @Override public StringBuilder toString(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); -- cgit v1.2.3 From d10c7916a2444b6cb1cf45be3ccb3d6e91a2f1b4 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 29 Jun 2012 04:09:48 +0200 Subject: NativeSurface.unlockSurface(): Change fail-fast policy to fail safe tolerant - This policy allows more simple destruction handling w/o validating on the top level. - Hence 'unlockSurface()' shall not throw any exception. - 'lockSurface()' keeps unchanges, clarified w/ explicit 'throws' declaration, ie will fail-fast. --- .../classes/com/jogamp/nativewindow/awt/JAWTWindow.java | 6 ++++-- .../classes/javax/media/nativewindow/NativeSurface.java | 8 +++++--- .../classes/javax/media/nativewindow/ProxySurface.java | 2 +- .../classes/jogamp/nativewindow/windows/GDISurface.java | 11 +++++------ src/newt/classes/com/jogamp/newt/opengl/GLWindow.java | 4 ++-- src/newt/classes/jogamp/newt/WindowImpl.java | 2 +- src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java | 5 ++++- .../classes/jogamp/newt/driver/windows/WindowsWindow.java | 9 ++++----- 8 files changed, 26 insertions(+), 21 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 3437358de..3815189ef 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -278,7 +278,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } @Override - public final int lockSurface() throws NativeWindowException { + public final int lockSurface() throws NativeWindowException, RuntimeException { surfaceLock.lock(); int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? @@ -322,7 +322,9 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if (surfaceLock.getHoldCount() == 1) { final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); try { - unlockSurfaceImpl(); + if(null != jawt) { + unlockSurfaceImpl(); + } } finally { adevice.unlock(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java index c58b34b18..cec7d4ec3 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java @@ -83,10 +83,11 @@ public interface NativeSurface extends SurfaceUpdatedListener { * @return {@link #LOCK_SUCCESS}, {@link #LOCK_SURFACE_CHANGED} or {@link #LOCK_SURFACE_NOT_READY}. * * @throws RuntimeException after timeout when waiting for the surface lock + * @throws NativeWindowException if native locking failed, maybe platform related * * @see com.jogamp.common.util.locks.RecursiveLock */ - public int lockSurface(); + public int lockSurface() throws NativeWindowException, RuntimeException; /** * Unlock the surface of this native window @@ -96,12 +97,13 @@ public interface NativeSurface extends SurfaceUpdatedListener { * The implementation shall also invoke {@link AbstractGraphicsDevice#unlock()} * for the final unlock (recursive count zero).

* - * @throws RuntimeException if surface is not locked + * The implementation shall be fail safe, i.e. tolerant in case the native resources + * are already released / unlocked. In this case the implementation shall simply ignore the call. * * @see #lockSurface * @see com.jogamp.common.util.locks.RecursiveLock */ - public void unlockSurface() throws NativeWindowException ; + public void unlockSurface(); /** * Query if surface is locked by another thread, i.e. not the current one. diff --git a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java index c8cd78d82..1dabc3dcd 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java @@ -123,7 +123,7 @@ public abstract class ProxySurface implements NativeSurface { } @Override - public int lockSurface() throws NativeWindowException { + public int lockSurface() throws NativeWindowException, RuntimeException { surfaceLock.lock(); int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java index 4da48bdae..c24f64b32 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java @@ -74,13 +74,12 @@ public class GDISurface extends ProxySurface { @Override final protected void unlockSurfaceImpl() { - if (0 == surfaceHandle) { - throw new InternalError("surface not acquired: "+this+", thread: "+Thread.currentThread().getName()); - } - if(0 == GDI.ReleaseDC(windowHandle, surfaceHandle)) { - throw new NativeWindowException("DC not released: "+this+", isWindow "+GDI.IsWindow(windowHandle)+", werr "+GDI.GetLastError()+", thread: "+Thread.currentThread().getName()); + if (0 != surfaceHandle) { + if(0 == GDI.ReleaseDC(windowHandle, surfaceHandle)) { + throw new NativeWindowException("DC not released: "+this+", isWindow "+GDI.IsWindow(windowHandle)+", werr "+GDI.GetLastError()+", thread: "+Thread.currentThread().getName()); + } + surfaceHandle=0; } - surfaceHandle=0; } @Override diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index b94bc0f27..bff1efcb5 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -995,12 +995,12 @@ public class GLWindow implements GLAutoDrawable, Window, NEWTEventConsumer, FPSC // @Override - public final int lockSurface() { + public final int lockSurface() throws NativeWindowException, RuntimeException { return window.lockSurface(); } @Override - public final void unlockSurface() throws NativeWindowException { + public final void unlockSurface() { window.unlockSurface(); } diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index 34f248121..45745e89c 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -563,7 +563,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // @Override - public final int lockSurface() { + public final int lockSurface() throws NativeWindowException, RuntimeException { windowLock.lock(); surfaceLock.lock(); int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java index b45c60e69..942994c13 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java @@ -104,7 +104,10 @@ public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverCl @Override protected void unlockSurfaceImpl() { if(!isOffscreenInstance) { - unlockSurface0(getWindowHandle()); + final long h = getWindowHandle(); + if(0 != h) { + unlockSurface0(h); + } } } diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java b/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java index a30aa133c..5e636d982 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java +++ b/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java @@ -87,12 +87,11 @@ public class WindowsWindow extends WindowImpl { @Override protected void unlockSurfaceImpl() { - if (0 == hdc) { - throw new InternalError("surface not acquired"); + if (0 != hdc) { + GDI.ReleaseDC(getWindowHandle(), hdc); + hdc_old = hdc; + hdc=0; } - GDI.ReleaseDC(getWindowHandle(), hdc); - hdc_old = hdc; - hdc=0; } @Override -- cgit v1.2.3 From c50fca1b5df9ec3b76fada4dd5dd307bdece531a Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 30 Jun 2012 03:39:33 +0200 Subject: JAWTUtil/MacOSXWindowSystemInterface-pbuffer: Cleanup / More DEBUG info JAWTUtil.getJAWT(..): - better local var names - one time init - add DEBUG trace JAWTUtil.: - add offscreenLayer info MacOSXWindowSystemInterface-pbuffer.m: - remove warning: access of protected vars from outside class - better local var names - more DEBUG info (pbuffer texture) --- .../macosx/MacOSXWindowSystemInterface-pbuffer.m | 25 +++++++++++----------- .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 16 ++++++++++---- 2 files changed, 24 insertions(+), 17 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m index 66bd10f89..3fc6ea0f6 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m @@ -32,8 +32,6 @@ int texWidth; int texHeight; GLuint textureID; - GLint swapInterval; - GLint swapIntervalCounter; struct timespec lastWaitTime; #ifdef HAS_CADisplayLink CADisplayLink* displayLink; @@ -43,6 +41,8 @@ int tc; struct timespec t0; @public + GLint swapInterval; + GLint swapIntervalCounter; pthread_mutex_t renderLock; pthread_cond_t renderSignal; BOOL shallDraw; @@ -280,23 +280,22 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink, } } */ GLenum textureTarget = [pbuffer textureTarget]; - GLfloat tWidth, tHeight; + GLfloat texCoordWidth, texCoordHeight; { GLsizei pwidth = [pbuffer pixelsWide]; GLsizei pheight = [pbuffer pixelsHigh]; - tWidth = textureTarget == GL_TEXTURE_2D ? (GLfloat)pwidth /(GLfloat)texWidth : pwidth; - tHeight = textureTarget == GL_TEXTURE_2D ? (GLfloat)pheight/(GLfloat)texHeight : pheight; + texCoordWidth = textureTarget == GL_TEXTURE_2D ? (GLfloat)pwidth /(GLfloat)texWidth : pwidth; + texCoordHeight = textureTarget == GL_TEXTURE_2D ? (GLfloat)pheight/(GLfloat)texHeight : pheight; } Bool texCreated = 0 == textureID; if(texCreated) { glGenTextures(1, &textureID); - DBG_PRINT("MyNSOpenGLLayer::drawInOpenGLContext %p, ctx %p, pfmt %p tex %dx%d -> %fx%f 0x%X: creating texID 0x%X\n", - self, context, pixelFormat, texWidth, texHeight, tWidth, tHeight, textureTarget, textureID); CGRect lRect = [self frame]; - DBG_PRINT("MyNSOpenGLLayer::drawInOpenGLContext %p frame0: %lf/%lf %lfx%lf\n", - self, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + DBG_PRINT("MyNSOpenGLLayer::drawInOpenGLContext %p, pbuffer %p %dx%d -> tex %dx%d [%fx%f] id 0x%X target 0x%X, frame: %lf/%lf %lfx%lf (refcnt %d)\n", + self, pbuffer, [pbuffer pixelsWide], [pbuffer pixelsHigh], texWidth, texHeight, texCoordWidth, texCoordHeight, textureID, textureTarget, + lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, (int)[self retainCount]); } glBindTexture(textureTarget, textureID); @@ -324,10 +323,10 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink, }; GLfloat tex[] = { - 0.0, 0.0, - 0.0, tHeight, - tWidth, tHeight, - tWidth, 0.0 + 0.0, 0.0, + 0.0, texCoordHeight, + texCoordWidth, texCoordHeight, + texCoordWidth, 0.0 }; glEnableClientState(GL_VERTEX_ARRAY); diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index 8098bdb1b..36d7c3727 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -115,8 +115,8 @@ public class JAWTUtil { JAWT jawt = JAWT.create(); // default queries - boolean tryOffscreenLayer = false; - boolean tryOnscreenLayer = true; + boolean tryOffscreenLayer; + boolean tryOnscreen; int jawt_version_flags_offscreen = jawt_version_flags; if(isOffscreenLayerRequired()) { @@ -124,7 +124,7 @@ public class JAWTUtil { if(Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0) { jawt_version_flags_offscreen |= JAWTUtil.JAWT_MACOSX_USE_CALAYER; tryOffscreenLayer = true; - tryOnscreenLayer = false; + tryOnscreen = false; } else { throw new RuntimeException("OSX: Invalid version of Java ("+Platform.JAVA_VERSION_NUMBER+") / OS X ("+Platform.OS_VERSION_NUMBER+")"); } @@ -135,9 +135,16 @@ public class JAWTUtil { if(Platform.OS_TYPE == Platform.OSType.MACOS) { jawt_version_flags_offscreen |= JAWTUtil.JAWT_MACOSX_USE_CALAYER; tryOffscreenLayer = true; + tryOnscreen = true; } else { throw new InternalError("offscreen requested and supported, but n/a for: "+Platform.OS_TYPE); } + } else { + tryOffscreenLayer = false; + tryOnscreen = true; + } + if(DEBUG) { + System.err.println("JAWTUtil.getJAWT(tryOffscreenLayer "+tryOffscreenLayer+", tryOnscreen "+tryOnscreen+")"); } StringBuilder errsb = new StringBuilder(); @@ -147,7 +154,7 @@ public class JAWTUtil { return jawt; } } - if(tryOnscreenLayer) { + if(tryOnscreen) { if(tryOffscreenLayer) { errsb.append(", "); } @@ -260,6 +267,7 @@ public class JAWTUtil { System.err.println("JAWTUtil: Is headless " + headlessMode); int hints = ( null != desktophints ) ? desktophints.size() : 0 ; System.err.println("JAWTUtil: AWT Desktop hints " + hints); + System.err.println("JAWTUtil: OffscreenLayer Supported: "+isOffscreenLayerSupported()+" - Required "+isOffscreenLayerRequired()); } } -- cgit v1.2.3 From 9a7c8896fe38ebcd42ed5238b09a7a36d46db9dc Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 30 Jun 2012 05:14:34 +0200 Subject: Fix Bug #589 (JAWT Offscreen-Layer resize) and Offscreen-Layer setSwapInterval() deadlock; Reuse JAWT instance; Cleanup - Fixes - OSXUtil.CreateCALayer*(..): Pass layer target size (if known). This fixes Bug #589 - MacOSXWindowSystemInterface-pbuffer.m: - ALL: displayLink NULL check - setSwapInterval(..): lock only for variable setting, could deadlock when start/stop CVDisplayLink - JAWTWindow.destroy(): use 'surfaceLock' instead of 'synchronized' - Cleanup / Performance - JAWTWindow.lockSurface(): Reuse JAWT instance - MacOSXJAWTWindow: AttachJAWTSurfaceLayer0(..) -> SetJAWTRootSurfaceLayer0(..) Reflects semantic better. - DEBUG - JAWTWindow.updateBounds(..) notify of bounds change --- make/scripts/tests.sh | 4 +- .../macosx/MacOSXWindowSystemInterface-pbuffer.m | 83 +++++++++++----------- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 26 +++++-- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 10 +-- .../jogamp/nativewindow/macosx/OSXUtil.java | 6 +- src/nativewindow/native/macosx/OSXmisc.m | 29 ++++---- .../junit/jogl/demos/es2/awt/TestGearsES2AWT.java | 27 ++++++- 7 files changed, 112 insertions(+), 73 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 646ff2249..55fbc5378 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -271,7 +271,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWT02WindowClosing #testawt com.jogamp.opengl.test.junit.jogl.awt.text.TestAWTTextRendererUseVertexArrayBug464 #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* +testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWTAnalyzeBug455 $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWTBug450 $* @@ -332,7 +332,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGTextureFromFileNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite01AWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite01NEWT $* -testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite02AWT $* +#testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite02AWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestTextureSequence01NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestTextureSequence01AWT $* diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m index 3fc6ea0f6..776284cfc 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m @@ -171,7 +171,7 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink, #endif [self setAsynchronous: YES]; - [self setNeedsDisplayOnBoundsChange: YES]; // FIXME: learn how to recreate on size change! + [self setNeedsDisplayOnBoundsChange: YES]; [self setOpaque: opaque ? YES : NO]; @@ -192,10 +192,8 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink, [displayLink setPaused: YES]; [displayLink release]; #else - if(NULL!=displayLink) { - CVDisplayLinkStop(displayLink); - CVDisplayLinkRelease(displayLink); - } + CVDisplayLinkStop(displayLink); + CVDisplayLinkRelease(displayLink); #endif displayLink = NULL; } @@ -267,18 +265,6 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink, { [context makeCurrentContext]; - /** - * v-sync doesn't works w/ NSOpenGLLayer's context .. well :( - * Using CVDisplayLink .. see setSwapInterval() below. - * - if(0 <= swapInterval) { - GLint si; - [context getValues: &si forParameter: NSOpenGLCPSwapInterval]; - if(si != swapInterval) { - DBG_PRINT("MyNSOpenGLLayer::drawInOpenGLContext %p setSwapInterval: %d -> %d\n", self, si, swapInterval); - [context setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval]; - } - } */ GLenum textureTarget = [pbuffer textureTarget]; GLfloat texCoordWidth, texCoordHeight; { @@ -359,33 +345,50 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink, - (void)setSwapInterval:(int)interval { - DBG_PRINT("MyNSOpenGLLayer::setSwapInterval: %d\n", interval); + /** + * v-sync doesn't works w/ NSOpenGLLayer's context .. well :( + * Using CVDisplayLink .. see setSwapInterval() below. + * + GLint si; + [context getValues: &si forParameter: NSOpenGLCPSwapInterval]; + if(si != swapInterval) { + DBG_PRINT("MyNSOpenGLLayer::drawInOpenGLContext %p setSwapInterval: %d -> %d\n", self, si, swapInterval); + [context setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval]; + } + } */ + + pthread_mutex_lock(&renderLock); + DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.0: %d - displayLink %p\n", interval, displayLink); swapInterval = interval; swapIntervalCounter = 0; - if(0 < swapInterval) { - tc = 0; - timespec_now(&t0); - - [self setAsynchronous: NO]; - #ifdef HAS_CADisplayLink - [displayLink setPaused: NO]; - [displayLink setFrameInterval: interval]; - #else - if(NULL!=displayLink) { + pthread_mutex_unlock(&renderLock); + + if(NULL!=displayLink) { + if(0 < swapInterval) { + tc = 0; + timespec_now(&t0); + + [self setAsynchronous: NO]; + #ifdef HAS_CADisplayLink + [displayLink setPaused: NO]; + [displayLink setFrameInterval: interval]; + #else + DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.1.b.1\n"); CVDisplayLinkStart(displayLink); - // FIXME: doesn't support interval .. - } - #endif - } else { - #ifdef HAS_CADisplayLink - [displayLink setPaused: YES]; - #else - if(NULL!=displayLink) { + DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.1.b.X\n"); + #endif + } else { + #ifdef HAS_CADisplayLink + [displayLink setPaused: YES]; + #else + DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.0.b.1\n"); CVDisplayLinkStop(displayLink); - } - #endif - [self setAsynchronous: YES]; + DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.0.b.X\n"); + #endif + [self setAsynchronous: YES]; + } } + DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.X: %d\n", interval); } -(void)tick @@ -414,9 +417,7 @@ NSOpenGLLayer* createNSOpenGLLayer(NSOpenGLContext* ctx, NSOpenGLPixelFormat* fm void setNSOpenGLLayerSwapInterval(NSOpenGLLayer* layer, int interval) { MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; - pthread_mutex_lock(&l->renderLock); [l setSwapInterval: interval]; - pthread_mutex_unlock(&l->renderLock); } void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_micros) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 3815189ef..cffe495f7 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -135,6 +135,13 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected abstract void invalidateNative(); protected final void updateBounds(JAWT_Rectangle jawtBounds) { + if(DEBUG) { + final Rectangle jb = new Rectangle(jawtBounds.getX(), jawtBounds.getY(), jawtBounds.getWidth(), jawtBounds.getHeight()); + if(!bounds.equals(jb)) { + System.err.println("JAWTWindow.updateBounds: "+bounds+" -> "+jb); + Thread.dumpStack(); + } + } bounds.setX(jawtBounds.getX()); bounds.setY(jawtBounds.getY()); bounds.setWidth(jawtBounds.getWidth()); @@ -186,7 +193,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } try { if(DEBUG) { - System.err.println("JAWTWindow.attachSurfaceHandle(): 0x"+Long.toHexString(layerHandle)); + System.err.println("JAWTWindow.attachSurfaceHandle(): 0x"+Long.toHexString(layerHandle) + ", bounds "+bounds); } attachSurfaceLayerImpl(layerHandle); } finally { @@ -288,8 +295,10 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); adevice.lock(); try { - jawt = fetchJAWTImpl(); - isOffscreenLayerSurface = JAWTUtil.isJAWTUsingOffscreenLayer(jawt); + if(null == jawt) { // no need to re-fetch for each frame + jawt = fetchJAWTImpl(); + isOffscreenLayerSurface = JAWTUtil.isJAWTUsingOffscreenLayer(jawt); + } res = lockSurfaceImpl(); if(LOCK_SUCCESS == res && drawable_old != drawable) { res = LOCK_SURFACE_CHANGED; @@ -386,9 +395,14 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, // @Override - public synchronized void destroy() { - invalidate(); - component = null; // don't dispose the AWT component, since we are merely an immutable uplink + public void destroy() { + surfaceLock.lock(); + try { + invalidate(); + component = null; // don't dispose the AWT component, since we are merely an immutable uplink + } finally { + surfaceLock.unlock(); + } } @Override diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 0ca5cd297..42fd08df1 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -207,20 +207,20 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable { ((MutableGraphicsConfiguration)getGraphicsConfiguration()).setChosenCapabilities(caps); } if(0 == rootSurfaceLayerHandle) { - rootSurfaceLayerHandle = OSXUtil.CreateCALayer(); + rootSurfaceLayerHandle = OSXUtil.CreateCALayer(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); if(0 == rootSurfaceLayerHandle) { OSXUtil.DestroyNSWindow(drawable); drawable = 0; unlockSurfaceImpl(); throw new NativeWindowException("Could not create root CALayer: "+this); } - if(!AttachJAWTSurfaceLayer0(dsi.getBuffer(), rootSurfaceLayerHandle)) { + if(!SetJAWTRootSurfaceLayer0(dsi.getBuffer(), rootSurfaceLayerHandle)) { OSXUtil.DestroyCALayer(rootSurfaceLayerHandle); rootSurfaceLayerHandle = 0; OSXUtil.DestroyNSWindow(drawable); drawable = 0; unlockSurfaceImpl(); - throw new NativeWindowException("Could not attach JAWT surfaceLayerHandle: "+this); + throw new NativeWindowException("Could not set JAWT rootSurfaceLayerHandle: "+this); } } ret = NativeWindow.LOCK_SUCCESS; @@ -267,8 +267,8 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable { } protected Point getLocationOnScreenNativeImpl(final int x0, final int y0) { return null; } - private static native boolean AttachJAWTSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); - // private static native boolean DetachJAWTSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); + private static native boolean SetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); + // private static native boolean UnsetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); // Variables for lockSurface/unlockSurface private JAWT_DrawingSurface ds; diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 3ca76a84a..94f949ea3 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -77,8 +77,8 @@ public class OSXUtil { DestroyNSWindow0(nsWindow); } - public static long CreateCALayer() { - return CreateCALayer0(); + public static long CreateCALayer(int x, int y, int width, int height) { + return CreateCALayer0(x, y, width, height); } public static void AddCASublayer(long rootCALayer, long subCALayer) { if(0==rootCALayer || 0==subCALayer) { @@ -117,7 +117,7 @@ public class OSXUtil { private static native void DestroyNSView0(long nsView); private static native long CreateNSWindow0(int x, int y, int width, int height); private static native void DestroyNSWindow0(long nsWindow); - private static native long CreateCALayer0(); + private static native long CreateCALayer0(int x, int y, int width, int height); private static native void AddCASublayer0(long rootCALayer, long subCALayer); private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 38ffde98b..e010fc440 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -225,22 +225,25 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyNSWindow0 /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: CreateCALayer0 - * Signature: (V)J + * Signature: (IIII)J */ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 - (JNIEnv *env, jclass unused) + (JNIEnv *env, jclass unused, jint x, jint y, jint width, jint height) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; CALayer* layer = [[CALayer alloc] init]; - DBG_PRINT("CALayer::CreateCALayer.0: %p (refcnt %d)\n", layer, (int)[layer retainCount]); + DBG_PRINT("CALayer::CreateCALayer.0: %p %d/%d %dx%d (refcnt %d)\n", layer, x, y, width, height, (int)[layer retainCount]); + // avoid zero size + if(0 == width) { width = 32; } + if(0 == height) { height = 32; } // initial dummy size ! CGRect lRect = [layer frame]; - lRect.origin.x = 0; - lRect.origin.y = 0; - lRect.size.width = 32; - lRect.size.height = 32; + lRect.origin.x = x; + lRect.origin.y = y; + lRect.size.width = width; + lRect.size.height = height; [layer setFrame: lRect]; // no animations for add/remove/swap sublayers etc // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] @@ -422,10 +425,10 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_IsMainThread0 /* * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow - * Method: AttachJAWTSurfaceLayer + * Method: SetJAWTRootSurfaceLayer0 * Signature: (JJ)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_AttachJAWTSurfaceLayer0 +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_SetJAWTRootSurfaceLayer0 (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) { JNF_COCOA_ENTER(env); @@ -437,9 +440,9 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow CALayer* layer = (CALayer*) (intptr_t) caLayer; [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ id surfaceLayers = (id )dsi->platformInfo; - DBG_PRINT("CALayer::attachJAWTSurfaceLayer: %p -> %p (refcnt %d)\n", surfaceLayers.layer, layer, (int)[layer retainCount]); + DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.0: %p -> %p (refcnt %d)\n", surfaceLayers.layer, layer, (int)[layer retainCount]); surfaceLayers.layer = layer; // already incr. retain count - DBG_PRINT("CALayer::attachJAWTSurfaceLayer.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]); + DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]); }]; JNF_COCOA_EXIT(env); return JNI_TRUE; @@ -447,9 +450,9 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow /* * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow - * Method: DetachJAWTSurfaceLayer + * Method: UnsetJAWTRootSurfaceLayer0 * Signature: (JJ)Z -JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_DetachJAWTSurfaceLayer0 +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_UnsetJAWTRootSurfaceLayer0 (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) { JNF_COCOA_ENTER(env); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java index c6e224548..ba9113af5 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java @@ -32,6 +32,8 @@ import javax.media.opengl.*; import com.jogamp.opengl.util.Animator; import javax.media.opengl.awt.GLCanvas; + +import com.jogamp.common.os.Platform; import com.jogamp.newt.event.awt.AWTKeyAdapter; import com.jogamp.newt.event.awt.AWTWindowAdapter; import com.jogamp.newt.event.TraceKeyAdapter; @@ -41,7 +43,11 @@ import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; import com.jogamp.opengl.test.junit.util.QuitAdapter; + +import java.awt.BorderLayout; +import java.awt.Dimension; import java.awt.Frame; +import java.awt.TextArea; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -57,6 +63,7 @@ public class TestGearsES2AWT extends UITestCase { static boolean firstUIActionOnProcess = false; static boolean forceES2 = false; static boolean shallUseOffscreenLayer = false; + static boolean addComp = true; static int swapInterval = 1; static boolean showFPS = false; @@ -77,8 +84,19 @@ public class TestGearsES2AWT extends UITestCase { final GLCanvas glCanvas = new GLCanvas(caps); Assert.assertNotNull(glCanvas); glCanvas.setShallUseOffscreenLayer(shallUseOffscreenLayer); - frame.add(glCanvas); - frame.setSize(512, 512); + Dimension glc_sz = new Dimension(width, height); + glCanvas.setMinimumSize(glc_sz); + glCanvas.setPreferredSize(glc_sz); + glCanvas.setSize(glc_sz); + if(addComp) { + final TextArea ta = new TextArea(2, 20); + ta.append("0123456789"); + ta.append(Platform.getNewline()); + ta.append("Some Text"); + ta.append(Platform.getNewline()); + frame.add(ta, BorderLayout.SOUTH); + } + frame.add(glCanvas, BorderLayout.CENTER); frame.setTitle("Gears AWT Test (translucent "+!caps.isBackgroundOpaque()+"), swapInterval "+swapInterval); glCanvas.addGLEventListener(new GearsES2(swapInterval)); @@ -91,12 +109,13 @@ public class TestGearsES2AWT extends UITestCase { javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { + frame.pack(); frame.setVisible(true); }}); animator.setUpdateFPSFrames(60, System.err); animator.start(); - while(!quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration() Date: Sat, 30 Jun 2012 15:44:55 +0200 Subject: Fix Bug 597: XDisplayString(0) -> SIGSEGV; Handle n/a DISPLAY It works now as follows: Note: Remote connection tested using ssh to localhost or an actual remote machine. Test w/ proper X11 authentication, i.e. DISPLAY and xauth: > cd projects/JOGL/jogl-bugs/597-headless/ > echo $DISPLAY localhost:10.0 > xclock 'works' T1.1 OK> java plop jogamp.opengl.x11.glx.X11GLXDrawableFactory@f581593 T1.2 OK> java -Djava.awt.headless=true plop jogamp.opengl.x11.glx.X11GLXDrawableFactory@6f34a7d8 +++ Test _without_ proper X11 authentication, i.e. DISPLAY and xauth: > xclock No protocol specified No protocol specified Error: Can't open display: :0.0 T2.1 OK> java plop No protocol specified No protocol specified Exception in thread "main" java.lang.InternalError: Can't connect to X11 window server using ':0.0' as the value of the DISPLAY variable. (Stack trace from: GLProfile.initProfilesForDefaultDevices(..) -> NativeWindowFactory.initSingleton(..) -> JAWTUtil.-> sun.awt.X11.XToolkit. -> sun.awt.X11GraphicsEnvironment.initDisplay(Native Method) T2.2 OK> java -Djava.awt.headless=true plop No protocol specified No protocol specified ... jogamp.opengl.x11.glx.X11GLXDrawableFactory@394a8cd1 --- .../classes/jogamp/nativewindow/x11/X11Util.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index c42bcf816..3c197062a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -109,10 +109,14 @@ public class X11Util { isX11LockAvailable = isXInitThreadsOK && !HAS_XLOCKDISPLAY_BUG ; final long dpy = X11Lib.XOpenDisplay(null); - try { - nullDisplayName = X11Lib.XDisplayString(dpy); - } finally { - X11Lib.XCloseDisplay(dpy); + if(0 != dpy) { + try { + nullDisplayName = X11Lib.XDisplayString(dpy); + } finally { + X11Lib.XCloseDisplay(dpy); + } + } else { + nullDisplayName = "nil"; } if(DEBUG) { -- cgit v1.2.3 From fd06292d4a208cbd613f4bdce7cae12e075e70ec Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 5 Jul 2012 14:32:00 +0200 Subject: NativeWindow/Newt X11ErrorHandler enhancement / unification - don't throw exceptions. Handles also XAWT BadMatch X_SetInputFocus. X11ErrorHandler code now dumps proper information about the opcode and error message and the running Java thread. Having propery "nativewindow.debug.X11Util.XErrorStackDump" or "nativewindow.debug=all' set, a stack trace is dumped. Since the X11ErrorHandler may catch an XAWT error: BadMatch X_SetInputFocus, we cannot throw an exception and better keep running. --- .../classes/jogamp/nativewindow/x11/X11Util.java | 23 ++- src/nativewindow/native/NativewindowCommon.c | 19 ++ src/nativewindow/native/NativewindowCommon.h | 1 + src/nativewindow/native/x11/Xmisc.c | 208 ++++++++++----------- src/nativewindow/native/x11/Xmisc.h | 44 +++++ .../classes/jogamp/newt/driver/x11/X11Display.java | 4 +- .../classes/jogamp/newt/driver/x11/X11Window.java | 3 + src/newt/native/NewtCommon.c | 19 ++ src/newt/native/NewtCommon.h | 1 + src/newt/native/X11Common.h | 2 +- src/newt/native/X11Display.c | 81 +++++--- src/newt/native/X11Window.c | 12 +- 12 files changed, 276 insertions(+), 141 deletions(-) create mode 100644 src/nativewindow/native/x11/Xmisc.h (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 3c197062a..fcc374751 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -81,9 +81,10 @@ public class X11Util { /** Value is true, best 'stable' results if not using XLockDisplay/XUnlockDisplay at all. */ public static final boolean HAS_XLOCKDISPLAY_BUG = true; - private static final boolean DEBUG = Debug.debug("X11Util"); - private static final boolean TRACE_DISPLAY_LIFECYCLE = Debug.getBooleanProperty("nativewindow.debug.X11Util.TraceDisplayLifecycle", true); - + public static final boolean DEBUG = Debug.debug("X11Util"); + public static final boolean XSYNC_ENABLED = Debug.isPropertyDefined("nativewindow.debug.X11Util.XSync", true); + public static final boolean XERROR_STACKDUMP = DEBUG || Debug.isPropertyDefined("nativewindow.debug.X11Util.XErrorStackDump", true); + private static final boolean TRACE_DISPLAY_LIFECYCLE = Debug.isPropertyDefined("nativewindow.debug.X11Util.TraceDisplayLifecycle", true); private static String nullDisplayName = null; private static boolean isX11LockAvailable = false; private static boolean requiresX11Lock = true; @@ -105,11 +106,14 @@ public class X11Util { } final boolean callXInitThreads = XINITTHREADS_ALWAYS_ENABLED || firstX11ActionOnProcess; - final boolean isXInitThreadsOK = initialize0( XINITTHREADS_ALWAYS_ENABLED || firstX11ActionOnProcess ); + final boolean isXInitThreadsOK = initialize0( XINITTHREADS_ALWAYS_ENABLED || firstX11ActionOnProcess, XERROR_STACKDUMP); isX11LockAvailable = isXInitThreadsOK && !HAS_XLOCKDISPLAY_BUG ; final long dpy = X11Lib.XOpenDisplay(null); if(0 != dpy) { + if(XSYNC_ENABLED) { + X11Lib.XSynchronize(dpy, true); + } try { nullDisplayName = X11Lib.XDisplayString(dpy); } finally { @@ -124,7 +128,8 @@ public class X11Util { ", requiresX11Lock "+requiresX11Lock+ ", XInitThreads [called "+callXInitThreads+", OK "+isXInitThreadsOK+"]"+ ", isX11LockAvailable "+isX11LockAvailable+ - ", X11 Display(NULL) <"+nullDisplayName+">"); + ", X11 Display(NULL) <"+nullDisplayName+">"+ + ", XSynchronize Enabled: "+XSYNC_ENABLED); // Thread.dumpStack(); } } @@ -455,6 +460,9 @@ public class X11Util { NativeWindowFactory.getDefaultToolkitLock().lock(); try { long handle = X11Lib.XOpenDisplay(arg0); + if(XSYNC_ENABLED && 0 != handle) { + X11Lib.XSynchronize(handle, true); + } if(TRACE_DISPLAY_LIFECYCLE) { System.err.println(Thread.currentThread()+" - X11Util.XOpenDisplay("+arg0+") 0x"+Long.toHexString(handle)); // Thread.dumpStack(); @@ -520,7 +528,10 @@ public class X11Util { return false; } - private static native boolean initialize0(boolean firstUIActionOnProcess); + private static final String getCurrentThreadName() { return Thread.currentThread().getName(); } // Callback for JNI + private static final void dumpStack() { Thread.dumpStack(); } // Callback for JNI + + private static native boolean initialize0(boolean firstUIActionOnProcess, boolean debug); private static native void shutdown0(); private static native void setX11ErrorHandler0(boolean onoff, boolean quiet); } diff --git a/src/nativewindow/native/NativewindowCommon.c b/src/nativewindow/native/NativewindowCommon.c index b866646a6..d2fdd5d69 100644 --- a/src/nativewindow/native/NativewindowCommon.c +++ b/src/nativewindow/native/NativewindowCommon.c @@ -1,5 +1,6 @@ #include "NativewindowCommon.h" +#include static const char * const ClazzNameRuntimeException = "java/lang/RuntimeException"; static jclass runtimeExceptionClz=NULL; @@ -45,6 +46,24 @@ int NativewindowCommon_init(JNIEnv *env) { return 0; } +const char * NativewindowCommon_GetStaticStringMethod(JNIEnv *jniEnv, jclass clazz, jmethodID jGetStrID, char *dest, int destSize, const char *altText) { + if(NULL != jniEnv && NULL != clazz && NULL != jGetStrID) { + jstring jstr = (jstring) (*jniEnv)->CallStaticObjectMethod(jniEnv, clazz, jGetStrID); + if(NULL != jstr) { + const char * str = (*jniEnv)->GetStringUTFChars(jniEnv, jstr, NULL); + if( NULL != str) { + strncpy(dest, str, destSize-1); + dest[destSize-1] = 0; // EOS + (*jniEnv)->ReleaseStringUTFChars(jniEnv, jstr, str); + return dest; + } + } + } + strncpy(dest, altText, destSize-1); + dest[destSize-1] = 0; // EOS + return dest; +} + jchar* NativewindowCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str) { jchar* strChars = NULL; diff --git a/src/nativewindow/native/NativewindowCommon.h b/src/nativewindow/native/NativewindowCommon.h index 41c4bd0eb..73b890c4f 100644 --- a/src/nativewindow/native/NativewindowCommon.h +++ b/src/nativewindow/native/NativewindowCommon.h @@ -7,6 +7,7 @@ int NativewindowCommon_init(JNIEnv *env); +const char * NativewindowCommon_GetStaticStringMethod(JNIEnv *jniEnv, jclass clazz, jmethodID jGetStrID, char *dest, int destSize, const char *altText); jchar* NativewindowCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str); void NativewindowCommon_FatalError(JNIEnv *env, const char* msg, ...); diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 439d9b334..5cbf5c04a 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -26,15 +26,19 @@ * or implied, of JogAmp Community. */ +#include "NativewindowCommon.h" +#include "Xmisc.h" +#include "jogamp_nativewindow_x11_X11Lib.h" + +// #define VERBOSE_ON 1 + +#ifdef VERBOSE_ON + #define DBG_PRINT(args...) fprintf(stderr, args); +#else + #define DBG_PRINT(args...) +#endif + -#include -#include -#include -#include -#include -#include -#include -#include /* Linux headers don't work properly */ #define __USE_GNU #include @@ -80,17 +84,6 @@ Bool XF86VidModeSetGammaRamp( #define RTLD_DEFAULT NULL #endif -#include "NativewindowCommon.h" -#include "jogamp_nativewindow_x11_X11Lib.h" - -// #define VERBOSE_ON 1 - -#ifdef VERBOSE_ON - #define DBG_PRINT(args...) fprintf(stderr, args); -#else - #define DBG_PRINT(args...) -#endif - static const char * const ClazzNameBuffers = "com/jogamp/common/nio/Buffers"; static const char * const ClazzNameBuffersStaticCstrName = "copyByteBuffer"; static const char * const ClazzNameBuffersStaticCstrSignature = "(Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer;"; @@ -98,6 +91,9 @@ static const char * const ClazzNameByteBuffer = "java/nio/ByteBuffer"; static const char * const ClazzNamePoint = "javax/media/nativewindow/util/Point"; static const char * const ClazzAnyCstrName = ""; static const char * const ClazzNamePointCstrSignature = "(II)V"; +static jclass X11UtilClazz = NULL; +static jmethodID getCurrentThreadNameID = NULL; +static jmethodID dumpStackID = NULL; static jclass clazzBuffers = NULL; static jmethodID cstrBuffers = NULL; static jclass clazzByteBuffer = NULL; @@ -109,6 +105,15 @@ static void _initClazzAccess(JNIEnv *env) { if(!NativewindowCommon_init(env)) return; + getCurrentThreadNameID = (*env)->GetStaticMethodID(env, X11UtilClazz, "getCurrentThreadName", "()Ljava/lang/String;"); + if(NULL==getCurrentThreadNameID) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't get method getCurrentThreadName"); + } + dumpStackID = (*env)->GetStaticMethodID(env, X11UtilClazz, "dumpStack", "()V"); + if(NULL==dumpStackID) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't get method dumpStack"); + } + c = (*env)->FindClass(env, ClazzNameBuffers); if(NULL==c) { NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNameBuffers); @@ -162,66 +167,71 @@ static void setupJVMVars(JNIEnv * env) { } static XErrorHandler origErrorHandler = NULL ; -static int errorHandlerBlocked = 0 ; static int errorHandlerQuiet = 0 ; +static int errorHandlerDebug = 0 ; +static int errorHandlerThrowException = 0; static int x11ErrorHandler(Display *dpy, XErrorEvent *e) { if(!errorHandlerQuiet) { - JNIEnv *curEnv = NULL; - JNIEnv *newEnv = NULL; - int envRes ; - const char * errStr = strerror(errno); + const char * errnoStr = strerror(errno); + char threadName[80]; + char errCodeStr[80]; + char reqCodeStr[80]; - fprintf(stderr, "Info: Nativewindow X11 Error: Display %p, Code 0x%X, errno %s\n", dpy, e->error_code, errStr); - fflush(stderr); + int shallBeDetached = 0; + JNIEnv *jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); - // retrieve this thread's JNIEnv curEnv - or detect it's detached - envRes = (*jvmHandle)->GetEnv(jvmHandle, (void **) &curEnv, jvmVersion) ; - if( JNI_EDETACHED == envRes ) { - // detached thread - attach to JVM - if( JNI_OK != ( envRes = (*jvmHandle)->AttachCurrentThread(jvmHandle, (void**) &newEnv, NULL) ) ) { - fprintf(stderr, "Nativewindow X11 Error: can't attach thread: %d\n", envRes); - return 0; + (void) NativewindowCommon_GetStaticStringMethod(jniEnv, X11UtilClazz, getCurrentThreadNameID, threadName, sizeof(threadName), "n/a"); + snprintf(errCodeStr, sizeof(errCodeStr), "%d", e->request_code); + XGetErrorDatabaseText(dpy, "XRequest", errCodeStr, "Unknown", reqCodeStr, sizeof(reqCodeStr)); + XGetErrorText(dpy, e->error_code, errCodeStr, sizeof(errCodeStr)); + + fprintf(stderr, "Info: Nativewindow X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", + threadName, e->error_code, errCodeStr, e->display, e->resourceid, e->serial, + e->request_code, e->minor_code, reqCodeStr); + + if( errorHandlerDebug ) { + (*jniEnv)->CallStaticVoidMethod(jniEnv, X11UtilClazz, dumpStackID); + } + + if(errorHandlerThrowException) { + if(NULL != jniEnv) { + NativewindowCommon_throwNewRuntimeException(jniEnv, "Nativewindow X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", + threadName, e->error_code, errCodeStr, e->display, e->resourceid, e->serial, + e->request_code, e->minor_code, reqCodeStr); + } else { + fprintf(stderr, "Nativewindow X11 Error: null JNIEnv"); + #if 0 + if(NULL!=origErrorHandler) { + origErrorHandler(dpy, e); + } + #endif } - curEnv = newEnv; - } else if( JNI_OK != envRes ) { - // oops .. - fprintf(stderr, "Nativewindow X11 Error: can't GetEnv: %d\n", envRes); - return 0; } - NativewindowCommon_throwNewRuntimeException(curEnv, "Info: Nativewindow X11 Error: Display %p, Code 0x%X, errno %s", - dpy, e->error_code, errStr); + fflush(stderr); - if( NULL != newEnv ) { - // detached attached thread + if (NULL != jniEnv && shallBeDetached) { (*jvmHandle)->DetachCurrentThread(jvmHandle); } } -#if 0 - if(NULL!=origErrorHandler) { - origErrorHandler(dpy, e); - } -#endif - return 0; } -static void x11ErrorHandlerEnable(Display *dpy, int onoff, JNIEnv * env) { - if(errorHandlerBlocked) return; - +void NativewindowCommon_x11ErrorHandlerEnable(JNIEnv * env, Display *dpy, int onoff, int quiet, int sync) { + errorHandlerQuiet = quiet; if(onoff) { if(NULL==origErrorHandler) { setupJVMVars(env); - if(NULL!=dpy) { + origErrorHandler = XSetErrorHandler(x11ErrorHandler); + if(sync && NULL!=dpy) { XSync(dpy, False); } - origErrorHandler = XSetErrorHandler(x11ErrorHandler); } } else { if(NULL!=origErrorHandler) { - if(NULL!=dpy) { + if(sync && NULL!=dpy) { XSync(dpy, False); } XSetErrorHandler(origErrorHandler); @@ -230,46 +240,27 @@ static void x11ErrorHandlerEnable(Display *dpy, int onoff, JNIEnv * env) { } } -static void x11ErrorHandlerEnableBlocking(JNIEnv * env, int onoff, int quiet) { - errorHandlerBlocked = 0 ; - x11ErrorHandlerEnable(NULL, onoff, env); - errorHandlerBlocked = onoff ; - errorHandlerQuiet = quiet; -} - - static XIOErrorHandler origIOErrorHandler = NULL; static int x11IOErrorHandler(Display *dpy) { - JNIEnv *curEnv = NULL; - JNIEnv *newEnv = NULL; - int envRes ; const char * dpyName = XDisplayName(NULL); - const char * errStr = strerror(errno); + const char * errnoStr = strerror(errno); + char threadName[80]; + int shallBeDetached = 0; + JNIEnv *jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); - fprintf(stderr, "Nativewindow X11 IOError: Display %p (%s): %s\n", dpy, dpyName, errStr); + (void) NativewindowCommon_GetStaticStringMethod(jniEnv, X11UtilClazz, getCurrentThreadNameID, threadName, sizeof(threadName), "n/a"); - // retrieve this thread's JNIEnv curEnv - or detect it's detached - envRes = (*jvmHandle)->GetEnv(jvmHandle, (void **) &curEnv, jvmVersion) ; - if( JNI_EDETACHED == envRes ) { - // detached thread - attach to JVM - if( JNI_OK != ( envRes = (*jvmHandle)->AttachCurrentThread(jvmHandle, (void**) &newEnv, NULL) ) ) { - fprintf(stderr, "Nativewindow X11 IOError: can't attach thread: %d\n", envRes); - return; - } - curEnv = newEnv; - } else if( JNI_OK != envRes ) { - // oops .. - fprintf(stderr, "Nativewindow X11 IOError: can't GetEnv: %d\n", envRes); - return; - } + fprintf(stderr, "Nativewindow X11 IOError (Thread %s): Display %p (%s): %s\n", threadName, dpy, dpyName, errnoStr); + (*jniEnv)->CallStaticVoidMethod(jniEnv, X11UtilClazz, dumpStackID); - NativewindowCommon_FatalError(curEnv, "Nativewindow X11 IOError: Display %p (%s): %s", dpy, dpyName, errStr); + if (NULL != jniEnv) { + NativewindowCommon_FatalError(jniEnv, "Nativewindow X11 IOError (Thread %s): Display %p (%s): %s", threadName, dpy, dpyName, errnoStr); - if( NULL != newEnv ) { - // detached attached thread - (*jvmHandle)->DetachCurrentThread(jvmHandle); + if (shallBeDetached) { + (*jvmHandle)->DetachCurrentThread(jvmHandle); + } } if(NULL!=origIOErrorHandler) { origIOErrorHandler(dpy); @@ -293,22 +284,31 @@ static int _initialized=0; static jboolean _xinitThreadsOK=JNI_FALSE; JNIEXPORT jboolean JNICALL -Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass _unused, jboolean firstUIActionOnProcess) { +Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass clazz, jboolean firstUIActionOnProcess, jboolean debug) { if(0==_initialized) { + if(debug) { + errorHandlerDebug = 1; + } + X11UtilClazz = (jclass)(*env)->NewGlobalRef(env, clazz); if( JNI_TRUE == firstUIActionOnProcess ) { if( 0 == XInitThreads() ) { fprintf(stderr, "Warning: XInitThreads() failed\n"); } else { _xinitThreadsOK=JNI_TRUE; - DBG_PRINT( "X11: XInitThreads() called for concurrent Thread support\n"); + if(debug) { + fprintf(stderr, "X11: XInitThreads() called for concurrent Thread support\n"); + } } - } else { - DBG_PRINT( "X11: XInitThreads() _not_ called for concurrent Thread support\n"); + } else if(debug) { + fprintf(stderr, "X11: XInitThreads() _not_ called for concurrent Thread support\n"); } _initClazzAccess(env); x11IOErrorHandlerEnable(1, env); _initialized=1; + if(JNI_TRUE == debug) { + fprintf(stderr, "Info: NativeWindow native init passed\n"); + } } return _xinitThreadsOK; } @@ -320,7 +320,7 @@ Java_jogamp_nativewindow_x11_X11Util_shutdown0(JNIEnv *env, jclass _unused) { JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Util_setX11ErrorHandler0(JNIEnv *env, jclass _unused, jboolean onoff, jboolean quiet) { - x11ErrorHandlerEnableBlocking(env, ( JNI_TRUE == onoff ) ? 1 : 0, ( JNI_TRUE == quiet ) ? 1 : 0); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, onoff ? 1 : 0, quiet ? 1 : 0, 0 /* no dpy, no sync */); } /* Java->C glue code: @@ -345,9 +345,9 @@ Java_jogamp_nativewindow_x11_X11Lib_XGetVisualInfo1__JJLjava_nio_ByteBuffer_2Lja if (arg3 != NULL) { _ptr3 = (int *) (((char*) (*env)->GetPrimitiveArrayCritical(env, arg3, NULL)) + arg3_byte_offset); } - x11ErrorHandlerEnable((Display *) (intptr_t) arg0, 1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 1, 0, 0); _res = XGetVisualInfo((Display *) (intptr_t) arg0, (long) arg1, (XVisualInfo *) _ptr2, (int *) _ptr3); - x11ErrorHandlerEnable((Display *) (intptr_t) arg0, 0, env); + NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 0, 0); count = _ptr3[0]; if (arg3 != NULL) { (*env)->ReleasePrimitiveArrayCritical(env, arg3, _ptr3, 0); @@ -368,9 +368,9 @@ Java_jogamp_nativewindow_x11_X11Lib_DefaultVisualID(JNIEnv *env, jclass _unused, if(0==display) { NativewindowCommon_FatalError(env, "invalid display connection.."); } - x11ErrorHandlerEnable((Display *) (intptr_t) display, 1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 1, 0, 0); r = (jlong) XVisualIDFromVisual( DefaultVisual( (Display*) (intptr_t) display, screen ) ); - x11ErrorHandlerEnable((Display *) (intptr_t) display, 0, env); + NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 0, 0); return r; } @@ -411,9 +411,9 @@ Java_jogamp_nativewindow_x11_X11Lib_XCloseDisplay__J(JNIEnv *env, jclass _unused if(0==display) { NativewindowCommon_FatalError(env, "invalid display connection.."); } - x11ErrorHandlerEnable((Display *) (intptr_t) display, 1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, 0, 0); _res = XCloseDisplay((Display *) (intptr_t) display); - x11ErrorHandlerEnable(NULL, 0, env); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, 0); return _res; } @@ -451,7 +451,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow return 0; } - x11ErrorHandlerEnable(dpy, 1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); scrn = ScreenOfDisplay(dpy, scrn_idx); @@ -471,7 +471,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow if (visual==NULL) { - x11ErrorHandlerEnable(dpy, 0, env); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); NativewindowCommon_throwNewRuntimeException(env, "could not query Visual by given VisualID, bail out!"); return 0; } @@ -511,13 +511,11 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow visual, attrMask, &xswa); - XSync(dpy, False); XSelectInput(dpy, window, 0); // no events - XSync(dpy, False); - x11ErrorHandlerEnable(dpy, 0, env); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); DBG_PRINT( "X11: [CreateWindow] created window %p on display %p\n", window, dpy); @@ -541,11 +539,11 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_DestroyDummyWindow return; } - x11ErrorHandlerEnable(dpy, 1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); XUnmapWindow(dpy, w); XSync(dpy, False); XDestroyWindow(dpy, w); - x11ErrorHandlerEnable(dpy, 0, env); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); } /* @@ -569,11 +567,11 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_x11_X11Lib_GetRelativeLocatio if( 0 == jdest_win ) { dest_win = root; } if( 0 == jsrc_win ) { src_win = root; } - x11ErrorHandlerEnable(dpy, 1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); res = XTranslateCoordinates(dpy, src_win, dest_win, src_x, src_y, &dest_x, &dest_y, &child); - x11ErrorHandlerEnable(dpy, 0, env); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0); DBG_PRINT( "X11: GetRelativeLocation0: %p %d/%d -> %p %d/%d - ok: %d\n", (void*)src_win, src_x, src_y, (void*)dest_win, dest_x, dest_y, (int)res); diff --git a/src/nativewindow/native/x11/Xmisc.h b/src/nativewindow/native/x11/Xmisc.h new file mode 100644 index 000000000..a44da950d --- /dev/null +++ b/src/nativewindow/native/x11/Xmisc.h @@ -0,0 +1,44 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +#ifndef Xmisc_h +#define Xmisc_h + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void NativewindowCommon_x11ErrorHandlerEnable(JNIEnv * env, Display *dpy, int onoff, int quiet, int sync); + +#endif /* Xmisc_h */ diff --git a/src/newt/classes/jogamp/newt/driver/x11/X11Display.java b/src/newt/classes/jogamp/newt/driver/x11/X11Display.java index 9464b979b..8243fcf9d 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/X11Display.java +++ b/src/newt/classes/jogamp/newt/driver/x11/X11Display.java @@ -49,7 +49,7 @@ public class X11Display extends DisplayImpl { static { NEWTJNILibLoader.loadNEWT(); - if ( !initIDs0() ) { + if ( !initIDs0(X11Util.XERROR_STACKDUMP) ) { throw new NativeWindowException("Failed to initialize X11Display jmethodIDs"); } @@ -139,7 +139,7 @@ public class X11Display extends DisplayImpl { //---------------------------------------------------------------------- // Internals only // - private static native boolean initIDs0(); + private static native boolean initIDs0(boolean debug); private native void CompleteDisplay0(long handle); diff --git a/src/newt/classes/jogamp/newt/driver/x11/X11Window.java b/src/newt/classes/jogamp/newt/driver/x11/X11Window.java index 143b94a57..9a5074c29 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/X11Window.java +++ b/src/newt/classes/jogamp/newt/driver/x11/X11Window.java @@ -230,6 +230,9 @@ public class X11Window extends WindowImpl { // Internals only // + private static final String getCurrentThreadName() { return Thread.currentThread().getName(); } // Callback for JNI + private static final void dumpStack() { Thread.dumpStack(); } // Callback for JNI + private final long getDisplayEDTHandle() { return ((X11Display) getScreen().getDisplay()).getEDTHandle(); } diff --git a/src/newt/native/NewtCommon.c b/src/newt/native/NewtCommon.c index 3713cfd6c..7f070e7d3 100644 --- a/src/newt/native/NewtCommon.c +++ b/src/newt/native/NewtCommon.c @@ -1,5 +1,6 @@ #include "NewtCommon.h" +#include static const char * const ClazzNameRuntimeException = "java/lang/RuntimeException"; static jclass runtimeExceptionClz=NULL; @@ -43,6 +44,24 @@ void NewtCommon_init(JNIEnv *env) { } } +const char * NewtCommon_GetStaticStringMethod(JNIEnv *jniEnv, jclass clazz, jmethodID jGetStrID, char *dest, int destSize, const char *altText) { + if(NULL != jniEnv && NULL != clazz && NULL != jGetStrID) { + jstring jstr = (jstring) (*jniEnv)->CallStaticObjectMethod(jniEnv, clazz, jGetStrID); + if(NULL != jstr) { + const char * str = (*jniEnv)->GetStringUTFChars(jniEnv, jstr, NULL); + if( NULL != str) { + strncpy(dest, str, destSize-1); + dest[destSize-1] = 0; // EOS + (*jniEnv)->ReleaseStringUTFChars(jniEnv, jstr, str); + return dest; + } + } + } + strncpy(dest, altText, destSize-1); + dest[destSize-1] = 0; // EOS + return dest; +} + jchar* NewtCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str) { jchar* strChars = NULL; diff --git a/src/newt/native/NewtCommon.h b/src/newt/native/NewtCommon.h index f5ca73b74..9a4e5ac70 100644 --- a/src/newt/native/NewtCommon.h +++ b/src/newt/native/NewtCommon.h @@ -34,6 +34,7 @@ void NewtCommon_init(JNIEnv *env); +const char * NewtCommon_GetStaticStringMethod(JNIEnv *jniEnv, jclass clazz, jmethodID jGetStrID, char *dest, int destSize, const char *altText); jchar* NewtCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str); void NewtCommon_FatalError(JNIEnv *env, const char* msg, ...); diff --git a/src/newt/native/X11Common.h b/src/newt/native/X11Common.h index cefef690f..982255b8a 100644 --- a/src/newt/native/X11Common.h +++ b/src/newt/native/X11Common.h @@ -70,9 +70,9 @@ extern jclass X11NewtWindowClazz; extern jmethodID insetsChangedID; extern jmethodID visibleChangedID; +void NewtDisplay_x11ErrorHandlerEnable(JNIEnv * env, Display *dpy, int onoff, int quiet, int sync); jobject getJavaWindowProperty(JNIEnv *env, Display *dpy, Window window, jlong javaObjectAtom, Bool showWarning); -void NewtDisplay_displayDispatchErrorHandlerEnable(int onoff, JNIEnv * env); Status NewtWindows_getRootAndParent (Display *dpy, Window w, Window * root_return, Window * parent_return); Status NewtWindows_updateInsets(JNIEnv *env, jobject jwindow, Display *dpy, Window window, int *left, int *right, int *top, int *bottom); diff --git a/src/newt/native/X11Display.c b/src/newt/native/X11Display.c index 88ac0df7e..5e2dc7c61 100644 --- a/src/newt/native/X11Display.c +++ b/src/newt/native/X11Display.c @@ -38,6 +38,8 @@ static const char * const ClazzNameX11NewtWindow = "jogamp/newt/driver/x11/X11Wi static jmethodID displayCompletedID = NULL; +static jmethodID getCurrentThreadNameID = NULL; +static jmethodID dumpStackID = NULL; static jmethodID sizeChangedID = NULL; static jmethodID positionChangedID = NULL; static jmethodID focusChangedID = NULL; @@ -61,32 +63,51 @@ static void setupJVMVars(JNIEnv * env) { } static XErrorHandler origErrorHandler = NULL ; +static int errorHandlerQuiet = 0 ; +static int errorHandlerDebug = 0 ; +static int errorHandlerThrowException = 0; -static int displayDispatchErrorHandler(Display *dpy, XErrorEvent *e) +static int x11ErrorHandler(Display *dpy, XErrorEvent *e) { - fprintf(stderr, "Warning: NEWT X11 Error: DisplayDispatch %p, Code 0x%X, errno %s\n", dpy, e->error_code, strerror(errno)); - - if (e->error_code == BadAtom) { - fprintf(stderr, " BadAtom (%p): Atom probably already removed\n", (void*)e->resourceid); - } else if (e->error_code == BadWindow) { - fprintf(stderr, " BadWindow (%p): Window probably already removed\n", (void*)e->resourceid); - } else { + if(!errorHandlerQuiet) { + const char * errnoStr = strerror(errno); + char threadName[80]; + char errCodeStr[80]; + char reqCodeStr[80]; + int shallBeDetached = 0; - JNIEnv *jniEnv = NULL; - const char * errStr = strerror(errno); + JNIEnv *jniEnv = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); - fprintf(stderr, "Info: NEWT X11 Error: Display %p, Code 0x%X, errno %s\n", dpy, e->error_code, errStr); + (void) NewtCommon_GetStaticStringMethod(jniEnv, X11NewtWindowClazz, getCurrentThreadNameID, threadName, sizeof(threadName), "n/a"); + snprintf(errCodeStr, sizeof(errCodeStr), "%d", e->request_code); + XGetErrorDatabaseText(dpy, "XRequest", errCodeStr, "Unknown", reqCodeStr, sizeof(reqCodeStr)); + XGetErrorText(dpy, e->error_code, errCodeStr, sizeof(errCodeStr)); - jniEnv = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); - if(NULL==jniEnv) { - fprintf(stderr, "NEWT X11 Error: null JNIEnv"); - return; + fprintf(stderr, "Info: Newt X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", + threadName, e->error_code, errCodeStr, e->display, e->resourceid, e->serial, + e->request_code, e->minor_code, reqCodeStr); + + if( errorHandlerDebug ) { + (*jniEnv)->CallStaticVoidMethod(jniEnv, X11NewtWindowClazz, dumpStackID); } - NewtCommon_throwNewRuntimeException(jniEnv, "Info: NEWT X11 Error: Display %p, Code 0x%X, errno %s", - dpy, e->error_code, errStr); + if(errorHandlerThrowException) { + if(NULL != jniEnv) { + NewtCommon_throwNewRuntimeException(jniEnv, "Newt X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", + threadName, e->error_code, errCodeStr, e->display, e->resourceid, e->serial, + e->request_code, e->minor_code, reqCodeStr); + } else { + fprintf(stderr, "Nativewindow X11 Error: null JNIEnv"); + #if 0 + if(NULL!=origErrorHandler) { + origErrorHandler(dpy, e); + } + #endif + } + } + fflush(stderr); - if (shallBeDetached) { + if (NULL != jniEnv && shallBeDetached) { (*jvmHandle)->DetachCurrentThread(jvmHandle); } } @@ -94,14 +115,21 @@ static int displayDispatchErrorHandler(Display *dpy, XErrorEvent *e) return 0; } -void NewtDisplay_displayDispatchErrorHandlerEnable(int onoff, JNIEnv * env) { +void NewtDisplay_x11ErrorHandlerEnable(JNIEnv * env, Display *dpy, int onoff, int quiet, int sync) { + errorHandlerQuiet = quiet; if(onoff) { if(NULL==origErrorHandler) { setupJVMVars(env); - origErrorHandler = XSetErrorHandler(displayDispatchErrorHandler); + origErrorHandler = XSetErrorHandler(x11ErrorHandler); + if(sync && NULL!=dpy) { + XSync(dpy, False); + } } } else { if(NULL!=origErrorHandler) { + if(sync && NULL!=dpy) { + XSync(dpy, False); + } XSetErrorHandler(origErrorHandler); origErrorHandler = NULL; } @@ -241,10 +269,13 @@ static jint X11InputState2NewtModifiers(unsigned int xstate) { * Signature: (Z)Z */ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Display_initIDs0 - (JNIEnv *env, jclass clazz) + (JNIEnv *env, jclass clazz, jboolean debug) { jclass c; + if(debug) { + errorHandlerDebug = 1 ; + } NewtCommon_init(env); if(NULL==X11NewtWindowClazz) { @@ -260,6 +291,8 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Display_initIDs0 } displayCompletedID = (*env)->GetMethodID(env, clazz, "displayCompleted", "(JJ)V"); + getCurrentThreadNameID = (*env)->GetStaticMethodID(env, X11NewtWindowClazz, "getCurrentThreadName", "()Ljava/lang/String;"); + dumpStackID = (*env)->GetStaticMethodID(env, X11NewtWindowClazz, "dumpStack", "()V"); insetsChangedID = (*env)->GetMethodID(env, X11NewtWindowClazz, "insetsChanged", "(ZIIII)V"); sizeChangedID = (*env)->GetMethodID(env, X11NewtWindowClazz, "sizeChanged", "(ZIIZ)V"); positionChangedID = (*env)->GetMethodID(env, X11NewtWindowClazz, "positionChanged", "(ZII)V"); @@ -275,6 +308,8 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Display_initIDs0 requestFocusID = (*env)->GetMethodID(env, X11NewtWindowClazz, "requestFocus", "(Z)V"); if (displayCompletedID == NULL || + getCurrentThreadNameID == NULL || + dumpStackID == NULL || insetsChangedID == NULL || sizeChangedID == NULL || positionChangedID == NULL || @@ -403,7 +438,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_DispatchMessages0 // DBG_PRINT( "X11: DispatchMessages dpy %p, win %p, Event %d\n", (void*)dpy, (void*)evt.xany.window, (int)evt.type); - NewtDisplay_displayDispatchErrorHandlerEnable(1, env); + NewtDisplay_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); jwindow = getJavaWindowProperty(env, dpy, evt.xany.window, javaObjectAtom, #ifdef VERBOSE_ON @@ -413,7 +448,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_DispatchMessages0 #endif ); - NewtDisplay_displayDispatchErrorHandlerEnable(0, env); + NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); if(NULL==jwindow) { fprintf(stderr, "Warning: NEWT X11 DisplayDispatch %p, Couldn't handle event %d for X11 window %p\n", diff --git a/src/newt/native/X11Window.c b/src/newt/native/X11Window.c index 0f93b3e76..daf9f2b53 100644 --- a/src/newt/native/X11Window.c +++ b/src/newt/native/X11Window.c @@ -683,12 +683,16 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_CloseWindow0 DBG_PRINT( "X11: CloseWindow START dpy %p, win %p\n", (void*)dpy, (void*)w); + NewtDisplay_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); + jwindow = getJavaWindowProperty(env, dpy, w, javaObjectAtom, True); if(NULL==jwindow) { + NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); NewtCommon_throwNewRuntimeException(env, "could not fetch Java Window object, bail out!"); return; } if ( JNI_FALSE == (*env)->IsSameObject(env, jwindow, obj) ) { + NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); NewtCommon_throwNewRuntimeException(env, "Internal Error .. Window global ref not the same!"); return; } @@ -696,7 +700,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_CloseWindow0 XSync(dpy, False); XSelectInput(dpy, w, 0); XUnmapWindow(dpy, w); - XSync(dpy, False); + NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); // Drain all events related to this window .. Java_jogamp_newt_driver_x11_X11Display_DispatchMessages0(env, obj, display, javaObjectAtom, windowDeleteAtom); @@ -757,7 +761,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_reconfigureWindow0 fsEWMHFlags |= _NET_WM_ABOVE; // toggle above } - NewtDisplay_displayDispatchErrorHandlerEnable(1, env); + NewtDisplay_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); DBG_PRINT( "X11: reconfigureWindow0 dpy %p, scrn %d, parent %p/%p, win %p, %d/%d %dx%d, parentChange %d, hasParent %d, decorationChange %d, undecorated %d, fullscreenChange %d, fullscreen %d, alwaysOnTopChange %d, alwaysOnTop %d, visibleChange %d, visible %d, tempInvisible %d, fsEWMHFlags %d\n", (void*)dpy, screen_index, (void*) jparent, (void*)parent, (void*)w, @@ -775,7 +779,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_reconfigureWindow0 ( TST_FLAG_CHANGE_FULLSCREEN(flags) || TST_FLAG_CHANGE_ALWAYSONTOP(flags) ) ) { Bool enable = TST_FLAG_CHANGE_FULLSCREEN(flags) ? TST_FLAG_IS_FULLSCREEN(flags) : TST_FLAG_IS_ALWAYSONTOP(flags) ; if( NewtWindows_setFullscreenEWMH(dpy, root, w, fsEWMHFlags, isVisible, enable) ) { - NewtDisplay_displayDispatchErrorHandlerEnable(0, env); + NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); #ifdef FS_GRAB_KEYBOARD if(TST_FLAG_CHANGE_FULLSCREEN(flags)) { if(TST_FLAG_IS_FULLSCREEN(flags)) { @@ -859,7 +863,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_reconfigureWindow0 #endif } - NewtDisplay_displayDispatchErrorHandlerEnable(0, env); + NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); DBG_PRINT( "X11: reconfigureWindow0 X\n"); } -- cgit v1.2.3 From 627a27581688e0b12300370c751e3823b1afe44b Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 6 Jul 2012 01:58:09 +0200 Subject: C code: remove warnings --- .../native/libav/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c | 6 +++--- src/nativewindow/native/x11/Xmisc.c | 8 ++++---- src/newt/native/X11Display.c | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/native/libav/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c b/src/jogl/native/libav/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c index 647de15ef..7fb64dade 100644 --- a/src/jogl/native/libav/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c +++ b/src/jogl/native/libav/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c @@ -572,7 +572,7 @@ JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_readNex (JNIEnv *env, jobject instance, jlong ptr, jlong jProcAddrGLTexSubImage2D, jint texTarget, jint texFmt, jint texType) { FFMPEGToolBasicAV_t *pAV = (FFMPEGToolBasicAV_t *)((void *)((intptr_t)ptr)); - PFNGLTEXSUBIMAGE2DPROC procAddrGLTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC) jProcAddrGLTexSubImage2D; + PFNGLTEXSUBIMAGE2DPROC procAddrGLTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC) (intptr_t)jProcAddrGLTexSubImage2D; jint res = 0; // 1 - audio, 2 - video AVPacket packet; @@ -694,10 +694,10 @@ JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_seek0 if(pos1 < pos0) { flags |= AVSEEK_FLAG_BACKWARD; } - fprintf(stderr, "SEEK: pre : u %d, p %d -> u %d, p %d\n", pos0, pts0, pos1, pts1); + fprintf(stderr, "SEEK: pre : u %ld, p %ld -> u %ld, p %ld\n", pos0, pts0, pos1, pts1); sp_av_seek_frame(pAV->pFormatCtx, pAV->vid, pts1, flags); pAV->vPTS = pAV->pVFrame->pkt_pts * my_av_q2i32(1000, pAV->pVStream->time_base); - fprintf(stderr, "SEEK: post : u %d, p %d\n", pAV->vPTS, pAV->pVFrame->pkt_pts); + fprintf(stderr, "SEEK: post : u %ld, p %ld\n", pAV->vPTS, pAV->pVFrame->pkt_pts); return pAV->vPTS; } diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 5cbf5c04a..21771c9aa 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -188,8 +188,8 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) XGetErrorText(dpy, e->error_code, errCodeStr, sizeof(errCodeStr)); fprintf(stderr, "Info: Nativewindow X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", - threadName, e->error_code, errCodeStr, e->display, e->resourceid, e->serial, - e->request_code, e->minor_code, reqCodeStr); + threadName, e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, + (int)e->request_code, (int)e->minor_code, reqCodeStr); if( errorHandlerDebug ) { (*jniEnv)->CallStaticVoidMethod(jniEnv, X11UtilClazz, dumpStackID); @@ -198,8 +198,8 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) if(errorHandlerThrowException) { if(NULL != jniEnv) { NativewindowCommon_throwNewRuntimeException(jniEnv, "Nativewindow X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", - threadName, e->error_code, errCodeStr, e->display, e->resourceid, e->serial, - e->request_code, e->minor_code, reqCodeStr); + threadName, e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, + (int)e->request_code, (int)e->minor_code, reqCodeStr); } else { fprintf(stderr, "Nativewindow X11 Error: null JNIEnv"); #if 0 diff --git a/src/newt/native/X11Display.c b/src/newt/native/X11Display.c index 5e2dc7c61..ce7d9a0e1 100644 --- a/src/newt/native/X11Display.c +++ b/src/newt/native/X11Display.c @@ -84,8 +84,8 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) XGetErrorText(dpy, e->error_code, errCodeStr, sizeof(errCodeStr)); fprintf(stderr, "Info: Newt X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", - threadName, e->error_code, errCodeStr, e->display, e->resourceid, e->serial, - e->request_code, e->minor_code, reqCodeStr); + threadName, e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, + (int)e->request_code, (int)e->minor_code, reqCodeStr); if( errorHandlerDebug ) { (*jniEnv)->CallStaticVoidMethod(jniEnv, X11NewtWindowClazz, dumpStackID); @@ -94,8 +94,8 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) if(errorHandlerThrowException) { if(NULL != jniEnv) { NewtCommon_throwNewRuntimeException(jniEnv, "Newt X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", - threadName, e->error_code, errCodeStr, e->display, e->resourceid, e->serial, - e->request_code, e->minor_code, reqCodeStr); + threadName, e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, + (int)e->request_code, (int)e->minor_code, reqCodeStr); } else { fprintf(stderr, "Nativewindow X11 Error: null JNIEnv"); #if 0 -- cgit v1.2.3 From dfee8c58d4915f78f57545c26a492668b2b68a87 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 6 Jul 2012 08:57:57 +0200 Subject: Fix SWT GLCanvas threading. Note: On OSX _only_ it's main thread is valid! --- make/scripts/tests-osx-x64-mainthread.sh | 11 +++ .../classes/com/jogamp/opengl/swt/GLCanvas.java | 99 +++++----------------- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 21 ++++- .../jogamp/nativewindow/macosx/OSXUtil.java | 22 +++++ .../test/junit/jogl/swt/TestSWTAccessor02GLn.java | 29 +++---- .../junit/jogl/swt/TestSWTAccessor03AWTGLn.java | 6 +- .../jogl/swt/TestSWTEclipseGLCanvas01GLn.java | 29 ++++--- .../junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java | 52 ++++++++---- 8 files changed, 143 insertions(+), 126 deletions(-) create mode 100644 make/scripts/tests-osx-x64-mainthread.sh (limited to 'src/nativewindow') diff --git a/make/scripts/tests-osx-x64-mainthread.sh b/make/scripts/tests-osx-x64-mainthread.sh new file mode 100644 index 000000000..bf95a9b67 --- /dev/null +++ b/make/scripts/tests-osx-x64-mainthread.sh @@ -0,0 +1,11 @@ + +export CLASSPATH=.:../../gluegen/make/../build-macosx/gluegen-rt.jar:../build-macosx/jar/jogl-all-noawt.jar:../build-macosx/jar/jogl-test.jar:../build-macosx/../make/lib/swt/cocoa-macosx-x86_64/swt-debug.jar:../../gluegen/make/../make/lib/junit.jar:/opt-share/apache-ant/lib/ant.jar:/opt-share/apache-ant/lib/ant-junit.jar:../build-macosx/jar/atomic/jogl-swt.jar:../build-macosx/jar/jogl-test.jar + +/usr/bin/java -d64 -XstartOnFirstThread -Djava.awt.headless=true com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn +#/usr/bin/java -d64 -XstartOnFirstThread -Djava.awt.headless=false com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn + +# +# Not working! +#/usr/bin/java -d64 -Djava.awt.headless=true com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn +#/usr/bin/java -d64 -Djava.awt.headless=false com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn + diff --git a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java index 571f5c5b2..5ee58b78d 100644 --- a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java +++ b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java @@ -47,7 +47,6 @@ import javax.media.opengl.Threading; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableHelper; -import jogamp.opengl.ThreadingImpl; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; @@ -62,6 +61,7 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import com.jogamp.common.GlueGenVersion; +import com.jogamp.common.os.Platform; import com.jogamp.common.util.VersionUtil; import com.jogamp.nativewindow.swt.SWTAccessor; import com.jogamp.opengl.JoglVersion; @@ -69,10 +69,6 @@ import com.jogamp.opengl.JoglVersion; /** * Native SWT Canvas implementing GLAutoDrawable *

- * FIXME: Still needs AWT for threading impl., - * ie. will issue a 'wrong thread' error if runs in headless mode! - *

- *

* FIXME: If this instance runs in multithreading mode, see {@link Threading#isSingleThreaded()} (impossible), * proper recursive locking is required for drawable/context @ destroy and display. * Recreation etc could pull those instances while animating! @@ -86,12 +82,6 @@ import com.jogamp.opengl.JoglVersion; However, since the user shall stick to the GLEventListener model while utilizing GLAutoDrawable implementations, she is safe due to the implicit locked state. *

- *

- * FIXME: [MT-2] Revise threading code - The logic whether to spawn off the GL task and - determination which thread to use is too complex and redundant. - (See isRenderThread(), runInGLThread() and runInDesignatedGLThread()) - *

*/ public class GLCanvas extends Canvas implements GLAutoDrawable { @@ -307,7 +297,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { @Override public void display() { - runInGLThread(makeCurrentAndDisplayAction, displayAction); + runInGLThread(makeCurrentAndDisplayAction); } @Override @@ -458,7 +448,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { @Override public void swapBuffers() throws GLException { - runInGLThread(makeCurrentAndSwapBuffersAction, swapBuffersAction); + runInGLThread(makeCurrentAndSwapBuffersAction); } // FIXME: API of update() method ? @@ -478,11 +468,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { } if(context.isCreated()) { - if (Threading.isSingleThreaded() && !Threading.isOpenGLThread()) { - runInDesignatedGLThread(disposeOnEDTGLAction); - } else if (context.isCreated()) { - helper.disposeGL(GLCanvas.this, drawable, context, postDisposeGLAction); - } + runInGLThread(disposeOnEDTGLAction); } if (animatorPaused) { @@ -500,70 +486,29 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { } /** - * Determines whether the current thread is the appropriate thread to use the GLContext in. If we are using one of - * the single-threaded policies in {@link Threading}, than this is either the SWT event dispatch thread, or the - * OpenGL worker thread depending on the state of {@link #useSWTThread}. Otherwise this always returns true because - * the threading model is user defined. - *

- * FIXME: Redundant .. remove! Merge isRenderThread, runInGLThread and runInDesignatedGLThread - * - * @return true if the calling thread is the correct thread to execute OpenGL calls in, false otherwise. - */ - protected boolean isRenderThread() { - if (Threading.isSingleThreaded()) { - if (ThreadingImpl.getMode() != ThreadingImpl.Mode.ST_WORKER) { - final Display display = getDisplay(); - return display != null && display.getThread() == Thread.currentThread(); - } - return Threading.isOpenGLThread(); - } - /* - * For multi-threaded rendering, the render thread is not defined... - */ - return true; - } - - /** - * Runs the specified action in the designated OpenGL thread. If the current thread is designated, then the - * syncAction is run synchronously, otherwise the asyncAction is dispatched to the appropriate worker thread. - * - * @param asyncAction - * The non-null action to dispatch to an OpenGL worker thread. This action should not assume that a - * GLContext is current when invoked. - * @param syncAction - * The non-null action to run synchronously if the current thread is designated to handle OpenGL calls. - * This action may assume the GLContext is current. - * FIXME: Redundant .. remove! Merge isRenderThread, runInGLThread and runInDesignatedGLThread + * Runs the specified action in an SWT compatible thread, which is: + *

    + *
  • Mac OSX + *
      + * + *
    • Main Thread: Run on OSX UI main thread.
    • + *
  • + *
  • Linux, Windows, .. + *
      + *
    • Use {@link Threading#invokeOnOpenGLThread(boolean, Runnable)}
    • + *
  • + *
+ * @see Platform#AWT_AVAILABLE + * @see Platform#getOSType() */ - private void runInGLThread(final Runnable asyncAction, final Runnable syncAction) { - if (Threading.isSingleThreaded() && !isRenderThread()) { - /* Run in designated GL thread */ - runInDesignatedGLThread(asyncAction); + private void runInGLThread(final Runnable action) { + if(Platform.OSType.MACOS == Platform.OS_TYPE) { + SWTAccessor.invoke(true, action); } else { - /* Run in current thread... */ - helper.invokeGL(drawable, context, syncAction, initAction); + Threading.invokeOnOpenGLThread(true, action); } } - /** - * Dispatches the specified runnable to the appropriate OpenGL worker thread (either the SWT event dispatch thread, - * or the OpenGL worker thread depending on the state of {@link #useSWTThread}). - * - * @param makeCurrentAndRunAction - * The non-null action to dispatch. - * FIXME: Redundant .. remove! Merge isRenderThread, runInGLThread and runInDesignatedGLThread - */ - private void runInDesignatedGLThread(final Runnable makeCurrentAndRunAction) { - if (ThreadingImpl.getMode() != ThreadingImpl.Mode.ST_WORKER) { - final Display display = getDisplay(); - assert display.getThread() != Thread.currentThread() : "Incorrect use of thread dispatching."; - display.syncExec(makeCurrentAndRunAction); - } else { - Threading.invokeOnOpenGLThread(true, makeCurrentAndRunAction); - } - } - - public static void main(final String[] args) { System.err.println(VersionUtil.getPlatformInfo()); System.err.println(GlueGenVersion.getInstance()); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index f4309617b..735d85fb1 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -37,11 +37,13 @@ import org.eclipse.swt.widgets.Control; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowFactory; + import com.jogamp.common.util.ReflectionUtil; import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsDevice; +import jogamp.common.awt.AWTEDTExecutor; import jogamp.nativewindow.macosx.OSXUtil; public class SWTAccessor { @@ -254,8 +256,25 @@ public class SWTAccessor { }); } + /** + * Runs the specified action in an SWT compatible thread, which is: + *
    + *
  • Mac OSX + *
      + * + *
    • Main Thread: Run on OSX UI main thread.
    • + *
  • + *
  • Linux, Windows, .. + *
      + *
    • Current thread.
    • + *
  • + *
+ * @see Platform#AWT_AVAILABLE + * @see Platform#getOSType() + */ public static void invoke(boolean wait, Runnable runnable) { - if(Platform.OS_TYPE == Platform.OSType.MACOS) { + if( Platform.OS_TYPE == Platform.OSType.MACOS ) { + // Use SWT main thread! Only reliable config w/ -XStartOnMainThread !? OSXUtil.RunOnMainThread(wait, runnable); } else { runnable.run(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 94f949ea3..2cd87f276 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -30,6 +30,7 @@ package jogamp.nativewindow.macosx; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.util.Point; +import jogamp.common.awt.AWTEDTExecutor; import jogamp.nativewindow.Debug; import jogamp.nativewindow.NWJNILibLoader; @@ -111,6 +112,27 @@ public class OSXUtil { return IsMainThread0(); } + /*** + private static boolean isAWTEDTMainThreadInit = false; + private static boolean isAWTEDTMainThread; + + public synchronized static boolean isAWTEDTMainThread() { + if(!isAWTEDTMainThreadInit) { + isAWTEDTMainThreadInit = true; + if(Platform.AWT_AVAILABLE) { + AWTEDTExecutor.singleton.invoke(true, new Runnable() { + public void run() { + isAWTEDTMainThread = IsMainThread(); + System.err.println("XXX: "+Thread.currentThread().getName()+" - isAWTEDTMainThread "+isAWTEDTMainThread); + } + }); + } else { + isAWTEDTMainThread = false; + } + } + return isAWTEDTMainThread; + } */ + private static native boolean initIDs0(); private static native Object GetLocationOnScreen0(long windowOrView, int src_x, int src_y); private static native long CreateNSView0(int x, int y, int width, int height); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor02GLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor02GLn.java index 0c350255e..2121205e2 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor02GLn.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor02GLn.java @@ -85,26 +85,17 @@ public class TestSWTAccessor02GLn extends UITestCase { @Before public void init() { - final Display[] r = new Display[1]; - final Shell[] s = new Shell[1]; SWTAccessor.invoke(true, new Runnable() { - public void run() { - r[0] = new Display(); - s[0] = new Shell(); - } - }); - display = r[0]; - shell = s[0]; - Assert.assertNotNull( display ); - Assert.assertNotNull( shell ); - - SWTAccessor.invoke(true, new Runnable() { - public void run() { - shell.setLayout( new FillLayout() ); - composite = new Composite( shell, SWT.NONE ); - Assert.assertNotNull( composite ); - composite.setLayout( new FillLayout() ); - }}); + public void run() { + display = new Display(); + Assert.assertNotNull( display ); + shell = new Shell( display ); + Assert.assertNotNull( shell ); + shell.setLayout( new FillLayout() ); + composite = new Composite( shell, SWT.NONE ); + composite.setLayout( new FillLayout() ); + Assert.assertNotNull( composite ); + }}); } @After diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor03AWTGLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor03AWTGLn.java index 966b39c57..ad8da8ad0 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor03AWTGLn.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor03AWTGLn.java @@ -75,7 +75,11 @@ public class TestSWTAccessor03AWTGLn extends UITestCase { @BeforeClass public static void startup() { - System.out.println( "GLProfile " + GLProfile.glAvailabilityToString() ); + System.out.println( "GLProfile " + GLProfile.glAvailabilityToString() ); + Frame f0 = new Frame("Test - AWT 1st"); + f0.add(new java.awt.Label("AWT was here 1st")); + f0.pack(); + f0.setVisible(true); if(!GLProfile.isAvailable(GLProfile.GL2)) { setTestSupported(false); } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTEclipseGLCanvas01GLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTEclipseGLCanvas01GLn.java index f38d5c7dc..0bd47c980 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTEclipseGLCanvas01GLn.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTEclipseGLCanvas01GLn.java @@ -53,6 +53,7 @@ import org.junit.BeforeClass; import org.junit.After; import org.junit.Test; +import com.jogamp.nativewindow.swt.SWTAccessor; import com.jogamp.opengl.test.junit.jogl.demos.es1.OneTriangle; import com.jogamp.opengl.test.junit.util.UITestCase; @@ -81,14 +82,17 @@ public class TestSWTEclipseGLCanvas01GLn extends UITestCase { @Before public void init() { - display = new Display(); - Assert.assertNotNull( display ); - shell = new Shell( display ); - Assert.assertNotNull( shell ); - shell.setLayout( new FillLayout() ); - composite = new Composite( shell, SWT.NONE ); - composite.setLayout( new FillLayout() ); - Assert.assertNotNull( composite ); + SWTAccessor.invoke(true, new Runnable() { + public void run() { + display = new Display(); + Assert.assertNotNull( display ); + shell = new Shell( display ); + Assert.assertNotNull( shell ); + shell.setLayout( new FillLayout() ); + composite = new Composite( shell, SWT.NONE ); + composite.setLayout( new FillLayout() ); + Assert.assertNotNull( composite ); + }}); } @After @@ -97,9 +101,12 @@ public class TestSWTEclipseGLCanvas01GLn extends UITestCase { Assert.assertNotNull( shell ); Assert.assertNotNull( composite ); try { - composite.dispose(); - shell.dispose(); - display.dispose(); + SWTAccessor.invoke(true, new Runnable() { + public void run() { + composite.dispose(); + shell.dispose(); + display.dispose(); + }}); } catch( Throwable throwable ) { throwable.printStackTrace(); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java index addb14ce5..ba33aa31d 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java @@ -34,6 +34,8 @@ import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; +import jogamp.nativewindow.macosx.OSXUtil; + import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; @@ -47,6 +49,8 @@ import org.junit.BeforeClass; import org.junit.After; import org.junit.Test; +import com.jogamp.common.os.Platform; +import com.jogamp.nativewindow.swt.SWTAccessor; import com.jogamp.opengl.swt.GLCanvas; import com.jogamp.opengl.test.junit.jogl.demos.es1.OneTriangle; import com.jogamp.opengl.test.junit.util.UITestCase; @@ -57,10 +61,10 @@ import com.jogamp.opengl.test.junit.util.UITestCase; * Uses JOGL's new SWT GLCanvas. *

*

- * Holds AWT in it's test name, since our impl. still needs the AWT threading, - * see {@link GLCanvas}. + * Note that {@link SWTAccessor#invoke(boolean, Runnable)} is still used to comply w/ + * SWT running on Mac OSX, i.e. to enforce UI action on the main thread. *

- * @author Wade Walker, et.al. + * @author Wade Walker, et al. */ public class TestSWTJOGLGLCanvas01GLn extends UITestCase { @@ -76,18 +80,24 @@ public class TestSWTJOGLGLCanvas01GLn extends UITestCase { @BeforeClass public static void startup() { System.out.println( "GLProfile " + GLProfile.glAvailabilityToString() ); + if( Platform.OS_TYPE == Platform.OSType.MACOS ) { + System.err.println("OSXUtil.isAWTEDTMainThread: "+ OSXUtil.isAWTEDTMainThread() ); + } } @Before public void init() { - display = new Display(); - Assert.assertNotNull( display ); - shell = new Shell( display ); - Assert.assertNotNull( shell ); - shell.setLayout( new FillLayout() ); - composite = new Composite( shell, SWT.NONE ); - composite.setLayout( new FillLayout() ); - Assert.assertNotNull( composite ); + SWTAccessor.invoke(true, new Runnable() { + public void run() { + display = new Display(); + Assert.assertNotNull( display ); + shell = new Shell( display ); + Assert.assertNotNull( shell ); + shell.setLayout( new FillLayout() ); + composite = new Composite( shell, SWT.NONE ); + composite.setLayout( new FillLayout() ); + Assert.assertNotNull( composite ); + }}); } @After @@ -96,9 +106,12 @@ public class TestSWTJOGLGLCanvas01GLn extends UITestCase { Assert.assertNotNull( shell ); Assert.assertNotNull( composite ); try { - composite.dispose(); - shell.dispose(); - display.dispose(); + SWTAccessor.invoke(true, new Runnable() { + public void run() { + composite.dispose(); + shell.dispose(); + display.dispose(); + }}); } catch( Throwable throwable ) { throwable.printStackTrace(); @@ -118,14 +131,19 @@ public class TestSWTJOGLGLCanvas01GLn extends UITestCase { Assert.assertNotNull( canvas ); canvas.addGLEventListener(new GLEventListener() { - public void init(final GLAutoDrawable drawable) { } + public void init(final GLAutoDrawable drawable) { + System.err.println(Thread.currentThread().getName()+" - SWT Canvas - GLEventListener - init()"); + } public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) { - OneTriangle.setup( drawable.getGL().getGL2(), width, height ); + System.err.println(Thread.currentThread().getName()+" - SWT Canvas - GLEventListener - reshape()"); + OneTriangle.setup( drawable.getGL().getGL2(), width, height ); } public void display(final GLAutoDrawable drawable) { OneTriangle.render( drawable.getGL().getGL2(), drawable.getWidth(), drawable.getHeight()); } - public void dispose(final GLAutoDrawable drawable) {} + public void dispose(final GLAutoDrawable drawable) { + System.err.println(Thread.currentThread().getName()+" - SWT Canvas - GLEventListener - dispose()"); + } }); shell.setText( getClass().getName() ); -- cgit v1.2.3 From 4e70a4811a860255b53eeae7a841ca473e1aba86 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 6 Jul 2012 09:06:03 +0200 Subject: Fix commit dfee8c58d4915f78f57545c26a492668b2b68a87 --- make/scripts/tests.sh | 5 +++-- src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java | 1 - .../jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java | 5 ----- 3 files changed, 3 insertions(+), 8 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 4d46ec4f4..0258187fd 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -293,12 +293,13 @@ function testawtswt() { # #testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTEclipseGLCanvas01GLn $* testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* -#testawt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor02GLn $* +#testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* +#testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor02GLn $* # # awtswt (testawtswt) # -#testawt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor03AWTGLn $* +#testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor03AWTGLn $* # # newt.awt (testawt) diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 2cd87f276..4d472b01a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -30,7 +30,6 @@ package jogamp.nativewindow.macosx; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.util.Point; -import jogamp.common.awt.AWTEDTExecutor; import jogamp.nativewindow.Debug; import jogamp.nativewindow.NWJNILibLoader; diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java index ba33aa31d..5e3d4dd8e 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java @@ -34,8 +34,6 @@ import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; -import jogamp.nativewindow.macosx.OSXUtil; - import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; @@ -80,9 +78,6 @@ public class TestSWTJOGLGLCanvas01GLn extends UITestCase { @BeforeClass public static void startup() { System.out.println( "GLProfile " + GLProfile.glAvailabilityToString() ); - if( Platform.OS_TYPE == Platform.OSType.MACOS ) { - System.err.println("OSXUtil.isAWTEDTMainThread: "+ OSXUtil.isAWTEDTMainThread() ); - } } @Before -- cgit v1.2.3 From 72a84b422327c6abb688339419d3552ec0e5c70c Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Mon, 9 Jul 2012 17:07:02 +0200 Subject: EGLGraphicsDevice adds desctruction callback and nativeDisplayID; EGLDisplayUtil adds creation of EGLGraphicsDevice. Due to EGL's location in JOGL, supporting destruction of an EGLGraphicsDevice is solved (hack) temporary by passing an eglTerminate callback to it's ctor. Using EGLGraphicsDevice's close() method to also issue eglTerminate() simplifies the code. In future we shall move EGL to nativewindow! --- .../classes/jogamp/opengl/egl/EGLDisplayUtil.java | 95 ++++++++++++++++++---- .../classes/jogamp/opengl/egl/EGLDrawable.java | 74 ++++++++--------- .../jogamp/opengl/egl/EGLDrawableFactory.java | 23 ++---- .../egl/EGLGraphicsConfigurationFactory.java | 34 ++++---- .../jogamp/nativewindow/egl/EGLGraphicsDevice.java | 43 +++++++++- .../jogamp/nativewindow/x11/X11GraphicsDevice.java | 1 - .../media/nativewindow/AbstractGraphicsDevice.java | 4 + .../jogamp/newt/driver/android/AndroidDisplay.java | 16 +--- .../jogamp/newt/driver/broadcom/egl/Display.java | 4 +- .../classes/jogamp/newt/driver/kd/KDDisplay.java | 15 +--- 10 files changed, 182 insertions(+), 127 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java index e09400c09..7f10d3bd9 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java @@ -30,12 +30,15 @@ package jogamp.opengl.egl; import java.nio.IntBuffer; +import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; +import javax.media.opengl.GLException; import jogamp.opengl.Debug; import com.jogamp.common.util.LongIntHashMap; +import com.jogamp.nativewindow.egl.EGLGraphicsDevice; /** * This implementation provides recursive calls to @@ -67,23 +70,6 @@ public class EGLDisplayUtil { return eglDisplay; } - public static long eglGetDisplay(NativeSurface surface, boolean allowFallBackToDefault) { - final long nDisplay; - if( NativeWindowFactory.TYPE_WINDOWS.equals(NativeWindowFactory.getNativeWindowType(false)) ) { - nDisplay = surface.getSurfaceHandle(); // don't even ask .. - } else { - nDisplay = surface.getDisplayHandle(); // 0 == EGL.EGL_DEFAULT_DISPLAY - } - long eglDisplay = EGLDisplayUtil.eglGetDisplay(nDisplay); - if (eglDisplay == EGL.EGL_NO_DISPLAY && nDisplay != EGL.EGL_DEFAULT_DISPLAY && allowFallBackToDefault) { - if(DEBUG) { - System.err.println("EGLDisplayUtil.eglGetDisplay(): Fall back to EGL_DEFAULT_DISPLAY"); - } - eglDisplay = EGLDisplayUtil.eglGetDisplay(EGL.EGL_DEFAULT_DISPLAY); - } - return eglDisplay; - } - public static synchronized boolean eglInitialize(long eglDisplay, int[] major, int major_offset, int[] minor, int minor_offset) { final boolean res; final int refCnt = eglDisplayCounter.get(eglDisplay) + 1; // 0 + 1 = 1 -> 1st init @@ -99,7 +85,19 @@ public class EGLDisplayUtil { return res; } + /** + * + * @param eglDisplay + * @param major + * @param minor + * @return true if the eglDisplay is valid and it's reference counter becomes one and {@link EGL#eglTerminate(long)} was successful, otherwise false + * + * @see EGL#eglInitialize(long, int[], int, int[], int)} + */ public static synchronized boolean eglInitialize(long eglDisplay, IntBuffer major, IntBuffer minor) { + if( EGL.EGL_NO_DISPLAY == eglDisplay) { + return false; + } final boolean res; final int refCnt = eglDisplayCounter.get(eglDisplay) + 1; // 0 + 1 = 1 -> 1st init if(1==refCnt) { // only initialize once @@ -114,7 +112,14 @@ public class EGLDisplayUtil { return res; } + /** + * @param eglDisplay the EGL display handle + * @return true if the eglDisplay is valid and it's reference counter becomes zero and {@link EGL#eglTerminate(long)} was successful, otherwise false + */ public static synchronized boolean eglTerminate(long eglDisplay) { + if( EGL.EGL_NO_DISPLAY == eglDisplay) { + return false; + } final boolean res; final int refCnt = eglDisplayCounter.get(eglDisplay) - 1; // 1 - 1 = 0 -> final terminate if(0==refCnt) { // no terminate if still in use or already terminated @@ -130,4 +135,60 @@ public class EGLDisplayUtil { } return res; } + + public static final EGLGraphicsDevice.EGLTerminateCallback eglTerminateCallback = new EGLGraphicsDevice.EGLTerminateCallback() { + public void eglTerminate(long eglDisplayHandle) { + EGLDisplayUtil.eglTerminate(eglDisplayHandle); + } + }; + + /** + * @param nativeDisplayID + * @param connection + * @param unitID + * @return an initialized EGLGraphicsDevice + * @throws GLException if {@link EGL#eglGetDisplay(long)} or {@link EGL#eglInitialize(long, int[], int, int[], int)} fails + * @see EGLGraphicsDevice#EGLGraphicsDevice(long, long, String, int, com.jogamp.nativewindow.egl.EGLGraphicsDevice.EGLTerminateCallback) + */ + public static EGLGraphicsDevice eglCreateEGLGraphicsDevice(long nativeDisplayID, String connection, int unitID) { + long eglDisplay = EGLDisplayUtil.eglGetDisplay(nativeDisplayID); + if (eglDisplay == EGL.EGL_NO_DISPLAY) { + throw new GLException("Failed to created EGL display: 0x"+Long.toHexString(nativeDisplayID)+", error 0x"+Integer.toHexString(EGL.eglGetError())); + } + if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) { + throw new GLException("eglInitialize failed"+", error 0x"+Integer.toHexString(EGL.eglGetError())); + } + return new EGLGraphicsDevice(nativeDisplayID, eglDisplay, connection, unitID, eglTerminateCallback); + } + + /** + * @param surface + * @param allowFallBackToDefault + * @return an initialized EGLGraphicsDevice + * @throws GLException if {@link EGL#eglGetDisplay(long)} or {@link EGL#eglInitialize(long, int[], int, int[], int)} fails + */ + public static EGLGraphicsDevice eglCreateEGLGraphicsDevice(NativeSurface surface, boolean allowFallBackToDefault) { + long nativeDisplayID; + if( NativeWindowFactory.TYPE_WINDOWS.equals(NativeWindowFactory.getNativeWindowType(false)) ) { + nativeDisplayID = surface.getSurfaceHandle(); // don't even ask .. + } else { + nativeDisplayID = surface.getDisplayHandle(); // 0 == EGL.EGL_DEFAULT_DISPLAY + } + long eglDisplay = EGLDisplayUtil.eglGetDisplay(nativeDisplayID); + if (eglDisplay == EGL.EGL_NO_DISPLAY && nativeDisplayID != EGL.EGL_DEFAULT_DISPLAY && allowFallBackToDefault) { + if(DEBUG) { + System.err.println("EGLDisplayUtil.eglGetDisplay(): Fall back to EGL_DEFAULT_DISPLAY"); + } + nativeDisplayID = EGL.EGL_DEFAULT_DISPLAY; + eglDisplay = EGLDisplayUtil.eglGetDisplay(nativeDisplayID); + } + if (eglDisplay == EGL.EGL_NO_DISPLAY) { + throw new GLException("Failed to created EGL display: "+surface+", error 0x"+Integer.toHexString(EGL.eglGetError())); + } + if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) { + throw new GLException("eglInitialize failed"+", error 0x"+Integer.toHexString(EGL.eglGetError())); + } + final AbstractGraphicsDevice adevice = surface.getGraphicsConfiguration().getScreen().getDevice(); + return new EGLGraphicsDevice(nativeDisplayID, eglDisplay, adevice.getConnection(), adevice.getUnitID(), eglTerminateCallback); + } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java index 491f22119..d777c4f04 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java @@ -46,34 +46,34 @@ import javax.media.opengl.*; import com.jogamp.nativewindow.egl.*; public abstract class EGLDrawable extends GLDrawableImpl { - protected boolean ownEGLDisplay = false; // for destruction - protected boolean ownEGLSurface = false; // for destruction + private boolean ownEGLDisplay = false; // for destruction + private boolean ownEGLSurface = false; // for destruction private EGLGraphicsConfiguration eglConfig; - protected long eglDisplay; - protected long eglSurface; + private EGLGraphicsDevice eglDevice; + private long eglSurface; protected EGLDrawable(EGLDrawableFactory factory, NativeSurface component) throws GLException { super(factory, component, false); eglSurface=EGL.EGL_NO_SURFACE; - eglDisplay=0; + eglDevice=null; } - public long getDisplay() { - return eglDisplay; + public final long getDisplay() { + return null != eglDevice ? eglDevice.getHandle() : 0; } @Override - public long getHandle() { + public final long getHandle() { return eglSurface; } - public EGLGraphicsConfiguration getGraphicsConfiguration() { + public final EGLGraphicsConfiguration getGraphicsConfiguration() { return eglConfig; } @Override - public GLCapabilitiesImmutable getChosenGLCapabilities() { + public final GLCapabilitiesImmutable getChosenGLCapabilities() { return (null==eglConfig)?super.getChosenGLCapabilities():(GLCapabilitiesImmutable)eglConfig.getChosenCapabilities(); } @@ -82,17 +82,17 @@ public abstract class EGLDrawable extends GLDrawableImpl { protected abstract long createSurface(long eglDpy, long eglNativeCfg, long surfaceHandle); - private void recreateSurface() { + private final void recreateSurface() { // create a new EGLSurface .. if(EGL.EGL_NO_SURFACE!=eglSurface) { - EGL.eglDestroySurface(eglDisplay, eglSurface); + EGL.eglDestroySurface(eglDevice.getHandle(), eglSurface); } if(DEBUG) { - System.err.println(getThreadName() + ": createSurface using eglDisplay "+toHexString(eglDisplay)+", "+eglConfig); + System.err.println(getThreadName() + ": createSurface using "+eglDevice+", "+eglConfig); } - eglSurface = createSurface(eglDisplay, eglConfig.getNativeConfig(), surface.getSurfaceHandle()); + eglSurface = createSurface(eglDevice.getHandle(), eglConfig.getNativeConfig(), surface.getSurfaceHandle()); int eglError0 = EGL.EGL_SUCCESS; if (EGL.EGL_NO_SURFACE == eglSurface) { eglError0 = EGL.eglGetError(); @@ -105,7 +105,7 @@ public abstract class EGLDrawable extends GLDrawableImpl { if(DEBUG) { System.err.println(getThreadName() + ": Info: Creation of window surface w/ surface handle failed: "+eglConfig+", error "+toHexString(eglError0)+", retry w/ windowHandle"); } - eglSurface = createSurface(eglDisplay, eglConfig.getNativeConfig(), nw.getWindowHandle()); + eglSurface = createSurface(eglDevice.getHandle(), eglConfig.getNativeConfig(), nw.getWindowHandle()); if (EGL.EGL_NO_SURFACE == eglSurface) { eglError0 = EGL.eglGetError(); } @@ -130,7 +130,7 @@ public abstract class EGLDrawable extends GLDrawableImpl { } @Override - protected void setRealizedImpl() { + protected final void setRealizedImpl() { if (realized) { AbstractGraphicsConfiguration aConfig = surface.getGraphicsConfiguration(); AbstractGraphicsDevice aDevice = aConfig.getScreen().getDevice(); @@ -139,9 +139,10 @@ public abstract class EGLDrawable extends GLDrawableImpl { System.err.println(getThreadName() + ": EGLDrawable.setRealized(true): using existing EGL config - START"); } // just fetch the data .. trust but verify .. - eglDisplay = aDevice.getHandle(); - if (eglDisplay == EGL.EGL_NO_DISPLAY) { - throw new GLException("Invalid EGL display in EGLGraphicsDevice from "+aDevice); + ownEGLDisplay = false; + eglDevice = (EGLGraphicsDevice) aDevice; + if (eglDevice.getHandle() == EGL.EGL_NO_DISPLAY) { + throw new GLException("Invalid EGL display in EGLGraphicsDevice "+eglDevice); } if(aConfig instanceof EGLGraphicsConfiguration) { eglConfig = (EGLGraphicsConfiguration) aConfig; // done .. @@ -151,12 +152,13 @@ public abstract class EGLDrawable extends GLDrawableImpl { int[] tmp = new int[1]; if ( 0 != surface.getSurfaceHandle() && - EGL.eglQuerySurface(eglDisplay, surface.getSurfaceHandle(), EGL.EGL_CONFIG_ID, tmp, 0) ) { + EGL.eglQuerySurface(eglDevice.getHandle(), surface.getSurfaceHandle(), EGL.EGL_CONFIG_ID, tmp, 0) ) { // surface holds static EGLSurface eglSurface = surface.getSurfaceHandle(); if(DEBUG) { System.err.println(getThreadName() + ": setSurface re-using component's EGLSurface: handle "+toHexString(eglSurface)); } + ownEGLSurface=false; } else { // EGLSurface is ours - subsequent updateHandle() will issue recreateSurface(); ownEGLSurface=true; @@ -173,35 +175,28 @@ public abstract class EGLDrawable extends GLDrawableImpl { // EGLSurface is ours .. ownEGLSurface=true; - eglDisplay = EGLDisplayUtil.eglGetDisplay(surface, true); - if (eglDisplay == EGL.EGL_NO_DISPLAY) { - throw new GLException("Failed to created EGL display: "+surface+", "+aDevice+", error "+toHexString(EGL.eglGetError())); - } - if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) { - throw new GLException("eglInitialize failed"+", error "+Integer.toHexString(EGL.eglGetError())); - } - EGLGraphicsDevice e = new EGLGraphicsDevice(eglDisplay, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); - AbstractGraphicsScreen s = new DefaultGraphicsScreen(e, aConfig.getScreen().getIndex()); + eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface, true); + AbstractGraphicsScreen eglScreen = new DefaultGraphicsScreen(eglDevice, aConfig.getScreen().getIndex()); final GLCapabilitiesImmutable capsRequested = (GLCapabilitiesImmutable) aConfig.getRequestedCapabilities(); if(aConfig instanceof EGLGraphicsConfiguration) { final EGLGLCapabilities capsChosen = (EGLGLCapabilities) aConfig.getChosenCapabilities(); if(0 == capsChosen.getEGLConfig()) { // 'refresh' the native EGLConfig handle - capsChosen.setEGLConfig(EGLGraphicsConfiguration.EGLConfigId2EGLConfig(eglDisplay, capsChosen.getEGLConfigID())); + capsChosen.setEGLConfig(EGLGraphicsConfiguration.EGLConfigId2EGLConfig(eglDevice.getHandle(), capsChosen.getEGLConfigID())); if(0 == capsChosen.getEGLConfig()) { throw new GLException("Refreshing native EGLConfig handle failed: "+capsChosen+" of "+aConfig); } } - eglConfig = new EGLGraphicsConfiguration(s, capsChosen, capsRequested, null); + eglConfig = new EGLGraphicsConfiguration(eglScreen, capsChosen, capsRequested, null); if(DEBUG) { System.err.println(getThreadName() + ": Reusing chosenCaps: "+eglConfig); } } else { eglConfig = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic( - capsRequested, capsRequested, null, s, aConfig.getVisualID(VIDType.NATIVE), false); + capsRequested, capsRequested, null, eglScreen, aConfig.getVisualID(VIDType.NATIVE), false); if (null == eglConfig) { - throw new GLException("Couldn't create EGLGraphicsConfiguration from "+s); + throw new GLException("Couldn't create EGLGraphicsConfiguration from "+eglScreen); } else if(DEBUG) { System.err.println(getThreadName() + ": Chosen eglConfig: "+eglConfig); } @@ -213,25 +208,23 @@ public abstract class EGLDrawable extends GLDrawableImpl { } } else if (ownEGLSurface && eglSurface != EGL.EGL_NO_SURFACE) { if(DEBUG) { - System.err.println(getThreadName() + ": EGLDrawable.setRealized(false): ownDisplay "+ownEGLDisplay+", ownSurface "+ownEGLSurface+", eglDisplay: "+toHexString(eglDisplay)+", eglSurface: "+toHexString(eglSurface)); + System.err.println(getThreadName() + ": EGLDrawable.setRealized(false): ownDisplay "+ownEGLDisplay+", ownSurface "+ownEGLSurface+", "+eglDevice+", eglSurface: "+toHexString(eglSurface)); } // Destroy the window surface - if (!EGL.eglDestroySurface(eglDisplay, eglSurface)) { + if (!EGL.eglDestroySurface(eglDevice.getHandle(), eglSurface)) { throw new GLException("Error destroying window surface (eglDestroySurface)"); } eglSurface = EGL.EGL_NO_SURFACE; - if (ownEGLDisplay && EGL.EGL_NO_DISPLAY!=eglDisplay) { - EGLDisplayUtil.eglTerminate(eglDisplay); - } - eglDisplay=EGL.EGL_NO_DISPLAY; eglConfig=null; + eglDevice.close(); + eglDevice=null; } } @Override protected final void swapBuffersImpl() { // single-buffer is already filtered out @ GLDrawableImpl#swapBuffers() - if(!EGL.eglSwapBuffers(eglDisplay, eglSurface)) { + if(!EGL.eglSwapBuffers(eglDevice.getHandle(), eglSurface)) { throw new GLException("Error swapping buffers, eglError "+toHexString(EGL.eglGetError())+", "+this); } } @@ -270,6 +263,7 @@ public abstract class EGLDrawable extends GLDrawableImpl { public String toString() { return getClass().getName()+"[realized "+isRealized()+ ",\n\tfactory "+getFactory()+ + ",\n\tdevice "+eglDevice+ ",\n\tsurface "+getNativeSurface()+ ",\n\teglSurface "+toHexString(eglSurface)+ ",\n\teglConfig "+eglConfig+ diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index e4f6f0ef8..f4fa1f13f 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -184,10 +184,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { if(DEBUG) { System.err.println("EGLDrawableFactory.destroy("+shutdownType+"): "+sr.device.toString()); } - final long eglDisplay = sr.device.getHandle(); - if(EGL.EGL_NO_DISPLAY != eglDisplay) { - EGLDisplayUtil.eglTerminate(eglDisplay); - } + sr.device.close(); } sharedMap.clear(); sharedMap = null; @@ -282,22 +279,14 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { if(null == eglES1DynamicLookupHelper && null == eglES2DynamicLookupHelper) { return null; } - String connection = adevice.getConnection(); + final String connection = adevice.getConnection(); SharedResource sr; synchronized(sharedMap) { sr = sharedMap.get(connection); } if(null==sr) { - long eglDisplay = EGLDisplayUtil.eglGetDisplay(EGL.EGL_DEFAULT_DISPLAY); - if (eglDisplay == EGL.EGL_NO_DISPLAY) { - throw new GLException("Failed to created EGL default display: error 0x"+Integer.toHexString(EGL.eglGetError())); - } else if(DEBUG) { - System.err.println("EGLDrawableFactory.createShared: eglDisplay(EGL_DEFAULT_DISPLAY): 0x"+Long.toHexString(eglDisplay)); - } - if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) { - throw new GLException("eglInitialize failed"+", error 0x"+Integer.toHexString(EGL.eglGetError())); - } - final EGLGraphicsDevice sharedDevice = new EGLGraphicsDevice(eglDisplay, connection, adevice.getUnitID()); + final EGLGraphicsDevice sharedDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, connection, adevice.getUnitID()); + // final boolean madeCurrentES1 = isEGLContextAvailable(sharedDevice, GLProfile.GLES1); // final boolean madeCurrentES2 = isEGLContextAvailable(sharedDevice, GLProfile.GLES2); final boolean madeCurrentES1 = true; // FIXME @@ -401,7 +390,9 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } @Override - protected NativeSurface createOffscreenSurfaceImpl(AbstractGraphicsDevice device, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, int width, int height) { + protected NativeSurface createOffscreenSurfaceImpl(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, int width, int height) { + final EGLGraphicsDevice eglDeviceReq = (EGLGraphicsDevice) deviceReq; + final EGLGraphicsDevice device = EGLDisplayUtil.eglCreateEGLGraphicsDevice(eglDeviceReq.getNativeDisplayID(), deviceReq.getConnection(), deviceReq.getUnitID()); WrappedSurface ns = new WrappedSurface(EGLGraphicsConfigurationFactory.createOffscreenGraphicsConfiguration(device, capsChosen, capsRequested, chooser)); ns.surfaceSizeChanged(width, height); return ns; diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java index 5ab2632c6..809e2b688 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java @@ -223,23 +223,17 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact throw new GLException("Null AbstractGraphicsDevice"); } - final long eglDisplay; + final EGLGraphicsDevice eglDevice; final boolean ownEGLDisplay; - if( !(absDevice instanceof EGLGraphicsDevice) ) { - eglDisplay = EGLDisplayUtil.eglGetDisplay(absDevice.getHandle()); - if (eglDisplay == EGL.EGL_NO_DISPLAY) { - throw new GLException("Could not get EGL display from: "+absDevice); - } - if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) { - throw new GLException("eglInitialize failed eglDisplay 0x"+Long.toHexString(eglDisplay)+", "+absDevice+", error 0x"+Integer.toHexString(EGL.eglGetError())); - } - ownEGLDisplay = true; - } else { - eglDisplay = absDevice.getHandle(); - if (eglDisplay == EGL.EGL_NO_DISPLAY) { - throw new GLException("Invalid EGL display: "+absDevice); + if( absDevice instanceof EGLGraphicsDevice ) { + eglDevice = (EGLGraphicsDevice) absDevice; + if (eglDevice.getHandle() == EGL.EGL_NO_DISPLAY) { + throw new GLException("Invalid EGL display: "+eglDevice); } ownEGLDisplay = false; + } else { + eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(absDevice.getHandle(), absDevice.getConnection(), absDevice.getUnitID()); + ownEGLDisplay = true; } EGLDrawableFactory factory = (EGLDrawableFactory) GLDrawableFactory.getEGLFactory(); @@ -248,7 +242,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact GLProfile glp = capsChosen.getGLProfile(); GLCapabilities fixedCaps; - EGLGraphicsConfiguration res = eglChooseConfig(eglDisplay, capsChosen, capsReq, chooser, absScreen, nativeVisualID, forceTransparentFlag); + EGLGraphicsConfiguration res = eglChooseConfig(eglDevice.getHandle(), capsChosen, capsReq, chooser, absScreen, nativeVisualID, forceTransparentFlag); if(null==res) { if(DEBUG) { System.err.println("eglChooseConfig failed with given capabilities "+capsChosen); @@ -267,7 +261,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(DEBUG) { System.err.println("trying fixed caps (1): "+fixedCaps); } - res = eglChooseConfig(eglDisplay, fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); + res = eglChooseConfig(eglDevice.getHandle(), fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); } if(null==res) { // @@ -280,7 +274,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(DEBUG) { System.err.println("trying fixed caps (2): "+fixedCaps); } - res = eglChooseConfig(eglDisplay, fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); + res = eglChooseConfig(eglDevice.getHandle(), fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); } if(null==res) { // @@ -295,14 +289,14 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(DEBUG) { System.err.println("trying fixed caps (3): "+fixedCaps); } - res = eglChooseConfig(eglDisplay, fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); + res = eglChooseConfig(eglDevice.getHandle(), fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); } if(null==res) { throw new GLException("Graphics configuration failed [direct caps, eglGetConfig/chooser and fixed-caps(1-3)]"); } if(ownEGLDisplay) { - ((EGLGLCapabilities) res.getChosenCapabilities()).setEGLConfig(0); // eglDisplay: EOL - EGLDisplayUtil.eglTerminate(eglDisplay); + ((EGLGLCapabilities) res.getChosenCapabilities()).setEGLConfig(0); // eglDisplay: EOL + eglDevice.close(); } return res; } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java index 4ee336176..d161f2f34 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java @@ -36,25 +36,60 @@ import javax.media.nativewindow.*; /** Encapsulates a graphics device on EGL platforms. */ - public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneable { - boolean closeDisplay = false; + final long nativeDisplayID; + final EGLTerminateCallback eglTerminateCallback; + /** + * Hack to allow inject a EGL termination call. + *

+ * FIXME: This shall be removed when relocated EGL to the nativewindow package, + * since then it can be utilized directly. + *

+ */ + public interface EGLTerminateCallback { + /** + * Implementation should issue an EGL.eglTerminate(eglDisplayHandle) call. + * @param eglDisplayHandle + */ + void eglTerminate(long eglDisplayHandle); + } + /** * Note that this is not an open connection, ie no native display handle exist. * This constructor exist to setup a default device connection/unit.
*/ public EGLGraphicsDevice(String connection, int unitID) { super(NativeWindowFactory.TYPE_EGL, connection, unitID); + this.nativeDisplayID = 0; + this.eglTerminateCallback = null; } - /** Constructs a new EGLGraphicsDevice corresponding to the given EGL display handle. */ - public EGLGraphicsDevice(long eglDisplay, String connection, int unitID) { + public EGLGraphicsDevice(long nativeDisplayID, long eglDisplay, String connection, int unitID, EGLTerminateCallback eglTerminateCallback) { super(NativeWindowFactory.TYPE_EGL, connection, unitID, eglDisplay); + this.nativeDisplayID = nativeDisplayID; + this.eglTerminateCallback = eglTerminateCallback; } + public long getNativeDisplayID() { return nativeDisplayID; } + public Object clone() { return super.clone(); } + + public boolean close() { + if(null != eglTerminateCallback) { + if(DEBUG) { + System.err.println(Thread.currentThread().getName() + " - eglTerminate: "+this); + } + eglTerminateCallback.eglTerminate(handle); + } + return super.close(); + } + + @Override + public String toString() { + return "EGLGraphicsDevice[type EGL, connection "+getConnection()+", unitID "+getUnitID()+", handle 0x"+Long.toHexString(getHandle())+", nativeDisplayID 0x"+Long.toHexString(nativeDisplayID)+"]"; + } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index 308756b54..a02332413 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -46,7 +46,6 @@ import javax.media.nativewindow.ToolkitLock; */ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneable { - public static final boolean DEBUG = Debug.debug("GraphicsDevice"); final boolean closeDisplay; /** Constructs a new X11GraphicsDevice corresponding to the given connection and default diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java index 1dd01a274..4979f1949 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java @@ -40,11 +40,15 @@ package javax.media.nativewindow; +import jogamp.nativewindow.Debug; + /** A interface describing a graphics device in a toolkit-independent manner. */ public interface AbstractGraphicsDevice extends Cloneable { + public static final boolean DEBUG = Debug.debug("GraphicsDevice"); + /** Dummy connection value for a default connection where no native support for multiple devices is available */ public static String DEFAULT_CONNECTION = "decon"; diff --git a/src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java b/src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java index 3f360f20f..0a43c9b8f 100644 --- a/src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java +++ b/src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java @@ -32,9 +32,6 @@ import jogamp.newt.*; import jogamp.opengl.egl.*; import javax.media.nativewindow.*; -import javax.media.opengl.GLException; - -import com.jogamp.nativewindow.egl.*; public class AndroidDisplay extends jogamp.newt.DisplayImpl { static { @@ -55,20 +52,11 @@ public class AndroidDisplay extends jogamp.newt.DisplayImpl { protected void createNativeImpl() { // EGL Device - final long eglDisplay = EGLDisplayUtil.eglGetDisplay(EGL.EGL_DEFAULT_DISPLAY); - if (eglDisplay == EGL.EGL_NO_DISPLAY) { - throw new GLException("Failed to created EGL default display: error 0x"+Integer.toHexString(EGL.eglGetError())); - } - if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) { - throw new GLException("eglInitialize failed eglDisplay 0x"+Long.toHexString(eglDisplay)+", error 0x"+Integer.toHexString(EGL.eglGetError())); - } - aDevice = new EGLGraphicsDevice(eglDisplay, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); } protected void closeNativeImpl() { - if (aDevice.getHandle() != EGL.EGL_NO_DISPLAY) { - EGLDisplayUtil.eglTerminate(aDevice.getHandle()); - } + aDevice.close(); } protected void dispatchMessagesNative() { diff --git a/src/newt/classes/jogamp/newt/driver/broadcom/egl/Display.java b/src/newt/classes/jogamp/newt/driver/broadcom/egl/Display.java index f90c62ff4..e3f50b7e0 100644 --- a/src/newt/classes/jogamp/newt/driver/broadcom/egl/Display.java +++ b/src/newt/classes/jogamp/newt/driver/broadcom/egl/Display.java @@ -61,11 +61,11 @@ public class Display extends jogamp.newt.DisplayImpl { } protected void createNativeImpl() { - long handle = CreateDisplay(Screen.fixedWidth, Screen.fixedHeight); + final long handle = CreateDisplay(Screen.fixedWidth, Screen.fixedHeight); if (handle == EGL.EGL_NO_DISPLAY) { throw new NativeWindowException("BC EGL CreateDisplay failed"); } - aDevice = new EGLGraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + aDevice = new EGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, handle, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT, null); } protected void closeNativeImpl() { diff --git a/src/newt/classes/jogamp/newt/driver/kd/KDDisplay.java b/src/newt/classes/jogamp/newt/driver/kd/KDDisplay.java index 73bbe0b5b..07b031841 100644 --- a/src/newt/classes/jogamp/newt/driver/kd/KDDisplay.java +++ b/src/newt/classes/jogamp/newt/driver/kd/KDDisplay.java @@ -42,8 +42,6 @@ import jogamp.newt.NEWTJNILibLoader; import jogamp.opengl.egl.EGL; import jogamp.opengl.egl.EGLDisplayUtil; -import com.jogamp.nativewindow.egl.EGLGraphicsDevice; - public class KDDisplay extends DisplayImpl { static { @@ -64,20 +62,11 @@ public class KDDisplay extends DisplayImpl { protected void createNativeImpl() { // FIXME: map name to EGL_*_DISPLAY - long handle = EGLDisplayUtil.eglGetDisplay(EGL.EGL_DEFAULT_DISPLAY); - if (handle == EGL.EGL_NO_DISPLAY) { - throw new NativeWindowException("eglGetDisplay failed"); - } - if (!EGLDisplayUtil.eglInitialize(handle, null, null)) { - throw new NativeWindowException("eglInitialize failed"); - } - aDevice = new EGLGraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); } protected void closeNativeImpl() { - if (aDevice.getHandle() != EGL.EGL_NO_DISPLAY) { - EGLDisplayUtil.eglTerminate(aDevice.getHandle()); - } + aDevice.close(); } protected void dispatchMessagesNative() { -- cgit v1.2.3 From 20bf031db719f7baa4c6e74734fc999061e08fe2 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 19 Jul 2012 21:15:10 +0200 Subject: Bug 599 - FBObject / Offscreen Support - Part 1 - New FBObject implementation handling FBO and it's attachments *** API CHANGE: Util -> Core *** while it's size and sample-count can be reconfigured on the fly. - com.jogamp.opengl.util.FBObject -> com.jogamp.opengl.FBObject - agnostic to texture unit - separate attachments using OO hierarchy reflecting FBO - handling MSAA and blitting - no FBO destruction for reconfig (attach/detach) - New GLFBODrawableImpl impl. an FBObject based GLDrawable - Instantiated by a dummy native surface (onscreen and invisible) hooked up to a dummy GLDrawable, which is the delegation for context creation. - Utilizies ProxySurface.UpstreamSurfaceHook for dummy surface avoiding specialization for native platforms. - TODO: Allow to utilize common surface interface as a dummy-surface to supporting API seperation of windowing/GL. The latter allows impl. of createGLDrawable(NativeSurface) with FBO. - New OffscreenAutoDrawable (extends GLAutoDrawableDelegate) for all offscreen drawables. Shall replace GLPbuffer. - New GLCapabilities*.isFBO() / setFBO(boolean) to request FBO offscreen, similar to isPBuffer(). Rule: if both are requested, FBO shall be favored. - GLContext adds raw FBO availability query (min. FBO avail), FBObject contains fine grained queries (TODO: Move parts to GLContext for efficiency). - Add framebuffer tracking, allowing fast querying: - GLBase/GLContext: public int getBoundFramebuffer(int target); public int getDefaultDrawFramebuffer(); public int getDefaultReadFramebuffer(); - GLContextImpl public final void setBoundFramebuffer(int target, int framebufferName) .. called by GL impl bind framebuffer - GL: getDefaultDrawFramebuffer(), getDefaultReadFramebuffer() Adding default framebuffer queries being issued by GL.glBindFramebuffer(target, 0) w/ a default framebuffer, o.e. zero. This allows a transparent use of a custom FBO even in case the applications attempts to reset FBO to zero. Value flow: GL <- GLContext <- GLDrawable, - GLCapabilities handle fbo/pbuffer seperate, don't disable the other - GLContext/GL track read/write framebuffer to be queried by FBObject to determine whether to bind/unbind a framebuffer - Test cases for multiple FBO w/ and w/o MSAA Other Features: - New interface ProxySurface.UpstreamSurfaceHook, allowing to hook an upstream surface of unknown type providing lifecycle and information (size, ..) callbacks. Used for all new dummy NativeSurface impl and SWT GLCanvas. - GLContext -> GLDrawable propagation context/drawable lifecycle via ProxySurface.UpstreamSurfaceHook allowing dynamic resources to react (create, init, ..) - contextRealized() - contextMadeCurrent() - SurfaceChangeable -> MutableSurface currently only contains setting the surface handle. TODO: May need to move ProxySurface.UpstreamSurfaceHook -> MutableSurface.UpstreamSurfaceHook, allowing other impl. classes (NEWT OffscreenWindow) to utilize the new upstream hookup mechanism - will allow FBO/Dummy window to work. - SWT GLCanvas using ProxySurface.UpstreamSurfaceHook for proper size propagation. - New GLAutoDrawable::getUpstreamWidget(), allowing GLEventListener to fetch the owning Java side UI element (NEWT, SWT, AWT, ..). - GLDrawableFactory: Removed createOffscreenSurface() - unused and not GL related - EGLDrawableFactory handles device/profile avail. mapping while actually creating context/drawable. This allows us to learn whether the ES context is software/hardware as well as FBO avail. - EGLDrawable: Removed secret buckets of EGL configs :) Employ native surface (X11, WGL, ..) to EGL 'mapping' in EGLDrawableFactory utilizing new EGLUpstreamSurfaceHook (implements ProxySurface.UpstreamSurfaceHook). Other Bugs: - Add CTX_OPTION_DEBUG to ctx/extension cache key since only a debug ctx may expose the ARB debug capability. This bug caused lack of ARB/AMD debug functionality. - Fix GLProfile deadlock (debug mode, w/ EGL/ES, no X11), dump availability information _after_ lock. - ImmModeSink draw(): Use GL's glDrawElements(..), don't cast for GL2ES1. Fixes use for GL2ES2. - Fix KeyEvent.getKeyChar() comment (-> only stable for keyTyped(..)) Misc: - Refined alot of API doc - New GLExtensions holds commonly used GL extension strings, allows better referencing and usage lookup. - Move GL (interface) decl. to GLBase - GLBuffers: Cleanup API doc (format, types) - TextureIO: Add PAM and PPM static suffix identifier - GLCapabilities getNumSamples() returns 0 if sampleBuffers is disabled, this seems to be more natural. - finalized a lot --- .gitignore | 5 +- doc/Platform.GLES.txt | 4 +- doc/TODO.txt | 11 +- etc/test.bat | 2 +- etc/test_dbg.bat | 2 +- make/config/jogl/gl-common.cfg | 13 + make/config/jogl/gl-if-CustomJavaCode-gl.java | 26 - .../config/jogl/gl-impl-CustomJavaCode-common.java | 53 +- .../jogl/gl-impl-CustomJavaCode-desktop.java | 25 +- .../jogl/gl-impl-CustomJavaCode-gl2_es2.java | 6 +- make/config/jogl/gl-impl-CustomJavaCode-gl4bc.java | 56 +- make/config/jogl/gl-impl-CustomJavaCode-gles1.java | 66 +- make/config/jogl/gl-impl-CustomJavaCode-gles2.java | 63 +- make/scripts/java-win32-dbg.bat | 13 +- make/scripts/java-win32.bat | 4 +- make/scripts/java-win64-dbg.bat | 12 +- make/scripts/java-win64.bat | 3 +- make/scripts/tests-x32.bat | 3 +- make/scripts/tests-x64.bat | 5 +- make/scripts/tests.sh | 41 +- make/stub_includes/opengl/macosx-window-system.h | 2 +- .../jogamp/gluegen/opengl/BuildStaticGLInfo.java | 4 +- .../com/jogamp/gluegen/opengl/GLConfiguration.java | 10 +- .../com/jogamp/gluegen/opengl/GLEmitter.java | 18 +- .../gluegen/runtime/opengl/GLExtensionNames.java | 190 -- .../gluegen/runtime/opengl/GLNameResolver.java | 191 ++ .../runtime/opengl/GLProcAddressResolver.java | 4 +- src/jogl/classes/com/jogamp/opengl/FBObject.java | 1943 ++++++++++++++++++++ .../classes/com/jogamp/opengl/GLExtensions.java | 81 + .../classes/com/jogamp/opengl/JoglVersion.java | 18 +- .../com/jogamp/opengl/OffscreenAutoDrawable.java | 89 + .../classes/com/jogamp/opengl/swt/GLCanvas.java | 72 +- .../classes/com/jogamp/opengl/util/FBObject.java | 483 ----- .../classes/com/jogamp/opengl/util/GLBuffers.java | 179 +- .../com/jogamp/opengl/util/GLReadBufferUtil.java | 12 +- .../com/jogamp/opengl/util/ImmModeSink.java | 25 +- .../com/jogamp/opengl/util/awt/Screenshot.java | 3 +- .../com/jogamp/opengl/util/awt/TextRenderer.java | 3 +- .../com/jogamp/opengl/util/texture/Texture.java | 25 +- .../com/jogamp/opengl/util/texture/TextureIO.java | 8 + .../opengl/util/texture/TextureSequence.java | 1 - .../util/texture/spi/NetPbmTextureWriter.java | 6 +- .../media/opengl/DefaultGLCapabilitiesChooser.java | 5 +- .../classes/javax/media/opengl/GLAutoDrawable.java | 48 +- .../javax/media/opengl/GLAutoDrawableDelegate.java | 18 +- src/jogl/classes/javax/media/opengl/GLBase.java | 55 + .../classes/javax/media/opengl/GLCapabilities.java | 31 +- .../media/opengl/GLCapabilitiesImmutable.java | 6 +- src/jogl/classes/javax/media/opengl/GLContext.java | 94 +- .../javax/media/opengl/GLDrawableFactory.java | 84 +- src/jogl/classes/javax/media/opengl/GLProfile.java | 52 +- .../classes/javax/media/opengl/awt/GLCanvas.java | 7 +- .../classes/javax/media/opengl/awt/GLJPanel.java | 7 +- .../jogamp/graph/curve/opengl/VBORegion2PES2.java | 32 +- src/jogl/classes/jogamp/opengl/GLContextImpl.java | 190 +- .../jogamp/opengl/GLDebugMessageHandler.java | 22 +- .../jogamp/opengl/GLDrawableFactoryImpl.java | 234 ++- src/jogl/classes/jogamp/opengl/GLDrawableImpl.java | 47 +- .../classes/jogamp/opengl/GLFBODrawableImpl.java | 138 ++ .../jogamp/opengl/GLGraphicsConfigurationUtil.java | 66 +- src/jogl/classes/jogamp/opengl/GLPbufferImpl.java | 8 +- src/jogl/classes/jogamp/opengl/egl/EGLContext.java | 76 +- .../classes/jogamp/opengl/egl/EGLDisplayUtil.java | 27 +- .../classes/jogamp/opengl/egl/EGLDrawable.java | 214 +-- .../jogamp/opengl/egl/EGLDrawableFactory.java | 307 +++- .../opengl/egl/EGLGraphicsConfiguration.java | 2 +- .../egl/EGLGraphicsConfigurationFactory.java | 65 +- .../jogamp/opengl/egl/EGLOnscreenDrawable.java | 4 +- .../jogamp/opengl/egl/EGLPbufferDrawable.java | 34 +- .../jogamp/opengl/egl/EGLUpstreamSurfaceHook.java | 56 + .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 24 +- .../opengl/macosx/cgl/MacOSXCGLDrawable.java | 4 - .../macosx/cgl/MacOSXCGLDrawableFactory.java | 153 +- .../macosx/cgl/MacOSXCGLGraphicsConfiguration.java | 4 +- .../macosx/cgl/MacOSXExternalCGLContext.java | 3 +- .../macosx/cgl/MacOSXPbufferCGLDrawable.java | 12 +- .../jogamp/opengl/util/av/EGLMediaPlayerImpl.java | 8 +- .../windows/wgl/WindowsBitmapWGLDrawable.java | 6 +- .../windows/wgl/WindowsDummyWGLDrawable.java | 109 -- .../windows/wgl/WindowsExternalWGLContext.java | 3 +- .../windows/wgl/WindowsExternalWGLDrawable.java | 7 +- .../windows/wgl/WindowsPbufferWGLContext.java | 4 +- .../windows/wgl/WindowsPbufferWGLDrawable.java | 19 +- .../opengl/windows/wgl/WindowsWGLContext.java | 6 +- .../windows/wgl/WindowsWGLDrawableFactory.java | 130 +- .../wgl/WindowsWGLGraphicsConfiguration.java | 22 +- .../WindowsWGLGraphicsConfigurationFactory.java | 19 +- .../jogamp/opengl/x11/glx/X11DummyGLXDrawable.java | 102 - .../opengl/x11/glx/X11ExternalGLXContext.java | 12 +- .../opengl/x11/glx/X11ExternalGLXDrawable.java | 5 +- .../jogamp/opengl/x11/glx/X11GLXContext.java | 9 +- .../opengl/x11/glx/X11GLXDrawableFactory.java | 145 +- .../x11/glx/X11GLXGraphicsConfiguration.java | 29 +- .../glx/X11GLXGraphicsConfigurationFactory.java | 17 +- .../opengl/x11/glx/X11OnscreenGLXDrawable.java | 7 +- .../opengl/x11/glx/X11PbufferGLXDrawable.java | 18 +- .../opengl/x11/glx/X11PixmapGLXDrawable.java | 6 +- .../macosx/MacOSXWindowSystemInterface-pbuffer.m | 2 +- .../native/macosx/MacOSXWindowSystemInterface.m | 12 +- .../com/jogamp/nativewindow/WrappedSurface.java | 34 +- .../jogamp/nativewindow/egl/EGLGraphicsDevice.java | 42 +- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 3 - .../jogamp/nativewindow/x11/X11GraphicsDevice.java | 36 +- .../jogamp/nativewindow/x11/X11GraphicsScreen.java | 8 +- .../media/nativewindow/AbstractGraphicsDevice.java | 27 +- .../media/nativewindow/DefaultGraphicsDevice.java | 13 + .../javax/media/nativewindow/MutableSurface.java | 44 + .../javax/media/nativewindow/ProxySurface.java | 127 +- .../media/nativewindow/SurfaceChangeable.java | 54 - .../jogamp/nativewindow/SurfaceUpdatedHelper.java | 4 +- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 21 +- .../jogamp/nativewindow/macosx/OSXUtil.java | 13 +- .../jogamp/nativewindow/windows/GDISurface.java | 51 +- src/nativewindow/native/macosx/OSXmisc.m | 52 +- src/newt/classes/com/jogamp/newt/Window.java | 16 +- .../classes/com/jogamp/newt/event/KeyEvent.java | 2 +- .../classes/com/jogamp/newt/opengl/GLWindow.java | 7 +- src/newt/classes/jogamp/newt/OffscreenWindow.java | 41 +- .../classes/jogamp/newt/driver/android/MD.java | 2 +- .../jogamp/newt/driver/macosx/MacWindow.java | 8 +- src/newt/native/NewtMacWindow.m | 6 +- .../test/junit/graph/TestTextRendererNEWT00.java | 2 +- .../graph/demos/GPURendererListenerBase01.java | 2 +- .../junit/graph/demos/ui/UIListenerBase01.java | 2 +- .../test/junit/jogl/acore/TestFBODrawableNEWT.java | 272 +++ .../test/junit/jogl/acore/TestFBOMRTNEWT01.java | 266 +++ .../junit/jogl/acore/TestFBOMix2DemosES2NEWT.java | 258 +++ .../jogl/acore/TestGLAutoDrawableDelegateNEWT.java | 2 +- .../acore/TestGLContextDrawableSwitchNEWT.java | 2 +- .../test/junit/jogl/acore/TestGLProfile01NEWT.java | 2 +- .../junit/jogl/acore/TestShutdownCompleteNEWT.java | 2 +- .../test/junit/jogl/caps/MultisampleDemoES1.java | 154 -- .../junit/jogl/caps/TestMultisampleES1AWT.java | 19 +- .../junit/jogl/caps/TestMultisampleES1NEWT.java | 20 +- .../junit/jogl/caps/TestMultisampleES2NEWT.java | 143 ++ .../opengl/test/junit/jogl/demos/es1/GearsES1.java | 19 +- .../junit/jogl/demos/es1/MultisampleDemoES1.java | 123 ++ .../test/junit/jogl/demos/es2/FBOMix2DemosES2.java | 309 ++++ .../opengl/test/junit/jogl/demos/es2/GearsES2.java | 39 +- .../junit/jogl/demos/es2/MultisampleDemoES2.java | 178 ++ .../test/junit/jogl/demos/es2/RedSquareES2.java | 48 +- .../jogl/demos/es2/TextureSequenceCubeES2.java | 9 +- .../test/junit/jogl/demos/es2/av/MovieCube.java | 5 +- .../test/junit/jogl/demos/es2/av/MovieSimple.java | 5 +- .../jogl/demos/es2/newt/TestGearsES2NEWT.java | 3 - .../jogl/demos/es2/newt/TestRedSquareES2NEWT.java | 7 +- .../junit/jogl/demos/es2/shader/mgl_default_xxx.fp | 10 + .../junit/jogl/demos/es2/shader/mgl_default_xxx.vp | 14 + .../junit/jogl/demos/es2/shader/texture02_xxx.fp | 20 + .../opengl/test/junit/jogl/demos/gl2/Gears.java | 18 +- .../jogl/demos/gl2/awt/TestGLJPanelAWTBug450.java | 188 ++ .../demos/gl2/awt/TestGearsGLJPanelAWTBug450.java | 194 -- .../test/junit/jogl/glsl/TestFBOMRTNEWT01.java | 229 --- .../junit/jogl/glsl/TestGLSLShaderState01NEWT.java | 1 - .../junit/jogl/glsl/TestGLSLShaderState02NEWT.java | 1 - .../test/junit/jogl/offscreen/ReadBufferBase.java | 4 +- .../test/junit/jogl/offscreen/Surface2File.java | 2 +- .../test/junit/jogl/swt/TestSWTAccessor02GLn.java | 41 +- .../TestGLReadBufferUtilTextureIOWrite01AWT.java | 19 +- .../TestGLReadBufferUtilTextureIOWrite01NEWT.java | 36 +- .../TestGLReadBufferUtilTextureIOWrite02AWT.java | 20 +- .../TestGLReadBufferUtilTextureIOWrite02NEWT.java | 20 +- .../util/texture/TestPNGTextureFromFileAWT.java | 13 +- .../util/texture/TestPNGTextureFromFileNEWT.java | 11 +- .../jogamp/opengl/test/junit/util/UITestCase.java | 55 +- 165 files changed, 6996 insertions(+), 3008 deletions(-) delete mode 100644 src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLExtensionNames.java create mode 100644 src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLNameResolver.java create mode 100644 src/jogl/classes/com/jogamp/opengl/FBObject.java create mode 100644 src/jogl/classes/com/jogamp/opengl/GLExtensions.java create mode 100644 src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java delete mode 100644 src/jogl/classes/com/jogamp/opengl/util/FBObject.java create mode 100644 src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java create mode 100644 src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java delete mode 100644 src/jogl/classes/jogamp/opengl/windows/wgl/WindowsDummyWGLDrawable.java delete mode 100644 src/jogl/classes/jogamp/opengl/x11/glx/X11DummyGLXDrawable.java create mode 100644 src/nativewindow/classes/javax/media/nativewindow/MutableSurface.java delete mode 100644 src/nativewindow/classes/javax/media/nativewindow/SurfaceChangeable.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMRTNEWT01.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMix2DemosES2NEWT.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/caps/MultisampleDemoES1.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES2NEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/MultisampleDemoES1.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/FBOMix2DemosES2.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/MultisampleDemoES2.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/shader/mgl_default_xxx.fp create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/shader/mgl_default_xxx.vp create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/shader/texture02_xxx.fp create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGLJPanelAWTBug450.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsGLJPanelAWTBug450.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestFBOMRTNEWT01.java (limited to 'src/nativewindow') diff --git a/.gitignore b/.gitignore index 6e3af642b..1cd3375b4 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,7 @@ javadoc_public build-temp make/temp* .idea/workspace.xml -**~ \ No newline at end of file +.settings/* +**~ +build* +make/lib/external/* diff --git a/doc/Platform.GLES.txt b/doc/Platform.GLES.txt index 0bcd3bc8b..901e040c4 100644 --- a/doc/Platform.GLES.txt +++ b/doc/Platform.GLES.txt @@ -33,7 +33,7 @@ a request for e.g. GL2ES2 will utilize the highest common desktop profile. ...> Linux: - PVRVFrame 2.09.29.0649 + PVRVFrame 2.09.29.0649, Version_REL_2.10 Debian Wheezy/testing x64, NV 290.10, 32bit libraries: OK GL_VENDOR Imagination Technologies (Host GL: `NVIDIA Corporation`) GL_RENDERER PowerVR PVRVFrame 8.1 SGX (Host GL: `GeForce GTX 460/PCI/SSE2`) @@ -75,7 +75,7 @@ Linux: Ubuntu 11.10 x64, AMD Catalyst 12.1, 64bit libraries, libgles2-mesa 7.11-0ubuntu3: Error (swrast error, null values) Windows: - PVRVFrame 2.09.29.0649 + PVRVFrame 2.09.29.0649, Version_REL_2.10 Windows7 64bit, NV 290.10, 32bit libraries: OK GL_VENDOR Imagination Technologies (Host GL: `NVIDIA Corporation`) GL_RENDERER PowerVR PVRVFrame 8.1 SGX (Host GL: `GeForce GTX 460/PCIe/SSE2`) diff --git a/doc/TODO.txt b/doc/TODO.txt index f86d31e4c..82f013265 100644 --- a/doc/TODO.txt +++ b/doc/TODO.txt @@ -1,16 +1,15 @@ WIP: +- GLPbuffer -> GLOffscreenAutoDrawable + - GLPbuffer GLDrawableFactory.createPbuffer() -> + GLOffscreenAutoDrawable GLDrawableFactory.createOffsceenAutoDrawable() + - Mark both deprecated! + Random, somewhat old to-do list: - Non-const array types must be properly released with JNI_COMMIT in order to see side effects if the array was copied. -- figure out how to deal with WGL entry points: - WINGDIAPI HGLRC WINAPI wglCreateLayerContext(HDC, int); - WINGDIAPI BOOL WINAPI wglUseFontBitmapsA(HDC, DWORD, DWORD, DWORD); - WINGDIAPI BOOL WINAPI wglUseFontBitmapsW(HDC, DWORD, DWORD, DWORD); - see commented-out section in make/stub_includes/win32/wingdi.h - - Need a disciplined mechanism for converting char* argument types. For example, many C functions accept a "char*" argument with the semantic that output data will be written into the buffer pointed to by the diff --git a/etc/test.bat b/etc/test.bat index 0c82233ca..d635c7e8f 100755 --- a/etc/test.bat +++ b/etc/test.bat @@ -1,7 +1,7 @@ set BLD_DIR=jar -set CP_ALL=.;%BLD_DIR%\gluegen-rt.jar;%BLD_DIR%\jogl.all.jar +set CP_ALL=.;%BLD_DIR%\gluegen-rt.jar;%BLD_DIR%\jogl-all.jar echo CP_ALL %CP_ALL% set X_ARGS="-Dsun.java2d.noddraw=true" "-Dsun.awt.noerasebackground=true" diff --git a/etc/test_dbg.bat b/etc/test_dbg.bat index 33bbb912b..209690758 100755 --- a/etc/test_dbg.bat +++ b/etc/test_dbg.bat @@ -1,7 +1,7 @@ set BLD_DIR=jar -set CP_ALL=.;%BLD_DIR%\gluegen-rt.jar;%BLD_DIR%\jogl.all.jar +set CP_ALL=.;%BLD_DIR%\gluegen-rt.jar;%BLD_DIR%\jogl-all.jar echo CP_ALL %CP_ALL% set D_ARGS="-Djogamp.debug=all" "-Dnativewindow.debug=all" "-Djogl.debug=all" "-Dnewt.debug=all" diff --git a/make/config/jogl/gl-common.cfg b/make/config/jogl/gl-common.cfg index 8af080ec8..9c5467583 100644 --- a/make/config/jogl/gl-common.cfg +++ b/make/config/jogl/gl-common.cfg @@ -481,6 +481,19 @@ JavaPrologue glGetString return _context.getGLVersion(); JavaPrologue glGetString } */ JavaPrologue glGetString } +# +# Allow special FBO GLContext/GLDrawable to reset to it's +# default FBO framebuffer. +# +JavaPrologue glBindFramebuffer if( 0 == framebuffer ) { +JavaPrologue glBindFramebuffer if( GL_FRAMEBUFFER == target || 0x8CA9 /* GL_DRAW_FRAMEBUFFER */ == target ) { +JavaPrologue glBindFramebuffer framebuffer = _context.getDefaultDrawFramebuffer(); +JavaPrologue glBindFramebuffer } else if( 0x8CA8 /* GL_READ_FRAMEBUFFER */ == target ) { +JavaPrologue glBindFramebuffer framebuffer = _context.getDefaultReadFramebuffer(); +JavaPrologue glBindFramebuffer } +JavaPrologue glBindFramebuffer } +JavaEpilogue glBindFramebuffer _context.setBoundFramebuffer(target, framebuffer); + # # Directives for Vertex Buffer Object and Pixel Buffer Object checking # diff --git a/make/config/jogl/gl-if-CustomJavaCode-gl.java b/make/config/jogl/gl-if-CustomJavaCode-gl.java index 77378aa45..9ea4f98b4 100644 --- a/make/config/jogl/gl-if-CustomJavaCode-gl.java +++ b/make/config/jogl/gl-if-CustomJavaCode-gl.java @@ -57,29 +57,3 @@ earmarked for ES 3.0 (hence kept in GL while fixing Bug 590) */ public static final int GL_HALF_FLOAT = 0x140B; - public void glClearDepth( double depth ); - - public void glDepthRange(double zNear, double zFar); - - /** - * @param target a GL buffer (VBO) target as used in {@link GL#glBindBuffer(int, int)}, ie {@link GL#GL_ELEMENT_ARRAY_BUFFER}, {@link GL#GL_ARRAY_BUFFER}, .. - * @return the GL buffer (VBO) name bound to a target via {@link GL#glBindBuffer(int, int)} or 0 if unbound. - */ - public int glGetBoundBuffer(int target); - - /** - * @param buffer a GL buffer name, generated with {@link GL#glGenBuffers(int, int[], int)} and used in {@link GL#glBindBuffer(int, int)}, {@link GL#glBufferData(int, long, java.nio.Buffer, int)} or {@link GL2#glNamedBufferDataEXT(int, long, java.nio.Buffer, int)} for example. - * @return the size of the given GL buffer - */ - public long glGetBufferSize(int buffer); - - /** - * @return true if a VBO is bound to {@link GL.GL_ARRAY_BUFFER} via {@link GL#glBindBuffer(int, int)}, otherwise false - */ - public boolean glIsVBOArrayEnabled(); - - /** - * @return true if a VBO is bound to {@link GL.GL_ELEMENT_ARRAY_BUFFER} via {@link GL#glBindBuffer(int, int)}, otherwise false - */ - public boolean glIsVBOElementArrayEnabled(); - diff --git a/make/config/jogl/gl-impl-CustomJavaCode-common.java b/make/config/jogl/gl-impl-CustomJavaCode-common.java index d552bc6e4..b05ba2643 100644 --- a/make/config/jogl/gl-impl-CustomJavaCode-common.java +++ b/make/config/jogl/gl-impl-CustomJavaCode-common.java @@ -1,48 +1,57 @@ + @Override public GLProfile getGLProfile() { return this.glProfile; } private final GLProfile glProfile; - public int glGetBoundBuffer(int target) { + @Override + public final int glGetBoundBuffer(int target) { return bufferStateTracker.getBoundBufferObject(target, this); } - public long glGetBufferSize(int buffer) { + @Override + public final long glGetBufferSize(int buffer) { return bufferSizeTracker.getDirectStateBufferSize(buffer, this); } - public boolean glIsVBOArrayEnabled() { + @Override + public final boolean glIsVBOArrayEnabled() { return checkArrayVBOEnabled(false); } - public boolean glIsVBOElementArrayEnabled() { + @Override + public final boolean glIsVBOElementArrayEnabled() { return checkElementVBOEnabled(false); } + @Override public final boolean isGL() { return true; } + @Override public final GL getGL() throws GLException { return this; } - public boolean isFunctionAvailable(String glFunctionName) { + @Override + public final boolean isFunctionAvailable(String glFunctionName) { return _context.isFunctionAvailable(glFunctionName); } - public boolean isExtensionAvailable(String glExtensionName) { + @Override + public final boolean isExtensionAvailable(String glExtensionName) { return _context.isExtensionAvailable(glExtensionName); } - public Object getExtension(String extensionName) { + @Override + public final Object getExtension(String extensionName) { // At this point we don't expose any extensions using this mechanism return null; } - /** Returns the context this GL object is associated with for better - error checking by DebugGL. */ - public GLContext getContext() { + @Override + public final GLContext getContext() { return _context; } @@ -51,18 +60,36 @@ /** * @see javax.media.opengl.GLContext#setSwapInterval(int) */ - public void setSwapInterval(int interval) { + @Override + public final void setSwapInterval(int interval) { _context.setSwapInterval(interval); } /** * @see javax.media.opengl.GLContext#getSwapInterval() */ - public int getSwapInterval() { + @Override + public final int getSwapInterval() { return _context.getSwapInterval(); } - public Object getPlatformGLExtensions() { + @Override + public final Object getPlatformGLExtensions() { return _context.getPlatformGLExtensions(); } + @Override + public final int getBoundFramebuffer(int target) { + return _context.getBoundFramebuffer(target); + } + + @Override + public final int getDefaultDrawFramebuffer() { + return _context.getDefaultDrawFramebuffer(); + } + + @Override + public final int getDefaultReadFramebuffer() { + return _context.getDefaultReadFramebuffer(); + } + diff --git a/make/config/jogl/gl-impl-CustomJavaCode-desktop.java b/make/config/jogl/gl-impl-CustomJavaCode-desktop.java index 33b0f1326..6a74b80a6 100644 --- a/make/config/jogl/gl-impl-CustomJavaCode-desktop.java +++ b/make/config/jogl/gl-impl-CustomJavaCode-desktop.java @@ -4,34 +4,42 @@ return GLBuffers.sizeof(this, imageSizeTemp, format, type, width, height, depth, pack) ; } + @Override public final boolean isGL4bc() { return _context.isGL4bc(); } + @Override public final boolean isGL4() { return _context.isGL4(); } + @Override public final boolean isGL3bc() { return _context.isGL3bc(); } + @Override public final boolean isGL3() { return _context.isGL3(); } + @Override public final boolean isGL2() { return _context.isGL2(); } + @Override public final boolean isGL2ES1() { return _context.isGL2ES1(); } + @Override public final boolean isGL2ES2() { return _context.isGL2ES2(); } + @Override public final boolean isGLES2Compatible() { return _context.isGLES2Compatible(); } @@ -40,10 +48,12 @@ return _context.isGL2GL3(); } + @Override public final boolean hasGLSL() { return _context.hasGLSL(); } + @Override public final GL4bc getGL4bc() throws GLException { if(!isGL4bc()) { throw new GLException("Not a GL4bc implementation"); @@ -51,6 +61,7 @@ return this; } + @Override public final GL4 getGL4() throws GLException { if(!isGL4()) { throw new GLException("Not a GL4 implementation"); @@ -58,6 +69,7 @@ return this; } + @Override public final GL3bc getGL3bc() throws GLException { if(!isGL3bc()) { throw new GLException("Not a GL3bc implementation"); @@ -65,6 +77,7 @@ return this; } + @Override public final GL3 getGL3() throws GLException { if(!isGL3()) { throw new GLException("Not a GL3 implementation"); @@ -72,6 +85,7 @@ return this; } + @Override public final GL2 getGL2() throws GLException { if(!isGL2()) { throw new GLException("Not a GL2 implementation"); @@ -79,6 +93,7 @@ return this; } + @Override public final GL2ES1 getGL2ES1() throws GLException { if(!isGL2ES1()) { throw new GLException("Not a GL2ES1 implementation"); @@ -86,6 +101,7 @@ return this; } + @Override public final GL2ES2 getGL2ES2() throws GLException { if(!isGL2ES2()) { throw new GLException("Not a GL2ES2 implementation"); @@ -93,6 +109,7 @@ return this; } + @Override public final GL2GL3 getGL2GL3() throws GLException { if(!isGL2GL3()) { throw new GLException("Not a GL2GL3 implementation"); @@ -100,26 +117,32 @@ return this; } + @Override public final boolean isGLES1() { return false; } + @Override public final boolean isGLES2() { return false; } + @Override public final boolean isGLES() { return false; } + @Override public final GLES1 getGLES1() throws GLException { throw new GLException("Not a GLES1 implementation"); } + @Override public final GLES2 getGLES2() throws GLException { throw new GLException("Not a GLES2 implementation"); } - public boolean isNPOTTextureAvailable() { + @Override + public final boolean isNPOTTextureAvailable() { return _context.isNPOTTextureAvailable(); } diff --git a/make/config/jogl/gl-impl-CustomJavaCode-gl2_es2.java b/make/config/jogl/gl-impl-CustomJavaCode-gl2_es2.java index b31a087e7..82b791208 100644 --- a/make/config/jogl/gl-impl-CustomJavaCode-gl2_es2.java +++ b/make/config/jogl/gl-impl-CustomJavaCode-gl2_es2.java @@ -1,4 +1,5 @@ - public void glVertexAttribPointer(GLArrayData array) { + @Override + public final void glVertexAttribPointer(GLArrayData array) { if(array.getComponentCount()==0) return; if(array.isVBO()) { glVertexAttribPointer(array.getLocation(), array.getComponentCount(), array.getComponentType(), @@ -9,7 +10,8 @@ } } - public void glUniform(GLUniformData data) { + @Override + public final void glUniform(GLUniformData data) { boolean done=false; if(data.isBuffer()) { Buffer buffer = data.getBuffer(); diff --git a/make/config/jogl/gl-impl-CustomJavaCode-gl4bc.java b/make/config/jogl/gl-impl-CustomJavaCode-gl4bc.java index 95aa7cc2c..e079a1a24 100644 --- a/make/config/jogl/gl-impl-CustomJavaCode-gl4bc.java +++ b/make/config/jogl/gl-impl-CustomJavaCode-gl4bc.java @@ -33,7 +33,7 @@ public GL4bcImpl(GLProfile glp, GLContextImpl context) { * Provides platform-independent access to the wglAllocateMemoryNV / * glXAllocateMemoryNV extension. */ -public java.nio.ByteBuffer glAllocateMemoryNV(int arg0, float arg1, float arg2, float arg3) { +public final java.nio.ByteBuffer glAllocateMemoryNV(int arg0, float arg1, float arg2, float arg3) { return _context.glAllocateMemoryNV(arg0, arg1, arg2, arg3); } @@ -52,7 +52,7 @@ private boolean haveGL15; private boolean haveGL21; private boolean haveARBVertexBufferObject; -private void initBufferObjectExtensionChecks() { +private final void initBufferObjectExtensionChecks() { if (bufferObjectExtensionsInitialized) return; bufferObjectExtensionsInitialized = true; @@ -63,12 +63,12 @@ private void initBufferObjectExtensionChecks() { haveARBVertexBufferObject = isExtensionAvailable("GL_ARB_vertex_buffer_object"); } -private boolean checkBufferObject(boolean extension1, - boolean extension2, - boolean extension3, - boolean enabled, - int state, - String kind, boolean throwException) { +private final boolean checkBufferObject(boolean extension1, + boolean extension2, + boolean extension3, + boolean enabled, + int state, + String kind, boolean throwException) { if (inBeginEndPair) { throw new GLException("May not call this between glBegin and glEnd"); } @@ -100,7 +100,7 @@ private boolean checkBufferObject(boolean extension1, return true; } -private boolean checkArrayVBODisabled(boolean throwException) { +private final boolean checkArrayVBODisabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(haveGL15, haveARBVertexBufferObject, @@ -110,7 +110,7 @@ private boolean checkArrayVBODisabled(boolean throwException) { "array vertex_buffer_object", throwException); } -private boolean checkArrayVBOEnabled(boolean throwException) { +private final boolean checkArrayVBOEnabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(haveGL15, haveARBVertexBufferObject, @@ -120,7 +120,7 @@ private boolean checkArrayVBOEnabled(boolean throwException) { "array vertex_buffer_object", throwException); } -private boolean checkElementVBODisabled(boolean throwException) { +private final boolean checkElementVBODisabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(haveGL15, haveARBVertexBufferObject, @@ -130,7 +130,7 @@ private boolean checkElementVBODisabled(boolean throwException) { "element vertex_buffer_object", throwException); } -private boolean checkElementVBOEnabled(boolean throwException) { +private final boolean checkElementVBOEnabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(haveGL15, haveARBVertexBufferObject, @@ -140,7 +140,7 @@ private boolean checkElementVBOEnabled(boolean throwException) { "element vertex_buffer_object", throwException); } -private boolean checkUnpackPBODisabled(boolean throwException) { +private final boolean checkUnpackPBODisabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(haveARBPixelBufferObject, haveEXTPixelBufferObject, @@ -150,7 +150,7 @@ private boolean checkUnpackPBODisabled(boolean throwException) { "unpack pixel_buffer_object", throwException); } -private boolean checkUnpackPBOEnabled(boolean throwException) { +private final boolean checkUnpackPBOEnabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(haveARBPixelBufferObject, haveEXTPixelBufferObject, @@ -160,7 +160,7 @@ private boolean checkUnpackPBOEnabled(boolean throwException) { "unpack pixel_buffer_object", throwException); } -private boolean checkPackPBODisabled(boolean throwException) { +private final boolean checkPackPBODisabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(haveARBPixelBufferObject, haveEXTPixelBufferObject, @@ -170,7 +170,7 @@ private boolean checkPackPBODisabled(boolean throwException) { "pack pixel_buffer_object", throwException); } -private boolean checkPackPBOEnabled(boolean throwException) { +private final boolean checkPackPBOEnabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(haveARBPixelBufferObject, haveEXTPixelBufferObject, @@ -180,18 +180,20 @@ private boolean checkPackPBOEnabled(boolean throwException) { "pack pixel_buffer_object", throwException); } -public boolean glIsPBOPackEnabled() { +@Override +public final boolean glIsPBOPackEnabled() { return checkPackPBOEnabled(false); } -public boolean glIsPBOUnpackEnabled() { +@Override +public final boolean glIsPBOUnpackEnabled() { return checkUnpackPBOEnabled(false); } -private HashMap arbMemCache = new HashMap(); +private final HashMap arbMemCache = new HashMap(); /** Entry point to C language function:
LPVOID glMapBuffer(GLenum target, GLenum access); */ -public java.nio.ByteBuffer glMapBuffer(int target, int access) { +public final java.nio.ByteBuffer glMapBuffer(int target, int access) { final long __addr_ = ((GL4bcProcAddressTable)_context.getGLProcAddressTable())._addressof_glMapBuffer; if (__addr_ == 0) { throw new GLException("Method \"glMapBuffer\" not available"); @@ -230,7 +232,7 @@ public java.nio.ByteBuffer glMapBuffer(int target, int access) { native private long dispatch_glMapBuffer(int target, int access, long glProcAddress); /** Entry point to C language function: GLvoid * {@native glMapNamedBufferEXT}(GLuint buffer, GLenum access);
Part of GL_EXT_direct_state_access */ -public java.nio.ByteBuffer glMapNamedBufferEXT(int bufferName, int access) { +public final java.nio.ByteBuffer glMapNamedBufferEXT(int bufferName, int access) { final long __addr_ = ((GL4bcProcAddressTable)_context.getGLProcAddressTable())._addressof_glMapNamedBufferEXT; if (__addr_ == 0) { throw new GLException("Method \"glMapNamedBufferEXT\" not available"); @@ -269,7 +271,8 @@ private native long dispatch_glMapNamedBufferEXT(int buffer, int access, long pr native private ByteBuffer newDirectByteBuffer(long addr, long capacity); - public void glVertexPointer(GLArrayData array) { + @Override + public final void glVertexPointer(GLArrayData array) { if(array.getComponentCount()==0) return; if(array.isVBO()) { glVertexPointer(array.getComponentCount(), array.getComponentType(), array.getStride(), array.getVBOOffset()); @@ -277,7 +280,8 @@ native private ByteBuffer newDirectByteBuffer(long addr, long capacity); glVertexPointer(array.getComponentCount(), array.getComponentType(), array.getStride(), array.getBuffer()); } } - public void glColorPointer(GLArrayData array) { + @Override + public final void glColorPointer(GLArrayData array) { if(array.getComponentCount()==0) return; if(array.isVBO()) { glColorPointer(array.getComponentCount(), array.getComponentType(), array.getStride(), array.getVBOOffset()); @@ -286,7 +290,8 @@ native private ByteBuffer newDirectByteBuffer(long addr, long capacity); } } - public void glNormalPointer(GLArrayData array) { + @Override + public final void glNormalPointer(GLArrayData array) { if(array.getComponentCount()==0) return; if(array.getComponentCount()!=3) { throw new GLException("Only 3 components per normal allowed"); @@ -297,7 +302,8 @@ native private ByteBuffer newDirectByteBuffer(long addr, long capacity); glNormalPointer(array.getComponentType(), array.getStride(), array.getBuffer()); } } - public void glTexCoordPointer(GLArrayData array) { + @Override + public final void glTexCoordPointer(GLArrayData array) { if(array.getComponentCount()==0) return; if(array.isVBO()) { glTexCoordPointer(array.getComponentCount(), array.getComponentType(), array.getStride(), array.getVBOOffset()); diff --git a/make/config/jogl/gl-impl-CustomJavaCode-gles1.java b/make/config/jogl/gl-impl-CustomJavaCode-gles1.java index dff33cf81..68eadc683 100644 --- a/make/config/jogl/gl-impl-CustomJavaCode-gles1.java +++ b/make/config/jogl/gl-impl-CustomJavaCode-gles1.java @@ -12,98 +12,122 @@ public GLES1Impl(GLProfile glp, GLContextImpl context) { this.glProfile = glp; } +@Override public final boolean isGL4bc() { return false; } +@Override public final boolean isGL4() { return false; } +@Override public final boolean isGL3bc() { return false; } +@Override public final boolean isGL3() { return false; } +@Override public final boolean isGL2() { return false; } +@Override public final boolean isGLES1() { return true; } +@Override public final boolean isGLES2() { return false; } +@Override public final boolean isGLES() { return true; } +@Override public final boolean isGL2ES1() { return true; } +@Override public final boolean isGL2ES2() { return false; } +@Override public final boolean isGLES2Compatible() { return false; } +@Override public final boolean isGL2GL3() { return false; } +@Override public final boolean hasGLSL() { return false; } +@Override public boolean isNPOTTextureAvailable() { return false; } +@Override public final GL4bc getGL4bc() throws GLException { throw new GLException("Not a GL4bc implementation"); } +@Override public final GL4 getGL4() throws GLException { throw new GLException("Not a GL4 implementation"); } +@Override public final GL3bc getGL3bc() throws GLException { throw new GLException("Not a GL3bc implementation"); } +@Override public final GL3 getGL3() throws GLException { throw new GLException("Not a GL3 implementation"); } +@Override public final GL2 getGL2() throws GLException { throw new GLException("Not a GL2 implementation"); } +@Override public final GLES1 getGLES1() throws GLException { return this; } +@Override public final GLES2 getGLES2() throws GLException { throw new GLException("Not a GLES2 implementation"); } +@Override public final GL2ES1 getGL2ES1() throws GLException { return this; } +@Override public final GL2ES2 getGL2ES2() throws GLException { throw new GLException("Not a GL2ES2 implementation"); } +@Override public final GL2GL3 getGL2GL3() throws GLException { throw new GLException("Not a GL2GL3 implementation"); } @@ -119,17 +143,17 @@ private final GLStateTracker glStateTracker; private boolean bufferObjectExtensionsInitialized = false; private boolean haveOESFramebufferObject; -private void initBufferObjectExtensionChecks() { +private final void initBufferObjectExtensionChecks() { if (bufferObjectExtensionsInitialized) return; bufferObjectExtensionsInitialized = true; haveOESFramebufferObject = isExtensionAvailable("GL_OES_framebuffer_object"); } -private boolean checkBufferObject(boolean avail, - boolean enabled, - int state, - String kind, boolean throwException) { +private final boolean checkBufferObject(boolean avail, + boolean enabled, + int state, + String kind, boolean throwException) { if (!avail) { if (!enabled) return true; @@ -157,7 +181,7 @@ private boolean checkBufferObject(boolean avail, return true; } -private boolean checkArrayVBODisabled(boolean throwException) { +private final boolean checkArrayVBODisabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(true, false, @@ -165,7 +189,7 @@ private boolean checkArrayVBODisabled(boolean throwException) { "array vertex_buffer_object", throwException); } -private boolean checkArrayVBOEnabled(boolean throwException) { +private final boolean checkArrayVBOEnabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(true, true, @@ -173,7 +197,7 @@ private boolean checkArrayVBOEnabled(boolean throwException) { "array vertex_buffer_object", throwException); } -private boolean checkElementVBODisabled(boolean throwException) { +private final boolean checkElementVBODisabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(true, false, @@ -181,7 +205,7 @@ private boolean checkElementVBODisabled(boolean throwException) { "element vertex_buffer_object", throwException); } -private boolean checkElementVBOEnabled(boolean throwException) { +private final boolean checkElementVBOEnabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(true, true, @@ -189,30 +213,30 @@ private boolean checkElementVBOEnabled(boolean throwException) { "element vertex_buffer_object", throwException); } -private boolean checkUnpackPBODisabled(boolean throwException) { +private final boolean checkUnpackPBODisabled(boolean throwException) { // PBO n/a for ES 1.1 or ES 2.0 return true; } -private boolean checkUnpackPBOEnabled(boolean throwException) { +private final boolean checkUnpackPBOEnabled(boolean throwException) { // PBO n/a for ES 1.1 or ES 2.0 return false; } -private boolean checkPackPBODisabled(boolean throwException) { +private final boolean checkPackPBODisabled(boolean throwException) { // PBO n/a for ES 1.1 or ES 2.0 return true; } -private boolean checkPackPBOEnabled(boolean throwException) { +private final boolean checkPackPBOEnabled(boolean throwException) { // PBO n/a for ES 1.1 or ES 2.0 return false; } -private HashMap arbMemCache = new HashMap(); +private final HashMap arbMemCache = new HashMap(); /** Entry point to C language function:
LPVOID glMapBuffer(GLenum target, GLenum access); */ -public java.nio.ByteBuffer glMapBuffer(int target, int access) { +public final java.nio.ByteBuffer glMapBuffer(int target, int access) { final long __addr_ = ((GLES1ProcAddressTable)_context.getGLProcAddressTable())._addressof_glMapBuffer; if (__addr_ == 0) { throw new GLException("Method \"glMapBuffer\" not available"); @@ -252,7 +276,8 @@ native private long dispatch_glMapBuffer(int target, int access, long glProcAddr native private ByteBuffer newDirectByteBuffer(long addr, long capacity); -public void glVertexPointer(GLArrayData array) { +@Override +public final void glVertexPointer(GLArrayData array) { if(array.getComponentCount()==0) return; if(array.isVBO()) { glVertexPointer(array.getComponentCount(), array.getComponentType(), array.getStride(), array.getVBOOffset()); @@ -260,7 +285,8 @@ public void glVertexPointer(GLArrayData array) { glVertexPointer(array.getComponentCount(), array.getComponentType(), array.getStride(), array.getBuffer()); } } -public void glColorPointer(GLArrayData array) { +@Override +public final void glColorPointer(GLArrayData array) { if(array.getComponentCount()==0) return; if(array.isVBO()) { glColorPointer(array.getComponentCount(), array.getComponentType(), array.getStride(), array.getVBOOffset()); @@ -269,7 +295,8 @@ public void glColorPointer(GLArrayData array) { } } -public void glNormalPointer(GLArrayData array) { +@Override +public final void glNormalPointer(GLArrayData array) { if(array.getComponentCount()==0) return; if(array.getComponentCount()!=3) { throw new GLException("Only 3 components per normal allowed"); @@ -280,7 +307,8 @@ public void glNormalPointer(GLArrayData array) { glNormalPointer(array.getComponentType(), array.getStride(), array.getBuffer()); } } -public void glTexCoordPointer(GLArrayData array) { +@Override +public final void glTexCoordPointer(GLArrayData array) { if(array.getComponentCount()==0) return; if(array.isVBO()) { glTexCoordPointer(array.getComponentCount(), array.getComponentType(), array.getStride(), array.getVBOOffset()); diff --git a/make/config/jogl/gl-impl-CustomJavaCode-gles2.java b/make/config/jogl/gl-impl-CustomJavaCode-gles2.java index a4976f5ea..760287364 100644 --- a/make/config/jogl/gl-impl-CustomJavaCode-gles2.java +++ b/make/config/jogl/gl-impl-CustomJavaCode-gles2.java @@ -1,6 +1,3 @@ -// Tracks glBegin/glEnd calls to determine whether it is legal to -// query Vertex Buffer Object state -private boolean inBeginEndPair; public GLES2Impl(GLProfile glp, GLContextImpl context) { this._context = context; @@ -16,18 +13,22 @@ public GLES2Impl(GLProfile glp, GLContextImpl context) { this.glProfile = glp; } +@Override public final boolean isGL4bc() { return false; } +@Override public final boolean isGL4() { return false; } +@Override public final boolean isGL3bc() { return false; } +@Override public final boolean isGL3() { return false; } @@ -36,78 +37,97 @@ public final boolean isGL2() { return false; } +@Override public final boolean isGLES1() { return false; } +@Override public final boolean isGLES2() { return true; } +@Override public final boolean isGLES() { return true; } +@Override public final boolean isGL2ES1() { return false; } +@Override public final boolean isGL2ES2() { return true; } +@Override public final boolean isGLES2Compatible() { return true; } +@Override public final boolean isGL2GL3() { return false; } +@Override public final boolean hasGLSL() { return true; } +@Override public boolean isNPOTTextureAvailable() { return true; } +@Override public final GL4bc getGL4bc() throws GLException { throw new GLException("Not a GL4bc implementation"); } +@Override public final GL4 getGL4() throws GLException { throw new GLException("Not a GL4 implementation"); } +@Override public final GL3bc getGL3bc() throws GLException { throw new GLException("Not a GL3bc implementation"); } +@Override public final GL3 getGL3() throws GLException { throw new GLException("Not a GL3 implementation"); } +@Override public final GL2 getGL2() throws GLException { throw new GLException("Not a GL2 implementation"); } +@Override public final GLES1 getGLES1() throws GLException { throw new GLException("Not a GLES1 implementation"); } +@Override public final GLES2 getGLES2() throws GLException { return this; } +@Override public final GL2ES1 getGL2ES1() throws GLException { throw new GLException("Not a GL2ES1 implementation"); } +@Override public final GL2ES2 getGL2ES2() throws GLException { return this; } +@Override public final GL2GL3 getGL2GL3() throws GLException { throw new GLException("Not a GL2GL3 implementation"); } @@ -123,17 +143,17 @@ private final GLStateTracker glStateTracker; private boolean bufferObjectExtensionsInitialized = false; private boolean haveOESFramebufferObject; -private void initBufferObjectExtensionChecks() { +private final void initBufferObjectExtensionChecks() { if (bufferObjectExtensionsInitialized) return; bufferObjectExtensionsInitialized = true; haveOESFramebufferObject = isExtensionAvailable("GL_OES_framebuffer_object"); } -private boolean checkBufferObject(boolean avail, - boolean enabled, - int state, - String kind, boolean throwException) { +private final boolean checkBufferObject(boolean avail, + boolean enabled, + int state, + String kind, boolean throwException) { if (!avail) { if (!enabled) return true; @@ -161,7 +181,7 @@ private boolean checkBufferObject(boolean avail, return true; } -private boolean checkArrayVBODisabled(boolean throwException) { +private final boolean checkArrayVBODisabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(true, false, @@ -169,7 +189,7 @@ private boolean checkArrayVBODisabled(boolean throwException) { "array vertex_buffer_object", throwException); } -private boolean checkArrayVBOEnabled(boolean throwException) { +private final boolean checkArrayVBOEnabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(true, true, @@ -177,7 +197,7 @@ private boolean checkArrayVBOEnabled(boolean throwException) { "array vertex_buffer_object", throwException); } -private boolean checkElementVBODisabled(boolean throwException) { +private final boolean checkElementVBODisabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(true, false, @@ -185,7 +205,7 @@ private boolean checkElementVBODisabled(boolean throwException) { "element vertex_buffer_object", throwException); } -private boolean checkElementVBOEnabled(boolean throwException) { +private final boolean checkElementVBOEnabled(boolean throwException) { initBufferObjectExtensionChecks(); return checkBufferObject(true, true, @@ -193,30 +213,31 @@ private boolean checkElementVBOEnabled(boolean throwException) { "element vertex_buffer_object", throwException); } -private boolean checkUnpackPBODisabled(boolean throwException) { +private final boolean checkUnpackPBODisabled(boolean throwException) { // PBO n/a for ES 1.1 or ES 2.0 return true; } -private boolean checkUnpackPBOEnabled(boolean throwException) { +private final boolean checkUnpackPBOEnabled(boolean throwException) { // PBO n/a for ES 1.1 or ES 2.0 return false; } -private boolean checkPackPBODisabled(boolean throwException) { +private final boolean checkPackPBODisabled(boolean throwException) { // PBO n/a for ES 1.1 or ES 2.0 return true; } -private boolean checkPackPBOEnabled(boolean throwException) { +private final boolean checkPackPBOEnabled(boolean throwException) { // PBO n/a for ES 1.1 or ES 2.0 return false; } -private HashMap arbMemCache = new HashMap(); +private final HashMap arbMemCache = new HashMap(); /** Entry point to C language function:
LPVOID glMapBuffer(GLenum target, GLenum access); */ -public java.nio.ByteBuffer glMapBuffer(int target, int access) { +@Override +public final java.nio.ByteBuffer glMapBuffer(int target, int access) { final long __addr_ = ((GLES2ProcAddressTable)_context.getGLProcAddressTable())._addressof_glMapBuffer; if (__addr_ == 0) { throw new GLException("Method \"glMapBuffer\" not available"); @@ -256,11 +277,13 @@ native private long dispatch_glMapBuffer(int target, int access, long glProcAddr native private ByteBuffer newDirectByteBuffer(long addr, long capacity); -public void glClearDepth(double depth) { +@Override +public final void glClearDepth(double depth) { glClearDepthf((float)depth); } -public void glDepthRange(double zNear, double zFar) { +@Override +public final void glDepthRange(double zNear, double zFar) { glDepthRangef((float)zNear, (float)zFar); } diff --git a/make/scripts/java-win32-dbg.bat b/make/scripts/java-win32-dbg.bat index d1797bdbb..6f8206721 100755 --- a/make/scripts/java-win32-dbg.bat +++ b/make/scripts/java-win32-dbg.bat @@ -9,9 +9,9 @@ set BLD_DIR=..\%BLD_SUB% set FFMPEG_LIB=%PROJECT_ROOT%\make\lib\ffmpeg\x32 -set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%FFMPEG_LIB%;%PATH% -REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\angle\win32;%PATH% -REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\PVRVFrame\OGLES-2.0\Windows_x86_32;%PATH% +REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%FFMPEG_LIB%;%PATH% +REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\external\angle\win32;%PATH% +set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\external\PVRVFrame\OGLES-2.0\Windows_x86_32;%PATH% REM set LIB_DIR=%BLD_DIR%\lib;..\..\gluegen\%BLD_SUB%\obj set LIB_DIR=%FFMPEG_LIB% @@ -20,11 +20,14 @@ set CP_ALL=.;%BLD_DIR%\jar\jogl-all.jar;%BLD_DIR%\jar\jogl-test.jar;..\..\gluege echo CP_ALL %CP_ALL% -set D_ARGS="-Djogamp.debug.IOUtil" "-Djogl.debug.GLSLCode" "-Djogl.debug.GLMediaPlayer" +set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.FBObject" +REM set D_ARGS="-Djogl.debug.GLDrawable" "-Djogl.debug.EGLDrawableFactory.DontQuery" +REM set D_ARGS="-Djogl.debug.GLDrawable" "-Djogl.debug.EGLDrawableFactory.QueryNativeTK" +REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" +REM set D_ARGS="-Djogamp.debug.IOUtil" "-Djogl.debug.GLSLCode" "-Djogl.debug.GLMediaPlayer" REM set D_ARGS="-Djogl.debug.ExtensionAvailabilityCache" "-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.ProcAddressHelper=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.NativeLibrary=true" REM set D_ARGS="-Djogamp.debug.JNILibLoader=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" "-Djogl.debug.GLProfile=true" -REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" REM set D_ARGS="-Dnewt.debug.Window" "-Dnativewindow.debug.TraceLock" REM set D_ARGS="-Dnativewindow.debug.TraceLock" REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display" diff --git a/make/scripts/java-win32.bat b/make/scripts/java-win32.bat index 9d59c045e..1d8430280 100755 --- a/make/scripts/java-win32.bat +++ b/make/scripts/java-win32.bat @@ -8,8 +8,8 @@ set PROJECT_ROOT=D:\projects\jogamp\jogl set BLD_DIR=..\%BLD_SUB% REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;c:\mingw\bin;%PATH% -set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\angle\win32;%PATH% -REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\PVRVFrame\OGLES-2.0\Windows_x86_32;%PATH% +REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\angle\win32;%PATH% +set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\PVRVFrame\OGLES-2.0\Windows_x86_32;%PATH% set BLD_DIR=..\%BLD_SUB% REM set LIB_DIR=..\..\gluegen\%BLD_SUB%\obj;%BLD_DIR%\lib diff --git a/make/scripts/java-win64-dbg.bat b/make/scripts/java-win64-dbg.bat index d6b0435ea..109755d2e 100755 --- a/make/scripts/java-win64-dbg.bat +++ b/make/scripts/java-win64-dbg.bat @@ -9,7 +9,8 @@ set BLD_DIR=..\%BLD_SUB% set FFMPEG_LIB=%PROJECT_ROOT%\make\lib\ffmpeg\x64 -set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%FFMPEG_LIB%;%PATH% +set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;c:\mingw\bin;%PATH% +REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\external\PVRVFrame\OGLES-2.0\Windows_x86_64;%PATH% REM set LIB_DIR=%BLD_DIR%\lib;..\..\gluegen\%BLD_SUB%\obj set LIB_DIR=%FFMPEG_LIB% @@ -17,7 +18,13 @@ set CP_ALL=.;%BLD_DIR%\jar\jogl-all.jar;%BLD_DIR%\jar\jogl-test.jar;..\..\gluege echo CP_ALL %CP_ALL% -set D_ARGS="-Djogamp.debug.IOUtil" "-Djogl.debug.GLSLCode" "-Djogl.debug.GLMediaPlayer" +set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.FBObject" +REM set D_ARGS="-Djogl.debug.GLDrawable" "-Djogl.debug.EGLDrawableFactory.DontQuery" +REM set D_ARGS="-Djogl.debug.GLDrawable" "-Djogl.debug.EGLDrawableFactory.QueryNativeTK" +REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" +REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug=all" "-Djogl.debug.EGLDrawableFactory.DontQuery" +REM set D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.CapabilitiesChooser -Djogl.debug.GLProfile" +REM set D_ARGS="-Djogamp.debug.IOUtil" "-Djogl.debug.GLSLCode" "-Djogl.debug.GLMediaPlayer" REM set D_ARGS="-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" "-Djogl.debug.GLSLCode" REM set D_ARGS="-Djogl.debug.ExtensionAvailabilityCache" "-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.ProcAddressHelper=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.NativeLibrary=true" @@ -33,7 +40,6 @@ REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLC REM set D_ARGS="-Dnewt.debug.Window" REM set D_ARGS="-Djogl.debug.GLDebugMessageHandler" "-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL" REM set D_ARGS="-Djogl.debug.DebugGL" "-Djogl.debug.GLDebugMessageHandler" "-Djogl.debug.GLSLCode" -REM set D_ARGS="-Djogl.debug.GraphicsConfiguration" "-Djogl.debug.CapabilitiesChooser" REM set D_ARGS="-Djogl.debug.GLContext" "-Dnewt.debug=all" REM set D_ARGS="-Dnewt.debug.Window" "-Dnativewindow.debug.TraceLock" REM set D_ARGS="-Dnativewindow.debug.TraceLock" diff --git a/make/scripts/java-win64.bat b/make/scripts/java-win64.bat index b8f438aab..2c09feedc 100755 --- a/make/scripts/java-win64.bat +++ b/make/scripts/java-win64.bat @@ -4,7 +4,8 @@ set J2RE_HOME=c:\jre1.6.0_30_x64 set JAVA_HOME=c:\jdk1.6.0_30_x64 set ANT_PATH=C:\apache-ant-1.8.2 -set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;c:\mingw\bin;%PATH% +REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;c:\mingw\bin;%PATH% +set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\external\PVRVFrame\OGLES-2.0\Windows_x86_64;%PATH% set BLD_DIR=..\%BLD_SUB% REM set LIB_DIR=%BLD_DIR%\lib;..\..\gluegen\%BLD_SUB%\obj diff --git a/make/scripts/tests-x32.bat b/make/scripts/tests-x32.bat index c29dcef39..7947759a4 100755 --- a/make/scripts/tests-x32.bat +++ b/make/scripts/tests-x32.bat @@ -51,7 +51,7 @@ REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode0 REM scripts\java-win32.bat com.jogamp.opengl.test.junit.newt.ManualScreenMode03NEWT REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple %* -scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube %* +REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube %* REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.TexCubeES2 %* REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle01NEWT @@ -94,6 +94,7 @@ REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMe REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.acore.TestMapBuffer01NEWT REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01 +scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT %* REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.glsl.TestFBOMRTNEWT01 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %* diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat index 32729d235..0b3711784 100755 --- a/make/scripts/tests-x64.bat +++ b/make/scripts/tests-x64.bat @@ -72,7 +72,7 @@ REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingPr REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT01GLn %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT02GLn %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTAWT01GLn %* -scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn %* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT -time 5000 @@ -96,7 +96,8 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMe REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestMapBuffer01NEWT REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01 -REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.glsl.TestFBOMRTNEWT01 +scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestFBOMRTNEWT01 %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %* diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 0258187fd..591f5f9d2 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -53,10 +53,17 @@ function jrun() { swton=$1 shift + #D_ARGS="-Djogl.debug.FBObject -Djogl.debug.DebugGL" + #D_ARGS="-Djogl.debug.FBObject" + #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.FBObject" #D_ARGS="-Djogl.debug.GLContext.NoProfileAliasing" #D_ARGS="-Djogamp.debug=all -Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all" + #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all -Djogamp.debug.Lock" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all" + #D_ARGS="-Djogl.debug.EGLDrawableFactory.DontQuery -Djogl.debug.GLDrawable" + #D_ARGS="-Djogl.debug.EGLDrawableFactory.QueryNativeTK -Djogl.debug.GLDrawable" + #D_ARGS="-Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug=all -Dnewt.debug=all" #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.TraceGL" #D_ARGS="-Djogl.debug.GLDebugMessageHandler" @@ -71,6 +78,7 @@ function jrun() { #D_ARGS="-Djogamp.debug.IOUtil -Djogl.debug.GLSLCode -Djogl.debug.GLMediaPlayer" #D_ARGS="-Djogl.debug.GLArrayData" #D_ARGS="-Djogl.debug.EGL -Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable" + #D_ARGS="-Djogl.debug.GLDrawable" #D_ARGS="-Dnewt.test.Screen.disableScreenMode -Dnewt.debug.Screen" #D_ARGS="-Djogl.debug.ExtensionAvailabilityCache -Djogl.debug=all -Dnativewindow.debug=all -Djogamp.debug.ProcAddressHelper=true -Djogamp.debug.NativeLibrary=true -Djogamp.debug.NativeLibrary.Lookup=true" #D_ARGS="-Dnewt.debug.MainThread" @@ -85,7 +93,7 @@ function jrun() { #D_ARGS="-Dnativewindow.debug.NativeWindow" #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT" #D_ARGS="-Dnewt.debug.EDT -Dnewt.debug.Window -Djogl.debug.GLContext" - #D_ARGS="-Dnativewindow.debug.ToolkitLock.TraceLock -Dnativewindow.debug.X11Util.XErrorStackDump -Dnativewindow.debug.X11Util.TraceDisplayLifecycle -Dnativewindow.debug.X11Util" + #D_ARGS="-Dnativewindow.debug.X11Util.XErrorStackDump -Dnativewindow.debug.X11Util.TraceDisplayLifecycle -Dnativewindow.debug.X11Util" #D_ARGS="-Dnativewindow.debug.X11Util -Djogl.debug.GLContext -Djogl.debug.GLDrawable -Dnewt.debug=all" #D_ARGS="-Dnativewindow.debug.X11Util -Dnativewindow.debug.X11Util.XSync" #D_ARGS="-Dnativewindow.debug.X11Util.XSync -Dnewt.debug.Window" @@ -100,9 +108,9 @@ function jrun() { #D_ARGS="-Djogl.debug.Animator -Dnewt.debug=all" #D_ARGS="-Dnewt.debug.EDT -Dnewt.debug.Display -Dnativewindow.debug.X11Util -Djogl.debug.GLDrawable -Djogl.debug.GLCanvas" #D_ARGS="-Djogl.debug.GLContext" - #D_ARGS="-Djogl.debug.GraphicsConfiguration -Djogl.debug.CapabilitiesChooser" + #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.CapabilitiesChooser" #D_ARGS="-Dnewt.debug.Screen -Dnewt.debug.EDT -Djogamp.debug.Lock" - #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GraphicsConfiguration" + #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.GraphicsConfiguration" #D_ARGS="-Dnewt.debug.EDT" #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT -Djogl.debug.GLContext" #D_ARGS="-Dnewt.debug.Window -Djogl.debug.Animator -Dnewt.debug.Screen" @@ -115,8 +123,6 @@ function jrun() { #D_ARGS="-Xprof" #D_ARGS="-Djogl.debug.Animator" #D_ARGS="-Dnativewindow.debug=all" - #D_ARGS="-Djogl.debug.GraphicsConfiguration" - #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.GraphicsConfiguration" #D_ARGS="-Djogl.debug.GLCanvas" #D_ARGS="-Dnativewindow.debug.ToolkitLock.TraceLock" #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLCode -Djogl.debug.TraceGL" @@ -162,20 +168,20 @@ function jrun() { C_ARG="com.jogamp.newt.util.MainThread" fi fi + #export LD_LIBRARY_PATH=$spath/../lib/external/PVRVFrame/OGLES-2.0/Linux_x86_64:$LD_LIBRARY_PATH + #export LD_LIBRARY_PATH=$spath/../lib/external/PVRVFrame/OGLES-2.0/Linux_x86_32:$LD_LIBRARY_PATH + #export LD_LIBRARY_PATH=/usr/local/projects/Xorg.modular/build-x86_64/lib:$LD_LIBRARY_PATH + #export LD_LIBRARY_PATH=/opt-linux-x86_64/x11lib-1.3:$LD_LIBRARY_PATH + #export LD_LIBRARY_PATH=/opt-linux-x86_64/mesa-7.8.1/lib64:$LD_LIBRARY_PATH + #export LD_LIBRARY_PATH=/usr/lib/mesa:/usr/lib32/mesa:$LD_LIBRARY_PATH + #export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/mesa:/usr/lib/i386-linux-gnu/mesa:$LD_LIBRARY_PATH echo echo "Test Start: $*" echo echo LD_LIBRARY_PATH $LD_LIBRARY_PATH echo echo $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $* - #LD_LIBRARY_PATH=/usr/local/projects/Xorg.modular/build-x86_64/lib:$LD_LIBRARY_PATH \ - #LD_LIBRARY_PATH=/opt-linux-x86_64/x11lib-1.3:$LD_LIBRARY_PATH \ - #LD_LIBRARY_PATH=/opt-linux-x86_64/mesa-7.8.1/lib64:$LD_LIBRARY_PATH \ #LIBGL_DRIVERS_PATH=/usr/lib/mesa:/usr/lib32/mesa \ - #LD_LIBRARY_PATH=/usr/lib/mesa:/usr/lib32/mesa:$LD_LIBRARY_PATH \ - #LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/mesa:/usr/lib/i386-linux-gnu/mesa:$LD_LIBRARY_PATH \ - #LD_LIBRARY_PATH=$spath/../lib/PVRVFrame/OGLES-2.0/Linux_x86_64:$LD_LIBRARY_PATH \ - #LD_LIBRARY_PATH=$spath/../lib/PVRVFrame/OGLES-2.0/Linux_x86_32:$LD_LIBRARY_PATH \ #gdb --args $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $* $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $* echo @@ -228,6 +234,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT2 $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT $* @@ -292,7 +299,7 @@ function testawtswt() { # swt (testswt) # #testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTEclipseGLCanvas01GLn $* -testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* +#testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* #testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* #testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor02GLn $* @@ -322,7 +329,8 @@ testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestTranslucentParentingAWT $* #testawt com.jogamp.opengl.test.junit.newt.TestCloseNewtAWT #testawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES2NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.caps.TestTranslucencyAWT $* #testawt com.jogamp.opengl.test.junit.jogl.caps.TestTranslucencyNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.glsl.TestShaderCompilationBug459AWT @@ -358,7 +366,9 @@ testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* #testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01 $* -#testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestFBOMRTNEWT01 $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMRTNEWT01 $* +testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMix2DemosES2NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT $* # # Graph @@ -394,6 +404,7 @@ testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* #testawt com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot $* #linux: +#testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES2NEWT $* # linux NV: cannot make ctx current .. # osx: #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* diff --git a/make/stub_includes/opengl/macosx-window-system.h b/make/stub_includes/opengl/macosx-window-system.h index e7fe13553..47b51a509 100644 --- a/make/stub_includes/opengl/macosx-window-system.h +++ b/make/stub_includes/opengl/macosx-window-system.h @@ -31,7 +31,7 @@ NSView* getNSView(NSOpenGLContext* ctx); NSOpenGLContext* createContext(NSOpenGLContext* shareContext, NSView* nsView, - Bool isBackingLayerView, + Bool allowIncompleteView, NSOpenGLPixelFormat* pixelFormat, Bool opaque, int* viewNotReady); diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java index 87a734e1f..482d35cae 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java @@ -293,9 +293,9 @@ public class BuildStaticGLInfo { output.println(" public static String getFunctionAssociation(String glFunctionName)"); output.println(" {"); output.println(" String mappedName = null;"); - output.println(" int funcNamePermNum = com.jogamp.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutationNumber(glFunctionName);"); + output.println(" int funcNamePermNum = com.jogamp.gluegen.runtime.opengl.GLNameResolver.getFuncNamePermutationNumber(glFunctionName);"); output.println(" for(int i = 0; null==mappedName && i < funcNamePermNum; i++) {"); - output.println(" String tmp = com.jogamp.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutation(glFunctionName, i);"); + output.println(" String tmp = com.jogamp.gluegen.runtime.opengl.GLNameResolver.getFuncNamePermutation(glFunctionName, i);"); output.println(" try {"); output.println(" mappedName = (String)funcToAssocMap.get(tmp);"); output.println(" } catch (Exception e) { }"); diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java b/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java index c1a4facd2..ba025e18c 100755 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java @@ -43,7 +43,7 @@ import com.jogamp.gluegen.GlueEmitterControls; import com.jogamp.gluegen.GlueGen; import com.jogamp.gluegen.MethodBinding; import com.jogamp.gluegen.procaddress.ProcAddressConfiguration; -import com.jogamp.gluegen.runtime.opengl.GLExtensionNames; +import com.jogamp.gluegen.runtime.opengl.GLNameResolver; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -224,11 +224,11 @@ public class GLConfiguration extends ProcAddressConfiguration { } } } - boolean isGLEnum = GLExtensionNames.isGLEnumeration(symbol); - boolean isGLFunc = GLExtensionNames.isGLFunction(symbol); + boolean isGLEnum = GLNameResolver.isGLEnumeration(symbol); + boolean isGLFunc = GLNameResolver.isGLFunction(symbol); if (isGLFunc || isGLEnum) { - if (GLExtensionNames.isExtensionVEN(symbol, isGLFunc)) { - String extSuffix = GLExtensionNames.getExtensionSuffix(symbol, isGLFunc); + if (GLNameResolver.isExtensionVEN(symbol, isGLFunc)) { + String extSuffix = GLNameResolver.getExtensionSuffix(symbol, isGLFunc); if (getDropUniqVendorExtensions(extSuffix)) { if (DEBUG_IGNORES) { System.err.println("Ignore UniqVendorEXT: " + symbol + ", vendor " + extSuffix); diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java b/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java index f4658ad7b..809c6783d 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java @@ -51,7 +51,7 @@ import com.jogamp.gluegen.SymbolFilter; import com.jogamp.gluegen.cgram.types.FunctionSymbol; import com.jogamp.gluegen.procaddress.ProcAddressEmitter; import com.jogamp.gluegen.procaddress.ProcAddressJavaMethodBindingEmitter; -import com.jogamp.gluegen.runtime.opengl.GLExtensionNames; +import com.jogamp.gluegen.runtime.opengl.GLNameResolver; import java.io.IOException; import java.io.PrintWriter; @@ -110,13 +110,13 @@ public class GLEmitter extends ProcAddressEmitter { if (declarations != null) { for (Iterator iterator = declarations.iterator(); iterator.hasNext();) { String decl = iterator.next(); - boolean isGLFunction = GLExtensionNames.isGLFunction(decl); + boolean isGLFunction = GLNameResolver.isGLFunction(decl); boolean isGLEnumeration = false; if (!isGLFunction) { - isGLEnumeration = GLExtensionNames.isGLEnumeration(decl); + isGLEnumeration = GLNameResolver.isGLEnumeration(decl); } if (isGLFunction || isGLEnumeration) { - String renamed = GLExtensionNames.normalize(decl, isGLFunction); + String renamed = GLNameResolver.normalize(decl, isGLFunction); if (!renamed.equals(decl)) { config.addJavaSymbolRename(decl, renamed); } @@ -181,7 +181,7 @@ public class GLEmitter extends ProcAddressEmitter { String cause = null; for (String decl : declarations) { boolean isFunc = !decl.startsWith("GL_"); - if (!GLExtensionNames.isExtension(decl, isFunc)) { + if (!GLNameResolver.isExtension(decl, isFunc)) { isExtension = false; break; } @@ -199,7 +199,7 @@ public class GLEmitter extends ProcAddressEmitter { } } cause = decl; - String unifiedName = GLExtensionNames.normalize(decl, isFunc); + String unifiedName = GLNameResolver.normalize(decl, isFunc); // NOTE that we look up the unified name in the // BuildStaticGLInfo's notion of the APIs -- since // we might not be emitting glue code for the @@ -472,12 +472,12 @@ public class GLEmitter extends ProcAddressEmitter { w.println(" * it was statically linked."); w.println(" */"); w.println(" public long getAddressFor(String functionNameUsr) {"); - w.println(" String functionNameBase = "+GLExtensionNames.class.getName()+".normalizeVEN(com.jogamp.gluegen.runtime.opengl.GLExtensionNames.normalizeARB(functionNameUsr, true), true);"); + w.println(" String functionNameBase = "+GLNameResolver.class.getName()+".normalizeVEN(com.jogamp.gluegen.runtime.opengl.GLNameResolver.normalizeARB(functionNameUsr, true), true);"); w.println(" String addressFieldNameBase = PROCADDRESS_VAR_PREFIX + functionNameBase;"); w.println(" java.lang.reflect.Field addressField = null;"); - w.println(" int funcNamePermNum = "+GLExtensionNames.class.getName()+".getFuncNamePermutationNumber(functionNameBase);"); + w.println(" int funcNamePermNum = "+GLNameResolver.class.getName()+".getFuncNamePermutationNumber(functionNameBase);"); w.println(" for(int i = 0; null==addressField && i < funcNamePermNum; i++) {"); - w.println(" String addressFieldName = "+GLExtensionNames.class.getName()+".getFuncNamePermutation(addressFieldNameBase, i);"); + w.println(" String addressFieldName = "+GLNameResolver.class.getName()+".getFuncNamePermutation(addressFieldNameBase, i);"); w.println(" try {"); w.println(" addressField = getClass().getField(addressFieldName);"); w.println(" } catch (Exception e) { }"); diff --git a/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLExtensionNames.java b/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLExtensionNames.java deleted file mode 100644 index 426333034..000000000 --- a/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLExtensionNames.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (c) 2003-2005 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. - * - */ -package com.jogamp.gluegen.runtime.opengl; - -public class GLExtensionNames { - //GL_XYZ : GL_XYZ, GL_XYZ_GL2, GL_XYZ_ARB, GL_XYZ_OES, GL_XYZ_OML - //GL_XYZ : GL_XYZ, GL_GL2_XYZ, GL_ARB_XYZ, GL_OES_XYZ, GL_OML_XYZ - // - // Pass-1 Unify ARB extensions with the same value - // Pass-2 Unify vendor extensions, - // if exist as an ARB extension with the same value. - // Pass-3 Emit - - public static final String[] extensionsARB = { "ARB", "GL2", "OES", "KHR", "OML" }; - public static final String[] extensionsVEN = { "3DFX", - "AMD", - "ANGLE", - "ARM", - "APPLE", - "ATI", - "EXT", - "HI", - "HP", - "IBM", - "IMG", - "MESA", - "MESAX", - "NV", - "QCOM", - "SGI", - "SGIS", - "SGIX", - "SUN", - "VIV", - "WIN" - }; - - - public static final boolean isGLFunction(String str) { - return str.startsWith("gl") || /* str.startsWith("glu") || str.startsWith("glX") || */ - str.startsWith("egl") || str.startsWith("wgl") || str.startsWith("agl") || - str.startsWith("cgl") ; - } - - public static final boolean isGLEnumeration(String str) { - return str.startsWith("GL_") || str.startsWith("GLU_") || str.startsWith("GLX_") || - str.startsWith("EGL_") || str.startsWith("WGL_") || str.startsWith("AGL_") || - str.startsWith("CGL_") ; - } - - public static final int getExtensionIdx(String[] extensions, String str, boolean isGLFunc) { - if(isGLFunc) { - for(int i = extensions.length - 1 ; i>=0 ; i--) { - if( str.endsWith(extensions[i]) ) { - return i; - } - } - } else { - for(int i = extensions.length - 1 ; i>=0 ; i--) { - if( str.endsWith("_"+extensions[i]) ) { - return i; - } - } - } - return -1; - } - - public static final boolean isExtension(String[] extensions, String str, boolean isGLFunc) { - return getExtensionIdx(extensions, str, isGLFunc)>=0; - } - - public static final String getExtensionSuffix(String str, boolean isGLFunc) { - int idx = getExtensionIdx(extensionsARB, str, isGLFunc); - if(idx>=0) { - return extensionsARB[idx]; - } - idx = getExtensionIdx(extensionsVEN, str, isGLFunc); - if(idx>=0) { - return extensionsVEN[idx]; - } - return null; - } - - public static final String normalize(String[] extensions, String str, boolean isGLFunc) { - boolean touched = false; - for(int i = extensions.length - 1 ; !touched && i>=0 ; i--) { - if(isGLFunc) { - if(str.endsWith(extensions[i])) { - // functions - str = str.substring(0, str.length()-extensions[i].length()); - touched=true; - } - } else { - if(str.endsWith("_"+extensions[i])) { - // enums - str = str.substring(0, str.length()-1-extensions[i].length()); - touched=true; - } - } - } - return str; - } - public static final String normalizeARB(String str, boolean isGLFunc) { - return normalize(extensionsARB, str, isGLFunc); - } - public static final boolean isExtensionARB(String str, boolean isGLFunc) { - return isExtension(extensionsARB, str, isGLFunc); - } - public static final String normalizeVEN(String str, boolean isGLFunc) { - return normalize(extensionsVEN, str, isGLFunc); - } - public static final boolean isExtensionVEN(String str, boolean isGLFunc) { - return isExtension(extensionsVEN, str, isGLFunc); - } - public static final String normalize(String str, boolean isGLFunc) { - if (isExtensionARB(str, isGLFunc)) { - return normalizeARB(str, isGLFunc); - } - if (isExtensionVEN(str, isGLFunc)) { - return normalizeVEN(str, isGLFunc); - } - return str; - } - public static final boolean isExtension(String str, boolean isGLFunc) { - return isExtension(extensionsARB, str, isGLFunc) || - isExtension(extensionsVEN, str, isGLFunc); - } - - public static final int getFuncNamePermutationNumber(String name) { - if(isExtensionARB(name, true) || isExtensionVEN(name, true)) { - // no name permutation, if it's already a known extension - return 1; - } - return 1 + extensionsARB.length + extensionsVEN.length; - } - - public static final String getFuncNamePermutation(String name, int i) { - // identity - if(i==0) { - return name; - } - if(0>i || i>=(1+extensionsARB.length + extensionsVEN.length)) { - throw new RuntimeException("Index out of range [0.."+(1+extensionsARB.length+extensionsVEN.length-1)+"]: "+i); - } - // ARB - i-=1; - if(i=0 ; i--) { + if( str.endsWith(extensions[i]) ) { + return i; + } + } + } else { + for(int i = extensions.length - 1 ; i>=0 ; i--) { + if( str.endsWith("_"+extensions[i]) ) { + return i; + } + } + } + return -1; + } + + public static final boolean isExtension(String[] extensions, String str, boolean isGLFunc) { + return getExtensionIdx(extensions, str, isGLFunc)>=0; + } + + public static final String getExtensionSuffix(String str, boolean isGLFunc) { + int idx = getExtensionIdx(extensionsARB, str, isGLFunc); + if(idx>=0) { + return extensionsARB[idx]; + } + idx = getExtensionIdx(extensionsVEN, str, isGLFunc); + if(idx>=0) { + return extensionsVEN[idx]; + } + return null; + } + + public static final String normalize(String[] extensions, String str, boolean isGLFunc) { + boolean touched = false; + for(int i = extensions.length - 1 ; !touched && i>=0 ; i--) { + if(isGLFunc) { + if(str.endsWith(extensions[i])) { + // functions + str = str.substring(0, str.length()-extensions[i].length()); + touched=true; + } + } else { + if(str.endsWith("_"+extensions[i])) { + // enums + str = str.substring(0, str.length()-1-extensions[i].length()); + touched=true; + } + } + } + return str; + } + public static final String normalizeARB(String str, boolean isGLFunc) { + return normalize(extensionsARB, str, isGLFunc); + } + public static final boolean isExtensionARB(String str, boolean isGLFunc) { + return isExtension(extensionsARB, str, isGLFunc); + } + public static final String normalizeVEN(String str, boolean isGLFunc) { + return normalize(extensionsVEN, str, isGLFunc); + } + public static final boolean isExtensionVEN(String str, boolean isGLFunc) { + return isExtension(extensionsVEN, str, isGLFunc); + } + public static final String normalize(String str, boolean isGLFunc) { + if (isExtensionARB(str, isGLFunc)) { + return normalizeARB(str, isGLFunc); + } + if (isExtensionVEN(str, isGLFunc)) { + return normalizeVEN(str, isGLFunc); + } + return str; + } + public static final boolean isExtension(String str, boolean isGLFunc) { + return isExtension(extensionsARB, str, isGLFunc) || + isExtension(extensionsVEN, str, isGLFunc); + } + + public static final int getFuncNamePermutationNumber(String name) { + if(isExtensionARB(name, true) || isExtensionVEN(name, true)) { + // no name permutation, if it's already a known extension + return 1; + } + return 1 + extensionsARB.length + extensionsVEN.length; + } + + public static final String getFuncNamePermutation(String name, int i) { + // identity + if(i==0) { + return name; + } + if(0>i || i>=(1+extensionsARB.length + extensionsVEN.length)) { + throw new RuntimeException("Index out of range [0.."+(1+extensionsARB.length+extensionsVEN.length-1)+"]: "+i); + } + // ARB + i-=1; + if(i + * Supports on-the-fly reconfiguration of dimension and multisample buffers via {@link #reset(GL, int, int, int)} + * while preserving the {@link Attachment} references. + *

+ *

+ * Integrates default read/write framebuffers via {@link GLContext#getDefaultReadFramebuffer()} and {@link GLContext#getDefaultReadFramebuffer()}, + * which is being hooked at {@link GL#glBindFramebuffer(int, int)} when the default (zero) framebuffer is selected. + *

+ * + *

FIXME: Implement support for {@link Type#DEPTH_TEXTURE}, {@link Type#STENCIL_TEXTURE} .

+ */ +public class FBObject { + protected static final boolean DEBUG = Debug.debug("FBObject"); + + /** + * Returns true if basic FBO support is available, otherwise false. + *

+ * Basic FBO is supported if the context is either GL-ES >= 2.0, GL >= core 3.0 or implements the extensions + * ARB_ES2_compatibility, ARB_framebuffer_object, EXT_framebuffer_object or OES_framebuffer_object. + *

+ *

+ * Basic FBO support may only include one color attachment and no multisampling, + * as well as limited internal formats for renderbuffer. + *

+ * @see GLContext#hasFBO() + */ + public static final boolean supportsBasicFBO(GL gl) { + return gl.getContext().hasFBO(); + } + + /** + * Returns true if full FBO support is available, otherwise false. + *

+ * Full FBO is supported if the context is either GL >= core 3.0 or implements the extensions + * ARB_framebuffer_object, or all of + * EXT_framebuffer_object, EXT_framebuffer_multisample, + * EXT_framebuffer_blit, GL_EXT_packed_depth_stencil. + *

+ *

+ * Full FBO support includes multiple color attachments and multisampling. + *

+ */ + public static final boolean supportsFullFBO(GL gl) { + return gl.isGL3() || // GL >= 3.0 + + gl.isExtensionAvailable(GLExtensions.ARB_framebuffer_object) || // ARB_framebuffer_object + + ( gl.isExtensionAvailable(GLExtensions.EXT_framebuffer_object) && // All EXT_framebuffer_object* + gl.isExtensionAvailable(GLExtensions.EXT_framebuffer_multisample) && + gl.isExtensionAvailable(GLExtensions.EXT_framebuffer_blit) && + gl.isExtensionAvailable(GLExtensions.EXT_packed_depth_stencil) ) ; + } + + public static final int getMaxSamples(GL gl) { + if( supportsFullFBO(gl) ) { + int[] val = new int[] { 0 } ; + gl.glGetIntegerv(GL2GL3.GL_MAX_SAMPLES, val, 0); + return val[0]; + } else { + return 0; + } + } + + /** Common super class of all attachments */ + public static abstract class Attachment { + public enum Type { + NONE, DEPTH, STENCIL, DEPTH_STENCIL, COLOR, COLOR_TEXTURE, DEPTH_TEXTURE, STENCIL_TEXTURE; + + /** + * Returns {@link #COLOR}, {@link #DEPTH}, {@link #STENCIL} or {@link #DEPTH_STENCIL} + * @throws IllegalArgumentException if format cannot be handled. + */ + public static Type determine(int format) throws IllegalArgumentException { + switch(format) { + case GL.GL_RGBA4: + case GL.GL_RGB5_A1: + case GL.GL_RGB565: + case GL.GL_RGB8: + case GL.GL_RGBA8: + return Type.COLOR; + case GL.GL_DEPTH_COMPONENT16: + case GL.GL_DEPTH_COMPONENT24: + case GL.GL_DEPTH_COMPONENT32: + return Type.DEPTH; + case GL.GL_STENCIL_INDEX1: + case GL.GL_STENCIL_INDEX4: + case GL.GL_STENCIL_INDEX8: + return Type.STENCIL; + case GL.GL_DEPTH24_STENCIL8: + return Type.DEPTH_STENCIL; + default: + throw new IllegalArgumentException("format invalid: 0x"+Integer.toHexString(format)); + } + } + }; + + /** immutable type [{@link #COLOR}, {@link #DEPTH}, {@link #STENCIL}, {@link #COLOR_TEXTURE}, {@link #DEPTH_TEXTURE}, {@link #STENCIL_TEXTURE} ] */ + public final Type type; + + /** immutable the internal format */ + public final int format; + + private int width, height; + + private int name; + + /** true if resource is initialized by {@link #initialize(GL)}, hence {@link #free(GL)} is allowed to free the GL resources. */ + protected boolean resourceOwner; + + private int initCounter; + + protected Attachment(Type type, int iFormat, int width, int height, int name) { + this.type = type; + this.format = iFormat; + this.width = width; + this.height = height; + this.name = name; + this.resourceOwner = false; + this.initCounter = 0; + } + + /** width of attachment */ + public final int getWidth() { return width; } + /** height of attachment */ + public final int getHeight() { return height; } + /* pp */ final void setSize(int w, int h) { width = w; height = h; } + + /** buffer name [1..max], maybe a texture or renderbuffer name, depending on type. */ + public final int getName() { return name; } + /* pp */ final void setName(int n) { name = n; } + + public final int getInitCounter() { return initCounter; } + + /** + * Initializes the attachment buffer and set it's parameter, if uninitialized, i.e. name is zero. + *

Implementation employs an initialization counter, hence it can be paired recursively with {@link #free(GL)}.

+ * @throws GLException if buffer generation or setup fails. The just created buffer name will be deleted in this case. + */ + public void initialize(GL gl) throws GLException { + initCounter++; + /* + super.initialize(gl); + if(1 == getInitCounter() && 0 == getName() ) { + do init .. + freeResources = true; // if all OK + } + */ + } + + /** + * Releases the attachment buffer if initialized, i.e. name is zero. + *

Implementation employs an initialization counter, hence it can be paired recursively with {@link #initialize(GL)}.

+ * @throws GLException if buffer release fails. + */ + public void free(GL gl) throws GLException { + /* + if(1 == getInitCounter() && freeResources && .. ) { + do free .. + } + super.free(gl); + */ + initCounter--; + if(0 == initCounter) { + resourceOwner = false; + name = 0; + } + if(DEBUG) { + System.err.println("Attachment.free: "+this); + } + } + + /** + *

+ * Comparison by {@link #type}, {@link #format}, {@link #width}, {@link #height} and {@link #name}. + *

+ * {@inheritDoc} + */ + @Override + public boolean equals(Object o) { + if( this == o ) return true; + if( ! ( o instanceof Attachment ) ) return false; + final Attachment a = (Attachment)o; + return type == a.type && + format == a.format || + width == a.width || + height== a.height || + name == a.name ; + } + + /** + *

+ * Hashed by {@link #type}, {@link #format}, {@link #width}, {@link #height} and {@link #name}. + *

+ * {@inheritDoc} + */ + @Override + public int hashCode() { + // 31 * x == (x << 5) - x + int hash = 31 + type.ordinal(); + hash = ((hash << 5) - hash) + format; + hash = ((hash << 5) - hash) + width; + hash = ((hash << 5) - hash) + height; + hash = ((hash << 5) - hash) + name; + return hash; + } + + int objectHashCode() { return super.hashCode(); } + + public String toString() { + return getClass().getSimpleName()+"[type "+type+", format 0x"+Integer.toHexString(format)+", "+width+"x"+height+ + ", name 0x"+Integer.toHexString(name)+", obj 0x"+Integer.toHexString(objectHashCode())+ + ", resOwner "+resourceOwner+", initCount "+initCounter+"]"; + } + + public static Type getType(int attachmentPoint, int maxColorAttachments) { + if( GL.GL_COLOR_ATTACHMENT0 <= attachmentPoint && attachmentPoint < GL.GL_COLOR_ATTACHMENT0+maxColorAttachments ) { + return Type.COLOR; + } + switch(attachmentPoint) { + case GL.GL_DEPTH_ATTACHMENT: + return Type.DEPTH; + case GL.GL_STENCIL_ATTACHMENT: + return Type.STENCIL; + default: + throw new IllegalArgumentException("Invalid attachment point 0x"+Integer.toHexString(attachmentPoint)); + } + } + } + + /** Other renderbuffer attachment which maybe a colorbuffer, depth or stencil. */ + public static class RenderAttachment extends Attachment { + private int samples; + + /** + * @param type allowed types are {@link Type#DEPTH}, {@link Type#STENCIL} or {@link Type#COLOR} + * @param iFormat + * @param samples + * @param width + * @param height + * @param name + */ + public RenderAttachment(Type type, int iFormat, int samples, int width, int height, int name) { + super(validateType(type), iFormat, width, height, name); + this.samples = samples; + } + + /** number of samples, or zero for no multisampling */ + public final int getSamples() { return samples; } + /* pp */ final void setSamples(int s) { samples = s; } + + private static Type validateType(Type type) { + switch(type) { + case DEPTH: + case STENCIL: + case COLOR: + return type; + default: + throw new IllegalArgumentException("Invalid type: "+type); + } + } + + /** + *

+ * Comparison by {@link #type}, {@link #format}, {@link #samples}, {@link #width}, {@link #height} and {@link #name}. + *

+ * {@inheritDoc} + */ + @Override + public boolean equals(Object o) { + if( this == o ) return true; + if( ! ( o instanceof RenderAttachment ) ) return false; + return super.equals(o) && + samples == ((RenderAttachment)o).samples; + } + + /** + *

+ * Hashed by {@link #type}, {@link #format}, {@link #samples}, {@link #width}, {@link #height} and {@link #name}. + *

+ * {@inheritDoc} + */ + @Override + public int hashCode() { + // 31 * x == (x << 5) - x + int hash = super.hashCode(); + hash = ((hash << 5) - hash) + samples; + return hash; + } + + @Override + public void initialize(GL gl) throws GLException { + super.initialize(gl); + if( 1 == getInitCounter() && 0 == getName() ) { + final int[] name = new int[] { -1 }; + gl.glGenRenderbuffers(1, name, 0); + if( 0 == name[0] ) { + throw new GLException("null renderbuffer, "+this); + } + setName(name[0]); + + gl.glBindRenderbuffer(GL.GL_RENDERBUFFER, getName()); + if( samples > 0 ) { + ((GL2GL3)gl).glRenderbufferStorageMultisample(GL.GL_RENDERBUFFER, samples, format, getWidth(), getHeight()); + } else { + gl.glRenderbufferStorage(GL.GL_RENDERBUFFER, format, getWidth(), getHeight()); + } + int glerr = gl.glGetError(); + if(GL.GL_NO_ERROR != glerr) { + gl.glDeleteRenderbuffers(1, name, 0); + setName(0); + throw new GLException("GL Error 0x"+Integer.toHexString(glerr)+" while creating "+this); + } + resourceOwner = true; + if(DEBUG) { + System.err.println("Attachment.init: "+this); + } + } + } + + @Override + public void free(GL gl) { + if(1 == getInitCounter() && resourceOwner && 0 != getName() ) { + final int[] name = new int[] { getName() }; + gl.glDeleteRenderbuffers(1, name, 0); + } + super.free(gl); + } + + public String toString() { + return getClass().getSimpleName()+"[type "+type+", format 0x"+Integer.toHexString(format)+", samples "+samples+", "+getWidth()+"x"+getHeight()+ + ", name 0x"+Integer.toHexString(getName())+", obj 0x"+Integer.toHexString(objectHashCode())+ + ", resOwner "+resourceOwner+", initCount "+getInitCounter()+"]"; + } + } + + /** + * Marker interface, denotes a color buffer attachment. + *

Always an instance of {@link Attachment}.

+ *

Either an instance of {@link ColorAttachment} or {@link TextureAttachment}. + */ + public static interface Colorbuffer { + } + + /** Color render buffer attachment */ + public static class ColorAttachment extends RenderAttachment implements Colorbuffer { + public ColorAttachment(int iFormat, int samples, int width, int height, int name) { + super(Type.COLOR, iFormat, samples, width, height, name); + } + } + + /** Texture attachment */ + public static class TextureAttachment extends Attachment implements Colorbuffer { + /** details of the texture setup */ + public final int dataFormat, dataType, magFilter, minFilter, wrapS, wrapT; + + /** + * @param type allowed types are [ {@link Type#COLOR_TEXTURE}, {@link Type#DEPTH_TEXTURE}, {@link Type#STENCIL_TEXTURE} ] + * @param iFormat + * @param width + * @param height + * @param dataFormat + * @param dataType + * @param magFilter + * @param minFilter + * @param wrapS + * @param wrapT + * @param name + */ + public TextureAttachment(Type type, int iFormat, int width, int height, int dataFormat, int dataType, + int magFilter, int minFilter, int wrapS, int wrapT, int name) { + super(validateType(type), iFormat, width, height, name); + this.dataFormat = dataFormat; + this.dataType = dataType; + this.magFilter = magFilter; + this.minFilter = minFilter; + this.wrapS = wrapS; + this.wrapT = wrapT; + } + + private static Type validateType(Type type) { + switch(type) { + case COLOR_TEXTURE: + case DEPTH_TEXTURE: + case STENCIL_TEXTURE: + return type; + default: + throw new IllegalArgumentException("Invalid type: "+type); + } + } + + /** + * Initializes the texture and set it's parameter, if uninitialized, i.e. name is zero. + * @throws GLException if texture generation and setup fails. The just created texture name will be deleted in this case. + */ + @Override + public void initialize(GL gl) throws GLException { + super.initialize(gl); + if( 1 == getInitCounter() && 0 == getName() ) { + final int[] name = new int[] { -1 }; + gl.glGenTextures(1, name, 0); + if(0 == name[0]) { + throw new GLException("null texture, "+this); + } + setName(name[0]); + + gl.glBindTexture(GL.GL_TEXTURE_2D, name[0]); + gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, format, getWidth(), getHeight(), 0, dataFormat, dataType, null); + if( 0 < magFilter ) { + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, magFilter); + } + if( 0 < minFilter ) { + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, minFilter); + } + if( 0 < wrapS ) { + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, wrapS); + } + if( 0 < wrapT ) { + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, wrapT); + } + int glerr = gl.glGetError(); + if(GL.GL_NO_ERROR != glerr) { + gl.glDeleteTextures(1, name, 0); + setName(0); + throw new GLException("GL Error 0x"+Integer.toHexString(glerr)+" while creating "+this); + } + resourceOwner = true; + } + if(DEBUG) { + System.err.println("Attachment.init: "+this); + } + } + + @Override + public void free(GL gl) { + if(1 == getInitCounter() && resourceOwner && 0 != getName() ) { + final int[] name = new int[] { getName() }; + gl.glDeleteTextures(1, name, 0); + } + super.free(gl); + } + } + + private boolean initialized; + private boolean basicFBOSupport; + private boolean fullFBOSupport; + private boolean rgba8Avail; + private boolean depth24Avail; + private boolean depth32Avail; + private boolean stencil01Avail; + private boolean stencil04Avail; + private boolean stencil08Avail; + private boolean stencil16Avail; + private boolean packedDepthStencilAvail; + private int maxColorAttachments, maxSamples, maxTextureSize, maxRenderbufferSize; + + private int width, height, samples; + private int vStatus; + private int fbName; + private boolean bound; + + private int colorAttachmentCount; + private Colorbuffer[] colorAttachmentPoints; // colorbuffer attachment points + private RenderAttachment depth, stencil; // depth and stencil maybe equal in case of packed-depth-stencil + + private final FBObject samplesSink; // MSAA sink + private TextureAttachment samplesSinkTexture; + private boolean samplesSinkDirty; + + // + // ColorAttachment helper .. + // + + private final void validateColorAttachmentPointRange(int point) { + if(maxColorAttachments != colorAttachmentPoints.length) { + throw new InternalError("maxColorAttachments "+maxColorAttachments+", array.lenght "+colorAttachmentPoints); + } + if(0 > point || point >= maxColorAttachments) { + throw new IllegalArgumentException("attachment point out of range: "+point+", should be within [0.."+(maxColorAttachments-1)+"]"); + } + } + + private final void validateAddColorAttachment(int point, Colorbuffer ca) { + validateColorAttachmentPointRange(point); + if( null != colorAttachmentPoints[point] ) { + throw new IllegalArgumentException("Cannot attach "+ca+", attachment point already in use by "+colorAttachmentPoints[point]); + } + } + + private final void addColorAttachment(int point, Colorbuffer ca) { + validateColorAttachmentPointRange(point); + final Colorbuffer c = colorAttachmentPoints[point]; + if( null != c && c != ca ) { + throw new IllegalArgumentException("Add failed: requested to add "+ca+" at "+point+", but slot is holding "+c+"; "+this); + } + colorAttachmentPoints[point] = ca; + colorAttachmentCount++; + } + + private final void removeColorAttachment(int point, Colorbuffer ca) { + validateColorAttachmentPointRange(point); + final Colorbuffer c = colorAttachmentPoints[point]; + if( null != c && c != ca ) { + throw new IllegalArgumentException("Remove failed: requested to removed "+ca+" at "+point+", but slot is holding "+c+"; "+this); + } + colorAttachmentPoints[point] = null; + colorAttachmentCount--; + } + + /** + * Return the {@link Colorbuffer} attachment at attachmentPoint if it is attached to this FBO, otherwise null. + * + * @see #attachColorbuffer(GL, boolean) + * @see #attachColorbuffer(GL, boolean) + * @see #attachTexture2D(GL, int, boolean, int, int, int, int) + * @see #attachTexture2D(GL, int, int, int, int, int, int, int, int) + */ + public final Colorbuffer getColorbuffer(int attachmentPoint) { + validateColorAttachmentPointRange(attachmentPoint); + return colorAttachmentPoints[attachmentPoint]; + } + + /** + * Finds the passed {@link Colorbuffer} within the valid range of attachment points + * using reference comparison only. + *

+ * Note: Slow. Implementation uses a logN array search to save resources, i.e. not using a HashMap. + *

+ * @param ca the {@link Colorbuffer} to look for. + * @return -1 if the {@link Colorbuffer} could not be found, otherwise [0..{@link #getMaxColorAttachments()}-1] + */ + public final int getColorbufferAttachmentPoint(Colorbuffer ca) { + for(int i=0; ireference only. + * + *

+ * Note: Slow. Uses {@link #getColorbufferAttachmentPoint(Colorbuffer)} to determine it's attachment point + * to be used for {@link #getColorbuffer(int)} + *

+ * + * @see #attachColorbuffer(GL, boolean) + * @see #attachColorbuffer(GL, boolean) + * @see #attachTexture2D(GL, int, boolean, int, int, int, int) + * @see #attachTexture2D(GL, int, int, int, int, int, int, int, int) + */ + public final Colorbuffer getColorbuffer(Colorbuffer ca) { + final int p = getColorbufferAttachmentPoint(ca); + return p>=0 ? getColorbuffer(p) : null; + } + + /** + * Creates an uninitialized FBObject instance. + *

+ * Call {@link #init(GL, int, int, int)} .. etc to use it. + *

+ */ + public FBObject() { + this(false); + } + /* pp */ FBObject(boolean isSampleSink) { + this.initialized = false; + + // TBD @ init + this.basicFBOSupport = false; + this.fullFBOSupport = false; + this.rgba8Avail = false; + this.depth24Avail = false; + this.depth32Avail = false; + this.stencil01Avail = false; + this.stencil04Avail = false; + this.stencil08Avail = false; + this.stencil16Avail = false; + this.packedDepthStencilAvail = false; + this.maxColorAttachments=-1; + this.maxSamples=-1; + this.maxTextureSize = 0; + this.maxRenderbufferSize = 0; + + this.width = 0; + this.height = 0; + this.samples = 0; + this.vStatus = -1; + this.fbName = 0; + this.bound = false; + + this.colorAttachmentPoints = null; // at init .. + this.colorAttachmentCount = 0; + this.depth = null; + this.stencil = null; + + this.samplesSink = isSampleSink ? null : new FBObject(true); + this.samplesSinkTexture = null; + this.samplesSinkDirty = true; + } + + private void init(GL gl, int width, int height, int samples) throws GLException { + if(initialized) { + throw new GLException("FBO already initialized"); + } + fullFBOSupport = supportsFullFBO(gl); + + if( !fullFBOSupport && !supportsBasicFBO(gl) ) { + throw new GLException("FBO not supported w/ context: "+gl.getContext()+", "+this); + } + + basicFBOSupport = true; + + rgba8Avail = gl.isGL2GL3() || gl.isExtensionAvailable(GLExtensions.OES_rgb8_rgba8); + depth24Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_depth24); + depth32Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_depth32); + stencil01Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_stencil1); + stencil04Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_stencil4); + stencil08Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_stencil8); + stencil16Avail = fullFBOSupport; + + packedDepthStencilAvail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_packed_depth_stencil); + + final boolean NV_fbo_color_attachments = gl.isExtensionAvailable(GLExtensions.NV_fbo_color_attachments); + + int val[] = new int[1]; + + int glerr = gl.glGetError(); + if(DEBUG && GL.GL_NO_ERROR != glerr) { + System.err.println("FBObject.init-preexisting.0 GL Error 0x"+Integer.toHexString(glerr)); + } + + int realMaxColorAttachments = 1; + maxColorAttachments = 1; + if( null != samplesSink && fullFBOSupport || NV_fbo_color_attachments ) { + try { + gl.glGetIntegerv(GL2GL3.GL_MAX_COLOR_ATTACHMENTS, val, 0); + glerr = gl.glGetError(); + if(GL.GL_NO_ERROR == glerr) { + realMaxColorAttachments = 1 <= val[0] ? val[0] : 1; // cap minimum to 1 + } else if(DEBUG) { + System.err.println("FBObject.init-GL_MAX_COLOR_ATTACHMENTS query GL Error 0x"+Integer.toHexString(glerr)); + } + } catch (GLException gle) {} + } + maxColorAttachments = realMaxColorAttachments <= 8 ? realMaxColorAttachments : 8; // cap to limit array size + + colorAttachmentPoints = new Colorbuffer[maxColorAttachments]; + colorAttachmentCount = 0; + + maxSamples = 0; + if(fullFBOSupport) { + gl.glGetIntegerv(GL2GL3.GL_MAX_SAMPLES, val, 0); + glerr = gl.glGetError(); + if(GL.GL_NO_ERROR == glerr) { + maxSamples = val[0]; + } else if(DEBUG) { + System.err.println("FBObject.init-GL_MAX_SAMPLES query GL Error 0x"+Integer.toHexString(glerr)); + } + } + gl.glGetIntegerv(GL.GL_MAX_TEXTURE_SIZE, val, 0); + maxTextureSize = val[0]; + gl.glGetIntegerv(GL.GL_MAX_RENDERBUFFER_SIZE, val, 0); + this.maxRenderbufferSize = val[0]; + + glerr = gl.glGetError(); + if(DEBUG && GL.GL_NO_ERROR != glerr) { + System.err.println("FBObject.init-preexisting.1 GL Error 0x"+Integer.toHexString(glerr)); + } + + this.width = width; + this.height = height; + this.samples = samples <= maxSamples ? samples : maxSamples; + + if(DEBUG) { + System.err.println("FBObject "+width+"x"+height+", "+samples+" -> "+samples+" samples"); + System.err.println("basicFBOSupport: "+basicFBOSupport); + System.err.println("fullFBOSupport: "+fullFBOSupport); + System.err.println("maxColorAttachments: "+maxColorAttachments+"/"+realMaxColorAttachments); + System.err.println("maxSamples: "+maxSamples); + System.err.println("maxTextureSize: "+maxTextureSize); + System.err.println("maxRenderbufferSize: "+maxRenderbufferSize); + System.err.println("rgba8: "+rgba8Avail); + System.err.println("depth24: "+depth24Avail); + System.err.println("depth32: "+depth32Avail); + System.err.println("stencil01: "+stencil01Avail); + System.err.println("stencil04: "+stencil04Avail); + System.err.println("stencil08: "+stencil08Avail); + System.err.println("stencil16: "+stencil16Avail); + System.err.println("packedDepthStencil: "+packedDepthStencilAvail); + System.err.println("NV_fbo_color_attachments: "+NV_fbo_color_attachments); + System.err.println(gl.getContext().getGLVersion()); + System.err.println(JoglVersion.getGLStrings(gl, null).toString()); + System.err.println(gl.getContext()); + } + + checkNoError(null, gl.glGetError(), "FBObject Init.pre"); // throws GLException if error + + if(width > 2 + maxTextureSize || height> 2 + maxTextureSize || + width > maxRenderbufferSize || height> maxRenderbufferSize ) { + throw new GLException("size "+width+"x"+height+" exceeds on of the maxima [texture "+maxTextureSize+", renderbuffer "+maxRenderbufferSize+"]"); + } + + if(null != samplesSink) { + // init sampling sink + samplesSink.reset(gl, width, height); + resetMSAATexture2DSink(gl); + } + + // generate fbo .. + gl.glGenFramebuffers(1, val, 0); + fbName = val[0]; + if(0 == fbName) { + throw new GLException("null framebuffer"); + } + + // bind fbo .. + gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, fbName); + checkNoError(gl, gl.glGetError(), "FBObject Init.bindFB"); // throws GLException if error + if(!gl.glIsFramebuffer(fbName)) { + checkNoError(gl, GL.GL_INVALID_VALUE, "FBObject Init.isFB"); // throws GLException + } + bound = true; + initialized = true; + + updateStatus(gl); + if(DEBUG) { + System.err.println("FBObject.init(): "+this); + } + } + + /** + * Initializes or resets this FBO's instance. + *

+ * In case the new parameters are compatible with the current ones + * no action will be performed. Otherwise all attachments will be recreated + * to match the new given parameters. + *

+ *

+ * Currently incompatibility and hence recreation is given if + * the size or sample count doesn't match for subsequent calls. + *

+ * + *

Leaves the FBO bound state untouched

+ * + * @param gl the current GL context + * @param newWidth + * @param newHeight + * @throws GLException in case of an error + */ + public final void reset(GL gl, int newWidth, int newHeight) { + reset(gl, newWidth, newHeight, 0); + } + + /** + * Initializes or resets this FBO's instance. + *

+ * In case the new parameters are compatible with the current ones + * no action will be performed. Otherwise all attachments will be recreated + * to match the new given parameters. + *

+ *

+ * Currently incompatibility and hence recreation is given if + * the size or sample count doesn't match for subsequent calls. + *

+ * + *

Leaves the FBO bound state untouched

+ * + * @param gl the current GL context + * @param newWidth + * @param newHeight + * @param newSamples if > 0, MSAA will be used, otherwise no multisampling. Will be capped to {@link #getMaxSamples()}. + * @throws GLException in case of an error + */ + public final void reset(GL gl, int newWidth, int newHeight, int newSamples) { + if(!initialized) { + init(gl, newWidth, newHeight, newSamples); + return; + } + newSamples = newSamples <= maxSamples ? newSamples : maxSamples; // clamp + + if( newWidth != width || newHeight != height || newSamples != samples ) { + if(DEBUG) { + System.err.println("FBObject.reset - START - "+this); + } + + final boolean wasBound = isBound(); + + width = newWidth; + height = newHeight; + samples = newSamples; + detachAllImpl(gl, true , true); + resetMSAATexture2DSink(gl); + + if(wasBound) { + bind(gl); + } else { + unbind(gl); + } + + if(DEBUG) { + System.err.println("FBObject.reset - END - "+this); + } + } + } + + /** + * Note that the status may reflect an incomplete state during transition of attachments. + * @return The FB status. {@link GL.GL_FRAMEBUFFER_COMPLETE} if ok, otherwise return GL FBO error state or -1 + * @see #validateStatus() + */ + public final int getStatus() { + return vStatus; + } + + /** return the {@link #getStatus()} as a string. */ + public final String getStatusString() { + return getStatusString(vStatus); + } + + public static final String getStatusString(int fbStatus) { + switch(fbStatus) { + case -1: + return "NOT A FBO"; + + case GL.GL_FRAMEBUFFER_COMPLETE: + return "OK"; + + case GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + return("GL FBO: incomplete, incomplete attachment\n"); + case GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + return("GL FBO: incomplete, missing attachment"); + case GL.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: + return("GL FBO: incomplete, attached images must have same dimensions"); + case GL.GL_FRAMEBUFFER_INCOMPLETE_FORMATS: + return("GL FBO: incomplete, attached images must have same format"); + case GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: + return("GL FBO: incomplete, missing draw buffer"); + case GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: + return("GL FBO: incomplete, missing read buffer"); + case GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + return("GL FBO: incomplete, missing multisample buffer"); + case GL3.GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: + return("GL FBO: incomplete, layer targets"); + + case GL.GL_FRAMEBUFFER_UNSUPPORTED: + return("GL FBO: Unsupported framebuffer format"); + case GL2GL3.GL_FRAMEBUFFER_UNDEFINED: + return("GL FBO: framebuffer undefined"); + + case 0: + return("GL FBO: incomplete, implementation fault"); + default: + return("GL FBO: incomplete, implementation ERROR 0x"+Integer.toHexString(fbStatus)); + } + } + + /** + * The status may even be valid if incomplete during transition of attachments. + * @see #getStatus() + */ + public final boolean isStatusValid() { + switch(vStatus) { + case GL.GL_FRAMEBUFFER_COMPLETE: + return true; + + case GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + case GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + case GL.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: + case GL.GL_FRAMEBUFFER_INCOMPLETE_FORMATS: + case GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: + case GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: + case GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + case GL3.GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: + if(0 == colorAttachmentCount || null == depth) { + // we are in transition + return true; + } + + case GL.GL_FRAMEBUFFER_UNSUPPORTED: + case GL2GL3.GL_FRAMEBUFFER_UNDEFINED: + + case 0: + default: + System.out.println("Framebuffer " + fbName + " is incomplete: status = 0x" + Integer.toHexString(vStatus) + + " : " + getStatusString(vStatus)); + return false; + } + } + + private final boolean checkNoError(GL gl, int err, String exceptionMessage) throws GLException { + if(GL.GL_NO_ERROR != err) { + if(null != gl) { + destroy(gl); + } + if(null != exceptionMessage) { + throw new GLException(exceptionMessage+" GL Error 0x"+Integer.toHexString(err)); + } + return false; + } + return true; + } + + private final void checkInitialized() throws GLException { + if(!initialized) { + throw new GLException("FBO not initialized, call init(GL) first."); + } + } + + /** + * Attaches a Texture2D Color Buffer to this FBO's instance at the given attachment point, + * selecting the texture data type and format automatically. + * + *

Using default min/mag filter {@link GL#GL_NEAREST} and default wrapS/wrapT {@link GL#GL_CLAMP_TO_EDGE}.

+ * + *

Leaves the FBO bound.

+ * + * @param gl the current GL context + * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] + * @param alpha set to true if you request alpha channel, otherwise false; + * @return TextureAttachment instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown + * @throws GLException in case the texture colorbuffer couldn't be allocated or MSAA has been chosen + */ + public final TextureAttachment attachTexture2D(GL gl, int attachmentPoint, boolean alpha) throws GLException { + return attachTexture2D(gl, attachmentPoint, alpha, GL.GL_NEAREST, GL.GL_NEAREST, GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE); + } + + /** + * Attaches a Texture2D Color Buffer to this FBO's instance at the given attachment point, + * selecting the texture data type and format automatically. + * + *

Leaves the FBO bound.

+ * + * @param gl the current GL context + * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] + * @param alpha set to true if you request alpha channel, otherwise false; + * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER} + * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} + * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S} + * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} + * @return TextureAttachment instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown + * @throws GLException in case the texture colorbuffer couldn't be allocated or MSAA has been chosen + */ + public final TextureAttachment attachTexture2D(GL gl, int attachmentPoint, boolean alpha, int magFilter, int minFilter, int wrapS, int wrapT) throws GLException { + final int textureInternalFormat, textureDataFormat, textureDataType; + if(gl.isGLES()) { + textureInternalFormat = alpha ? GL.GL_RGBA : GL.GL_RGB; + textureDataFormat = alpha ? GL.GL_RGBA : GL.GL_RGB; + textureDataType = GL.GL_UNSIGNED_BYTE; + } else { + textureInternalFormat = alpha ? GL.GL_RGBA8 : GL.GL_RGB8; + textureDataFormat = alpha ? GL.GL_BGRA : GL.GL_RGB; + textureDataType = alpha ? GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV : GL.GL_UNSIGNED_BYTE; + } + return attachTexture2D(gl, attachmentPoint, textureInternalFormat, textureDataFormat, textureDataType, magFilter, minFilter, wrapS, wrapT); + } + + /** + * Attaches a Texture2D Color Buffer to this FBO's instance at the given attachment point. + * + *

Leaves the FBO bound.

+ * + * @param gl the current GL context + * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] + * @param internalFormat internalFormat parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} + * @param dataFormat format parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} + * @param dataType type parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} + * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER} + * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} + * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S} + * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} + * @return TextureAttachment instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown + * @throws GLException in case the texture colorbuffer couldn't be allocated or MSAA has been chosen + */ + public final TextureAttachment attachTexture2D(GL gl, int attachmentPoint, + int internalFormat, int dataFormat, int dataType, + int magFilter, int minFilter, int wrapS, int wrapT) throws GLException { + return attachTexture2D(gl, attachmentPoint, + new TextureAttachment(Type.COLOR_TEXTURE, internalFormat, width, height, dataFormat, dataType, + magFilter, minFilter, wrapS, wrapT, 0 /* name */)); + } + + /** + * Attaches a Texture2D Color Buffer to this FBO's instance at the given attachment point. + * + *

+ * In case the passed TextureAttachment texA is uninitialized, i.e. it's texture name is zero, + * a new texture name is generated and setup w/ the texture parameter.
+ * Otherwise, i.e. texture name is not zero, the passed TextureAttachment texA is + * considered complete and assumed matching this FBO requirement. A GL error may occur is the latter is untrue. + *

+ * + *

Leaves the FBO bound.

+ * + * @param gl the current GL context + * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] + * @param texA the to be attached {@link TextureAttachment}. Maybe complete or uninitialized, see above. + * @return the passed TextureAttachment texA instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown + * @throws GLException in case the texture colorbuffer couldn't be allocated or MSAA has been chosen + */ + public final TextureAttachment attachTexture2D(GL gl, int attachmentPoint, TextureAttachment texA) throws GLException { + validateAddColorAttachment(attachmentPoint, texA); + + if(samples>0) { + removeColorAttachment(attachmentPoint, texA); + throw new GLException("Texture2D not supported w/ MSAA. If you have enabled MSAA with exisiting texture attachments, you may want to detach them via detachAllTexturebuffer(gl)."); + } + + texA.initialize(gl); + addColorAttachment(attachmentPoint, texA); + + bind(gl); + + // Set up the color buffer for use as a renderable texture: + gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, + GL.GL_COLOR_ATTACHMENT0 + attachmentPoint, + GL.GL_TEXTURE_2D, texA.getName(), 0); + updateStatus(gl); + + if(!isStatusValid()) { + detachColorbuffer(gl, attachmentPoint); + throw new GLException("attachTexture2D "+texA+" at "+attachmentPoint+" failed "+getStatusString()+", "+this); + } + if(DEBUG) { + System.err.println("FBObject.attachTexture2D: "+this); + } + return texA; + } + + /** + * Attaches a Color Buffer to this FBO's instance at the given attachment point, + * selecting the format automatically. + * + *

Leaves the FBO bound.

+ * + * @param gl the current GL context + * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] + * @param alpha set to true if you request alpha channel, otherwise false; + * @return ColorAttachment instance describing the new attached colorbuffer if bound and configured successfully, otherwise GLException is thrown + * @throws GLException in case the colorbuffer couldn't be allocated + */ + public final ColorAttachment attachColorbuffer(GL gl, int attachmentPoint, boolean alpha) throws GLException { + final int internalFormat; + if( rgba8Avail ) { + internalFormat = alpha ? GL.GL_RGBA8 : GL.GL_RGB8 ; + } else { + internalFormat = alpha ? GL.GL_RGBA4 : GL.GL_RGB565; + } + return attachColorbuffer(gl, attachmentPoint, internalFormat); + } + + /** + * Attaches a Color Buffer to this FBO's instance at the given attachment point. + * + *

Leaves the FBO bound.

+ * + * @param gl the current GL context + * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] + * @param internalFormat usually {@link GL#GL_RGBA4}, {@link GL#GL_RGB5_A1}, {@link GL#GL_RGB565}, {@link GL#GL_RGB8} or {@link GL#GL_RGBA8} + * @return ColorAttachment instance describing the new attached colorbuffer if bound and configured successfully, otherwise GLException is thrown + * @throws GLException in case the colorbuffer couldn't be allocated + * @throws IllegalArgumentException if internalFormat doesn't reflect a colorbuffer + */ + public final ColorAttachment attachColorbuffer(GL gl, int attachmentPoint, int internalFormat) throws GLException, IllegalArgumentException { + final Attachment.Type atype = Attachment.Type.determine(internalFormat); + if( Attachment.Type.COLOR != atype ) { + throw new IllegalArgumentException("colorformat invalid: 0x"+Integer.toHexString(internalFormat)+", "+this); + } + + return attachColorbuffer(gl, attachmentPoint, new ColorAttachment(internalFormat, samples, width, height, 0)); + } + + /** + * Attaches a Color Buffer to this FBO's instance at the given attachment point. + * + *

Leaves the FBO bound.

+ * + * @param gl + * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] + * @param colA the template for the new {@link ColorAttachment} + * @return ColorAttachment instance describing the new attached colorbuffer if bound and configured successfully, otherwise GLException is thrown + * @throws GLException in case the colorbuffer couldn't be allocated + */ + public final ColorAttachment attachColorbuffer(GL gl, int attachmentPoint, ColorAttachment colA) throws GLException { + validateAddColorAttachment(attachmentPoint, colA); + + colA.initialize(gl); + addColorAttachment(attachmentPoint, colA); + + bind(gl); + + // Attach the color buffer + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, + GL.GL_COLOR_ATTACHMENT0 + attachmentPoint, + GL.GL_RENDERBUFFER, colA.getName()); + + updateStatus(gl); + if(!isStatusValid()) { + detachColorbuffer(gl, attachmentPoint); + throw new GLException("attachColorbuffer "+colA+" at "+attachmentPoint+" failed "+getStatusString()+", "+this); + } + if(DEBUG) { + System.err.println("FBObject.attachColorbuffer: "+this); + } + return colA; + } + + + /** + * Attaches one depth, stencil or packed-depth-stencil buffer to this FBO's instance, + * selecting the internalFormat automatically. + *

+ * Stencil and depth buffer can be attached only once. + *

+ *

+ * In case the desired type or bit-number is not supported, the next available one is chosen. + *

+ *

+ * Use {@link #getDepthAttachment()} and/or {@link #getStencilAttachment()} to retrieve details + * about the attached buffer. The details cannot be returned, since it's possible 2 buffers + * are being created, depth and stencil. + *

+ * + *

Leaves the FBO bound.

+ * + * @param gl + * @param atype either {@link Type#DEPTH}, {@link Type#STENCIL} or {@link Type#DEPTH_STENCIL} + * @param reqBits desired bits for depth or -1 for default (24 bits) + * @throws GLException in case the renderbuffer couldn't be allocated or one is already attached. + * @throws IllegalArgumentException + * @see #getDepthAttachment() + * @see #getStencilAttachment() + */ + public final void attachRenderbuffer(GL gl, Attachment.Type atype, int reqBits) throws GLException, IllegalArgumentException { + if( 0 > reqBits ) { + reqBits = 24; + } + final int internalFormat; + int internalStencilFormat = -1; + + switch ( atype ) { + case DEPTH: + if( 32 <= reqBits && depth32Avail ) { + internalFormat = GL.GL_DEPTH_COMPONENT32; + } else if( 24 <= reqBits && depth24Avail ) { + internalFormat = GL.GL_DEPTH_COMPONENT24; + } else { + internalFormat = GL.GL_DEPTH_COMPONENT16; + } + break; + + case STENCIL: + if( 16 <= reqBits && stencil16Avail ) { + internalFormat = GL2GL3.GL_STENCIL_INDEX16; + } else if( 8 <= reqBits && stencil08Avail ) { + internalFormat = GL.GL_STENCIL_INDEX8; + } else if( 4 <= reqBits && stencil04Avail ) { + internalFormat = GL.GL_STENCIL_INDEX4; + } else if( 1 <= reqBits && stencil01Avail ) { + internalFormat = GL.GL_STENCIL_INDEX1; + } else { + throw new GLException("stencil buffer n/a"); + } + break; + + case DEPTH_STENCIL: + if( packedDepthStencilAvail ) { + internalFormat = GL.GL_DEPTH24_STENCIL8; + } else { + if( 24 <= reqBits && depth24Avail ) { + internalFormat = GL.GL_DEPTH_COMPONENT24; + } else { + internalFormat = GL.GL_DEPTH_COMPONENT16; + } + if( stencil08Avail ) { + internalStencilFormat = GL.GL_STENCIL_INDEX8; + } else if( stencil04Avail ) { + internalStencilFormat = GL.GL_STENCIL_INDEX4; + } else if( stencil01Avail ) { + internalStencilFormat = GL.GL_STENCIL_INDEX1; + } else { + throw new GLException("stencil buffer n/a"); + } + } + break; + default: + throw new IllegalArgumentException("only depth/stencil types allowed, was "+atype+", "+this); + } + + attachRenderbufferImpl(gl, atype, internalFormat); + + if(0<=internalStencilFormat) { + attachRenderbufferImpl(gl, Attachment.Type.STENCIL, internalStencilFormat); + } + } + + /** + * Attaches one depth, stencil or packed-depth-stencil buffer to this FBO's instance, + * depending on the internalFormat. + *

+ * Stencil and depth buffer can be attached only once. + *

+ *

+ * Use {@link #getDepthAttachment()} and/or {@link #getStencilAttachment()} to retrieve details + * about the attached buffer. The details cannot be returned, since it's possible 2 buffers + * are being created, depth and stencil. + *

+ * + *

Leaves the FBO bound.

+ * + * @param gl the current GL context + * @param internalFormat {@link GL#GL_DEPTH_COMPONENT16}, {@link GL#GL_DEPTH_COMPONENT24}, {@link GL#GL_DEPTH_COMPONENT32}, + * {@link GL#GL_STENCIL_INDEX1}, {@link GL#GL_STENCIL_INDEX4}, {@link GL#GL_STENCIL_INDEX8} + * or {@link GL#GL_DEPTH24_STENCIL8} + * @throws GLException in case the renderbuffer couldn't be allocated or one is already attached. + * @throws IllegalArgumentException + * @see #getDepthAttachment() + * @see #getStencilAttachment() + */ + public final void attachRenderbuffer(GL gl, int internalFormat) throws GLException, IllegalArgumentException { + final Attachment.Type atype = Attachment.Type.determine(internalFormat); + if( Attachment.Type.DEPTH != atype && Attachment.Type.STENCIL != atype && Attachment.Type.DEPTH_STENCIL != atype ) { + throw new IllegalArgumentException("renderformat invalid: 0x"+Integer.toHexString(internalFormat)+", "+this); + } + attachRenderbufferImpl(gl, atype, internalFormat); + } + + protected final void attachRenderbufferImpl(GL gl, Attachment.Type atype, int internalFormat) throws GLException { + if( null != depth && ( Attachment.Type.DEPTH == atype || Attachment.Type.DEPTH_STENCIL == atype ) ) { + throw new GLException("FBO depth buffer already attached (rb "+depth+"), type is "+atype+", 0x"+Integer.toHexString(internalFormat)+", "+this); + } + if( null != stencil && ( Attachment.Type.STENCIL== atype || Attachment.Type.DEPTH_STENCIL == atype ) ) { + throw new GLException("FBO stencil buffer already attached (rb "+stencil+"), type is "+atype+", 0x"+Integer.toHexString(internalFormat)+", "+this); + } + attachRenderbufferImpl2(gl, atype, internalFormat); + } + + private final void attachRenderbufferImpl2(GL gl, Attachment.Type atype, int internalFormat) throws GLException { + if( Attachment.Type.DEPTH == atype ) { + if(null == depth) { + depth = new RenderAttachment(Type.DEPTH, internalFormat, samples, width, height, 0); + } else { + depth.setSize(width, height); + depth.setSamples(samples); + } + depth.initialize(gl); + } else if( Attachment.Type.STENCIL == atype ) { + if(null == stencil) { + stencil = new RenderAttachment(Type.STENCIL, internalFormat, samples, width, height, 0); + } else { + stencil.setSize(width, height); + stencil.setSamples(samples); + } + stencil.initialize(gl); + } else if( Attachment.Type.DEPTH_STENCIL == atype ) { + if(null == depth) { + depth = new RenderAttachment(Type.DEPTH, internalFormat, samples, width, height, 0); + } else { + depth.setSize(width, height); + depth.setSamples(samples); + } + depth.initialize(gl); + if(null == stencil) { + stencil = new RenderAttachment(Type.STENCIL, internalFormat, samples, width, height, depth.getName()); + } else { + stencil.setName(depth.getName()); + stencil.setSize(width, height); + stencil.setSamples(samples); + } + stencil.initialize(gl); + } + + bind(gl); + + // Attach the buffer + if( Attachment.Type.DEPTH == atype ) { + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, depth.getName()); + } else if( Attachment.Type.STENCIL == atype ) { + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, stencil.getName()); + } else if( Attachment.Type.DEPTH_STENCIL == atype ) { + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, depth.getName()); + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, stencil.getName()); + } + + updateStatus(gl); + if( !isStatusValid() ) { + detachRenderbuffer(gl, atype); + throw new GLException("renderbuffer attachment failed: "+this.getStatusString()); + } + + if(DEBUG) { + System.err.println("FBObject.attachRenderbuffer: "+this); + } + } + + /** + *

Leaves the FBO bound!

+ * @param gl + * @param ca + * @throws IllegalArgumentException + */ + public final void detachColorbuffer(GL gl, int attachmentPoint) throws IllegalArgumentException { + if(null == detachColorbufferImpl(gl, attachmentPoint, false)) { + throw new IllegalArgumentException("ColorAttachment at "+attachmentPoint+", not attached, "+this); + } + if(DEBUG) { + System.err.println("FBObject.detachAll: "+this); + } + } + + private final Colorbuffer detachColorbufferImpl(GL gl, int attachmentPoint, boolean recreate) { + final Colorbuffer colbuf = colorAttachmentPoints[attachmentPoint]; // shortcut, don't validate here + + if(null == colbuf) { + return null; + } + + bind(gl); + + if(colbuf instanceof TextureAttachment) { + final TextureAttachment texA = (TextureAttachment) colbuf; + if( 0 != texA.getName() ) { + gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, + GL.GL_COLOR_ATTACHMENT0 + attachmentPoint, + GL.GL_TEXTURE_2D, 0, 0); + gl.glBindTexture(GL.GL_TEXTURE_2D, 0); + } + texA.free(gl); + removeColorAttachment(attachmentPoint, texA); + if(recreate) { + texA.setSize(width, height); + attachTexture2D(gl, attachmentPoint, texA); + } + } else if(colbuf instanceof ColorAttachment) { + final ColorAttachment colA = (ColorAttachment) colbuf; + if( 0 != colA.getName() ) { + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, + GL.GL_COLOR_ATTACHMENT0+attachmentPoint, + GL.GL_RENDERBUFFER, 0); + } + colA.free(gl); + removeColorAttachment(attachmentPoint, colbuf); + if(recreate) { + colA.setSize(width, height); + colA.setSamples(samples); + attachColorbuffer(gl, attachmentPoint, colA); + } + } + return colbuf; + } + + /** + * + * @param gl + * @param reqAType {@link Type#DEPTH}, {@link Type#DEPTH} or {@link Type#DEPTH_STENCIL} + */ + public final void detachRenderbuffer(GL gl, Attachment.Type atype) throws IllegalArgumentException { + detachRenderbufferImpl(gl, atype, false); + } + + public final boolean isDepthStencilPackedFormat() { + final boolean res = null != depth && null != stencil && + depth.format == stencil.format ; + if(res && depth.getName() != stencil.getName() ) { + throw new InternalError("depth/stencil packed format not sharing: depth "+depth+", stencil "+stencil); + } + return res; + } + + private final void detachRenderbufferImpl(GL gl, Attachment.Type atype, boolean recreate) throws IllegalArgumentException { + switch ( atype ) { + case DEPTH: + case STENCIL: + case DEPTH_STENCIL: + break; + default: + throw new IllegalArgumentException("only depth/stencil types allowed, was "+atype+", "+this); + } + if( null == depth && null == stencil ) { + return ; // nop + } + // reduction of possible combinations, create unique atype command(s) + final ArrayList actions = new ArrayList(2); + if( isDepthStencilPackedFormat() ) { + // packed + actions.add(Attachment.Type.DEPTH_STENCIL); + } else { + // individual + switch ( atype ) { + case DEPTH: + if( null != depth ) { actions.add(Attachment.Type.DEPTH); } + break; + case STENCIL: + if( null != stencil ) { actions.add(Attachment.Type.STENCIL); } + break; + case DEPTH_STENCIL: + if( null != depth ) { actions.add(Attachment.Type.DEPTH); } + if( null != stencil ) { actions.add(Attachment.Type.STENCIL); } + break; + default: // handled + } + } + + bind(gl); + + for(int i = 0; i < actions.size(); i++) { + final int format; + + Attachment.Type action = actions.get(i); + switch ( action ) { + case DEPTH: + format = depth.format; + if( 0 != depth.getName() ) { + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, 0); + } + depth.free(gl); + if(!recreate) { + depth = null; + } + break; + case STENCIL: + format = stencil.format; + if(0 != stencil.getName()) { + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, 0); + } + stencil.free(gl); + if(!recreate) { + stencil = null; + } + break; + case DEPTH_STENCIL: + format = depth.format; + if(0 != depth.getName()) { + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, 0); + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, 0); + } + depth.free(gl); + stencil.free(gl); + if(!recreate) { + depth = null; + stencil = null; + } + break; + default: + throw new InternalError("XXX"); + } + if(recreate) { + attachRenderbufferImpl2(gl, action, format); + } + } + } + + /** + * Detaches all {@link ColorAttachment}s, {@link TextureAttachment}s and {@link RenderAttachment}s. + *

Leaves the FBO bound!

+ *

+ * An attached sampling sink texture will be detached as well, see {@link #getSamplingSink()}. + *

+ * @param gl the current GL context + */ + public final void detachAll(GL gl) { + if(null != samplesSink) { + samplesSink.detachAll(gl); + } + detachAllImpl(gl, true/* detachNonColorbuffer */, false /* recreate */); + } + + /** + * Detaches all {@link ColorAttachment}s and {@link TextureAttachment}s. + *

Leaves the FBO bound!

+ *

+ * An attached sampling sink texture will be detached as well, see {@link #getSamplingSink()}. + *

+ * @param gl the current GL context + */ + public final void detachAllColorbuffer(GL gl) { + if(null != samplesSink) { + samplesSink.detachAllColorbuffer(gl); + } + detachAllImpl(gl, false/* detachNonColorbuffer */, false /* recreate */); + } + + /** + * Detaches all {@link TextureAttachment}s + *

Leaves the FBO bound!

+ *

+ * An attached sampling sink texture will be detached as well, see {@link #getSamplingSink()}. + *

+ * @param gl the current GL context + */ + public final void detachAllTexturebuffer(GL gl) { + if(null != samplesSink) { + samplesSink.detachAllTexturebuffer(gl); + } + for(int i=0; i0 ) { + throw new InternalError("Non zero ColorAttachments "+this); + } + + if(detachNonColorbuffer) { + detachRenderbufferImpl(gl, Attachment.Type.DEPTH_STENCIL, recreate); + } + + if(DEBUG) { + System.err.println("FBObject.detachAll: [resetNonColorbuffer "+detachNonColorbuffer+", recreate "+recreate+"]: "+this); + } + } + + /** + * @param gl the current GL context + */ + public final void destroy(GL gl) { + if(null != samplesSink) { + samplesSink.destroy(gl); + } + + detachAllImpl(gl, true /* detachNonColorbuffer */, false /* recreate */); + + // cache FB names, preset exposed to zero, + // braking ties w/ GL/GLContext link to getReadFramebuffer()/getWriteFramebuffer() + final int fb_cache = fbName; + fbName = 0; + + int name[] = new int[1]; + if(0!=fb_cache) { + name[0] = fb_cache; + gl.glDeleteFramebuffers(1, name, 0); + } + initialized = false; + bound = false; + if(DEBUG) { + System.err.println("FBObject.destroy: "+this); + } + } + + private final boolean sampleSinkSizeMismatch() { + return samplesSink.getWidth() != width || samplesSink.getHeight() != height ; + } + private final boolean sampleSinkTexMismatch() { + return null == samplesSinkTexture || 0 == samplesSinkTexture.getName() ; + } + private final boolean sampleSinkDepthStencilMismatch() { + final boolean depthMismatch = ( null != depth && null == samplesSink.depth ) || + ( null != depth && null != samplesSink.depth && + depth.format != samplesSink.depth.format ); + + final boolean stencilMismatch = ( null != stencil && null == samplesSink.stencil ) || + ( null != stencil && null != samplesSink.stencil && + stencil.format != samplesSink.stencil.format ); + + return depthMismatch || stencilMismatch; + } + + private final void resetMSAATexture2DSink(GL gl) throws GLException { + if(0 == samples) { + // MSAA off + if(null != samplesSink) { + samplesSink.detachAll(gl); + } + return; + } + + boolean sampleSinkSizeMismatch = sampleSinkSizeMismatch(); + boolean sampleSinkTexMismatch = sampleSinkTexMismatch(); + boolean sampleSinkDepthStencilMismatch = sampleSinkDepthStencilMismatch(); + + /** if(DEBUG) { + System.err.println("FBObject.resetMSAATexture2DSink.0: \n\tTHIS "+this+",\n\tSINK "+samplesSink+ + "\n\t size "+sampleSinkSizeMismatch +", tex "+sampleSinkTexMismatch +", depthStencil "+sampleSinkDepthStencilMismatch); + } */ + + if(!sampleSinkSizeMismatch && !sampleSinkTexMismatch && !sampleSinkDepthStencilMismatch) { + // all properties match .. + return; + } + + unbind(gl); + + if(DEBUG) { + System.err.println("FBObject.resetMSAATexture2DSink: BEGIN\n\tTHIS "+this+",\n\tSINK "+samplesSink+ + "\n\t size "+sampleSinkSizeMismatch +", tex "+sampleSinkTexMismatch +", depthStencil "+sampleSinkDepthStencilMismatch); + } + + if( sampleSinkDepthStencilMismatch ) { + samplesSink.detachAllRenderbuffer(gl); + } + + if( sampleSinkSizeMismatch ) { + samplesSink.reset(gl, width, height); + } + + if(null == samplesSinkTexture) { + samplesSinkTexture = samplesSink.attachTexture2D(gl, 0, true); + } else if( 0 == samplesSinkTexture.getName() ) { + samplesSinkTexture.setSize(width, height); + samplesSink.attachTexture2D(gl, 0, samplesSinkTexture); + } + + if( sampleSinkDepthStencilMismatch ) { + samplesSink.attachRenderbuffer(gl, depth.format); + if( null != stencil && !isDepthStencilPackedFormat() ) { + samplesSink.attachRenderbuffer(gl, stencil.format); + } + } + + sampleSinkSizeMismatch = sampleSinkSizeMismatch(); + sampleSinkTexMismatch = sampleSinkTexMismatch(); + sampleSinkDepthStencilMismatch = sampleSinkDepthStencilMismatch(); + if(sampleSinkSizeMismatch || sampleSinkTexMismatch || sampleSinkDepthStencilMismatch) { + throw new InternalError("Samples sink mismatch after reset: \n\tTHIS "+this+",\n\t SINK "+samplesSink+ + "\n\t size "+sampleSinkSizeMismatch +", tex "+sampleSinkTexMismatch +", depthStencil "+sampleSinkDepthStencilMismatch); + } + + if(DEBUG) { + System.err.println("FBObject.resetMSAATexture2DSink: END\n\tTHIS "+this+",\n\tSINK "+samplesSink+ + "\n\t size "+sampleSinkSizeMismatch +", tex "+sampleSinkTexMismatch +", depthStencil "+sampleSinkDepthStencilMismatch); + } + } + + /** + * Bind this FBO, i.e. bind write framebuffer to {@link #getWriteFramebuffer()}. + * + *

If multisampling is used, it sets the read framebuffer to the sampling sink {@link #getWriteFramebuffer()}, + * if full FBO is supported.

+ * + *

+ * In case you have attached more than one color buffer, + * you may want to setup {@link GL2GL3#glDrawBuffers(int, int[], int)}. + *

+ * @param gl the current GL context + * @throws GLException + */ + public final void bind(GL gl) throws GLException { + if(!bound || fbName != gl.getBoundFramebuffer(GL.GL_FRAMEBUFFER)) { + checkInitialized(); + if(samples > 0 && fullFBOSupport) { + // draw to multisampling - read from samplesSink + gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, getWriteFramebuffer()); + gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, getReadFramebuffer()); + } else { + // one for all + gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, getWriteFramebuffer()); + } + + checkNoError(null, gl.glGetError(), "FBObject post-bind"); // throws GLException if error + bound = true; + samplesSinkDirty = true; + } + } + + /** + * Unbind this FBO, i.e. bind read and write framebuffer to default, see {@link GLBase#getDefaultDrawFramebuffer()}. + * + *

If full FBO is supported, sets the read and write framebuffer individually to default, hence not disturbing + * an optional operating MSAA FBO, see {@link GLBase#getDefaultReadFramebuffer()} and {@link GLBase#getDefaultDrawFramebuffer()}

+ * + * @param gl the current GL context + * @throws GLException + */ + public final void unbind(GL gl) throws GLException { + if(bound) { + if(fullFBOSupport) { + // default read/draw buffers, may utilize GLContext/GLDrawable override of + // GLContext.getDefaultDrawFramebuffer() and GLContext.getDefaultReadFramebuffer() + gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, 0); + gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, 0); + } else { + gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); // default draw buffer + } + checkNoError(null, gl.glGetError(), "FBObject post-unbind"); // throws GLException if error + bound = false; + } + } + + /** + * Returns true if framebuffer object is bound via {@link #bind(GL)}, otherwise false. + *

+ * Method verifies the bound state via {@link GL#getBoundFramebuffer(int)}. + *

+ * @param gl the current GL context + */ + public final boolean isBound(GL gl) { + bound = bound && fbName != gl.getBoundFramebuffer(GL.GL_FRAMEBUFFER) ; + return bound; + } + + /** Returns true if framebuffer object is bound via {@link #bind(GL)}, otherwise false. */ + public final boolean isBound() { return bound; } + + /** + * Samples the multisampling colorbuffer (msaa-buffer) to it's sink {@link #getSamplingSink()}. + * + *

The operation is skipped, if no multisampling is used or + * the msaa-buffer has not been flagged dirty by a previous call of {@link #bind(GL)}, + * see {@link #isSamplingBufferDirty()}

+ * + *

If full FBO is supported, sets the read and write framebuffer individually to default after sampling, hence not disturbing + * an optional operating MSAA FBO, see {@link GLBase#getDefaultReadFramebuffer()} and {@link GLBase#getDefaultDrawFramebuffer()}

+ * + *

In case you intend to employ {@link GL#glReadPixels(int, int, int, int, int, int, java.nio.Buffer) glReadPixels(..)} + * you may want to call {@link GL#glBindFramebuffer(int, int) glBindFramebuffer}({@link GL2GL3#GL_READ_FRAMEBUFFER}, {@link #getReadFramebuffer()}); + *

+ * + *

Leaves the FBO unbound.

+ * + * @param gl the current GL context + * @param ta {@link TextureAttachment} to use, prev. attached w/ {@link #attachTexture2D(GL, int, boolean, int, int, int, int) attachTexture2D(..)} + * @throws IllegalArgumentException + */ + public final void syncSamplingBuffer(GL gl) { + unbind(gl); + if(samples>0 && samplesSinkDirty) { + samplesSinkDirty = false; + resetMSAATexture2DSink(gl); + gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, fbName); + gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, samplesSink.getWriteFramebuffer()); + ((GL2GL3)gl).glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, // since MSAA is supported, ugly cast is OK + GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST); + if(fullFBOSupport) { + // default read/draw buffers, may utilize GLContext/GLDrawable override of + // GLContext.getDefaultDrawFramebuffer() and GLContext.getDefaultReadFramebuffer() + gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, 0); + gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, 0); + } else { + gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); // default draw buffer + } + } + } + + /** + * Bind the given texture colorbuffer. + * + *

If multisampling is being used, {@link #syncSamplingBuffer(GL)} is being called.

+ * + *

Leaves the FBO unbound!

+ * + * @param gl the current GL context + * @param ta {@link TextureAttachment} to use, prev. attached w/ {@link #attachTexture2D(GL, int, boolean, int, int, int, int) attachTexture2D(..)} + * @throws IllegalArgumentException + */ + public final void use(GL gl, TextureAttachment ta) throws IllegalArgumentException { + if(null == ta) { throw new IllegalArgumentException("null TextureAttachment"); } + if(samples > 0 && samplesSinkTexture == ta) { + syncSamplingBuffer(gl); + } else { + unbind(gl); + } + gl.glBindTexture(GL.GL_TEXTURE_2D, ta.getName()); // use it .. + } + + /** + * Unbind texture, ie bind 'non' texture 0 + * + *

Leaves the FBO unbound.

+ */ + public final void unuse(GL gl) { + unbind(gl); + gl.glBindTexture(GL.GL_TEXTURE_2D, 0); // don't use it + } + + /** + * Returns true if basic or full FBO is supported, otherwise false. + * @param full true for full FBO supported query, otherwise false for basic FBO support query. + * @see #supportsFullFBO(GL) + * @see #supportsBasicFBO(GL) + * @throws GLException if {@link #init(GL)} hasn't been called. + */ + public final boolean supportsFBO(boolean full) throws GLException { checkInitialized(); return full ? fullFBOSupport : basicFBOSupport; } + + /** + * Returns true if renderbuffer accepts internal format {@link GL#GL_RGB8} and {@link GL#GL_RGBA8}, otherwise false. + * @throws GLException if {@link #init(GL)} hasn't been called. + */ + public final boolean supportsRGBA8() throws GLException { checkInitialized(); return rgba8Avail; } + + /** + * Returns true if {@link GL#GL_DEPTH_COMPONENT16}, {@link GL#GL_DEPTH_COMPONENT24} or {@link GL#GL_DEPTH_COMPONENT32} is supported, otherwise false. + * @param bits 16, 24 or 32 bits + * @throws GLException if {@link #init(GL)} hasn't been called. + */ + public final boolean supportsDepth(int bits) throws GLException { + checkInitialized(); + switch(bits) { + case 16: return basicFBOSupport; + case 24: return depth24Avail; + case 32: return depth32Avail; + default: return false; + } + } + + /** + * Returns true if {@link GL#GL_STENCIL_INDEX1}, {@link GL#GL_STENCIL_INDEX4}, {@link GL#GL_STENCIL_INDEX8} or {@link GL2GL3#GL_STENCIL_INDEX16} is supported, otherwise false. + * @param bits 1, 4, 8 or 16 bits + * @throws GLException if {@link #init(GL)} hasn't been called. + */ + public final boolean supportsStencil(int bits) throws GLException { + checkInitialized(); + switch(bits) { + case 1: return stencil01Avail; + case 4: return stencil04Avail; + case 8: return stencil08Avail; + case 16: return stencil16Avail; + default: return false; + } + } + + /** + * Returns true if {@link GL#GL_DEPTH24_STENCIL8} is supported, otherwise false. + * @throws GLException if {@link #init(GL)} hasn't been called. + */ + public final boolean supportsPackedDepthStencil() throws GLException { checkInitialized(); return packedDepthStencilAvail; } + + /** + * Returns the maximum number of colorbuffer attachments. + * @throws GLException if {@link #init(GL)} hasn't been called. + */ + public final int getMaxColorAttachments() throws GLException { checkInitialized(); return maxColorAttachments; } + + /** + * Returns the maximum number of samples for multisampling. Maybe zero if multisampling is not supported. + * @throws GLException if {@link #init(GL)} hasn't been called. + */ + public final int getMaxSamples() throws GLException { checkInitialized(); return maxSamples; } + + /** + * Returns true if this instance has been initialized with {@link #reset(GL, int, int)} + * or {@link #reset(GL, int, int, int)}, otherwise false + */ + public final boolean isInitialized() { return initialized; } + /** Returns the width */ + public final int getWidth() { return width; } + /** Returns the height */ + public final int getHeight() { return height; } + /** Returns the number of samples for multisampling (MSAA). zero if no multisampling is used. */ + public final int getNumSamples() { return samples; } + /** Returns the framebuffer name to render to. */ + public final int getWriteFramebuffer() { return fbName; } + /** Returns the framebuffer name to read from. Depending on multisampling, this may be a different framebuffer. */ + public final int getReadFramebuffer() { return ( samples > 0 ) ? samplesSink.getReadFramebuffer() : fbName; } + /** Return the number of color/texture attachments */ + public final int getColorAttachmentCount() { return colorAttachmentCount; } + /** Return the stencil {@link RenderAttachment} attachment, if exist. Maybe share the same {@link Attachment#getName()} as {@link #getDepthAttachment()}, if packed depth-stencil is being used. */ + public final RenderAttachment getStencilAttachment() { return stencil; } + /** Return the depth {@link RenderAttachment} attachment. Maybe share the same {@link Attachment#getName()} as {@link #getStencilAttachment()}, if packed depth-stencil is being used. */ + public final RenderAttachment getDepthAttachment() { return depth; } + + /** Return the complete multisampling {@link FBObject} sink, if using multisampling. */ + public final FBObject getSamplingSinkFBO() { return samplesSink; } + + /** Return the multisampling {@link TextureAttachment} sink, if using multisampling. */ + public final TextureAttachment getSamplingSink() { return samplesSinkTexture; } + /** + * Returns true if the multisampling colorbuffer (msaa-buffer) + * has been flagged dirty by a previous call of {@link #bind(GL)}, + * otherwise false. + */ + public final boolean isSamplingBufferDirty() { return samplesSinkDirty; } + + int objectHashCode() { return super.hashCode(); } + + public final String toString() { + final String caps = null != colorAttachmentPoints ? Arrays.asList(colorAttachmentPoints).toString() : null ; + return "FBO[name r/w "+fbName+"/"+getReadFramebuffer()+", init "+initialized+", bound "+bound+", size "+width+"x"+height+", samples "+samples+"/"+maxSamples+ + ", depth "+depth+", stencil "+stencil+", color attachments: "+colorAttachmentCount+"/"+maxColorAttachments+ + ": "+caps+", msaa-sink "+samplesSinkTexture+", isSamplesSink "+(null == samplesSink)+ + ", obj 0x"+Integer.toHexString(objectHashCode())+"]"; + } + + private final void updateStatus(GL gl) { + if( 0 == fbName ) { + vStatus = -1; + } else { + vStatus = gl.glCheckFramebufferStatus(GL.GL_FRAMEBUFFER); + } + } +} diff --git a/src/jogl/classes/com/jogamp/opengl/GLExtensions.java b/src/jogl/classes/com/jogamp/opengl/GLExtensions.java new file mode 100644 index 000000000..f7e25fa01 --- /dev/null +++ b/src/jogl/classes/com/jogamp/opengl/GLExtensions.java @@ -0,0 +1,81 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl; + +/** + * Class holding OpenGL extension strings, commonly used by JOGL's implementation. + */ +public class GLExtensions { + public static final String VERSION_1_2 = "GL_VERSION_1_2"; + public static final String VERSION_1_4 = "GL_VERSION_1_4"; + public static final String VERSION_1_5 = "GL_VERSION_1_5"; + public static final String VERSION_2_0 = "GL_VERSION_2_0"; + + public static final String ARB_debug_output = "GL_ARB_debug_output"; + public static final String AMD_debug_output = "GL_AMD_debug_output"; + + public static final String ARB_framebuffer_object = "GL_ARB_framebuffer_object"; + public static final String OES_framebuffer_object = "GL_OES_framebuffer_object"; + public static final String EXT_framebuffer_object = "GL_EXT_framebuffer_object"; + public static final String EXT_framebuffer_blit = "GL_EXT_framebuffer_blit"; + public static final String EXT_framebuffer_multisample = "GL_EXT_framebuffer_multisample"; + public static final String EXT_packed_depth_stencil = "GL_EXT_packed_depth_stencil"; + public static final String OES_depth24 = "GL_OES_depth24"; + public static final String OES_depth32 = "GL_OES_depth32"; + public static final String OES_packed_depth_stencil = "GL_OES_packed_depth_stencil"; + public static final String NV_fbo_color_attachments = "GL_NV_fbo_color_attachments"; + + public static final String ARB_ES2_compatibility = "GL_ARB_ES2_compatibility"; + + public static final String EXT_abgr = "GL_EXT_abgr"; + public static final String OES_rgb8_rgba8 = "GL_OES_rgb8_rgba8"; + public static final String OES_stencil1 = "GL_OES_stencil1"; + public static final String OES_stencil4 = "GL_OES_stencil4"; + public static final String OES_stencil8 = "GL_OES_stencil8"; + public static final String APPLE_float_pixels = "GL_APPLE_float_pixels"; + + public static final String ARB_texture_non_power_of_two = "GL_ARB_texture_non_power_of_two"; + public static final String ARB_texture_rectangle = "GL_ARB_texture_rectangle"; + public static final String EXT_texture_rectangle = "GL_EXT_texture_rectangle"; + public static final String NV_texture_rectangle = "GL_NV_texture_rectangle"; + public static final String EXT_texture_format_BGRA8888 = "GL_EXT_texture_format_BGRA8888"; + public static final String IMG_texture_format_BGRA8888 = "GL_IMG_texture_format_BGRA8888"; + public static final String EXT_texture_compression_s3tc = "GL_EXT_texture_compression_s3tc"; + public static final String NV_texture_compression_vtc = "GL_NV_texture_compression_vtc"; + public static final String SGIS_generate_mipmap = "GL_SGIS_generate_mipmap"; + public static final String OES_read_format = "GL_OES_read_format"; + + public static final String OES_EGL_image_external = "GL_OES_EGL_image_external"; + + // + // Aliased GLX/WGL/.. extensions + // + + public static final String ARB_pixel_format = "GL_ARB_pixel_format"; + public static final String ARB_pbuffer = "GL_ARB_pbuffer"; +} diff --git a/src/jogl/classes/com/jogamp/opengl/JoglVersion.java b/src/jogl/classes/com/jogamp/opengl/JoglVersion.java index 75785fd86..cdb4b82bb 100644 --- a/src/jogl/classes/com/jogamp/opengl/JoglVersion.java +++ b/src/jogl/classes/com/jogamp/opengl/JoglVersion.java @@ -93,11 +93,13 @@ public class JoglVersion extends JogampVersion { return sb; } - public static StringBuilder getDefaultOpenGLInfo(StringBuilder sb, boolean withCapabilitiesInfo) { + public static StringBuilder getDefaultOpenGLInfo(AbstractGraphicsDevice device, StringBuilder sb, boolean withCapabilitiesInfo) { if(null==sb) { sb = new StringBuilder(); } - final AbstractGraphicsDevice device = GLProfile.getDefaultDevice(); + if(null == device) { + device = GLProfile.getDefaultDevice(); + } sb.append("Default Profiles on device ").append(device).append(Platform.getNewline()); if(null!=device) { GLProfile.glAvailabilityToString(device, sb, "\t", 1); @@ -120,13 +122,21 @@ public class JoglVersion extends JogampVersion { if(null==sb) { sb = new StringBuilder(); } - GLContext ctx = gl.getContext(); - + sb.append(VersionUtil.SEPERATOR).append(Platform.getNewline()); sb.append(device.getClass().getSimpleName()).append("[type ") .append(device.getType()).append(", connection ").append(device.getConnection()).append("]: ").append(Platform.getNewline()); GLProfile.glAvailabilityToString(device, sb, "\t", 1); sb.append(Platform.getNewline()); + + return getGLStrings(gl, sb); + } + + public static StringBuilder getGLStrings(GL gl, StringBuilder sb) { + if(null==sb) { + sb = new StringBuilder(); + } + final GLContext ctx = gl.getContext(); sb.append("Swap Interval ").append(gl.getSwapInterval()); sb.append(Platform.getNewline()); sb.append("GL Profile ").append(gl.getGLProfile()); diff --git a/src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java b/src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java new file mode 100644 index 000000000..1ea8595c6 --- /dev/null +++ b/src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java @@ -0,0 +1,89 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl; + +import javax.media.opengl.GLAutoDrawableDelegate; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLException; + +import jogamp.opengl.GLFBODrawableImpl; + +/** + * Platform-independent class exposing FBO offscreen functionality to + * applications. + *

+ * This class distinguishes itself from {@link GLAutoDrawableDelegate} + * with it's {@link #setSize(int, int)} functionality. + *

+ */ +public class OffscreenAutoDrawable extends GLAutoDrawableDelegate { + + public OffscreenAutoDrawable(GLDrawable drawable, GLContext context, Object upstreamWidget) { + super(drawable, context, upstreamWidget); + } + + /** + * Attempts to resize this offscreen auto drawable, if supported + * by the underlying {@link GLDrawable). + * @param newWidth + * @param newHeight + * @return true if resize was executed, otherwise false. + * @throws GLException in case of an error during the resize operation + */ + public boolean setSize(int newWidth, int newHeight) throws GLException { + boolean done = false; + if(drawable instanceof GLFBODrawableImpl) { + context.makeCurrent(); + try { + ((GLFBODrawableImpl)drawable).setSize(context.getGL(), newWidth, newHeight); + done = true; + } finally { + context.release(); + } + } + if(done) { + this.defaultWindowResizedOp(); + return true; + } + return false; + } + + /** + * If the underlying {@link GLDrawable} is an FBO implementation + * and contains an {#link FBObject}, the same is returned. + * Otherwise returns null. + */ + public FBObject getFBObject() { + if(drawable instanceof GLFBODrawableImpl) { + return ((GLFBODrawableImpl)drawable).getFBObject(); + } + return null; + } +} diff --git a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java index 5ee58b78d..0d9d3ddf5 100644 --- a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java +++ b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java @@ -231,6 +231,8 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { /* Get the nativewindow-Graphics Device associated with this control (which is determined by the parent Composite) */ device = SWTAccessor.getDevice(this); + /* Since we have no means of querying the screen index yet, assume 0. Good choice due to Xinerama alike settings anyways. */ + final int screenIdx = 0; /* Native handle for the control, used to associate with GLContext */ nativeWindowHandle = SWTAccessor.getWindowHandle(this); @@ -243,7 +245,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { final GLDrawableFactory glFactory = GLDrawableFactory.getFactory(caps.getGLProfile()); /* Create a NativeWindow proxy for the SWT canvas */ - proxySurface = glFactory.createProxySurface(device, nativeWindowHandle, caps, chooser); + proxySurface = glFactory.createProxySurface(device, screenIdx, nativeWindowHandle, caps, chooser, swtCanvasUpStreamHook); /* Associate a GL surface with the proxy */ drawable = glFactory.createGLDrawable(proxySurface); @@ -265,12 +267,58 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { addControlListener(new ControlAdapter() { @Override public void controlResized(final ControlEvent arg0) { - clientArea = GLCanvas.this.getClientArea(); - /* Mark for OpenGL reshape next time the control is painted */ - sendReshape = true; + updateSizeCheck(); } }); } + private final ProxySurface.UpstreamSurfaceHook swtCanvasUpStreamHook = new ProxySurface.UpstreamSurfaceHook() { + @Override + public final void create(ProxySurface s) { /* nop */ } + + @Override + public final void destroy(ProxySurface s) { /* nop */ } + + @Override + public final int getWidth(ProxySurface s) { + return clientArea.width; + } + + @Override + public final int getHeight(ProxySurface s) { + return clientArea.height; + } + + @Override + public String toString() { + return "SETUpstreamSurfaceHook[upstream: "+GLCanvas.this.toString()+"]"; + } + + }; + + protected final void updateSizeCheck() { + clientArea = GLCanvas.this.getClientArea(); + if (clientArea != null && + proxySurface.getWidth() != clientArea.width && + proxySurface.getHeight() != clientArea.height) { + sendReshape = true; // Mark for OpenGL reshape next time the control is painted + } + sendReshape = false; + } + + @Override + public final Object getUpstreamWidget() { + return this; + } + + @Override + public int getWidth() { + return clientArea.width; + } + + @Override + public int getHeight() { + return clientArea.height; + } @Override public void addGLEventListener(final GLEventListener arg0) { @@ -417,25 +465,11 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { return (drawable != null) ? drawable.getHandle() : 0; } - @Override - public int getHeight() { - final Rectangle clientArea = this.clientArea; - if (clientArea == null) return 0; - return clientArea.height; - } - @Override public NativeSurface getNativeSurface() { return (drawable != null) ? drawable.getNativeSurface() : null; } - @Override - public int getWidth() { - final Rectangle clientArea = this.clientArea; - if (clientArea == null) return 0; - return clientArea.width; - } - @Override public boolean isRealized() { return (drawable != null) ? drawable.isRealized() : false; @@ -515,7 +549,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { // System.err.println(NativeWindowVersion.getInstance()); System.err.println(JoglVersion.getInstance()); - System.err.println(JoglVersion.getDefaultOpenGLInfo(null, true).toString()); + System.err.println(JoglVersion.getDefaultOpenGLInfo(null, null, true).toString()); final GLCapabilitiesImmutable caps = new GLCapabilities( GLProfile.getDefault(GLProfile.getDefaultDevice()) ); final Display display = new Display(); diff --git a/src/jogl/classes/com/jogamp/opengl/util/FBObject.java b/src/jogl/classes/com/jogamp/opengl/util/FBObject.java deleted file mode 100644 index 3e049a334..000000000 --- a/src/jogl/classes/com/jogamp/opengl/util/FBObject.java +++ /dev/null @@ -1,483 +0,0 @@ -/* - * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright (c) 2011 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. - * - */ - -package com.jogamp.opengl.util; - -import javax.media.opengl.*; - -public class FBObject { - static final int MAX_FBO_TEXTURES = 32; // just for our impl .. not the real 'max' FBO color attachments - private int[] fbo_tex_names; - private int[] fbo_tex_units; - private int fbo_tex_num; - private int colorattachment_num; - - private boolean initialized; - private int width, height; - private int fb, depth_rb, stencil_rb, vStatus; - private boolean bound; - - public FBObject(int width, int height) { - this.fbo_tex_names = new int[MAX_FBO_TEXTURES]; - this.fbo_tex_units = new int[MAX_FBO_TEXTURES]; - this.fbo_tex_num = 0; - this.colorattachment_num = 0; - this.initialized = false; - this.width = width; - this.height = height; - this.fb = 0; - this.depth_rb = 0; - this.stencil_rb = 0; - this.bound = false; - } - - /** - * @return true if the FB status is valid, otherwise false - * @see #getStatus() - */ - public boolean isStatusValid() { - switch(vStatus) { - case GL.GL_FRAMEBUFFER_COMPLETE: - return true; - case GL.GL_FRAMEBUFFER_UNSUPPORTED: - case GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - case GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - case GL.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - case GL.GL_FRAMEBUFFER_INCOMPLETE_FORMATS: - //case GL2.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: - //case GL2.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: - //case GL2.GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT: - case 0: - default: - System.out.println("Framebuffer " + fb + " is incomplete: status = 0x" + Integer.toHexString(vStatus) + - " : " + getStatusString(vStatus)); - return false; - } - } - - /** - * @return The FB status. {@link GL.GL_FRAMEBUFFER_COMPLETE} if ok, otherwise return GL FBO error state or -1 - * @see #validateStatus() - */ - public int getStatus() { - return vStatus; - } - - public String getStatusString() { - return getStatusString(vStatus); - } - - public static final String getStatusString(int fbStatus) { - switch(fbStatus) { - case -1: - return "NOT A FBO"; - case GL.GL_FRAMEBUFFER_COMPLETE: - return "OK"; - case GL.GL_FRAMEBUFFER_UNSUPPORTED: - return("GL FBO: Unsupported framebuffer format"); - case GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - return("GL FBO: incomplete, incomplete attachment\n"); - case GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - return("GL FBO: incomplete, missing attachment"); - case GL.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - return("GL FBO: incomplete, attached images must have same dimensions"); - case GL.GL_FRAMEBUFFER_INCOMPLETE_FORMATS: - return("GL FBO: incomplete, attached images must have same format"); - case GL2.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: - return("GL FBO: incomplete, missing draw buffer"); - case GL2.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: - return("GL FBO: incomplete, missing read buffer"); - case GL2.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: - return("GL FBO: incomplete, missing multisample buffer"); - case 0: - return("GL FBO: incomplete, implementation fault"); - default: - return("GL FBO: incomplete, implementation ERROR"); - } - } - - private boolean checkNoError(GL gl, int err, String exceptionMessage) { - if(GL.GL_NO_ERROR != err) { - if(null != gl) { - destroy(gl); - } - if(null != exceptionMessage) { - throw new GLException(exceptionMessage+" GL Error 0x"+Integer.toHexString(err)); - } - return false; - } - return true; - } - - private final void checkInitialized() { - if(!initialized) { - throw new GLException("FBO not initialized, call init(GL) first."); - } - } - - private final void checkBound(GL gl, boolean shallBeBound) { - checkInitialized(); - if(bound != shallBeBound) { - final String s0 = shallBeBound ? "not" : "already" ; - throw new GLException("FBO "+s0+" bound "+toString()); - } - checkNoError(null, gl.glGetError(), "FBObject pre"); // throws GLException if error - } - - /** - * Initializes this FBO's instance with it's texture. - * - *

Leaves the FBO bound!

- * - * @param gl the current GL context - * @throws GLException in case of an error - */ - public void init(GL gl) throws GLException { - if(initialized) { - throw new GLException("FBO already initialized"); - } - checkNoError(null, gl.glGetError(), "FBObject Init.pre"); // throws GLException if error - - // generate fbo .. - int name[] = new int[1]; - - gl.glGenFramebuffers(1, name, 0); - fb = name[0]; - if(fb==0) { - throw new GLException("null generated framebuffer"); - } - - // bind fbo .. - gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, fb); - checkNoError(gl, gl.glGetError(), "FBObject Init.bindFB"); // throws GLException if error - if(!gl.glIsFramebuffer(fb)) { - checkNoError(gl, GL.GL_INVALID_VALUE, "FBObject Init.isFB"); // throws GLException - } - bound = true; - initialized = true; - - updateStatus(gl); - } - - /** - * Attaches a[nother] Texture2D Color Buffer to this FBO's instance, - * selecting the texture data type and format automatically. - *

This may be done as many times as many color attachments are supported, - * see {@link GL2GL3#GL_MAX_COLOR_ATTACHMENTS}.

- * - *

Assumes a bound FBO

- *

Leaves the FBO bound!

- * - * @param gl the current GL context - * @param texUnit the desired texture unit ranging from [0..{@link GL2#GL_MAX_TEXTURE_UNITS}-1], or -1 if no unit shall be activate at {@link #use(GL, int)} - * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER} - * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} - * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S} - * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} - * @return idx of the new attached texture, otherwise -1 - * @throws GLException in case of an error - */ - public int attachTexture2D(GL gl, int texUnit, int magFilter, int minFilter, int wrapS, int wrapT) throws GLException { - final int textureInternalFormat, textureDataFormat, textureDataType; - if(gl.isGLES()) { - textureInternalFormat=GL.GL_RGBA; - textureDataFormat=GL.GL_RGBA; - textureDataType=GL.GL_UNSIGNED_BYTE; - } else { - textureInternalFormat=GL.GL_RGBA8; - textureDataFormat=GL.GL_BGRA; - textureDataType=GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV; - } - return attachTexture2D(gl, texUnit, textureInternalFormat, textureDataFormat, textureDataType, magFilter, minFilter, wrapS, wrapT); - } - - /** - * Attaches a[nother] Texture2D Color Buffer to this FBO's instance, - * selecting the texture data type and format automatically. - *

This may be done as many times as many color attachments are supported, - * see {@link GL2GL3#GL_MAX_COLOR_ATTACHMENTS}.

- * - *

Assumes a bound FBO

- *

Leaves the FBO bound!

- * - * @param gl the current GL context - * @param texUnit the desired texture unit ranging from [0..{@link GL2#GL_MAX_TEXTURE_UNITS}-1], or -1 if no unit shall be activate at {@link #use(GL, int)} - * @param textureInternalFormat internalFormat parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} - * @param textureDataFormat format parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} - * @param textureDataType type parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} - * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER} - * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} - * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S} - * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} - * @return index of the texture colorbuffer if bound and configured successfully, otherwise -1 - * @throws GLException in case the texture colorbuffer couldn't be allocated - */ - public int attachTexture2D(GL gl, int texUnit, - int textureInternalFormat, int textureDataFormat, int textureDataType, - int magFilter, int minFilter, int wrapS, int wrapT) throws GLException { - checkBound(gl, true); - final int fbo_tex_idx = fbo_tex_num; - gl.glGenTextures(1, fbo_tex_names, fbo_tex_num); - if(fbo_tex_names[fbo_tex_idx]==0) { - throw new GLException("null generated texture"); - } - fbo_tex_units[fbo_tex_idx] = texUnit; - fbo_tex_num++; - if(0<=texUnit) { - gl.glActiveTexture(GL.GL_TEXTURE0 + texUnit); - } - gl.glBindTexture(GL.GL_TEXTURE_2D, fbo_tex_names[fbo_tex_idx]); - checkNoError(gl, gl.glGetError(), "FBObject Init.bindTex"); // throws GLException if error - gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, textureInternalFormat, width, height, 0, - textureDataFormat, textureDataType, null); - int glerr = gl.glGetError(); - if(GL.GL_NO_ERROR != glerr) { - int[] sz = new int[1]; - gl.glGetIntegerv(GL.GL_MAX_TEXTURE_SIZE, sz, 0); - // throws GLException if error - checkNoError(gl, glerr, "FBObject Init.texImage2D: "+ - " int-fmt 0x"+Integer.toHexString(textureInternalFormat)+ - ", "+width+"x"+height+ - ", data-fmt 0x"+Integer.toHexString(textureDataFormat)+ - ", data-type 0x"+Integer.toHexString(textureDataType)+ - ", max tex-sz "+sz[0]); - } - if( 0 < magFilter ) { - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, magFilter); - } - if( 0 < minFilter ) { - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, minFilter); - } - if( 0 < wrapS ) { - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, wrapS); - } - if( 0 < wrapT ) { - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, wrapT); - } - - // Set up the color buffer for use as a renderable texture: - gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, - GL.GL_COLOR_ATTACHMENT0 + colorattachment_num++, - GL.GL_TEXTURE_2D, fbo_tex_names[fbo_tex_idx], 0); - - updateStatus(gl); - return isStatusValid() ? fbo_tex_idx : -1; - } - - /** - * Attaches one Depth Buffer to this FBO's instance. - *

This may be done only one time.

- * - *

Assumes a bound FBO

- *

Leaves the FBO bound!

- * @param gl the current GL context - * @param depthComponentType {@link GL#GL_DEPTH_COMPONENT16}, {@link GL#GL_DEPTH_COMPONENT24} or {@link GL#GL_DEPTH_COMPONENT32} - * @return true if the depth renderbuffer could be bound and configured, otherwise false - * @throws GLException in case the depth renderbuffer couldn't be allocated or one is already attached. - */ - public boolean attachDepthBuffer(GL gl, int depthComponentType) throws GLException { - checkBound(gl, true); - if(depth_rb != 0) { - throw new GLException("FBO depth buffer already attached (rb "+depth_rb+")"); - } - int name[] = new int[1]; - gl.glGenRenderbuffers(1, name, 0); - depth_rb = name[0]; - if(depth_rb==0) { - throw new GLException("null generated renderbuffer"); - } - // Initialize the depth buffer: - gl.glBindRenderbuffer(GL.GL_RENDERBUFFER, depth_rb); - if(!gl.glIsRenderbuffer(depth_rb)) { - System.err.println("not a depthbuffer: "+ depth_rb); - name[0] = depth_rb; - gl.glDeleteRenderbuffers(1, name, 0); - depth_rb=0; - return false; - } - - gl.glRenderbufferStorage(GL.GL_RENDERBUFFER, depthComponentType, width, height); - // Set up the depth buffer attachment: - gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, - GL.GL_DEPTH_ATTACHMENT, - GL.GL_RENDERBUFFER, depth_rb); - updateStatus(gl); - return isStatusValid(); - } - - /** - * Attaches one Stencil Buffer to this FBO's instance. - *

This may be done only one time.

- * - *

Assumes a bound FBO

- *

Leaves the FBO bound!

- * @param gl the current GL context - * @param stencilComponentType {@link GL#GL_STENCIL_INDEX1}, {@link GL#GL_STENCIL_INDEX4} or {@link GL#GL_STENCIL_INDEX8} - * @return true if the stencil renderbuffer could be bound and configured, otherwise false - * @throws GLException in case the stencil renderbuffer couldn't be allocated or one is already attached. - */ - public boolean attachStencilBuffer(GL gl, int stencilComponentType) throws GLException { - checkBound(gl, true); - if(stencil_rb != 0) { - throw new GLException("FBO stencil buffer already attached (rb "+stencil_rb+")"); - } - int name[] = new int[1]; - gl.glGenRenderbuffers(1, name, 0); - stencil_rb = name[0]; - if(stencil_rb==0) { - throw new GLException("null generated stencilbuffer"); - } - // Initialize the stencil buffer: - gl.glBindRenderbuffer(GL.GL_RENDERBUFFER, stencil_rb); - if(!gl.glIsRenderbuffer(stencil_rb)) { - System.err.println("not a stencilbuffer: "+ stencil_rb); - name[0] = stencil_rb; - gl.glDeleteRenderbuffers(1, name, 0); - stencil_rb=0; - return false; - } - gl.glRenderbufferStorage(GL.GL_RENDERBUFFER, stencilComponentType, width, height); - gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, - GL.GL_STENCIL_ATTACHMENT, - GL.GL_RENDERBUFFER, stencil_rb); - updateStatus(gl); - return isStatusValid(); - } - - /** - * @param gl the current GL context - */ - public void destroy(GL gl) { - if(bound) { - unbind(gl); - } - - int name[] = new int[1]; - - if(0!=stencil_rb) { - name[0] = stencil_rb; - gl.glDeleteRenderbuffers(1, name, 0); - stencil_rb = 0; - } - if(0!=depth_rb) { - name[0] = depth_rb; - gl.glDeleteRenderbuffers(1, name, 0); - depth_rb=0; - } - if(null!=fbo_tex_names && fbo_tex_num>0) { - gl.glDeleteTextures(1, fbo_tex_names, fbo_tex_num); - fbo_tex_names = new int[MAX_FBO_TEXTURES]; - fbo_tex_units = new int[MAX_FBO_TEXTURES]; - fbo_tex_num = 0; - } - colorattachment_num = 0; - if(0!=fb) { - name[0] = fb; - gl.glDeleteFramebuffers(1, name, 0); - fb = 0; - } - initialized = false; - } - - /** - * Bind this FBO - *

In case you have attached more than one color buffer, - * you may want to setup {@link GL2GL3#glDrawBuffers(int, int[], int)}.

- * @param gl the current GL context - */ - public void bind(GL gl) { - checkBound(gl, false); - gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, fb); - bound = true; - } - - /** - * Unbind FBO, ie bind 'non' FBO 0 - * @param gl the current GL context - */ - public void unbind(GL gl) { - checkBound(gl, true); - gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); - bound = false; - } - - /** - * Bind the texture with given index. - * - *

If a valid texture unit was named via {@link #attachTexture2D(GL, int, int, int, int, int) attachTexture2D(..)}, - * the unit is activated via {@link GL#glActiveTexture(int) glActiveTexture(GL.GL_TEXTURE0 + unit)}.

- * @param gl the current GL context - * @param texIdx index of the texture to use, prev. attached w/ {@link #attachTexture2D(GL, int, int, int, int, int) attachTexture2D(..)} - */ - public void use(GL gl, int texIdx) { - checkBound(gl, false); - if(texIdx >= fbo_tex_num) { - throw new GLException("Invalid texId, only "+fbo_tex_num+" textures are attached"); - } - if(0<=fbo_tex_units[texIdx]) { - gl.glActiveTexture(GL.GL_TEXTURE0 + fbo_tex_units[texIdx]); - } - gl.glBindTexture(GL.GL_TEXTURE_2D, fbo_tex_names[texIdx]); // use it .. - } - - /** Unbind texture, ie bind 'non' texture 0 */ - public void unuse(GL gl) { - checkBound(gl, false); - gl.glBindTexture(GL.GL_TEXTURE_2D, 0); // don't use it - } - - public final boolean isBound() { return bound; } - public final int getWidth() { return width; } - public final int getHeight() { return height; } - public final int getFBName() { return fb; } - public final int getTextureNumber() { return fbo_tex_num; } - public final int getTextureName(int idx) { return fbo_tex_names[idx]; } - - /** @return the named texture unit ranging from [0..{@link GL2#GL_MAX_TEXTURE_UNITS}-1], or -1 if no unit was desired. */ - public final int getTextureUnit(int idx) { return fbo_tex_units[idx]; } - public final int getColorAttachmentNumber() { return colorattachment_num; } - public final int getStencilBuffer() { return stencil_rb; } - public final int getDepthBuffer() { return depth_rb; } - public final String toString() { - return "FBO[name "+fb+", size "+width+"x"+height+", color num "+colorattachment_num+", tex num "+fbo_tex_num+", depth "+depth_rb+", stencil "+stencil_rb+"]"; - } - - private void updateStatus(GL gl) { - if(!gl.glIsFramebuffer(fb)) { - vStatus = -1; - } else { - vStatus = gl.glCheckFramebufferStatus(GL.GL_FRAMEBUFFER); - } - } -} diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java b/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java index 8401b9cd2..331d6fa4e 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java @@ -39,6 +39,7 @@ package com.jogamp.opengl.util; import com.jogamp.common.nio.Buffers; + import javax.media.opengl.GL; import javax.media.opengl.GL2; import javax.media.opengl.GL2ES2; @@ -56,22 +57,32 @@ import java.nio.*; public class GLBuffers extends Buffers { /** - * @param glType shall be one of - * GL_UNSIGNED_BYTE, GL_BYTE, GL_UNSIGNED_SHORT, GL_SHORT, - * GL_UNSIGNED_INT, GL_INT, GL_HALF_FLOAT, GL_FLOAT, GL_DOUBLE, - * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV, - * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV, - * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV, - * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV, - * GL_UNSIGNED_INT_8_8_8_8, GL_UNSIGNED_INT_8_8_8_8_REV, - * GL_UNSIGNED_INT_10_10_10_2, GL_UNSIGNED_INT_2_10_10_10_REV - * GL_UNSIGNED_INT_24_8, GL_UNSIGNED_INT_10F_11F_11F_REV, - * GL_UNSIGNED_INT_5_9_9_9_REV, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, - * GL_HILO16_NV, GL_SIGNED_HILO16_NV (27) + * @param glType shall be one of (29)
+ * GL_BYTE, GL_UNSIGNED_BYTE,
+ * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV,
+ *
+ * GL_SHORT, GL_UNSIGNED_SHORT,
+ * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
+ * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV,
+ * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV,
+ * GL.GL_HALF_FLOAT, GLES2.GL_HALF_FLOAT_OES:
+ *
+ * GL_FIXED, GL_INT
+ * GL_UNSIGNED_INT, GL_UNSIGNED_INT_8_8_8_8,
+ * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
+ * GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_24_8,
+ * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
+ * GL_HILO16_NV, GL_SIGNED_HILO16_NV
+ *
+ * GL2GL3.GL_FLOAT_32_UNSIGNED_INT_24_8_REV
+ *
+ * GL_FLOAT, GL_DOUBLE
+ * * @return -1 if glType is unhandled, otherwise the actual value > 0 */ public static final int sizeOfGLType(int glType) { - switch (glType) { // 25 + switch (glType) { // 29 + // case GL2.GL_BITMAP: case GL.GL_BYTE: case GL.GL_UNSIGNED_BYTE: case GL2GL3.GL_UNSIGNED_BYTE_3_3_2: @@ -86,6 +97,8 @@ public class GLBuffers extends Buffers { case GL2GL3.GL_UNSIGNED_SHORT_4_4_4_4_REV: case GL2GL3.GL_UNSIGNED_SHORT_5_5_5_1: case GL2GL3.GL_UNSIGNED_SHORT_1_5_5_5_REV: + case GL.GL_HALF_FLOAT: + case GLES2.GL_HALF_FLOAT_OES: return SIZEOF_SHORT; case GL.GL_FIXED: @@ -108,29 +121,38 @@ public class GLBuffers extends Buffers { case GL.GL_FLOAT: return SIZEOF_FLOAT; - case GL2.GL_DOUBLE: + case GL2GL3.GL_DOUBLE: return SIZEOF_DOUBLE; } return -1; } /** - * @param glType shall be one of - * GL_UNSIGNED_BYTE, GL_BYTE, GL_UNSIGNED_SHORT, GL_SHORT, - * GL_UNSIGNED_INT, GL_INT, GL_HALF_FLOAT, GL_FLOAT, GL_DOUBLE, - * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV, - * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV, - * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV, - * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV, - * GL_UNSIGNED_INT_8_8_8_8, GL_UNSIGNED_INT_8_8_8_8_REV, - * GL_UNSIGNED_INT_10_10_10_2, GL_UNSIGNED_INT_2_10_10_10_REV - * GL_UNSIGNED_INT_24_8, GL_UNSIGNED_INT_10F_11F_11F_REV, - * GL_UNSIGNED_INT_5_9_9_9_REV, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, - * GL_HILO16_NV, GL_SIGNED_HILO16_NV (27) + * @param glType shall be one of (29)
+ * GL_BYTE, GL_UNSIGNED_BYTE,
+ * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV,
+ *
+ * GL_SHORT, GL_UNSIGNED_SHORT,
+ * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
+ * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV,
+ * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV,
+ * GL_HALF_FLOAT, GL_HALF_FLOAT_OES
+ *
+ * GL_FIXED, GL_INT
+ * GL_UNSIGNED_INT, GL_UNSIGNED_INT_8_8_8_8,
+ * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
+ * GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_24_8,
+ * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
+ * GL_HILO16_NV, GL_SIGNED_HILO16_NV
+ *
+ * GL_FLOAT_32_UNSIGNED_INT_24_8_REV
+ *
+ * GL_FLOAT, GL_DOUBLE
+ * * @return null if glType is unhandled, otherwise the new Buffer object */ public static final Buffer newDirectGLBuffer(int glType, int numElements) { - switch (glType) { + switch (glType) { // 29 case GL.GL_BYTE: case GL.GL_UNSIGNED_BYTE: case GL2GL3.GL_UNSIGNED_BYTE_3_3_2: @@ -145,6 +167,8 @@ public class GLBuffers extends Buffers { case GL2GL3.GL_UNSIGNED_SHORT_4_4_4_4_REV: case GL2GL3.GL_UNSIGNED_SHORT_5_5_5_1: case GL2GL3.GL_UNSIGNED_SHORT_1_5_5_5_REV: + case GL.GL_HALF_FLOAT: + case GLES2.GL_HALF_FLOAT_OES: return newDirectShortBuffer(numElements); case GL.GL_FIXED: @@ -174,18 +198,26 @@ public class GLBuffers extends Buffers { } /** - * @param glType shall be one of - * GL_UNSIGNED_BYTE, GL_BYTE, GL_UNSIGNED_SHORT, GL_SHORT, - * GL_UNSIGNED_INT, GL_INT, GL_HALF_FLOAT, GL_FLOAT, GL_DOUBLE, - * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV, - * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV, - * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV, - * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV, - * GL_UNSIGNED_INT_8_8_8_8, GL_UNSIGNED_INT_8_8_8_8_REV, - * GL_UNSIGNED_INT_10_10_10_2, GL_UNSIGNED_INT_2_10_10_10_REV - * GL_UNSIGNED_INT_24_8, GL_UNSIGNED_INT_10F_11F_11F_REV, - * GL_UNSIGNED_INT_5_9_9_9_REV, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, - * GL_HILO16_NV, GL_SIGNED_HILO16_NV (27) + * @param glType shall be one of (29)
+ * GL_BYTE, GL_UNSIGNED_BYTE,
+ * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV,
+ *
+ * GL_SHORT, GL_UNSIGNED_SHORT,
+ * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
+ * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV,
+ * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV,
+ * GL_HALF_FLOAT, GL_HALF_FLOAT_OES
+ *
+ * GL_FIXED, GL_INT
+ * GL_UNSIGNED_INT, GL_UNSIGNED_INT_8_8_8_8,
+ * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
+ * GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_24_8,
+ * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
+ * GL_HILO16_NV, GL_SIGNED_HILO16_NV
+ *
+ * GL_FLOAT_32_UNSIGNED_INT_24_8_REV
+ *
+ * GL_FLOAT, GL_DOUBLE
* @return null if glType is unhandled or parent is null or bufLen is 0, otherwise the new Buffer object */ public static final Buffer sliceGLBuffer(ByteBuffer parent, int bytePos, int byteLen, int glType) { @@ -195,7 +227,7 @@ public class GLBuffers extends Buffers { parent.position(bytePos); parent.limit(bytePos + byteLen); - switch (glType) { + switch (glType) { // 29 case GL.GL_BYTE: case GL.GL_UNSIGNED_BYTE: case GL2GL3.GL_UNSIGNED_BYTE_3_3_2: @@ -210,6 +242,8 @@ public class GLBuffers extends Buffers { case GL2GL3.GL_UNSIGNED_SHORT_4_4_4_4_REV: case GL2GL3.GL_UNSIGNED_SHORT_5_5_5_1: case GL2GL3.GL_UNSIGNED_SHORT_1_5_5_5_REV: + case GL.GL_HALF_FLOAT: + case GLES2.GL_HALF_FLOAT_OES: return parent.asShortBuffer(); case GL.GL_FIXED: @@ -362,28 +396,46 @@ public class GLBuffers extends Buffers { * * @param tmp a pass through integer array of size >= 1 used to store temp data (performance) * - * @param format must be one of - * GL_COLOR_INDEX, GL_STENCIL_INDEX, GL_DEPTH_COMPONENT, GL_DEPTH_STENCIL, - * GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, GL_LUMINANCE, - * GL_RG, GL_LUMINANCE_ALPHA, - * GL_RGB, GL_BGR, GL_RGBA, GL_BGRA, GL_ABGR_EXT, - * GL_RED_INTEGER, GL_GREEN_INTEGER, GL_BLUE_INTEGER, - * GL_RG_INTEGER, GL_RGB_INTEGER, GL_BGR_INTEGER, - * GL_RGBA_INTEGER, GL_BGRA_INTEGER, GL_HILO_NV, GL_SIGNED_HILO_NV (26) + * @param format must be one of (26)
+ * GL_COLOR_INDEX GL_STENCIL_INDEX
+ * GL_DEPTH_COMPONENT GL_DEPTH_STENCIL
+ * GL_RED GL_RED_INTEGER
+ * GL_GREEN GL_GREEN_INTEGER
+ * GL_BLUE GL_BLUE_INTEGER
+ * GL_ALPHA GL_LUMINANCE (12)
+ *
+ * GL_LUMINANCE_ALPHA GL_RG
+ * GL_RG_INTEGER GL_HILO_NV
+ * GL_SIGNED_HILO_NV (5)
+ *
+ * GL_RGB GL_RGB_INTEGER
+ * GL_BGR GL_BGR_INTEGER (4)
+ *
+ * GL_RGBA GL_RGBA_INTEGER
+ * GL_BGRA GL_BGRA_INTEGER
+ * GL_ABGR_EXT (5)
* - * @param type must be one of - * GL_BITMAP, - * GL_UNSIGNED_BYTE, GL_BYTE, GL_UNSIGNED_SHORT, GL_SHORT, - * GL_UNSIGNED_INT, GL_INT, GL_HALF_FLOAT, GL_FLOAT, GL_DOUBLE, - * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV, - * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV, - * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV, - * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV, - * GL_UNSIGNED_INT_8_8_8_8, GL_UNSIGNED_INT_8_8_8_8_REV, - * GL_UNSIGNED_INT_10_10_10_2, GL_UNSIGNED_INT_2_10_10_10_REV - * GL_UNSIGNED_INT_24_8, GL_UNSIGNED_INT_10F_11F_11F_REV, - * GL_UNSIGNED_INT_5_9_9_9_REV, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, - * GL_HILO16_NV, GL_SIGNED_HILO16_NV (28) + * @param type must be one of (30)
+ * GL_BITMAP,
+ * GL_BYTE, GL_UNSIGNED_BYTE,
+ * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV,
+ *
+ * GL_SHORT, GL_UNSIGNED_SHORT,
+ * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
+ * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV,
+ * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV,
+ * GL_HALF_FLOAT, GL_HALF_FLOAT_OES
+ *
+ * GL_FIXED, GL_INT
+ * GL_UNSIGNED_INT, GL_UNSIGNED_INT_8_8_8_8,
+ * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
+ * GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_24_8,
+ * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
+ * GL_HILO16_NV, GL_SIGNED_HILO16_NV
+ *
+ * GL_FLOAT_32_UNSIGNED_INT_24_8_REV
+ *
+ * GL_FLOAT, GL_DOUBLE
* * @param width in pixels * @param height in pixels @@ -402,7 +454,7 @@ public class GLBuffers extends Buffers { if (height < 0) return 0; if (depth < 0) return 0; - switch (format) /* 24 */ { + switch (format) /* 26 */ { case GL2.GL_COLOR_INDEX: case GL2GL3.GL_STENCIL_INDEX: case GL2GL3.GL_DEPTH_COMPONENT: @@ -445,7 +497,7 @@ public class GLBuffers extends Buffers { throw new GLException("format 0x"+Integer.toHexString(format)+" not supported [yet], pls notify the maintainer in case this is our bug."); } - switch (type) /* 26 */ { + switch (type) /* 30 */ { case GL2.GL_BITMAP: if (GL2.GL_COLOR_INDEX == format || GL2GL3.GL_STENCIL_INDEX == format) { return (depth * (height * ((width+7)/8))); @@ -460,6 +512,7 @@ public class GLBuffers extends Buffers { case GLES2.GL_HALF_FLOAT_OES: esize = 2; break; + case GL.GL_FIXED: case GL2ES2.GL_INT: case GL.GL_UNSIGNED_INT: case GL.GL_FLOAT: diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java b/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java index 368cbc0a2..b0fae8a6d 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java @@ -35,6 +35,7 @@ import java.io.IOException; import java.nio.*; import javax.media.opengl.*; +import com.jogamp.opengl.GLExtensions; import com.jogamp.opengl.util.texture.Texture; import com.jogamp.opengl.util.texture.TextureData; import com.jogamp.opengl.util.texture.TextureIO; @@ -67,6 +68,10 @@ public class GLReadBufferUtil { return null!=readTextureData && null!=readPixelBuffer ; } + public boolean hasAlpha() { return 4 == components ? true : false ; } + + public GLPixelStorageModes getGLPixelStorageModes() { return psm; } + /** * @return the raw pixel ByteBuffer, filled by {@link #readPixels(GLAutoDrawable, boolean)} */ @@ -104,13 +109,14 @@ public class GLReadBufferUtil { /** * Read the drawable's pixels to TextureData and Texture, if requested at construction * - * @param gl the current GL object + * @param gl the current GL context object. It's read drawable is being used as the pixel source. * @param drawable the drawable to read from * @param flip weather to flip the data vertically or not * * @see #GLReadBufferUtil(boolean, boolean) */ - public boolean readPixels(GL gl, GLDrawable drawable, boolean flip) { + public boolean readPixels(GL gl, boolean flip) { + final GLDrawable drawable = gl.getContext().getGLReadDrawable(); final int textureInternalFormat, textureDataFormat, textureDataType; final int[] glImplColorReadVals = new int[] { 0, 0 }; @@ -118,7 +124,7 @@ public class GLReadBufferUtil { textureInternalFormat=GL.GL_RGB; textureDataFormat=GL.GL_RGB; textureDataType = GL.GL_UNSIGNED_BYTE; - } else if(gl.isGLES2Compatible() || gl.isExtensionAvailable("GL_OES_read_format")) { + } else if(gl.isGLES2Compatible() || gl.isExtensionAvailable(GLExtensions.OES_read_format)) { gl.glGetIntegerv(GL.GL_IMPLEMENTATION_COLOR_READ_FORMAT, glImplColorReadVals, 0); gl.glGetIntegerv(GL.GL_IMPLEMENTATION_COLOR_READ_TYPE, glImplColorReadVals, 1); textureInternalFormat = (4 == components) ? GL.GL_RGBA : GL.GL_RGB; diff --git a/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java b/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java index 3b817afcf..cf0373044 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java +++ b/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java @@ -1,15 +1,20 @@ package com.jogamp.opengl.util; -import com.jogamp.common.util.*; -import com.jogamp.opengl.util.glsl.ShaderState; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.ShortBuffer; +import java.util.ArrayList; +import java.util.Iterator; -import javax.media.opengl.*; -import javax.media.opengl.fixedfunc.*; +import javax.media.opengl.GL; +import javax.media.opengl.GL2ES1; +import javax.media.opengl.GL2ES2; +import javax.media.opengl.GLException; +import javax.media.opengl.fixedfunc.GLPointerFunc; -import java.nio.*; -import java.util.Iterator; -import java.util.ArrayList; +import com.jogamp.common.util.ReflectionUtil; +import com.jogamp.opengl.util.glsl.ShaderState; public class ImmModeSink { @@ -337,10 +342,8 @@ public class ImmModeSink { enableBuffer(gl, true); if (buffer!=null) { - GL2ES1 glf = gl.getGL2ES1(); - if(null==indices) { - glf.glDrawArrays(mode, 0, count); + gl.glDrawArrays(mode, 0, count); } else { Class clazz = indices.getClass(); int type=-1; @@ -352,7 +355,7 @@ public class ImmModeSink { if(0>type) { throw new GLException("Given Buffer Class not supported: "+clazz+", should be ubyte or ushort:\n\t"+this); } - glf.glDrawElements(mode, indices.remaining(), type, indices); + gl.glDrawElements(mode, indices.remaining(), type, indices); // GL2: gl.glDrawRangeElements(mode, 0, indices.remaining()-1, indices.remaining(), type, indices); } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/Screenshot.java b/src/jogl/classes/com/jogamp/opengl/util/awt/Screenshot.java index fa66673fd..0022d5c2d 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/Screenshot.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/Screenshot.java @@ -48,6 +48,7 @@ import javax.media.opengl.GLException; import javax.media.opengl.glu.gl2.GLUgl2; import com.jogamp.common.util.IOUtil; +import com.jogamp.opengl.GLExtensions; import com.jogamp.opengl.util.GLPixelStorageModes; import com.jogamp.opengl.util.TGAWriter; @@ -392,7 +393,7 @@ public class Screenshot { private static void checkExtABGR() { GL2 gl = GLUgl2.getCurrentGL2(); - if (!gl.isExtensionAvailable("GL_EXT_abgr")) { + if (!gl.isExtensionAvailable(GLExtensions.EXT_abgr)) { throw new IllegalArgumentException("Saving alpha channel requires GL_EXT_abgr"); } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java index 622ee1b79..1735fcddd 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java @@ -41,6 +41,7 @@ package com.jogamp.opengl.util.awt; import com.jogamp.common.nio.Buffers; +import com.jogamp.opengl.GLExtensions; import com.jogamp.opengl.util.*; import com.jogamp.opengl.util.packrect.*; import com.jogamp.opengl.util.texture.*; @@ -1976,7 +1977,7 @@ public class TextRenderer { private final boolean is15Available(GL gl) { if (!checkFor_isExtensionAvailable_GL_VERSION_1_5) { - isExtensionAvailable_GL_VERSION_1_5 = gl.isExtensionAvailable("GL_VERSION_1_5"); + isExtensionAvailable_GL_VERSION_1_5 = gl.isExtensionAvailable(GLExtensions.VERSION_1_5); checkFor_isExtensionAvailable_GL_VERSION_1_5 = true; } return isExtensionAvailable_GL_VERSION_1_5; diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java b/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java index 49d4add5f..e7bf87a36 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java @@ -44,6 +44,7 @@ import javax.media.nativewindow.NativeWindowFactory; import jogamp.opengl.*; +import com.jogamp.opengl.GLExtensions; import com.jogamp.opengl.util.texture.spi.*; /** @@ -262,8 +263,8 @@ public class Texture { * * See the
performance tips above for hints * on how to maximize performance when using many Texture objects. - * @param gl TODO - * + * + * @param gl the current GL context * @throws GLException if no OpenGL context was current or if any * OpenGL-related errors occurred */ @@ -448,12 +449,12 @@ public class Texture { // See whether we have automatic mipmap generation support boolean haveAutoMipmapGeneration = - (gl.isExtensionAvailable("GL_VERSION_1_4") || - gl.isExtensionAvailable("GL_SGIS_generate_mipmap")); + (gl.isExtensionAvailable(GLExtensions.VERSION_1_4) || + gl.isExtensionAvailable(GLExtensions.SGIS_generate_mipmap)); // Indicate to the TextureData what functionality is available - data.setHaveEXTABGR(gl.isExtensionAvailable("GL_EXT_abgr")); - data.setHaveGL12(gl.isExtensionAvailable("GL_VERSION_1_2")); + data.setHaveEXTABGR(gl.isExtensionAvailable(GLExtensions.EXT_abgr)); + data.setHaveGL12(gl.isExtensionAvailable(GLExtensions.VERSION_1_2)); // Indicates whether both width and height are power of two boolean isPOT = isPowerOfTwo(imgWidth) && isPowerOfTwo(imgHeight); @@ -646,7 +647,7 @@ public class Texture { int minFilter = (data.getMipmap() ? GL.GL_LINEAR_MIPMAP_LINEAR : GL.GL_LINEAR); int magFilter = GL.GL_LINEAR; - int wrapMode = (gl.isExtensionAvailable("GL_VERSION_1_2") || !gl.isGL2()) ? GL.GL_CLAMP_TO_EDGE : GL2.GL_CLAMP; + int wrapMode = (gl.isExtensionAvailable(GLExtensions.VERSION_1_2) || !gl.isGL2()) ? GL.GL_CLAMP_TO_EDGE : GL2.GL_CLAMP; // REMIND: figure out what to do for GL_TEXTURE_RECTANGLE_ARB if (texTarget != GL2.GL_TEXTURE_RECTANGLE_ARB) { @@ -925,8 +926,8 @@ public class Texture { private void updateSubImageImpl(GL gl, TextureData data, int newTarget, int mipmapLevel, int dstx, int dsty, int srcx, int srcy, int width, int height) throws GLException { - data.setHaveEXTABGR(gl.isExtensionAvailable("GL_EXT_abgr")); - data.setHaveGL12(gl.isExtensionAvailable("GL_VERSION_1_2")); + data.setHaveEXTABGR(gl.isExtensionAvailable(GLExtensions.EXT_abgr)); + data.setHaveGL12(gl.isExtensionAvailable(GLExtensions.VERSION_1_2)); Buffer buffer = data.getBuffer(); if (buffer == null && data.getMipmapData() == null) { @@ -1044,8 +1045,8 @@ public class Texture { case GL.GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL.GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL.GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: - if (!gl.isExtensionAvailable("GL_EXT_texture_compression_s3tc") && - !gl.isExtensionAvailable("GL_NV_texture_compression_vtc")) { + if (!gl.isExtensionAvailable(GLExtensions.EXT_texture_compression_s3tc) && + !gl.isExtensionAvailable(GLExtensions.NV_texture_compression_vtc)) { throw new GLException("DXTn compressed textures not supported by this graphics card"); } break; @@ -1081,7 +1082,7 @@ public class Texture { private static boolean haveTexRect(GL gl) { return (!disableTexRect && TextureIO.isTexRectEnabled() && - gl.isExtensionAvailable("GL_ARB_texture_rectangle")); + gl.isExtensionAvailable(GLExtensions.ARB_texture_rectangle)); } private static boolean preferTexRect(GL gl) { diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java index ca97cdc4b..b878c6002 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java @@ -155,6 +155,14 @@ public class TextureIO { file. */ public static final String TIFF = "tiff"; + /** Constant which can be used as a file suffix to indicate a PAM + file, NetPbm magic 7 - binary RGB and RGBA. Write support only. */ + public static final String PAM = "pam"; + + /** Constant which can be used as a file suffix to indicate a PAM + file, NetPbm magic 6 - binary RGB. Write support only. */ + public static final String PPM = "ppm"; + private static final boolean DEBUG = Debug.debug("TextureIO"); // For manually disabling the use of the texture rectangle diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java index 5ee2104a3..6b41c0bc8 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java @@ -102,7 +102,6 @@ import javax.media.opengl.GL; */ public interface TextureSequence { public static final String GL_OES_EGL_image_external_Required_Prelude = "#extension GL_OES_EGL_image_external : enable\n"; - public static final String GL_OES_EGL_image_external = "GL_OES_EGL_image_external"; public static final String samplerExternalOES = "samplerExternalOES"; public static final String sampler2D = "sampler2D"; diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java index c2b131b97..cd42a1157 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java @@ -77,8 +77,10 @@ public class NetPbmTextureWriter implements TextureWriter { public int getMagic() { return magic; } - public static final String PPM = "ppm"; - public static final String PAM = "pam"; + /** @see TextureIO#PPM */ + public static final String PPM = TextureIO.PPM; + /** @see TextureIO#PAM */ + public static final String PAM = TextureIO.PAM; public String getSuffix() { return (magic==6)?PPM:PAM; } diff --git a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java index b57b85e5c..1b84bd9bd 100644 --- a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java +++ b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java @@ -141,7 +141,7 @@ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { for (int i = 0; i < scores.length; i++) { scores[i] = NO_SCORE; } - final int gldes_samples = gldes.getSampleBuffers() ? gldes.getNumSamples() : 0; + final int gldes_samples = gldes.getNumSamples(); // Compute score for each for (int i = 0; i < availnum; i++) { @@ -158,8 +158,7 @@ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { if (gldes.getStereo() != cur.getStereo()) { continue; } - final int cur_samples = - cur.getSampleBuffers() ? cur.getNumSamples() : 0; + final int cur_samples = cur.getNumSamples() ; int score = 0; // Compute difference in color depth diff --git a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java index 80d4f796c..0b2c664fe 100644 --- a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java +++ b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java @@ -51,8 +51,8 @@ import jogamp.opengl.Debug; 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.

- + based rendering mechanism as well by end users directly. +

The implementation shall initialize itself as soon as possible, ie if the attached {@link javax.media.nativewindow.NativeSurface NativeSurface} becomes visible/realized. The following protocol shall be satisfied: @@ -64,18 +64,18 @@ import jogamp.opengl.Debug; registered {@link GLEventListener}s. This can be done immediatly, or with the followup {@link #display display(..)} call.

  • Send a reshape event by calling {@link GLEventListener#reshape reshape(..)} for all registered {@link GLEventListener}s. This shall be done after the {@link GLEventListener#init init(..)} calls.
  • -

    - +

    +

    Another implementation detail is the drawable reconfiguration. One use case is where a window is being dragged to another screen with a different pixel configuration, ie {@link GLCapabilities}. The implementation - shall be able to detect such cases in conjunction with the associated {@link javax.media.nativewindow.NativeSurface NativeSurface}.
    + shall be able to detect such cases in conjunction with the associated {@link javax.media.nativewindow.NativeSurface NativeSurface}.
    For example, AWT's {@link java.awt.Canvas} 's {@link java.awt.Canvas#getGraphicsConfiguration getGraphicsConfiguration()} is capable to determine a display device change. This is demonstrated within {@link javax.media.opengl.awt.GLCanvas}'s and NEWT's AWTCanvas {@link javax.media.opengl.awt.GLCanvas#getGraphicsConfiguration getGraphicsConfiguration()} specialization. Another demonstration is NEWT's {@link javax.media.nativewindow.NativeWindow NativeWindow} - implementation on the Windows platform, which utilizes the native platform's MonitorFromWindow(HWND) function.
    + implementation on the Windows platform, which utilizes the native platform's MonitorFromWindow(HWND) function.
    All OpenGL resources shall be regenerated, while the drawable's {@link GLCapabilities} has - to be choosen again. The following protocol shall be satisfied. + to be chosen again. The following protocol shall be satisfied.

    • Controlled disposal:
      • @@ -97,16 +97,16 @@ import jogamp.opengl.Debug;
      Note: Current graphics driver keep the surface configuration for a given window, even if the window is moved to a monitor with a different pixel configuration, ie 32bpp to 16bpp. However, it is best to not assume such behavior - and make your application comply with the above protocol.

      - - However, to not introduce to much breakage with older applications and because of the situation + and make your application comply with the above protocol. +

      + Avoiding breakage with older applications and because of the situation mentioned above, the boolean system property jogl.screenchange.action will control the - screen change action as follows:
      - + screen change action as follows:

           -Djogl.screenchange.action=false Disable the drawable reconfiguration (the default)
           -Djogl.screenchange.action=true  Enable  the drawable reconfiguration
           
      +

      */ public interface GLAutoDrawable extends GLDrawable { /** Flag reflecting wheather the drawable reconfiguration will be issued in @@ -362,5 +362,29 @@ public interface GLAutoDrawable extends GLDrawable { demos for examples. @return the set GL pipeline or null if not successful */ public GL setGL(GL gl); + + /** + * Method may return the upstream UI toolkit object + * holding this {@link GLAutoDrawable} instance, if exist. + *

      + * Currently known Java UI toolkits and it's known return types are: + * + * + *
      Toolkit GLAutoDrawable Implementation ~ Return Type of getUpstreamWidget() + *
      NEWT {@link com.jogamp.newt.opengl.GLWindow} has a {@link com.jogamp.newt.Window} + *
      SWT {@link com.jogamp.opengl.swt.GLCanvas} is a {@link org.eclipse.swt.widgets.Canvas} + *
      AWT {@link javax.media.opengl.awt.GLCanvas} is a {@link java.awt.Canvas} + *
      AWT {@link javax.media.opengl.awt.GLJPanel} is a {@link javax.swing.JPanel} + *
      + * However, the result may be other object types than the listed above + * due to new supported toolkits. + *

      + *

      + * This method may also return null if no UI toolkit is being used, + * as common for offscreen rendering. + *

      + * @return + */ + public Object getUpstreamWidget(); } diff --git a/src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java b/src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java index 89d5cc4cb..1f6166719 100644 --- a/src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java +++ b/src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java @@ -56,8 +56,14 @@ import jogamp.opengl.GLDrawableImpl; public class GLAutoDrawableDelegate extends GLAutoDrawableBase { public static final boolean DEBUG = Debug.debug("GLAutoDrawableDelegate"); - public GLAutoDrawableDelegate(GLDrawable drawable, GLContext context) { + /** + * @param drawable + * @param context + * @param upstreamWidget optional UI element holding this instance, see {@link #getUpstreamWidget()}. + */ + public GLAutoDrawableDelegate(GLDrawable drawable, GLContext context, Object upstreamWidget) { super((GLDrawableImpl)drawable, (GLContextImpl)context); + this.upstreamWidget = null; } // @@ -80,8 +86,14 @@ public class GLAutoDrawableDelegate extends GLAutoDrawableBase { // Complete GLAutoDrawable // - private RecursiveLock lock = LockFactory.createRecursiveLock(); // instance wide lock - + private final RecursiveLock lock = LockFactory.createRecursiveLock(); // instance wide lock + private final Object upstreamWidget; + + @Override + public final Object getUpstreamWidget() { + return upstreamWidget; + } + /** * {@inheritDoc} *

      diff --git a/src/jogl/classes/javax/media/opengl/GLBase.java b/src/jogl/classes/javax/media/opengl/GLBase.java index bd24b15bc..f5831a72d 100644 --- a/src/jogl/classes/javax/media/opengl/GLBase.java +++ b/src/jogl/classes/javax/media/opengl/GLBase.java @@ -340,5 +340,60 @@ public interface GLBase { * completeness. */ public Object getExtension(String extensionName); + + /** Aliased entrypoint of void {@native glClearDepth}(GLclampd depth); and void {@native glClearDepthf}(GLclampf depth); . */ + public void glClearDepth( double depth ); + + /** Aliased entrypoint of void {@native glDepthRange}(GLclampd depth); and void {@native glDepthRangef}(GLclampf depth); . */ + public void glDepthRange(double zNear, double zFar); + + /** + * @param target a GL buffer (VBO) target as used in {@link GL#glBindBuffer(int, int)}, ie {@link GL#GL_ELEMENT_ARRAY_BUFFER}, {@link GL#GL_ARRAY_BUFFER}, .. + * @return the GL buffer (VBO) name bound to a target via {@link GL#glBindBuffer(int, int)} or 0 if unbound. + */ + public int glGetBoundBuffer(int target); + + /** + * @param buffer a GL buffer name, generated with {@link GL#glGenBuffers(int, int[], int)} and used in {@link GL#glBindBuffer(int, int)}, {@link GL#glBufferData(int, long, java.nio.Buffer, int)} or {@link GL2#glNamedBufferDataEXT(int, long, java.nio.Buffer, int)} for example. + * @return the size of the given GL buffer + */ + public long glGetBufferSize(int buffer); + + /** + * @return true if a VBO is bound to {@link GL.GL_ARRAY_BUFFER} via {@link GL#glBindBuffer(int, int)}, otherwise false + */ + public boolean glIsVBOArrayEnabled(); + + /** + * @return true if a VBO is bound to {@link GL.GL_ELEMENT_ARRAY_BUFFER} via {@link GL#glBindBuffer(int, int)}, otherwise false + */ + public boolean glIsVBOElementArrayEnabled(); + + /** + * Return the framebuffer name bound to this context, + * see {@link GL#glBindFramebuffer(int, int)}. + */ + public int getBoundFramebuffer(int target); + + /** + * Return the default draw framebuffer name. + *

      + * May differ from it's default zero + * in case an framebuffer object ({@link FBObject}) based drawable + * is being used. + *

      + */ + public int getDefaultDrawFramebuffer(); + + /** + * Return the default read framebuffer name. + *

      + * May differ from it's default zero + * in case an framebuffer object ({@link FBObject}) based drawable + * is being used. + *

      + */ + public int getDefaultReadFramebuffer(); + } diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilities.java b/src/jogl/classes/javax/media/opengl/GLCapabilities.java index e5258bcfd..8845ec665 100644 --- a/src/jogl/classes/javax/media/opengl/GLCapabilities.java +++ b/src/jogl/classes/javax/media/opengl/GLCapabilities.java @@ -183,8 +183,8 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil return -1; } - final int ms = sampleBuffers ? numSamples : 0; - final int xms = caps.getSampleBuffers() ? caps.getNumSamples() : 0; + final int ms = getNumSamples(); + final int xms = caps.getNumSamples() ; if(ms > xms) { return 1; @@ -231,15 +231,13 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil /** * Enables or disables pbuffer usage. *

      - * If enabled this method also invokes {@link #setOnscreen(int) setOnscreen(false)} - * and {@link #setFBO(int) setFBO(false)}
      + * If enabled this method also invokes {@link #setOnscreen(int) setOnscreen(false)}. *

      * Defaults to false. */ public void setPBuffer(boolean enable) { if(enable) { setOnscreen(false); - setFBO(false); } isPBuffer = enable; } @@ -252,28 +250,28 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil /** * Enables or disables FBO usage. *

      - * If enabled this method also invokes {@link #setOnscreen(int) setOnscreen(false)} - * and {@link #setPBuffer(int) setPBuffer(false)}
      + * If enabled this method also invokes {@link #setOnscreen(int) setOnscreen(false)}. *

      * Defaults to false. */ public void setFBO(boolean enable) { if(enable) { setOnscreen(false); - setPBuffer(false); } isFBO = enable; } /** * Sets whether the drawable surface supports onscreen.
      - * If enabled this method also invokes {@link #setPBuffer(int) setPBuffer(false)}
      + * If enabled this method also invokes {@link #setPBuffer(int) setPBuffer(false)} + * and {@link #setFBO(int) setFBO(false)}
      * Defaults to true. */ @Override public void setOnscreen(boolean onscreen) { if(onscreen) { setPBuffer(false); + setFBO(false); } super.setOnscreen(onscreen); } @@ -413,15 +411,18 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil return sampleBuffers; } - /** If sample buffers are enabled, indicates the number of buffers - to be allocated. Defaults to 2. */ + /** + * If sample buffers are enabled, indicates the number of buffers + * to be allocated. Defaults to 2. + * @see #getNumSamples() + */ public void setNumSamples(int numSamples) { this.numSamples = numSamples; } @Override public final int getNumSamples() { - return numSamples; + return sampleBuffers ? numSamples : 0; } /** For pbuffers only, indicates whether floating-point buffers @@ -492,12 +493,14 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil if(!isOnscreen()) { if(isFBO) { sink.append(", fbo"); - } else if(isPBuffer) { + } + if(isPBuffer) { sink.append(", pbuffer [r2t ").append(pbufferRenderToTexture?1:0) .append(", r2tr ").append(pbufferRenderToTextureRectangle?1:0) .append(", float ").append(pbufferFloatingPointBuffers?1:0) .append("]"); - } else { + } + if(!isFBO && !isPBuffer) { sink.append(", pixmap"); } } diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java b/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java index 883f3912e..7e0459b2d 100644 --- a/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java +++ b/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java @@ -111,7 +111,7 @@ public interface GLCapabilitiesImmutable extends CapabilitiesImmutable { /** * Returns the number of sample buffers to be allocated if sample - * buffers are enabled. Defaults to 2. + * buffers are enabled, otherwise returns 0. Defaults to 2. */ int getNumSamples(); @@ -144,12 +144,12 @@ public interface GLCapabilitiesImmutable extends CapabilitiesImmutable { boolean getStereo(); /** - * Indicates whether pbuffer is used/requested. + * Indicates whether pbuffer offscreen is used/requested. */ boolean isPBuffer(); /** - * Indicates whether FBO is used/requested. + * Indicates whether FBO offscreen is used/requested. */ boolean isFBO(); diff --git a/src/jogl/classes/javax/media/opengl/GLContext.java b/src/jogl/classes/javax/media/opengl/GLContext.java index 351f90027..63a02ad9c 100644 --- a/src/jogl/classes/javax/media/opengl/GLContext.java +++ b/src/jogl/classes/javax/media/opengl/GLContext.java @@ -55,6 +55,7 @@ import com.jogamp.common.os.Platform; import com.jogamp.common.util.IntObjectHashMap; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; +import com.jogamp.opengl.GLExtensions; /** Abstraction for an OpenGL rendering context. In order to perform OpenGL rendering, a context must be "made current" on the current @@ -69,6 +70,7 @@ import com.jogamp.common.util.locks.RecursiveLock; abstraction provides a stable object which clients can use to refer to a given context. */ public abstract class GLContext { + /** * If true (default), bootstrapping the available GL profiles * will use the highest compatible GL context for each profile, @@ -120,13 +122,13 @@ public abstract class GLContext { protected static final int CTX_PROFILE_ES = 1 << 3; /** ARB_create_context related: flag forward compatible. Cache key value. See {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ protected static final int CTX_OPTION_FORWARD = 1 << 4; - /** ARB_create_context related: flag debug. Not a cache key. See {@link #setContextCreationFlags(int)}, {@link GLAutoDrawable#setContextCreationFlags(int)}, {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ + /** ARB_create_context related: flag debug. Cache key value. See {@link #setContextCreationFlags(int)}, {@link GLAutoDrawable#setContextCreationFlags(int)}, {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ public static final int CTX_OPTION_DEBUG = 1 << 5; /** GL_ARB_ES2_compatibility implementation related: Context is compatible w/ ES2. Not a cache key. See {@link #isGLES2Compatible()}, {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ protected static final int CTX_IMPL_ES2_COMPAT = 1 << 8; - /** Context supports FBO, details see {@link #hasFBO()}. + /** Context supports basic FBO, details see {@link #hasFBO()}. * Not a cache key. * @see #hasFBO() * @see #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile) @@ -136,16 +138,6 @@ public abstract class GLContext { /** Context uses software rasterizer, otherwise hardware rasterizer. Cache key value. See {@link #isHardwareRasterizer()}, {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ protected static final int CTX_IMPL_ACCEL_SOFT = 1 << 15; - protected static final String GL_ARB_ES2_compatibility = "GL_ARB_ES2_compatibility"; - protected static final String GL_ARB_framebuffer_object = "GL_ARB_framebuffer_object"; - protected static final String GL_EXT_framebuffer_object = "GL_EXT_framebuffer_object"; - protected static final String GL_EXT_framebuffer_blit = "GL_EXT_framebuffer_blit"; - protected static final String GL_EXT_framebuffer_multisample = "GL_EXT_framebuffer_multisample"; - protected static final String GL_EXT_packed_depth_stencil = "GL_EXT_packed_depth_stencil"; - protected static final String GL_ARB_texture_non_power_of_two = "GL_ARB_texture_non_power_of_two"; - protected static final String GL_EXT_texture_format_BGRA8888 = "GL_EXT_texture_format_BGRA8888"; - protected static final String GL_IMG_texture_format_BGRA8888 = "GL_IMG_texture_format_BGRA8888"; - private static final ThreadLocal currentContext = new ThreadLocal(); private final HashMap attachedObjectsByString = new HashMap(); @@ -639,11 +631,19 @@ public abstract class GLContext { return 0 == ( ctxOptions & CTX_IMPL_ACCEL_SOFT ) ; } - /** Returns whether the context supports FBO, hence is either GL-ES >= 2.0, >= core GL 3.0 or implements the extensions - * GL_ARB_ES2_compatibility, ARB_framebuffer_object or all of - * EXT_framebuffer_object, EXT_framebuffer_multisample, - * EXT_framebuffer_blit, GL_EXT_packed_depth_stencil. + /** + * Returns true if basic FBO support is available, otherwise false. + *

      + * Basic FBO is supported if the context is either GL-ES >= 2.0, GL >= core 3.0 or implements the extensions + * GL_ARB_ES2_compatibility, GL_ARB_framebuffer_object, GL_EXT_framebuffer_object or GL_OES_framebuffer_object. + *

      + *

      + * Basic FBO support may only include one color attachment and no multisampling, + * as well as limited internal formats for renderbuffer. + *

      * @see #CTX_IMPL_FBO + * @see com.jogamp.opengl.FBObject#supportsBasicFBO(GL) + * @see com.jogamp.opengl.FBObject#supportsFullFBO(GL) */ public final boolean hasFBO() { return 0 != ( ctxOptions & CTX_IMPL_FBO ) ; @@ -659,13 +659,13 @@ public abstract class GLContext { /** Note: The GL impl. may return a const value, ie {@link GLES2#isNPOTTextureAvailable()} always returns true. */ public boolean isNPOTTextureAvailable() { - return isGL3() || isGLES2Compatible() || isExtensionAvailable(GL_ARB_texture_non_power_of_two); + return isGL3() || isGLES2Compatible() || isExtensionAvailable(GLExtensions.ARB_texture_non_power_of_two); } public boolean isTextureFormatBGRA8888Available() { return isGL2GL3() || - isExtensionAvailable(GL_EXT_texture_format_BGRA8888) || - isExtensionAvailable(GL_IMG_texture_format_BGRA8888) ; + isExtensionAvailable(GLExtensions.EXT_texture_format_BGRA8888) || + isExtensionAvailable(GLExtensions.IMG_texture_format_BGRA8888) ; } /** @see GLProfile#isGL4bc() */ @@ -798,7 +798,32 @@ public abstract class GLContext { } protected boolean bindSwapBarrierImpl(int group, int barrier) { /** nop per default .. **/ return false; } - + /** + * Return the framebuffer name bound to this context, + * see {@link GL#glBindFramebuffer(int, int)}. + */ + public abstract int getBoundFramebuffer(int target); + + /** + * Return the default draw framebuffer name. + *

      + * May differ from it's default zero + * in case an framebuffer object ({@link FBObject}) based drawable + * is being used. + *

      + */ + public abstract int getDefaultDrawFramebuffer(); + + /** + * Return the default read framebuffer name. + *

      + * May differ from it's default zero + * in case an framebuffer object ({@link FBObject}) based drawable + * is being used. + *

      + */ + public abstract int getDefaultReadFramebuffer(); + /** * @return The extension implementing the GLDebugOutput feature, * either GL_ARB_debug_output or GL_AMD_debug_output. @@ -984,6 +1009,7 @@ public abstract class GLContext { deviceVersionsAvailableSet.add(devKey); if (DEBUG) { System.err.println(getThreadName() + ": createContextARB: SET mappedVersionsAvailableSet "+devKey); + System.err.println(GLContext.dumpAvailableGLVersions(null).toString()); } } } @@ -1010,6 +1036,10 @@ public abstract class GLContext { validateProfileBits(profile, "profile"); validateProfileBits(resCtp, "resCtp"); + if(DEBUG) { + System.err.println("GLContext.mapAvailableGLVersion: "+device+": "+getGLVersion(reqMajor, 0, profile, null)+" -> "+getGLVersion(resMajor, resMinor, resCtp, null)); + // Thread.dumpStack(); + } final String key = getDeviceVersionAvailableKey(device, reqMajor, profile); final Integer val = new Integer(composeBits(resMajor, resMinor, resCtp)); synchronized(deviceVersionAvailable) { @@ -1122,7 +1152,9 @@ public abstract class GLContext { } else /* if (glpImpl.isGL2()) */ { reqMajorCTP[0]=2; } - if( glpImpl.isGL2() ) { // incl GL3bc and GL4bc + if( glpImpl.isGLES() ) { + reqMajorCTP[1]=CTX_PROFILE_ES; + } else if( glpImpl.isGL2() ) { // incl GL3bc and GL4bc reqMajorCTP[1]=CTX_PROFILE_COMPAT; } else { reqMajorCTP[1]=CTX_PROFILE_CORE; @@ -1141,8 +1173,7 @@ public abstract class GLContext { int _major[] = { 0 }; int _minor[] = { 0 }; int _ctp[] = { 0 }; - if( GLContext.getAvailableGLVersion(device, reqMajorCTP[0], reqMajorCTP[1], - _major, _minor, _ctp)) { + if( GLContext.getAvailableGLVersion(device, reqMajorCTP[0], reqMajorCTP[1], _major, _minor, _ctp)) { return _ctp[0]; } return 0; // n/a @@ -1180,6 +1211,23 @@ public abstract class GLContext { return null; } + /** + * Returns true if it is possible to create an framebuffer object (FBO). + *

      + * FBO feature is implemented in OpenGL, hence it is {@link GLProfile} dependent. + *

      + *

      + * FBO support is queried as described in {@link #hasFBO()}. + *

      + * + * @param device the device to request whether FBO is available for + * @param glp {@link GLProfile} to check for FBO capabilities + * @see GLContext#hasFBO() + */ + public static final boolean isFBOAvailable(AbstractGraphicsDevice device, GLProfile glp) { + return 0 != ( CTX_IMPL_FBO & getAvailableContextProperties(device, glp) ); + } + /** * @param device the device to request whether the profile is available for * @param reqMajor Key Value either 1, 2, 3 or 4 diff --git a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java index d6480e7aa..612a02f14 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java @@ -50,9 +50,11 @@ import com.jogamp.common.JogampRuntimeException; import com.jogamp.common.util.ReflectionUtil; import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; import javax.media.opengl.GLProfile.ShutdownType; import jogamp.opengl.Debug; @@ -398,9 +400,18 @@ public abstract class GLDrawableFactory { /** * Creates a Offscreen GLDrawable incl it's offscreen {@link javax.media.nativewindow.NativeSurface} with the given capabilites and dimensions. *

      - * A Pbuffer drawable/surface is created if both {@link javax.media.opengl.GLCapabilities#isPBuffer() caps.isPBuffer()} - * and {@link #canCreateGLPbuffer(javax.media.nativewindow.AbstractGraphicsDevice) canCreateGLPbuffer(device)} is true.
      - * Otherwise a simple pixmap/bitmap drawable/surface is created, which is unlikely to be hardware accelerated.
      + * It's {@link AbstractGraphicsConfiguration} is properly set according to the given {@link GLCapabilitiesImmutable}, see below. + *

      + *

      + * A FBO drawable is created if both {@link javax.media.opengl.GLCapabilities#isFBO() caps.isFBO()} + * and {@link GLContext#isFBOAvailable(AbstractGraphicsDevice, GLProfile) canCreateFBO(device, caps.getGLProfile())} is true. + *

      + *

      + * A Pbuffer drawable is created if both {@link javax.media.opengl.GLCapabilities#isPBuffer() caps.isPBuffer()} + * and {@link #canCreateGLPbuffer(javax.media.nativewindow.AbstractGraphicsDevice) canCreateGLPbuffer(device)} is true. + *

      + *

      + * If neither FBO nor Pbuffer is available, a simple pixmap/bitmap drawable/surface is created, which is unlikely to be hardware accelerated. *

      * * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared device to be used, may be null for the platform's default device. @@ -421,42 +432,31 @@ public abstract class GLDrawableFactory { throws GLException; /** - * Creates an offscreen NativeSurface.
      - * A Pbuffer surface is created if both {@link javax.media.opengl.GLCapabilities#isPBuffer() caps.isPBuffer()} - * and {@link #canCreateGLPbuffer(javax.media.nativewindow.AbstractGraphicsDevice) canCreateGLPbuffer(device)} is true.
      - * Otherwise a simple pixmap/bitmap surface is created. The latter is unlikely to be hardware accelerated.
      - * - * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be null for the platform's default device. - * @param caps the requested GLCapabilties - * @param chooser the custom chooser, may be null for default - * @param width the requested offscreen width - * @param height the requested offscreen height - * @return the created offscreen native surface - * - * @throws GLException if any window system-specific errors caused - * the creation of the GLDrawable to fail. - */ - public abstract NativeSurface createOffscreenSurface(AbstractGraphicsDevice device, - GLCapabilitiesImmutable caps, - GLCapabilitiesChooser chooser, - int width, int height); - - /** - * Highly experimental API entry, allowing developer of new windowing system bindings - * to leverage the native window handle to produce a NativeSurface implementation (ProxySurface), having the required GLCapabilities.
      - * Such surface can be used to instantiate a GLDrawable and hence test your new binding w/o the - * costs of providing a full set of abstraction like the AWT GLCanvas or even the native NEWT bindings. + * Creates a proxy {@link NativeSurface} w/ defined surface handle, i.e. a {@link WrappedSurface} or {@link GDISurface} instance. + *

      + * It's {@link AbstractGraphicsConfiguration} is properly set according to the given {@link GLCapabilitiesImmutable}. + *

      + *

      + * Lifecycle (destruction) of the given surface handle shall be handled by the caller. + *

      + *

      + * Such surface can be used to instantiate a GLDrawable. With the help of {@link GLAutoDrawableDelegate} + * you will be able to implement a new native windowing system binding almost on-the-fly, see {@link com.jogamp.opengl.swt.GLCanvas}. + *

      * - * @param device the platform's target device, shall not be null + * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be null for the platform's default device. + * Caller has to ensure it is compatible w/ the given windowHandle + * @param screenIdx matching screen index of given windowHandle * @param windowHandle the native window handle * @param caps the requested GLCapabilties * @param chooser the custom chooser, may be null for default - * @return The proxy surface wrapping the windowHandle on the device + * @param upstream optional {@link ProxySurface.UpstreamSurfaceHook} allowing control of the {@link ProxySurface}'s lifecycle and data it presents. + * @return the created {@link ProxySurface} instance w/ defined surface handle. */ - public abstract ProxySurface createProxySurface(AbstractGraphicsDevice device, + public abstract ProxySurface createProxySurface(AbstractGraphicsDevice device, + int screenIdx, long windowHandle, - GLCapabilitiesImmutable caps, - GLCapabilitiesChooser chooser); + GLCapabilitiesImmutable caps, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream); /** * Returns true if it is possible to create a GLPbuffer. Some older @@ -492,23 +492,7 @@ public abstract class GLDrawableFactory { GLContext shareWith) throws GLException; - /** - * Returns true if it is possible to create an framebuffer object (FBO). - *

      - * FBO feature is implemented in OpenGL, hence it is {@link GLProfile} dependent. - *

      - *

      - * FBO support is queried as described in {@link GLContext#hasFBO()}. - *

      - * - * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be null for the platform's default device. - * @param glp {@link GLProfile} to check for FBO capabilities - * @see GLContext#hasFBO() - */ - public final boolean canCreateFBO(AbstractGraphicsDevice device, GLProfile glp) { - return 0 != ( GLContext.CTX_IMPL_FBO & GLContext.getAvailableContextProperties(device, glp) ); - } - + //---------------------------------------------------------------------- // Methods for interacting with third-party OpenGL libraries diff --git a/src/jogl/classes/javax/media/opengl/GLProfile.java b/src/jogl/classes/javax/media/opengl/GLProfile.java index a7200b560..73d13a387 100644 --- a/src/jogl/classes/javax/media/opengl/GLProfile.java +++ b/src/jogl/classes/javax/media/opengl/GLProfile.java @@ -117,10 +117,12 @@ public class GLProfile { * @deprecated Use {@link #initSingleton()}. This method is subject to be removed in future versions of JOGL. */ public static void initSingleton(final boolean firstUIActionOnProcess) { + final boolean justInitialized; initLock.lock(); try { if(!initialized) { // volatile: ok initialized = true; + justInitialized = true; if(DEBUG) { System.err.println("GLProfile.initSingleton(firstUIActionOnProcess: "+firstUIActionOnProcess+") - thread "+Thread.currentThread().getName()); Thread.dumpStack(); @@ -166,10 +168,17 @@ public class GLProfile { return null; } }); + } else { + justInitialized = false; } } finally { initLock.unlock(); } + if(DEBUG) { + if( justInitialized && ( hasGL234Impl || hasGLES1Impl || hasGLES2Impl ) ) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(defaultDevice, null, true)); + } + } } /** @@ -1532,18 +1541,17 @@ public class GLProfile { if(DEBUG) { // System.err.println("GLProfile.init addedAnyProfile "+addedAnyProfile+" (desktop: "+addedDesktopProfile+", egl "+addedEGLProfile+")"); - System.err.println("GLProfile.init addedAnyProfile "+addedAnyProfile); - System.err.println("GLProfile.init isAWTAvailable "+isAWTAvailable); - System.err.println("GLProfile.init hasDesktopGLFactory "+hasDesktopGLFactory); - System.err.println("GLProfile.init hasGL234Impl "+hasGL234Impl); - System.err.println("GLProfile.init hasEGLFactory "+hasEGLFactory); - System.err.println("GLProfile.init hasGLES1Impl "+hasGLES1Impl); - System.err.println("GLProfile.init hasGLES2Impl "+hasGLES2Impl); - System.err.println("GLProfile.init defaultDevice "+defaultDevice); - System.err.println("GLProfile.init profile order "+array2String(GL_PROFILE_LIST_ALL)); - if(hasGL234Impl || hasGLES1Impl || hasGLES2Impl) { // avoid deadlock - System.err.println(JoglVersion.getDefaultOpenGLInfo(null, true)); - } + System.err.println("GLProfile.init addedAnyProfile "+addedAnyProfile); + System.err.println("GLProfile.init isAWTAvailable "+isAWTAvailable); + System.err.println("GLProfile.init hasDesktopGLFactory "+hasDesktopGLFactory); + System.err.println("GLProfile.init hasGL234Impl "+hasGL234Impl); + System.err.println("GLProfile.init hasEGLFactory "+hasEGLFactory); + System.err.println("GLProfile.init hasGLES1Impl "+hasGLES1Impl); + System.err.println("GLProfile.init hasGLES2Impl "+hasGLES2Impl); + System.err.println("GLProfile.init defaultDevice "+defaultDevice); + System.err.println("GLProfile.init defaultDevice Desktop "+defaultDesktopDevice); + System.err.println("GLProfile.init defaultDevice EGL "+defaultEGLDevice); + System.err.println("GLProfile.init profile order "+array2String(GL_PROFILE_LIST_ALL)); } } @@ -1642,24 +1650,6 @@ public class GLProfile { if (DEBUG) { System.err.println("GLProfile.initProfilesForDevice: "+device+": egl Shared Ctx "+eglSharedCtxAvail); } - if( hasGLES2Impl ) { - // The native ES2 impl. overwrites a previous mapping using 'ES2 compatibility' by a desktop profile - GLContext.mapAvailableGLVersion(device, - 2, GLContext.CTX_PROFILE_ES, - 2, 0, GLContext.CTX_PROFILE_ES|GLContext.CTX_IMPL_ES2_COMPAT); - if (DEBUG) { - System.err.println(GLContext.getThreadName() + ": initProfilesForDeviceCritical-MapVersionsAvailable HAVE: ES2 -> ES 2.0"); - } - } - if( hasGLES1Impl ) { - // Always favor the native ES1 impl. - GLContext.mapAvailableGLVersion(device, - 1, GLContext.CTX_PROFILE_ES, - 1, 0, GLContext.CTX_PROFILE_ES); - if (DEBUG) { - System.err.println(GLContext.getThreadName() + ": initProfilesForDeviceCritical-MapVersionsAvailable HAVE: ES1 -> ES 1.0"); - } - } addedEGLProfile = computeProfileMap(device, false /* desktopCtxUndef*/, false /* esCtxUndef */); } @@ -1767,7 +1757,7 @@ public class GLProfile { } _mappedProfiles.put(profile, glProfile); if (DEBUG) { - System.err.println("GLProfile.init map "+glProfile+" on devide "+device.getConnection()); + System.err.println("GLProfile.init map "+glProfile+" on device "+device.getConnection()); } if(null==defaultGLProfileHW && isHardwareRasterizer[0]) { defaultGLProfileHW=glProfile; diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 48f7ea24a..c2e36ef9b 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -261,6 +261,11 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing this.device = device; } + @Override + public final Object getUpstreamWidget() { + return this; + } + @Override public void setShallUseOffscreenLayer(boolean v) { shallUseOffscreenLayer = v; @@ -1070,7 +1075,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing // System.err.println(NativeWindowVersion.getInstance()); System.err.println(JoglVersion.getInstance()); - System.err.println(JoglVersion.getDefaultOpenGLInfo(null, true).toString()); + System.err.println(JoglVersion.getDefaultOpenGLInfo(null, null, true).toString()); final GLCapabilitiesImmutable caps = new GLCapabilities( GLProfile.getDefault(GLProfile.getDefaultDevice()) ); final Frame frame = new Frame("JOGL AWT Test"); diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java index cd18c5098..acb8f2183 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java @@ -87,7 +87,7 @@ import jogamp.opengl.awt.Java2D; import jogamp.opengl.awt.Java2DGLContext; import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol; -import com.jogamp.opengl.util.FBObject; +import com.jogamp.opengl.FBObject; import com.jogamp.opengl.util.GLBuffers; // FIXME: Subclasses need to call resetGLFunctionAvailability() on their @@ -250,6 +250,11 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing this.shareWith = shareWith; } + @Override + public final Object getUpstreamWidget() { + return this; + } + @Override public void display() { if (EventQueue.isDispatchThread()) { diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java index 804e9ee14..aabef29b0 100644 --- a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java +++ b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java @@ -32,7 +32,6 @@ import java.nio.FloatBuffer; import javax.media.opengl.GL2ES2; // FIXME: Subsume GL2GL3.GL_DRAW_FRAMEBUFFER -> GL2ES2.GL_DRAW_FRAMEBUFFER ! import javax.media.opengl.GL; -import javax.media.opengl.GLException; import javax.media.opengl.GLUniformData; import javax.media.opengl.fixedfunc.GLMatrixFunc; @@ -45,7 +44,9 @@ import com.jogamp.graph.geom.Vertex; import com.jogamp.graph.curve.opengl.GLRegion; import com.jogamp.graph.curve.opengl.RenderState; -import com.jogamp.opengl.util.FBObject; +import com.jogamp.opengl.FBObject; +import com.jogamp.opengl.FBObject.Attachment; +import com.jogamp.opengl.FBObject.TextureAttachment; import com.jogamp.opengl.util.GLArrayDataServer; import com.jogamp.opengl.util.PMVMatrix; import com.jogamp.opengl.util.glsl.ShaderState; @@ -60,6 +61,7 @@ public class VBORegion2PES2 extends GLRegion { private FBObject fbo; + private TextureAttachment texA; private PMVMatrix fboPMVMatrix; GLUniformData mgl_fboPMVMatrix; @@ -72,7 +74,7 @@ public class VBORegion2PES2 extends GLRegion { super(renderModes); fboPMVMatrix = new PMVMatrix(); mgl_fboPMVMatrix = new GLUniformData(UniformNames.gcu_PMVMatrix, 4, 4, fboPMVMatrix.glGetPMvMatrixf()); - mgl_ActiveTexture = new GLUniformData(UniformNames.gcu_TextureUnit, textureEngine); + mgl_ActiveTexture = new GLUniformData(UniformNames.gcu_TextureUnit, textureEngine); } public void update(GL2ES2 gl, RenderState rs) { @@ -214,8 +216,9 @@ public class VBORegion2PES2 extends GLRegion { final ShaderState st = rs.getShaderState(); gl.glViewport(0, 0, width, hight); - st.uniform(gl, mgl_ActiveTexture); - fbo.use(gl, 0); + st.uniform(gl, mgl_ActiveTexture); + gl.glActiveTexture(GL.GL_TEXTURE0 + mgl_ActiveTexture.intValue()); + fbo.use(gl, texA); verticeFboAttr.enableBuffer(gl, true); texCoordFboAttr.enableBuffer(gl, true); indicesFbo.enableBuffer(gl, true); @@ -244,20 +247,16 @@ public class VBORegion2PES2 extends GLRegion { // System.out.println("FBO Scale: " + m.glGetMatrixf().get(0) +" " + m.glGetMatrixf().get(5)); if(null != fbo && fbo.getWidth() != tex_width_c && fbo.getHeight() != tex_height_c ) { - fbo.destroy(gl); - fbo = null; + fbo.reset(gl, tex_width_c, tex_height_c); } - if(null == fbo) { - fbo = new FBObject(tex_width_c, tex_height_c); - fbo.init(gl); + if(null == fbo) { + fbo = new FBObject(); + fbo.reset(gl, tex_width_c, tex_height_c); // FIXME: shall not use bilinear, due to own AA ? However, w/o bilinear result is not smooth - fbo.attachTexture2D(gl, mgl_ActiveTexture.intValue(), GL2ES2.GL_LINEAR, GL2ES2.GL_LINEAR, GL2ES2.GL_CLAMP_TO_EDGE, GL2ES2.GL_CLAMP_TO_EDGE); - // fbo.attachTexture2D(gl, mgl_ActiveTexture.intValue(), GL2ES2.GL_NEAREST, GL2ES2.GL_NEAREST, GL2ES2.GL_CLAMP_TO_EDGE, GL2ES2.GL_CLAMP_TO_EDGE); - fbo.attachDepthBuffer(gl, GL.GL_DEPTH_COMPONENT16); // FIXME: or shall we use 24 or 32 bit depth ? - if(!fbo.isStatusValid()) { - throw new GLException("FBO invalid: "+fbo); - } + texA = fbo.attachTexture2D(gl, 0, true, GL2ES2.GL_LINEAR, GL2ES2.GL_LINEAR, GL2ES2.GL_CLAMP_TO_EDGE, GL2ES2.GL_CLAMP_TO_EDGE); + // texA = fbo.attachTexture2D(gl, 0, GL2ES2.GL_NEAREST, GL2ES2.GL_NEAREST, GL2ES2.GL_CLAMP_TO_EDGE, GL2ES2.GL_CLAMP_TO_EDGE); + fbo.attachRenderbuffer(gl, Attachment.Type.DEPTH, 24); } else { fbo.bind(gl); } @@ -305,6 +304,7 @@ public class VBORegion2PES2 extends GLRegion { if(null != fbo) { fbo.destroy(gl); fbo = null; + texA = null; } if(null != verticeTxtAttr) { st.ownAttribute(verticeTxtAttr, false); diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index 4dd8806fa..e730bc62e 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -49,8 +49,9 @@ import com.jogamp.common.os.DynamicLookupHelper; import com.jogamp.common.util.ReflectionUtil; import com.jogamp.gluegen.runtime.FunctionAddressResolver; import com.jogamp.gluegen.runtime.ProcAddressTable; -import com.jogamp.gluegen.runtime.opengl.GLExtensionNames; +import com.jogamp.gluegen.runtime.opengl.GLNameResolver; import com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver; +import com.jogamp.opengl.GLExtensions; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; @@ -88,13 +89,14 @@ public abstract class GLContextImpl extends GLContext { // Tracks creation and initialization of buffer objects to avoid // repeated glGet calls upon glMapBuffer operations private GLBufferSizeTracker bufferSizeTracker; // Singleton - Set by GLContextShareSet - private GLBufferStateTracker bufferStateTracker = new GLBufferStateTracker(); - private GLStateTracker glStateTracker = new GLStateTracker(); + private final GLBufferStateTracker bufferStateTracker = new GLBufferStateTracker(); + private final GLStateTracker glStateTracker = new GLStateTracker(); private GLDebugMessageHandler glDebugHandler = null; + private final int[] boundFBOTarget = new int[] { 0, 0 }; // { draw, read } protected GLDrawableImpl drawable; protected GLDrawableImpl drawableRead; - + protected GL gl; protected static final Object mappedContextTypeObjectLock; @@ -140,11 +142,11 @@ public abstract class GLContextImpl extends GLContext { bufferSizeTracker.clearCachedBufferSizes(); } - if (bufferStateTracker != null) { + if (bufferStateTracker != null) { // bufferStateTracker.clearBufferObjectState(); } - if (glStateTracker != null) { + if (glStateTracker != null) { // glStateTracker.clearStates(false); } @@ -156,6 +158,11 @@ public abstract class GLContextImpl extends GLContext { glRenderer = ""; glRendererLowerCase = glRenderer; + + if (boundFBOTarget != null) { // + boundFBOTarget[0] = 0; // draw + boundFBOTarget[1] = 0; // read + } super.resetStates(); } @@ -199,7 +206,7 @@ public abstract class GLContextImpl extends GLContext { drawableRead = (GLDrawableImpl) readWrite; } final GLDrawable old = drawable; - drawable = ( null != readWrite ) ? (GLDrawableImpl) readWrite : null; + drawable = (GLDrawableImpl) readWrite ; if(lockHeld) { makeCurrent(); } @@ -252,16 +259,19 @@ public abstract class GLContextImpl extends GLContext { public void release() throws GLException { release(false); } - private void release(boolean force) throws GLException { + private void release(boolean inDestruction) throws GLException { if(TRACE_SWITCH) { - System.err.println(getThreadName() +": GLContext.ContextSwitch: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+" - release() - force: "+force+", "+lock); + System.err.println(getThreadName() +": GLContext.ContextSwitch: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+" - release() - force: "+inDestruction+", "+lock); } if ( !lock.isOwner(Thread.currentThread()) ) { throw new GLException("Context not current on current thread "+Thread.currentThread().getName()+": "+this); } - final boolean actualRelease = ( force || lock.getHoldCount() == 1 ) && 0 != contextHandle; + final boolean actualRelease = ( inDestruction || lock.getHoldCount() == 1 ) && 0 != contextHandle; try { if( actualRelease ) { + if( !inDestruction ) { + drawable.contextMadeCurrent(this, false); + } releaseImpl(); } } finally { @@ -306,13 +316,12 @@ public abstract class GLContextImpl extends GLContext { } try { // release current context - if(null != glDebugHandler) { - if(lock.getHoldCount() == 1) { - // needs current context to disable debug handler - makeCurrent(); - } - glDebugHandler.enable(false); + if(lock.getHoldCount() == 1) { + // needs current context to disable debug handler + makeCurrent(); } + drawable.contextRealized(this, false); + glDebugHandler.enable(false); if(lock.getHoldCount() > 1) { // pending release() after makeCurrent() release(true); @@ -488,11 +497,18 @@ public abstract class GLContextImpl extends GLContext { if(TRACE_GL) { gl = gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Trace", null, gl, new Object[] { System.err } ) ); } + + drawable.contextRealized(this, true); + if(DEBUG || TRACE_SWITCH) { System.err.println(getThreadName() +": GLContext.ContextSwitch: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+" - switch - CONTEXT_CURRENT_NEW - "+lock); } - } else if(TRACE_SWITCH) { - System.err.println(getThreadName() +": GLContext.ContextSwitch: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+" - switch - CONTEXT_CURRENT - "+lock); + } else { + drawable.contextMadeCurrent(this, true); + + if(TRACE_SWITCH) { + System.err.println(getThreadName() +": GLContext.ContextSwitch: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+" - switch - CONTEXT_CURRENT - "+lock); + } } /* FIXME: refactor dependence on Java 2D / JOGL bridge @@ -543,14 +559,11 @@ public abstract class GLContextImpl extends GLContext { final AbstractGraphicsConfiguration config = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice device = config.getScreen().getDevice(); - if( !GLContext.getAvailableGLVersionsSet(device) ) { - final int reqMajor; - final int reqProfile; - if( 0 != ( ctxOptions & GLContext.CTX_PROFILE_ES) ) { - // ES1 or ES2 - reqMajor = ctxMajorVersion; - reqProfile = GLContext.CTX_PROFILE_ES; - } else { + // Non ARB desktop profiles may not have been registered + if( !GLContext.getAvailableGLVersionsSet(device) ) { // not yet set + if( 0 == ( ctxOptions & GLContext.CTX_PROFILE_ES) ) { // not ES profile + final int reqMajor; + final int reqProfile; if(ctxMajorVersion<3 || ctxMajorVersion==3 && ctxMinorVersion==0) { reqMajor = 2; } else { @@ -561,12 +574,13 @@ public abstract class GLContextImpl extends GLContext { } else { reqProfile = GLContext.CTX_PROFILE_COMPAT; } - } - GLContext.mapAvailableGLVersion(device, reqMajor, reqProfile, - ctxMajorVersion, ctxMinorVersion, ctxOptions); - GLContext.setAvailableGLVersionsSet(device); - if (DEBUG) { - System.err.println(getThreadName() + ": createContextOLD-MapVersionsAvailable HAVE: " + device+" -> "+reqMajor+"."+reqProfile+ " -> "+getGLVersion()); + GLContext.mapAvailableGLVersion(device, reqMajor, reqProfile, + ctxMajorVersion, ctxMinorVersion, ctxOptions); + GLContext.setAvailableGLVersionsSet(device); + + if (DEBUG) { + System.err.println(getThreadName() + ": createContextOLD-MapVersionsAvailable HAVE: " + device+" -> "+reqMajor+"."+reqProfile+ " -> "+getGLVersion()); + } } } } @@ -776,7 +790,7 @@ public abstract class GLContextImpl extends GLContext { } /** - * Note: Since context creation is temproary, caller need to issue {@link #resetStates()}, if creation was successful, i.e. returns true. + * Note: Since context creation is temporary, caller need to issue {@link #resetStates()}, if creation was successful, i.e. returns true. * This method does not reset the states, allowing the caller to utilize the state variables. **/ private final boolean createContextARBMapVersionsAvailable(int reqMajor, int reqProfile) { @@ -1034,22 +1048,29 @@ public abstract class GLContextImpl extends GLContext { table.reset(getDrawableImpl().getGLDynamicLookupHelper() ); } - private final void initGLRendererStrings() { + private final boolean initGLRendererStrings() { final GLDynamicLookupHelper glDynLookupHelper = getDrawableImpl().getGLDynamicLookupHelper(); final long _glGetString = glDynLookupHelper.dynamicLookupFunction("glGetString"); if(0 == _glGetString) { // FIXME System.err.println("Warning: Entry point to 'glGetString' is NULL."); - Thread.dumpStack(); + if(DEBUG) { + Thread.dumpStack(); + } + return false; } else { final String _glRenderer = glGetStringInt(GL.GL_RENDERER, _glGetString); if(null == _glRenderer) { // FIXME - System.err.println("Warning: GL_RENDERER is NULL."); - Thread.dumpStack(); + if(DEBUG) { + System.err.println("Warning: GL_RENDERER is NULL."); + Thread.dumpStack(); + } + return false; } else { glRenderer = _glRenderer; glRendererLowerCase = glRenderer.toLowerCase(); + return true; } } } @@ -1088,17 +1109,20 @@ public abstract class GLContextImpl extends GLContext { } updateGLXProcAddressTable(); - initGLRendererStrings(); + final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); + final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); + + if( !initGLRendererStrings() && DEBUG) { + System.err.println("Warning: intialization of GL renderer strings failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); + } if(!isCurrentContextHardwareRasterizer()) { ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT; } - final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); - final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits); if (DEBUG) { - System.err.println(getThreadName() + ": Context FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); + System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.0 FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); } // @@ -1154,11 +1178,10 @@ public abstract class GLContextImpl extends GLContext { } } - if( 0 != ( CTX_PROFILE_ES & ctxProfileBits ) && ctxMajorVersion >= 2 || - isExtensionAvailable(GL_ARB_ES2_compatibility) ) { + if( ( 0 != ( CTX_PROFILE_ES & ctxProfileBits ) && major >= 2 ) || isExtensionAvailable(GLExtensions.ARB_ES2_compatibility) ) { ctxProfileBits |= CTX_IMPL_ES2_COMPAT; ctxProfileBits |= CTX_IMPL_FBO; - } else if( hasFBOImpl(ctxMajorVersion, ctxProfileBits, extensionAvailability) ) { + } else if( hasFBOImpl(major, ctxProfileBits, extensionAvailability) ) { ctxProfileBits |= CTX_IMPL_FBO; } @@ -1168,23 +1191,26 @@ public abstract class GLContextImpl extends GLContext { setContextVersion(major, minor, ctxProfileBits, true); setDefaultSwapInterval(); + + if(DEBUG) { + System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: "+contextFQN+" - "+GLContext.getGLVersion(ctxMajorVersion, ctxMinorVersion, ctxOptions, null)); + } } - protected static final boolean hasFBOImpl(int ctxMajorVersion, int ctxProfileBits, ExtensionAvailabilityCache extCache) { - return ( ctxMajorVersion >= 3 ) || // any >= 3.0 GL ctx + protected static final boolean hasFBOImpl(int major, int ctp, ExtensionAvailabilityCache extCache) { + return ( 0 != (ctp & CTX_PROFILE_ES) && major >= 2 ) || // ES >= 2.0 - ( 0 != (ctxProfileBits & CTX_PROFILE_ES) && ctxMajorVersion >= 2 ) || // ES >= 2.0 + major >= 3 || // any >= 3.0 GL ctx ( null != extCache && - ( extCache.isExtensionAvailable(GL_ARB_ES2_compatibility) ) || // ES 2.0 compatible + extCache.isExtensionAvailable(GLExtensions.ARB_ES2_compatibility) || // ES 2.0 compatible - ( extCache.isExtensionAvailable(GL_ARB_framebuffer_object) ) || // ARB_framebuffer_object + extCache.isExtensionAvailable(GLExtensions.ARB_framebuffer_object) || // ARB_framebuffer_object - ( extCache.isExtensionAvailable(GL_EXT_framebuffer_object) && // EXT_framebuffer_object* - extCache.isExtensionAvailable(GL_EXT_framebuffer_multisample) && - extCache.isExtensionAvailable(GL_EXT_framebuffer_blit) && - extCache.isExtensionAvailable(GL_EXT_packed_depth_stencil) ) ); + extCache.isExtensionAvailable(GLExtensions.EXT_framebuffer_object) || // EXT_framebuffer_object + + extCache.isExtensionAvailable(GLExtensions.OES_framebuffer_object) ) ; // OES_framebuffer_object excluded } protected final void removeCachedVersion(int major, int minor, int ctxProfileBits) { @@ -1259,11 +1285,11 @@ public abstract class GLContextImpl extends GLContext { // dynamic function lookup at last incl name aliasing (not cached) DynamicLookupHelper dynLookup = getDrawableImpl().getGLDynamicLookupHelper(); - String tmpBase = GLExtensionNames.normalizeVEN(GLExtensionNames.normalizeARB(glFunctionName, true), true); + String tmpBase = GLNameResolver.normalizeVEN(GLNameResolver.normalizeARB(glFunctionName, true), true); long addr = 0; - int variants = GLExtensionNames.getFuncNamePermutationNumber(tmpBase); + int variants = GLNameResolver.getFuncNamePermutationNumber(tmpBase); for(int i = 0; 0==addr && i < variants; i++) { - String tmp = GLExtensionNames.getFuncNamePermutation(tmpBase, i); + String tmp = GLNameResolver.getFuncNamePermutation(tmpBase, i); try { addr = dynLookup.dynamicLookupFunction(tmp); } catch (Exception e) { } @@ -1317,7 +1343,7 @@ public abstract class GLContextImpl extends GLContext { protected static String getContextFQN(AbstractGraphicsDevice device, int major, int minor, int ctxProfileBits) { // remove non-key values - ctxProfileBits &= ~( GLContext.CTX_OPTION_DEBUG | GLContext.CTX_IMPL_ES2_COMPAT | GLContext.CTX_IMPL_FBO ) ; + ctxProfileBits &= ~( GLContext.CTX_IMPL_ES2_COMPAT | GLContext.CTX_IMPL_FBO ) ; return device.getUniqueID() + "-" + toHexString(composeBits(major, minor, ctxProfileBits)); } @@ -1371,6 +1397,56 @@ public abstract class GLContextImpl extends GLContext { return lock.getQueueLength()>0; } + //--------------------------------------------------------------------------- + // Special FBO hook + // + + /** + * Tracks {@link GL#GL_FRAMEBUFFER}, {@link GL2GL3#GL_DRAW_FRAMEBUFFER} and {@link GL2GL3#GL_READ_FRAMEBUFFER} + * to be returned via {@link #getBoundFramebuffer(int)}. + * + *

      Invoked by {@link GL#glBindFramebuffer(int, int)}.

      + * + *

      Assumes valid framebufferName range of [0..{@link Integer#MAX_VALUE}]

      + * + *

      Does not throw an exception if target is unknown or framebufferName invalid.

      + */ + public final void setBoundFramebuffer(int target, int framebufferName) { + if(0 > framebufferName) { + return; // ignore invalid name + } + switch(target) { + case GL.GL_FRAMEBUFFER: + boundFBOTarget[0] = framebufferName; // draw + boundFBOTarget[1] = framebufferName; // read + break; + case GL2GL3.GL_DRAW_FRAMEBUFFER: + boundFBOTarget[0] = framebufferName; // draw + break; + case GL2GL3.GL_READ_FRAMEBUFFER: + boundFBOTarget[1] = framebufferName; // read + break; + default: // ignore untracked target + } + } + @Override + public final int getBoundFramebuffer(int target) { + switch(target) { + case GL.GL_FRAMEBUFFER: + case GL2GL3.GL_DRAW_FRAMEBUFFER: + return boundFBOTarget[0]; // draw + case GL2GL3.GL_READ_FRAMEBUFFER: + return boundFBOTarget[1]; // read + default: + throw new InternalError("Invalid FBO target name: "+toHexString(target)); + } + } + + @Override + public final int getDefaultDrawFramebuffer() { return drawable.getDefaultDrawFramebuffer(); } + @Override + public final int getDefaultReadFramebuffer() { return drawable.getDefaultReadFramebuffer(); } + //--------------------------------------------------------------------------- // GL_ARB_debug_output, GL_AMD_debug_output helpers // diff --git a/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java b/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java index b950c2fdf..0000e6199 100644 --- a/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java +++ b/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java @@ -37,6 +37,8 @@ import javax.media.opengl.GLException; import com.jogamp.common.os.Platform; import com.jogamp.gluegen.runtime.ProcAddressTable; +import com.jogamp.opengl.GLExtensions; + import jogamp.opengl.gl4.GL4bcProcAddressTable; /** @@ -54,12 +56,6 @@ import jogamp.opengl.gl4.GL4bcProcAddressTable; * the messages are translated to ARB {@link GLDebugMessage}, using {@link GLDebugMessage#translateAMDEvent(javax.media.opengl.GLContext, long, int, int, int, String)}.

      */ public class GLDebugMessageHandler { - /** Extension GL_ARB_debug_output implementing GLDebugMessage */ - public static final String GL_ARB_debug_output = "GL_ARB_debug_output".intern(); - - /** Extension GL_AMD_debug_output implementing GLDebugMessage */ - public static final String GL_AMD_debug_output = "GL_AMD_debug_output".intern(); - private static final boolean DEBUG = Debug.debug("GLDebugMessageHandler"); private static final int EXT_ARB = 1; @@ -131,11 +127,11 @@ public class GLDebugMessageHandler { } return; } - if( ctx.isExtensionAvailable(GL_ARB_debug_output) ) { - extName = GL_ARB_debug_output; + if( ctx.isExtensionAvailable(GLExtensions.ARB_debug_output) ) { + extName = GLExtensions.ARB_debug_output; extType = EXT_ARB; - } else if( ctx.isExtensionAvailable(GL_AMD_debug_output) ) { - extName = GL_AMD_debug_output; + } else if( ctx.isExtensionAvailable(GLExtensions.AMD_debug_output) ) { + extName = GLExtensions.AMD_debug_output; extType = EXT_AMD; } if(DEBUG) { @@ -145,6 +141,8 @@ public class GLDebugMessageHandler { if(0 == extType) { if(DEBUG) { System.err.println("GLDebugMessageHandler: No extension available! "+ctx.getGLVersion()); + System.err.println("GL_EXTENSIONS "+ctx.getGLExtensionCount()); + System.err.println(ctx.getGLExtensionsString()); } return; } @@ -190,11 +188,11 @@ public class GLDebugMessageHandler { } public final boolean isExtensionARB() { - return extName == GL_ARB_debug_output; + return extName == GLExtensions.ARB_debug_output; } public final boolean isExtensionAMD() { - return extName == GL_AMD_debug_output; + return extName == GLExtensions.AMD_debug_output; } /** diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index e5c44a8d4..897d3fcaf 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -47,7 +47,8 @@ import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.OffscreenLayerSurface; import javax.media.nativewindow.ProxySurface; -import javax.media.nativewindow.SurfaceChangeable; +import javax.media.nativewindow.MutableSurface; +import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; @@ -88,7 +89,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { return null; } protected abstract GLContext getOrCreateSharedContextImpl(AbstractGraphicsDevice device); - + /** * Returns the shared device mapped to the device {@link AbstractGraphicsDevice#getConnection()}, * either a preexisting or newly created, or null if creation failed or not supported.
      @@ -115,7 +116,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { } protected abstract AbstractGraphicsDevice getOrCreateSharedDeviceImpl(AbstractGraphicsDevice device); - /** + /** * Returns the GLDynamicLookupHelper * @param profile if EGL/ES, profile 1 refers to ES1 and 2 to ES2, * otherwise the profile is ignored. @@ -125,6 +126,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { //--------------------------------------------------------------------------- // Dispatching GLDrawable construction in respect to the NativeSurface Capabilities // + @Override public GLDrawable createGLDrawable(NativeSurface target) { if (target == null) { throw new IllegalArgumentException("Null target"); @@ -132,23 +134,37 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { final MutableGraphicsConfiguration config = (MutableGraphicsConfiguration) target.getGraphicsConfiguration(); final GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); final AbstractGraphicsDevice adevice = config.getScreen().getDevice(); + final boolean isFBOAvailable = GLContext.isFBOAvailable(adevice, chosenCaps.getGLProfile()); GLDrawable result = null; adevice.lock(); try { final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(target, true); if(null != ols) { - // layered surface -> Offscreen/PBuffer + // layered surface -> Offscreen/[FBO|PBuffer] final GLCapabilities chosenCapsMod = (GLCapabilities) chosenCaps.cloneMutable(); chosenCapsMod.setOnscreen(false); - chosenCapsMod.setPBuffer(canCreateGLPbuffer(adevice)); + if( isFBOAvailable ) { + chosenCapsMod.setFBO(true); + } else if(canCreateGLPbuffer(adevice)) { + chosenCapsMod.setPBuffer(true); + } else { + chosenCapsMod.setFBO(false); + chosenCapsMod.setPBuffer(false); + } config.setChosenCapabilities(chosenCapsMod); if(DEBUG) { System.err.println("GLDrawableFactoryImpl.createGLDrawable -> OnscreenDrawable -> Offscreen-Layer: "+target); } - if( ! ( target instanceof SurfaceChangeable ) ) { + if( ! ( target instanceof MutableSurface ) ) { throw new IllegalArgumentException("Passed NativeSurface must implement SurfaceChangeable for offscreen layered surface: "+target); + } + if( ((GLCapabilitiesImmutable)config.getRequestedCapabilities()).isFBO() && isFBOAvailable ) { + // FIXME JAU: Need to revise passed MutableSurface to work w/ FBO .. + final GLDrawableImpl dummyDrawable = createOnscreenDrawableImpl(target); + result = new GLFBODrawableImpl(this, dummyDrawable, target, target.getWidth(), target.getHeight(), 0 /* textureUnit */); + } else { + result = createOffscreenDrawableImpl(target); } - result = createOffscreenDrawableImpl(target); } else if(chosenCaps.isOnscreen()) { // onscreen if(DEBUG) { @@ -158,12 +174,18 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { } else { // offscreen if(DEBUG) { - System.err.println("GLDrawableFactoryImpl.createGLDrawable -> OffScreenDrawable (PBuffer: "+chosenCaps.isPBuffer()+"): "+target); + System.err.println("GLDrawableFactoryImpl.createGLDrawable -> OffScreenDrawable, FBO-chosen(-avail)/PBuffer: "+chosenCaps.isFBO()+"("+isFBOAvailable+")/"+chosenCaps.isPBuffer()+": "+target); } - if( ! ( target instanceof SurfaceChangeable ) ) { + if( ! ( target instanceof MutableSurface ) ) { throw new IllegalArgumentException("Passed NativeSurface must implement SurfaceChangeable for offscreen: "+target); } - result = createOffscreenDrawableImpl(target); + if( ((GLCapabilitiesImmutable)config.getRequestedCapabilities()).isFBO() && isFBOAvailable ) { + // FIXME JAU: Need to revise passed MutableSurface to work w/ FBO .. + final GLDrawableImpl dummyDrawable = createOnscreenDrawableImpl(target); + result = new GLFBODrawableImpl(this, dummyDrawable, target, target.getWidth(), target.getHeight(), 0 /* textureUnit */); + } else { + result = createOffscreenDrawableImpl(target); + } } } finally { adevice.unlock(); @@ -176,43 +198,42 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { //--------------------------------------------------------------------------- // - // Onscreen GLDrawable construction + // Onscreen GLDrawable construction // protected abstract GLDrawableImpl createOnscreenDrawableImpl(NativeSurface target); //--------------------------------------------------------------------------- // - // PBuffer Offscreen GLDrawable construction + // PBuffer Offscreen GLDrawable construction // - + + @Override public abstract boolean canCreateGLPbuffer(AbstractGraphicsDevice device); + @Override public GLPbuffer createGLPbuffer(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, int width, int height, GLContext shareWith) { - if(height<=0 || height<=0) { - throw new GLException("Width and height of pbuffer must be positive (were (" + - width + ", " + height + "))"); + if(width<=0 || height<=0) { + throw new GLException("initial size must be positive (were (" + width + " x " + height + "))"); } - AbstractGraphicsDevice device = getOrCreateSharedDevice(deviceReq); if(null == device) { throw new GLException("No shared device for requested: "+deviceReq); } - - if (!canCreateGLPbuffer(device)) { - throw new GLException("Pbuffer support not available with device: "+device); + if ( !canCreateGLPbuffer(device) ) { + throw new GLException("Pbuffer not available with device: "+device); } - - GLCapabilitiesImmutable capsChosen = GLGraphicsConfigurationUtil.fixGLPBufferGLCapabilities(capsRequested); + + final GLCapabilitiesImmutable capsChosen = GLGraphicsConfigurationUtil.fixGLPBufferGLCapabilities(capsRequested); GLDrawableImpl drawable = null; device.lock(); try { - drawable = (GLDrawableImpl) createGLDrawable( createOffscreenSurfaceImpl(device, capsChosen, capsRequested, chooser, width, height) ); + drawable = (GLDrawableImpl) createGLDrawable( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, width, height, null) ); if(null != drawable) { drawable.setRealized(true); } @@ -228,75 +249,155 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { //--------------------------------------------------------------------------- // - // Offscreen GLDrawable construction + // Offscreen GLDrawable construction // - protected abstract GLDrawableImpl createOffscreenDrawableImpl(NativeSurface target) ; - + @Override public GLDrawable createOffscreenDrawable(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, - int width, - int height) { + int width, int height) { if(width<=0 || height<=0) { - throw new GLException("Width and height of pbuffer must be positive (were (" + - width + ", " + height + "))"); + throw new GLException("initial size must be positive (were (" + width + " x " + height + "))"); } - AbstractGraphicsDevice device = getOrCreateSharedDevice(deviceReq); + final AbstractGraphicsDevice device = getOrCreateSharedDevice(deviceReq); if(null == device) { throw new GLException("No shared device for requested: "+deviceReq); } - GLCapabilitiesImmutable capsChosen = GLGraphicsConfigurationUtil.fixOffScreenGLCapabilities(capsRequested, canCreateGLPbuffer(deviceReq)); - + + if( capsRequested.isFBO() && GLContext.isFBOAvailable(device, capsRequested.getGLProfile()) ) { + device.lock(); + try { + return createFBODrawableImpl(device, capsRequested, chooser, width, height); + } finally { + device.unlock(); + } + } + + final GLCapabilitiesImmutable capsChosen = GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(capsRequested, false, canCreateGLPbuffer(device)); device.lock(); try { - return createGLDrawable( createOffscreenSurfaceImpl(device, capsChosen, capsRequested, chooser, width, height) ); + return createOffscreenDrawableImpl( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, width, height, null) ); } finally { device.unlock(); } } - public NativeSurface createOffscreenSurface(AbstractGraphicsDevice deviceReq, - GLCapabilitiesImmutable capsRequested, - GLCapabilitiesChooser chooser, - int width, int height) { - AbstractGraphicsDevice device = getOrCreateSharedDevice(deviceReq); + /** Creates a platform independent offscreen FBO GLDrawable implementation */ + protected GLDrawable createFBODrawableImpl(AbstractGraphicsDevice device, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, + int initialWidth, int initialHeight) { + final GLCapabilitiesImmutable dummyCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(requestedCaps); + final NativeSurface dummySurface = createDummySurfaceImpl(device, true, dummyCaps, null, 64, 64); + final GLDrawableImpl dummyDrawable = createOnscreenDrawableImpl(dummySurface); + + return new GLFBODrawableImpl(this, dummyDrawable, dummySurface, initialWidth, initialHeight, 0 /* textureUnit */); + } + + /** Creates a platform dependent offscreen pbuffer/pixmap GLDrawable implementation */ + protected abstract GLDrawableImpl createOffscreenDrawableImpl(NativeSurface target) ; + + /** + * Creates a mutable {@link ProxySurface} w/o defined surface handle. + *

      + * It's {@link AbstractGraphicsConfiguration} is properly set according to the given {@link GLCapabilitiesImmutable}. + *

      + *

      + * Lifecycle (destruction) of the TBD surface handle shall be handled by the caller. + *

      + * @param device a valid platform dependent target device. + * @param createNewDevice if true a new device instance is created using device details, + * otherwise device instance is used as-is. + * @param capsChosen + * @param capsRequested + * @param chooser the custom chooser, may be null for default + * @param width the initial width + * @param height the initial height + * @param lifecycleHook 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, int width, int height, UpstreamSurfaceHook lifecycleHook); + + /** + * A dummy surface is not visible on screen and will not be used to render directly to, + * it maybe on- or offscreen. + *

      + * 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. + *

      + * @param deviceReq which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared device to be used, may be null 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 MutableSurface} instance w/o defined surface handle + */ + public NativeSurface 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); } - GLCapabilitiesImmutable capsChosen = GLGraphicsConfigurationUtil.fixOffScreenGLCapabilities(capsRequested, canCreateGLPbuffer(deviceReq)); - device.lock(); try { - return createOffscreenSurfaceImpl(device, capsChosen, capsRequested, chooser, width, height); + return createDummySurfaceImpl(device, true, requestedCaps, chooser, width, height); } finally { device.unlock(); } } - + /** - * creates an offscreen NativeSurface, which must implement SurfaceChangeable as well, - * so the windowing system related implementation is able to set the surface handle. + * A dummy surface is not visible on screen and will not be used to render directly to, + * it maybe on- or offscreen. + *

      + * 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. + *

      + * @param device a valid platform dependent target device. + * @param createNewDevice if true a new device instance is created using device details, + * otherwise device instance is used as-is. + * @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 MutableSurface} instance w/o defined surface handle */ - protected abstract NativeSurface createOffscreenSurfaceImpl(AbstractGraphicsDevice device, - GLCapabilitiesImmutable capabilities, GLCapabilitiesImmutable capsRequested, - GLCapabilitiesChooser chooser, - int width, int height); + public abstract ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice device, boolean createNewDevice, + GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height); - public ProxySurface createProxySurface(AbstractGraphicsDevice device, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser) { + //--------------------------------------------------------------------------- + // + // 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: "+device); + throw new GLException("No shared device for requested: "+deviceReq); } device.lock(); try { - return createProxySurfaceImpl(device, windowHandle, capsRequested, chooser); + return createProxySurfaceImpl(device, screenIdx, windowHandle, capsRequested, chooser, upstream); } finally { device.unlock(); } - } - - protected abstract ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice device, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser); + } + + /** + * Creates a {@link ProxySurface} with a set surface handle. + *

      + * Implementation is also required to allocate it's own {@link AbstractGraphicsDevice} instance. + *

      + * @param upstream TODO + */ + protected abstract ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, + GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream); //--------------------------------------------------------------------------- // @@ -304,7 +405,8 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { // protected abstract GLContext createExternalGLContextImpl(); - + + @Override public GLContext createExternalGLContext() { NativeWindowFactory.getDefaultToolkitLock().lock(); try { @@ -316,6 +418,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { protected abstract GLDrawable createExternalGLDrawableImpl(); + @Override public GLDrawable createExternalGLDrawable() { NativeWindowFactory.getDefaultToolkitLock().lock(); try { @@ -398,7 +501,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { * 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, @@ -484,7 +587,8 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { return; if (gammaShutdownHook == null) { gammaShutdownHook = new Thread(new Runnable() { - public void run() { + @Override + public void run() { synchronized (GLDrawableFactoryImpl.this) { resetGammaRamp(originalGammaRamp); } diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java index 58a4ac6b4..abf2bf557 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java @@ -42,6 +42,7 @@ package jogamp.opengl; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.ProxySurface; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; @@ -75,7 +76,7 @@ public abstract class GLDrawableImpl implements GLDrawable { if( !realized ) { return; // destroyed already } - GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable)surface.getGraphicsConfiguration().getChosenCapabilities(); + final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable)surface.getGraphicsConfiguration().getChosenCapabilities(); if ( caps.getDoubleBuffered() ) { if(!surface.surfaceSwap()) { int lockRes = lockSurface(); // it's recursive, so it's ok within [makeCurrent .. release] @@ -149,6 +150,9 @@ public abstract class GLDrawableImpl implements GLDrawable { realized = realizedArg; AbstractGraphicsDevice aDevice = surface.getGraphicsConfiguration().getScreen().getDevice(); if(realizedArg) { + if(surface instanceof ProxySurface) { + ((ProxySurface)surface).createNotify(); + } if(NativeSurface.LOCK_SURFACE_NOT_READY >= lockSurface()) { throw new GLException("GLDrawableImpl.setRealized(true): Surface not ready (lockSurface)"); } @@ -156,17 +160,21 @@ public abstract class GLDrawableImpl implements GLDrawable { aDevice.lock(); } try { - setRealizedImpl(); if(realizedArg) { + setRealizedImpl(); updateHandle(); } else { destroyHandle(); + setRealizedImpl(); } } finally { if(realizedArg) { unlockSurface(); } else { aDevice.unlock(); + if(surface instanceof ProxySurface) { + ((ProxySurface)surface).destroyNotify(); + } } } } else if(DEBUG) { @@ -175,6 +183,39 @@ public abstract class GLDrawableImpl implements GLDrawable { } protected abstract void setRealizedImpl(); + /** + * Callback for special implementations, allowing GLContext to trigger GL related lifecycle: construct, destroy. + *

      + * If realized is true, the context has just been created and made current. + *

      + *

      + * If realized is false, the context is still current and will be release and destroyed after this method returns. + *

      + *

      + * @see #contextMadeCurrent(GLContext, boolean) + */ + protected void contextRealized(GLContext glc, boolean realized) {} + + /** + * Callback for special implementations, allowing GLContext to trigger GL related lifecycle: makeCurrent, release. + *

      + * Will not be called if {@link #contextRealized(GLContext, boolean)} has been triggered. + *

      + *

      + * If current is true, the context has just been made current. + *

      + *

      + * If current is false, the context is still current and will be release after this method returns. + *

      + * @see #contextRealized(GLContext, boolean) + */ + protected void contextMadeCurrent(GLContext glc, boolean current) { } + + /** Callback for special implementations, allowing GLContext to fetch a custom default render framebuffer. Defaults to zero.*/ + protected int getDefaultDrawFramebuffer() { return 0; } + /** Callback for special implementations, allowing GLContext to fetch a custom default read framebuffer. Defaults to zero. */ + protected int getDefaultReadFramebuffer() { return 0; } + @Override public final synchronized boolean isRealized() { return realized; @@ -190,10 +231,12 @@ public abstract class GLDrawableImpl implements GLDrawable { return surface.getHeight(); } + /** @see NativeSurface#lockSurface() */ public final int lockSurface() throws GLException { return surface.lockSurface(); } + /** @see NativeSurface#unlockSurface() */ public final void unlockSurface() { surface.unlockSurface(); } diff --git a/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java new file mode 100644 index 000000000..b7ea4f826 --- /dev/null +++ b/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java @@ -0,0 +1,138 @@ +package jogamp.opengl; + +import javax.media.nativewindow.NativeSurface; +import javax.media.opengl.GL; +import javax.media.opengl.GL2GL3; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLException; + +import com.jogamp.nativewindow.MutableGraphicsConfiguration; +import com.jogamp.opengl.FBObject; +import com.jogamp.opengl.FBObject.Attachment; +import com.jogamp.opengl.FBObject.TextureAttachment; + +/** + * Offscreen GLDrawable implementation using framebuffer object (FBO) + * as it's offscreen rendering mechanism. + * + * @see GLDrawableImpl#contextRealized(GLContext, boolean) + * @see GLDrawableImpl#contextMadeCurrent(GLContext, boolean) + * @see GLDrawableImpl#getDefaultDrawFramebuffer() + * @see GLDrawableImpl#getDefaultReadFramebuffer() + */ +public class GLFBODrawableImpl extends GLDrawableImpl { + final GLDrawableImpl parent; + final FBObject fbo; + int texUnit; + int samplesTexUnit = 0; + int width=0, height=0, samples=0; + + protected GLFBODrawableImpl(GLDrawableFactoryImpl factory, GLDrawableImpl parent, + NativeSurface surface, int initialWidth, int initialHeight, int textureUnit) { + super(factory, surface, false); + this.parent = parent; + this.texUnit = textureUnit; + final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) surface.getGraphicsConfiguration().getChosenCapabilities(); + this.width = initialWidth; + this.height = initialHeight; + this.samples = caps.getNumSamples(); + this.fbo = new FBObject(); + } + + @Override + protected void contextRealized(GLContext glc, boolean realized) { + final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) surface.getGraphicsConfiguration().getChosenCapabilities(); + final GL gl = glc.getGL(); + if(realized) { + fbo.reset(gl, width, height, samples); + samples = fbo.getNumSamples(); // update, maybe capped + if(samples > 0) { + fbo.attachColorbuffer(gl, 0, caps.getAlphaBits()>0); + } else { + fbo.attachTexture2D(gl, 0, caps.getAlphaBits()>0); + } + if( caps.getStencilBits() > 0 ) { + fbo.attachRenderbuffer(gl, Attachment.Type.DEPTH_STENCIL, 24); + } else { + fbo.attachRenderbuffer(gl, Attachment.Type.DEPTH, 24); + } + } else if(null != fbo) { + fbo.destroy(gl); + } + } + + @Override + protected void contextMadeCurrent(GLContext glc, boolean current) { + final GL gl = glc.getGL(); + if(current) { + fbo.bind(gl); + } else { + fbo.unbind(gl); + gl.glActiveTexture(GL.GL_TEXTURE0 + texUnit); + fbo.use(gl, samples > 0 ? fbo.getSamplingSink() : (TextureAttachment) fbo.getColorbuffer(0) ); + if( samples > 0) { + gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, fbo.getReadFramebuffer()); + } + } + } + + @Override + protected int getDefaultDrawFramebuffer() { return fbo.getWriteFramebuffer(); } + + @Override + protected int getDefaultReadFramebuffer() { return fbo.getReadFramebuffer(); } + + public FBObject getFBObject() { return fbo; } + + public void setSize(GL gl, int newWidth, int newHeight) throws GLException { + width = newWidth; + height = newHeight; + fbo.reset(gl, width, height, samples); + samples = fbo.getNumSamples(); // update, maybe capped + } + + public void setSamples(GL gl, int newSamples) throws GLException { + samples = newSamples; + fbo.reset(gl, width, height, samples); + samples = fbo.getNumSamples(); // update, maybe capped + } + + + @Override + public GLContext createContext(GLContext shareWith) { + final GLContext ctx = parent.createContext(shareWith); + ctx.setGLDrawable(this, false); + return ctx; + } + + @Override + public GLDynamicLookupHelper getGLDynamicLookupHelper() { + return parent.getGLDynamicLookupHelper(); + } + + @Override + protected void swapBuffersImpl() { + } + + @Override + protected void setRealizedImpl() { + parent.setRealized(realized); + if(realized) { + final MutableGraphicsConfiguration msConfig = (MutableGraphicsConfiguration) surface.getGraphicsConfiguration(); + final GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable) msConfig.getChosenCapabilities(); + final GLCapabilitiesImmutable chosenFBOCaps = GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(chosenCaps, true /*FBO*/, false /*PBO*/); + msConfig.setChosenCapabilities(chosenFBOCaps); + } + } + + @Override + public int getWidth() { + return width; + } + + @Override + public int getHeight() { + return height; + } +} diff --git a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java index b7c15bfda..900d6a2a0 100644 --- a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java +++ b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java @@ -38,7 +38,8 @@ public class GLGraphicsConfigurationUtil { public static final int WINDOW_BIT = 1 << 0; public static final int BITMAP_BIT = 1 << 1; public static final int PBUFFER_BIT = 1 << 2; - public static final int ALL_BITS = WINDOW_BIT | BITMAP_BIT | PBUFFER_BIT ; + public static final int FBO_BIT = 1 << 3; + public static final int ALL_BITS = WINDOW_BIT | BITMAP_BIT | PBUFFER_BIT | FBO_BIT ; public static final StringBuilder winAttributeBits2String(StringBuilder sb, int winattrbits) { if(null==sb) { @@ -61,30 +62,43 @@ public class GLGraphicsConfigurationUtil { sb.append(", "); } sb.append("PBUFFER"); + seperator=true; + } + if( 0 != ( FBO_BIT & winattrbits ) ) { + if(seperator) { + sb.append(", "); + } + sb.append("FBO"); } return sb; } /** + * @param isFBO TODO * @return bitmask representing the input boolean in exclusive or logic, ie only one bit will be set */ - public static final int getWinAttributeBits(boolean isOnscreen, boolean isPBuffer) { + public static final int getWinAttributeBits(boolean isOnscreen, boolean isPBuffer, boolean isFBO) { int winattrbits = 0; if(isOnscreen) { winattrbits |= WINDOW_BIT; - } else if (!isPBuffer) { - winattrbits |= BITMAP_BIT; } else { - winattrbits |= PBUFFER_BIT; + if(isFBO) { + winattrbits |= FBO_BIT; + } + if (!isPBuffer) { + winattrbits |= BITMAP_BIT; + } else { + winattrbits |= PBUFFER_BIT; + } } return winattrbits; } /** - * @see #getWinAttributeBits(boolean, boolean) + * @see #getWinAttributeBits(boolean, boolean, boolean) */ public static final int getWinAttributeBits(GLCapabilitiesImmutable caps) { - return getWinAttributeBits(caps.isOnscreen(), caps.isPBuffer()); + return getWinAttributeBits(caps.isOnscreen(), caps.isPBuffer(), false); } public static final boolean addGLCapabilitiesPermutations(List capsBucket, GLCapabilitiesImmutable temp, int winattrbits) { @@ -92,43 +106,58 @@ public class GLGraphicsConfigurationUtil { if( 0 != ( WINDOW_BIT & winattrbits ) ) { GLCapabilities cpy = (GLCapabilities) temp.cloneMutable(); cpy.setOnscreen(true); + cpy.setPBuffer(false); + cpy.setFBO(false); capsBucket.add(cpy); } - if( 0 != ( PBUFFER_BIT & winattrbits ) ) { + if( 0 != ( PBUFFER_BIT & winattrbits ) || 0 != ( FBO_BIT & winattrbits ) ) { GLCapabilities cpy = (GLCapabilities) temp.cloneMutable(); - cpy.setPBuffer(true); + cpy.setFBO(0 != ( FBO_BIT & winattrbits )); + cpy.setPBuffer(0 != ( PBUFFER_BIT & winattrbits )); capsBucket.add(cpy); } if( 0 != ( BITMAP_BIT & winattrbits ) ) { GLCapabilities cpy = (GLCapabilities) temp.cloneMutable(); cpy.setOnscreen(false); cpy.setPBuffer(false); + cpy.setFBO(false); capsBucket.add(cpy); } return capsBucket.size() > preSize; } - public static GLCapabilitiesImmutable fixGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean pbufferAvailable) + public static GLCapabilitiesImmutable fixGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean fboAvailable, boolean pbufferAvailable) { if( !capsRequested.isOnscreen() ) { - return fixOffScreenGLCapabilities(capsRequested, pbufferAvailable); + return fixOffscreenGLCapabilities(capsRequested, fboAvailable, pbufferAvailable); } - return capsRequested; + return fixOnscreenGLCapabilities(capsRequested); } - public static GLCapabilitiesImmutable fixOffScreenGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean pbufferAvailable) + public static GLCapabilitiesImmutable fixOnscreenGLCapabilities(GLCapabilitiesImmutable capsRequested) + { + if( !capsRequested.isOnscreen() ) { + // fix caps .. + GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); + caps2.setOnscreen(true); + return caps2; + } + return capsRequested; + } + + public static GLCapabilitiesImmutable fixOffscreenGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean fboAvailable, boolean pbufferAvailable) { if( capsRequested.getDoubleBuffered() || capsRequested.isOnscreen() || - ( !pbufferAvailable && capsRequested.isPBuffer() ) ) + ( fboAvailable != capsRequested.isFBO() ) || + ( pbufferAvailable != capsRequested.isPBuffer() ) ) { // fix caps .. GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); caps2.setDoubleBuffered(false); // FIXME DBLBUFOFFSCRN caps2.setOnscreen(false); - if(caps2.isPBuffer() && !pbufferAvailable) { - caps2.setPBuffer(false); - } + caps2.setFBO( fboAvailable ); + caps2.setPBuffer( pbufferAvailable ); return caps2; } return capsRequested; @@ -136,12 +165,13 @@ public class GLGraphicsConfigurationUtil { public static GLCapabilitiesImmutable fixGLPBufferGLCapabilities(GLCapabilitiesImmutable capsRequested) { - if( capsRequested.getDoubleBuffered() || capsRequested.isOnscreen() || !capsRequested.isPBuffer()) { + if( capsRequested.getDoubleBuffered() || capsRequested.isOnscreen() || !capsRequested.isPBuffer() || capsRequested.isFBO() ) { // fix caps .. GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); caps2.setDoubleBuffered(false); // FIXME DBLBUFOFFSCRN - we don't need to be single buffered .. caps2.setOnscreen(false); caps2.setPBuffer(true); + caps2.setFBO(false); return caps2; } return capsRequested; diff --git a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java index a8277fd71..bbc28e283 100644 --- a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java @@ -54,8 +54,7 @@ import javax.media.opengl.GLPbuffer; public class GLPbufferImpl extends GLAutoDrawableBase implements GLPbuffer { private int floatMode; - public GLPbufferImpl(GLDrawableImpl pbufferDrawable, - GLContext sharedContext) { + public GLPbufferImpl(GLDrawableImpl pbufferDrawable, GLContext sharedContext) { super(pbufferDrawable, null); // drawable := pbufferDrawable GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) @@ -111,6 +110,11 @@ public class GLPbufferImpl extends GLAutoDrawableBase implements GLPbuffer { // GLAutoDrawable completion // + @Override + public final Object getUpstreamWidget() { + return null; + } + @Override public void destroy() { defaultDestroyOp(); diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLContext.java b/src/jogl/classes/jogamp/opengl/egl/EGLContext.java index 65a4c3ece..c5d0df645 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLContext.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLContext.java @@ -110,14 +110,8 @@ public abstract class EGLContext extends GLContextImpl { @Override protected void makeCurrentImpl() throws GLException { - if(EGL.EGL_NO_DISPLAY==((EGLDrawable)drawable).getDisplay() ) { - throw new GLException("drawable not properly initialized, NO DISPLAY: "+drawable); - } if (EGL.eglGetCurrentContext() != contextHandle) { - if (!EGL.eglMakeCurrent(((EGLDrawable)drawable).getDisplay(), - drawable.getHandle(), - drawableRead.getHandle(), - contextHandle)) { + if (!EGL.eglMakeCurrent(drawable.getNativeSurface().getDisplayHandle(), drawable.getHandle(), drawableRead.getHandle(), contextHandle)) { throw new GLException("Error making context 0x" + Long.toHexString(contextHandle) + " current: error code 0x" + Integer.toHexString(EGL.eglGetError())); } @@ -126,10 +120,7 @@ public abstract class EGLContext extends GLContextImpl { @Override protected void releaseImpl() throws GLException { - if (!EGL.eglMakeCurrent(((EGLDrawable)drawable).getDisplay(), - EGL.EGL_NO_SURFACE, - EGL.EGL_NO_SURFACE, - EGL.EGL_NO_CONTEXT)) { + if (!EGL.eglMakeCurrent(drawable.getNativeSurface().getDisplayHandle(), EGL.EGL_NO_SURFACE, EGL.EGL_NO_SURFACE, EGL.EGL_NO_CONTEXT)) { throw new GLException("Error freeing OpenGL context 0x" + Long.toHexString(contextHandle) + ": error code 0x" + Integer.toHexString(EGL.eglGetError())); } @@ -137,7 +128,7 @@ public abstract class EGLContext extends GLContextImpl { @Override protected void destroyImpl() throws GLException { - if (!EGL.eglDestroyContext(((EGLDrawable)drawable).getDisplay(), contextHandle)) { + if (!EGL.eglDestroyContext(drawable.getNativeSurface().getDisplayHandle(), contextHandle)) { final int eglError = EGL.eglGetError(); if(EGL.EGL_SUCCESS != eglError) { /* oops, Mesa EGL impl. may return false, but has no EGL error */ throw new GLException("Error destroying OpenGL context 0x" + @@ -158,16 +149,16 @@ public abstract class EGLContext extends GLContextImpl { @Override protected boolean createImpl(GLContextImpl shareWith) throws GLException { - long eglDisplay = ((EGLDrawable)drawable).getDisplay(); - EGLGraphicsConfiguration config = ((EGLDrawable)drawable).getGraphicsConfiguration(); - GLProfile glProfile = drawable.getGLProfile(); - long eglConfig = config.getNativeConfig(); + final EGLGraphicsConfiguration config = (EGLGraphicsConfiguration) drawable.getNativeSurface().getGraphicsConfiguration(); + final long eglDisplay = config.getScreen().getDevice().getHandle(); + final GLProfile glProfile = drawable.getGLProfile(); + final long eglConfig = config.getNativeConfig(); long shareWithHandle = EGL.EGL_NO_CONTEXT; - if (eglDisplay == 0) { + if ( 0 == eglDisplay ) { throw new GLException("Error: attempted to create an OpenGL context without a display connection"); } - if (eglConfig == 0) { + if ( 0 == eglConfig ) { throw new GLException("Error: attempted to create an OpenGL context without a graphics configuration"); } @@ -217,10 +208,7 @@ public abstract class EGLContext extends GLContextImpl { ",\n\t"+this+ ",\n\tsharing with 0x" + Long.toHexString(shareWithHandle)); } - if (!EGL.eglMakeCurrent(((EGLDrawable)drawable).getDisplay(), - drawable.getHandle(), - drawableRead.getHandle(), - contextHandle)) { + if (!EGL.eglMakeCurrent(eglDisplay, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) { throw new GLException("Error making context 0x" + Long.toHexString(contextHandle) + " current: error code " + EGL.eglGetError()); } @@ -269,8 +257,7 @@ public abstract class EGLContext extends GLContextImpl { eglQueryStringInitialized = true; } if (eglQueryStringAvailable) { - final String ret = EGL.eglQueryString(((EGLDrawable)drawable).getDisplay(), - EGL.EGL_EXTENSIONS); + final String ret = EGL.eglQueryString(drawable.getNativeSurface().getDisplayHandle(), EGL.EGL_EXTENSIONS); if (DEBUG) { System.err.println("EGL extensions: " + ret); } @@ -291,7 +278,7 @@ public abstract class EGLContext extends GLContextImpl { } return false; } - return EGL.eglSwapInterval(((EGLDrawable)drawable).getDisplay(), interval); + return EGL.eglSwapInterval(drawable.getNativeSurface().getDisplayHandle(), interval); } @Override @@ -300,6 +287,45 @@ public abstract class EGLContext extends GLContextImpl { @Override public abstract void releasePbufferFromTexture(); + // + // Accessible .. + // + + /** + * If context is an ES profile, map it to the given device + * via {@link GLContext#mapAvailableGLVersion(AbstractGraphicsDevice, int, int, int, int, int)}. + *

      + * We intentionally override a non native EGL device ES profile mapping, + * i.e. this will override/modify an already 'set' X11/WGL/.. mapping. + *

      + * + * @param device + */ + protected void mapCurrentAvailableGLVersion(AbstractGraphicsDevice device) { + mapCurrentAvailableGLVersionImpl(device, ctxMajorVersion, ctxMinorVersion, ctxOptions); + } + + protected static void mapStaticGLESVersion(AbstractGraphicsDevice device, int major) { + int ctp = ( 2 == major ) ? ( GLContext.CTX_PROFILE_ES | GLContext.CTX_IMPL_ES2_COMPAT | GLContext.CTX_IMPL_FBO ) : ( GLContext.CTX_PROFILE_ES ); + mapCurrentAvailableGLVersionImpl(device, major, 0, ctp); + } + private static void mapCurrentAvailableGLVersionImpl(AbstractGraphicsDevice device, int major, int minor, int ctp) { + if( 0 != ( ctp & GLContext.CTX_PROFILE_ES) ) { + // ES1 or ES2 + final int reqMajor = major; + final int reqProfile = GLContext.CTX_PROFILE_ES; + GLContext.mapAvailableGLVersion(device, reqMajor, reqProfile, + major, minor, ctp); + } + } + + protected static boolean getAvailableGLVersionsSet(AbstractGraphicsDevice device) { + return GLContext.getAvailableGLVersionsSet(device); + } + protected static void setAvailableGLVersionsSet(AbstractGraphicsDevice device) { + GLContext.setAvailableGLVersionsSet(device); + } + protected static String toHexString(int hex) { return GLContext.toHexString(hex); } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java index 7f10d3bd9..432010f49 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java @@ -136,7 +136,17 @@ public class EGLDisplayUtil { return res; } - public static final EGLGraphicsDevice.EGLTerminateCallback eglTerminateCallback = new EGLGraphicsDevice.EGLTerminateCallback() { + public static final EGLGraphicsDevice.EGLDisplayLifecycleCallback eglLifecycleCallback = new EGLGraphicsDevice.EGLDisplayLifecycleCallback() { + public long eglGetAndInitDisplay(long nativeDisplayID) { + long eglDisplay = EGLDisplayUtil.eglGetDisplay(nativeDisplayID); + if (eglDisplay == EGL.EGL_NO_DISPLAY) { + throw new GLException("Failed to created EGL display: 0x"+Long.toHexString(nativeDisplayID)+", error 0x"+Integer.toHexString(EGL.eglGetError())); + } + if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) { + throw new GLException("eglInitialize failed"+", error 0x"+Integer.toHexString(EGL.eglGetError())); + } + return eglDisplay; + } public void eglTerminate(long eglDisplayHandle) { EGLDisplayUtil.eglTerminate(eglDisplayHandle); } @@ -148,17 +158,12 @@ public class EGLDisplayUtil { * @param unitID * @return an initialized EGLGraphicsDevice * @throws GLException if {@link EGL#eglGetDisplay(long)} or {@link EGL#eglInitialize(long, int[], int, int[], int)} fails - * @see EGLGraphicsDevice#EGLGraphicsDevice(long, long, String, int, com.jogamp.nativewindow.egl.EGLGraphicsDevice.EGLTerminateCallback) + * @see EGLGraphicsDevice#EGLGraphicsDevice(long, long, String, int, com.jogamp.nativewindow.egl.EGLGraphicsDevice.EGLDisplayLifecycleCallback) */ public static EGLGraphicsDevice eglCreateEGLGraphicsDevice(long nativeDisplayID, String connection, int unitID) { - long eglDisplay = EGLDisplayUtil.eglGetDisplay(nativeDisplayID); - if (eglDisplay == EGL.EGL_NO_DISPLAY) { - throw new GLException("Failed to created EGL display: 0x"+Long.toHexString(nativeDisplayID)+", error 0x"+Integer.toHexString(EGL.eglGetError())); - } - if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) { - throw new GLException("eglInitialize failed"+", error 0x"+Integer.toHexString(EGL.eglGetError())); - } - return new EGLGraphicsDevice(nativeDisplayID, eglDisplay, connection, unitID, eglTerminateCallback); + final EGLGraphicsDevice eglDisplay = new EGLGraphicsDevice(nativeDisplayID, 0, connection, unitID, eglLifecycleCallback); + eglDisplay.open(); + return eglDisplay; } /** @@ -189,6 +194,6 @@ public class EGLDisplayUtil { throw new GLException("eglInitialize failed"+", error 0x"+Integer.toHexString(EGL.eglGetError())); } final AbstractGraphicsDevice adevice = surface.getGraphicsConfiguration().getScreen().getDevice(); - return new EGLGraphicsDevice(nativeDisplayID, eglDisplay, adevice.getConnection(), adevice.getUnitID(), eglTerminateCallback); + return new EGLGraphicsDevice(nativeDisplayID, eglDisplay, adevice.getConnection(), adevice.getUnitID(), eglLifecycleCallback); } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java index d777c4f04..383b61f88 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java @@ -36,82 +36,65 @@ package jogamp.opengl.egl; -import jogamp.opengl.GLDynamicLookupHelper; -import jogamp.opengl.GLDrawableImpl; +import javax.media.nativewindow.MutableSurface; +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindow; +import javax.media.nativewindow.ProxySurface; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLException; -import javax.media.nativewindow.*; -import javax.media.nativewindow.VisualIDHolder.VIDType; -import javax.media.opengl.*; +import jogamp.opengl.GLDrawableImpl; +import jogamp.opengl.GLDynamicLookupHelper; -import com.jogamp.nativewindow.egl.*; +import com.jogamp.nativewindow.egl.EGLGraphicsDevice; public abstract class EGLDrawable extends GLDrawableImpl { - private boolean ownEGLDisplay = false; // for destruction private boolean ownEGLSurface = false; // for destruction - private EGLGraphicsConfiguration eglConfig; - private EGLGraphicsDevice eglDevice; - private long eglSurface; - protected EGLDrawable(EGLDrawableFactory factory, - NativeSurface component) throws GLException { + protected EGLDrawable(EGLDrawableFactory factory, NativeSurface component) throws GLException { super(factory, component, false); - eglSurface=EGL.EGL_NO_SURFACE; - eglDevice=null; - } - - public final long getDisplay() { - return null != eglDevice ? eglDevice.getHandle() : 0; - } - - @Override - public final long getHandle() { - return eglSurface; - } - - public final EGLGraphicsConfiguration getGraphicsConfiguration() { - return eglConfig; - } - - @Override - public final GLCapabilitiesImmutable getChosenGLCapabilities() { - return (null==eglConfig)?super.getChosenGLCapabilities():(GLCapabilitiesImmutable)eglConfig.getChosenCapabilities(); } @Override public abstract GLContext createContext(GLContext shareWith); - protected abstract long createSurface(long eglDpy, long eglNativeCfg, long surfaceHandle); + protected abstract long createSurface(EGLGraphicsConfiguration config, long nativeSurfaceHandle); private final void recreateSurface() { - // create a new EGLSurface .. - if(EGL.EGL_NO_SURFACE!=eglSurface) { - EGL.eglDestroySurface(eglDevice.getHandle(), eglSurface); - } - + final EGLGraphicsConfiguration eglConfig = (EGLGraphicsConfiguration) surface.getGraphicsConfiguration(); + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) eglConfig.getScreen().getDevice(); if(DEBUG) { - System.err.println(getThreadName() + ": createSurface using "+eglDevice+", "+eglConfig); + System.err.println(getThreadName() + ": createSurface using "+eglConfig); + } + if( EGL.EGL_NO_SURFACE != surface.getSurfaceHandle() ) { + EGL.eglDestroySurface(eglDevice.getHandle(), surface.getSurfaceHandle()); } - - eglSurface = createSurface(eglDevice.getHandle(), eglConfig.getNativeConfig(), surface.getSurfaceHandle()); - int eglError0 = EGL.EGL_SUCCESS; + + final EGLUpstreamSurfaceHook upstreamHook = (EGLUpstreamSurfaceHook) ((ProxySurface)surface).getUpstreamSurfaceHook(); + final NativeSurface upstreamSurface = upstreamHook.getUpstreamSurface(); + long eglSurface = createSurface(eglConfig, upstreamSurface.getSurfaceHandle()); + + int eglError0; if (EGL.EGL_NO_SURFACE == eglSurface) { eglError0 = EGL.eglGetError(); if(EGL.EGL_BAD_NATIVE_WINDOW == eglError0) { // Try window handle if available and differs (Windows HDC / HWND). // ANGLE impl. required HWND on Windows. - if(surface instanceof NativeWindow) { - final NativeWindow nw = (NativeWindow) surface; + if(upstreamSurface instanceof NativeWindow) { + final NativeWindow nw = (NativeWindow) upstreamSurface; if(nw.getWindowHandle() != nw.getSurfaceHandle()) { if(DEBUG) { System.err.println(getThreadName() + ": Info: Creation of window surface w/ surface handle failed: "+eglConfig+", error "+toHexString(eglError0)+", retry w/ windowHandle"); } - eglSurface = createSurface(eglDevice.getHandle(), eglConfig.getNativeConfig(), nw.getWindowHandle()); + eglSurface = createSurface(eglConfig, nw.getWindowHandle()); if (EGL.EGL_NO_SURFACE == eglSurface) { eglError0 = EGL.eglGetError(); } } } } + } else { + eglError0 = EGL.EGL_SUCCESS; } if (EGL.EGL_NO_SURFACE == eglSurface) { throw new GLException("Creation of window surface failed: "+eglConfig+", "+surface+", error "+toHexString(eglError0)); @@ -120,6 +103,8 @@ public abstract class EGLDrawable extends GLDrawableImpl { if(DEBUG) { System.err.println(getThreadName() + ": setSurface using component: handle "+toHexString(surface.getSurfaceHandle())+" -> "+toHexString(eglSurface)); } + + ((MutableSurface)surface).setSurfaceHandle(eglSurface); } @Override @@ -131,123 +116,71 @@ public abstract class EGLDrawable extends GLDrawableImpl { @Override protected final void setRealizedImpl() { + final EGLGraphicsConfiguration eglConfig = (EGLGraphicsConfiguration) surface.getGraphicsConfiguration(); + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) eglConfig.getScreen().getDevice(); if (realized) { - AbstractGraphicsConfiguration aConfig = surface.getGraphicsConfiguration(); - AbstractGraphicsDevice aDevice = aConfig.getScreen().getDevice(); - if(aDevice instanceof EGLGraphicsDevice) { + final long eglDisplayHandle = eglDevice.getHandle(); + if (EGL.EGL_NO_DISPLAY == eglDisplayHandle) { + throw new GLException("Invalid EGL display in EGLGraphicsDevice "+eglDevice); + } + int[] tmp = new int[1]; + boolean eglSurfaceValid = 0 != surface.getSurfaceHandle(); + if(eglSurfaceValid) { + eglSurfaceValid = EGL.eglQuerySurface(eglDisplayHandle, surface.getSurfaceHandle(), EGL.EGL_CONFIG_ID, tmp, 0); + if(!eglSurfaceValid) { + if(DEBUG) { + System.err.println(getThreadName() + ": EGLDrawable.setRealizedImpl eglQuerySuface failed: "+toHexString(EGL.eglGetError())+", "+surface); + } + } + } + if(eglSurfaceValid) { + // surface holds valid EGLSurface if(DEBUG) { - System.err.println(getThreadName() + ": EGLDrawable.setRealized(true): using existing EGL config - START"); + System.err.println(getThreadName() + ": EGLDrawable.setRealizedImpl re-using component's EGLSurface: handle "+toHexString(surface.getSurfaceHandle())); + } + ownEGLSurface=false; + } else { + // EGLSurface is ours - subsequent updateHandle() will issue recreateSurface(); + // However .. let's validate the surface object first + if( ! (surface instanceof ProxySurface) ) { + throw new InternalError("surface not ProxySurface: "+surface.getClass().getName()+", "+surface); } - // just fetch the data .. trust but verify .. - ownEGLDisplay = false; - eglDevice = (EGLGraphicsDevice) aDevice; - if (eglDevice.getHandle() == EGL.EGL_NO_DISPLAY) { - throw new GLException("Invalid EGL display in EGLGraphicsDevice "+eglDevice); + final ProxySurface.UpstreamSurfaceHook upstreamHook = ((ProxySurface)surface).getUpstreamSurfaceHook(); + if( null == upstreamHook ) { + throw new InternalError("null upstreamHook of: "+surface); } - if(aConfig instanceof EGLGraphicsConfiguration) { - eglConfig = (EGLGraphicsConfiguration) aConfig; // done .. - if (null == eglConfig) { - throw new GLException("Null EGLGraphicsConfiguration from "+aConfig); - } - - int[] tmp = new int[1]; - if ( 0 != surface.getSurfaceHandle() && - EGL.eglQuerySurface(eglDevice.getHandle(), surface.getSurfaceHandle(), EGL.EGL_CONFIG_ID, tmp, 0) ) { - // surface holds static EGLSurface - eglSurface = surface.getSurfaceHandle(); - if(DEBUG) { - System.err.println(getThreadName() + ": setSurface re-using component's EGLSurface: handle "+toHexString(eglSurface)); - } - ownEGLSurface=false; - } else { - // EGLSurface is ours - subsequent updateHandle() will issue recreateSurface(); - ownEGLSurface=true; - } - } else { - throw new GLException("EGLGraphicsDevice hold by non EGLGraphicsConfiguration: "+aConfig); + if( ! (upstreamHook instanceof EGLUpstreamSurfaceHook) ) { + throw new InternalError("upstreamHook not EGLUpstreamSurfaceHook: Surface: "+surface.getClass().getName()+", "+surface+"; UpstreamHook: "+upstreamHook.getClass().getName()+", "+upstreamHook); } - } else { - if(DEBUG) { - System.err.println(getThreadName() + ": EGLDrawable.setRealized(true): creating new EGL config - START"); + if( null == ((EGLUpstreamSurfaceHook)upstreamHook).getUpstreamSurface() ) { + throw new InternalError("null upstream surface"); } - // create a new EGL config .. - ownEGLDisplay=true; - // EGLSurface is ours .. ownEGLSurface=true; - - eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface, true); - AbstractGraphicsScreen eglScreen = new DefaultGraphicsScreen(eglDevice, aConfig.getScreen().getIndex()); - final GLCapabilitiesImmutable capsRequested = (GLCapabilitiesImmutable) aConfig.getRequestedCapabilities(); - if(aConfig instanceof EGLGraphicsConfiguration) { - final EGLGLCapabilities capsChosen = (EGLGLCapabilities) aConfig.getChosenCapabilities(); - if(0 == capsChosen.getEGLConfig()) { - // 'refresh' the native EGLConfig handle - capsChosen.setEGLConfig(EGLGraphicsConfiguration.EGLConfigId2EGLConfig(eglDevice.getHandle(), capsChosen.getEGLConfigID())); - if(0 == capsChosen.getEGLConfig()) { - throw new GLException("Refreshing native EGLConfig handle failed: "+capsChosen+" of "+aConfig); - } - } - eglConfig = new EGLGraphicsConfiguration(eglScreen, capsChosen, capsRequested, null); - if(DEBUG) { - System.err.println(getThreadName() + ": Reusing chosenCaps: "+eglConfig); - } - } else { - eglConfig = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic( - capsRequested, capsRequested, null, eglScreen, aConfig.getVisualID(VIDType.NATIVE), false); - - if (null == eglConfig) { - throw new GLException("Couldn't create EGLGraphicsConfiguration from "+eglScreen); - } else if(DEBUG) { - System.err.println(getThreadName() + ": Chosen eglConfig: "+eglConfig); - } + if(DEBUG) { + System.err.println(getThreadName() + ": EGLDrawable.setRealizedImpl owning EGLSurface"); } - // subsequent updateHandle() will issue recreateSurface(); - } - if(DEBUG) { - System.err.println(getThreadName() + ": EGLDrawable.setRealized(true): END: ownDisplay "+ownEGLDisplay+", ownSurface "+ownEGLSurface); } - } else if (ownEGLSurface && eglSurface != EGL.EGL_NO_SURFACE) { + } else if (ownEGLSurface && surface.getSurfaceHandle() != EGL.EGL_NO_SURFACE) { if(DEBUG) { - System.err.println(getThreadName() + ": EGLDrawable.setRealized(false): ownDisplay "+ownEGLDisplay+", ownSurface "+ownEGLSurface+", "+eglDevice+", eglSurface: "+toHexString(eglSurface)); + System.err.println(getThreadName() + ": EGLDrawable.setRealized(false): ownSurface "+ownEGLSurface+", "+eglDevice+", eglSurface: "+toHexString(surface.getSurfaceHandle())); } // Destroy the window surface - if (!EGL.eglDestroySurface(eglDevice.getHandle(), eglSurface)) { + if (!EGL.eglDestroySurface(eglDevice.getHandle(), surface.getSurfaceHandle())) { throw new GLException("Error destroying window surface (eglDestroySurface)"); } - eglSurface = EGL.EGL_NO_SURFACE; - eglConfig=null; - eglDevice.close(); - eglDevice=null; + ((MutableSurface)surface).setSurfaceHandle(EGL.EGL_NO_SURFACE); } } @Override protected final void swapBuffersImpl() { + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) surface.getGraphicsConfiguration().getScreen().getDevice(); // single-buffer is already filtered out @ GLDrawableImpl#swapBuffers() - if(!EGL.eglSwapBuffers(eglDevice.getHandle(), eglSurface)) { + if(!EGL.eglSwapBuffers(eglDevice.getHandle(), surface.getSurfaceHandle())) { throw new GLException("Error swapping buffers, eglError "+toHexString(EGL.eglGetError())+", "+this); } } - /** - * Surface not realizes yet (onscreen) .. Quering EGL surface size only makes sense for external drawable. - * Leave it here for later impl. of an EGLExternalDrawable. - public int getWidth() { - int[] tmp = new int[1]; - if (!EGL.eglQuerySurface(eglDisplay, eglSurface, EGL.EGL_WIDTH, tmp, 0)) { - throw new GLException("Error querying surface width, eglError "+toHexString(EGL.eglGetError())); - } - return tmp[0]; - } - - public int getHeight() { - int[] tmp = new int[1]; - if (!EGL.eglQuerySurface(eglDisplay, eglSurface, EGL.EGL_HEIGHT, tmp, 0)) { - throw new GLException("Error querying surface height, eglError "+toHexString(EGL.eglGetError())); - } - return tmp[0]; - } */ - @Override public GLDynamicLookupHelper getGLDynamicLookupHelper() { if (getGLProfile().usesNativeGLES2()) { @@ -263,10 +196,9 @@ public abstract class EGLDrawable extends GLDrawableImpl { public String toString() { return getClass().getName()+"[realized "+isRealized()+ ",\n\tfactory "+getFactory()+ - ",\n\tdevice "+eglDevice+ ",\n\tsurface "+getNativeSurface()+ - ",\n\teglSurface "+toHexString(eglSurface)+ - ",\n\teglConfig "+eglConfig+ + ",\n\teglSurface "+toHexString(surface.getSurfaceHandle())+ + ",\n\teglConfig "+surface.getGraphicsConfiguration()+ ",\n\trequested "+getRequestedGLCapabilities()+ ",\n\tchosen "+getChosenGLCapabilities()+"]"; } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index f4fa1f13f..c848e3e5c 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -46,21 +46,29 @@ import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.DefaultGraphicsScreen; +import javax.media.nativewindow.MutableSurface; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; +import javax.media.nativewindow.VisualIDHolder.VIDType; import javax.media.nativewindow.VisualIDHolder; +import javax.media.opengl.GL; +import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; import javax.media.opengl.GLProfile.ShutdownType; +import jogamp.opengl.Debug; import jogamp.opengl.GLDrawableFactoryImpl; import jogamp.opengl.GLDrawableImpl; import jogamp.opengl.GLDynamicLookupHelper; +import jogamp.opengl.GLGraphicsConfigurationUtil; import com.jogamp.common.JogampRuntimeException; import com.jogamp.common.os.Platform; @@ -69,6 +77,9 @@ import com.jogamp.nativewindow.WrappedSurface; import com.jogamp.nativewindow.egl.EGLGraphicsDevice; public class EGLDrawableFactory extends GLDrawableFactoryImpl { + /* package */ static final boolean QUERY_EGL_ES = !Debug.isPropertyDefined("jogl.debug.EGLDrawableFactory.DontQuery", true); + /* package */ static final boolean QUERY_EGL_ES_NATIVE_TK = Debug.isPropertyDefined("jogl.debug.EGLDrawableFactory.QueryNativeTK", true); + private static GLDynamicLookupHelper eglES1DynamicLookupHelper = null; private static GLDynamicLookupHelper eglES2DynamicLookupHelper = null; private static boolean isANGLE = false; @@ -231,7 +242,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { // final EGLContext getContextES1() { return contextES1; } // final EGLContext getContextES2() { return contextES2; } final boolean wasES1ContextAvailable() { return wasES1ContextCreated; } - final boolean wasES2ContextAvailable() { return wasES2ContextCreated; } + final boolean wasES2ContextAvailable() { return wasES2ContextCreated; } } @Override @@ -245,35 +256,98 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { return null!=eglES2DynamicLookupHelper || null!=eglES1DynamicLookupHelper; } - /** - private boolean isEGLContextAvailable(EGLGraphicsDevice sharedDevice, String profile) { - boolean madeCurrent = false; - final GLCapabilities caps = new GLCapabilities(GLProfile.get(profile)); - caps.setRedBits(5); caps.setGreenBits(5); caps.setBlueBits(5); caps.setAlphaBits(0); - caps.setDoubleBuffered(false); - caps.setOnscreen(false); - caps.setPBuffer(true); - final EGLDrawable drawable = (EGLDrawable) createGLDrawable( createOffscreenSurfaceImpl(sharedDevice, caps, caps, null, 64, 64) ); - if(null!=drawable) { + private boolean isEGLContextAvailable(AbstractGraphicsDevice adevice, EGLGraphicsDevice sharedEGLDevice, String profileString) { + if( !GLProfile.isAvailable(adevice, profileString) ) { + return false; + } + final GLProfile glp = GLProfile.get(adevice, profileString) ; + final GLDrawableFactoryImpl desktopFactory = (GLDrawableFactoryImpl) GLDrawableFactory.getDesktopFactory(); + EGLGraphicsDevice eglDevice = null; + NativeSurface surface = null; + ProxySurface upstreamSurface = null; // X11, GLX, .. + boolean success = false; + boolean deviceFromUpstreamSurface = false; + try { + final GLCapabilities caps = new GLCapabilities(glp); + caps.setRedBits(5); caps.setGreenBits(5); caps.setBlueBits(5); caps.setAlphaBits(0); + if(adevice instanceof EGLGraphicsDevice || null == desktopFactory || !QUERY_EGL_ES_NATIVE_TK) { + eglDevice = sharedEGLDevice; // reuse + surface = createDummySurfaceImpl(eglDevice, false, caps, null, 64, 64); // egl pbuffer offscreen + upstreamSurface = (ProxySurface)surface; + upstreamSurface.createNotify(); + deviceFromUpstreamSurface = false; + } else { + surface = desktopFactory.createDummySurface(adevice, caps, null, 64, 64); // X11, WGL, .. dummy window + upstreamSurface = ( surface instanceof ProxySurface ) ? (ProxySurface)surface : null ; + if(null != upstreamSurface) { + upstreamSurface.createNotify(); + } + eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface, true); + deviceFromUpstreamSurface = true; + } + + final EGLDrawable drawable = (EGLDrawable) createOnscreenDrawableImpl ( surface ); + drawable.setRealized(true); final EGLContext context = (EGLContext) drawable.createContext(null); if (null != context) { - context.setSynchronized(true); try { context.makeCurrent(); // could cause exception - madeCurrent = context.isCurrent(); + success = context.isCurrent(); + if(success) { + final String glVersion = context.getGL().glGetString(GL.GL_VERSION); + if(null == glVersion) { + // Oops .. something is wrong + if(DEBUG) { + System.err.println("EGLDrawableFactory.isEGLContextAvailable: "+eglDevice+", "+context.getGLVersion()+" - VERSION is null, dropping availability!"); + } + success = false; + } + } + if(success) { + context.mapCurrentAvailableGLVersion(eglDevice); + if(eglDevice != adevice) { + context.mapCurrentAvailableGLVersion(adevice); + } + } } catch (GLException gle) { if (DEBUG) { - System.err.println("EGLDrawableFactory.createShared: INFO: makeCurrent failed"); + System.err.println("EGLDrawableFactory.createShared: INFO: context create/makeCurrent failed"); gle.printStackTrace(); } } finally { context.destroy(); } } - drawable.destroy(); + drawable.setRealized(false); + } catch (Throwable t) { + if(DEBUG) { + System.err.println("Catched Exception:"); + t.printStackTrace(); + } + success = false; + } finally { + if(eglDevice == sharedEGLDevice) { + if(null != upstreamSurface) { + upstreamSurface.destroyNotify(); + } + } else if( deviceFromUpstreamSurface ) { + if(null != eglDevice) { + eglDevice.close(); + } + if(null != upstreamSurface) { + upstreamSurface.destroyNotify(); + } + } else { + if(null != upstreamSurface) { + upstreamSurface.destroyNotify(); + } + if(null != eglDevice) { + eglDevice.close(); + } + } } - return madeCurrent; - } */ + return success; + } /* package */ SharedResource getOrCreateEGLSharedResource(AbstractGraphicsDevice adevice) { if(null == eglES1DynamicLookupHelper && null == eglES2DynamicLookupHelper) { @@ -285,18 +359,41 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { sr = sharedMap.get(connection); } if(null==sr) { - final EGLGraphicsDevice sharedDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, connection, adevice.getUnitID()); + final boolean madeCurrentES1; + final boolean madeCurrentES2; + final EGLGraphicsDevice sharedDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); - // final boolean madeCurrentES1 = isEGLContextAvailable(sharedDevice, GLProfile.GLES1); - // final boolean madeCurrentES2 = isEGLContextAvailable(sharedDevice, GLProfile.GLES2); - final boolean madeCurrentES1 = true; // FIXME - final boolean madeCurrentES2 = true; // FIXME + if(QUERY_EGL_ES) { + madeCurrentES1 = isEGLContextAvailable(adevice, sharedDevice, GLProfile.GLES1); + madeCurrentES2 = isEGLContextAvailable(adevice, sharedDevice, GLProfile.GLES2); + } else { + madeCurrentES1 = true; + madeCurrentES2 = true; + EGLContext.mapStaticGLESVersion(sharedDevice, 1); + if(sharedDevice != adevice) { + EGLContext.mapStaticGLESVersion(adevice, 1); + } + EGLContext.mapStaticGLESVersion(sharedDevice, 2); + if(sharedDevice != adevice) { + EGLContext.mapStaticGLESVersion(adevice, 2); + } + } + + if( !EGLContext.getAvailableGLVersionsSet(adevice) ) { + // Even though we override the non EGL native mapping intentionally, + // avoid exception due to double 'set' - carefull exception of the rule. + EGLContext.setAvailableGLVersionsSet(adevice); + } sr = new SharedResource(sharedDevice, madeCurrentES1, madeCurrentES2); + synchronized(sharedMap) { sharedMap.put(connection, sr); + if(adevice != sharedDevice) { + sharedMap.put(sharedDevice.getConnection(), sr); + } } if (DEBUG) { - System.err.println("EGLDrawableFactory.createShared: device: " + sharedDevice); + System.err.println("EGLDrawableFactory.createShared: devices: queried " + QUERY_EGL_ES + "[nativeTK "+QUERY_EGL_ES_NATIVE_TK+"], " + adevice + ", " + sharedDevice); System.err.println("EGLDrawableFactory.createShared: context ES1: " + madeCurrentES1); System.err.println("EGLDrawableFactory.createShared: context ES2: " + madeCurrentES2); } @@ -367,8 +464,51 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { if (target == null) { throw new IllegalArgumentException("Null target"); } - return new EGLOnscreenDrawable(this, target); + return new EGLOnscreenDrawable(this, getEGLSurface(target)); + } + + protected static NativeSurface getEGLSurface(NativeSurface surface) { + AbstractGraphicsConfiguration aConfig = surface.getGraphicsConfiguration(); + AbstractGraphicsDevice aDevice = aConfig.getScreen().getDevice(); + if( aDevice instanceof EGLGraphicsDevice && aConfig instanceof EGLGraphicsConfiguration ) { + // already in native EGL format + if(DEBUG) { + System.err.println(getThreadName() + ": getEGLSurface - already in EGL format - use as-is: "+aConfig); + } + return surface; + } + // create EGL instance out of platform native types + final EGLGraphicsDevice eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface, true); + final AbstractGraphicsScreen eglScreen = new DefaultGraphicsScreen(eglDevice, aConfig.getScreen().getIndex()); + final GLCapabilitiesImmutable capsRequested = (GLCapabilitiesImmutable) aConfig.getRequestedCapabilities(); + final EGLGraphicsConfiguration eglConfig; + if( aConfig instanceof EGLGraphicsConfiguration ) { + // Config is already in EGL type - reuse .. + final EGLGLCapabilities capsChosen = (EGLGLCapabilities) aConfig.getChosenCapabilities(); + if( 0 == capsChosen.getEGLConfig() ) { + // 'refresh' the native EGLConfig handle + capsChosen.setEGLConfig(EGLGraphicsConfiguration.EGLConfigId2EGLConfig(eglDevice.getHandle(), capsChosen.getEGLConfigID())); + if( 0 == capsChosen.getEGLConfig() ) { + throw new GLException("Refreshing native EGLConfig handle failed: "+capsChosen+" of "+aConfig); + } + } + eglConfig = new EGLGraphicsConfiguration(eglScreen, capsChosen, capsRequested, null); + if(DEBUG) { + System.err.println(getThreadName() + ": getEGLSurface - Reusing chosenCaps: "+eglConfig); + } + } else { + eglConfig = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic( + capsRequested, capsRequested, null, eglScreen, aConfig.getVisualID(VIDType.NATIVE), false); + + if (null == eglConfig) { + throw new GLException("Couldn't create EGLGraphicsConfiguration from "+eglScreen); + } else if(DEBUG) { + System.err.println(getThreadName() + ": getEGLSurface - Chosen eglConfig: "+eglConfig); + } + } + return new WrappedSurface(eglConfig, EGL.EGL_NO_SURFACE, surface.getWidth(), surface.getHeight(), new EGLUpstreamSurfaceHook(surface)); } + static String getThreadName() { return Thread.currentThread().getName(); } @Override protected GLDrawableImpl createOffscreenDrawableImpl(NativeSurface target) { @@ -390,22 +530,115 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } @Override - protected NativeSurface createOffscreenSurfaceImpl(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, int width, int height) { - final EGLGraphicsDevice eglDeviceReq = (EGLGraphicsDevice) deviceReq; - final EGLGraphicsDevice device = EGLDisplayUtil.eglCreateEGLGraphicsDevice(eglDeviceReq.getNativeDisplayID(), deviceReq.getConnection(), deviceReq.getUnitID()); - WrappedSurface ns = new WrappedSurface(EGLGraphicsConfigurationFactory.createOffscreenGraphicsConfiguration(device, capsChosen, capsRequested, chooser)); - ns.surfaceSizeChanged(width, height); - return ns; + protected ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, + GLCapabilitiesChooser chooser, int width, int height, UpstreamSurfaceHook lifecycleHook) { + final EGLGraphicsDevice device; + if(createNewDevice) { + final EGLGraphicsDevice eglDeviceReq = (EGLGraphicsDevice) deviceReq; + device = EGLDisplayUtil.eglCreateEGLGraphicsDevice(eglDeviceReq.getNativeDisplayID(), deviceReq.getConnection(), deviceReq.getUnitID()); + } else { + device = (EGLGraphicsDevice) deviceReq; + } + final DefaultGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); + final EGLGraphicsConfiguration config = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED, false); + if(null == config) { + throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); + } + return new WrappedSurface(config, 0, width, height, lifecycleHook); + } + + @Override + public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { + final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(requestedCaps, false, canCreateGLPbuffer(deviceReq)); + return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, width, height, dummySurfaceLifecycleHook); + } + private static final ProxySurface.UpstreamSurfaceHook dummySurfaceLifecycleHook = new ProxySurface.UpstreamSurfaceHook() { + @Override + public final void create(ProxySurface s) { + if( EGL.EGL_NO_SURFACE == s.getSurfaceHandle() ) { + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) s.getGraphicsConfiguration().getScreen().getDevice(); + if(0 == eglDevice.getHandle()) { + eglDevice.open(); + s.setImplBitfield(ProxySurface.OWN_DEVICE); + } + createPBufferSurfaceImpl(s, false); + if(DEBUG) { + System.err.println("EGLDrawableFactory.dummySurfaceLifecycleHook.create: "+s); + } + } + } + @Override + public final void destroy(ProxySurface s) { + if( EGL.EGL_NO_SURFACE != s.getSurfaceHandle() ) { + final EGLGraphicsConfiguration config = (EGLGraphicsConfiguration) s.getGraphicsConfiguration(); + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) config.getScreen().getDevice(); + EGL.eglDestroySurface(eglDevice.getHandle(), s.getSurfaceHandle()); + s.setSurfaceHandle(EGL.EGL_NO_SURFACE); + if( 0 != ( ProxySurface.OWN_DEVICE & s.getImplBitfield() ) ) { + eglDevice.close(); + } + if(DEBUG) { + System.err.println("EGLDrawableFactory.dummySurfaceLifecycleHook.create: "+s); + } + } + } + @Override + public final int getWidth(ProxySurface s) { + return s.initialWidth; + } + @Override + public final int getHeight(ProxySurface s) { + return s.initialHeight; + } + @Override + public String toString() { + return "EGLSurfaceLifecycleHook[]"; + } + + }; + + /** + * @param ms {@link MutableSurface} which dimensions and config are being used to create the pbuffer surface. + * It will also hold the resulting pbuffer surface handle. + * @param useTexture + * @return the passed {@link MutableSurface} which now has the EGL pbuffer surface set as it's handle + */ + protected static MutableSurface createPBufferSurfaceImpl(MutableSurface ms, boolean useTexture) { + final EGLGraphicsConfiguration config = (EGLGraphicsConfiguration) ms.getGraphicsConfiguration(); + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) config.getScreen().getDevice(); + final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); + final int texFormat; + + if(useTexture) { + texFormat = caps.getAlphaBits() > 0 ? EGL.EGL_TEXTURE_RGBA : EGL.EGL_TEXTURE_RGB ; + } else { + texFormat = EGL.EGL_NO_TEXTURE; + } + + if (DEBUG) { + System.out.println("Pbuffer config: " + config); + } + + final int[] attrs = EGLGraphicsConfiguration.CreatePBufferSurfaceAttribList(ms.getWidth(), ms.getHeight(), texFormat); + final long surf = EGL.eglCreatePbufferSurface(eglDevice.getHandle(), config.getNativeConfig(), attrs, 0); + if (EGL.EGL_NO_SURFACE==surf) { + throw new GLException("Creation of window surface (eglCreatePbufferSurface) failed, dim "+ms.getWidth()+"x"+ms.getHeight()+", error 0x"+Integer.toHexString(EGL.eglGetError())); + } else if(DEBUG) { + System.err.println("PBuffer setSurface result: eglSurface 0x"+Long.toHexString(surf)); + } + ms.setSurfaceHandle(surf); + return ms; } @Override - protected ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice adevice, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser) { - // FIXME device/windowHandle -> screen ?! - EGLGraphicsDevice device = (EGLGraphicsDevice) adevice; - DefaultGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); - EGLGraphicsConfiguration cfg = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED, false); - WrappedSurface ns = new WrappedSurface(cfg, windowHandle); - return ns; + protected ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { + final EGLGraphicsDevice eglDeviceReq = (EGLGraphicsDevice) deviceReq; + final EGLGraphicsDevice device = EGLDisplayUtil.eglCreateEGLGraphicsDevice(eglDeviceReq.getNativeDisplayID(), deviceReq.getConnection(), deviceReq.getUnitID()); + final DefaultGraphicsScreen screen = new DefaultGraphicsScreen(device, screenIdx); + final EGLGraphicsConfiguration cfg = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED, false); + return new WrappedSurface(cfg, windowHandle, 0, 0, upstream); } @Override diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java index 56e7a4d22..214b36493 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java @@ -151,7 +151,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple public static EGLGLCapabilities EGLConfig2Capabilities(GLProfile glp, long display, long config, boolean relaxed, boolean onscreen, boolean usePBuffer, boolean forceTransparentFlag) { List bucket = new ArrayList(); - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer); + final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, false); if( EGLConfig2Capabilities(bucket, glp, display, config, winattrmask, forceTransparentFlag) ) { return (EGLGLCapabilities) bucket.get(0); } else if ( relaxed && EGLConfig2Capabilities(bucket, glp, display, config, GLGraphicsConfigurationUtil.ALL_BITS, forceTransparentFlag) ) { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java index 809e2b688..6be9cb547 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java @@ -38,7 +38,6 @@ import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.CapabilitiesChooser; import javax.media.nativewindow.CapabilitiesImmutable; -import javax.media.nativewindow.DefaultGraphicsScreen; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.VisualIDHolder; import javax.media.nativewindow.VisualIDHolder.VIDType; @@ -47,6 +46,7 @@ import javax.media.nativewindow.NativeWindowFactory; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; import javax.media.opengl.GLDrawableFactory; @@ -180,6 +180,9 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact } EGLGraphicsDevice eglDevice = sharedResource.getDevice(); long eglDisplay = eglDevice.getHandle(); + if(0 == eglDisplay) { + throw new GLException("null eglDisplay"); + } List availableCaps = null; IntBuffer numConfigs = Buffers.newDirectIntBuffer(1); @@ -236,11 +239,9 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact ownEGLDisplay = true; } - EGLDrawableFactory factory = (EGLDrawableFactory) GLDrawableFactory.getEGLFactory(); - capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, factory.canCreateGLPbuffer(absDevice) ); - - GLProfile glp = capsChosen.getGLProfile(); - GLCapabilities fixedCaps; + final GLProfile glp = capsChosen.getGLProfile(); + final EGLDrawableFactory factory = (EGLDrawableFactory) GLDrawableFactory.getEGLFactory(); + capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, GLContext.isFBOAvailable(absDevice, glp), factory.canCreateGLPbuffer(absDevice) ); EGLGraphicsConfiguration res = eglChooseConfig(eglDevice.getHandle(), capsChosen, capsReq, chooser, absScreen, nativeVisualID, forceTransparentFlag); if(null==res) { @@ -251,13 +252,18 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact // Last try .. add a fixed embedded profile [ATI, Nokia, Intel, ..] // // rgb888 - d16, s4 - fixedCaps = new GLCapabilities(glp); + final GLCapabilities fixedCaps = new GLCapabilities(glp); fixedCaps.setRedBits(8); fixedCaps.setGreenBits(8); fixedCaps.setBlueBits(8); fixedCaps.setDepthBits(16); fixedCaps.setSampleBuffers(true); fixedCaps.setNumSamples(4); + if( !capsChosen.isOnscreen() ) { + fixedCaps.setOnscreen(false); + fixedCaps.setPBuffer(capsChosen.isPBuffer()); + fixedCaps.setFBO(capsChosen.isFBO()); + } if(DEBUG) { System.err.println("trying fixed caps (1): "+fixedCaps); } @@ -266,11 +272,16 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(null==res) { // // rgb565 - d16, s0 - fixedCaps = new GLCapabilities(glp); + final GLCapabilities fixedCaps = new GLCapabilities(glp); fixedCaps.setRedBits(5); fixedCaps.setGreenBits(6); fixedCaps.setBlueBits(5); fixedCaps.setDepthBits(16); + if( !capsChosen.isOnscreen() ) { + fixedCaps.setOnscreen(false); + fixedCaps.setPBuffer(capsChosen.isPBuffer()); + fixedCaps.setFBO(capsChosen.isFBO()); + } if(DEBUG) { System.err.println("trying fixed caps (2): "+fixedCaps); } @@ -279,13 +290,18 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(null==res) { // // rgb565 - d16, s4 - fixedCaps = new GLCapabilities(glp); + final GLCapabilities fixedCaps = new GLCapabilities(glp); fixedCaps.setRedBits(5); fixedCaps.setGreenBits(6); fixedCaps.setBlueBits(5); fixedCaps.setDepthBits(16); fixedCaps.setSampleBuffers(true); fixedCaps.setNumSamples(4); + if( !capsChosen.isOnscreen() ) { + fixedCaps.setOnscreen(false); + fixedCaps.setPBuffer(capsChosen.isPBuffer()); + fixedCaps.setFBO(capsChosen.isFBO()); + } if(DEBUG) { System.err.println("trying fixed caps (3): "+fixedCaps); } @@ -309,7 +325,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact final GLProfile glp = capsChosen.getGLProfile(); final boolean onscreen = capsChosen.isOnscreen(); final boolean usePBuffer = capsChosen.isPBuffer(); - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer); + final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, false); List availableCaps = null; int recommendedIndex = -1; long recommendedEGLConfig = -1; @@ -322,8 +338,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact throw new GLException("EGLGraphicsConfiguration.eglChooseConfig: Get maxConfigs (eglGetConfigs) no configs"); } if (DEBUG) { - System.err.println("EGLGraphicsConfiguration.eglChooseConfig: eglChooseConfig maxConfigs: "+numConfigs.get(0)); - System.err.println("EGLGraphicsConfiguration.eglChooseConfig: eglDisplay "+toHexString(eglDisplay)+", "+capsChosen+", nativeVisualID "+toHexString(nativeVisualID)); + System.err.println("EGLGraphicsConfiguration.eglChooseConfig: eglChooseConfig eglDisplay "+toHexString(eglDisplay)+", nativeVisualID "+toHexString(nativeVisualID)+", onscreen "+onscreen+", usePBuffer "+usePBuffer+", "+capsChosen+", numConfigs "+numConfigs.get(0)); } final IntBuffer attrs = Buffers.newDirectIntBuffer(EGLGraphicsConfiguration.GLCapabilities2AttribList(capsChosen)); @@ -362,7 +377,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact throw new GLException("EGLGraphicsConfiguration.eglChooseConfig: #2 Get all configs (eglGetConfigs) call failed, error "+toHexString(EGL.eglGetError())); } if (numConfigs.get(0) > 0) { - availableCaps = eglConfigs2GLCaps(glp, eglDisplay, configs, numConfigs.get(0), winattrmask, forceTransparentFlag); + availableCaps = eglConfigs2GLCaps(glp, eglDisplay, configs, numConfigs.get(0), winattrmask, forceTransparentFlag); } } @@ -370,6 +385,8 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(DEBUG) { // FIXME: this happens on a ATI PC Emulation .. System.err.println("EGLGraphicsConfiguration.eglChooseConfig: #2 Graphics configuration 1st choice and 2nd choice failed - no configs"); + availableCaps = eglConfigs2GLCaps(glp, eglDisplay, configs, numConfigs.get(0), GLGraphicsConfigurationUtil.ALL_BITS, forceTransparentFlag); + printCaps("AllCaps", availableCaps, System.err); } return null; } @@ -428,27 +445,5 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact out.println(prefix+"["+i+"] "+caps.get(i)); } } - - static EGLGraphicsConfiguration createOffscreenGraphicsConfiguration(AbstractGraphicsDevice device, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsReq, GLCapabilitiesChooser chooser) { - if(capsChosen.isOnscreen()) { - throw new GLException("Error: Onscreen set: "+capsChosen); - } - - if(capsChosen.getDoubleBuffered()) { - // OFFSCREEN !DOUBLE_BUFFER // FIXME DBLBUFOFFSCRN - GLCapabilities caps2 = (GLCapabilities) capsChosen.cloneMutable(); - caps2.setDoubleBuffered(false); - capsChosen = caps2; - } - - DefaultGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); - EGLGraphicsConfiguration eglConfig = chooseGraphicsConfigurationStatic(capsChosen, capsReq, chooser, screen, VisualIDHolder.VID_UNDEFINED, false); - if (null == eglConfig) { - throw new GLException("Couldn't create EGLGraphicsConfiguration from "+screen); - } else if(DEBUG) { - System.err.println("Chosen eglConfig: "+eglConfig); - } - return eglConfig; - } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenDrawable.java b/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenDrawable.java index 3768f1588..d54057775 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenDrawable.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenDrawable.java @@ -54,8 +54,8 @@ public class EGLOnscreenDrawable extends EGLDrawable { } @Override - protected long createSurface(long eglDpy, long eglNativeCfg, long surfaceHandle) { - return EGL.eglCreateWindowSurface(eglDpy, eglNativeCfg, surfaceHandle, null); + protected long createSurface(EGLGraphicsConfiguration config, long nativeSurfaceHandle) { + return EGL.eglCreateWindowSurface(config.getScreen().getDevice().getHandle(), config.getNativeConfig(), nativeSurfaceHandle, null); } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLPbufferDrawable.java b/src/jogl/classes/jogamp/opengl/egl/EGLPbufferDrawable.java index b2217c095..4a36625bd 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLPbufferDrawable.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLPbufferDrawable.java @@ -40,15 +40,11 @@ package jogamp.opengl.egl; -import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.NativeSurface; -import javax.media.nativewindow.SurfaceChangeable; -import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.nativewindow.MutableSurface; import javax.media.opengl.GLContext; -import javax.media.opengl.GLException; public class EGLPbufferDrawable extends EGLDrawable { - private int texFormat; protected static final boolean useTexture = false; // No yet .. protected EGLPbufferDrawable(EGLDrawableFactory factory, NativeSurface target) { @@ -56,30 +52,12 @@ public class EGLPbufferDrawable extends EGLDrawable { } @Override - protected long createSurface(long eglDpy, long eglNativeCfg, long surfaceHandle) { - final AbstractGraphicsConfiguration config = getNativeSurface().getGraphicsConfiguration(); - final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); - - if(useTexture) { - texFormat = caps.getAlphaBits() > 0 ? EGL.EGL_TEXTURE_RGBA : EGL.EGL_TEXTURE_RGB ; - } else { - texFormat = EGL.EGL_NO_TEXTURE; - } - - if (DEBUG) { - System.out.println("Pbuffer config: " + config); - } - - NativeSurface nw = getNativeSurface(); - int[] attrs = EGLGraphicsConfiguration.CreatePBufferSurfaceAttribList(nw.getWidth(), nw.getHeight(), texFormat); - long surf = EGL.eglCreatePbufferSurface(eglDpy, eglNativeCfg, attrs, 0); - if (EGL.EGL_NO_SURFACE==surf) { - throw new GLException("Creation of window surface (eglCreatePbufferSurface) failed, dim "+nw.getWidth()+"x"+nw.getHeight()+", error 0x"+Integer.toHexString(EGL.eglGetError())); - } else if(DEBUG) { - System.err.println("PBuffer setSurface result: eglSurface 0x"+Long.toHexString(surf)); + protected long createSurface(EGLGraphicsConfiguration config, long nativeSurfaceHandle) { + final MutableSurface ms = (MutableSurface)getNativeSurface(); + if(config != ms.getGraphicsConfiguration()) { + throw new InternalError("Not same: "+config.hashCode()+", "+ms.getGraphicsConfiguration()+": "+config+", "+ms.getGraphicsConfiguration()); } - ((SurfaceChangeable)nw).setSurfaceHandle(surf); - return surf; + return EGLDrawableFactory.createPBufferSurfaceImpl(ms, useTexture).getSurfaceHandle(); } @Override diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java b/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java new file mode 100644 index 000000000..42c6e100e --- /dev/null +++ b/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java @@ -0,0 +1,56 @@ +package jogamp.opengl.egl; + +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.ProxySurface; +import javax.media.opengl.GLException; + +import com.jogamp.nativewindow.egl.EGLGraphicsDevice; + +public class EGLUpstreamSurfaceHook implements ProxySurface.UpstreamSurfaceHook { + private final NativeSurface upstreamSurface; + + public EGLUpstreamSurfaceHook(NativeSurface upstream) { + upstreamSurface = upstream; + } + + public final NativeSurface getUpstreamSurface() { return upstreamSurface; } + + @Override + public final void create(ProxySurface surface) { + if(upstreamSurface instanceof ProxySurface) { + ((ProxySurface)upstreamSurface).createNotify(); + if(NativeSurface.LOCK_SURFACE_NOT_READY >= upstreamSurface.lockSurface()) { + throw new GLException("Could not lock: "+upstreamSurface); + } + } + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) surface.getGraphicsConfiguration().getScreen().getDevice(); + eglDevice.open(); + } + + @Override + public final void destroy(ProxySurface surface) { + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) surface.getGraphicsConfiguration().getScreen().getDevice(); + eglDevice.close(); + if(upstreamSurface instanceof ProxySurface) { + upstreamSurface.unlockSurface(); + ((ProxySurface)upstreamSurface).destroyNotify(); + } + } + + @Override + public final int getWidth(ProxySurface s) { + return upstreamSurface.getWidth(); + } + + @Override + public final int getHeight(ProxySurface s) { + return upstreamSurface.getHeight(); + } + + @Override + public String toString() { + final String us_s = null != upstreamSurface ? ( upstreamSurface.getClass().getName() + ": " + upstreamSurface ) : "nil"; + return "EGLUpstreamSurfaceHook[upstream: "+us_s+"]"; + } + +} diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index aa66aa9d1..4bf2a3c9d 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -48,6 +48,7 @@ import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.OffscreenLayerSurface; +import javax.media.nativewindow.ProxySurface; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLException; @@ -63,6 +64,7 @@ import com.jogamp.common.os.Platform; import com.jogamp.common.util.VersionNumber; import com.jogamp.gluegen.runtime.ProcAddressTable; import com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver; +import com.jogamp.opengl.GLExtensions; public abstract class MacOSXCGLContext extends GLContextImpl { @@ -252,9 +254,11 @@ public abstract class MacOSXCGLContext extends GLContextImpl @Override protected void makeCurrentImpl() throws GLException { + /** FIXME: won't work w/ special drawables (like FBO) - check for CGL mode regressions! + * if (getOpenGLMode() != ((MacOSXCGLDrawable)drawable).getOpenGLMode()) { setOpenGLMode(((MacOSXCGLDrawable)drawable).getOpenGLMode()); - } + } */ if (!impl.makeCurrent(contextHandle)) { throw new GLException("Error making Context current: "+this); } @@ -338,8 +342,8 @@ public abstract class MacOSXCGLContext extends GLContextImpl @Override public boolean isExtensionAvailable(String glExtensionName) { - if (glExtensionName.equals("GL_ARB_pbuffer") || - glExtensionName.equals("GL_ARB_pixel_format")) { + if (glExtensionName.equals(GLExtensions.ARB_pbuffer) || + glExtensionName.equals(GLExtensions.ARB_pixel_format)) { return true; } return super.isExtensionAvailable(glExtensionName); @@ -426,10 +430,13 @@ public abstract class MacOSXCGLContext extends GLContextImpl @Override public long create(long share, int ctp, int major, int minor) { long ctx = 0; - final MacOSXCGLDrawable drawable = (MacOSXCGLDrawable) MacOSXCGLContext.this.drawable; final NativeSurface surface = drawable.getNativeSurface(); final MacOSXCGLGraphicsConfiguration config = (MacOSXCGLGraphicsConfiguration) surface.getGraphicsConfiguration(); final OffscreenLayerSurface backingLayerHost = NativeWindowFactory.getOffscreenLayerSurface(surface, true); + boolean allowIncompleteView = null != backingLayerHost; + if( !allowIncompleteView && surface instanceof ProxySurface ) { + allowIncompleteView = 0 != ( ProxySurface.INVISIBLE_WINDOW & ((ProxySurface)surface).getImplBitfield() ) ; + } final GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); long pixelFormat = MacOSXCGLGraphicsConfiguration.GLCapabilities2NSPixelFormat(chosenCaps, ctp, major, minor); if (pixelFormat == 0) { @@ -443,13 +450,12 @@ public abstract class MacOSXCGLContext extends GLContextImpl screenVSyncTimeout = 1000000f / sRefreshRate; if(DEBUG) { System.err.println("NS create OSX>=lion "+isLionOrLater); - System.err.println("NS create backendType: "+drawable.getOpenGLMode()); + System.err.println("NS create allowIncompleteView: "+allowIncompleteView); System.err.println("NS create backingLayerHost: "+backingLayerHost); System.err.println("NS create share: "+share); System.err.println("NS create chosenCaps: "+chosenCaps); System.err.println("NS create pixelFormat: "+toHexString(pixelFormat)); System.err.println("NS create drawable native-handle: "+toHexString(drawable.getHandle())); - System.err.println("NS create drawable NSView-handle: "+toHexString(drawable.getNSViewHandle())); System.err.println("NS create screen refresh-rate: "+sRefreshRate+" hz, "+screenVSyncTimeout+" micros"); // Thread.dumpStack(); } @@ -457,7 +463,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl int[] viewNotReady = new int[1]; // Try to allocate a context with this ctx = CGL.createContext(share, - drawable.getNSViewHandle(), null!=backingLayerHost, + drawable.getHandle(), allowIncompleteView, pixelFormat, chosenCaps.isBackgroundOpaque(), viewNotReady, 0); @@ -473,10 +479,6 @@ public abstract class MacOSXCGLContext extends GLContextImpl CGL.setContextOpacity(ctx, 0); } - if(DEBUG) { - GLCapabilitiesImmutable caps0 = MacOSXCGLGraphicsConfiguration.NSPixelFormat2GLCapabilities(null, pixelFormat); - System.err.println("NS create pixelformat2GLCaps: "+caps0); - } GLCapabilitiesImmutable fixedCaps = MacOSXCGLGraphicsConfiguration.NSPixelFormat2GLCapabilities(chosenCaps.getGLProfile(), pixelFormat); fixedCaps = GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(fixedCaps, chosenCaps.isBackgroundOpaque()); config.setChosenCapabilities(fixedCaps); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java index 257635b8c..841edb2b0 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java @@ -106,10 +106,6 @@ public abstract class MacOSXCGLDrawable extends GLDrawableImpl { protected void setRealizedImpl() { } - protected long getNSViewHandle() { - return GLBackendType.NSOPENGL == openGLMode ? getHandle() : 0; - } - protected void registerContext(MacOSXCGLContext ctx) { // NOTE: we need to keep track of the created contexts in order to // implement swapBuffers() because of how Mac OS X implements its diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java index 4e9d18fed..9689d9f64 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java @@ -50,8 +50,8 @@ import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.DefaultGraphicsScreen; import javax.media.nativewindow.NativeSurface; -import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; import javax.media.opengl.GL; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; @@ -62,15 +62,19 @@ import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; import javax.media.opengl.GLProfile.ShutdownType; +import jogamp.nativewindow.macosx.OSXUtil; import jogamp.opengl.DesktopGLDynamicLookupHelper; +import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableFactoryImpl; import jogamp.opengl.GLDrawableImpl; import jogamp.opengl.GLDynamicLookupHelper; +import jogamp.opengl.GLGraphicsConfigurationUtil; import com.jogamp.common.JogampRuntimeException; import com.jogamp.common.util.ReflectionUtil; import com.jogamp.nativewindow.WrappedSurface; import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; +import com.jogamp.opengl.GLExtensions; public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { private static DesktopGLDynamicLookupHelper macOSXCGLDynamicLookupHelper = null; @@ -214,44 +218,39 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { if (null == glp) { throw new GLException("Couldn't get default GLProfile for device: "+sharedDevice); } - final GLCapabilities caps = new GLCapabilities(glp); - caps.setRedBits(5); caps.setGreenBits(5); caps.setBlueBits(5); caps.setAlphaBits(0); - caps.setDepthBits(5); - caps.setDoubleBuffered(false); - caps.setOnscreen(false); - caps.setPBuffer(true); - final MacOSXCGLDrawable drawable = (MacOSXCGLDrawable) createGLDrawable( createOffscreenSurfaceImpl(sharedDevice, caps, caps, null, 64, 64) ); - if(null!=drawable) { - drawable.setRealized(true); - final GLContext context = drawable.createContext(null); - if (null != context) { - try { - context.makeCurrent(); // could cause exception - madeCurrent = context.isCurrent(); - if(madeCurrent) { - GL gl = context.getGL(); - hasNPOTTextures = gl.isNPOTTextureAvailable(); - hasRECTTextures = gl.isExtensionAvailable("GL_EXT_texture_rectangle"); - hasAppleFloatPixels = gl.isExtensionAvailable("GL_APPLE_float_pixels"); - } - } catch (GLException gle) { - if (DEBUG) { - System.err.println("MacOSXCGLDrawableFactory.createShared: INFO: makeCurrent catched exception:"); - gle.printStackTrace(); - } - } finally { - try { - context.destroy(); - } catch (GLException gle) { - if (DEBUG) { - System.err.println("MacOSXCGLDrawableFactory.createShared: INFO: destroy catched exception:"); - gle.printStackTrace(); - } - } + final GLDrawableImpl sharedDrawable = createOnscreenDrawableImpl(createDummySurfaceImpl(sharedDevice, false, new GLCapabilities(glp), null, 64, 64)); + sharedDrawable.setRealized(true); + + final GLContextImpl sharedContext = (GLContextImpl) sharedDrawable.createContext(null); + if (null == sharedContext) { + throw new GLException("Couldn't create shared context for drawable: "+sharedDrawable); + } + + try { + sharedContext.makeCurrent(); // could cause exception + madeCurrent = sharedContext.isCurrent(); + if(madeCurrent) { + GL gl = sharedContext.getGL(); + hasNPOTTextures = gl.isNPOTTextureAvailable(); + hasRECTTextures = gl.isExtensionAvailable(GLExtensions.EXT_texture_rectangle); + hasAppleFloatPixels = gl.isExtensionAvailable(GLExtensions.APPLE_float_pixels); + } + } catch (GLException gle) { + if (DEBUG) { + System.err.println("MacOSXCGLDrawableFactory.createShared: INFO: makeCurrent catched exception:"); + gle.printStackTrace(); + } + } finally { + try { + sharedContext.destroy(); + } catch (GLException gle) { + if (DEBUG) { + System.err.println("MacOSXCGLDrawableFactory.createShared: INFO: destroy catched exception:"); + gle.printStackTrace(); } } - drawable.setRealized(false); } + sharedDrawable.setRealized(false); } sr = new SharedResource(sharedDevice, madeCurrent, hasNPOTTextures, hasRECTTextures, hasAppleFloatPixels); synchronized(sharedMap) { @@ -332,18 +331,82 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { } @Override - protected NativeSurface createOffscreenSurfaceImpl(AbstractGraphicsDevice device,GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, int width, int height) { - AbstractGraphicsScreen screen = DefaultGraphicsScreen.createDefault(NativeWindowFactory.TYPE_MACOSX); - WrappedSurface ns = new WrappedSurface(MacOSXCGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen, true)); - ns.surfaceSizeChanged(width, height); - return ns; + protected ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, + GLCapabilitiesChooser chooser, int width, int height, UpstreamSurfaceHook lifecycleHook) { + final MacOSXGraphicsDevice device; + if(createNewDevice) { + device = new MacOSXGraphicsDevice(deviceReq.getUnitID()); + } else { + device = (MacOSXGraphicsDevice)deviceReq; + } + final AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); + final MacOSXCGLGraphicsConfiguration config = MacOSXCGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen, true); + if(null == config) { + throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); + } + return new WrappedSurface(config, 0, width, height, lifecycleHook); } @Override - protected ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice device, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser) { - AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); - WrappedSurface ns = new WrappedSurface(MacOSXCGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen, true), windowHandle); - return ns; + public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { + final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(requestedCaps); + return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, width, height, dummySurfaceLifecycleHook); + } + private static final ProxySurface.UpstreamSurfaceHook dummySurfaceLifecycleHook = new ProxySurface.UpstreamSurfaceHook() { + long nsWindow = 0; + @Override + public final void create(ProxySurface s) { + if(0 == nsWindow && 0 == s.getSurfaceHandle()) { + nsWindow = OSXUtil.CreateNSWindow(0, 0, s.getWidth(), s.getHeight()); + if(0 == nsWindow) { + throw new GLException("Error NS window 0"); + } + long nsView = OSXUtil.GetNSView(nsWindow); + if(0 == nsView) { + throw new GLException("Error NS view 0"); + } + s.setSurfaceHandle(nsView); + s.setImplBitfield(ProxySurface.INVISIBLE_WINDOW); + if(DEBUG) { + System.err.println("MacOSXCGLDrawableFactory.dummySurfaceLifecycleHook.create: "+s); + } + } + } + @Override + public final void destroy(ProxySurface s) { + if(0 != nsWindow && 0 != s.getSurfaceHandle()) { + OSXUtil.DestroyNSWindow(nsWindow); + nsWindow = 0; + s.setSurfaceHandle(0); + if(DEBUG) { + System.err.println("MacOSXCGLDrawableFactory.dummySurfaceLifecycleHook.destroy: "+s); + } + } + } + @Override + public final int getWidth(ProxySurface s) { + return s.initialWidth; + } + @Override + public final int getHeight(ProxySurface s) { + return s.initialHeight; + } + + @Override + public String toString() { + return "MacOSXLSurfaceLifecycleHook[]"; + } + + }; + + @Override + protected ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { + final MacOSXGraphicsDevice device = new MacOSXGraphicsDevice(deviceReq.getUnitID()); + final AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, screenIdx); + final MacOSXCGLGraphicsConfiguration config = MacOSXCGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen, true); + return new WrappedSurface(config, windowHandle, 0, 0, upstream); } @Override diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java index 8393a688e..421e1ef96 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java @@ -154,7 +154,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration break; case CGL.NSOpenGLPFASamples: - ivalues[idx] = caps.getSampleBuffers() ? ivalues[idx] = caps.getNumSamples() : 0; + ivalues[idx] = caps.getNumSamples() ; break; default: @@ -233,7 +233,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration return fmt.get(0); } - static GLCapabilitiesImmutable CGLPixelFormat2GLCapabilities(long pixelFormat) { + static GLCapabilitiesImmutable CGLPixelFormat2GLCapabilities(long pixelFormat) { return PixelFormat2GLCapabilities(null, pixelFormat, false); } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java index ad4c06af2..6be9e386d 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java @@ -114,8 +114,7 @@ public class MacOSXExternalCGLContext extends MacOSXCGLContext { // set a fake marker stating a valid drawable currentDrawable = 1; } - WrappedSurface ns = new WrappedSurface(cfg); - ns.setSurfaceHandle(currentDrawable); + WrappedSurface ns = new WrappedSurface(cfg, currentDrawable, 64, 64, null); return new MacOSXExternalCGLContext(new Drawable(factory, ns), isNSContext, contextHandle); } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java index 242cea068..b144c020d 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java @@ -42,7 +42,7 @@ package jogamp.opengl.macosx.cgl; import javax.media.nativewindow.DefaultGraphicsConfiguration; import javax.media.nativewindow.NativeSurface; -import javax.media.nativewindow.SurfaceChangeable; +import javax.media.nativewindow.MutableSurface; import javax.media.opengl.GL; import javax.media.opengl.GL2; import javax.media.opengl.GL2GL3; @@ -95,12 +95,6 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { return ctx; } - @Override - protected long getNSViewHandle() { - // pbuffer handle is NSOpenGLPixelBuffer - return 0; - } - @Override public long getHandle() { return pBuffer; @@ -115,7 +109,7 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { NativeSurface ns = getNativeSurface(); impl.destroy(pBuffer); this.pBuffer = 0; - ((SurfaceChangeable)ns).setSurfaceHandle(0); + ((MutableSurface)ns).setSurfaceHandle(0); } } @@ -174,7 +168,7 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { throw new GLException("pbuffer creation error: CGL.createPBuffer() failed"); } - ((SurfaceChangeable)ns).setSurfaceHandle(pBuffer); + ((MutableSurface)ns).setSurfaceHandle(pBuffer); } @Override diff --git a/src/jogl/classes/jogamp/opengl/util/av/EGLMediaPlayerImpl.java b/src/jogl/classes/jogamp/opengl/util/av/EGLMediaPlayerImpl.java index 31f13297b..6bf8839af 100644 --- a/src/jogl/classes/jogamp/opengl/util/av/EGLMediaPlayerImpl.java +++ b/src/jogl/classes/jogamp/opengl/util/av/EGLMediaPlayerImpl.java @@ -113,7 +113,7 @@ public abstract class EGLMediaPlayerImpl extends GLMediaPlayerImpl { // create EGLImage from texture clientBuffer = null; // FIXME nioTmp.put(0, EGL.EGL_NONE); - image = eglExt.eglCreateImageKHR( eglDrawable.getDisplay(), eglCtx.getHandle(), + image = eglExt.eglCreateImageKHR( eglDrawable.getNativeSurface().getDisplayHandle(), eglCtx.getHandle(), EGLExt.EGL_GL_TEXTURE_2D_KHR, clientBuffer, nioTmp); if (0==image) { @@ -130,7 +130,7 @@ public abstract class EGLMediaPlayerImpl extends GLMediaPlayerImpl { // rendering the EGLImage texture before we tell OpenMAX to fill // it with a new frame. tmp[0] = EGL.EGL_NONE; - sync = eglExt.eglCreateSyncKHR(eglDrawable.getDisplay(), EGLExt.EGL_SYNC_FENCE_KHR, tmp, 0); + sync = eglExt.eglCreateSyncKHR(eglDrawable.getNativeSurface().getDisplayHandle(), EGLExt.EGL_SYNC_FENCE_KHR, tmp, 0); if (0==sync) { throw new RuntimeException("EGLSync creation failed: "+EGL.eglGetError()+", ctx "+eglCtx+", err "+toHexString(EGL.eglGetError())); } @@ -159,10 +159,10 @@ public abstract class EGLMediaPlayerImpl extends GLMediaPlayerImpl { final EGLTextureFrame eglTex = (EGLTextureFrame) imgTex; if(0!=eglTex.getImage()) { - eglExt.eglDestroyImageKHR(eglDrawable.getDisplay(), eglTex.getImage()); + eglExt.eglDestroyImageKHR(eglDrawable.getNativeSurface().getDisplayHandle(), eglTex.getImage()); } if(0!=eglTex.getSync()) { - eglExt.eglDestroySyncKHR(eglDrawable.getDisplay(), eglTex.getSync()); + eglExt.eglDestroySyncKHR(eglDrawable.getNativeSurface().getDisplayHandle(), eglTex.getSync()); } super.destroyTexImage(gl, imgTex); } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsBitmapWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsBitmapWGLDrawable.java index 296d53ce3..cf6f43b1c 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsBitmapWGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsBitmapWGLDrawable.java @@ -41,7 +41,7 @@ package jogamp.opengl.windows.wgl; import javax.media.nativewindow.NativeSurface; -import javax.media.nativewindow.SurfaceChangeable; +import javax.media.nativewindow.MutableSurface; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; @@ -139,7 +139,7 @@ public class WindowsBitmapWGLDrawable extends WindowsWGLDrawable { hbitmap = 0; throw new GLException("Error creating device context for offscreen OpenGL context, werr "+werr); } - ((SurfaceChangeable)ns).setSurfaceHandle(hdc); + ((MutableSurface)ns).setSurfaceHandle(hdc); if(DEBUG) { System.err.println("WindowsBitmapWGLDrawable (2): "+ns); } @@ -164,7 +164,7 @@ public class WindowsBitmapWGLDrawable extends WindowsWGLDrawable { GDI.DeleteDC(ns.getSurfaceHandle()); origbitmap = 0; hbitmap = 0; - ((SurfaceChangeable)ns).setSurfaceHandle(0); + ((MutableSurface)ns).setSurfaceHandle(0); } } } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsDummyWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsDummyWGLDrawable.java deleted file mode 100644 index 05d6d9862..000000000 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsDummyWGLDrawable.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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.windows.wgl; - -import javax.media.nativewindow.AbstractGraphicsScreen; -import javax.media.nativewindow.NativeSurface; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLContext; -import javax.media.opengl.GLDrawableFactory; -import javax.media.opengl.GLException; -import javax.media.opengl.GLProfile; - -import jogamp.nativewindow.windows.GDI; -import jogamp.nativewindow.windows.GDISurface; -import jogamp.nativewindow.windows.GDIUtil; - -public class WindowsDummyWGLDrawable extends WindowsWGLDrawable { - private long hwnd; - private boolean handleHwndLifecycle; - - private WindowsDummyWGLDrawable(GLDrawableFactory factory, GDISurface ns, boolean handleHwndLifecycle) { - super(factory, ns, true); - this.handleHwndLifecycle = handleHwndLifecycle; - - if(NativeSurface.LOCK_SURFACE_NOT_READY >= ns.lockSurface()) { - throw new GLException("WindowsDummyWGLDrawable: surface not ready (lockSurface)"); - } - try { - WindowsWGLGraphicsConfiguration config = (WindowsWGLGraphicsConfiguration)ns.getGraphicsConfiguration(); - config.updateGraphicsConfiguration(factory, ns, null); - if (DEBUG) { - System.err.println("WindowsDummyWGLDrawable: "+config); - } - } catch (Throwable t) { - setRealized(false); - throw new GLException(t); - } finally { - unlockSurface(); - } - } - - public static WindowsDummyWGLDrawable create(GLDrawableFactory factory, GLProfile glp, AbstractGraphicsScreen absScreen, - long windowHandle, int width, int height, boolean handleWindowLifecycle) { - if(0 == windowHandle) { - throw new GLException("Error windowHandle 0, werr: "+GDI.GetLastError()); - } - GLCapabilities caps = new GLCapabilities(glp); - WindowsWGLGraphicsConfiguration cfg = WindowsWGLGraphicsConfigurationFactory.createDefaultGraphicsConfiguration(caps, absScreen); - GDISurface ns = new GDISurface(cfg, windowHandle); - ns.surfaceSizeChanged(width, height); - return new WindowsDummyWGLDrawable(factory, ns, handleWindowLifecycle); - } - - @Override - public GLContext createContext(GLContext shareWith) { - // FIXME: figure out how to hook back in the Java 2D / JOGL bridge - return new WindowsWGLContext(this, shareWith); - } - - @Override - protected void setRealizedImpl() { - super.setRealizedImpl(); - if(!realized) { - if (handleHwndLifecycle && hwnd != 0) { - GDI.ShowWindow(hwnd, GDI.SW_HIDE); - GDIUtil.DestroyDummyWindow(hwnd); - hwnd = 0; - } - } - } -} diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java index 86441c688..96c1187d3 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java @@ -55,7 +55,6 @@ import com.jogamp.nativewindow.WrappedSurface; import jogamp.nativewindow.windows.GDI; import jogamp.opengl.GLContextShareSet; - public class WindowsExternalWGLContext extends WindowsWGLContext { private GLContext lastContext; @@ -103,7 +102,7 @@ public class WindowsExternalWGLContext extends WindowsWGLContext { System.err.println("WindowsExternalWGLContext valid hdc/pfd, retrieved cfg: " + cfg); } } - return new WindowsExternalWGLContext(new Drawable(factory, new WrappedSurface(cfg, hdc)), ctx, cfg); + return new WindowsExternalWGLContext(new Drawable(factory, new WrappedSurface(cfg, hdc, 64, 64, null)), ctx, cfg); } @Override diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java index 8f22aa60e..15bd005dc 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java @@ -50,6 +50,7 @@ import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; import jogamp.nativewindow.windows.GDI; +import jogamp.nativewindow.windows.GDIUtil; import com.jogamp.nativewindow.WrappedSurface; @@ -69,9 +70,9 @@ public class WindowsExternalWGLDrawable extends WindowsWGLDrawable { throw new GLException("Error: attempted to make an external GLContext without a valid pixelformat, werr " + GDI.GetLastError()); } - AbstractGraphicsScreen aScreen = DefaultGraphicsScreen.createDefault(NativeWindowFactory.TYPE_WINDOWS); - WindowsWGLGraphicsConfiguration cfg = WindowsWGLGraphicsConfiguration.createFromExternal(factory, hdc, pfdID, glp, aScreen, true); - return new WindowsExternalWGLDrawable(factory, new WrappedSurface(cfg, hdc)); + final AbstractGraphicsScreen aScreen = DefaultGraphicsScreen.createDefault(NativeWindowFactory.TYPE_WINDOWS); + final WindowsWGLGraphicsConfiguration cfg = WindowsWGLGraphicsConfiguration.createFromExternal(factory, hdc, pfdID, glp, aScreen, true); + return new WindowsExternalWGLDrawable(factory, new WrappedSurface(cfg, hdc, 64, 64, null)); } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLContext.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLContext.java index a11d6e78e..7dda6a1f1 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLContext.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLContext.java @@ -42,6 +42,8 @@ package jogamp.opengl.windows.wgl; import javax.media.opengl.*; +import com.jogamp.opengl.GLExtensions; + import jogamp.opengl.GLContextImpl; public class WindowsPbufferWGLContext extends WindowsWGLContext { @@ -112,7 +114,7 @@ public class WindowsPbufferWGLContext extends WindowsWGLContext { } else { hasRTT = true; - if (rect && !gl.isExtensionAvailable("GL_NV_texture_rectangle")) { + if (rect && !gl.isExtensionAvailable(GLExtensions.NV_texture_rectangle)) { System.err.println("WindowsPbufferWGLContext: WARNING: GL_NV_texture_rectangle extension not " + "supported; skipping requested render_to_texture_rectangle support for pbuffer"); rect = false; diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java index b00c796ec..175622343 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java @@ -42,7 +42,7 @@ package jogamp.opengl.windows.wgl; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.SurfaceChangeable; +import javax.media.nativewindow.MutableSurface; import javax.media.opengl.GL; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; @@ -92,7 +92,7 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { if (wglExt.wglReleasePbufferDCARB(buffer, ns.getSurfaceHandle()) == 0) { throw new GLException("Error releasing pbuffer device context: error code " + GDI.GetLastError()); } - ((SurfaceChangeable)ns).setSurfaceHandle(0); + ((MutableSurface)ns).setSurfaceHandle(0); } if (!wglExt.wglDestroyPbufferARB(buffer)) { throw new GLException("Error destroying pbuffer: error code " + GDI.GetLastError()); @@ -121,7 +121,7 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { } try { long sharedHdc = sharedSurface.getSurfaceHandle(); - WGLExt wglExt = sharedResource.getContext().getWGLExt(); + WGLExt wglExt = ((WindowsWGLContext)sharedResource.getContext()).getWGLExt(); if (DEBUG) { System.out.println("Pbuffer config: " + config); @@ -131,7 +131,6 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { float[] fattributes = new float[1]; int[] floatModeTmp = new int[1]; int niattribs = 0; - int width, height; GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable)config.getChosenCapabilities(); GLProfile glProfile = chosenCaps.getGLProfile(); @@ -206,7 +205,7 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { iattributes[niattribs++] = WGLExt.WGL_MIPMAP_TEXTURE_ARB; iattributes[niattribs++] = GL.GL_FALSE; - iattributes[niattribs++] = WGLExt.WGL_PBUFFER_LARGEST_ARB; + iattributes[niattribs++] = WGLExt.WGL_PBUFFER_LARGEST_ARB; // exact iattributes[niattribs++] = GL.GL_FALSE; } @@ -235,7 +234,7 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { NativeSurface ns = getNativeSurface(); // Set up instance variables buffer = tmpBuffer; - ((SurfaceChangeable)ns).setSurfaceHandle(tmpHdc); + ((MutableSurface)ns).setSurfaceHandle(tmpHdc); cachedWGLExt = wglExt; // Re-query chosen pixel format @@ -249,14 +248,6 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { } config.setCapsPFD(newCaps); } - - // Determine the actual width and height we were able to create. - int[] tmp = new int[1]; - wglExt.wglQueryPbufferARB( buffer, WGLExt.WGL_PBUFFER_WIDTH_ARB, tmp, 0 ); - width = tmp[0]; - wglExt.wglQueryPbufferARB( buffer, WGLExt.WGL_PBUFFER_HEIGHT_ARB, tmp, 0 ); - height = tmp[0]; - ((SurfaceChangeable)ns).surfaceSizeChanged(width, height); } finally { sharedSurface.unlockSurface(); } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java index f143c158b..8825bad0a 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java @@ -53,6 +53,8 @@ import javax.media.opengl.GLCapabilitiesImmutable; import com.jogamp.gluegen.runtime.ProcAddressTable; import com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver; +import com.jogamp.opengl.GLExtensions; + import jogamp.nativewindow.windows.GDI; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableImpl; @@ -77,8 +79,8 @@ public class WindowsWGLContext extends GLContextImpl { functionNameMap.put("glFreeMemoryNV", "wglFreeMemoryNV"); extensionNameMap = new HashMap(); - extensionNameMap.put("GL_ARB_pbuffer", "WGL_ARB_pbuffer"); - extensionNameMap.put("GL_ARB_pixel_format", "WGL_ARB_pixel_format"); + extensionNameMap.put(GLExtensions.ARB_pbuffer, WindowsWGLDrawableFactory.WGL_ARB_pbuffer); + extensionNameMap.put(GLExtensions.ARB_pixel_format, WindowsWGLDrawableFactory.WGL_ARB_pixel_format); } // FIXME: figure out how to hook back in the Java 2D / JOGL bridge diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java index 176d27a71..09e97ff79 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java @@ -51,9 +51,10 @@ import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.DefaultGraphicsScreen; import javax.media.nativewindow.NativeSurface; -import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; import javax.media.opengl.GL; +import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; @@ -67,9 +68,11 @@ import jogamp.nativewindow.windows.GDISurface; import jogamp.nativewindow.windows.GDIUtil; import jogamp.nativewindow.windows.RegisteredClassFactory; import jogamp.opengl.DesktopGLDynamicLookupHelper; +import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableFactoryImpl; import jogamp.opengl.GLDrawableImpl; import jogamp.opengl.GLDynamicLookupHelper; +import jogamp.opengl.GLGraphicsConfigurationUtil; import jogamp.opengl.SharedResourceRunner; import com.jogamp.common.JogampRuntimeException; @@ -79,6 +82,7 @@ import com.jogamp.common.util.ReflectionUtil; import com.jogamp.common.util.VersionNumber; import com.jogamp.nativewindow.WrappedSurface; import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; +import com.jogamp.opengl.GLExtensions; public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { private static DesktopGLDynamicLookupHelper windowsWGLDynamicLookupHelper = null; @@ -203,8 +207,8 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { static class SharedResource implements SharedResourceRunner.Resource { private WindowsGraphicsDevice device; private AbstractGraphicsScreen screen; - private WindowsDummyWGLDrawable drawable; - private WindowsWGLContext context; + private GLDrawableImpl drawable; + private GLContextImpl context; private boolean hasARBPixelFormat; private boolean hasARBMultisample; private boolean hasARBPBuffer; @@ -214,7 +218,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { private boolean isVendorNVIDIA; private boolean needsCurrenContext4ARBPFDQueries; - SharedResource(WindowsGraphicsDevice dev, AbstractGraphicsScreen scrn, WindowsDummyWGLDrawable draw, WindowsWGLContext ctx, + SharedResource(WindowsGraphicsDevice dev, AbstractGraphicsScreen scrn, GLDrawableImpl draw, GLContextImpl ctx, boolean arbPixelFormat, boolean arbMultisample, boolean arbPBuffer, boolean arbReadDrawable, String glVendor) { device = dev; screen = scrn; @@ -250,9 +254,9 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { @Override final public AbstractGraphicsScreen getScreen() { return screen; } @Override - final public WindowsWGLDrawable getDrawable() { return drawable; } + final public GLDrawableImpl getDrawable() { return drawable; } @Override - final public WindowsWGLContext getContext() { return context; } + final public GLContextImpl getContext() { return context; } final boolean hasARBPixelFormat() { return hasARBPixelFormat; } final boolean hasARBMultisample() { return hasARBMultisample; } @@ -302,21 +306,18 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { @Override public SharedResourceRunner.Resource createSharedResource(String connection) { - WindowsGraphicsDevice sharedDevice = new WindowsGraphicsDevice(connection, AbstractGraphicsDevice.DEFAULT_UNIT); + final WindowsGraphicsDevice sharedDevice = new WindowsGraphicsDevice(connection, AbstractGraphicsDevice.DEFAULT_UNIT); sharedDevice.lock(); try { - AbstractGraphicsScreen absScreen = new DefaultGraphicsScreen(sharedDevice, 0); - GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP, false); + final AbstractGraphicsScreen absScreen = new DefaultGraphicsScreen(sharedDevice, 0); + final GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP, false); if (null == glp) { throw new GLException("Couldn't get default GLProfile for device: "+sharedDevice); } - final int f_dim = 64; - long hwnd = GDIUtil.CreateDummyWindow(0, 0, f_dim, f_dim); - WindowsDummyWGLDrawable sharedDrawable = WindowsDummyWGLDrawable.create(WindowsWGLDrawableFactory.this, glp, absScreen, hwnd, f_dim, f_dim, true); - if (null == sharedDrawable) { - throw new GLException("Couldn't create shared drawable for screen: "+absScreen+", "+glp); - } - WindowsWGLContext sharedContext = (WindowsWGLContext) sharedDrawable.createContext(null); + final GLDrawableImpl sharedDrawable = createOnscreenDrawableImpl(createDummySurfaceImpl(sharedDevice, false, new GLCapabilities(glp), null, 64, 64)); + sharedDrawable.setRealized(true); + + final GLContextImpl sharedContext = (GLContextImpl) sharedDrawable.createContext(null); if (null == sharedContext) { throw new GLException("Couldn't create shared context for drawable: "+sharedDrawable); } @@ -329,7 +330,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { try { hasARBPixelFormat = sharedContext.isExtensionAvailable(WGL_ARB_pixel_format); hasARBMultisample = sharedContext.isExtensionAvailable(WGL_ARB_multisample); - hasARBPBuffer = sharedContext.isExtensionAvailable(GL_ARB_pbuffer); + hasARBPBuffer = sharedContext.isExtensionAvailable(GLExtensions.ARB_pbuffer); hasARBReadDrawableAvailable = sharedContext.isExtensionAvailable(WGL_ARB_make_current_read) && sharedContext.isFunctionAvailable(wglMakeContextCurrent); vendor = sharedContext.getGL().glGetString(GL.GL_VENDOR); @@ -401,7 +402,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { return false; } - final static String GL_ARB_pbuffer = "GL_ARB_pbuffer"; + final static String WGL_ARB_pbuffer = "WGL_ARB_pbuffer"; final static String WGL_ARB_pixel_format = "WGL_ARB_pixel_format"; final static String WGL_ARB_multisample = "WGL_ARB_multisample"; final static String WGL_NV_float_buffer = "WGL_NV_float_buffer"; @@ -534,22 +535,89 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { } @Override - protected final NativeSurface createOffscreenSurfaceImpl(AbstractGraphicsDevice device, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, int width, int height) { - AbstractGraphicsScreen screen = DefaultGraphicsScreen.createDefault(NativeWindowFactory.TYPE_WINDOWS); - WrappedSurface ns = new WrappedSurface(WindowsWGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic( - capsChosen, capsRequested, chooser, screen) ); - ns.surfaceSizeChanged(width, height); - return ns; + protected final ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, + GLCapabilitiesChooser chooser, int width, int height, UpstreamSurfaceHook lifecycleHook) { + final WindowsGraphicsDevice device; + if(createNewDevice) { + device = new WindowsGraphicsDevice(deviceReq.getConnection(), deviceReq.getUnitID()); + } else { + device = (WindowsGraphicsDevice)deviceReq; + } + final AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); + final WindowsWGLGraphicsConfiguration config = WindowsWGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen); + if(null == config) { + throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); + } + return new WrappedSurface(config, 0, width, height, lifecycleHook); } @Override - protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice adevice, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser) { - // FIXME device/windowHandle -> screen ?! - WindowsGraphicsDevice device = (WindowsGraphicsDevice) adevice; - AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); - WindowsWGLGraphicsConfiguration cfg = WindowsWGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen); - GDISurface ns = new GDISurface(cfg, windowHandle); - return ns; + public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { + final WindowsGraphicsDevice device; + if(createNewDevice) { + device = new WindowsGraphicsDevice(deviceReq.getConnection(), deviceReq.getUnitID()); + } else { + device = (WindowsGraphicsDevice)deviceReq; + } + final AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); + final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(requestedCaps); + final WindowsWGLGraphicsConfiguration config = WindowsWGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(chosenCaps, requestedCaps, chooser, screen); + if(null == config) { + throw new GLException("Choosing GraphicsConfiguration failed w/ "+requestedCaps+" on "+screen); + } + return new GDISurface(config, 0, width, height, dummySurfaceLifecycleHook); + } + private static final ProxySurface.UpstreamSurfaceHook dummySurfaceLifecycleHook = new ProxySurface.UpstreamSurfaceHook() { + @Override + public final void create(ProxySurface s) { + final GDISurface ms = (GDISurface)s; + if(0 == ms.getWindowHandle()) { + final long windowHandle = GDIUtil.CreateDummyWindow(0, 0, s.getWidth(), s.getHeight()); + if(0 == windowHandle) { + throw new GLException("Error windowHandle 0, werr: "+GDI.GetLastError()); + } + ms.setWindowHandle(windowHandle); + if(DEBUG) { + System.err.println("WindowsWGLDrawableFactory.dummySurfaceLifecycleHook.create: "+ms); + } + } + } + @Override + public final void destroy(ProxySurface s) { + final GDISurface ms = (GDISurface)s; + if(0 != ms.getWindowHandle()) { + GDI.ShowWindow(ms.getWindowHandle(), GDI.SW_HIDE); + GDIUtil.DestroyDummyWindow(ms.getWindowHandle()); + ms.setWindowHandle(0); + if(DEBUG) { + System.err.println("WindowsWGLDrawableFactory.dummySurfaceLifecycleHook.destroy: "+ms); + } + } + } + @Override + public final int getWidth(ProxySurface s) { + return s.initialWidth; + } + @Override + public final int getHeight(ProxySurface s) { + return s.initialHeight; + } + + @Override + public String toString() { + return "GDISurfaceLifecycleHook[]"; + } + }; + + + @Override + protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { + final WindowsGraphicsDevice device = new WindowsGraphicsDevice(deviceReq.getConnection(), deviceReq.getUnitID()); + final AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, screenIdx); + final WindowsWGLGraphicsConfiguration cfg = WindowsWGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen); + return new GDISurface(cfg, windowHandle, 0, 0, upstream); } @Override diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java index 408d8b074..209589b29 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java @@ -48,11 +48,13 @@ import javax.media.opengl.GLPbuffer; import javax.media.opengl.GLProfile; import com.jogamp.nativewindow.MutableGraphicsConfiguration; +import com.jogamp.opengl.GLExtensions; import jogamp.nativewindow.windows.DWM_BLURBEHIND; import jogamp.nativewindow.windows.GDI; import jogamp.nativewindow.windows.MARGINS; import jogamp.nativewindow.windows.PIXELFORMATDESCRIPTOR; +import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLGraphicsConfigurationUtil; public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable { @@ -160,7 +162,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } if (!WGLUtil.SetPixelFormat(hdc, caps.getPFDID(), caps.getPFD())) { - throw new GLException("Unable to set pixel format " + caps + + throw new GLException("Unable to set pixel format " + caps.getPFDID() + " of " + caps + " for device context " + toHexString(hdc) + ": error code " + GDI.GetLastError()); } @@ -250,7 +252,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } if(sharedResource.hasARBPBuffer()) { - WindowsWGLContext sharedCtx = sharedResource.getContext(); + GLContextImpl sharedCtx = sharedResource.getContext(); if(null != sharedCtx && sharedCtx.isExtensionAvailable(WindowsWGLDrawableFactory.WGL_NV_float_buffer)) { // pbo float buffer iattributes[niattribs++] = WGLExt.WGL_FLOAT_COMPONENTS_NV; // nvidia @@ -313,12 +315,12 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio int niattribs = fillAttribsForGeneralWGLARBQuery(sharedResource, iattributes); - if (!sharedResource.getContext().getWGLExt().wglGetPixelFormatAttribivARB(hdc, pfdID, 0, niattribs, iattributes, 0, iresults, 0)) { + if (!((WindowsWGLContext)sharedResource.getContext()).getWGLExt().wglGetPixelFormatAttribivARB(hdc, pfdID, 0, niattribs, iattributes, 0, iresults, 0)) { throw new GLException("wglARBPFID2GLCapabilities: Error getting pixel format attributes for pixel format " + pfdID + " of device context " + toHexString(hdc) + ", werr " + GDI.GetLastError()); } List bucket = new ArrayList(1); - final int winattrbits = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer); + final int winattrbits = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, false); if(AttribList2GLCapabilities(bucket, glp, hdc, pfdID, iattributes, niattribs, iresults, winattrbits)) { return (WGLGLCapabilities) bucket.get(0); } @@ -342,7 +344,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio int[] pformatsTmp = new int[WindowsWGLGraphicsConfiguration.MAX_PFORMATS]; int[] numFormatsTmp = new int[1]; - if ( !sharedResource.getContext().getWGLExt().wglChoosePixelFormatARB(hdc, iattributes, 0, + if ( !((WindowsWGLContext)sharedResource.getContext()).getWGLExt().wglChoosePixelFormatARB(hdc, iattributes, 0, fattributes, 0, WindowsWGLGraphicsConfiguration.MAX_PFORMATS, pformatsTmp, 0, numFormatsTmp, 0)) @@ -374,7 +376,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio static List wglARBPFIDs2GLCapabilities(WindowsWGLDrawableFactory.SharedResource sharedResource, long hdc, int[] pfdIDs, GLProfile glp, boolean onscreen, boolean usePBuffer) { - final int winattrbits = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer); + final int winattrbits = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, false); return wglARBPFIDs2GLCapabilitiesImpl(sharedResource, hdc, pfdIDs, glp, winattrbits); } @@ -398,7 +400,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio for(int i = 0; i= 1 && - sharedResource.getContext().getWGLExt().wglGetPixelFormatAttribivARB(hdc, pfdIDs[i], 0, niattribs, iattributes, 0, iresults, 0) ) { + ((WindowsWGLContext)sharedResource.getContext()).getWGLExt().wglGetPixelFormatAttribivARB(hdc, pfdIDs[i], 0, niattribs, iattributes, 0, iresults, 0) ) { AttribList2GLCapabilities(bucket, glp, hdc, pfdIDs[i], iattributes, niattribs, iresults, winattrbits); } else if (DEBUG) { System.err.println("wglARBPFIDs2GLCapabilities: Cannot get pixel format attributes for pixel format " + @@ -507,9 +509,9 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio throw new GLException("Render-to-texture-rectangle requires render-to-texture to be specified"); } - WindowsWGLContext sharedCtx = sharedResource.getContext(); + GLContextImpl sharedCtx = sharedResource.getContext(); if (rect) { - if (!sharedCtx.isExtensionAvailable("GL_NV_texture_rectangle")) { + if (!sharedCtx.isExtensionAvailable(GLExtensions.NV_texture_rectangle)) { throw new GLException("Render-to-texture-rectangle requires GL_NV_texture_rectangle extension"); } } @@ -658,7 +660,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } static WGLGLCapabilities PFD2GLCapabilities(GLProfile glp, long hdc, int pfdID, boolean onscreen) { - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, false); + final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, false, false); List capsBucket = new ArrayList(1); if( PFD2GLCapabilities(capsBucket, glp, hdc, pfdID, winattrmask) ) { return (WGLGLCapabilities) capsBucket.get(0); diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java index 850b64aa8..943c7fec4 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java @@ -52,6 +52,7 @@ import javax.media.opengl.GLProfile; import jogamp.nativewindow.windows.GDI; import jogamp.nativewindow.windows.PIXELFORMATDESCRIPTOR; +import jogamp.opengl.GLDrawableImpl; import jogamp.opengl.GLGraphicsConfigurationFactory; import jogamp.opengl.GLGraphicsConfigurationUtil; @@ -99,10 +100,10 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat if(null==absScreen) { absScreen = DefaultGraphicsScreen.createDefault(NativeWindowFactory.TYPE_WINDOWS); } - AbstractGraphicsDevice absDevice = absScreen.getDevice(); - + final AbstractGraphicsDevice absDevice = absScreen.getDevice(); + final GLDrawableFactory factory = GLDrawableFactory.getDesktopFactory(); capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( - capsChosen, GLDrawableFactory.getDesktopFactory().canCreateGLPbuffer(absDevice) ); + capsChosen, GLContext.isFBOAvailable(absDevice, capsChosen.getGLProfile()), factory.canCreateGLPbuffer(absDevice) ); return new WindowsWGLGraphicsConfiguration( absScreen, capsChosen, capsReq, (GLCapabilitiesChooser)chooser ); } @@ -112,9 +113,9 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat if(null == sharedResource) { throw new GLException("Shared resource for device n/a: "+device); } - WindowsWGLDrawable sharedDrawable = sharedResource.getDrawable(); + GLDrawableImpl sharedDrawable = sharedResource.getDrawable(); GLCapabilitiesImmutable capsChosen = sharedDrawable.getChosenGLCapabilities(); - WindowsWGLContext sharedContext = sharedResource.getContext(); + GLContext sharedContext = sharedResource.getContext(); List availableCaps = null; if ( sharedResource.needsCurrentContext4ARBPFDQueries() ) { @@ -150,7 +151,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } static List getAvailableGLCapabilitiesARB(long hdc, WindowsWGLDrawableFactory.SharedResource sharedResource, GLProfile glProfile) { - int[] pformats = WindowsWGLGraphicsConfiguration.wglAllARBPFIDs(sharedResource.getContext(), hdc); + int[] pformats = WindowsWGLGraphicsConfiguration.wglAllARBPFIDs((WindowsWGLContext)sharedResource.getContext(), hdc); return WindowsWGLGraphicsConfiguration.wglARBPFIDs2AllGLCapabilities(sharedResource, hdc, pformats, glProfile); } @@ -265,7 +266,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } AbstractGraphicsDevice device = config.getScreen().getDevice(); WindowsWGLDrawableFactory.SharedResource sharedResource = ((WindowsWGLDrawableFactory)factory).getOrCreateSharedResource(device); - WindowsWGLContext sharedContext = null; + GLContext sharedContext = null; if (null != sharedResource && sharedResource.needsCurrentContext4ARBPFDQueries()) { sharedContext = sharedResource.getContext(); if(GLContext.CONTEXT_NOT_CURRENT == sharedContext.makeCurrent()) { @@ -355,7 +356,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat System.err.println("updateGraphicsConfigurationARB: wglChoosePixelFormatARB failed with: "+capsChosen); } // 2nd choice: get all GLCapabilities available, no preferred recommendedIndex available - pformats = WindowsWGLGraphicsConfiguration.wglAllARBPFIDs(sharedResource.getContext(), hdc); + pformats = WindowsWGLGraphicsConfiguration.wglAllARBPFIDs((WindowsWGLContext)sharedResource.getContext(), hdc); if (DEBUG) { final int len = ( null != pformats ) ? pformats.length : 0; System.err.println("updateGraphicsConfigurationARB: NumFormats (wglAllARBPFIDs) " + len); @@ -451,7 +452,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat if(null == pformats) { pformats = WindowsWGLGraphicsConfiguration.wglAllGDIPFIDs(hdc); } - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, false); + final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, false, false); for (int i = 0; i < pformats.length; i++) { WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(availableCaps, glProfile, hdc, pformats[i], winattrmask); diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11DummyGLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11DummyGLXDrawable.java deleted file mode 100644 index 8914e2db9..000000000 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11DummyGLXDrawable.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package jogamp.opengl.x11.glx; - -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLCapabilitiesImmutable; -import javax.media.opengl.GLDrawableFactory; -import javax.media.opengl.GLProfile; - -import jogamp.nativewindow.x11.X11Lib; - -import com.jogamp.nativewindow.WrappedSurface; -import com.jogamp.nativewindow.x11.X11GraphicsDevice; -import com.jogamp.nativewindow.x11.X11GraphicsScreen; - -public class X11DummyGLXDrawable extends X11OnscreenGLXDrawable { - private static final int f_dim = 64; - private long dummyWindow = 0; - - /** - * Due to the ATI Bug https://bugzilla.mozilla.org/show_bug.cgi?id=486277, - * we cannot switch the Display as we please, - * hence we reuse the target's screen configuration. - */ - public X11DummyGLXDrawable(X11GraphicsScreen screen, GLDrawableFactory factory, GLCapabilitiesImmutable caps) { - super(factory, - new WrappedSurface(X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic( - caps, caps, null, screen))); - this.realized = true; - - WrappedSurface ns = (WrappedSurface) getNativeSurface(); - X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration)ns.getGraphicsConfiguration(); - - X11GraphicsDevice device = (X11GraphicsDevice) screen.getDevice(); - long dpy = device.getHandle(); - int scrn = screen.getIndex(); - int visualID = config.getXVisualID(); - - dummyWindow = X11Lib.CreateDummyWindow(dpy, scrn, visualID, f_dim, f_dim); - ns.setSurfaceHandle( dummyWindow ); - ns.surfaceSizeChanged(f_dim, f_dim); - - updateHandle(); - } - - public static X11DummyGLXDrawable create(X11GraphicsScreen screen, GLDrawableFactory factory, GLProfile glp) { - GLCapabilities caps = new GLCapabilities(glp); - return new X11DummyGLXDrawable(screen, factory, caps); - } - - public void setSize(int width, int height) { - } - - @Override - public int getWidth() { - return 1; - } - - @Override - public int getHeight() { - return 1; - } - - - @Override - protected void setRealizedImpl() { - super.setRealizedImpl(); - if(!realized) { - if(0!=dummyWindow) { - destroyHandle(); - X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration)getNativeSurface().getGraphicsConfiguration(); - X11Lib.DestroyDummyWindow(config.getScreen().getDevice().getHandle(), dummyWindow); - } - } - } -} diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java index 53776386c..b847363e0 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java @@ -76,8 +76,15 @@ public class X11ExternalGLXContext extends X11GLXContext { long drawable = GLX.glXGetCurrentDrawable(); if (drawable == 0) { throw new GLException("Error: attempted to make an external GLDrawable without a drawable/context current"); - } + } int[] val = new int[1]; + + int w, h; + GLX.glXQueryDrawable(display, drawable, GLX.GLX_WIDTH, val, 0); + w=val[0]; + GLX.glXQueryDrawable(display, drawable, GLX.GLX_HEIGHT, val, 0); + h=val[0]; + GLX.glXQueryContext(display, ctx, GLX.GLX_SCREEN, val, 0); X11GraphicsScreen x11Screen = (X11GraphicsScreen) X11GraphicsScreen.createScreenDevice(display, val[0], false); @@ -97,8 +104,7 @@ public class X11ExternalGLXContext extends X11GLXContext { cfg = X11GLXGraphicsConfiguration.create(glp, x11Screen, val[0]); } - WrappedSurface ns = new WrappedSurface(cfg); - ns.setSurfaceHandle(drawable); + final WrappedSurface ns = new WrappedSurface(cfg, drawable, w, h, null); return new X11ExternalGLXContext(new Drawable(factory, ns), ctx); } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java index 3fabe7a13..8652e2d4a 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java @@ -87,10 +87,7 @@ public class X11ExternalGLXDrawable extends X11GLXDrawable { System.err.println("X11ExternalGLXDrawable: WARNING: forcing GLX_RGBA_TYPE for newly created contexts (current 0x"+Integer.toHexString(val[0])+")"); } } - WrappedSurface ns = new WrappedSurface(cfg); - ns.setSurfaceHandle(drawable); - ns.surfaceSizeChanged(w, h); - return new X11ExternalGLXDrawable(factory, ns); + return new X11ExternalGLXDrawable(factory, new WrappedSurface(cfg, drawable, w, h, null)); } @Override diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java index 0afadc677..e6b74a769 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java @@ -61,6 +61,7 @@ import jogamp.opengl.GLDrawableImpl; import com.jogamp.common.nio.Buffers; import com.jogamp.gluegen.runtime.ProcAddressTable; import com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver; +import com.jogamp.opengl.GLExtensions; public abstract class X11GLXContext extends GLContextImpl { private static final Map functionNameMap; @@ -83,8 +84,8 @@ public abstract class X11GLXContext extends GLContextImpl { functionNameMap.put("glFreeMemoryNV", "glXFreeMemoryNV"); extensionNameMap = new HashMap(); - extensionNameMap.put("GL_ARB_pbuffer", "GLX_SGIX_pbuffer"); - extensionNameMap.put("GL_ARB_pixel_format", "GLX_SGIX_pbuffer"); // good enough + extensionNameMap.put(GLExtensions.ARB_pbuffer, X11GLXDrawableFactory.GLX_SGIX_pbuffer); + extensionNameMap.put(GLExtensions.ARB_pixel_format, X11GLXDrawableFactory.GLX_SGIX_pbuffer); // good enough } X11GLXContext(GLDrawableImpl drawable, @@ -508,8 +509,8 @@ public abstract class X11GLXContext extends GLContextImpl { @Override public boolean isExtensionAvailable(String glExtensionName) { - if (glExtensionName.equals("GL_ARB_pbuffer") || - glExtensionName.equals("GL_ARB_pixel_format")) { + if (glExtensionName.equals(GLExtensions.ARB_pbuffer) || + glExtensionName.equals(GLExtensions.ARB_pixel_format)) { return getGLDrawable().getFactory().canCreateGLPbuffer( drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice() ); } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index 9a563bdb8..8ffbf3951 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -49,6 +49,8 @@ import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; +import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; @@ -64,6 +66,7 @@ import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableFactoryImpl; import jogamp.opengl.GLDrawableImpl; import jogamp.opengl.GLDynamicLookupHelper; +import jogamp.opengl.GLGraphicsConfigurationUtil; import jogamp.opengl.SharedResourceRunner; import com.jogamp.common.util.VersionNumber; @@ -79,6 +82,8 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { public static final VersionNumber versionOneThree = new VersionNumber(1, 3, 0); public static final VersionNumber versionOneFour = new VersionNumber(1, 4, 0); + static final String GLX_SGIX_pbuffer = "GLX_SGIX_pbuffer"; + private static DesktopGLDynamicLookupHelper x11GLXDynamicLookupHelper = null; public X11GLXDrawableFactory() { @@ -153,8 +158,8 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { static class SharedResource implements SharedResourceRunner.Resource { X11GraphicsDevice device; X11GraphicsScreen screen; - X11DummyGLXDrawable drawable; - X11GLXContext context; + GLDrawableImpl drawable; + GLContextImpl context; String glXServerVendorName; boolean isGLXServerVendorATI; boolean isGLXServerVendorNVIDIA; @@ -164,7 +169,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { boolean glXMultisampleAvailable; SharedResource(X11GraphicsDevice dev, X11GraphicsScreen scrn, - X11DummyGLXDrawable draw, X11GLXContext ctx, + GLDrawableImpl draw, GLContextImpl ctx, VersionNumber glXServerVer, String glXServerVendor, boolean glXServerMultisampleAvail) { device = dev; screen = scrn; @@ -224,13 +229,15 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { @Override public SharedResourceRunner.Resource createSharedResource(String connection) { - X11GraphicsDevice sharedDevice = + final X11GraphicsDevice sharedDevice = new X11GraphicsDevice(X11Util.openDisplay(connection), AbstractGraphicsDevice.DEFAULT_UNIT, - true); // own non-shared display connection, no locking + true); // own non-shared display connection, w/ locking // new X11GraphicsDevice(X11Util.openDisplay(connection), AbstractGraphicsDevice.DEFAULT_UNIT, - // NativeWindowFactory.getNullToolkitLock(), true); // own non-shared display connection, no locking + // NativeWindowFactory.getNullToolkitLock(), true); // own non-shared display connection, w/o locking sharedDevice.lock(); try { + final X11GraphicsScreen sharedScreen = new X11GraphicsScreen(sharedDevice, 0); + if(!GLXUtil.isGLXAvailableOnServer(sharedDevice)) { throw new GLException("GLX not available on device/server: "+sharedDevice); } @@ -242,20 +249,20 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { X11Util.setMarkAllDisplaysUnclosable(true); X11Util.markDisplayUncloseable(sharedDevice.getHandle()); } - X11GraphicsScreen sharedScreen = new X11GraphicsScreen(sharedDevice, 0); - - GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP, false); + + final GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP, false); if (null == glp) { throw new GLException("Couldn't get default GLProfile for device: "+sharedDevice); } - X11DummyGLXDrawable sharedDrawable = X11DummyGLXDrawable.create(sharedScreen, X11GLXDrawableFactory.this, glp); - if (null == sharedDrawable) { - throw new GLException("Couldn't create shared drawable for screen: "+sharedScreen+", "+glp); - } - X11GLXContext sharedContext = (X11GLXContext) sharedDrawable.createContext(null); + + final GLDrawableImpl sharedDrawable = createOnscreenDrawableImpl(createDummySurfaceImpl(sharedDevice, false, new GLCapabilities(glp), null, 64, 64)); + sharedDrawable.setRealized(true); + + final GLContextImpl sharedContext = (GLContextImpl) sharedDrawable.createContext(null); if (null == sharedContext) { throw new GLException("Couldn't create shared context for drawable: "+sharedDrawable); } + boolean madeCurrent = false; sharedContext.makeCurrent(); try { @@ -298,7 +305,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { if (null != sr.context) { // may cause JVM SIGSEGV: - sr.context.destroy(); + sr.context.destroy(); // will also pull the dummy MutuableSurface sr.context = null; } @@ -394,7 +401,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { if (target == null) { throw new IllegalArgumentException("Null target"); } - return new X11OnscreenGLXDrawable(this, target); + return new X11OnscreenGLXDrawable(this, target, false); } @Override @@ -495,40 +502,88 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { } @Override - protected final NativeSurface createOffscreenSurfaceImpl(AbstractGraphicsDevice deviceReq, - GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, - GLCapabilitiesChooser chooser, - int width, int height) { - if(null == deviceReq) { - throw new InternalError("deviceReq is null"); - } - final SharedResourceRunner.Resource sr = sharedResourceRunner.getOrCreateShared(deviceReq); - if(null==sr) { - throw new InternalError("No SharedResource for: "+deviceReq); + protected final ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + GLCapabilitiesImmutable capsChosen, + GLCapabilitiesImmutable capsRequested, + GLCapabilitiesChooser chooser, int width, int height, UpstreamSurfaceHook lifecycleHook) { + final X11GraphicsDevice device; + if(createNewDevice) { + // Null X11 locking, due to private non-shared Display handle + device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), NativeWindowFactory.getNullToolkitLock(), true); + } else { + device = (X11GraphicsDevice)deviceReq; } - final X11GraphicsScreen sharedScreen = (X11GraphicsScreen) sr.getScreen(); - final AbstractGraphicsDevice sharedDevice = sharedScreen.getDevice(); // should be same .. - - // create screen/device pair - Null X11 locking, due to private non-shared Display handle - final X11GraphicsDevice device = new X11GraphicsDevice(X11Util.openDisplay(sharedDevice.getConnection()), AbstractGraphicsDevice.DEFAULT_UNIT, NativeWindowFactory.getNullToolkitLock(), true); - final X11GraphicsScreen screen = new X11GraphicsScreen(device, sharedScreen.getIndex()); - - WrappedSurface ns = new WrappedSurface( - X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen) ); - if(ns != null) { - ns.surfaceSizeChanged(width, height); + final X11GraphicsScreen screen = new X11GraphicsScreen(device, 0); + final X11GLXGraphicsConfiguration config = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen); + if(null == config) { + throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); } - return ns; + return new WrappedSurface( config, 0, width, height, lifecycleHook); } @Override - protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice adevice, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser) { - // FIXME device/windowHandle -> screen ?! - X11GraphicsDevice device = (X11GraphicsDevice) adevice; - X11GraphicsScreen screen = new X11GraphicsScreen(device, 0); - X11GLXGraphicsConfiguration cfg = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen); - WrappedSurface ns = new WrappedSurface(cfg, windowHandle); - return ns; + public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { + final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(requestedCaps); + return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, width, height, dummySurfaceLifecycleHook); + } + private static final ProxySurface.UpstreamSurfaceHook dummySurfaceLifecycleHook = new ProxySurface.UpstreamSurfaceHook() { + @Override + public final void create(ProxySurface s) { + if( 0 == s.getSurfaceHandle() ) { + final X11GLXGraphicsConfiguration cfg = (X11GLXGraphicsConfiguration) s.getGraphicsConfiguration(); + final X11GraphicsScreen screen = (X11GraphicsScreen) cfg.getScreen(); + final X11GraphicsDevice device = (X11GraphicsDevice) screen.getDevice(); + if(0 == device.getHandle()) { + device.open(); + s.setImplBitfield(ProxySurface.OWN_DEVICE); + } + final long windowHandle = X11Lib.CreateDummyWindow(device.getHandle(), screen.getIndex(), cfg.getXVisualID(), s.getWidth(), s.getHeight()); + if(0 == windowHandle) { + throw new GLException("Creating dummy window failed w/ "+cfg+", "+s.getWidth()+"x"+s.getHeight()); + } + s.setSurfaceHandle(windowHandle); + if(DEBUG) { + System.err.println("X11GLXDrawableFactory.dummySurfaceLifecycleHook.create: "+s); + } + } + } + @Override + public final void destroy(ProxySurface s) { + if(0 != s.getSurfaceHandle()) { + final X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration) s.getGraphicsConfiguration(); + final X11GraphicsDevice device = (X11GraphicsDevice) config.getScreen().getDevice(); + X11Lib.DestroyDummyWindow(device.getHandle(), s.getSurfaceHandle()); + s.setSurfaceHandle(0); + if( 0 != ( ProxySurface.OWN_DEVICE & s.getImplBitfield() ) ) { + device.close(); + } + if(DEBUG) { + System.err.println("X11GLXDrawableFactory.dummySurfaceLifecycleHook.destroy: "+s); + } + } + } + @Override + public final int getWidth(ProxySurface s) { + return s.initialWidth; + } + @Override + public final int getHeight(ProxySurface s) { + return s.initialHeight; + } + @Override + public String toString() { + return "X11SurfaceLifecycleHook[]"; + } + }; + + + @Override + protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { + final X11GraphicsDevice device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), NativeWindowFactory.getNullToolkitLock(), true); + final X11GraphicsScreen screen = new X11GraphicsScreen(device, screenIdx); + final X11GLXGraphicsConfiguration cfg = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen); + return new WrappedSurface(cfg, windowHandle, 0, 0, upstream); } @Override diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java index b54b5150c..b5b80e0b3 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java @@ -36,12 +36,14 @@ package jogamp.opengl.x11.glx; import java.util.ArrayList; import java.util.List; +import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.opengl.DefaultGLCapabilitiesChooser; import javax.media.opengl.GL; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; @@ -67,7 +69,8 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem } static X11GLXGraphicsConfiguration create(GLProfile glp, X11GraphicsScreen x11Screen, int fbcfgID) { - final long display = x11Screen.getDevice().getHandle(); + final AbstractGraphicsDevice device = x11Screen.getDevice(); + final long display = device.getHandle(); if(0==display) { throw new GLException("Display null of "+x11Screen); } @@ -80,7 +83,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem glp = GLProfile.getDefault(x11Screen.getDevice()); } final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); - final X11GLCapabilities caps = GLXFBConfig2GLCapabilities(glp, display, fbcfg, true, true, true, factory.isGLXMultisampleAvailable(x11Screen.getDevice())); + final X11GLCapabilities caps = GLXFBConfig2GLCapabilities(glp, device, fbcfg, true, true, true, factory.isGLXMultisampleAvailable(device)); if(null==caps) { throw new GLException("GLCapabilities null of "+toHexString(fbcfg)); } @@ -233,11 +236,11 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem return true; } - static int FBCfgDrawableTypeBits(final long display, final long fbcfg) { + static int FBCfgDrawableTypeBits(final AbstractGraphicsDevice device, GLProfile glp, final long fbcfg) { int val = 0; int[] tmp = new int[1]; - int fbtype = glXGetFBConfig(display, fbcfg, GLX.GLX_DRAWABLE_TYPE, tmp, 0); + int fbtype = glXGetFBConfig(device.getHandle(), fbcfg, GLX.GLX_DRAWABLE_TYPE, tmp, 0); if ( 0 != ( fbtype & GLX.GLX_WINDOW_BIT ) ) { val |= GLGraphicsConfigurationUtil.WINDOW_BIT; @@ -248,17 +251,20 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem if ( 0 != ( fbtype & GLX.GLX_PBUFFER_BIT ) ) { val |= GLGraphicsConfigurationUtil.PBUFFER_BIT; } + if ( GLContext.isFBOAvailable(device, glp) ) { + val |= GLGraphicsConfigurationUtil.FBO_BIT; + } return val; } - static X11GLCapabilities GLXFBConfig2GLCapabilities(GLProfile glp, long display, long fbcfg, + static X11GLCapabilities GLXFBConfig2GLCapabilities(GLProfile glp, AbstractGraphicsDevice device, long fbcfg, boolean relaxed, boolean onscreen, boolean usePBuffer, boolean isMultisampleAvailable) { ArrayList bucket = new ArrayList(); - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer); - if( GLXFBConfig2GLCapabilities(bucket, glp, display, fbcfg, winattrmask, isMultisampleAvailable) ) { + final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, false); + if( GLXFBConfig2GLCapabilities(bucket, glp, device, fbcfg, winattrmask, isMultisampleAvailable) ) { return (X11GLCapabilities) bucket.get(0); - } else if ( relaxed && GLXFBConfig2GLCapabilities(bucket, glp, display, fbcfg, GLGraphicsConfigurationUtil.ALL_BITS, isMultisampleAvailable) ) { + } else if ( relaxed && GLXFBConfig2GLCapabilities(bucket, glp, device, fbcfg, GLGraphicsConfigurationUtil.ALL_BITS, isMultisampleAvailable) ) { return (X11GLCapabilities) bucket.get(0); } return null; @@ -273,11 +279,12 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem } static boolean GLXFBConfig2GLCapabilities(List capsBucket, - GLProfile glp, long display, long fbcfg, + GLProfile glp, AbstractGraphicsDevice device, long fbcfg, int winattrmask, boolean isMultisampleAvailable) { - final int allDrawableTypeBits = FBCfgDrawableTypeBits(display, fbcfg); + final int allDrawableTypeBits = FBCfgDrawableTypeBits(device, glp, fbcfg); int drawableTypeBits = winattrmask & allDrawableTypeBits; - + + final long display = device.getHandle(); int fbcfgid = X11GLXGraphicsConfiguration.glXFBConfig2FBConfigID(display, fbcfg); XVisualInfo visualInfo = GLX.glXGetVisualFromFBConfig(display, fbcfg); if(null == visualInfo) { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java index 8377d2453..331401c06 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java @@ -44,6 +44,7 @@ import javax.media.opengl.DefaultGLCapabilitiesChooser; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; @@ -161,7 +162,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF return null; } for (int i = 0; i < fbcfgsL.limit(); i++) { - if( !X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(availableCaps, glProfile, display, fbcfgsL.get(i), GLGraphicsConfigurationUtil.ALL_BITS, isMultisampleAvailable) ) { + if( !X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(availableCaps, glProfile, absDevice, fbcfgsL.get(i), GLGraphicsConfigurationUtil.ALL_BITS, isMultisampleAvailable) ) { if(DEBUG) { System.err.println("X11GLXGraphicsConfiguration.getAvailableGLCapabilitiesFBConfig: FBConfig invalid (2): ("+x11Screen+"): fbcfg: "+toHexString(fbcfgsL.get(i))); } @@ -209,7 +210,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF X11GraphicsDevice x11Device = (X11GraphicsDevice) x11Screen.getDevice(); X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); - capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, factory.canCreateGLPbuffer(x11Device) ); + capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, GLContext.isFBOAvailable(x11Device, capsChosen.getGLProfile()), factory.canCreateGLPbuffer(x11Device) ); boolean usePBuffer = capsChosen.isPBuffer(); X11GLXGraphicsConfiguration res = null; @@ -245,7 +246,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); - final X11GLCapabilities caps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(glp, display, fbcfg, true, true, true, factory.isGLXMultisampleAvailable(absDevice)); + final X11GLCapabilities caps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(glp, absDevice, fbcfg, true, true, true, factory.isGLXMultisampleAvailable(absDevice)); return new X11GLXGraphicsConfiguration(x11Screen, caps, caps, new DefaultGLCapabilitiesChooser()); } @@ -258,6 +259,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF GLProfile glProfile = capsChosen.getGLProfile(); boolean onscreen = capsChosen.isOnscreen(); boolean usePBuffer = capsChosen.isPBuffer(); + boolean useFBO = capsChosen.isFBO(); // Utilizing FBConfig // @@ -270,13 +272,12 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF int[] attribs = X11GLXGraphicsConfiguration.GLCapabilities2AttribList(capsChosen, true, isMultisampleAvailable, display, screen); int[] count = { -1 }; List availableCaps = new ArrayList(); - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer); - + final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, useFBO); // 1st choice: get GLCapabilities based on users GLCapabilities setting recommendedIndex as preferred choice fbcfgsL = GLX.glXChooseFBConfig(display, screen, attribs, 0, count, 0); if (fbcfgsL != null && fbcfgsL.limit()>0) { for (int i = 0; i < fbcfgsL.limit(); i++) { - if( !X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(availableCaps, glProfile, display, fbcfgsL.get(i), winattrmask, isMultisampleAvailable) ) { + if( !X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(availableCaps, glProfile, absDevice, fbcfgsL.get(i), winattrmask, isMultisampleAvailable) ) { if(DEBUG) { System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: FBConfig invalid (1): ("+x11Screen+","+capsChosen+"): fbcfg: "+toHexString(fbcfgsL.get(i))); } @@ -309,7 +310,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } for (int i = 0; i < fbcfgsL.limit(); i++) { - if( !X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(availableCaps, glProfile, display, fbcfgsL.get(i), winattrmask, isMultisampleAvailable) ) { + if( !X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(availableCaps, glProfile, absDevice, fbcfgsL.get(i), winattrmask, isMultisampleAvailable) ) { if(DEBUG) { System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: FBConfig invalid (2): ("+x11Screen+"): fbcfg: "+toHexString(fbcfgsL.get(i))); } @@ -338,7 +339,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } GLProfile glProfile = capsChosen.getGLProfile(); - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(capsChosen.isOnscreen(), false /* pbuffer */); + final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(capsChosen.isOnscreen(), false /* pbuffer */, false); List availableCaps = new ArrayList(); int recommendedIndex = -1; diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11OnscreenGLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11OnscreenGLXDrawable.java index 9e22afa6d..363299321 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11OnscreenGLXDrawable.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11OnscreenGLXDrawable.java @@ -51,10 +51,13 @@ public class X11OnscreenGLXDrawable extends X11GLXDrawable { long glXWindow; // GLXWindow, a GLXDrawable representation boolean useGLXWindow; - protected X11OnscreenGLXDrawable(GLDrawableFactory factory, NativeSurface component) { - super(factory, component, false); + protected X11OnscreenGLXDrawable(GLDrawableFactory factory, NativeSurface component, boolean realized) { + super(factory, component, realized); glXWindow=0; useGLXWindow=false; + if(realized) { + updateHandle(); + } } @Override diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11PbufferGLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11PbufferGLXDrawable.java index cdf81ebd3..e1fe2f27e 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11PbufferGLXDrawable.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11PbufferGLXDrawable.java @@ -43,7 +43,7 @@ package jogamp.opengl.x11.glx; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.NativeSurface; -import javax.media.nativewindow.SurfaceChangeable; +import javax.media.nativewindow.MutableSurface; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; @@ -77,7 +77,7 @@ public class X11PbufferGLXDrawable extends X11GLXDrawable { if (ns.getSurfaceHandle() != 0) { GLX.glXDestroyPbuffer(ns.getDisplayHandle(), ns.getSurfaceHandle()); } - ((SurfaceChangeable)ns).setSurfaceHandle(0); + ((MutableSurface)ns).setSurfaceHandle(0); } private void createPbuffer() { @@ -108,12 +108,14 @@ public class X11PbufferGLXDrawable extends X11GLXDrawable { // Create the p-buffer. int niattribs = 0; - int[] iattributes = new int[5]; + int[] iattributes = new int[7]; iattributes[niattribs++] = GLX.GLX_PBUFFER_WIDTH; iattributes[niattribs++] = ns.getWidth(); iattributes[niattribs++] = GLX.GLX_PBUFFER_HEIGHT; iattributes[niattribs++] = ns.getHeight(); + iattributes[niattribs++] = GLX.GLX_LARGEST_PBUFFER; // exact + iattributes[niattribs++] = 0; iattributes[niattribs++] = 0; long pbuffer = GLX.glXCreatePbuffer(display, config.getFBConfig(), iattributes, 0); @@ -123,15 +125,7 @@ public class X11PbufferGLXDrawable extends X11GLXDrawable { } // Set up instance variables - ((SurfaceChangeable)ns).setSurfaceHandle(pbuffer); - - // Determine the actual width and height we were able to create. - int[] tmp = new int[1]; - GLX.glXQueryDrawable(display, pbuffer, GLX.GLX_WIDTH, tmp, 0); - int width = tmp[0]; - GLX.glXQueryDrawable(display, pbuffer, GLX.GLX_HEIGHT, tmp, 0); - int height = tmp[0]; - ((SurfaceChangeable)ns).surfaceSizeChanged(width, height); + ((MutableSurface)ns).setSurfaceHandle(pbuffer); if (DEBUG) { System.err.println("Created pbuffer " + this); diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11PixmapGLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11PixmapGLXDrawable.java index 1e7b89828..04627724c 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11PixmapGLXDrawable.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11PixmapGLXDrawable.java @@ -43,7 +43,7 @@ package jogamp.opengl.x11.glx; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.NativeSurface; -import javax.media.nativewindow.SurfaceChangeable; +import javax.media.nativewindow.MutableSurface; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; @@ -93,7 +93,7 @@ public class X11PixmapGLXDrawable extends X11GLXDrawable { pixmap = 0; throw new GLException("glXCreateGLXPixmap failed"); } - ((SurfaceChangeable)ns).setSurfaceHandle(drawable); + ((MutableSurface)ns).setSurfaceHandle(drawable); if (DEBUG) { System.err.println("Created pixmap " + toHexString(pixmap) + ", GLXPixmap " + toHexString(drawable) + @@ -133,7 +133,7 @@ public class X11PixmapGLXDrawable extends X11GLXDrawable { X11Lib.XFreePixmap(display, pixmap); drawable = 0; pixmap = 0; - ((SurfaceChangeable)ns).setSurfaceHandle(0); + ((MutableSurface)ns).setSurfaceHandle(0); display = 0; } } diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m index 776284cfc..b81b43e54 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m @@ -32,7 +32,6 @@ int texWidth; int texHeight; GLuint textureID; - struct timespec lastWaitTime; #ifdef HAS_CADisplayLink CADisplayLink* displayLink; #else @@ -41,6 +40,7 @@ int tc; struct timespec t0; @public + struct timespec lastWaitTime; GLint swapInterval; GLint swapIntervalCounter; pthread_mutex_t renderLock; diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m index 8ac9f4700..d3f703142 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m @@ -503,7 +503,7 @@ NSView* getNSView(NSOpenGLContext* ctx) { NSOpenGLContext* createContext(NSOpenGLContext* share, NSView* view, - Bool isBackingLayerView, + Bool allowIncompleteView, NSOpenGLPixelFormat* fmt, Bool opaque, int* viewNotReady) @@ -512,13 +512,13 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, getRendererInfo(); - DBG_PRINT("createContext.0: share %p, view %p, isBackingLayer %d, pixfmt %p, opaque %d\n", - share, view, (int)isBackingLayerView, fmt, opaque); + DBG_PRINT("createContext.0: share %p, view %p, allowIncompleteView %d, pixfmt %p, opaque %d\n", + share, view, (int)allowIncompleteView, fmt, opaque); if (view != NULL) { Bool viewReady = true; - if(!isBackingLayerView) { + if(!allowIncompleteView) { if ([view lockFocusIfCanDraw] == NO) { DBG_PRINT("createContext.1 [view lockFocusIfCanDraw] failed\n"); viewReady = false; @@ -527,7 +527,7 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, if(viewReady) { NSRect frame = [view frame]; if ((frame.size.width == 0) || (frame.size.height == 0)) { - if(!isBackingLayerView) { + if(!allowIncompleteView) { [view unlockFocus]; } DBG_PRINT("createContext.2 view.frame size %dx%d\n", (int)frame.size.width, (int)frame.size.height); @@ -558,7 +558,7 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, [ctx setValues:&zeroOpacity forParameter:NSOpenGLCPSurfaceOpacity]; } [ctx setView:view]; - if(!isBackingLayerView) { + if(!allowIncompleteView) { [view unlockFocus]; } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java b/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java index 04f616daf..b7f6ba45d 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java @@ -30,51 +30,49 @@ package com.jogamp.nativewindow; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.ProxySurface; -import javax.media.nativewindow.SurfaceChangeable; +public class WrappedSurface extends ProxySurface { + protected long surfaceHandle; -public class WrappedSurface extends ProxySurface implements SurfaceChangeable { - protected long surfaceHandle; - - public WrappedSurface(AbstractGraphicsConfiguration cfg) { - this(cfg, 0); - } - - public WrappedSurface(AbstractGraphicsConfiguration cfg, long handle) { - super(cfg); + public WrappedSurface(AbstractGraphicsConfiguration cfg, long handle, int initialWidth, int initialHeight, UpstreamSurfaceHook upstream) { + super(cfg, initialWidth, initialHeight, upstream); surfaceHandle=handle; } @Override - protected final void invalidateImpl() { + protected void invalidateImpl() { surfaceHandle = 0; } @Override - final public long getSurfaceHandle() { + public final long getSurfaceHandle() { return surfaceHandle; } @Override - final public void setSurfaceHandle(long surfaceHandle) { + public final void setSurfaceHandle(long surfaceHandle) { this.surfaceHandle=surfaceHandle; } - + @Override - final protected int lockSurfaceImpl() { - return LOCK_SUCCESS; + protected final int lockSurfaceImpl() { + return LOCK_SUCCESS; } @Override - final protected void unlockSurfaceImpl() { + protected final void unlockSurfaceImpl() { } @Override public String toString() { + final UpstreamSurfaceHook ush = getUpstreamSurfaceHook(); + final String ush_s = null != ush ? ( ush.getClass().getName() + ": " + ush ) : "nil"; + return "WrappedSurface[config " + getPrivateGraphicsConfiguration()+ ", displayHandle 0x" + Long.toHexString(getDisplayHandle()) + ", surfaceHandle 0x" + Long.toHexString(getSurfaceHandle()) + ", size " + getWidth() + "x" + getHeight() + - ", surfaceLock "+surfaceLock+"]"; + ", surfaceLock "+surfaceLock+ + ", upstreamSurfaceHook "+ush_s+"]"; } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java index d161f2f34..389949e90 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java @@ -38,7 +38,7 @@ import javax.media.nativewindow.*; */ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneable { final long nativeDisplayID; - final EGLTerminateCallback eglTerminateCallback; + final EGLDisplayLifecycleCallback eglLifecycleCallback; /** * Hack to allow inject a EGL termination call. @@ -47,7 +47,14 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl * since then it can be utilized directly. *

      */ - public interface EGLTerminateCallback { + public interface EGLDisplayLifecycleCallback { + /** + * Implementation should issue an EGL.eglGetDisplay(nativeDisplayID) + * inclusive EGL.eglInitialize(eglDisplayHandle, ..) call. + * @param eglDisplayHandle + */ + public long eglGetAndInitDisplay(long nativeDisplayID); + /** * Implementation should issue an EGL.eglTerminate(eglDisplayHandle) call. * @param eglDisplayHandle @@ -61,28 +68,45 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl */ public EGLGraphicsDevice(String connection, int unitID) { super(NativeWindowFactory.TYPE_EGL, connection, unitID); - this.nativeDisplayID = 0; - this.eglTerminateCallback = null; + this.nativeDisplayID = 0 ; // EGL.EGL_DEFAULT_DISPLAY + this.eglLifecycleCallback = null; } - public EGLGraphicsDevice(long nativeDisplayID, long eglDisplay, String connection, int unitID, EGLTerminateCallback eglTerminateCallback) { + public EGLGraphicsDevice(long nativeDisplayID, long eglDisplay, String connection, int unitID, EGLDisplayLifecycleCallback eglLifecycleCallback) { super(NativeWindowFactory.TYPE_EGL, connection, unitID, eglDisplay); this.nativeDisplayID = nativeDisplayID; - this.eglTerminateCallback = eglTerminateCallback; + this.eglLifecycleCallback = eglLifecycleCallback; } public long getNativeDisplayID() { return nativeDisplayID; } + @Override public Object clone() { return super.clone(); } + + @Override + public boolean open() { + if(null != eglLifecycleCallback && 0 == handle) { + if(DEBUG) { + System.err.println(Thread.currentThread().getName() + " - EGLGraphicsDevice.open(): "+this); + } + handle = eglLifecycleCallback.eglGetAndInitDisplay(nativeDisplayID); + if(0 == handle) { + throw new NativeWindowException("EGLGraphicsDevice.open() failed: "+this); + } + return true; + } + return false; + } + @Override public boolean close() { - if(null != eglTerminateCallback) { + if(null != eglLifecycleCallback && 0 != handle) { if(DEBUG) { - System.err.println(Thread.currentThread().getName() + " - eglTerminate: "+this); + System.err.println(Thread.currentThread().getName() + " - EGLGraphicsDevice.close(): "+this); } - eglTerminateCallback.eglTerminate(handle); + eglLifecycleCallback.eglTerminate(handle); } return super.close(); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index 735d85fb1..0494bb408 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -43,7 +43,6 @@ import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsDevice; -import jogamp.common.awt.AWTEDTExecutor; import jogamp.nativewindow.macosx.OSXUtil; public class SWTAccessor { @@ -204,8 +203,6 @@ public class SWTAccessor { if( null != OS_gtk_class ) { long widgedHandle = callStaticMethodL2L(OS_GTK_WIDGET_WINDOW, handle); long displayHandle = callStaticMethodL2L(OS_gdk_x11_drawable_get_xdisplay, widgedHandle); - // FIXME: May think about creating a private non-shared X11 Display handle, like we use to for AWT - // to avoid locking problems ! return new X11GraphicsDevice(displayHandle, AbstractGraphicsDevice.DEFAULT_UNIT, false); } if( NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false) ) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index a02332413..7a98e3c25 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -33,7 +33,6 @@ package com.jogamp.nativewindow.x11; -import jogamp.nativewindow.Debug; import jogamp.nativewindow.x11.X11Lib; import jogamp.nativewindow.x11.X11Util; @@ -46,7 +45,7 @@ import javax.media.nativewindow.ToolkitLock; */ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneable { - final boolean closeDisplay; + final boolean handleOwner; /** Constructs a new X11GraphicsDevice corresponding to the given connection and default * {@link javax.media.nativewindow.ToolkitLock} via {@link NativeWindowFactory#getDefaultToolkitLock(String)}.
      @@ -56,7 +55,7 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl */ public X11GraphicsDevice(String connection, int unitID) { super(NativeWindowFactory.TYPE_X11, connection, unitID); - closeDisplay = false; + handleOwner = false; } /** Constructs a new X11GraphicsDevice corresponding to the given native display handle and default @@ -69,7 +68,7 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl if(0==display) { throw new NativeWindowException("null display"); } - closeDisplay = owner; + handleOwner = owner; } /** @@ -82,16 +81,39 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl if(0==display) { throw new NativeWindowException("null display"); } - closeDisplay = owner; + handleOwner = owner; } + public int getDefaultVisualID() { + // It still could be an AWT hold handle .. + final long display = getHandle(); + final int scrnIdx = X11Lib.DefaultScreen(display); + return (int) X11Lib.DefaultVisualID(display, scrnIdx); + } + + @Override public Object clone() { return super.clone(); } + @Override + public boolean open() { + if(handleOwner && 0 == handle) { + if(DEBUG) { + System.err.println(Thread.currentThread().getName() + " - X11GraphicsDevice.open(): "+this); + } + handle = X11Util.openDisplay(connection); + if(0 == handle) { + throw new NativeWindowException("X11GraphicsDevice.open() failed: "+this); + } + return true; + } + return false; + } + + @Override public boolean close() { - // FIXME: shall we respect the unitID ? - if(closeDisplay && 0 != handle) { + if(handleOwner && 0 != handle) { if(DEBUG) { System.err.println(Thread.currentThread().getName() + " - X11GraphicsDevice.close(): "+this); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java index 94013ec38..014f4f688 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java @@ -56,13 +56,11 @@ public class X11GraphicsScreen extends DefaultGraphicsScreen implements Cloneabl return new X11GraphicsScreen(new X11GraphicsDevice(display, AbstractGraphicsDevice.DEFAULT_UNIT, owner), screenIdx); } - public long getDefaultVisualID() { + public int getVisualID() { // It still could be an AWT hold handle .. - long display = getDevice().getHandle(); - int scrnIdx = X11Lib.DefaultScreen(display); - return X11Lib.DefaultVisualID(display, scrnIdx); + return (int) X11Lib.DefaultVisualID(getDevice().getHandle(), getIndex()); } - + private static int fetchScreen(X11GraphicsDevice device, int screen) { // It still could be an AWT hold handle .. if(X11Util.XineramaIsEnabled(device.getHandle())) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java index 4979f1949..756e4451b 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java @@ -113,16 +113,33 @@ public interface AbstractGraphicsDevice extends Cloneable { */ public void unlock(); + /** + * Optionally [re]opening the device if handle is null. + *

      + * The default implementation is a NOP. + *

      + *

      + * Example implementations like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice} + * or {@link com.jogamp.nativewindow.egl.EGLGraphicsDevice} + * issue the native open operation in case handle is null. + *

      + * + * @return true if the handle was null and opening was successful, otherwise false. + */ + public boolean open(); + /** - * Optionally closing the device. + * Optionally closing the device if handle is not null. *

      * The default implementation is a NOP, just setting the handle to null. *

      - * The specific implementing, ie {@link com.jogamp.nativewindow.x11.X11GraphicsDevice}, - * shall have a enable/disable like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice#setCloseDisplay(boolean, boolean)},
      - * which shall be invoked at creation time to determine ownership/role of freeing the resource.
      + *

      + * Example implementations like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice} + * or {@link com.jogamp.nativewindow.egl.EGLGraphicsDevice} + * issue the native close operation or skip it depending on the handles's ownership. + *

      * - * @return true if the handle was not null, otherwise false. + * @return true if the handle was not null and closing was successful, otherwise false. */ public boolean close(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java index 187959a67..583fde07f 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java @@ -97,22 +97,27 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice } } + @Override public final String getType() { return type; } + @Override public final String getConnection() { return connection; } + @Override public final int getUnitID() { return unitID; } + @Override public final String getUniqueID() { return uniqueID; } + @Override public final long getHandle() { return handle; } @@ -124,6 +129,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long) * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long, javax.media.nativewindow.ToolkitLock) */ + @Override public final void lock() { toolkitLock.lock(); } @@ -135,10 +141,17 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long) * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long, javax.media.nativewindow.ToolkitLock) */ + @Override public final void unlock() { toolkitLock.unlock(); } + + @Override + public boolean open() { + return false; + } + @Override public boolean close() { if(0 != handle) { handle = 0; diff --git a/src/nativewindow/classes/javax/media/nativewindow/MutableSurface.java b/src/nativewindow/classes/javax/media/nativewindow/MutableSurface.java new file mode 100644 index 000000000..ff53c8109 --- /dev/null +++ b/src/nativewindow/classes/javax/media/nativewindow/MutableSurface.java @@ -0,0 +1,44 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package javax.media.nativewindow; + +/** + * Provides a {@link NativeSurface} with a mutable surfaceHandle + * via {@link #setSurfaceHandle(long)}. + * + * @see NativeSurface + */ +public interface MutableSurface extends NativeSurface { + + /** + * Sets the surface handle which is created outside of this implementation. + */ + public void setSurfaceHandle(long surfaceHandle); +} + diff --git a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java index 1dabc3dcd..7fc9789c2 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java @@ -28,38 +28,108 @@ package javax.media.nativewindow; - import jogamp.nativewindow.Debug; import jogamp.nativewindow.SurfaceUpdatedHelper; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; -public abstract class ProxySurface implements NativeSurface { +public abstract class ProxySurface implements NativeSurface, MutableSurface { public static final boolean DEBUG = Debug.debug("ProxySurface"); + + /** + * Implementation specific bitvalue stating the upstream's {@link AbstractGraphicsDevice} is owned by this {@link ProxySurface}. + * @see #setImplBitfield(int) + * @see #getImplBitfield() + */ + public static final int OWN_DEVICE = 1 << 7; + + /** + * Implementation specific bitvalue stating the upstream's {@link NativeSurface} is an invisible window, i.e. maybe incomplete. + * @see #setImplBitfield(int) + * @see #getImplBitfield() + */ + public static final int INVISIBLE_WINDOW = 1 << 8; - private SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); - private AbstractGraphicsConfiguration config; // control access due to delegation - protected RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); + /** Interface allowing upstream caller to pass lifecycle actions and size info to a {@link ProxySurface} instance. */ + public interface UpstreamSurfaceHook { + /** called within {@link ProxySurface#createNotify()} within lock, before using surface. */ + public void create(ProxySurface s); + /** called within {@link ProxySurface#destroyNotify()} within lock, before clearing fields. */ + public void destroy(ProxySurface s); + + /** Returns the width of the upstream surface */ + public int getWidth(ProxySurface s); + /** Returns the height of the upstream surface */ + public int getHeight(ProxySurface s); + } + + private final SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); + private final AbstractGraphicsConfiguration config; // control access due to delegation + private final UpstreamSurfaceHook upstream; + public final int initialWidth; + public final int initialHeight; private long surfaceHandle_old; + protected RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); protected long displayHandle; - protected int height; protected int scrnIndex; - protected int width; + protected int implBitfield; - public ProxySurface(AbstractGraphicsConfiguration cfg) { - invalidate(); - config = cfg; - displayHandle=cfg.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); - surfaceHandle_old = 0; + /** + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param initialWidth the initial width + * @param initialHeight the initial height + */ + protected ProxySurface(AbstractGraphicsConfiguration cfg, int initialWidth, int initialHeight, UpstreamSurfaceHook upstream) { + if(null == cfg) { + throw new IllegalArgumentException("null config"); + } + this.config = cfg; + this.upstream = upstream; + this.initialWidth = initialWidth; + this.initialHeight = initialHeight; + this.displayHandle=config.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); + this.surfaceHandle_old = 0; + this.implBitfield = 0; } - void invalidate() { - displayHandle = 0; - invalidateImpl(); + public final UpstreamSurfaceHook getUpstreamSurfaceHook() { return upstream; } + + /** + * If a valid {@link UpstreamSurfaceHook} instance is passed in the + * {@link ProxySurface#ProxySurface(AbstractGraphicsConfiguration, int, int, UpstreamSurfaceHook) constructor}, + * {@link UpstreamSurfaceHook#create(ProxySurface)} is being issued and the proxy surface/window handles shall be set. + */ + public void createNotify() { + if(null != upstream) { + upstream.create(this); + } + this.displayHandle=config.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); + this.surfaceHandle_old = 0; } - protected abstract void invalidateImpl(); - + + /** + * If a valid {@link UpstreamSurfaceHook} instance is passed in the + * {@link ProxySurface#ProxySurface(AbstractGraphicsConfiguration, int, int, UpstreamSurfaceHook) constructor}, + * {@link UpstreamSurfaceHook#destroy(ProxySurface)} is being issued and all fields are cleared. + */ + public void destroyNotify() { + if(null != upstream) { + upstream.destroy(this); + invalidateImpl(); + } + this.displayHandle = 0; + this.surfaceHandle_old = 0; + } + + /** + * Must be overridden by implementations allowing having a {@link UpstreamSurfaceHook} being passed. + * @see #destroyNotify() + */ + protected void invalidateImpl() { + throw new InternalError("UpstreamSurfaceHook given, but required method not implemented."); + } + @Override public final long getDisplayHandle() { return displayHandle; @@ -82,19 +152,23 @@ public abstract class ProxySurface implements NativeSurface { @Override public abstract long getSurfaceHandle(); + @Override + public abstract void setSurfaceHandle(long surfaceHandle); + @Override public final int getWidth() { - return width; + if(null != upstream) { + return upstream.getWidth(this); + } + return initialWidth; } @Override public final int getHeight() { - return height; - } - - public void surfaceSizeChanged(int width, int height) { - this.width = width; - this.height = height; + if(null != upstream) { + return upstream.getHeight(this); + } + return initialHeight; } @Override @@ -187,7 +261,10 @@ public abstract class ProxySurface implements NativeSurface { public final Thread getSurfaceLockOwner() { return surfaceLock.getOwner(); } - + @Override public abstract String toString(); + + public int getImplBitfield() { return implBitfield; } + public void setImplBitfield(int v) { implBitfield=v; } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/SurfaceChangeable.java b/src/nativewindow/classes/javax/media/nativewindow/SurfaceChangeable.java deleted file mode 100644 index 956e68e61..000000000 --- a/src/nativewindow/classes/javax/media/nativewindow/SurfaceChangeable.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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.nativewindow; - -public interface SurfaceChangeable { - - /** Sets the surface handle which is created outside of this implementation */ - public void setSurfaceHandle(long surfaceHandle); - - /** - * The surface's size has been determined or changed. - * Implementation shall update the stored surface size with the given ones. - */ - public void surfaceSizeChanged(int width, int height); - -} - diff --git a/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java b/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java index 4877d5c4f..4f68c6945 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java +++ b/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java @@ -34,8 +34,8 @@ import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.SurfaceUpdatedListener; public class SurfaceUpdatedHelper implements SurfaceUpdatedListener { - private Object surfaceUpdatedListenersLock = new Object(); - private ArrayList surfaceUpdatedListeners = new ArrayList(); + private final Object surfaceUpdatedListenersLock = new Object(); + private final ArrayList surfaceUpdatedListeners = new ArrayList(); // // Management Utils diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 42fd08df1..e81d61e0f 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -48,7 +48,7 @@ import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.Capabilities; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.SurfaceChangeable; +import javax.media.nativewindow.MutableSurface; import javax.media.nativewindow.util.Point; import com.jogamp.nativewindow.MutableGraphicsConfiguration; @@ -62,7 +62,7 @@ import jogamp.nativewindow.jawt.JAWT_DrawingSurfaceInfo; import jogamp.nativewindow.jawt.macosx.JAWT_MacOSXDrawingSurfaceInfo; import jogamp.nativewindow.macosx.OSXUtil; -public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable { +public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { public MacOSXJAWTWindow(Object comp, AbstractGraphicsConfiguration config) { super(comp, config); if(DEBUG) { @@ -103,24 +103,9 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable { if(DEBUG) { System.err.println("MacOSXJAWTWindow.setSurfaceHandle(): 0x"+Long.toHexString(surfaceHandle)); } - sscSet &= 0 != surfaceHandle; // reset ssc flag if NULL surfaceHandle, ie. back to JAWT this.surfaceHandle = surfaceHandle; } - public void surfaceSizeChanged(int width, int height) { - sscSet = true; - sscWidth = width; - sscHeight = height; - } - - public int getWidth() { - return sscSet ? sscWidth : super.getWidth(); - } - - public int getHeight() { - return sscSet ? sscHeight: super.getHeight(); - } - protected JAWT fetchJAWTImpl() throws NativeWindowException { // use offscreen if supported and [ applet or requested ] return JAWTUtil.getJAWT(getShallUseOffscreenLayer() || isApplet()); @@ -280,8 +265,6 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable { private long rootSurfaceLayerHandle = 0; // attached to the JAWT_SurfaceLayer private long surfaceHandle = 0; - private int sscWidth, sscHeight; - private boolean sscSet = false; // Workaround for instance of 4796548 private boolean firstLock = true; diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 4d472b01a..99fc9244e 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -63,19 +63,15 @@ public class OSXUtil { return (Point) GetLocationOnScreen0(windowOrView, src_x, src_y); } - public static long CreateNSView(int x, int y, int width, int height) { - return CreateNSView0(x, y, width, height); - } - public static void DestroyNSView(long nsView) { - DestroyNSView0(nsView); - } - public static long CreateNSWindow(int x, int y, int width, int height) { return CreateNSWindow0(x, y, width, height); } public static void DestroyNSWindow(long nsWindow) { DestroyNSWindow0(nsWindow); } + public static long GetNSView(long nsWindow) { + return GetNSView0(nsWindow); + } public static long CreateCALayer(int x, int y, int width, int height) { return CreateCALayer0(x, y, width, height); @@ -134,10 +130,9 @@ public class OSXUtil { private static native boolean initIDs0(); private static native Object GetLocationOnScreen0(long windowOrView, int src_x, int src_y); - private static native long CreateNSView0(int x, int y, int width, int height); - private static native void DestroyNSView0(long nsView); private static native long CreateNSWindow0(int x, int y, int width, int height); private static native void DestroyNSWindow0(long nsWindow); + private static native long GetNSView0(long nsWindow); private static native long CreateCALayer0(int x, int y, int width, int height); private static native void AddCASublayer0(long rootCALayer, long subCALayer); private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java index c24f64b32..e368aa6a1 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java @@ -31,6 +31,7 @@ package jogamp.nativewindow.windows; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; /** @@ -43,22 +44,49 @@ public class GDISurface extends ProxySurface { protected long windowHandle; protected long surfaceHandle; - public GDISurface(AbstractGraphicsConfiguration cfg, long windowHandle) { - super(cfg); - if(0 == windowHandle) { - throw new NativeWindowException("Error hwnd 0, werr: "+GDI.GetLastError()); - } + public GDISurface(AbstractGraphicsConfiguration cfg, long windowHandle, int initialWidth, int initialHeight, UpstreamSurfaceHook upstream) { + super(cfg, initialWidth, initialHeight, upstream); this.windowHandle=windowHandle; + this.surfaceHandle=0; } @Override - protected final void invalidateImpl() { - windowHandle=0; - surfaceHandle=0; + protected void invalidateImpl() { + if(0 != surfaceHandle) { + throw new NativeWindowException("didn't release surface Handle: "+this); + } + windowHandle = 0; + // surfaceHandle = 0; + } + + /** + * {@inheritDoc} + *

      + * Actually the window handle (HWND), since the surfaceHandle (HDC) is derived + * from it at {@link #lockSurface()}. + *

      + */ + @Override + public final void setSurfaceHandle(long surfaceHandle) { + this.windowHandle = surfaceHandle; + } + + /** + * Sets the window handle (HWND). + */ + public final void setWindowHandle(long windowHandle) { + this.windowHandle = windowHandle; + } + + public final long getWindowHandle() { + return windowHandle; } @Override final protected int lockSurfaceImpl() { + if (0 == windowHandle) { + throw new NativeWindowException("null window handle: "+this); + } if (0 != surfaceHandle) { throw new InternalError("surface not released"); } @@ -89,12 +117,15 @@ public class GDISurface extends ProxySurface { @Override final public String toString() { - return "GDISurface[config "+getPrivateGraphicsConfiguration()+ + final UpstreamSurfaceHook ush = getUpstreamSurfaceHook(); + final String ush_s = null != ush ? ( ush.getClass().getName() + ": " + ush ) : "nil"; + return getClass().getSimpleName()+"[config "+getPrivateGraphicsConfiguration()+ ", displayHandle 0x"+Long.toHexString(getDisplayHandle())+ ", windowHandle 0x"+Long.toHexString(windowHandle)+ ", surfaceHandle 0x"+Long.toHexString(getSurfaceHandle())+ ", size "+getWidth()+"x"+getHeight()+ - ", surfaceLock "+surfaceLock+"]"; + ", surfaceLock "+surfaceLock+ + ", upstreamSurfaceHook "+ush_s+"]"; } } diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index e010fc440..ebfefe345 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -148,37 +148,6 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetLocationOnS return res; } -/* - * Class: Java_jogamp_nativewindow_macosx_OSXUtil - * Method: CreateNSView0 - * Signature: (IIIIZ)J - */ -JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateNSView0 - (JNIEnv *env, jclass unused, jint x, jint y, jint width, jint height) -{ - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - NSRect rect = NSMakeRect(x, y, width, height); - NSView * view = [[NSView alloc] initWithFrame: rect] ; - [view setCanDrawConcurrently: YES]; - [pool release]; - - return (jlong) (intptr_t) view; -} - -/* - * Class: Java_jogamp_nativewindow_macosx_OSXUtil - * Method: DestroyNSView0 - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyNSView0 - (JNIEnv *env, jclass unused, jlong nsView) -{ - NSView* view = (NSView*) (intptr_t) nsView; - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - [view release]; - [pool release]; -} - /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: CreateNSWindow0 @@ -222,6 +191,27 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyNSWindow0 [pool release]; } +/* + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: GetNSView0 + * Signature: (J)J + */ +JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSView0 + (JNIEnv *env, jclass unused, jlong window) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSWindow* win = (NSWindow*) ((intptr_t) window); + + DBG_PRINT( "contentView0 - window: %p (START)\n", win); + + jlong res = (jlong) ((intptr_t) [win contentView]); + + DBG_PRINT( "contentView0 - window: %p (END)\n", win); + + [pool release]; + return res; +} + /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: CreateCALayer0 diff --git a/src/newt/classes/com/jogamp/newt/Window.java b/src/newt/classes/com/jogamp/newt/Window.java index 71e86d520..e8537fec5 100644 --- a/src/newt/classes/com/jogamp/newt/Window.java +++ b/src/newt/classes/com/jogamp/newt/Window.java @@ -40,8 +40,20 @@ import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.WindowClosingProtocol; /** - * Specifying the public Window functionality for the - * using a Window and for shadowing one like {@link com.jogamp.newt.opengl.GLWindow}. + * Specifying NEWT's Window functionality: + *
        + *
      • On- and offscreen windows
      • + *
      • Keyboard and multi-pointer input
      • + *
      • Native reparenting
      • + *
      • Toggable fullscreen and decoration mode
      • + *
      • Transparency
      • + *
      • ... and more
      • + *
      + *

      + * One use case is {@link com.jogamp.newt.opengl.GLWindow}, which delegates + * window operation to an instance of this interface while providing OpenGL + * functionality. + *

      */ public interface Window extends NativeWindow, WindowClosingProtocol { public static final boolean DEBUG_MOUSE_EVENT = Debug.debug("Window.MouseEvent"); diff --git a/src/newt/classes/com/jogamp/newt/event/KeyEvent.java b/src/newt/classes/com/jogamp/newt/event/KeyEvent.java index 44fcea49c..4db661eeb 100644 --- a/src/newt/classes/com/jogamp/newt/event/KeyEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/KeyEvent.java @@ -43,7 +43,7 @@ public class KeyEvent extends InputEvent this.keyChar=keyChar; } - /** Only valid if delivered via {@link KeyListener#keyPressed(KeyEvent)} */ + /** Only valid on all platforms at {@link KeyListener#keyTyped(KeyEvent)} */ public char getKeyChar() { return keyChar; } diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index f08fbc8fa..c50ab77c4 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -124,6 +124,11 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind this.window.setLifecycleHook(new GLLifecycleHook()); } + @Override + public final Object getUpstreamWidget() { + return window; + } + /** * Creates a new GLWindow attaching a new Window referencing a * new default Screen and default Display with the given GLCapabilities. @@ -762,7 +767,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind System.err.println(GlueGenVersion.getInstance()); System.err.println(JoglVersion.getInstance()); - System.err.println(JoglVersion.getDefaultOpenGLInfo(null, true).toString()); + System.err.println(JoglVersion.getDefaultOpenGLInfo(null, null, true).toString()); final GLProfile glp = GLProfile.getDefault(); final GLCapabilitiesImmutable caps = new GLCapabilities( glp ); diff --git a/src/newt/classes/jogamp/newt/OffscreenWindow.java b/src/newt/classes/jogamp/newt/OffscreenWindow.java index 050e24b6c..be543aba9 100644 --- a/src/newt/classes/jogamp/newt/OffscreenWindow.java +++ b/src/newt/classes/jogamp/newt/OffscreenWindow.java @@ -34,15 +34,24 @@ package jogamp.newt; -import javax.media.nativewindow.*; +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.GraphicsConfigurationFactory; +import javax.media.nativewindow.MutableSurface; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.ProxySurface; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.Point; -public class OffscreenWindow extends WindowImpl implements SurfaceChangeable { +public class OffscreenWindow extends WindowImpl implements MutableSurface { long surfaceHandle = 0; - + ProxySurface.UpstreamSurfaceHook upstreamHook; + ProxySurface dummySurface; + public OffscreenWindow() { + upstreamHook = null; + dummySurface = null; } static long nextWindowHandle = 0x100; // start here - a marker @@ -52,6 +61,17 @@ public class OffscreenWindow extends WindowImpl implements SurfaceChangeable { throw new NativeWindowException("Capabilities is onscreen"); } final AbstractGraphicsScreen aScreen = getScreen().getGraphicsScreen(); + /** Cannot use OpenGL here .. + if(capsRequested instanceof GLCapabilitiesImmutable) { + final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) capsRequested; + if(caps.isFBO() && GLContext.isFBOAvailable(aScreen.getDevice(), caps.getGLProfile()) ) { + final GLDrawableFactoryImpl factory = (GLDrawableFactoryImpl) GLDrawableFactory.getFactory(caps.getGLProfile()); + final GLCapabilitiesImmutable dummyCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(caps); + final ProxySurface dummySurface = factory.createDummySurfaceImpl(aScreen.getDevice(), false, dummyCaps, null, 64, 64); + upstreamHook = dummySurface.getUpstreamSurfaceHook(); + dummySurface.createNotify(); + } + } */ final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(aScreen.getDevice()).chooseGraphicsConfiguration( capsRequested, capsRequested, capabilitiesChooser, aScreen); if (null == cfg) { @@ -68,13 +88,14 @@ public class OffscreenWindow extends WindowImpl implements SurfaceChangeable { // nop } - public void surfaceSizeChanged(int width, int height) { - sizeChanged(false, width, height, false); - } - @Override public synchronized void destroy() { super.destroy(); + if(null != dummySurface) { + dummySurface.destroyNotify(); + dummySurface = null; + upstreamHook = null; + } surfaceHandle = 0; } @@ -84,8 +105,12 @@ public class OffscreenWindow extends WindowImpl implements SurfaceChangeable { @Override public long getSurfaceHandle() { + if(null != dummySurface) { + return dummySurface.getSurfaceHandle(); + // return upstreamHook.getWidth(); + } return surfaceHandle; - } + } protected void requestFocusImpl(boolean reparented) { } diff --git a/src/newt/classes/jogamp/newt/driver/android/MD.java b/src/newt/classes/jogamp/newt/driver/android/MD.java index 403eae383..f2f30937b 100644 --- a/src/newt/classes/jogamp/newt/driver/android/MD.java +++ b/src/newt/classes/jogamp/newt/driver/android/MD.java @@ -43,7 +43,7 @@ public class MD { .append(JoglVersion.getInstance()).append(Platform.NEWLINE) .append(Platform.NEWLINE); - JoglVersion.getDefaultOpenGLInfo(sb, true); + JoglVersion.getDefaultOpenGLInfo(null, sb, true); return sb.toString(); } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java index 942994c13..fcca5c843 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java @@ -38,7 +38,7 @@ import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.SurfaceChangeable; +import javax.media.nativewindow.MutableSurface; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.InsetsImmutable; import javax.media.nativewindow.util.Point; @@ -50,7 +50,7 @@ import jogamp.newt.driver.DriverUpdatePosition; import com.jogamp.newt.event.KeyEvent; -public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverClearFocus, DriverUpdatePosition { +public class MacWindow extends WindowImpl implements MutableSurface, DriverClearFocus, DriverUpdatePosition { static { MacDisplay.initSingleton(); @@ -131,10 +131,6 @@ public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverCl } } - public void surfaceSizeChanged(int width, int height) { - sizeChanged(false, width, height, false); - } - @Override protected void setTitleImpl(final String title) { setTitle0(getWindowHandle(), title); diff --git a/src/newt/native/NewtMacWindow.m b/src/newt/native/NewtMacWindow.m index f914467af..b58b99e38 100644 --- a/src/newt/native/NewtMacWindow.m +++ b/src/newt/native/NewtMacWindow.m @@ -972,7 +972,7 @@ static jint mods2JavaMods(NSUInteger mods) NSView* nsview = [self contentView]; if( ! [nsview isMemberOfClass:[NewtView class]] ) { - return; + return NO; } NewtView* view = (NewtView *) nsview; @@ -981,14 +981,14 @@ static jint mods2JavaMods(NSUInteger mods) DBG_PRINT( "*************** windowWillClose.0: %p\n", (void *)(intptr_t)javaWindowObject); if (javaWindowObject == NULL) { DBG_PRINT("windowWillClose: null javaWindowObject\n"); - return; + return NO; } int shallBeDetached = 0; JavaVM *jvmHandle = [view getJVMHandle]; JNIEnv* env = NewtCommon_GetJNIEnv(jvmHandle, [view getJVMVersion], &shallBeDetached); if(NULL==env) { DBG_PRINT("windowWillClose: null JNIEnv\n"); - return; + return NO; } [view setDestroyNotifySent: true]; // earmark assumption of being closed diff --git a/src/test/com/jogamp/opengl/test/junit/graph/TestTextRendererNEWT00.java b/src/test/com/jogamp/opengl/test/junit/graph/TestTextRendererNEWT00.java index a09cc76ac..b22be0a93 100644 --- a/src/test/com/jogamp/opengl/test/junit/graph/TestTextRendererNEWT00.java +++ b/src/test/com/jogamp/opengl/test/junit/graph/TestTextRendererNEWT00.java @@ -194,7 +194,7 @@ public class TestTextRendererNEWT00 extends UITestCase { pw.printf("%s-%03dx%03d-T%04d", objName, drawable.getWidth(), drawable.getHeight(), texSize[0]); final String filename = dir + sw +".png"; - if(screenshot.readPixels(drawable.getGL(), drawable, false)) { + if(screenshot.readPixels(drawable.getGL(), false)) { screenshot.write(new File(filename)); } } diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURendererListenerBase01.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURendererListenerBase01.java index a3182a30f..6378c1ee3 100644 --- a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURendererListenerBase01.java +++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURendererListenerBase01.java @@ -194,7 +194,7 @@ public abstract class GPURendererListenerBase01 implements GLEventListener { pw.printf("-%03dx%03d-Z%04d-T%04d-%s", drawable.getWidth(), drawable.getHeight(), (int)Math.abs(zoom), texSize[0], objName); final String filename = dir + tech + sw +".png"; - if(screenshot.readPixels(drawable.getGL(), drawable, false)) { + if(screenshot.readPixels(drawable.getGL(), false)) { screenshot.write(new File(filename)); } } diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIListenerBase01.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIListenerBase01.java index d0093ad0c..15daf70cd 100644 --- a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIListenerBase01.java +++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIListenerBase01.java @@ -180,7 +180,7 @@ public abstract class UIListenerBase01 implements GLEventListener { pw.printf("-%03dx%03d-Z%04d-T%04d-%s", drawable.getWidth(), drawable.getHeight(), (int)Math.abs(zoom), 0, objName); final String filename = dir + tech + sw +".png"; - if(screenshot.readPixels(drawable.getGL(), drawable, false)) { + if(screenshot.readPixels(drawable.getGL(), false)) { screenshot.write(new File(filename)); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java new file mode 100644 index 000000000..1a33845b3 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java @@ -0,0 +1,272 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.io.IOException; + +import javax.media.opengl.GL; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLProfile; + +import jogamp.opengl.GLFBODrawableImpl; + +import org.junit.Assert; +import org.junit.Test; + +import com.jogamp.opengl.FBObject; +import com.jogamp.opengl.OffscreenAutoDrawable; +import com.jogamp.opengl.test.junit.jogl.demos.es2.FBOMix2DemosES2; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.jogl.demos.es2.MultisampleDemoES2; +import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.util.GLReadBufferUtil; +import com.jogamp.opengl.util.texture.TextureIO; + +public class TestFBODrawableNEWT extends UITestCase { + + static final int widthStep = 800/4; + static final int heightStep = 600/4; + volatile int szStep = 2; + + @Test + public void testGL2ES2_Demo1Normal() throws InterruptedException { + final GLProfile glp = GLProfile.getGL2ES2(); + final GLCapabilities caps = new GLCapabilities(glp); + testGLFBODrawableImpl(caps, new GearsES2(0)); + } + + @Test + public void testGL2ES2_Demo1MSAA4() throws InterruptedException { + final GLProfile glp = GLProfile.getGL2ES2(); + final GLCapabilities caps = new GLCapabilities(glp); + caps.setSampleBuffers(true); + caps.setNumSamples(4); + testGLFBODrawableImpl(caps, new GearsES2(0)); + } + + @Test + public void testGL2ES2_Demo2Normal() throws InterruptedException { + final GLProfile glp = GLProfile.getGL2ES2(); + final GLCapabilities caps = new GLCapabilities(glp); + testGLFBODrawableImpl(caps, new MultisampleDemoES2(false)); + } + + @Test + public void testGL2ES2_Demo2MSAA4() throws InterruptedException { + final GLProfile glp = GLProfile.getGL2ES2(); + final GLCapabilities caps = new GLCapabilities(glp); + caps.setSampleBuffers(true); + caps.setNumSamples(4); + testGLFBODrawableImpl(caps, new MultisampleDemoES2(true)); + } + + @Test + public void testGL2ES2_FBODemoNormal() throws InterruptedException { + final GLProfile glp = GLProfile.getGL2ES2(); + final FBOMix2DemosES2 demo = new FBOMix2DemosES2(0); + demo.setDoRotation(false); + final GLCapabilities caps = new GLCapabilities(glp); + testGLFBODrawableImpl(caps, demo); + } + + @Test + public void testGL2ES2_FBODemoMSAA4() throws InterruptedException { + final GLProfile glp = GLProfile.getGL2ES2(); + final FBOMix2DemosES2 demo = new FBOMix2DemosES2(0); + demo.setDoRotation(false); + final GLCapabilities caps = new GLCapabilities(glp); + caps.setSampleBuffers(true); + caps.setNumSamples(4); + testGLFBODrawableImpl(caps, demo); + } + + @Test + public void testEGLES2_Demo0Normal() throws InterruptedException { + if( GLProfile.isAvailable(GLProfile.GLES2) ) { + final GLProfile glp = GLProfile.get(GLProfile.GLES2); + final GLCapabilities caps = new GLCapabilities(glp); + testGLFBODrawableImpl(caps, new GearsES2(0)); + } else { + System.err.println("EGL ES2 n/a"); + } + } + + @Test + public void testEGLES2_Demo0MSAA4() throws InterruptedException { + if( GLProfile.isAvailable(GLProfile.GLES2) ) { + final GLProfile glp = GLProfile.get(GLProfile.GLES2); + final GLCapabilities caps = new GLCapabilities(glp); + caps.setSampleBuffers(true); + caps.setNumSamples(4); + testGLFBODrawableImpl(caps, new GearsES2(0)); + } else { + System.err.println("EGL ES2 n/a"); + } + } + + boolean skipShot = false; + + void testGLFBODrawableImpl(GLCapabilities caps, GLEventListener demo) throws InterruptedException { + final GLReadBufferUtil screenshot = new GLReadBufferUtil(false, false); + caps.setFBO(true); + final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); + final GLDrawable fboDrawable = factory.createOffscreenDrawable(null, caps, null, widthStep*szStep, heightStep*szStep); + Assert.assertNotNull(fboDrawable); + Assert.assertTrue("Not an FBO Drawable", fboDrawable instanceof GLFBODrawableImpl); + + fboDrawable.setRealized(true); + Assert.assertTrue(fboDrawable.isRealized()); + + final FBObject fbo = ((GLFBODrawableImpl)fboDrawable).getFBObject(); + + System.out.println("Realized: "+fboDrawable); + System.out.println("Realized: "+fboDrawable.getChosenGLCapabilities()); + System.out.println("Realized: "+fbo); + + final GLContext context = fboDrawable.createContext(null); + Assert.assertNotNull(context); + + int res = context.makeCurrent(); + Assert.assertTrue(GLContext.CONTEXT_CURRENT_NEW==res || GLContext.CONTEXT_CURRENT==res); + context.release(); + + System.out.println("Post Create-Ctx: "+fbo); + final FBObject.Colorbuffer colorA = fbo.getColorbuffer(0); + Assert.assertNotNull(colorA); + final FBObject.RenderAttachment depthA = fbo.getDepthAttachment(); + Assert.assertNotNull(depthA); + + final OffscreenAutoDrawable glad = new OffscreenAutoDrawable(fboDrawable, context, null); + + glad.addGLEventListener(demo); + glad.addGLEventListener(new GLEventListener() { + volatile int displayCount=0; + volatile int reshapeCount=0; + public void init(GLAutoDrawable drawable) {} + public void dispose(GLAutoDrawable drawable) {} + public void display(GLAutoDrawable drawable) { + final GL gl = drawable.getGL(); + // System.err.println(Thread.currentThread().getName()+": ** display: "+displayCount+": step "+szStep+" "+drawable.getWidth()+"x"+drawable.getHeight()); + // System.err.println(Thread.currentThread().getName()+": ** FBO-THIS: "+fbo); + // System.err.println(Thread.currentThread().getName()+": ** FBO-SINK: "+fbo.getSamplingSinkFBO()); + // System.err.println(Thread.currentThread().getName()+": ** drawable-read: "+gl.getDefaultReadFramebuffer()); + if(skipShot) { + skipShot=false; + } else { + snapshot(getSimpleTestName("."), displayCount, "msaa"+fbo.getNumSamples(), gl, screenshot, TextureIO.PNG, null); + } + Assert.assertEquals(drawable.getWidth(), widthStep*szStep); + Assert.assertEquals(drawable.getHeight(), heightStep*szStep); + displayCount++; + } + public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { + System.err.println(Thread.currentThread().getName()+": ** reshape: "+reshapeCount+": step "+szStep+" "+width+"x"+height+" - "+drawable.getWidth()+"x"+drawable.getHeight()); + Assert.assertEquals(drawable.getWidth(), widthStep*szStep); + Assert.assertEquals(drawable.getHeight(), heightStep*szStep); + reshapeCount++; + } + }); + + // 0 - szStep = 2 + glad.display(); + + // 1, 2 (resize + display) + szStep = 1; + skipShot=true; + glad.setSize(widthStep*szStep, heightStep*szStep); + glad.display(); + Assert.assertEquals(glad.getWidth(), widthStep*szStep); + Assert.assertEquals(glad.getHeight(), heightStep*szStep); + { + // Check whether the attachment reference are still valid! + FBObject.Colorbuffer _colorA = fbo.getColorbuffer(0); + Assert.assertNotNull(_colorA); + Assert.assertTrue(colorA == _colorA); + Assert.assertTrue(colorA.equals(_colorA)); + FBObject.RenderAttachment _depthA = fbo.getDepthAttachment(); + Assert.assertNotNull(_depthA); + Assert.assertTrue(depthA == _depthA); + Assert.assertTrue(depthA.equals(_depthA)); + + _colorA = fbo.getColorbuffer(colorA); + Assert.assertNotNull(_colorA); + Assert.assertTrue(colorA == _colorA); + Assert.assertTrue(colorA.equals(_colorA)); + } + + // 3, 4 (resize + display) + szStep = 4; + skipShot=true; + glad.setSize(widthStep*szStep, heightStep*szStep); + glad.display(); + Assert.assertEquals(glad.getWidth(), widthStep*szStep); + Assert.assertEquals(glad.getHeight(), heightStep*szStep); + { + // Check whether the attachment reference are still valid! + FBObject.Colorbuffer _colorA = fbo.getColorbuffer(0); + Assert.assertNotNull(_colorA); + Assert.assertTrue(colorA == _colorA); + final FBObject.RenderAttachment _depthA = fbo.getDepthAttachment(); + Assert.assertNotNull(_depthA); + Assert.assertTrue(depthA == _depthA); + + _colorA = fbo.getColorbuffer(colorA); + Assert.assertNotNull(_colorA); + Assert.assertTrue(colorA == _colorA); + } + + // 5 + glad.display(); + Assert.assertEquals(glad.getWidth(), widthStep*szStep); + Assert.assertEquals(glad.getHeight(), heightStep*szStep); + + // 6, 7 (resize + display) + szStep = 3; + skipShot=true; + glad.setSize(widthStep*szStep, heightStep*szStep); + glad.display(); + Assert.assertEquals(glad.getWidth(), widthStep*szStep); + Assert.assertEquals(glad.getHeight(), heightStep*szStep); + + glad.destroy(); + System.out.println("Fin: "+fboDrawable); + + // final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(fboDrawable, context); + } + + public static void main(String args[]) throws IOException { + org.junit.runner.JUnitCore.main(TestFBODrawableNEWT.class.getName()); + } + +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMRTNEWT01.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMRTNEWT01.java new file mode 100644 index 000000000..f7c83a03b --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMRTNEWT01.java @@ -0,0 +1,266 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.test.junit.jogl.acore; + +import com.jogamp.opengl.FBObject; +import com.jogamp.opengl.FBObject.TextureAttachment; +import com.jogamp.opengl.util.GLArrayDataServer; +import com.jogamp.opengl.util.GLReadBufferUtil; +import com.jogamp.opengl.util.PMVMatrix; +import com.jogamp.opengl.util.glsl.ShaderCode; +import com.jogamp.opengl.util.glsl.ShaderProgram; +import com.jogamp.opengl.util.glsl.ShaderState; +import com.jogamp.opengl.util.texture.TextureIO; +import com.jogamp.opengl.FBObject.Attachment.Type; +import com.jogamp.opengl.test.junit.jogl.demos.es2.RedSquareES2; +import com.jogamp.opengl.test.junit.util.MiscUtils; +import com.jogamp.opengl.test.junit.util.NEWTGLContext; +import com.jogamp.opengl.test.junit.util.UITestCase; + +import java.io.IOException; + +import javax.media.nativewindow.NativeSurface; +import javax.media.opengl.GL; +import javax.media.opengl.GL2ES2; +import javax.media.opengl.GL2GL3; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLPipelineFactory; +import javax.media.opengl.GLProfile; +import javax.media.opengl.GLUniformData; + +import org.junit.Assert; +import org.junit.Test; + +public class TestFBOMRTNEWT01 extends UITestCase { + static long durationPerTest = 10*40*2; // ms + + @Test + public void test01() throws InterruptedException { + final int step = 4; + final int width = 800; + final int height = 600; + // preset .. + if(!GLProfile.isAvailable(GLProfile.GL2GL3)) { + System.err.println("Test requires GL2/GL3 profile."); + return; + } + final NEWTGLContext.WindowContext winctx = NEWTGLContext.createOnscreenWindow( + new GLCapabilities(GLProfile.getGL2GL3()), width/step, height/step, true); + final GLDrawable drawable = winctx.context.getGLDrawable(); + GL2GL3 gl = winctx.context.getGL().getGL2GL3(); + gl = gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Debug", null, gl, null) ).getGL2GL3(); + System.err.println(winctx.context); + + Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); + // test code .. + final ShaderState st = new ShaderState(); + // st.setVerbose(true); + + final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RedSquareES2.class, "shader", + "shader/bin", "fbo-mrt-1", false); + final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader", + "shader/bin", "fbo-mrt-1", false); + final ShaderProgram sp0 = new ShaderProgram(); + sp0.add(gl, vp0, System.err); + sp0.add(gl, fp0, System.err); + Assert.assertTrue(0<=sp0.program()); + Assert.assertTrue(!sp0.inUse()); + Assert.assertTrue(!sp0.linked()); + Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); + st.attachShaderProgram(gl, sp0, false); + + final ShaderCode vp1 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RedSquareES2.class, "shader", + "shader/bin", "fbo-mrt-2", false); + final ShaderCode fp1 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader", + "shader/bin", "fbo-mrt-2", false); + final ShaderProgram sp1 = new ShaderProgram(); + sp1.add(gl, vp1, System.err); + sp1.add(gl, fp1, System.err); + Assert.assertTrue(0<=sp1.program()); + Assert.assertTrue(!sp1.inUse()); + Assert.assertTrue(!sp1.linked()); + Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); + st.attachShaderProgram(gl, sp1, true); + + final PMVMatrix pmvMatrix = new PMVMatrix(); + final GLUniformData pmvMatrixUniform = new GLUniformData("gcu_PMVMatrix", 4, 4, pmvMatrix.glGetPMvMatrixf()); + Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); + st.ownUniform(pmvMatrixUniform); + st.uniform(gl, pmvMatrixUniform); + Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); + + final GLArrayDataServer vertices0 = GLArrayDataServer.createGLSL("gca_Vertices", 3, GL.GL_FLOAT, false, 4, GL.GL_STATIC_DRAW); + // st.bindAttribLocation(gl, 0, vertices0); + vertices0.putf(0); vertices0.putf(1); vertices0.putf(0); + vertices0.putf(1); vertices0.putf(1); vertices0.putf(0); + vertices0.putf(0); vertices0.putf(0); vertices0.putf(0); + vertices0.putf(1); vertices0.putf(0); vertices0.putf(0); + vertices0.seal(gl, true); + st.ownAttribute(vertices0, true); + vertices0.enableBuffer(gl, false); + Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); + + final GLArrayDataServer colors0 = GLArrayDataServer.createGLSL("gca_Colors", 4, GL.GL_FLOAT, false, 4, GL.GL_STATIC_DRAW); + // st.bindAttribLocation(gl, 1, colors0); + colors0.putf(1); colors0.putf(0); colors0.putf(1); colors0.putf(1); + colors0.putf(0); colors0.putf(0); colors0.putf(1); colors0.putf(1); + colors0.putf(0); colors0.putf(0); colors0.putf(0); colors0.putf(1); + colors0.putf(0); colors0.putf(1); colors0.putf(1); colors0.putf(1); + colors0.seal(gl, true); + st.ownAttribute(colors0, true); + colors0.enableBuffer(gl, false); + Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); + + final GLUniformData texUnit0 = new GLUniformData("gcs_TexUnit0", 0); + st.ownUniform(texUnit0); + st.uniform(gl, texUnit0); + final GLUniformData texUnit1 = new GLUniformData("gcs_TexUnit1", 1); + st.ownUniform(texUnit1); + st.uniform(gl, texUnit1); + + final GLArrayDataServer texCoords0 = GLArrayDataServer.createGLSL("gca_TexCoords", 2, GL.GL_FLOAT, false, 4, GL.GL_STATIC_DRAW); + // st.bindAttribLocation(gl, 2, texCoords0); + texCoords0.putf(0f); texCoords0.putf(1f); + texCoords0.putf(1f); texCoords0.putf(1f); + texCoords0.putf(0f); texCoords0.putf(0f); + texCoords0.putf(1f); texCoords0.putf(0f); + texCoords0.seal(gl, true); + st.ownAttribute(texCoords0, true); + texCoords0.enableBuffer(gl, false); + Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); + + final int texA0Point = 0; // attachment point for texA0 + final int texA1Point = 1; // attachment point for texA1 + + // FBO w/ 2 texture2D color buffers + final FBObject fbo_mrt = new FBObject(); + fbo_mrt.reset(gl, drawable.getWidth(), drawable.getHeight()); + final TextureAttachment texA0 = fbo_mrt.attachTexture2D(gl, texA0Point, true, GL.GL_NEAREST, GL.GL_NEAREST, GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE); + final TextureAttachment texA1 = fbo_mrt.attachTexture2D(gl, texA1Point, true, GL.GL_NEAREST, GL.GL_NEAREST, GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE); + fbo_mrt.attachRenderbuffer(gl, Type.DEPTH, 24); + Assert.assertTrue( fbo_mrt.isStatusValid() ) ; + fbo_mrt.unbind(gl); + + // misc GL setup + gl.glClearColor(1, 1, 1, 1); + gl.glEnable(GL2ES2.GL_DEPTH_TEST); + Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); + + // reshape + pmvMatrix.glMatrixMode(PMVMatrix.GL_PROJECTION); + pmvMatrix.glLoadIdentity(); + pmvMatrix.glOrthof(0f, 1f, 0f, 1f, -10f, 10f); + pmvMatrix.glMatrixMode(PMVMatrix.GL_MODELVIEW); + pmvMatrix.glLoadIdentity(); + st.uniform(gl, pmvMatrixUniform); + Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); + + final int[] two_buffers = new int[] { GL.GL_COLOR_ATTACHMENT0+texA0Point, GL.GL_COLOR_ATTACHMENT0+texA1Point }; + final int[] bck_buffers = new int[] { GL2GL3.GL_BACK_LEFT }; + + final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false); + int step_i = 0; + int[] last_snap_size = new int[] { 0, 0 }; + + for(int i=0; i buffer0, Green -> buffer1 + st.attachShaderProgram(gl, sp0, true); + vertices0.enableBuffer(gl, true); + colors0.enableBuffer(gl, true); + + fbo_mrt.bind(gl); + gl.glDrawBuffers(2, two_buffers, 0); + gl.glViewport(0, 0, fbo_mrt.getWidth(), fbo_mrt.getHeight()); + + gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + gl.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4); + fbo_mrt.unbind(gl); + vertices0.enableBuffer(gl, false); + colors0.enableBuffer(gl, false); + + // pass 2 - mix buffer0, buffer1 and blue + // rg = buffer0.rg + buffer1.rg, b = Blue - length(rg); + st.attachShaderProgram(gl, sp1, true); + vertices0.enableBuffer(gl, true); + colors0.enableBuffer(gl, true); + texCoords0.enableBuffer(gl, true); + gl.glDrawBuffers(1, bck_buffers, 0); + + gl.glViewport(0, 0, drawable.getWidth(), drawable.getHeight()); + + gl.glActiveTexture(GL.GL_TEXTURE0 + texUnit0.intValue()); + fbo_mrt.use(gl, texA0); + gl.glActiveTexture(GL.GL_TEXTURE0 + texUnit1.intValue()); + fbo_mrt.use(gl, texA1); + gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + gl.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4); + fbo_mrt.unuse(gl); + vertices0.enableBuffer(gl, false); + colors0.enableBuffer(gl, false); + texCoords0.enableBuffer(gl, false); + + { + final NativeSurface ns = gl.getContext().getGLReadDrawable().getNativeSurface(); + if(last_snap_size[0] != ns.getWidth() && last_snap_size[1] != ns.getHeight()) { + gl.glFinish(); // sync .. no swap buffers yet! + snapshot(getSimpleTestName("."), step_i, null, gl, screenshot, TextureIO.PNG, null); // overwrite ok + last_snap_size[0] = ns.getWidth(); + last_snap_size[1] = ns.getHeight(); + } + } + + drawable.swapBuffers(); + Thread.sleep(50); + int j = (int) ( (long)i / (durationPerTest/(long)step) ) + 1; + if(j>step_i) { + int w = width/step * j; + int h = height/step * j; + System.err.println("resize: "+step_i+" -> "+j+" - "+w+"x"+h); + fbo_mrt.reset(gl, w, h); + winctx.window.setSize(w, h); + step_i = j; + } + } + + NEWTGLContext.destroyWindow(winctx); + } + + public static void main(String args[]) throws IOException { + System.err.println("main - start"); + for(int i=0; i "+num); + demo.setMSAA(num); + } + } + } + }); + + animator.start(); + // glWindow.setSkipContextReleaseThread(animator.getThread()); + + glWindow.setVisible(true); + + System.err.println("NW chosen: "+glWindow.getDelegatedWindow().getChosenCapabilities()); + System.err.println("GL chosen: "+glWindow.getChosenCapabilities()); + System.err.println("window pos/siz: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", "+glWindow.getInsets()); + + animator.setUpdateFPSFrames(60, showFPS ? System.err : null); + + while(!quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration()= 0; i--) { - immModeSink.glVertex3f((float) (radius * Math.cos(i * increment)), - (float) (radius * Math.sin(i * increment)), - 0f); - immModeSink.glVertex3f((float) (-1.0 * radius * Math.cos(i * increment)), - (float) (-1.0 * radius * Math.sin(i * increment)), - 0f); - } - immModeSink.glEnd(gl, false); - } - - public void dispose(GLAutoDrawable drawable) { - immModeSink.destroy(drawable.getGL()); - immModeSink = null; - } - - public void display(GLAutoDrawable drawable) { - GL2ES1 gl = drawable.getGL().getGL2ES1(); - if (multisample) { - gl.glEnable(GL.GL_MULTISAMPLE); - } - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - immModeSink.draw(gl, true); - if (multisample) { - gl.glDisable(GL.GL_MULTISAMPLE); - } - } - - // Unused routines - public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { - } - - public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { - } -} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1AWT.java index 4b0caf898..478bd4543 100755 --- a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1AWT.java @@ -40,7 +40,6 @@ package com.jogamp.opengl.test.junit.jogl.caps; -import java.io.File; import java.lang.reflect.InvocationTargetException; import java.awt.BorderLayout; import java.awt.Frame; @@ -48,14 +47,15 @@ import java.awt.Frame; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; -import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; +import com.jogamp.opengl.test.junit.jogl.demos.es1.MultisampleDemoES1; import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; import com.jogamp.opengl.util.GLReadBufferUtil; +import com.jogamp.opengl.util.texture.TextureIO; import org.junit.Test; @@ -75,13 +75,6 @@ public class TestMultisampleES1AWT extends UITestCase { org.junit.runner.JUnitCore.main(tstname); } - protected void snapshot(GLAutoDrawable drawable, boolean alpha, boolean flip, String filename) { - GLReadBufferUtil screenshot = new GLReadBufferUtil(alpha, false); - if(screenshot.readPixels(drawable.getGL(), drawable, flip)) { - screenshot.write(new File(filename)); - } - } - @Test public void testOnscreenMultiSampleAA0() throws InterruptedException, InvocationTargetException { testMultiSampleAAImpl(0); @@ -98,6 +91,7 @@ public class TestMultisampleES1AWT extends UITestCase { } private void testMultiSampleAAImpl(int reqSamples) throws InterruptedException, InvocationTargetException { + final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false); GLProfile glp = GLProfile.getMaxFixedFunc(true); GLCapabilities caps = new GLCapabilities(glp); GLCapabilitiesChooser chooser = new MultisampleChooser01(); @@ -110,14 +104,11 @@ public class TestMultisampleES1AWT extends UITestCase { canvas = new GLCanvas(caps, chooser, null, null); canvas.addGLEventListener(new MultisampleDemoES1(reqSamples>0?true:false)); canvas.addGLEventListener(new GLEventListener() { + int displayCount = 0; public void init(GLAutoDrawable drawable) {} public void dispose(GLAutoDrawable drawable) {} public void display(GLAutoDrawable drawable) { - final GLCapabilitiesImmutable caps = drawable.getChosenGLCapabilities(); - final String pfmt = caps.getAlphaBits() > 0 ? "rgba" : "rgb_"; - final String aaext = caps.getSampleExtension(); - final int samples = caps.getSampleBuffers() ? caps.getNumSamples() : 0 ; - snapshot(drawable, false, false, getSimpleTestName(".")+"-F_rgb_-I_"+pfmt+"-S"+samples+"-"+aaext+"-"+drawable.getGLProfile().getName()+".png"); + snapshot(getSimpleTestName("."), displayCount++, null, drawable.getGL(), screenshot, TextureIO.PNG, null); } public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } }); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1NEWT.java index 2e47b6841..ed8e2bd85 100755 --- a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1NEWT.java @@ -40,21 +40,20 @@ package com.jogamp.opengl.test.junit.jogl.caps; -import java.io.File; - import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; -import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import org.junit.Test; import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.opengl.test.junit.jogl.demos.es1.MultisampleDemoES1; import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; import com.jogamp.opengl.util.GLReadBufferUtil; +import com.jogamp.opengl.util.texture.TextureIO; public class TestMultisampleES1NEWT extends UITestCase { static long durationPerTest = 60; // ms @@ -71,13 +70,6 @@ public class TestMultisampleES1NEWT extends UITestCase { org.junit.runner.JUnitCore.main(tstname); } - protected void snapshot(GLAutoDrawable drawable, boolean alpha, boolean flip, String filename) { - GLReadBufferUtil screenshot = new GLReadBufferUtil(alpha, false); - if(screenshot.readPixels(drawable.getGL(), drawable, flip)) { - screenshot.write(new File(filename)); - } - } - @Test public void testOnscreenMultiSampleAA0() throws InterruptedException { testMultiSampleAAImpl(true, 0); @@ -119,6 +111,7 @@ public class TestMultisampleES1NEWT extends UITestCase { } private void testMultiSampleAAImpl(boolean onscreen, int reqSamples) throws InterruptedException { + final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false); GLProfile glp = GLProfile.getMaxFixedFunc(true); GLCapabilities caps = new GLCapabilities(glp); GLCapabilitiesChooser chooser = new MultisampleChooser01(); @@ -136,14 +129,11 @@ public class TestMultisampleES1NEWT extends UITestCase { window.setCapabilitiesChooser(chooser); window.addGLEventListener(new MultisampleDemoES1(reqSamples>0?true:false)); window.addGLEventListener(new GLEventListener() { + int displayCount = 0; public void init(GLAutoDrawable drawable) {} public void dispose(GLAutoDrawable drawable) {} public void display(GLAutoDrawable drawable) { - final GLCapabilitiesImmutable caps = drawable.getChosenGLCapabilities(); - final String pfmt = caps.getAlphaBits() > 0 ? "rgba" : "rgb_"; - final String aaext = caps.getSampleExtension(); - final int samples = caps.getSampleBuffers() ? caps.getNumSamples() : 0 ; - snapshot(drawable, false, false, getSimpleTestName(".")+"-F_rgb_-I_"+pfmt+"-S"+samples+"-"+aaext+"-"+drawable.getGLProfile().getName()+".png"); + snapshot(getSimpleTestName("."), displayCount++, null, drawable.getGL(), screenshot, TextureIO.PNG, null); } public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } }); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES2NEWT.java new file mode 100644 index 000000000..b2dad1f39 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES2NEWT.java @@ -0,0 +1,143 @@ +/* + * 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 com.jogamp.opengl.test.junit.jogl.caps; + +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesChooser; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLProfile; + +import org.junit.Test; + +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.opengl.test.junit.jogl.demos.es2.MultisampleDemoES2; +import com.jogamp.opengl.test.junit.util.MiscUtils; +import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.util.GLReadBufferUtil; +import com.jogamp.opengl.util.texture.TextureIO; + +public class TestMultisampleES2NEWT extends UITestCase { + static long durationPerTest = 60; // ms + private GLWindow window; + + public static void main(String[] args) { + for(int i=0; i0) { + caps.setSampleBuffers(true); + caps.setNumSamples(reqSamples); + } + + window = GLWindow.create(caps); + window.setCapabilitiesChooser(chooser); + window.addGLEventListener(new MultisampleDemoES2(reqSamples>0?true:false)); + window.addGLEventListener(new GLEventListener() { + int displayCount = 0; + public void init(GLAutoDrawable drawable) {} + public void dispose(GLAutoDrawable drawable) {} + public void display(GLAutoDrawable drawable) { + snapshot(getSimpleTestName("."), displayCount++, null, drawable.getGL(), screenshot, TextureIO.PNG, null); + } + public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } + }); + window.setSize(512, 512); + window.setVisible(true); + window.requestFocus(); + + Thread.sleep(durationPerTest); + + window.destroy(); + } + +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/GearsES1.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/GearsES1.java index 5c82a43c6..e81d1b4af 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/GearsES1.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/GearsES1.java @@ -129,12 +129,13 @@ public class GearsES1 implements GLEventListener { gl.glEnable(GL2ES1.GL_NORMALIZE); - if (drawable.getNativeSurface() instanceof Window) { - Window window = (Window) drawable.getNativeSurface(); + final Object upstreamWidget = drawable.getUpstreamWidget(); + if (upstreamWidget instanceof Window) { + final Window window = (Window) upstreamWidget; window.addMouseListener(gearsMouse); window.addKeyListener(gearsKeys); - } else if (GLProfile.isAWTAvailable() && drawable instanceof java.awt.Component) { - java.awt.Component comp = (java.awt.Component) drawable; + } else if (GLProfile.isAWTAvailable() && upstreamWidget instanceof java.awt.Component) { + final java.awt.Component comp = (java.awt.Component) upstreamWidget; new com.jogamp.newt.event.awt.AWTMouseAdapter(gearsMouse).addTo(comp); new com.jogamp.newt.event.awt.AWTKeyAdapter(gearsKeys).addTo(comp); } @@ -165,8 +166,9 @@ public class GearsES1 implements GLEventListener { public void dispose(GLAutoDrawable drawable) { System.err.println(Thread.currentThread()+" GearsES1.dispose ... "); - if (drawable.getNativeSurface() instanceof Window) { - Window window = (Window) drawable.getNativeSurface(); + final Object upstreamWidget = drawable.getUpstreamWidget(); + if (upstreamWidget instanceof Window) { + final Window window = (Window) upstreamWidget; window.removeMouseListener(gearsMouse); window.removeKeyListener(gearsKeys); } @@ -188,8 +190,9 @@ public class GearsES1 implements GLEventListener { GL2ES1 gl = drawable.getGL().getGL2ES1(); final boolean hasFocus; - if(drawable.getNativeSurface() instanceof NativeWindow) { - hasFocus = ((NativeWindow)drawable.getNativeSurface()).hasFocus(); + final Object upstreamWidget = drawable.getUpstreamWidget(); + if(upstreamWidget instanceof NativeWindow) { + hasFocus = ((NativeWindow)upstreamWidget).hasFocus(); } else { hasFocus = true; } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/MultisampleDemoES1.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/MultisampleDemoES1.java new file mode 100644 index 000000000..aad56581b --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/MultisampleDemoES1.java @@ -0,0 +1,123 @@ +/* + * 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 com.jogamp.opengl.test.junit.jogl.demos.es1; + +import javax.media.opengl.GL; +import javax.media.opengl.GL2ES1; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLEventListener; + +import com.jogamp.opengl.util.ImmModeSink; + +public class MultisampleDemoES1 implements GLEventListener { + + boolean multisample; + ImmModeSink immModeSink; + + public MultisampleDemoES1(boolean multisample) { + this.multisample = multisample; + } + + public void init(GLAutoDrawable drawable) { + System.err.println(); + System.err.println("Requested: " + drawable.getNativeSurface().getGraphicsConfiguration().getRequestedCapabilities()); + System.err.println(); + System.err.println("Chosen : " + drawable.getChosenGLCapabilities()); + System.err.println(); + GL2ES1 gl = drawable.getGL().getGL2ES1(); + if (multisample) { + gl.glEnable(GL.GL_MULTISAMPLE); + } + gl.glClearColor(0, 0, 0, 0); + // gl.glEnable(GL.GL_DEPTH_TEST); + // gl.glDepthFunc(GL.GL_LESS); + gl.glMatrixMode(GL2ES1.GL_MODELVIEW); + gl.glLoadIdentity(); + gl.glMatrixMode(GL2ES1.GL_PROJECTION); + gl.glLoadIdentity(); + gl.glOrtho(-1, 1, -1, 1, -1, 1); + if (multisample) { + gl.glDisable(GL.GL_MULTISAMPLE); + } + immModeSink = ImmModeSink.createFixed(gl, GL.GL_STATIC_DRAW, 40, + 3, GL.GL_FLOAT, // vertex + 0, GL.GL_FLOAT, // color + 0, GL.GL_FLOAT,// normal + 0, GL.GL_FLOAT); // texture + final int numSteps = 20; + final double increment = Math.PI / numSteps; + final double radius = 1; + immModeSink.glBegin(GL.GL_LINES); + for (int i = numSteps - 1; i >= 0; i--) { + immModeSink.glVertex3f((float) (radius * Math.cos(i * increment)), + (float) (radius * Math.sin(i * increment)), + 0f); + immModeSink.glVertex3f((float) (-1.0 * radius * Math.cos(i * increment)), + (float) (-1.0 * radius * Math.sin(i * increment)), + 0f); + } + immModeSink.glEnd(gl, false); + } + + public void dispose(GLAutoDrawable drawable) { + immModeSink.destroy(drawable.getGL()); + immModeSink = null; + } + + public void display(GLAutoDrawable drawable) { + GL2ES1 gl = drawable.getGL().getGL2ES1(); + if (multisample) { + gl.glEnable(GL.GL_MULTISAMPLE); + } + gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + immModeSink.draw(gl, true); + if (multisample) { + gl.glDisable(GL.GL_MULTISAMPLE); + } + } + + // Unused routines + public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { + } + + public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { + } +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/FBOMix2DemosES2.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/FBOMix2DemosES2.java new file mode 100644 index 000000000..3dfbb4893 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/FBOMix2DemosES2.java @@ -0,0 +1,309 @@ +/** + * Copyright (C) 2011 JogAmp Community. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.jogamp.opengl.test.junit.jogl.demos.es2; + +import java.nio.FloatBuffer; + +import javax.media.opengl.GL; +import javax.media.opengl.GL2ES2; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLUniformData; +import javax.media.opengl.fixedfunc.GLMatrixFunc; + +import com.jogamp.opengl.FBObject; +import com.jogamp.opengl.FBObject.TextureAttachment; +import com.jogamp.opengl.FBObject.Attachment.Type; +import com.jogamp.opengl.util.GLArrayDataServer; +import com.jogamp.opengl.util.PMVMatrix; +import com.jogamp.opengl.util.glsl.ShaderCode; +import com.jogamp.opengl.util.glsl.ShaderProgram; +import com.jogamp.opengl.util.glsl.ShaderState; + +public class FBOMix2DemosES2 implements GLEventListener { + private final GearsES2 demo0; + private final RedSquareES2 demo1; + private final int swapInterval; + private int numSamples; + private boolean demo0Only; + + + private final ShaderState st; + private final PMVMatrix pmvMatrix; + + private final FBObject fbo0; + private final FBObject fbo1; + + private TextureAttachment fbo0Tex; + private TextureAttachment fbo1Tex; + + private ShaderProgram sp0; + private GLUniformData pmvMatrixUniform; + private GLArrayDataServer interleavedVBO; + private GLUniformData texUnit0; + private GLUniformData texUnit1; + + public FBOMix2DemosES2(int swapInterval) { + demo0 = new GearsES2(-1); + demo0.setIsFBOSlave(true); + demo1 = new RedSquareES2(-1); + demo1.setIsFBOSlave(true); + this.swapInterval = swapInterval; + + st = new ShaderState(); + // st.setVerbose(true); + pmvMatrix = new PMVMatrix(); + + fbo0 = new FBObject(); + fbo1 = new FBObject(); + + numSamples = 0; + demo0Only = false; + } + + public void setDemo0Only(boolean v) { + this.demo0Only = v; + } + public boolean getDemo0Only() { return demo0Only; } + + public void setMSAA(int numSamples) { + this.numSamples=numSamples; + } + public int getMSAA() { return numSamples; } + + public void setDoRotation(boolean rotate) { demo1.setDoRotation(rotate); } + + static final String[] es2_prelude = { "#version 100\n", "precision mediump float;\n" }; + static final String gl2_prelude = "#version 110\n"; + + @Override + public void init(GLAutoDrawable drawable) { + final GL2ES2 gl = drawable.getGL().getGL2ES2(); + + demo0.init(drawable); + demo1.init(drawable); + + final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, FBOMix2DemosES2.class, "shader", + "shader/bin", "texture01_xxx", true); + final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, FBOMix2DemosES2.class, "shader", + "shader/bin", "texture02_xxx", true); + + // Prelude shader code w/ GLSL profile specifics [ 1. pre-proc, 2. other ] + int fp0Pos; + if(gl.isGLES2()) { + vp0.insertShaderSource(0, 0, es2_prelude[0]); + fp0Pos = fp0.insertShaderSource(0, 0, es2_prelude[0]); + } else { + vp0.insertShaderSource(0, 0, gl2_prelude); + fp0Pos = fp0.insertShaderSource(0, 0, gl2_prelude); + } + if(gl.isGLES2()) { + fp0Pos = fp0.insertShaderSource(0, fp0Pos, es2_prelude[1]); + } + + sp0 = new ShaderProgram(); + sp0.add(gl, vp0, System.err); + sp0.add(gl, fp0, System.err); + st.attachShaderProgram(gl, sp0, true); + + pmvMatrixUniform = new GLUniformData("mgl_PMVMatrix", 4, 4, pmvMatrix.glGetPMvMatrixf()); + st.ownUniform(pmvMatrixUniform); + st.uniform(gl, pmvMatrixUniform); + + interleavedVBO = GLArrayDataServer.createGLSLInterleaved(3+4+2, GL.GL_FLOAT, false, 3*4, GL.GL_STATIC_DRAW); + { + interleavedVBO.addGLSLSubArray("mgl_Vertex", 3, GL.GL_ARRAY_BUFFER); + interleavedVBO.addGLSLSubArray("mgl_Color", 4, GL.GL_ARRAY_BUFFER); + //interleavedVBO.addGLSLSubArray("mgl_Normal", 3, GL.GL_ARRAY_BUFFER); + interleavedVBO.addGLSLSubArray("mgl_MultiTexCoord", 2, GL.GL_ARRAY_BUFFER); + + FloatBuffer ib = (FloatBuffer)interleavedVBO.getBuffer(); + + for(int i=0; i<4; i++) { + ib.put(s_quadVertices, i*3, 3); + ib.put(s_quadColors, i*4, 4); + //ib.put(s_cubeNormals, i*3, 3); + ib.put(s_quadTexCoords, i*2, 2); + } + } + interleavedVBO.seal(gl, true); + interleavedVBO.enableBuffer(gl, false); + st.ownAttribute(interleavedVBO, true); + + texUnit0 = new GLUniformData("mgl_Texture0", 0); + st.ownUniform(texUnit0); + st.uniform(gl, texUnit0); + texUnit1 = new GLUniformData("mgl_Texture1", 1); + st.ownUniform(texUnit1); + st.uniform(gl, texUnit1); + + st.useProgram(gl, false); + + System.err.println("**** Init"); + resetFBOs(gl, drawable); + + fbo0.attachRenderbuffer(gl, Type.DEPTH, 24); + fbo0.unbind(gl); + fbo1.attachRenderbuffer(gl, Type.DEPTH, 24); + fbo1.unbind(gl); + gl.glEnable(GL2ES2.GL_DEPTH_TEST); + + numSamples=fbo0.getNumSamples(); + } + + /** Since we switch MSAA and non-MSAA we need to take extra care, i.e. sync msaa for both FBOs ..*/ + private void resetFBOs(GL gl, GLAutoDrawable drawable) { + // remove all texture attachments, since MSAA uses just color-render-buffer + // and non-MSAA uses texture2d-buffer + fbo0.detachAllColorbuffer(gl); + fbo1.detachAllColorbuffer(gl); + + fbo0.reset(gl, drawable.getWidth(), drawable.getHeight(), numSamples); + fbo1.reset(gl, drawable.getWidth(), drawable.getHeight(), numSamples); + if(fbo0.getNumSamples() != fbo1.getNumSamples()) { + throw new InternalError("sample size mismatch: \n\t0: "+fbo0+"\n\t1: "+fbo1); + } + numSamples = fbo0.getNumSamples(); + + if(numSamples>0) { + fbo0.attachColorbuffer(gl, 0, true); + fbo1.attachColorbuffer(gl, 0, true); + fbo0Tex = fbo0.getSamplingSink(); + fbo1Tex = fbo1.getSamplingSink(); + } else { + fbo0Tex = fbo0.attachTexture2D(gl, 0, true); + fbo1Tex = fbo1.attachTexture2D(gl, 0, true); + } + } + + @Override + public void dispose(GLAutoDrawable drawable) { + final GL2ES2 gl = drawable.getGL().getGL2ES2(); + demo0.dispose(drawable); + demo1.dispose(drawable); + fbo0.destroy(gl); + fbo1.destroy(gl); + st.destroy(gl); + + fbo0Tex = null; + fbo1Tex = null; + sp0 = null; + pmvMatrixUniform = null; + interleavedVBO = null; + } + + @Override + public void display(GLAutoDrawable drawable) { + final GL2ES2 gl = drawable.getGL().getGL2ES2(); + + if( fbo0.getNumSamples() != numSamples ) { + System.err.println("**** NumSamples: "+fbo0.getNumSamples()+" -> "+numSamples); + resetFBOs(gl, drawable); + } + + if(0 < numSamples) { + gl.glEnable(GL.GL_MULTISAMPLE); + } + + fbo0.bind(gl); + demo0.display(drawable); + fbo0.unbind(gl); + + if(!demo0Only) { + fbo1.bind(gl); + demo1.display(drawable); + fbo1.unbind(gl); + } + + st.useProgram(gl, true); + gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + + gl.glActiveTexture(GL.GL_TEXTURE0 + texUnit0.intValue()); + fbo0.use(gl, fbo0Tex); + if(!demo0Only) { + gl.glActiveTexture(GL.GL_TEXTURE0 + texUnit1.intValue()); + fbo1.use(gl, fbo1Tex); + } + interleavedVBO.enableBuffer(gl, true); + + gl.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4); + + interleavedVBO.enableBuffer(gl, false); + fbo0.unuse(gl); + if(!demo0Only) { + fbo1.unuse(gl); + } + + st.useProgram(gl, false); + } + + @Override + public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { + final GL2ES2 gl = drawable.getGL().getGL2ES2(); + + if(-1 != swapInterval) { + gl.setSwapInterval(swapInterval); // in case switching the drawable (impl. may bound attribute there) + } + + // if(drawable.getWidth() == fbo0.getWidth() && drawable.getHeight() == fbo0.getHeight() ) { + System.err.println("**** Reshape: "+width+"x"+height); + resetFBOs(gl, drawable); + //} + + fbo0.bind(gl); + demo0.reshape(drawable, x, y, width, height); + fbo0.unbind(gl); + fbo1.bind(gl); + demo1.reshape(drawable, x, y, width, height); + fbo1.unbind(gl); + + pmvMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION); + pmvMatrix.glLoadIdentity(); + pmvMatrix.glOrthof(-1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 10.0f); + + pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); + pmvMatrix.glLoadIdentity(); + + st.useProgram(gl, true); + st.uniform(gl, pmvMatrixUniform); + st.useProgram(gl, false); + + } + + private static final float[] s_quadVertices = { + -1f, -1f, 0f, // LB + 1f, -1f, 0f, // RB + -1f, 1f, 0f, // LT + 1f, 1f, 0f // RT + }; + private static final float[] s_quadColors = { + 1f, 1f, 1f, 1f, + 1f, 1f, 1f, 1f, + 1f, 1f, 1f, 1f, + 1f, 1f, 1f, 1f }; + private static final float[] s_quadTexCoords = { + 0f, 0f, // LB + 1f, 0f, // RB + 0f, 1f, // LT + 1f, 1f // RT + }; +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java index 6aea5bb9c..38e8a15ce 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java @@ -65,6 +65,7 @@ public class GearsES2 implements GLEventListener { private int prevMouseX, prevMouseY; private boolean isInitialized = false; + boolean isFBOSlave = false; public GearsES2(int swapInterval) { this.swapInterval = swapInterval; @@ -74,6 +75,8 @@ public class GearsES2 implements GLEventListener { this.swapInterval = 1; } + public void setIsFBOSlave(boolean v) { isFBOSlave = v; } + public void setPMVUseBackingArray(boolean pmvUseBackingArray) { this.pmvUseBackingArray = pmvUseBackingArray; } @@ -115,7 +118,6 @@ public class GearsES2 implements GLEventListener { System.err.println("GL_RENDERER: " + gl.glGetString(GL.GL_RENDERER)); System.err.println("GL_VERSION: " + gl.glGetString(GL.GL_VERSION)); - gl.glEnable(GL.GL_CULL_FACE); gl.glEnable(GL.GL_DEPTH_TEST); st = new ShaderState(); @@ -168,13 +170,14 @@ public class GearsES2 implements GLEventListener { gear3 = new GearsObjectES2(gear3, pmvMatrix, pmvMatrixUniform, colorU); System.err.println("gear3 reused: "+gear3); } - - if (drawable.getNativeSurface() instanceof Window) { - Window window = (Window) drawable.getNativeSurface(); + + final Object upstreamWidget = drawable.getUpstreamWidget(); + if (upstreamWidget instanceof Window) { + final Window window = (Window) upstreamWidget; window.addMouseListener(gearsMouse); window.addKeyListener(gearsKeys); - } else if (GLProfile.isAWTAvailable() && drawable instanceof java.awt.Component) { - java.awt.Component comp = (java.awt.Component) drawable; + } else if (GLProfile.isAWTAvailable() && upstreamWidget instanceof java.awt.Component) { + final java.awt.Component comp = (java.awt.Component) upstreamWidget; new com.jogamp.newt.event.awt.AWTMouseAdapter(gearsMouse).addTo(comp); new com.jogamp.newt.event.awt.AWTKeyAdapter(gearsKeys).addTo(comp); } @@ -187,7 +190,9 @@ public class GearsES2 implements GLEventListener { System.err.println(Thread.currentThread()+" GearsES2.reshape "+x+"/"+y+" "+width+"x"+height+", swapInterval "+swapInterval); GL2ES2 gl = drawable.getGL().getGL2ES2(); - gl.setSwapInterval(swapInterval); // in case switching the drawable (impl. may bound attribute there) + if(-1 != swapInterval) { + gl.setSwapInterval(swapInterval); // in case switching the drawable (impl. may bound attribute there) + } st.useProgram(gl, true); pmvMatrix.glMatrixMode(PMVMatrix.GL_PROJECTION); @@ -218,8 +223,9 @@ public class GearsES2 implements GLEventListener { } isInitialized = false; System.err.println(Thread.currentThread()+" GearsES2.dispose ... "); - if (drawable.getNativeSurface() instanceof Window) { - Window window = (Window) drawable.getNativeSurface(); + final Object upstreamWidget = drawable.getUpstreamWidget(); + if (upstreamWidget instanceof Window) { + final Window window = (Window) upstreamWidget; window.removeMouseListener(gearsMouse); window.removeKeyListener(gearsKeys); } @@ -235,6 +241,7 @@ public class GearsES2 implements GLEventListener { colorU = null; st.destroy(gl); st = null; + System.err.println(Thread.currentThread()+" GearsES2.dispose FIN"); } @@ -246,12 +253,16 @@ public class GearsES2 implements GLEventListener { GL2ES2 gl = drawable.getGL().getGL2ES2(); final boolean hasFocus; - if(drawable.getNativeSurface() instanceof NativeWindow) { - hasFocus = ((NativeWindow)drawable.getNativeSurface()).hasFocus(); + final Object upstreamWidget = drawable.getUpstreamWidget(); + if(upstreamWidget instanceof NativeWindow) { + hasFocus = ((NativeWindow)upstreamWidget).hasFocus(); } else { hasFocus = true; } - if(hasFocus) { + + gl.glEnable(GL.GL_CULL_FACE); + + if( isFBOSlave || hasFocus ) { gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); } else { gl.glClearColor(0.2f, 0.2f, 0.2f, 0.0f); @@ -278,7 +289,9 @@ public class GearsES2 implements GLEventListener { gear2.draw(gl, 3.1f, -2.0f, -2f * angle - 9.0f, GearsObject.green); gear3.draw(gl, -3.1f, 4.2f, -2f * angle - 25.0f, GearsObject.blue); pmvMatrix.glPopMatrix(); - st.useProgram(gl, false); + st.useProgram(gl, false); + + gl.glDisable(GL.GL_CULL_FACE); } boolean confinedFixedCenter = false; diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/MultisampleDemoES2.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/MultisampleDemoES2.java new file mode 100644 index 000000000..5facc1a49 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/MultisampleDemoES2.java @@ -0,0 +1,178 @@ +/* + * 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 com.jogamp.opengl.test.junit.jogl.demos.es2; + +import javax.media.opengl.GL; +import javax.media.opengl.GL2ES2; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLUniformData; +import javax.media.opengl.fixedfunc.GLMatrixFunc; + +import com.jogamp.opengl.util.ImmModeSink; +import com.jogamp.opengl.util.PMVMatrix; +import com.jogamp.opengl.util.glsl.ShaderCode; +import com.jogamp.opengl.util.glsl.ShaderProgram; +import com.jogamp.opengl.util.glsl.ShaderState; + +public class MultisampleDemoES2 implements GLEventListener { + + private boolean multisample; + private final ShaderState st; + private final PMVMatrix pmvMatrix; + private ShaderProgram sp0; + private GLUniformData pmvMatrixUniform; + private ImmModeSink immModeSink; + + public MultisampleDemoES2(boolean multisample) { + this.multisample = multisample; + st = new ShaderState(); + st.setVerbose(true); + pmvMatrix = new PMVMatrix(); + } + + static final String[] es2_prelude = { "#version 100\n", "precision mediump float;\n" }; + static final String gl2_prelude = "#version 110\n"; + + public void init(GLAutoDrawable glad) { + final GL2ES2 gl = glad.getGL().getGL2ES2(); + System.err.println(); + System.err.println("Requested: " + glad.getNativeSurface().getGraphicsConfiguration().getRequestedCapabilities()); + System.err.println(); + System.err.println("Chosen : " + glad.getChosenGLCapabilities()); + System.err.println(); + + final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, MultisampleDemoES2.class, "shader", + "shader/bin", "mgl_default_xxx", true); + final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, MultisampleDemoES2.class, "shader", + "shader/bin", "mgl_default_xxx", true); + + // Prelude shader code w/ GLSL profile specifics [ 1. pre-proc, 2. other ] + int fp0Pos; + if(gl.isGLES2()) { + vp0.insertShaderSource(0, 0, es2_prelude[0]); + fp0Pos = fp0.insertShaderSource(0, 0, es2_prelude[0]); + } else { + vp0.insertShaderSource(0, 0, gl2_prelude); + fp0Pos = fp0.insertShaderSource(0, 0, gl2_prelude); + } + if(gl.isGLES2()) { + fp0Pos = fp0.insertShaderSource(0, fp0Pos, es2_prelude[1]); + } + + sp0 = new ShaderProgram(); + sp0.add(gl, vp0, System.err); + sp0.add(gl, fp0, System.err); + st.attachShaderProgram(gl, sp0, true); + + pmvMatrixUniform = new GLUniformData("mgl_PMVMatrix", 4, 4, pmvMatrix.glGetPMvMatrixf()); + st.ownUniform(pmvMatrixUniform); + st.uniform(gl, pmvMatrixUniform); + + // Using predef array names, see + // GLPointerFuncUtil.getPredefinedArrayIndexName(glArrayIndex); + immModeSink = ImmModeSink.createGLSL(gl, GL.GL_STATIC_DRAW, 40, + 3, GL.GL_FLOAT, // vertex + 4, GL.GL_FLOAT, // color + 0, GL.GL_FLOAT,// normal + 0, GL.GL_FLOAT); // texture + final int numSteps = 20; + final double increment = Math.PI / numSteps; + final double radius = 1; + immModeSink.glBegin(GL.GL_LINES); + for (int i = numSteps - 1; i >= 0; i--) { + immModeSink.glVertex3f((float) (radius * Math.cos(i * increment)), + (float) (radius * Math.sin(i * increment)), + 0f); + immModeSink.glColor4f( 1f, 1f, 1f, 1f ); + immModeSink.glVertex3f((float) (-1.0 * radius * Math.cos(i * increment)), + (float) (-1.0 * radius * Math.sin(i * increment)), + 0f); + immModeSink.glColor4f( 1f, 1f, 1f, 1f ); + } + immModeSink.glEnd(gl, false); + + st.useProgram(gl, false); + } + + public void dispose(GLAutoDrawable glad) { + final GL2ES2 gl = glad.getGL().getGL2ES2(); + immModeSink.destroy(gl); + immModeSink = null; + st.destroy(gl); + } + + public void display(GLAutoDrawable glad) { + final GL2ES2 gl = glad.getGL().getGL2ES2(); + if (multisample) { + gl.glEnable(GL.GL_MULTISAMPLE); + } + gl.glClearColor(0, 0, 0, 0); + // gl.glEnable(GL.GL_DEPTH_TEST); + // gl.glDepthFunc(GL.GL_LESS); + gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + + st.useProgram(gl, true); + + immModeSink.draw(gl, true); + + st.useProgram(gl, false); + } + + // Unused routines + public void reshape(GLAutoDrawable glad, int x, int y, int width, int height) { + System.err.println("reshape .."); + final GL2ES2 gl = glad.getGL().getGL2ES2(); + pmvMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION); + pmvMatrix.glLoadIdentity(); + // pmvMatrix.glOrthof(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f); + pmvMatrix.glOrthof(-1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 10.0f); + pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); + pmvMatrix.glLoadIdentity(); + + st.useProgram(gl, true); + st.uniform(gl, pmvMatrixUniform); + st.useProgram(gl, false); + } + + public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { + } +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/RedSquareES2.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/RedSquareES2.java index 6982d61b7..436c44759 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/RedSquareES2.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/RedSquareES2.java @@ -27,9 +27,9 @@ */ package com.jogamp.opengl.test.junit.jogl.demos.es2; +import com.jogamp.newt.Window; import com.jogamp.newt.event.MouseAdapter; import com.jogamp.newt.event.MouseEvent; -import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.util.GLArrayDataServer; import com.jogamp.opengl.util.PMVMatrix; import com.jogamp.opengl.util.glsl.ShaderCode; @@ -37,10 +37,8 @@ import com.jogamp.opengl.util.glsl.ShaderProgram; import com.jogamp.opengl.util.glsl.ShaderState; import javax.media.opengl.GL; import javax.media.opengl.GL2ES2; -import javax.media.opengl.GLAnimatorControl; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLEventListener; -import javax.media.opengl.GLRunnable; import javax.media.opengl.GLUniformData; public class RedSquareES2 implements GLEventListener { @@ -52,10 +50,11 @@ public class RedSquareES2 implements GLEventListener { long t0; private int swapInterval = 0; MyMouseAdapter myMouse = new MyMouseAdapter(); - GLWindow glWindow = null; + Window window = null; float aspect = 1.0f; boolean doRotate = true; boolean isInitialized = false; + boolean isFBOSlave = false; public RedSquareES2(int swapInterval) { this.swapInterval = swapInterval; @@ -65,6 +64,7 @@ public class RedSquareES2 implements GLEventListener { this.swapInterval = 1; } + public void setIsFBOSlave(boolean v) { isFBOSlave = v; } public void setAspect(float aspect) { this.aspect = aspect; } public void setDoRotation(boolean rotate) { this.doRotate = rotate; } @@ -129,13 +129,13 @@ public class RedSquareES2 implements GLEventListener { colors.enableBuffer(gl, false); // OpenGL Render Settings - gl.glClearColor(0, 0, 0, 0); gl.glEnable(GL2ES2.GL_DEPTH_TEST); st.useProgram(gl, false); - if (glad instanceof GLWindow) { - glWindow = (GLWindow) glad; - glWindow.addMouseListener(myMouse); + final Object upstreamWidget = glad.getUpstreamWidget(); + if (!isFBOSlave && upstreamWidget instanceof Window) { + window = (Window) upstreamWidget; + window.addMouseListener(myMouse); } t0 = System.currentTimeMillis(); System.err.println(Thread.currentThread()+" RedSquareES2.init FIN"); @@ -145,6 +145,7 @@ public class RedSquareES2 implements GLEventListener { long t1 = System.currentTimeMillis(); GL2ES2 gl = glad.getGL().getGL2ES2(); + gl.glClearColor(0, 0, 0, 0); gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); st.useProgram(gl, true); // One rotation every four seconds @@ -171,7 +172,9 @@ public class RedSquareES2 implements GLEventListener { System.err.println(Thread.currentThread()+" RedSquareES2.reshape "+x+"/"+y+" "+width+"x"+height+", swapInterval "+swapInterval); GL2ES2 gl = glad.getGL().getGL2ES2(); - gl.setSwapInterval(swapInterval); // in case switching the drawable (impl. may bound attribute there) + if(-1 != swapInterval) { + gl.setSwapInterval(swapInterval); // in case switching the drawable (impl. may bound attribute there) + } st.useProgram(gl, true); // Set location in front of camera @@ -192,9 +195,9 @@ public class RedSquareES2 implements GLEventListener { } isInitialized = false; System.err.println(Thread.currentThread()+" RedSquareES2.dispose ... "); - if (null != glWindow) { - glWindow.removeMouseListener(myMouse); - glWindow = null; + if (null != window) { + window.removeMouseListener(myMouse); + window = null; } GL2ES2 gl = glad.getGL().getGL2ES2(); st.destroy(gl); @@ -207,24 +210,9 @@ public class RedSquareES2 implements GLEventListener { class MyMouseAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) { System.err.println(e); - if(null != glWindow && e.getSource() == glWindow.getDelegatedWindow()) { - if(e.getX() < glWindow.getWidth()/2) { - glWindow.setFullscreen(!glWindow.isFullscreen()); - System.err.println("setFullscreen: "+glWindow.isFullscreen()); - } else { - glWindow.invoke(false, new GLRunnable() { - public boolean run(GLAutoDrawable drawable) { - GL gl = drawable.getGL(); - gl.setSwapInterval(gl.getSwapInterval()<=0?1:0); - System.err.println("setSwapInterval: "+gl.getSwapInterval()); - final GLAnimatorControl a = drawable.getAnimator(); - if( null != a ) { - a.resetFPSCounter(); - } - return true; - } - }); - } + if(null != window && e.getSource() == window) { + window.setFullscreen(!window.isFullscreen()); + System.err.println("setFullscreen: "+window.isFullscreen()); } } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/TextureSequenceCubeES2.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/TextureSequenceCubeES2.java index b04bd07c1..9217e2b53 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/TextureSequenceCubeES2.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/TextureSequenceCubeES2.java @@ -265,11 +265,12 @@ public class TextureSequenceCubeES2 implements GLEventListener { st.useProgram(gl, false); - if (drawable instanceof Window) { - Window window = (Window) drawable; + final Object upstreamWidget = drawable.getUpstreamWidget(); + if (upstreamWidget instanceof Window) { + final Window window = (Window) upstreamWidget; window.addMouseListener(mouseAction); - } else if (GLProfile.isAWTAvailable() && drawable instanceof java.awt.Component) { - java.awt.Component comp = (java.awt.Component) drawable; + } else if (GLProfile.isAWTAvailable() && upstreamWidget instanceof java.awt.Component) { + final java.awt.Component comp = (java.awt.Component) upstreamWidget; new com.jogamp.newt.event.awt.AWTMouseAdapter(mouseAction).addTo(comp); } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieCube.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieCube.java index 0b83aacd8..7f2713354 100755 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieCube.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieCube.java @@ -163,8 +163,9 @@ public class MovieCube implements GLEventListener, GLMediaEventListener { mPlayer.start(); boolean added; - if (drawable instanceof Window) { - Window window = (Window) drawable; + final Object upstreamWidget = drawable.getUpstreamWidget(); + if (upstreamWidget instanceof Window) { + final Window window = (Window) upstreamWidget; window.addKeyListener(keyAction); added = true; } else { added = false; } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieSimple.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieSimple.java index 8210065ab..e17c9e88b 100755 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieSimple.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieSimple.java @@ -400,8 +400,9 @@ public class MovieSimple implements GLEventListener, GLMediaEventListener { startTime = System.currentTimeMillis(); - if (drawable instanceof Window) { - Window window = (Window) drawable; + final Object upstreamWidget = drawable.getUpstreamWidget(); + if (upstreamWidget instanceof Window) { + final Window window = (Window) upstreamWidget; window.addMouseListener(mouseAction); winWidth = window.getWidth(); winHeight = window.getHeight(); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java index 04563d62e..797a16485 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java @@ -258,7 +258,6 @@ public class TestGearsES2NEWT extends UITestCase { public static void main(String args[]) throws IOException { int x=0, y=0, w=640, h=480; - boolean useSize = false; boolean usePos = false; for(int i=0; i= height. + * + * Draws the Gears demo in a window that's twice as wide than it is tall, + * and checks to see if a particular pixel in the right half of the frame + * is colored. + * + * @author Wade Walker (adapted from TestGearsGLJPanelAWT) + */ +public class TestGLJPanelAWTBug450 extends UITestCase { + static GLProfile glp; + static int width, height; + static int r_x, r_y; + /** Set this if test fails. Needed because we can't throw an exception + * all the way up the stack from where we test the pixel. */ + static boolean failed; + + @BeforeClass + public static void initClass() { + glp = GLProfile.getGL2ES2(); + Assert.assertNotNull(glp); + height = 256; + width = 2*height; + r_x = 5*height/4; // 5/8 * width + r_y = height/2; + } + + @AfterClass + public static void releaseClass() { + } + + protected void runTestGL(GLCapabilities caps) + throws AWTException, InterruptedException, InvocationTargetException + { + final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false); + JFrame frame = new JFrame("Swing GLJPanel"); + Assert.assertNotNull(frame); + + GLJPanel glJPanel = new GLJPanel(caps); + Assert.assertNotNull(glJPanel); + RedSquareES2 demo = new RedSquareES2(); + demo.setAspect((float)width/(float)height); + demo.setDoRotation(false); + glJPanel.addGLEventListener(demo); + glJPanel.addGLEventListener(new GLEventListener() { + int f = 0; + @Override + public void init(GLAutoDrawable drawable) { + // drawable.getGL().glClearColor(0, 0, 1, 1); + } + @Override + public void display(GLAutoDrawable drawable) { + // look at one pixel at the bottom of the frame, just right of + // the center line, and make sure it's not black + GL2 gl = GLUgl2.getCurrentGL2(); + ByteBuffer bytebuffer = ByteBuffer.allocateDirect( 3 ); + gl.glReadPixels( r_x, r_y, 1, 1, GL2.GL_BGR, GL2.GL_UNSIGNED_BYTE, bytebuffer ); + byte byte0 = bytebuffer.get( 0 ); + byte byte1 = bytebuffer.get( 1 ); + byte byte2 = bytebuffer.get( 2 ); + if( (byte0 == 0) && (byte1 == 0) && (byte2 == 0) ) { + failed = true; + } + if(0 == f) { + System.err.println("BGR ("+r_x+"/"+r_y+"): "+byte0+", "+byte1+", "+byte2+" - OK "+(!failed)); + snapshot(getSimpleTestName("."), f, null, gl, screenshot, TextureIO.PNG, null); + } + f++; + } + @Override + public void dispose(GLAutoDrawable drawable) {} + @Override + public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } + }); + + FPSAnimator animator = new FPSAnimator(glJPanel, 60); + + final JFrame _frame = frame; + final GLJPanel _glJPanel = glJPanel; + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + _frame.getContentPane().add(_glJPanel, BorderLayout.CENTER); + _frame.setSize(width, height); + _frame.setVisible(true); + } } ) ; + + animator.setUpdateFPSFrames(1, null); + animator.start(); + Assert.assertEquals(true, animator.isAnimating()); + + while(animator.isAnimating() && animator.getTotalFPSDuration()= height. - * - * Draws the Gears demo in a window that's twice as wide than it is tall, - * and checks to see if a particular pixel in the right half of the frame - * is colored. - * - * @author Wade Walker (adapted from TestGearsGLJPanelAWT) - */ -public class TestGearsGLJPanelAWTBug450 extends UITestCase { - static GLProfile glp; - static int width, height; - static int r_x, r_y; - /** Set this if test fails. Needed because we can't throw an exception - * all the way up the stack from where we test the pixel. */ - static boolean failed; - - @BeforeClass - public static void initClass() { - glp = GLProfile.getGL2ES2(); - Assert.assertNotNull(glp); - height = 256; - width = 2*height; - r_x = 5*height/4; // 5/8 * width - r_y = height/2; - } - - @AfterClass - public static void releaseClass() { - } - - protected void snapshot(GLAutoDrawable drawable, boolean alpha, boolean flip, String filename) { - GLReadBufferUtil screenshot = new GLReadBufferUtil(alpha, false); - if(screenshot.readPixels(drawable.getGL(), drawable, flip)) { - screenshot.write(new File(filename)); - } - } - - protected void runTestGL(GLCapabilities caps) - throws AWTException, InterruptedException, InvocationTargetException - { - JFrame frame = new JFrame("Swing GLJPanel"); - Assert.assertNotNull(frame); - - GLJPanel glJPanel = new GLJPanel(caps); - Assert.assertNotNull(glJPanel); - RedSquareES2 demo = new RedSquareES2(); - demo.setAspect((float)width/(float)height); - demo.setDoRotation(false); - glJPanel.addGLEventListener(demo); - glJPanel.addGLEventListener(new GLEventListener() { - int f = 0; - @Override - public void init(GLAutoDrawable drawable) { - // drawable.getGL().glClearColor(0, 0, 1, 1); - } - @Override - public void display(GLAutoDrawable drawable) { - // look at one pixel at the bottom of the frame, just right of - // the center line, and make sure it's not black - GL2 gl = GLUgl2.getCurrentGL2(); - ByteBuffer bytebuffer = ByteBuffer.allocateDirect( 3 ); - gl.glReadPixels( r_x, r_y, 1, 1, GL2.GL_BGR, GL2.GL_UNSIGNED_BYTE, bytebuffer ); - byte byte0 = bytebuffer.get( 0 ); - byte byte1 = bytebuffer.get( 1 ); - byte byte2 = bytebuffer.get( 2 ); - if( (byte0 == 0) && (byte1 == 0) && (byte2 == 0) ) { - failed = true; - } - if(0 == f) { - System.err.println("BGR ("+r_x+"/"+r_y+"): "+byte0+", "+byte1+", "+byte2+" - OK "+(!failed)); - snapshot(drawable, true, false, getSimpleTestName(".")+".png"); - } - f++; - } - @Override - public void dispose(GLAutoDrawable drawable) {} - @Override - public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } - }); - - FPSAnimator animator = new FPSAnimator(glJPanel, 60); - - final JFrame _frame = frame; - final GLJPanel _glJPanel = glJPanel; - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - _frame.getContentPane().add(_glJPanel, BorderLayout.CENTER); - _frame.setSize(width, height); - _frame.setVisible(true); - } } ) ; - - animator.setUpdateFPSFrames(1, null); - animator.start(); - Assert.assertEquals(true, animator.isAnimating()); - - while(animator.isAnimating() && animator.getTotalFPSDuration() buffer0, Green -> buffer1 - st.attachShaderProgram(gl, sp0, true); - vertices0.enableBuffer(gl, true); - colors0.enableBuffer(gl, true); - - fbo_mrt.bind(gl); - gl.glDrawBuffers(2, two_buffers, 0); - gl.glViewport(0, 0, fbo_mrt.getWidth(), fbo_mrt.getHeight()); - - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - gl.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4); - fbo_mrt.unbind(gl); - vertices0.enableBuffer(gl, false); - colors0.enableBuffer(gl, false); - - // pass 2 - mix buffer0, buffer1 and blue - // rg = buffer0.rg + buffer1.rg, b = Blue - length(rg); - st.attachShaderProgram(gl, sp1, true); - vertices0.enableBuffer(gl, true); - colors0.enableBuffer(gl, true); - texCoords0.enableBuffer(gl, true); - gl.glDrawBuffers(1, bck_buffers, 0); - - gl.glViewport(0, 0, drawable.getWidth(), drawable.getHeight()); - fbo_mrt.use(gl, 0); - fbo_mrt.use(gl, 1); - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - gl.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4); - fbo_mrt.unuse(gl); - vertices0.enableBuffer(gl, false); - colors0.enableBuffer(gl, false); - texCoords0.enableBuffer(gl, false); - - drawable.swapBuffers(); - Thread.sleep(50); - } - - NEWTGLContext.destroyWindow(winctx); - } - - public static void main(String args[]) throws IOException { - System.err.println("main - start"); - for(int i=0; i 0 ? "rgba" : "rgb_"; - snapshot(drawable, true, false, getSimpleTestName(".")+"-F_rgba-I_"+pfmt+"-"+drawable.getGLProfile().getName()+".png"); - snapshot(drawable, false, false, getSimpleTestName(".")+"-F_rgb_-I_"+pfmt+"-"+drawable.getGLProfile().getName()+".png"); + snapshot(getSimpleTestName("."), f, null, drawable.getGL(), screenshotRGBA, TextureIO.PNG, null); + snapshot(getSimpleTestName("."), f, null, drawable.getGL(), screenshotRGB, TextureIO.PNG, null); + f++; } public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } }); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite01NEWT.java index b5b12035d..5681df0ad 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite01NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite01NEWT.java @@ -28,8 +28,6 @@ package com.jogamp.opengl.test.junit.jogl.util.texture; -import java.io.File; - import com.jogamp.newt.opengl.GLWindow; import javax.media.opengl.GLAutoDrawable; @@ -37,6 +35,7 @@ import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import com.jogamp.opengl.util.GLReadBufferUtil; +import com.jogamp.opengl.util.texture.TextureIO; import com.jogamp.opengl.test.junit.util.UITestCase; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; @@ -62,32 +61,26 @@ public class TestGLReadBufferUtilTextureIOWrite01NEWT extends UITestCase { height = 256; } - protected void snapshot(GLAutoDrawable drawable, boolean alpha, boolean flip, String filename) { - GLReadBufferUtil screenshot = new GLReadBufferUtil(alpha, false); - if(screenshot.readPixels(drawable.getGL(), drawable, flip)) { - screenshot.write(new File(filename)); - } - } - @Test public void testOnscreenWritePNG_TGA_PAM() throws InterruptedException { + final GLReadBufferUtil screenshotRGB = new GLReadBufferUtil(false, false); + final GLReadBufferUtil screenshotRGBA = new GLReadBufferUtil(true, false); GLWindow glWindow = GLWindow.create(caps); Assert.assertNotNull(glWindow); glWindow.setTitle("Shared Gears NEWT Test"); glWindow.setSize(width, height); glWindow.addGLEventListener(new GearsES2(1)); glWindow.addGLEventListener(new GLEventListener() { + int f = 0; public void init(GLAutoDrawable drawable) {} public void dispose(GLAutoDrawable drawable) {} public void display(GLAutoDrawable drawable) { - final String pfmt = drawable.getChosenGLCapabilities().getAlphaBits() > 0 ? "rgba" : "rgb_"; - // snapshot(drawable, false, true, getSimpleTestName(".")+"-rgb_-"+drawable.getGLProfile().getName()+".ppm"); - snapshot(drawable, true, false, getSimpleTestName(".")+"-F_rgba-I_"+pfmt+"-"+drawable.getGLProfile().getName()+".png"); - snapshot(drawable, true, false, getSimpleTestName(".")+"-F_rgba-I_"+pfmt+"-"+drawable.getGLProfile().getName()+".tga"); - snapshot(drawable, true, true, getSimpleTestName(".")+"-F_rgba-I_"+pfmt+"-"+drawable.getGLProfile().getName()+".pam"); - snapshot(drawable, false, false, getSimpleTestName(".")+"-F_rgb_-I_"+pfmt+"-"+drawable.getGLProfile().getName()+".png"); - snapshot(drawable, false, false, getSimpleTestName(".")+"-F_rgb_-I_"+pfmt+"-"+drawable.getGLProfile().getName()+".tga"); - snapshot(drawable, false, true, getSimpleTestName(".")+"-F_rgb_-I_"+pfmt+"-"+drawable.getGLProfile().getName()+".pam"); + snapshot(getSimpleTestName("."), f++, null, drawable.getGL(), screenshotRGBA, TextureIO.PNG, null); + snapshot(getSimpleTestName("."), f++, null, drawable.getGL(), screenshotRGB, TextureIO.PNG, null); + snapshot(getSimpleTestName("."), f++, null, drawable.getGL(), screenshotRGBA, TextureIO.TGA, null); + snapshot(getSimpleTestName("."), f++, null, drawable.getGL(), screenshotRGB, TextureIO.TGA, null); + snapshot(getSimpleTestName("."), f++, null, drawable.getGL(), screenshotRGBA, TextureIO.PAM, null); + snapshot(getSimpleTestName("."), f++, null, drawable.getGL(), screenshotRGB, TextureIO.PAM, null); } public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } }); @@ -98,18 +91,21 @@ public class TestGLReadBufferUtilTextureIOWrite01NEWT extends UITestCase { @Test public void testOffscreenWritePNG() throws InterruptedException { + final GLReadBufferUtil screenshotRGB = new GLReadBufferUtil(false, false); + final GLReadBufferUtil screenshotRGBA = new GLReadBufferUtil(true, false); final GLCapabilities caps2 = WindowUtilNEWT.fixCaps(caps, false, true, false); GLWindow glWindow = GLWindow.create(caps2); Assert.assertNotNull(glWindow); glWindow.setSize(width, height); glWindow.addGLEventListener(new GearsES2(1)); glWindow.addGLEventListener(new GLEventListener() { + int f = 0; public void init(GLAutoDrawable drawable) {} public void dispose(GLAutoDrawable drawable) {} public void display(GLAutoDrawable drawable) { - final String pfmt = drawable.getChosenGLCapabilities().getAlphaBits() > 0 ? "rgba" : "rgb_"; - snapshot(drawable, true, false, getSimpleTestName(".")+"-F_rgba-I_"+pfmt+"-"+drawable.getGLProfile().getName()+".png"); - snapshot(drawable, false, false, getSimpleTestName(".")+"-F_rgb_-I_"+pfmt+"-"+drawable.getGLProfile().getName()+".png"); + snapshot(getSimpleTestName("."), f, null, drawable.getGL(), screenshotRGBA, TextureIO.PNG, null); + snapshot(getSimpleTestName("."), f, null, drawable.getGL(), screenshotRGB, TextureIO.PNG, null); + f++; } public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } }); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite02AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite02AWT.java index 10dd4ea70..43641fe6d 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite02AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite02AWT.java @@ -30,9 +30,6 @@ package com.jogamp.opengl.test.junit.jogl.util.texture; import java.awt.Dimension; import java.awt.Frame; -import java.io.File; -import java.io.PrintWriter; -import java.io.StringWriter; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; @@ -45,6 +42,7 @@ import jogamp.nativewindow.jawt.JAWTUtil; import com.jogamp.opengl.util.Animator; import com.jogamp.opengl.util.GLReadBufferUtil; +import com.jogamp.opengl.util.texture.TextureIO; import com.jogamp.opengl.test.junit.util.AWTRobotUtil; import com.jogamp.opengl.test.junit.util.UITestCase; @@ -71,20 +69,6 @@ public class TestGLReadBufferUtilTextureIOWrite02AWT extends UITestCase { height = 64; } - protected void snapshot(GLAutoDrawable drawable, GLReadBufferUtil screenshot, int i) { - final StringWriter filename = new StringWriter(); - { - final PrintWriter pw = new PrintWriter(filename); - final String pfmt = drawable.getChosenGLCapabilities().getAlphaBits() > 0 ? "rgba" : "rgb_"; - pw.printf("%s-F_rgba-I_%s-%s-n%03d-%04dx%04d.png", - getSimpleTestName("."), pfmt, drawable.getGLProfile().getName(), i, drawable.getWidth(), drawable.getHeight()); - } - drawable.getGL().glFinish(); // poor mans sync .. - if(screenshot.readPixels(drawable.getGL(), drawable, false)) { - screenshot.write(new File(filename.toString())); - } - } - protected void testWritePNGWithResizeImpl(boolean offscreenLayer) throws InterruptedException { if(!offscreenLayer && JAWTUtil.isOffscreenLayerRequired()) { System.err.println("onscreen layer n/a"); @@ -127,7 +111,7 @@ public class TestGLReadBufferUtilTextureIOWrite02AWT extends UITestCase { if(snap) { System.err.println("XXX: ["+fw_old+", "+dw_old+"], "+fw+"x"+fh+", "+dw+"x"+dh+", sz_changed "+sz_changed+", snap "+snap); c=0; - snapshot(drawable, screenshot, i++); + snapshot(getSimpleTestName("."), i++, null, drawable.getGL(), screenshot, TextureIO.PNG, null); dw_old = dw; fw_old = fw; Threading.invoke(true, new Runnable() { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite02NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite02NEWT.java index ed0791f7c..d1ffa84cf 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite02NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestGLReadBufferUtilTextureIOWrite02NEWT.java @@ -28,10 +28,6 @@ package com.jogamp.opengl.test.junit.jogl.util.texture; -import java.io.File; -import java.io.PrintWriter; -import java.io.StringWriter; - import com.jogamp.newt.opengl.GLWindow; import javax.media.opengl.GLAutoDrawable; @@ -41,6 +37,7 @@ import javax.media.opengl.GLProfile; import com.jogamp.opengl.util.Animator; import com.jogamp.opengl.util.GLReadBufferUtil; +import com.jogamp.opengl.util.texture.TextureIO; import com.jogamp.opengl.test.junit.util.UITestCase; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; @@ -66,19 +63,6 @@ public class TestGLReadBufferUtilTextureIOWrite02NEWT extends UITestCase { height = 64; } - protected void snapshot(GLAutoDrawable drawable, GLReadBufferUtil screenshot, int i) { - final StringWriter filename = new StringWriter(); - { - final PrintWriter pw = new PrintWriter(filename); - final String pfmt = drawable.getChosenGLCapabilities().getAlphaBits() > 0 ? "rgba" : "rgb_"; - pw.printf("%s-F_rgba-I_%s-%s-n%03d-%04dx%04d.png", - getSimpleTestName("."), pfmt, drawable.getGLProfile().getName(), i, drawable.getWidth(), drawable.getHeight()); - } - if(screenshot.readPixels(drawable.getGL(), drawable, false)) { - screenshot.write(new File(filename.toString())); - } - } - private void testWritePNGWithResizeImpl(boolean offscreen) throws InterruptedException { final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false); final GLCapabilities caps2 = offscreen ? WindowUtilNEWT.fixCaps(caps, false, true, false) : caps; @@ -110,7 +94,7 @@ public class TestGLReadBufferUtilTextureIOWrite02NEWT extends UITestCase { if(snap) { System.err.println("XXX: ["+dw_old+"], "+dw+"x"+dh+", sz_changed "+sz_changed+", snap "+snap); c=0; - snapshot(drawable, screenshot, i++); + snapshot(getSimpleTestName("."), i++, null, drawable.getGL(), screenshot, TextureIO.PNG, null); dw_old = dw; new Thread() { @Override diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGTextureFromFileAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGTextureFromFileAWT.java index 068732696..0d4f2b01e 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGTextureFromFileAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGTextureFromFileAWT.java @@ -52,7 +52,6 @@ import com.jogamp.opengl.util.GLReadBufferUtil; import java.awt.Dimension; import java.awt.Frame; -import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URLConnection; @@ -96,16 +95,10 @@ public class TestPNGTextureFromFileAWT extends UITestCase { testTextureStream = null; } - protected void snapshot(GLAutoDrawable drawable, String filename) { - GLReadBufferUtil screenshot = new GLReadBufferUtil(false, false); - if(screenshot.readPixels(drawable.getGL(), drawable, false)) { - screenshot.write(new File(filename)); - } - } - public void testImpl(boolean useFFP, final InputStream istream, final boolean useAWTIIOP) throws InterruptedException, IOException { + final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false); GLProfile glp; if(useFFP && GLProfile.isAvailable(GLProfile.GL2GL3)) { glp = GLProfile.getGL2GL3(); @@ -137,7 +130,7 @@ public class TestPNGTextureFromFileAWT extends UITestCase { // the bug submitter was doing it final GLEventListener gle = useFFP ? new TextureDraw01GL2Listener( texData ) : new TextureDraw01ES2Listener( texData ) ; glc.addGLEventListener(gle); - glc.addGLEventListener(new GLEventListener() { + glc.addGLEventListener(new GLEventListener() { boolean shot = false; @Override public void init(GLAutoDrawable drawable) {} @@ -147,7 +140,7 @@ public class TestPNGTextureFromFileAWT extends UITestCase { // 1 snapshot if(null!=((TextureDraw01Accessor)gle).getTexture() && !shot) { shot = true; - snapshot(drawable, getSimpleTestName(".")+".png"); + snapshot(getSimpleTestName("."), 0, null, drawable.getGL(), screenshot, TextureIO.PNG, null); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGTextureFromFileNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGTextureFromFileNEWT.java index d973dea2d..b4faafbe7 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGTextureFromFileNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGTextureFromFileNEWT.java @@ -48,7 +48,6 @@ import com.jogamp.opengl.util.texture.TextureIO; import com.jogamp.opengl.util.Animator; import com.jogamp.opengl.util.GLReadBufferUtil; -import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URLConnection; @@ -80,14 +79,8 @@ public class TestPNGTextureFromFileNEWT extends UITestCase { testTextureStream = null; } - protected void snapshot(GLAutoDrawable drawable, String filename) { - GLReadBufferUtil screenshot = new GLReadBufferUtil(false, false); - if(screenshot.readPixels(drawable.getGL(), drawable, false)) { - screenshot.write(new File(filename)); - } - } - public void testImpl(boolean useFFP, final InputStream istream) throws InterruptedException, IOException { + final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false); GLProfile glp; if(useFFP && GLProfile.isAvailable(GLProfile.GL2GL3)) { glp = GLProfile.getGL2GL3(); @@ -119,7 +112,7 @@ public class TestPNGTextureFromFileNEWT extends UITestCase { // 1 snapshot if(null!=((TextureDraw01Accessor)gle).getTexture() && !shot) { shot = true; - snapshot(drawable, getSimpleTestName(".")+".png"); + snapshot(getSimpleTestName("."), 0, null, drawable.getGL(), screenshot, TextureIO.PNG, null); } } diff --git a/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java b/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java index 672675fab..c07d5b741 100644 --- a/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java +++ b/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java @@ -28,7 +28,17 @@ package com.jogamp.opengl.test.junit.util; +import java.io.File; +import java.io.PrintWriter; +import java.io.StringWriter; + +import javax.media.opengl.GL; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLDrawable; + import com.jogamp.common.util.locks.SingletonInstance; +import com.jogamp.opengl.util.GLReadBufferUtil; +import com.jogamp.opengl.util.texture.TextureIO; import org.junit.Assume; import org.junit.Before; @@ -108,6 +118,49 @@ public abstract class UITestCase { } static final String unsupportedTestMsg = "Test not supported on this platform."; - + + /** + * Takes a snapshot of the drawable's current framebuffer. Example filenames: + *
      +     * TestFBODrawableNEWT.test01-F_rgba-I_rgba-S0_default-GL2-n0004-0800x0600.png
      +     * TestFBODrawableNEWT.test01-F_rgba-I_rgba-S0_default-GL2-n0005-0800x0600.png
      +     * 
      + * + * @param simpleTestName will be used as the filename prefix + * @param sn sequential number + * @param postSNDetail optional detail to be added to the filename after sn + * @param gl the current GL context object. It's read drawable is being used as the pixel source and to gather some details which will end up in the filename. + * @param readBufferUtil the {@link GLReadBufferUtil} to be used to read the pixels for the screenshot. + * @param fileSuffix Optional file suffix without a dot defining the file type, i.e. "png". + * If null the "png" as defined in {@link TextureIO#PNG} is being used. + * @param destPath Optional platform dependent file path. It shall use {@link File#separatorChar} as is directory separator. + * It shall not end with a directory separator, {@link File#separatorChar}. + * If null the current working directory is being used. + */ + public static void snapshot(String simpleTestName, int sn, String postSNDetail, GL gl, GLReadBufferUtil readBufferUtil, String fileSuffix, String destPath) { + if(null == fileSuffix) { + fileSuffix = TextureIO.PNG; + } + final StringWriter filenameSW = new StringWriter(); + { + final GLDrawable drawable = gl.getContext().getGLReadDrawable(); + final GLCapabilitiesImmutable caps = drawable.getChosenGLCapabilities(); + final String F_pfmt = readBufferUtil.hasAlpha() ? "rgba" : "rgb_"; + final String pfmt = caps.getAlphaBits() > 0 ? "rgba" : "rgb_"; + final String aaext = caps.getSampleExtension(); + final int samples = caps.getNumSamples() ; + postSNDetail = null != postSNDetail ? "-"+postSNDetail : ""; + final PrintWriter pw = new PrintWriter(filenameSW); + pw.printf("%s-n%04d%s-F_%s-I_%s-S%d_%s-%s-%04dx%04d.%s", + simpleTestName, sn, postSNDetail, F_pfmt, pfmt, samples, aaext, drawable.getGLProfile().getName(), + drawable.getWidth(), drawable.getHeight(), fileSuffix); + } + final String filename = null != destPath ? destPath + File.separator + filenameSW.toString() : filenameSW.toString(); + System.err.println(Thread.currentThread().getName()+": ** screenshot: "+filename); + gl.glFinish(); // just make sure rendering finished .. + if(readBufferUtil.readPixels(gl, false)) { + readBufferUtil.write(new File(filename)); + } + } } -- cgit v1.2.3 From 4a08de4511a627c3d87d6a33debbd561962c0312 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 20 Jul 2012 14:08:49 +0200 Subject: GLCapabilities Native Aquisition: Set alpha bits at last - due to it's auto setting by setSampleBuffers(true) and setBackgroundOpaque(false) This bug lead to X11 GLCapabilities rgba: 8/8/8/1 - which ofc is invalid. Sideeffect was a bad selected GLXFB configuration and the GLContext couldn't be made current. Patch sets alpha bits reflecting reality carefully after opaque/samples. Added API doc note. --- .../media/opengl/DefaultGLCapabilitiesChooser.java | 3 +- .../jogamp/opengl/GLGraphicsConfigurationUtil.java | 4 +- .../opengl/egl/EGLGraphicsConfiguration.java | 37 +++++++-------- .../egl/EGLGraphicsConfigurationFactory.java | 8 ++-- .../macosx/cgl/MacOSXCGLGraphicsConfiguration.java | 5 ++- .../opengl/windows/wgl/WGLGLCapabilities.java | 8 +++- .../jogamp/opengl/x11/glx/X11GLXContext.java | 2 +- .../x11/glx/X11GLXGraphicsConfiguration.java | 52 +++++++++++----------- .../javax/media/nativewindow/Capabilities.java | 15 +++++-- .../junit/jogl/caps/TestMultisampleES2NEWT.java | 9 ++-- .../test/junit/jogl/caps/TestTranslucencyAWT.java | 1 - .../parenting/TestTranslucentParentingAWT.java | 1 - 12 files changed, 82 insertions(+), 63 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java index 1b84bd9bd..5fa8ce32d 100644 --- a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java +++ b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java @@ -117,6 +117,7 @@ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { final int availnum = available.size(); if (DEBUG) { + Thread.dumpStack(); System.err.println("Desired: " + gldes); System.err.println("Available: " + availnum); for (int i = 0; i < available.size(); i++) { @@ -241,7 +242,7 @@ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { if (i > 0) { System.err.print(","); } - System.err.print(" " + scores[i]); + System.err.print(" " + i +": " + scores[i]); } System.err.println(" ]"); } diff --git a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java index 900d6a2a0..3f38f33bc 100644 --- a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java +++ b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java @@ -177,14 +177,16 @@ public class GLGraphicsConfigurationUtil { return capsRequested; } + /** Fix opaque setting while preserve alpha bits */ public static GLCapabilitiesImmutable fixOpaqueGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean isOpaque) { GLCapabilities caps2 = null; if( capsRequested.isBackgroundOpaque() != isOpaque) { - // fix caps .. + final int alphaBits = capsRequested.getAlphaBits(); caps2 = (GLCapabilities) capsRequested.cloneMutable(); caps2.setBackgroundOpaque(isOpaque); + caps2.setAlphaBits(alphaBits); return caps2; } return capsRequested; diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java index 214b36493..73867fb40 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java @@ -209,24 +209,6 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple return false; } - if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_RED_SIZE, val)) { - caps.setRedBits(val.get(0)); - } - if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_GREEN_SIZE, val)) { - caps.setGreenBits(val.get(0)); - } - if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_BLUE_SIZE, val)) { - caps.setBlueBits(val.get(0)); - } - if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_ALPHA_SIZE, val)) { - caps.setAlphaBits(val.get(0)); - } - if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_STENCIL_SIZE, val)) { - caps.setStencilBits(val.get(0)); - } - if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_DEPTH_SIZE, val)) { - caps.setDepthBits(val.get(0)); - } if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_SAMPLES, val)) { caps.setSampleBuffers(val.get(0)>0?true:false); caps.setNumSamples(val.get(0)); @@ -262,6 +244,25 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple caps.setTransparentAlphaValue(val.get(0)==EGL.EGL_DONT_CARE?-1:val.get(0)); } */ } + // ALPHA shall be set at last - due to it's auto setting by the above (!opaque / samples) + if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_RED_SIZE, val)) { + caps.setRedBits(val.get(0)); + } + if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_GREEN_SIZE, val)) { + caps.setGreenBits(val.get(0)); + } + if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_BLUE_SIZE, val)) { + caps.setBlueBits(val.get(0)); + } + if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_ALPHA_SIZE, val)) { + caps.setAlphaBits(val.get(0)); + } + if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_STENCIL_SIZE, val)) { + caps.setStencilBits(val.get(0)); + } + if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_DEPTH_SIZE, val)) { + caps.setDepthBits(val.get(0)); + } return GLGraphicsConfigurationUtil.addGLCapabilitiesPermutations(capsBucket, caps, drawableTypeBits ); } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java index 6be9cb547..d79c351a0 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java @@ -253,12 +253,12 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact // // rgb888 - d16, s4 final GLCapabilities fixedCaps = new GLCapabilities(glp); + fixedCaps.setSampleBuffers(true); + fixedCaps.setNumSamples(4); fixedCaps.setRedBits(8); fixedCaps.setGreenBits(8); fixedCaps.setBlueBits(8); fixedCaps.setDepthBits(16); - fixedCaps.setSampleBuffers(true); - fixedCaps.setNumSamples(4); if( !capsChosen.isOnscreen() ) { fixedCaps.setOnscreen(false); fixedCaps.setPBuffer(capsChosen.isPBuffer()); @@ -291,12 +291,12 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact // // rgb565 - d16, s4 final GLCapabilities fixedCaps = new GLCapabilities(glp); + fixedCaps.setSampleBuffers(true); + fixedCaps.setNumSamples(4); fixedCaps.setRedBits(5); fixedCaps.setGreenBits(6); fixedCaps.setBlueBits(5); fixedCaps.setDepthBits(16); - fixedCaps.setSampleBuffers(true); - fixedCaps.setNumSamples(4); if( !capsChosen.isOnscreen() ) { fixedCaps.setOnscreen(false); fixedCaps.setPBuffer(capsChosen.isPBuffer()); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java index 421e1ef96..202644bb3 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java @@ -281,6 +281,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration glp = GLProfile.get(GLProfile.GL2); } GLCapabilities caps = new GLCapabilities(glp); + int alphaBits = 0; for (int i = 0; i < len; i++) { int attr = cglInternalAttributeToken[i+off]; switch (attr) { @@ -317,7 +318,8 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration break; case CGL.NSOpenGLPFAAlphaSize: - caps.setAlphaBits(ivalues[i]); + // ALPHA shall be set at last - due to it's auto setting by !opaque / samples + alphaBits = ivalues[i]; break; case CGL.NSOpenGLPFADepthSize: @@ -350,6 +352,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration break; } } + caps.setAlphaBits(alphaBits); return caps; } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java index e255a0672..6a4ce5a4e 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java @@ -52,10 +52,11 @@ public class WGLGLCapabilities extends GLCapabilities { public boolean setValuesByGDI() { arb_pixelformat = -1; + // ALPHA shall be set at last - due to it's auto setting by !opaque / samples setRedBits(pfd.getCRedBits()); setGreenBits(pfd.getCGreenBits()); setBlueBits(pfd.getCBlueBits()); - setAlphaBits(pfd.getCAlphaBits()); + setAlphaBits(pfd.getCAlphaBits()); setAccumRedBits(pfd.getCAccumRedBits()); setAccumGreenBits(pfd.getCAccumGreenBits()); setAccumBlueBits(pfd.getCAccumBlueBits()); @@ -77,6 +78,7 @@ public class WGLGLCapabilities extends GLCapabilities { public boolean setValuesByARB(final int[] iattribs, final int niattribs, final int[] iresults) { arb_pixelformat = 1; + int alphaBits = 0; for (int i = 0; i < niattribs; i++) { int attr = iattribs[i]; switch (attr) { @@ -143,7 +145,8 @@ public class WGLGLCapabilities extends GLCapabilities { break; case WGLExt.WGL_ALPHA_BITS_ARB: - setAlphaBits(iresults[i]); + // ALPHA shall be set at last - due to it's auto setting by !opaque / samples + alphaBits = iresults[i]; break; case WGLExt.WGL_ACCUM_RED_BITS_ARB: @@ -174,6 +177,7 @@ public class WGLGLCapabilities extends GLCapabilities { throw new GLException("Unknown pixel format attribute " + iattribs[i]); } } + setAlphaBits(alphaBits); return true; } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java index e6b74a769..e1e25be67 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java @@ -152,7 +152,7 @@ public abstract class X11GLXContext extends GLContextImpl { throw new InternalError("Given readDrawable but no driver support"); } } catch (RuntimeException re) { - if(TRACE_SWITCH) { + if(DEBUG || TRACE_SWITCH) { System.err.println(getThreadName()+": Warning: X11GLXContext.glXMakeContextCurrent failed: "+re+", with "+ "dpy "+toHexString(dpy)+ ", write "+toHexString(writeDrawable)+ diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java index b5b80e0b3..95b1cc457 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java @@ -308,19 +308,6 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem } GLCapabilities res = new X11GLCapabilities(visualInfo, fbcfg, fbcfgid, glp); - res.setDoubleBuffered(glXGetFBConfig(display, fbcfg, GLX.GLX_DOUBLEBUFFER, tmp, 0) != 0); - res.setStereo (glXGetFBConfig(display, fbcfg, GLX.GLX_STEREO, tmp, 0) != 0); - res.setHardwareAccelerated(glXGetFBConfig(display, fbcfg, GLX.GLX_CONFIG_CAVEAT, tmp, 0) != GLX.GLX_SLOW_CONFIG); - res.setDepthBits (glXGetFBConfig(display, fbcfg, GLX.GLX_DEPTH_SIZE, tmp, 0)); - res.setStencilBits (glXGetFBConfig(display, fbcfg, GLX.GLX_STENCIL_SIZE, tmp, 0)); - res.setRedBits (glXGetFBConfig(display, fbcfg, GLX.GLX_RED_SIZE, tmp, 0)); - res.setGreenBits (glXGetFBConfig(display, fbcfg, GLX.GLX_GREEN_SIZE, tmp, 0)); - res.setBlueBits (glXGetFBConfig(display, fbcfg, GLX.GLX_BLUE_SIZE, tmp, 0)); - res.setAlphaBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ALPHA_SIZE, tmp, 0)); - res.setAccumRedBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_RED_SIZE, tmp, 0)); - res.setAccumGreenBits(glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_GREEN_SIZE, tmp, 0)); - res.setAccumBlueBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_BLUE_SIZE, tmp, 0)); - res.setAccumAlphaBits(glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_ALPHA_SIZE, tmp, 0)); if (isMultisampleAvailable) { res.setSampleBuffers(glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLE_BUFFERS, tmp, 0) != 0); res.setNumSamples (glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLES, tmp, 0)); @@ -336,6 +323,20 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem res.setTransparentBlueValue(xrmask.getBlueMask()); res.setTransparentAlphaValue(alphaMask); } + // ALPHA shall be set at last - due to it's auto setting by the above (!opaque / samples) + res.setDoubleBuffered(glXGetFBConfig(display, fbcfg, GLX.GLX_DOUBLEBUFFER, tmp, 0) != 0); + res.setStereo (glXGetFBConfig(display, fbcfg, GLX.GLX_STEREO, tmp, 0) != 0); + res.setHardwareAccelerated(glXGetFBConfig(display, fbcfg, GLX.GLX_CONFIG_CAVEAT, tmp, 0) != GLX.GLX_SLOW_CONFIG); + res.setRedBits (glXGetFBConfig(display, fbcfg, GLX.GLX_RED_SIZE, tmp, 0)); + res.setGreenBits (glXGetFBConfig(display, fbcfg, GLX.GLX_GREEN_SIZE, tmp, 0)); + res.setBlueBits (glXGetFBConfig(display, fbcfg, GLX.GLX_BLUE_SIZE, tmp, 0)); + res.setAlphaBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ALPHA_SIZE, tmp, 0)); + res.setAccumRedBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_RED_SIZE, tmp, 0)); + res.setAccumGreenBits(glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_GREEN_SIZE, tmp, 0)); + res.setAccumBlueBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_BLUE_SIZE, tmp, 0)); + res.setAccumAlphaBits(glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_ALPHA_SIZE, tmp, 0)); + res.setDepthBits (glXGetFBConfig(display, fbcfg, GLX.GLX_DEPTH_SIZE, tmp, 0)); + res.setStencilBits (glXGetFBConfig(display, fbcfg, GLX.GLX_STENCIL_SIZE, tmp, 0)); try { res.setPbufferFloatingPointBuffers(glXGetFBConfig(display, fbcfg, GLXExt.GLX_FLOAT_COMPONENTS_NV, tmp, 0) != GL.GL_FALSE); @@ -429,18 +430,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem // Note: use of hardware acceleration is determined by // glXCreateContext, not by the XVisualInfo. Optimistically claim // that all GLCapabilities have the capability to be hardware - // accelerated. - res.setHardwareAccelerated(true); - res.setDepthBits (glXGetConfig(display, info, GLX.GLX_DEPTH_SIZE, tmp, 0)); - res.setStencilBits (glXGetConfig(display, info, GLX.GLX_STENCIL_SIZE, tmp, 0)); - res.setRedBits (glXGetConfig(display, info, GLX.GLX_RED_SIZE, tmp, 0)); - res.setGreenBits (glXGetConfig(display, info, GLX.GLX_GREEN_SIZE, tmp, 0)); - res.setBlueBits (glXGetConfig(display, info, GLX.GLX_BLUE_SIZE, tmp, 0)); - res.setAlphaBits (glXGetConfig(display, info, GLX.GLX_ALPHA_SIZE, tmp, 0)); - res.setAccumRedBits (glXGetConfig(display, info, GLX.GLX_ACCUM_RED_SIZE, tmp, 0)); - res.setAccumGreenBits(glXGetConfig(display, info, GLX.GLX_ACCUM_GREEN_SIZE, tmp, 0)); - res.setAccumBlueBits (glXGetConfig(display, info, GLX.GLX_ACCUM_BLUE_SIZE, tmp, 0)); - res.setAccumAlphaBits(glXGetConfig(display, info, GLX.GLX_ACCUM_ALPHA_SIZE, tmp, 0)); + // accelerated. if (isMultisampleEnabled) { res.setSampleBuffers(glXGetConfig(display, info, GLX.GLX_SAMPLE_BUFFERS, tmp, 0) != 0); res.setNumSamples (glXGetConfig(display, info, GLX.GLX_SAMPLES, tmp, 0)); @@ -456,6 +446,18 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem res.setTransparentBlueValue(xrmask.getBlueMask()); res.setTransparentAlphaValue(alphaMask); } + // ALPHA shall be set at last - due to it's auto setting by the above (!opaque / samples) + res.setHardwareAccelerated(true); + res.setDepthBits (glXGetConfig(display, info, GLX.GLX_DEPTH_SIZE, tmp, 0)); + res.setStencilBits (glXGetConfig(display, info, GLX.GLX_STENCIL_SIZE, tmp, 0)); + res.setRedBits (glXGetConfig(display, info, GLX.GLX_RED_SIZE, tmp, 0)); + res.setGreenBits (glXGetConfig(display, info, GLX.GLX_GREEN_SIZE, tmp, 0)); + res.setBlueBits (glXGetConfig(display, info, GLX.GLX_BLUE_SIZE, tmp, 0)); + res.setAlphaBits (glXGetConfig(display, info, GLX.GLX_ALPHA_SIZE, tmp, 0)); + res.setAccumRedBits (glXGetConfig(display, info, GLX.GLX_ACCUM_RED_SIZE, tmp, 0)); + res.setAccumGreenBits(glXGetConfig(display, info, GLX.GLX_ACCUM_GREEN_SIZE, tmp, 0)); + res.setAccumBlueBits (glXGetConfig(display, info, GLX.GLX_ACCUM_BLUE_SIZE, tmp, 0)); + res.setAccumAlphaBits(glXGetConfig(display, info, GLX.GLX_ACCUM_ALPHA_SIZE, tmp, 0)); return GLGraphicsConfigurationUtil.addGLCapabilitiesPermutations(capsBucket, res, drawableTypeBits); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java index 196f23598..cb33aec5e 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java +++ b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java @@ -211,9 +211,18 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { 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. */ + /** + * 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. + *

      + * Note: If alpha bits are zero, they are set to one + * by {@link #setBackgroundOpaque(boolean)} and it's OpenGL specialization GLCapabilities::setSampleBuffers(boolean).
      + * Ensure to call this method after the above to ensure a zero value.
      + * The above automated settings takes into account, that the user calls this method to request alpha bits, + * not to reflect a current state. Nevertheless if this is the case - call it at last. + *

      + */ public void setAlphaBits(int alphaBits) { this.alphaBits = alphaBits; } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES2NEWT.java index b2dad1f39..02fcae6ef 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES2NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES2NEWT.java @@ -57,7 +57,6 @@ import com.jogamp.opengl.util.texture.TextureIO; public class TestMultisampleES2NEWT extends UITestCase { static long durationPerTest = 60; // ms - private GLWindow window; public static void main(String[] args) { for(int i=0; i0?true:false)); window.addGLEventListener(new GLEventListener() { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestTranslucencyAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestTranslucencyAWT.java index 8e720965c..7cce5d1e4 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestTranslucencyAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestTranslucencyAWT.java @@ -65,7 +65,6 @@ public class TestTranslucencyAWT extends UITestCase { public static void initClass() { size = new Dimension(400,200); glCaps = new GLCapabilities(null); - glCaps.setAlphaBits(8); glCaps.setBackgroundOpaque(false); } diff --git a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestTranslucentParentingAWT.java b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestTranslucentParentingAWT.java index 57b8517a6..373c83fce 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestTranslucentParentingAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestTranslucentParentingAWT.java @@ -69,7 +69,6 @@ public class TestTranslucentParentingAWT extends UITestCase { public static void initClass() { size = new Dimension(400,200); glCaps = new GLCapabilities(null); - glCaps.setAlphaBits(8); glCaps.setBackgroundOpaque(false); } -- cgit v1.2.3 From 72785ac35aa7c95bc675f3d773c6a7764b5b0ddc Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 20 Jul 2012 15:44:00 +0200 Subject: Fix OSX regression of commit 20bf031db719f7baa4c6e74734fc999061e08fe2 - handling w/ non NSView handles (pbuffer) --- .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 17 ++++++++++++++++- .../jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java | 4 ++++ .../opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java | 6 ++++++ src/jogl/native/macosx/MacOSXWindowSystemInterface.m | 2 +- .../classes/jogamp/nativewindow/macosx/OSXUtil.java | 5 +++++ src/nativewindow/native/macosx/OSXmisc.m | 6 ++++++ 6 files changed, 38 insertions(+), 2 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 4bf2a3c9d..cb79e1560 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -54,6 +54,7 @@ import javax.media.opengl.GLContext; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; +import jogamp.nativewindow.macosx.OSXUtil; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableImpl; import jogamp.opengl.GLGraphicsConfigurationUtil; @@ -430,6 +431,19 @@ public abstract class MacOSXCGLContext extends GLContextImpl @Override public long create(long share, int ctp, int major, int minor) { long ctx = 0; + final long nsViewHandle; + if(drawable instanceof MacOSXCGLDrawable) { + // we allow null here! (special pbuffer case) + nsViewHandle = ((MacOSXCGLDrawable)MacOSXCGLContext.this.drawable).getNSViewHandle(); + } else { + // we only allow a valid NSView here + final long aHandle = drawable.getHandle(); + if( OSXUtil.isNSView(aHandle) ) { + nsViewHandle = aHandle; + } else { + throw new RuntimeException("Anonymous drawable instance's handle not of type NSView: "+drawable.getClass().getName()+", "+drawable); + } + } final NativeSurface surface = drawable.getNativeSurface(); final MacOSXCGLGraphicsConfiguration config = (MacOSXCGLGraphicsConfiguration) surface.getGraphicsConfiguration(); final OffscreenLayerSurface backingLayerHost = NativeWindowFactory.getOffscreenLayerSurface(surface, true); @@ -456,6 +470,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl System.err.println("NS create chosenCaps: "+chosenCaps); System.err.println("NS create pixelFormat: "+toHexString(pixelFormat)); System.err.println("NS create drawable native-handle: "+toHexString(drawable.getHandle())); + System.err.println("NS create drawable NSView-handle: "+toHexString(nsViewHandle)); System.err.println("NS create screen refresh-rate: "+sRefreshRate+" hz, "+screenVSyncTimeout+" micros"); // Thread.dumpStack(); } @@ -463,7 +478,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl int[] viewNotReady = new int[1]; // Try to allocate a context with this ctx = CGL.createContext(share, - drawable.getHandle(), allowIncompleteView, + nsViewHandle, allowIncompleteView, pixelFormat, chosenCaps.isBackgroundOpaque(), viewNotReady, 0); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java index 841edb2b0..af767f0c3 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java @@ -105,6 +105,10 @@ public abstract class MacOSXCGLDrawable extends GLDrawableImpl { @Override protected void setRealizedImpl() { } + + protected long getNSViewHandle() { + return GLBackendType.NSOPENGL == openGLMode ? getHandle() : 0; + } protected void registerContext(MacOSXCGLContext ctx) { // NOTE: we need to keep track of the created contexts in order to diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java index b144c020d..8f2f386af 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java @@ -94,6 +94,12 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { registerContext(ctx); return ctx; } + + @Override + protected long getNSViewHandle() { + // pbuffer handle is NSOpenGLPixelBuffer + return 0; + } @Override public long getHandle() { diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m index d3f703142..f774f8f4a 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m @@ -515,7 +515,7 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, DBG_PRINT("createContext.0: share %p, view %p, allowIncompleteView %d, pixfmt %p, opaque %d\n", share, view, (int)allowIncompleteView, fmt, opaque); - if (view != NULL) { + if (view != nil) { Bool viewReady = true; if(!allowIncompleteView) { diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 99fc9244e..4767dff18 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -59,6 +59,10 @@ public class OSXUtil { return false; } + public static boolean isNSView(long object) { + return isNSView0(object); + } + public static Point GetLocationOnScreen(long windowOrView, int src_x, int src_y) { return (Point) GetLocationOnScreen0(windowOrView, src_x, src_y); } @@ -129,6 +133,7 @@ public class OSXUtil { } */ private static native boolean initIDs0(); + private static native boolean isNSView0(long object); private static native Object GetLocationOnScreen0(long windowOrView, int src_x, int src_y); private static native long CreateNSWindow0(int x, int y, int width, int height); private static native void DestroyNSWindow0(long nsWindow); diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index ebfefe345..37fa4c88f 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -92,6 +92,12 @@ Java_jogamp_nativewindow_macosx_OSXUtil_initIDs0(JNIEnv *env, jclass _unused) { return JNI_TRUE; } +JNIEXPORT jboolean JNICALL +Java_jogamp_nativewindow_macosx_OSXUtil_isNSView0(JNIEnv *env, jclass _unused, jlong object) { + NSObject *nsObj = (NSObject*) (intptr_t) object; + return [nsObj isMemberOfClass:[NSView class]]; +} + /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: getLocationOnScreen0 -- cgit v1.2.3 From e58e7739379147af8c7b875f6e8a7cdb40e342bc Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 20 Jul 2012 22:05:32 +0200 Subject: Fix OSX OffscreenLayerSurface (OLS) regressions (pbuffer based) - Use pbuffer (still), don't set FBO (invisible) - OLS (only impl is JAWTWindow now) stores the attached layer handle created and attached by the GLContext implementation, so 'others' may detach it -> NewtCanvasAWT - NewtCanvasAWT.removeNotify() needs to ask the OLS to detach the layer since it's parent will be gone. - MacOSXCGLContext destroy allows a removed OLS (see above) --- make/scripts/tests.sh | 5 ++--- .../classes/jogamp/opengl/GLDrawableFactoryImpl.java | 5 +++-- .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 13 +++++++------ .../com/jogamp/nativewindow/awt/JAWTWindow.java | 18 +++++++++++++++--- .../media/nativewindow/OffscreenLayerSurface.java | 9 +++++++-- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 10 ++++++++-- 6 files changed, 42 insertions(+), 18 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index af99b8e72..19297ae25 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -407,10 +407,9 @@ function testawtswt() { # osx: #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01GLCanvasAWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer02NewtCanvasAWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES2NEWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01GLCanvasAWT $* +testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer02NewtCanvasAWT $* $spath/count-edt-start.sh java-run.log diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index 897d3fcaf..34bb8704a 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -143,9 +143,10 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { // layered surface -> Offscreen/[FBO|PBuffer] final GLCapabilities chosenCapsMod = (GLCapabilities) chosenCaps.cloneMutable(); chosenCapsMod.setOnscreen(false); - if( isFBOAvailable ) { + /* if( isFBOAvailable ) { // FIXME JAU: FBO n/a yet chosenCapsMod.setFBO(true); - } else if(canCreateGLPbuffer(adevice)) { + } else */ + if( canCreateGLPbuffer(adevice) ) { chosenCapsMod.setPBuffer(true); } else { chosenCapsMod.setFBO(false); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index cb79e1560..82525cfde 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -444,9 +444,10 @@ public abstract class MacOSXCGLContext extends GLContextImpl throw new RuntimeException("Anonymous drawable instance's handle not of type NSView: "+drawable.getClass().getName()+", "+drawable); } } - final NativeSurface surface = drawable.getNativeSurface(); + final NativeSurface surface = drawable.getNativeSurface(); final MacOSXCGLGraphicsConfiguration config = (MacOSXCGLGraphicsConfiguration) surface.getGraphicsConfiguration(); final OffscreenLayerSurface backingLayerHost = NativeWindowFactory.getOffscreenLayerSurface(surface, true); + boolean allowIncompleteView = null != backingLayerHost; if( !allowIncompleteView && surface instanceof ProxySurface ) { allowIncompleteView = 0 != ( ProxySurface.INVISIBLE_WINDOW & ((ProxySurface)surface).getImplBitfield() ) ; @@ -519,10 +520,10 @@ public abstract class MacOSXCGLContext extends GLContextImpl texWidth = drawable.getWidth(); texHeight = drawable.getHeight(); } - nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, nsOpenGLLayerPFmt, drawable.getHandle(), fixedCaps.isBackgroundOpaque(), texWidth, texHeight); if(0>=texWidth || 0>=texHeight || !drawable.isRealized()) { throw new GLException("Drawable not realized yet or invalid texture size, texSize "+texWidth+"x"+texHeight+", "+drawable); } + nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, nsOpenGLLayerPFmt, drawable.getHandle(), fixedCaps.isBackgroundOpaque(), texWidth, texHeight); if (DEBUG) { System.err.println("NS create nsOpenGLLayer "+toHexString(nsOpenGLLayer)+", texSize "+texWidth+"x"+texHeight+", "+drawable); } @@ -545,11 +546,11 @@ public abstract class MacOSXCGLContext extends GLContextImpl System.err.println("NS destroy nsOpenGLLayer "+toHexString(nsOpenGLLayer)); } final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(surface, true); - if(null == ols) { - throw new InternalError("XXX: "+ols); + if(null != ols && ols.isSurfaceLayerAttached()) { + // still having a valid OLS attached to surface (parent OLS could have been removed) + ols.detachSurfaceLayer(); } - CGL.releaseNSOpenGLLayer(nsOpenGLLayer); - ols.detachSurfaceLayer(nsOpenGLLayer); + CGL.releaseNSOpenGLLayer(nsOpenGLLayer); CGL.deletePixelFormat(nsOpenGLLayerPFmt); nsOpenGLLayerPFmt = 0; nsOpenGLLayer = 0; diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index cffe495f7..d4b927cf1 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -81,6 +81,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected long drawable; protected Rectangle bounds; protected Insets insets; + private long offscreenSurfaceLayer; private long drawable_old; @@ -106,6 +107,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, invalidate(); this.component = windowObject; this.isApplet = false; + this.offscreenSurfaceLayer = 0; } @Override @@ -196,6 +198,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, System.err.println("JAWTWindow.attachSurfaceHandle(): 0x"+Long.toHexString(layerHandle) + ", bounds "+bounds); } attachSurfaceLayerImpl(layerHandle); + offscreenSurfaceLayer = layerHandle; } finally { unlockSurface(); } @@ -206,25 +209,34 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, * {@inheritDoc} */ @Override - public final void detachSurfaceLayer(final long layerHandle) throws NativeWindowException { + public final void detachSurfaceLayer() throws NativeWindowException { if( !isOffscreenLayerSurfaceEnabled() ) { throw new java.lang.UnsupportedOperationException("Not an offscreen layer surface"); } + if( 0 == offscreenSurfaceLayer) { + throw new NativeWindowException("No offscreen layer attached: "+this); + } int lockRes = lockSurface(); if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { throw new NativeWindowException("Could not lock (offscreen layer): "+this); } try { if(DEBUG) { - System.err.println("JAWTWindow.detachSurfaceHandle(): 0x"+Long.toHexString(layerHandle)); + System.err.println("JAWTWindow.detachSurfaceHandle(): 0x"+Long.toHexString(offscreenSurfaceLayer)); } - detachSurfaceLayerImpl(layerHandle); + detachSurfaceLayerImpl(offscreenSurfaceLayer); + offscreenSurfaceLayer = 0; } finally { unlockSurface(); } } protected abstract void detachSurfaceLayerImpl(final long layerHandle); + @Override + public final boolean isSurfaceLayerAttached() { + return 0 != offscreenSurfaceLayer; + } + // // SurfaceUpdateListener // diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index dd36509ba..f7dbc6c27 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -42,7 +42,12 @@ public interface OffscreenLayerSurface { * Detaches a previously attached offscreen layer from this offscreen layer surface. * @see #attachSurfaceLayer(long) * @see #isOffscreenLayerSurfaceEnabled() - * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false + * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false + * or no surface layer is attached. */ - public void detachSurfaceLayer(final long layerHandle) throws NativeWindowException; + public void detachSurfaceLayer() throws NativeWindowException; + + /** Returns true if a surface layer is attached, otherwise false. */ + public boolean isSurfaceLayerAttached(); + } diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 9af4a02ae..cd0e9aab6 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -42,7 +42,9 @@ import java.security.PrivilegedAction; import java.util.Set; import javax.media.nativewindow.NativeWindow; +import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.OffscreenLayerOption; +import javax.media.nativewindow.OffscreenLayerSurface; import javax.media.nativewindow.WindowClosingProtocol; import javax.swing.MenuSelectionManager; @@ -368,6 +370,10 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto if(DEBUG) { System.err.println("NewtCanvasAWT.removeNotify: "+newtChild+", from "+cont); } + final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(newtChild, true); + if(null != ols && ols.isSurfaceLayerAttached()) { + ols.detachSurfaceLayer(); + } reparentWindow(false, cont); super.removeNotify(); } @@ -413,7 +419,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto // since this it is completely covered by the newtChild (z-order). setFocusable(true); } else { - configureNewtChild(false); + configureNewtChild(false); newtChild.setVisible(false); newtChild.reparentWindow(null); if(null != jawtWindow) { @@ -445,7 +451,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto NewtFactoryAWT.destroyNativeWindow(jawtWindow); jawtWindow=null; } - newtChild.setVisible(false); + newtChild.setVisible(false); newtChild.reparentWindow(null); newtChild.destroy(); newtChild=null; -- cgit v1.2.3 From 00bef95008b02cc71e166da122884402e9381f44 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 24 Jul 2012 00:14:02 +0200 Subject: Fix GraphicsConfigurationFactory: Map factory to device-type _and_ capabilities-type; Add a pre-set nativeVisualID to chooseGraphicsConfiguration(..) Map factory to device-type _and_ capabilities-type: - Allows using different GraphicsConfigurationFactory implementations for different capabilities-types. Previous impl. failed to use an OpenGL agnostic CapabilitiesImmutable for 'chooseGraphicsConfiguration(..)' since only the GL aware factory was mapped. The latter failed since it expected a GLCapabilitiesImmutable. - The passed capabilities-type as well as device-type given at getFactory(..) is traversed top-to-down to find a most suitable factory: For-All devT := getTopDownDeviceTypes(deviceType) For-All capsT := getTopDownCapabilitiesTypes(capabilitiesType) f = factory.get(devT, capsT); if(f) { return f; } end end Add a pre-set nativeVisualID to chooseGraphicsConfiguration(..) - In situations where a native visualID is already chosen [by external means for example], but we still need to query a matching GraphicsConfiguration - we require to pass a non VisualIDHolder.VID_UNDEFINED nativeVisualID. We had a hack implemented before within some implementations and their static calls, however an agnostic mechanism is required to implement new NativeSurface/Window's platform agnostic. - X11GLXGraphicsConfigurationFactory: respect a pre-set xvisualID - X11GLXDrawableFactory.createProxySurfaceImpl(..) queries the given windowHandle's visualID and 'chooses' the configuration accordingly. If the visualID is undefined an exception is thrown, since window is invalid. These mechanics are implicit for Windows and OSX. Fix X11GLXGraphicsConfiguration.updateGraphicsConfiguration(): - Skip any action if a valid X11GLCapabilities is already chosen, i.e. w/ visualID. Otherwise choose a suitable configuration incl. visualID. The latter is quite impossible and invalid, since visualID must be defined at window creation time and the update method is issued with a valid window. X11 - Misc: - Added 'int jogamp.nativewindow.x11.X11Lib.GetVisualIDFromWindow(..)' - All returned visualID's are of type 'int' --- make/config/nativewindow/x11-CustomJavaCode.java | 4 +- .../javax/media/opengl/GLDrawableFactory.java | 3 +- .../classes/javax/media/opengl/awt/GLCanvas.java | 9 +- .../jogamp/opengl/GLDrawableFactoryImpl.java | 3 + .../opengl/egl/EGLGraphicsConfiguration.java | 6 +- .../egl/EGLGraphicsConfigurationFactory.java | 16 +- .../cgl/MacOSXCGLGraphicsConfigurationFactory.java | 4 +- .../MacOSXAWTCGLGraphicsConfigurationFactory.java | 8 +- .../WindowsWGLGraphicsConfigurationFactory.java | 4 +- .../WindowsAWTWGLGraphicsConfigurationFactory.java | 8 +- .../opengl/x11/glx/X11ExternalGLXContext.java | 5 +- .../opengl/x11/glx/X11GLXDrawableFactory.java | 15 +- .../x11/glx/X11GLXGraphicsConfiguration.java | 29 ++- .../glx/X11GLXGraphicsConfigurationFactory.java | 113 ++++++++--- .../nativewindow/awt/AWTGraphicsConfiguration.java | 4 +- .../jogamp/nativewindow/x11/X11GraphicsDevice.java | 2 +- .../jogamp/nativewindow/x11/X11GraphicsScreen.java | 2 +- .../nativewindow/GraphicsConfigurationFactory.java | 226 +++++++++++++++++---- .../DefaultGraphicsConfigurationFactoryImpl.java | 2 +- .../x11/X11GraphicsConfigurationFactory.java | 18 +- .../awt/X11AWTGraphicsConfigurationFactory.java | 16 +- src/nativewindow/native/x11/Xmisc.c | 30 ++- src/newt/classes/jogamp/newt/OffscreenWindow.java | 5 +- .../classes/jogamp/newt/driver/awt/AWTCanvas.java | 6 +- .../jogamp/newt/driver/broadcom/egl/Window.java | 5 +- .../jogamp/newt/driver/intel/gdl/Window.java | 4 +- .../classes/jogamp/newt/driver/kd/KDWindow.java | 5 +- .../jogamp/newt/driver/macosx/MacWindow.java | 5 +- .../jogamp/newt/driver/windows/WindowsWindow.java | 5 +- .../classes/jogamp/newt/driver/x11/X11Window.java | 4 +- 30 files changed, 422 insertions(+), 144 deletions(-) (limited to 'src/nativewindow') diff --git a/make/config/nativewindow/x11-CustomJavaCode.java b/make/config/nativewindow/x11-CustomJavaCode.java index 73439fcc7..56aec4725 100644 --- a/make/config/nativewindow/x11-CustomJavaCode.java +++ b/make/config/nativewindow/x11-CustomJavaCode.java @@ -24,7 +24,9 @@ /** Entry point to C language function: XVisualInfo * XGetVisualInfo(Display * , long, XVisualInfo * , int * ); */ private static native java.nio.ByteBuffer XGetVisualInfo1(long arg0, long arg1, java.nio.ByteBuffer arg2, Object arg3, int arg3_byte_offset); - public static native long DefaultVisualID(long display, int screen); + public static native int GetVisualIDFromWindow(long display, long window); + + public static native int DefaultVisualID(long display, int screen); public static native long CreateDummyWindow(long display, int screen_index, int visualID, int width, int height); public static native void DestroyDummyWindow(long display, long window); diff --git a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java index 612a02f14..9a0d2cb99 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java @@ -434,7 +434,8 @@ public abstract class GLDrawableFactory { /** * Creates a proxy {@link NativeSurface} w/ defined surface handle, i.e. a {@link WrappedSurface} or {@link GDISurface} instance. *

      - * It's {@link AbstractGraphicsConfiguration} is properly set according to the given {@link GLCapabilitiesImmutable}. + * It's {@link AbstractGraphicsConfiguration} is properly set according to the given + * windowHandle's native visualID if set or the given {@link GLCapabilitiesImmutable}. *

      *

      * Lifecycle (destruction) of the given surface handle shall be handled by the caller. diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 694a081b8..03fd78ac7 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -60,6 +60,7 @@ import java.util.ArrayList; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.OffscreenLayerOption; +import javax.media.nativewindow.VisualIDHolder; import javax.media.nativewindow.WindowClosingProtocol; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; @@ -1062,9 +1063,9 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing if( EventQueue.isDispatchThread() || Thread.holdsLock(getTreeLock()) ) { config = (AWTGraphicsConfiguration) - GraphicsConfigurationFactory.getFactory(AWTGraphicsDevice.class).chooseGraphicsConfiguration(capsChosen, + GraphicsConfigurationFactory.getFactory(AWTGraphicsDevice.class, GLCapabilitiesImmutable.class).chooseGraphicsConfiguration(capsChosen, capsRequested, - chooser, aScreen); + chooser, aScreen, VisualIDHolder.VID_UNDEFINED); } else { try { final ArrayList bucket = new ArrayList(1); @@ -1072,9 +1073,9 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing @Override public void run() { AWTGraphicsConfiguration c = (AWTGraphicsConfiguration) - GraphicsConfigurationFactory.getFactory(AWTGraphicsDevice.class).chooseGraphicsConfiguration(capsChosen, + GraphicsConfigurationFactory.getFactory(AWTGraphicsDevice.class, GLCapabilitiesImmutable.class).chooseGraphicsConfiguration(capsChosen, capsRequested, - chooser, aScreen); + chooser, aScreen, VisualIDHolder.VID_UNDEFINED); bucket.add(c); } }); diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index 34bb8704a..f092288fb 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -381,6 +381,9 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { if(null == device) { throw new GLException("No shared device for requested: "+deviceReq); } + if(0 == windowHandle) { + throw new IllegalArgumentException("Null windowHandle"); + } device.lock(); try { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java index 73867fb40..716a6e6f1 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java @@ -42,6 +42,7 @@ import java.util.List; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.DefaultGLCapabilitiesChooser; @@ -96,9 +97,10 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple } void updateGraphicsConfiguration() { + CapabilitiesImmutable capsChosen = getChosenCapabilities(); EGLGraphicsConfiguration newConfig = (EGLGraphicsConfiguration) - GraphicsConfigurationFactory.getFactory(getScreen().getDevice()).chooseGraphicsConfiguration( - getChosenCapabilities(), getRequestedCapabilities(), chooser, getScreen()); + GraphicsConfigurationFactory.getFactory(getScreen().getDevice(), capsChosen).chooseGraphicsConfiguration( + capsChosen, getRequestedCapabilities(), chooser, getScreen(), VisualIDHolder.VID_UNDEFINED); if(null!=newConfig) { // FIXME: setScreen( ... ); setChosenCapabilities(newConfig.getChosenCapabilities()); diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java index d79c351a0..0b21d2054 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java @@ -81,27 +81,27 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact // become the pre-selector for X11/.. to match the native visual id w/ EGL, if native ES is selected final String nwType = NativeWindowFactory.getNativeWindowType(false); if(NativeWindowFactory.TYPE_X11 == nwType) { - nativeGraphicsConfigurationFactory = GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, eglFactory); + nativeGraphicsConfigurationFactory = GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, GLCapabilitiesImmutable.class, eglFactory); } /* else if(NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false)) { nativeGraphicsConfigurationFactory = GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.windows.WindowsGraphicsDevice.class, eglFactory); } else if(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false)) { } */ // become the selector for KD/EGL .. - kdeglGraphicsConfigurationFactory = GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.egl.EGLGraphicsDevice.class, eglFactory); + kdeglGraphicsConfigurationFactory = GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.egl.EGLGraphicsDevice.class, GLCapabilitiesImmutable.class, eglFactory); } static void unregisterFactory() { final String nwType = NativeWindowFactory.getNativeWindowType(false); if(NativeWindowFactory.TYPE_X11 == nwType) { - GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, nativeGraphicsConfigurationFactory); + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, GLCapabilitiesImmutable.class, nativeGraphicsConfigurationFactory); } /* else if(NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false)) { GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.windows.WindowsGraphicsDevice.class, nativeGraphicsConfigurationFactory); } else if(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false)) { } */ nativeGraphicsConfigurationFactory = null; - GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.egl.EGLGraphicsDevice.class, kdeglGraphicsConfigurationFactory); + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.egl.EGLGraphicsDevice.class, GLCapabilitiesImmutable.class, kdeglGraphicsConfigurationFactory); kdeglGraphicsConfigurationFactory = null; } @@ -110,7 +110,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl ( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, - CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen) { + CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { if (absScreen == null) { throw new IllegalArgumentException("This NativeWindowFactory accepts only AbstractGraphicsDevice objects"); } @@ -140,7 +140,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact cfg = chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable) capsChosen, (GLCapabilitiesImmutable) capsRequested, (GLCapabilitiesChooser) chooser, - absScreen, VisualIDHolder.VID_UNDEFINED, false); + absScreen, nativeVisualID, false); } else { // handle non native cases (X11, ..) if(null == nativeGraphicsConfigurationFactory) { @@ -154,7 +154,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact cfg = chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable) capsChosen, (GLCapabilitiesImmutable) capsRequested, (GLCapabilitiesChooser) chooser, - absScreen, VisualIDHolder.VID_UNDEFINED, false); + absScreen, nativeVisualID, false); if(null == cfg || VisualIDHolder.VID_UNDEFINED == cfg.getVisualID(VIDType.NATIVE)) { cfg = null; if(DEBUG) { @@ -167,7 +167,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(DEBUG) { System.err.println("EGLGraphicsConfigurationFactory.choose..: Delegate to "+nativeGraphicsConfigurationFactory.getClass().getSimpleName()); } - cfg = nativeGraphicsConfigurationFactory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, absScreen); + cfg = nativeGraphicsConfigurationFactory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, absScreen, nativeVisualID); } } return cfg; diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java index 1a9070aef..f138e7557 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java @@ -50,14 +50,14 @@ import javax.media.opengl.GLCapabilitiesImmutable; public class MacOSXCGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFactory { static void registerFactory() { - GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice.class, new MacOSXCGLGraphicsConfigurationFactory()); + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice.class, GLCapabilitiesImmutable.class, new MacOSXCGLGraphicsConfigurationFactory()); } private MacOSXCGLGraphicsConfigurationFactory() { } protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, - CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen) { + CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { return chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, absScreen, false); } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java index a6fa01bad..edf9b7c84 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java @@ -58,14 +58,14 @@ import jogamp.opengl.macosx.cgl.MacOSXCGLGraphicsConfiguration; public class MacOSXAWTCGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFactory { public static void registerFactory() { - GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, new MacOSXAWTCGLGraphicsConfigurationFactory()); + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, GLCapabilitiesImmutable.class, new MacOSXAWTCGLGraphicsConfigurationFactory()); } private MacOSXAWTCGLGraphicsConfigurationFactory() { } protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, - CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen) { + CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { GraphicsDevice device = null; if (absScreen != null && !(absScreen instanceof AWTGraphicsScreen)) { @@ -103,9 +103,9 @@ public class MacOSXAWTCGLGraphicsConfigurationFactory extends GLGraphicsConfigur GraphicsConfiguration gc = device.getDefaultConfiguration(); MacOSXCGLGraphicsConfiguration macConfig = (MacOSXCGLGraphicsConfiguration) - GraphicsConfigurationFactory.getFactory(macDevice).chooseGraphicsConfiguration(capsChosen, + GraphicsConfigurationFactory.getFactory(macDevice, capsChosen).chooseGraphicsConfiguration(capsChosen, capsRequested, - chooser, macScreen); + chooser, macScreen, nativeVisualID); if (macConfig == null) { throw new GLException("Unable to choose a GraphicsConfiguration: "+capsChosen+",\n\t"+chooser+"\n\t"+macScreen); diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java index 943c7fec4..00ed91bb4 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java @@ -69,13 +69,13 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat static VisualIDHolder.VIDComparator PfdIDComparator = new VisualIDHolder.VIDComparator(VisualIDHolder.VIDType.WIN32_PFD); static void registerFactory() { - GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.windows.WindowsGraphicsDevice.class, new WindowsWGLGraphicsConfigurationFactory()); + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.windows.WindowsGraphicsDevice.class, GLCapabilitiesImmutable.class, new WindowsWGLGraphicsConfigurationFactory()); } private WindowsWGLGraphicsConfigurationFactory() { } protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( - CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen) { + CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { if (! (capsChosen instanceof GLCapabilitiesImmutable) ) { throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilities objects - chosen"); diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java index bd64b58a4..3b2ff133a 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java @@ -63,14 +63,14 @@ import javax.media.opengl.GLDrawableFactory; public class WindowsAWTWGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFactory { public static void registerFactory() { - GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, new WindowsAWTWGLGraphicsConfigurationFactory()); + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, GLCapabilitiesImmutable.class, new WindowsAWTWGLGraphicsConfigurationFactory()); } private WindowsAWTWGLGraphicsConfigurationFactory() { } protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, - CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen) { + CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { GraphicsDevice device = null; if (absScreen != null && !(absScreen instanceof AWTGraphicsScreen)) { @@ -105,11 +105,11 @@ public class WindowsAWTWGLGraphicsConfigurationFactory extends GLGraphicsConfigu WindowsGraphicsDevice winDevice = new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); DefaultGraphicsScreen winScreen = new DefaultGraphicsScreen(winDevice, awtScreen.getIndex()); - GraphicsConfigurationFactory configFactory = GraphicsConfigurationFactory.getFactory(winDevice); + GraphicsConfigurationFactory configFactory = GraphicsConfigurationFactory.getFactory(winDevice, capsChosen); WindowsWGLGraphicsConfiguration winConfig = (WindowsWGLGraphicsConfiguration) configFactory.chooseGraphicsConfiguration(capsChosen, capsRequested, - chooser, winScreen); + chooser, winScreen, nativeVisualID); if (winConfig == null) { throw new GLException("Unable to choose a GraphicsConfiguration: "+capsChosen+",\n\t"+chooser+"\n\t"+winScreen); } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java index b847363e0..1f3edbd8a 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java @@ -41,6 +41,7 @@ package jogamp.opengl.x11.glx; import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; @@ -94,9 +95,9 @@ public class X11ExternalGLXContext extends X11GLXContext { // of 0, which doesn't work in a subsequent call to glXChooseFBConfig; if this happens, // create and use a default config (this has been observed when running on CentOS 5.5 inside // of VMWare Server 2.0 with the Mesa 6.5.1 drivers) - if( X11GLXGraphicsConfiguration.GLXFBConfigIDValid(display, x11Screen.getIndex(), val[0]) ) { + if( VisualIDHolder.VID_UNDEFINED == val[0] || !X11GLXGraphicsConfiguration.GLXFBConfigIDValid(display, x11Screen.getIndex(), val[0]) ) { GLCapabilities glcapsDefault = new GLCapabilities(GLProfile.getDefault()); - cfg = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(glcapsDefault, glcapsDefault, null, x11Screen); + cfg = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(glcapsDefault, glcapsDefault, null, x11Screen, VisualIDHolder.VID_UNDEFINED); if(DEBUG) { System.err.println("X11ExternalGLXContext invalid FBCONFIG_ID "+val[0]+", using default cfg: " + cfg); } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index 8ffbf3951..b2e74f9d4 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -50,6 +50,7 @@ import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; +import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; @@ -514,7 +515,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { device = (X11GraphicsDevice)deviceReq; } final X11GraphicsScreen screen = new X11GraphicsScreen(device, 0); - final X11GLXGraphicsConfiguration config = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen); + final X11GLXGraphicsConfiguration config = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED); if(null == config) { throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); } @@ -582,7 +583,17 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { final X11GraphicsDevice device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), NativeWindowFactory.getNullToolkitLock(), true); final X11GraphicsScreen screen = new X11GraphicsScreen(device, screenIdx); - final X11GLXGraphicsConfiguration cfg = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen); + final int xvisualID = X11Lib.GetVisualIDFromWindow(device.getHandle(), windowHandle); + if(VisualIDHolder.VID_UNDEFINED == xvisualID) { + throw new GLException("Undefined VisualID of window 0x"+Long.toHexString(windowHandle)+", window probably invalid"); + } + if(DEBUG) { + System.err.println("X11GLXDrawableFactory.createProxySurfaceImpl 0x"+Long.toHexString(windowHandle)+": visualID 0x"+Integer.toHexString(xvisualID)); + } + final X11GLXGraphicsConfiguration cfg = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen, xvisualID); + if(DEBUG) { + System.err.println("X11GLXDrawableFactory.createProxySurfaceImpl 0x"+Long.toHexString(windowHandle)+": "+cfg); + } return new WrappedSurface(cfg, windowHandle, 0, 0, upstream); } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java index 95b1cc457..b458fffe1 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java @@ -37,7 +37,9 @@ import java.util.ArrayList; import java.util.List; import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.GraphicsConfigurationFactory; +import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.DefaultGLCapabilitiesChooser; import javax.media.opengl.GL; import javax.media.opengl.GLCapabilities; @@ -102,16 +104,25 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem } void updateGraphicsConfiguration() { - X11GLXGraphicsConfiguration newConfig = (X11GLXGraphicsConfiguration) - GraphicsConfigurationFactory.getFactory(getScreen().getDevice()).chooseGraphicsConfiguration( - getChosenCapabilities(), getRequestedCapabilities(), chooser, getScreen()); - if(null!=newConfig) { - // FIXME: setScreen( ... ); - setXVisualInfo(newConfig.getXVisualInfo()); - setChosenCapabilities(newConfig.getChosenCapabilities()); - if(DEBUG) { - System.err.println("updateGraphicsConfiguration: "+this); + final CapabilitiesImmutable aChosenCaps = getChosenCapabilities(); + if( !(aChosenCaps instanceof X11GLCapabilities) || VisualIDHolder.VID_UNDEFINED == aChosenCaps.getVisualID(VIDType.X11_XVISUAL) ) { + // This case is actually quite impossible, since on X11 the visualID and hence GraphicsConfiguration + // must be determined _before_ window creation! + final X11GLXGraphicsConfiguration newConfig = (X11GLXGraphicsConfiguration) + GraphicsConfigurationFactory.getFactory(getScreen().getDevice(), aChosenCaps).chooseGraphicsConfiguration( + aChosenCaps, getRequestedCapabilities(), chooser, getScreen(), VisualIDHolder.VID_UNDEFINED); + if(null!=newConfig) { + // FIXME: setScreen( ... ); + setXVisualInfo(newConfig.getXVisualInfo()); + setChosenCapabilities(newConfig.getChosenCapabilities()); + if(DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.updateGraphicsConfiguration updated:"+this); + } + } else { + throw new GLException("No native VisualID pre-chosen and update failed: "+this); } + } else if (DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.updateGraphicsConfiguration kept:"+this); } } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java index 331401c06..234b06bdb 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java @@ -40,6 +40,7 @@ import javax.media.nativewindow.CapabilitiesChooser; import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.VisualIDHolder; +import javax.media.nativewindow.VisualIDHolder.VIDType; import javax.media.opengl.DefaultGLCapabilitiesChooser; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; @@ -74,20 +75,24 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF static GraphicsConfigurationFactory fallbackX11GraphicsConfigurationFactory = null; static void registerFactory() { final GraphicsConfigurationFactory newFactory = new X11GLXGraphicsConfigurationFactory(); - final GraphicsConfigurationFactory oldFactory = GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, newFactory); + final GraphicsConfigurationFactory oldFactory = GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, GLCapabilitiesImmutable.class, newFactory); if(oldFactory == newFactory) { throw new InternalError("GraphicsConfigurationFactory lifecycle impl. error"); } - if(null == oldFactory) { - throw new InternalError("Missing fallback GraphicsConfigurationFactory"); + if(null != oldFactory) { + fallbackX11GraphicsConfigurationFactory = oldFactory; + } else { + fallbackX11GraphicsConfigurationFactory = GraphicsConfigurationFactory.getFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, CapabilitiesImmutable.class); + if( null == fallbackX11GraphicsConfigurationFactory ) { + throw new InternalError("Missing fallback GraphicsConfigurationFactory"); + } } - fallbackX11GraphicsConfigurationFactory = oldFactory; } private X11GLXGraphicsConfigurationFactory() { } protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( - CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen) { + CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { if (!(absScreen instanceof X11GraphicsScreen)) { throw new IllegalArgumentException("Only X11GraphicsScreen are allowed here"); } @@ -109,12 +114,12 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF if(DEBUG) { System.err.println("No GLX available, fallback to "+fallbackX11GraphicsConfigurationFactory.getClass().getSimpleName()+" for: "+absScreen); } - return fallbackX11GraphicsConfigurationFactory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, absScreen); + return fallbackX11GraphicsConfigurationFactory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, absScreen, VisualIDHolder.VID_UNDEFINED); } throw new InternalError("No GLX and no fallback GraphicsConfigurationFactory available for: "+absScreen); } return chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested, - (GLCapabilitiesChooser)chooser, (X11GraphicsScreen)absScreen); + (GLCapabilitiesChooser)chooser, (X11GraphicsScreen)absScreen, nativeVisualID); } protected static List getAvailableCapabilities(X11GLXDrawableFactory factory, AbstractGraphicsDevice device) { @@ -199,7 +204,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF static X11GLXGraphicsConfiguration chooseGraphicsConfigurationStatic(GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsReq, GLCapabilitiesChooser chooser, - X11GraphicsScreen x11Screen) { + X11GraphicsScreen x11Screen, int xvisualID) { if (x11Screen == null) { throw new IllegalArgumentException("AbstractGraphicsScreen is null"); } @@ -215,19 +220,19 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF X11GLXGraphicsConfiguration res = null; if( factory.isGLXVersionGreaterEqualOneThree(x11Device) ) { - res = chooseGraphicsConfigurationFBConfig(capsChosen, capsReq, chooser, x11Screen); + res = chooseGraphicsConfigurationFBConfig(capsChosen, capsReq, chooser, x11Screen, xvisualID); } if(null==res) { if(usePBuffer) { - throw new GLException("Error: Couldn't create X11GLXGraphicsConfiguration based on FBConfig for "+capsChosen); + throw new GLException("Error: Couldn't create X11GLXGraphicsConfiguration based on FBConfig for visualID "+toHexString(xvisualID)+", "+capsChosen); } - res = chooseGraphicsConfigurationXVisual(capsChosen, capsReq, chooser, x11Screen); + res = chooseGraphicsConfigurationXVisual(capsChosen, capsReq, chooser, x11Screen, xvisualID); } if(null==res) { - throw new GLException("Error: Couldn't create X11GLXGraphicsConfiguration based on FBConfig and XVisual for "+capsChosen); + throw new GLException("Error: Couldn't create X11GLXGraphicsConfiguration based on FBConfig and XVisual for visualID "+toHexString(xvisualID)+", "+x11Screen+", "+capsChosen); } if(DEBUG) { - System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationStatic("+x11Screen+","+capsChosen+"): "+res); + System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationStatic(visualID "+toHexString(xvisualID)+", "+x11Screen+","+capsChosen+"): "+res); } return res; } @@ -253,7 +258,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF private static X11GLXGraphicsConfiguration chooseGraphicsConfigurationFBConfig(GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsReq, GLCapabilitiesChooser chooser, - X11GraphicsScreen x11Screen) { + X11GraphicsScreen x11Screen, int xvisualID) { int recommendedIndex = -1; PointerBuffer fbcfgsL = null; GLProfile glProfile = capsChosen.getGLProfile(); @@ -273,8 +278,11 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF int[] count = { -1 }; List availableCaps = new ArrayList(); final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, useFBO); - // 1st choice: get GLCapabilities based on users GLCapabilities setting recommendedIndex as preferred choice - fbcfgsL = GLX.glXChooseFBConfig(display, screen, attribs, 0, count, 0); + // 1st choice: get GLCapabilities based on users GLCapabilities setting recommendedIndex as preferred choice, + // skipped if xvisualID is given + if( VisualIDHolder.VID_UNDEFINED == xvisualID ) { + fbcfgsL = GLX.glXChooseFBConfig(display, screen, attribs, 0, count, 0); + } if (fbcfgsL != null && fbcfgsL.limit()>0) { for (int i = 0; i < fbcfgsL.limit(); i++) { if( !X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(availableCaps, glProfile, absDevice, fbcfgsL.get(i), winattrmask, isMultisampleAvailable) ) { @@ -317,6 +325,33 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } } } + + if(DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: got configs: "+availableCaps.size()); + for(int i=0; i chosenIndex ) { if (DEBUG) { @@ -333,7 +368,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF private static X11GLXGraphicsConfiguration chooseGraphicsConfigurationXVisual(GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsReq, GLCapabilitiesChooser chooser, - X11GraphicsScreen x11Screen) { + X11GraphicsScreen x11Screen, int xvisualID) { if (chooser == null) { chooser = new DefaultGLCapabilitiesChooser(); } @@ -351,14 +386,18 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF final boolean isMultisampleAvailable = factory.isGLXMultisampleAvailable(absDevice); int[] attribs = X11GLXGraphicsConfiguration.GLCapabilities2AttribList(capsChosen, false, isMultisampleAvailable, display, screen); + XVisualInfo recommendedVis = null; // 1st choice: get GLCapabilities based on users GLCapabilities setting recommendedIndex as preferred choice - XVisualInfo recommendedVis = GLX.glXChooseVisual(display, screen, attribs, 0); - if (DEBUG) { - System.err.print("glXChooseVisual recommended "); - if (recommendedVis == null) { - System.err.println("null visual"); - } else { - System.err.println("visual id " + toHexString(recommendedVis.getVisualid())); + // skipped if xvisualID is given + if( VisualIDHolder.VID_UNDEFINED == xvisualID ) { + recommendedVis = GLX.glXChooseVisual(display, screen, attribs, 0); + if (DEBUG) { + System.err.print("glXChooseVisual recommended "); + if (recommendedVis == null) { + System.err.println("null visual"); + } else { + System.err.println("visual id " + toHexString(recommendedVis.getVisualid())); + } } } @@ -384,6 +423,32 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } } + if(DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationXVisual: got configs: "+availableCaps.size()); + for(int i=0; i chosenIndex ) { if (DEBUG) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java index 61d5e5c0d..2a152ff35 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java @@ -95,8 +95,8 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple GraphicsConfiguration gc = awtGraphicsDevice.getDefaultConfiguration(); capsChosen = AWTGraphicsConfiguration.setupCapabilitiesRGBABits(capsRequested, gc); } - final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(awtDevice); - final AbstractGraphicsConfiguration config = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, null, awtScreen); + final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(awtDevice, capsChosen); + final AbstractGraphicsConfiguration config = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, null, awtScreen, VisualIDHolder.VID_UNDEFINED); if(config instanceof AWTGraphicsConfiguration) { return (AWTGraphicsConfiguration) config; } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index 7a98e3c25..5e4d6f41a 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -88,7 +88,7 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl // It still could be an AWT hold handle .. final long display = getHandle(); final int scrnIdx = X11Lib.DefaultScreen(display); - return (int) X11Lib.DefaultVisualID(display, scrnIdx); + return X11Lib.DefaultVisualID(display, scrnIdx); } @Override diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java index 014f4f688..5f3c220ca 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java @@ -58,7 +58,7 @@ public class X11GraphicsScreen extends DefaultGraphicsScreen implements Cloneabl public int getVisualID() { // It still could be an AWT hold handle .. - return (int) X11Lib.DefaultVisualID(getDevice().getHandle(), getIndex()); + return X11Lib.DefaultVisualID(getDevice().getHandle(), getIndex()); } private static int fetchScreen(X11GraphicsDevice device, int screen) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java index 2610f2cfa..c3fdc6798 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java @@ -36,9 +36,15 @@ package javax.media.nativewindow; import com.jogamp.common.util.ReflectionUtil; import jogamp.nativewindow.Debug; import jogamp.nativewindow.DefaultGraphicsConfigurationFactoryImpl; + +import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; +import java.util.Iterator; +import java.util.List; import java.util.Map; +import java.util.Set; /** * Provides the mechanism by which the graphics configuration for a @@ -59,8 +65,43 @@ import java.util.Map; public abstract class GraphicsConfigurationFactory { protected static final boolean DEBUG; - private static Map, GraphicsConfigurationFactory> registeredFactories; - private static Class abstractGraphicsDeviceClass; + private static class DeviceCapsType { + public final Class deviceType; + public final Class capsType; + private final int hash32; + + public DeviceCapsType(Class deviceType, Class capsType) { + this.deviceType = deviceType; + this.capsType = capsType; + + // 31 * x == (x << 5) - x + int hash32 = 31 + deviceType.hashCode(); + hash32 = ((hash32 << 5) - hash32) + capsType.hashCode(); + this.hash32 = hash32; + } + + public final int hashCode() { + return hash32; + } + + public final boolean equals(Object obj) { + if(this == obj) { return true; } + if (obj instanceof DeviceCapsType) { + DeviceCapsType dct = (DeviceCapsType)obj; + return deviceType == dct.deviceType && capsType == dct.capsType; + } + return false; + } + + @Override + public final String toString() { + return "DeviceCapsType["+deviceType.getName()+", "+capsType.getName()+"]"; + } + + } + + private static final Map registeredFactories; + private static final DeviceCapsType defaultDeviceCapsType; static boolean initialized = false; static { @@ -69,7 +110,8 @@ public abstract class GraphicsConfigurationFactory { System.err.println(Thread.currentThread().getName()+" - Info: GraphicsConfigurationFactory."); // Thread.dumpStack(); } - abstractGraphicsDeviceClass = javax.media.nativewindow.AbstractGraphicsDevice.class; + registeredFactories = Collections.synchronizedMap(new HashMap()); + defaultDeviceCapsType = new DeviceCapsType(AbstractGraphicsDevice.class, CapabilitiesImmutable.class); } public static synchronized void initSingleton() { @@ -79,14 +121,13 @@ public abstract class GraphicsConfigurationFactory { if(DEBUG) { System.err.println(Thread.currentThread().getName()+" - GraphicsConfigurationFactory.initSingleton()"); } - registeredFactories = Collections.synchronizedMap(new HashMap, GraphicsConfigurationFactory>()); // Register the default no-op factory for arbitrary // AbstractGraphicsDevice implementations, including // AWTGraphicsDevice instances -- the OpenGL binding will take // care of handling AWTGraphicsDevices on X11 platforms (as // well as X11GraphicsDevices in non-AWT situations) - registerFactory(abstractGraphicsDeviceClass, new DefaultGraphicsConfigurationFactoryImpl()); + registerFactory(defaultDeviceCapsType.deviceType, defaultDeviceCapsType.capsType, new DefaultGraphicsConfigurationFactoryImpl()); if (NativeWindowFactory.TYPE_X11.equals(NativeWindowFactory.getNativeWindowType(true))) { try { @@ -112,7 +153,6 @@ public abstract class GraphicsConfigurationFactory { System.err.println(Thread.currentThread().getName()+" - GraphicsConfigurationFactory.shutdown()"); } registeredFactories.clear(); - registeredFactories = null; } } @@ -133,74 +173,175 @@ public abstract class GraphicsConfigurationFactory { protected GraphicsConfigurationFactory() { } - /** Returns the factory for use with the given type of - AbstractGraphicsDevice. */ - public static GraphicsConfigurationFactory getFactory(AbstractGraphicsDevice device) { + /** + * Returns the graphics configuration factory for use with the + * given device and capability. + * + * @see #getFactory(Class, Class) + */ + public static GraphicsConfigurationFactory getFactory(AbstractGraphicsDevice device, CapabilitiesImmutable caps) { if (device == null) { - return getFactory(AbstractGraphicsDevice.class); + throw new IllegalArgumentException("null device"); + } + if (caps == null) { + throw new IllegalArgumentException("null caps"); } - return getFactory(device.getClass()); + return getFactory(device.getClass(), caps.getClass()); } /** * Returns the graphics configuration factory for use with the - * given class, which must implement the {@link - * AbstractGraphicsDevice} interface. + * given device and capability class. + *

      + * Note: Registered device types maybe classes or interfaces, where capabilities types are interfaces only. + *

      + * + *

      + * Pseudo code for finding a suitable factory is: + *

      +        For-All devT := getTopDownDeviceTypes(deviceType)
      +            For-All capsT := getTopDownCapabilitiesTypes(capabilitiesType)
      +               f = factory.get(devT, capsT);
      +               if(f) { return f; }
      +            end
      +        end
      +     * 
      + *

      * - * @throws IllegalArgumentException if the given class does not implement AbstractGraphicsDevice + * @param deviceType the minimum capabilities class type accepted, must implement or extend {@link AbstractGraphicsDevice} + * @param capabilitiesType the minimum capabilities class type accepted, must implement or extend {@link CapabilitiesImmutable} + * + * @throws IllegalArgumentException if the deviceType does not implement {@link AbstractGraphicsDevice} or + * capabilitiesType does not implement {@link CapabilitiesImmutable} */ - public static GraphicsConfigurationFactory getFactory(Class abstractGraphicsDeviceImplementor) + public static GraphicsConfigurationFactory getFactory(Class deviceType, Class capabilitiesType) throws IllegalArgumentException, NativeWindowException { - if (!(abstractGraphicsDeviceClass.isAssignableFrom(abstractGraphicsDeviceImplementor))) { + if (!(defaultDeviceCapsType.deviceType.isAssignableFrom(deviceType))) { throw new IllegalArgumentException("Given class must implement AbstractGraphicsDevice"); } - - GraphicsConfigurationFactory factory = null; - Class clazz = abstractGraphicsDeviceImplementor; - while (clazz != null) { - factory = registeredFactories.get(clazz); - if (factory != null) { - if(DEBUG) { - System.err.println("GraphicsConfigurationFactory.getFactory() "+abstractGraphicsDeviceImplementor+" -> "+factory); + if (!(defaultDeviceCapsType.capsType.isAssignableFrom(capabilitiesType))) { + throw new IllegalArgumentException("Given capabilities class must implement CapabilitiesImmutable"); + } + if(DEBUG) { + Thread.dumpStack(); + System.err.println("GraphicsConfigurationFactory.getFactory: "+deviceType.getName()+", "+capabilitiesType.getName()); + dumpFactories(); + } + + final List> deviceTypes = getAllAssignableClassesFrom(defaultDeviceCapsType.deviceType, deviceType, false); + if(DEBUG) { + System.err.println("GraphicsConfigurationFactory.getFactory() deviceTypes: " + deviceTypes); + } + final List> capabilitiesTypes = getAllAssignableClassesFrom(defaultDeviceCapsType.capsType, capabilitiesType, true); + if(DEBUG) { + System.err.println("GraphicsConfigurationFactory.getFactory() capabilitiesTypes: " + capabilitiesTypes); + } + for(int j=0; j interfaceDevice = deviceTypes.get(j); + for(int i=0; i interfaceCaps = capabilitiesTypes.get(i); + final DeviceCapsType dct = new DeviceCapsType(interfaceDevice, interfaceCaps); + final GraphicsConfigurationFactory factory = registeredFactories.get(dct); + if (factory != null) { + if(DEBUG) { + System.err.println("GraphicsConfigurationFactory.getFactory() found "+dct+" -> "+factory); + } + return factory; } - return factory; } - clazz = clazz.getSuperclass(); } // Return the default - factory = registeredFactories.get(abstractGraphicsDeviceClass); + final GraphicsConfigurationFactory factory = registeredFactories.get(defaultDeviceCapsType); if(DEBUG) { - System.err.println("GraphicsConfigurationFactory.getFactory() DEFAULT "+abstractGraphicsDeviceClass+" -> "+factory); + System.err.println("GraphicsConfigurationFactory.getFactory() DEFAULT "+defaultDeviceCapsType+" -> "+factory); } return factory; } + private static ArrayList> getAllAssignableClassesFrom(Class superClassOrInterface, Class fromClass, boolean interfacesOnly) { + // Using a todo list avoiding a recursive loop! + final ArrayList> inspectClasses = new ArrayList>(); + final ArrayList> resolvedInterfaces = new ArrayList>(); + inspectClasses.add(fromClass); + for(int j=0; j clazz = inspectClasses.get(j); + getAllAssignableClassesFrom(superClassOrInterface, clazz, interfacesOnly, resolvedInterfaces, inspectClasses); + } + return resolvedInterfaces; + } + private static void getAllAssignableClassesFrom(Class superClassOrInterface, Class fromClass, boolean interfacesOnly, List> resolvedInterfaces, List> inspectClasses) { + final ArrayList> types = new ArrayList>(); + if( superClassOrInterface.isAssignableFrom(fromClass) && !resolvedInterfaces.contains(fromClass)) { + if( !interfacesOnly || fromClass.isInterface() ) { + types.add(fromClass); + } + } + types.addAll(Arrays.asList(fromClass.getInterfaces())); + + for(int i=0; i iface = types.get(i); + if( superClassOrInterface.isAssignableFrom(iface) && !resolvedInterfaces.contains(iface) ) { + resolvedInterfaces.add(iface); + if( !superClassOrInterface.equals(iface) && !inspectClasses.contains(iface) ) { + inspectClasses.add(iface); // safe add to todo list, avoiding a recursive nature + } + } + } + final Class parentClass = fromClass.getSuperclass(); + if( null != parentClass && superClassOrInterface.isAssignableFrom(parentClass) && !inspectClasses.contains(parentClass) ) { + inspectClasses.add(parentClass); // safe add to todo list, avoiding a recursive nature + } + } + private static void dumpFactories() { + Set dcts = registeredFactories.keySet(); + int i=0; + for(Iterator iter = dcts.iterator(); iter.hasNext(); ) { + DeviceCapsType dct = iter.next(); + System.err.println("Factory #"+i+": "+dct+" -> "+registeredFactories.get(dct)); + i++; + } + } - /** Registers a GraphicsConfigurationFactory handling graphics - * device objects of the given class. This does not need to be - * called by end users, only implementors of new + /** + * Registers a GraphicsConfigurationFactory handling + * the given graphics device and capability class. + *

      + * This does not need to be called by end users, only implementors of new * GraphicsConfigurationFactory subclasses. - * + *

      + * + *

      + * Note: Registered device types maybe classes or interfaces, where capabilities types are interfaces only. + *

      + * + *

      See {@link #getFactory(Class, Class)} for a description of the find algorithm.

      + * + * @param deviceType the minimum capabilities class type accepted, must implement or extend interface {@link AbstractGraphicsDevice} + * @param capabilitiesType the minimum capabilities class type accepted, must extend interface {@link CapabilitiesImmutable} * @return the previous registered factory, or null if none * @throws IllegalArgumentException if the given class does not implement AbstractGraphicsDevice */ - protected static GraphicsConfigurationFactory registerFactory(Class abstractGraphicsDeviceImplementor, GraphicsConfigurationFactory factory) + protected static GraphicsConfigurationFactory registerFactory(Class abstractGraphicsDeviceImplementor, Class capabilitiesType, GraphicsConfigurationFactory factory) throws IllegalArgumentException { - if (!(abstractGraphicsDeviceClass.isAssignableFrom(abstractGraphicsDeviceImplementor))) { - throw new IllegalArgumentException("Given class must implement AbstractGraphicsDevice"); + if (!(defaultDeviceCapsType.deviceType.isAssignableFrom(abstractGraphicsDeviceImplementor))) { + throw new IllegalArgumentException("Given device class must implement AbstractGraphicsDevice"); } + if (!(defaultDeviceCapsType.capsType.isAssignableFrom(capabilitiesType))) { + throw new IllegalArgumentException("Given capabilities class must implement CapabilitiesImmutable"); + } + final DeviceCapsType dct = new DeviceCapsType(abstractGraphicsDeviceImplementor, capabilitiesType); final GraphicsConfigurationFactory prevFactory; if(null == factory) { - prevFactory = registeredFactories.remove(abstractGraphicsDeviceImplementor); + prevFactory = registeredFactories.remove(dct); if(DEBUG) { - System.err.println("GraphicsConfigurationFactory.registerFactory() remove "+abstractGraphicsDeviceImplementor+ + System.err.println("GraphicsConfigurationFactory.registerFactory() remove "+dct+ ", deleting: "+prevFactory); } } else { - prevFactory = registeredFactories.put(abstractGraphicsDeviceImplementor, factory); + prevFactory = registeredFactories.put(dct, factory); if(DEBUG) { - System.err.println("GraphicsConfigurationFactory.registerFactory() put "+abstractGraphicsDeviceImplementor+" -> "+factory+ + System.err.println("GraphicsConfigurationFactory.registerFactory() put "+dct+" -> "+factory+ ", overridding: "+prevFactory); } } @@ -244,6 +385,7 @@ public abstract class GraphicsConfigurationFactory { * @param capsRequested the original requested capabilities * @param chooser the choosing implementation * @param screen the referring Screen + * @param nativeVisualID if not {@link VisualIDHolder#VID_UNDEFINED} it reflects a pre-chosen visualID of the native platform's windowing system. * @return the complete GraphicsConfiguration * * @throws IllegalArgumentException if the data type of the passed @@ -258,7 +400,7 @@ public abstract class GraphicsConfigurationFactory { public final AbstractGraphicsConfiguration chooseGraphicsConfiguration(CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, - AbstractGraphicsScreen screen) + AbstractGraphicsScreen screen, int nativeVisualID) throws IllegalArgumentException, NativeWindowException { if(null==capsChosen) { throw new NativeWindowException("Chosen Capabilities are null"); @@ -275,7 +417,7 @@ public abstract class GraphicsConfigurationFactory { } device.lock(); try { - return chooseGraphicsConfigurationImpl(capsChosen, capsRequested, chooser, screen); + return chooseGraphicsConfigurationImpl(capsChosen, capsRequested, chooser, screen, nativeVisualID); } finally { device.unlock(); } @@ -283,7 +425,7 @@ public abstract class GraphicsConfigurationFactory { protected abstract AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl(CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, - CapabilitiesChooser chooser, AbstractGraphicsScreen screen) + CapabilitiesChooser chooser, AbstractGraphicsScreen screen, int nativeVisualID) throws IllegalArgumentException, NativeWindowException; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java index f34b740d4..52e9c8308 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java @@ -37,7 +37,7 @@ import javax.media.nativewindow.*; public class DefaultGraphicsConfigurationFactoryImpl extends GraphicsConfigurationFactory { protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( - CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen screen) { + CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen screen, int nativeVisualID) { return new DefaultGraphicsConfiguration(screen, capsChosen, capsRequested); } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java index 070f87216..b11dd1df1 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java @@ -39,33 +39,39 @@ import javax.media.nativewindow.CapabilitiesChooser; import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.VisualIDHolder; import com.jogamp.nativewindow.x11.X11GraphicsConfiguration; import com.jogamp.nativewindow.x11.X11GraphicsScreen; public class X11GraphicsConfigurationFactory extends GraphicsConfigurationFactory { public static void registerFactory() { - GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, new X11GraphicsConfigurationFactory()); + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, CapabilitiesImmutable.class, new X11GraphicsConfigurationFactory()); } private X11GraphicsConfigurationFactory() { } protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( - CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen screen) + CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen screen, int nativeVisualID) throws IllegalArgumentException, NativeWindowException { if(!(screen instanceof X11GraphicsScreen)) { throw new NativeWindowException("Only valid X11GraphicsScreen are allowed"); } - final X11Capabilities x11CapsChosen = new X11Capabilities(getXVisualInfo(screen, capsChosen)); - AbstractGraphicsConfiguration res = new X11GraphicsConfiguration((X11GraphicsScreen)screen, x11CapsChosen, capsRequested, x11CapsChosen.getXVisualInfo()); + final X11Capabilities x11CapsChosen; + if(VisualIDHolder.VID_UNDEFINED == nativeVisualID) { + x11CapsChosen = new X11Capabilities(getXVisualInfo(screen, capsChosen)); + } else { + x11CapsChosen = new X11Capabilities(getXVisualInfo(screen, nativeVisualID)); + } + final AbstractGraphicsConfiguration res = new X11GraphicsConfiguration((X11GraphicsScreen)screen, x11CapsChosen, capsRequested, x11CapsChosen.getXVisualInfo()); if(DEBUG) { - System.err.println("X11GraphicsConfigurationFactory.chooseGraphicsConfigurationImpl("+screen+","+capsChosen+"): "+res); + System.err.println("X11GraphicsConfigurationFactory.chooseGraphicsConfigurationImpl(visualID 0x"+Integer.toHexString(nativeVisualID)+", "+screen+","+capsChosen+"): "+res); } return res; } - public static XVisualInfo getXVisualInfo(AbstractGraphicsScreen screen, long visualID) + public static XVisualInfo getXVisualInfo(AbstractGraphicsScreen screen, int visualID) { XVisualInfo xvi_temp = XVisualInfo.create(); xvi_temp.setVisualid(visualID); diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java b/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java index b6bf63d44..1de03e8be 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java @@ -61,14 +61,14 @@ import jogamp.nativewindow.x11.X11Util; public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFactory { public static void registerFactory() { - GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, new X11AWTGraphicsConfigurationFactory()); + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, CapabilitiesImmutable.class, new X11AWTGraphicsConfigurationFactory()); } private X11AWTGraphicsConfigurationFactory() { } protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, - CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen) { + CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { if (absScreen != null && !(absScreen instanceof AWTGraphicsScreen)) { throw new IllegalArgumentException("This GraphicsConfigurationFactory accepts only AWTGraphicsScreen objects"); @@ -77,18 +77,18 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac absScreen = AWTGraphicsScreen.createDefault(); } - return chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, (AWTGraphicsScreen)absScreen); + return chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, (AWTGraphicsScreen)absScreen, nativeVisualID); } public static AWTGraphicsConfiguration chooseGraphicsConfigurationStatic( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, - CapabilitiesChooser chooser, AWTGraphicsScreen awtScreen) { + CapabilitiesChooser chooser, AWTGraphicsScreen awtScreen, int nativeVisualID) { if(DEBUG) { System.err.println("X11AWTGraphicsConfigurationFactory: got "+awtScreen); } final GraphicsDevice device = ((AWTGraphicsDevice)awtScreen.getDevice()).getGraphicsDevice(); - + final long displayHandleAWT = X11SunJDKReflection.graphicsDeviceGetDisplay(device); final long displayHandle; boolean owner = false; @@ -121,8 +121,8 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac System.err.println("X11AWTGraphicsConfigurationFactory: made "+x11Screen); } - final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(x11Device); - AbstractGraphicsConfiguration aConfig = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen); + final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(x11Device, capsChosen); + AbstractGraphicsConfiguration aConfig = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen, nativeVisualID); if (aConfig == null) { throw new NativeWindowException("Unable to choose a GraphicsConfiguration (1): "+capsChosen+",\n\t"+chooser+"\n\t"+x11Screen); } @@ -160,7 +160,7 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac // try again using an AWT Colormodel compatible configuration GraphicsConfiguration gc = device.getDefaultConfiguration(); capsChosen = AWTGraphicsConfiguration.setupCapabilitiesRGBABits(capsChosen, gc); - aConfig = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen); + aConfig = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen, nativeVisualID); if (aConfig == null) { throw new NativeWindowException("Unable to choose a GraphicsConfiguration (2): "+capsChosen+",\n\t"+chooser+"\n\t"+x11Screen); } diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 21771c9aa..fcba8580c 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -362,14 +362,40 @@ Java_jogamp_nativewindow_x11_X11Lib_XGetVisualInfo1__JJLjava_nio_ByteBuffer_2Lja return jbyteCopy; } -JNIEXPORT jlong JNICALL +JNIEXPORT jint JNICALL +Java_jogamp_nativewindow_x11_X11Lib_GetVisualIDFromWindow(JNIEnv *env, jclass _unused, jlong display, jlong window) { + Display * dpy = (Display *)(intptr_t)display; + Window w = (Window) window; + XWindowAttributes xwa; + jlong r = 0; // undefinded + + if(NULL==dpy) { + NativewindowCommon_throwNewRuntimeException(env, "invalid display connection.."); + return; + } + + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 1, 0, 1); + memset(&xwa, 0, sizeof(XWindowAttributes)); + XGetWindowAttributes(dpy, w, &xwa); + if(NULL != xwa.visual) { + r = (jint) XVisualIDFromVisual( xwa.visual ); + } else { + r = 0; + } + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); + + return r; +} + + +JNIEXPORT jint JNICALL Java_jogamp_nativewindow_x11_X11Lib_DefaultVisualID(JNIEnv *env, jclass _unused, jlong display, jint screen) { jlong r; if(0==display) { NativewindowCommon_FatalError(env, "invalid display connection.."); } NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 1, 0, 0); - r = (jlong) XVisualIDFromVisual( DefaultVisual( (Display*) (intptr_t) display, screen ) ); + r = (jint) XVisualIDFromVisual( DefaultVisual( (Display*) (intptr_t) display, screen ) ); NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 0, 0); return r; } diff --git a/src/newt/classes/jogamp/newt/OffscreenWindow.java b/src/newt/classes/jogamp/newt/OffscreenWindow.java index be543aba9..ba98ca3af 100644 --- a/src/newt/classes/jogamp/newt/OffscreenWindow.java +++ b/src/newt/classes/jogamp/newt/OffscreenWindow.java @@ -40,6 +40,7 @@ import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.MutableSurface; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.VisualIDHolder; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.Point; @@ -72,8 +73,8 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { dummySurface.createNotify(); } } */ - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(aScreen.getDevice()).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, aScreen); + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(aScreen.getDevice(), capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, aScreen, VisualIDHolder.VID_UNDEFINED); if (null == cfg) { throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); } diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java b/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java index 5a49dd57c..a7950048a 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java +++ b/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java @@ -46,6 +46,7 @@ import javax.media.nativewindow.CapabilitiesChooser; import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.VisualIDHolder; import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration; @@ -53,6 +54,7 @@ import com.jogamp.nativewindow.awt.AWTGraphicsDevice; import com.jogamp.nativewindow.awt.AWTGraphicsScreen; import com.jogamp.newt.Window; +@SuppressWarnings("serial") public class AWTCanvas extends Canvas { private GraphicsDevice device; private GraphicsConfiguration chosen; @@ -252,9 +254,9 @@ public class AWTCanvas extends Canvas { AWTGraphicsScreen.createScreenDevice(device, AbstractGraphicsDevice.DEFAULT_UNIT): AWTGraphicsScreen.createDefault(); AWTGraphicsConfiguration config = (AWTGraphicsConfiguration) - GraphicsConfigurationFactory.getFactory(AWTGraphicsDevice.class).chooseGraphicsConfiguration(capsChosen, + GraphicsConfigurationFactory.getFactory(AWTGraphicsDevice.class, capsChosen.getClass()).chooseGraphicsConfiguration(capsChosen, capsRequested, - chooser, aScreen); + chooser, aScreen, VisualIDHolder.VID_UNDEFINED); if (config == null) { throw new NativeWindowException("Error: Couldn't fetch AWTGraphicsConfiguration"); } diff --git a/src/newt/classes/jogamp/newt/driver/broadcom/egl/Window.java b/src/newt/classes/jogamp/newt/driver/broadcom/egl/Window.java index ed1d0511a..223ad6484 100644 --- a/src/newt/classes/jogamp/newt/driver/broadcom/egl/Window.java +++ b/src/newt/classes/jogamp/newt/driver/broadcom/egl/Window.java @@ -37,6 +37,7 @@ package jogamp.newt.driver.broadcom.egl; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.VisualIDHolder; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.Point; import javax.media.opengl.GLCapabilitiesImmutable; @@ -57,8 +58,8 @@ public class Window extends jogamp.newt.WindowImpl { } // query a good configuration, however chose the final one by the native queried egl-cfg-id // after creation at {@link #windowCreated(int, int, int)}. - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice()).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen()); + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); if (null == cfg) { throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); } diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java index 09e0e3016..d5c75abd4 100644 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java @@ -54,8 +54,8 @@ public class Window extends jogamp.newt.WindowImpl { final AbstractGraphicsScreen aScreen = getScreen().getGraphicsScreen(); final AbstractGraphicsDevice aDevice = getScreen().getDisplay().getGraphicsDevice(); - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(aDevice).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, aScreen); + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(aDevice, capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, aScreen, VisualIDHolder.VID_UNDEFINED); if (null == cfg) { throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); } diff --git a/src/newt/classes/jogamp/newt/driver/kd/KDWindow.java b/src/newt/classes/jogamp/newt/driver/kd/KDWindow.java index bb76d21ff..9f9d6948e 100644 --- a/src/newt/classes/jogamp/newt/driver/kd/KDWindow.java +++ b/src/newt/classes/jogamp/newt/driver/kd/KDWindow.java @@ -37,6 +37,7 @@ package jogamp.newt.driver.kd; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.VisualIDHolder; import javax.media.nativewindow.VisualIDHolder.VIDType; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.Point; @@ -59,8 +60,8 @@ public class KDWindow extends WindowImpl { if(0!=getParentWindowHandle()) { throw new RuntimeException("Window parenting not supported (yet)"); } - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice()).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen()); + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); if (null == cfg) { throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java index fcca5c843..720d4ee4c 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java @@ -39,6 +39,7 @@ import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.MutableSurface; +import javax.media.nativewindow.VisualIDHolder; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.InsetsImmutable; import javax.media.nativewindow.util.Point; @@ -61,8 +62,8 @@ public class MacWindow extends WindowImpl implements MutableSurface, DriverClear @Override protected void createNativeImpl() { - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice()).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen()); + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); if (null == cfg) { throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); } diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java b/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java index 5e636d982..34d76a148 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java +++ b/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java @@ -41,6 +41,7 @@ import jogamp.newt.WindowImpl; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.VisualIDHolder; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.InsetsImmutable; import javax.media.nativewindow.util.Point; @@ -119,8 +120,8 @@ public class WindowsWindow extends WindowImpl { protected void createNativeImpl() { final WindowsScreen screen = (WindowsScreen) getScreen(); final WindowsDisplay display = (WindowsDisplay) screen.getDisplay(); - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice()).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, screen.getGraphicsScreen()); + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, screen.getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); if (null == cfg) { throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); } diff --git a/src/newt/classes/jogamp/newt/driver/x11/X11Window.java b/src/newt/classes/jogamp/newt/driver/x11/X11Window.java index 9a5074c29..5501f5a3c 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/X11Window.java +++ b/src/newt/classes/jogamp/newt/driver/x11/X11Window.java @@ -63,9 +63,9 @@ public class X11Window extends WindowImpl { protected void createNativeImpl() { final X11Screen screen = (X11Screen) getScreen(); final X11Display display = (X11Display) screen.getDisplay(); - final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice()); + final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice(), capsRequested); final AbstractGraphicsConfiguration cfg = factory.chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, screen.getGraphicsScreen()); + capsRequested, capsRequested, capabilitiesChooser, screen.getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); if(DEBUG_IMPLEMENTATION) { System.err.println("X11Window.createNativeImpl() factory: "+factory+", chosen config: "+cfg); } -- cgit v1.2.3 From 7bb5885fc3a904f49e22f0c8cbf747d9b189a7ba Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 25 Jul 2012 04:23:35 +0200 Subject: SWT Update: SWT GLCanvas creates lazy when resource is ready; Create new NewtCanvasSWT allowing to parent NEWT windows natively. SWT GLCanvas creates lazy when resource is ready - Ensures drawable and context are created when size > zero and native visualID is valid. The latter is platform dependent. - Note that you cannot utilize custom GLCapabilities w/ this one, since the configurations is already realized - use NewtCanvasSWT. Create new NewtCanvasSWT allowing to parent NEWT windows natively: - Similar to NewtCanvasAWT - Allows attaching / detaching NEWT windows NewtCanvasAWT: Public setNEWTChild(..) fixed Added test cases for the above - tested on Linux, OSX and Windows w/ SWT Note: As usual for OSX, add -XstartOnFirstThread Details: - NEWT Display has new method: 'EDTUtil setEDTUtil(EDTUtil)' allowing to set a custom event dispatch utility. We use this to set our SWTEDTUtil for using NEWT w/ SWT complying w/ SWT threading constraints. --- etc/profile.jogl | 5 + make/build-common.xml | 2 + make/build-newt.xml | 19 +- make/build-test.xml | 99 ++-- make/scripts/java-win64-dbg.bat | 4 +- make/scripts/tests-x64.bat | 25 +- make/scripts/tests.sh | 19 +- make/stub_includes/win32/wingdi.h | 2 + .../gluegen/opengl/BuildComposablePipeline.java | 2 +- .../classes/com/jogamp/opengl/swt/GLCanvas.java | 199 +++++--- src/jogl/classes/jogamp/opengl/GLContextImpl.java | 1 - .../com/jogamp/nativewindow/swt/SWTAccessor.java | 25 + .../media/nativewindow/NativeWindowFactory.java | 17 + .../jogamp/nativewindow/macosx/OSXUtil.java | 35 +- src/nativewindow/native/macosx/OSXmisc.m | 74 ++- src/newt/classes/com/jogamp/newt/Display.java | 17 + .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 74 ++- .../classes/com/jogamp/newt/opengl/GLWindow.java | 1 - .../classes/com/jogamp/newt/swt/NewtCanvasSWT.java | 508 +++++++++++++++++++++ .../classes/com/jogamp/newt/swt/SWTEDTUtil.java | 99 ++++ src/newt/classes/jogamp/newt/DisplayImpl.java | 40 +- src/newt/classes/jogamp/newt/WindowImpl.java | 11 +- .../newt/awt/event/AWTParentWindowAdapter.java | 21 +- .../classes/jogamp/newt/driver/awt/AWTDisplay.java | 11 +- .../jogamp/newt/driver/macosx/MacWindow.java | 5 +- .../jogamp/newt/driver/windows/WindowsWindow.java | 11 +- src/newt/native/MacWindow.m | 56 ++- .../test/junit/jogl/swt/TestNewtCanvasSWTGLn.java | 233 ++++++++++ .../test/junit/jogl/swt/TestSWTAccessor02GLn.java | 278 ----------- .../junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java | 55 ++- .../junit/newt/parenting/TestParenting01aSWT.java | 210 +++++++++ .../junit/newt/parenting/TestParenting04AWT.java | 239 ++++++++++ .../junit/newt/parenting/TestParenting04SWT.java | 264 +++++++++++ 33 files changed, 2158 insertions(+), 503 deletions(-) create mode 100644 src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java create mode 100644 src/newt/classes/com/jogamp/newt/swt/SWTEDTUtil.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/swt/TestNewtCanvasSWTGLn.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor02GLn.java create mode 100644 src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01aSWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting04AWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting04SWT.java (limited to 'src/nativewindow') diff --git a/etc/profile.jogl b/etc/profile.jogl index 4402adde6..7dd51919d 100755 --- a/etc/profile.jogl +++ b/etc/profile.jogl @@ -25,6 +25,9 @@ function concat_jogl_list() ARCH=`uname -m` KERNEL=`uname -s | awk ' { printf "%s",tolower($0) ; } '` +if [ "$KERNEL" = "sunos" ] ; then + KERNEL="solaris" +fi uname -a | grep -i LINUX && OSS=x11 uname -a | grep -i Darwin && OSS=osx @@ -99,6 +102,8 @@ export JOGL_CLASSPATH if [ "$KERNEL" = "linux" ] ; then SWT_SUB="gtk" +elif [ "$KERNEL" = "solaris" ] ; then + SWT_SUB="gtk" elif [ "$KERNEL" = "darwin" ] ; then SWT_SUB="cocoa" KERNEL="macosx" diff --git a/make/build-common.xml b/make/build-common.xml index 8d440a766..4de5de58b 100644 --- a/make/build-common.xml +++ b/make/build-common.xml @@ -362,6 +362,7 @@ + @@ -374,6 +375,7 @@ + diff --git a/make/build-newt.xml b/make/build-newt.xml index a6be5042e..776708857 100644 --- a/make/build-newt.xml +++ b/make/build-newt.xml @@ -107,6 +107,9 @@ + + @@ -135,11 +138,16 @@ + + + + - + @@ -707,6 +715,13 @@ + + + + + + - + diff --git a/make/build-test.xml b/make/build-test.xml index 51eadfebd..f295ae321 100644 --- a/make/build-test.xml +++ b/make/build-test.xml @@ -427,7 +427,7 @@ - - + - - @@ -491,40 +489,71 @@ - - - - - - - - - - - - - - - - + + + + - + - + - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/make/scripts/java-win64-dbg.bat b/make/scripts/java-win64-dbg.bat index 109755d2e..c8a90454d 100755 --- a/make/scripts/java-win64-dbg.bat +++ b/make/scripts/java-win64-dbg.bat @@ -18,7 +18,7 @@ set CP_ALL=.;%BLD_DIR%\jar\jogl-all.jar;%BLD_DIR%\jar\jogl-test.jar;..\..\gluege echo CP_ALL %CP_ALL% -set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.FBObject" +REM set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.FBObject" REM set D_ARGS="-Djogl.debug.GLDrawable" "-Djogl.debug.EGLDrawableFactory.DontQuery" REM set D_ARGS="-Djogl.debug.GLDrawable" "-Djogl.debug.EGLDrawableFactory.QueryNativeTK" REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" @@ -37,7 +37,7 @@ REM set D_ARGS="-Djogl.debug=all" REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch" "-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL" REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch" "-Djogl.windows.useWGLVersionOf5WGLGDIFuncSet" REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch" -REM set D_ARGS="-Dnewt.debug.Window" +set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display" REM set D_ARGS="-Djogl.debug.GLDebugMessageHandler" "-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL" REM set D_ARGS="-Djogl.debug.DebugGL" "-Djogl.debug.GLDebugMessageHandler" "-Djogl.debug.GLSLCode" REM set D_ARGS="-Djogl.debug.GLContext" "-Dnewt.debug=all" diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat index 0b3711784..6d3e46af6 100755 --- a/make/scripts/tests-x64.bat +++ b/make/scripts/tests-x64.bat @@ -28,22 +28,29 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestTransf REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLSimple01NEWT -time 2000 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestParenting01AWT -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01bAWT %* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cAWT -time 50000 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestListenerCom01AWT REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01bAWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cAWT -time 50000 +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03AWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03bAWT -time 100000 +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01AWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aSWT $* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT $* +scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* + +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor03AWTGLn $* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTGLn $* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestWindows01NEWT REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestGLWindows02NEWTAnimated -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.nativewindow.TestRecursiveToolkitLockCORE -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03AWT %* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT %* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01AWT %* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03bAWT -time 100000 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT @@ -56,8 +63,6 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.Mo REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.TexCubeES2 %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle01NEWT -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT -REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestCloseNewtAWT REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleAWT -time 10000 @@ -96,7 +101,7 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMe REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestMapBuffer01NEWT REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01 -scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestFBOMRTNEWT01 %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %* diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 13e172770..af6218968 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -61,7 +61,7 @@ function jrun() { #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all -Djogamp.debug.Lock" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all" - #D_ARGS="-Djogl.debug=all -Dnewt.debug=all" + D_ARGS="-Dnewt.debug.Window" #D_ARGS="-Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.EGLDrawableFactory.DontQuery -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.EGLDrawableFactory.QueryNativeTK -Djogl.debug.GLDrawable" @@ -145,7 +145,8 @@ function jrun() { echo CLASSPATH $CLASSPATH X_ARGS="-Djava.awt.headless=false $X_ARGS" else - export CLASSPATH=$JOGAMP_ALL_NOAWT_CLASSPATH + export CLASSPATH=$JOGAMP_ALL_AWT_CLASSPATH + #export CLASSPATH=$JOGAMP_ALL_NOAWT_CLASSPATH #export CLASSPATH=$JOGAMP_MOBILE_CLASSPATH #export CLASSPATH=.:$GLUEGEN_JAR:$JOGL_BUILD_DIR/jar/atomic/jogl-core.jar:$JOGL_BUILD_DIR/jar/atomic/jogl-gldesktop.jar:$JOGL_BUILD_DIR/jar/atomic/jogl-os-x11.jar:$JOGL_BUILD_DIR/jar/atomic/jogl-util.jar:$JOGL_BUILD_DIR/jar/atomic/nativewindow-core.jar:$JOGL_BUILD_DIR/jar/atomic/nativewindow-os-x11.jar:$JOGL_BUILD_DIR/jar/atomic/newt-core.jar:$JOGL_BUILD_DIR/jar/atomic/newt-driver-x11.jar:$JOGL_BUILD_DIR/jar/atomic/newt-ogl.jar:$JOGL_BUILD_DIR/jar/jogl-test.jar:$SWT_CLASSPATH:$JUNIT_JAR:$ANT_JARS X_ARGS="-Djava.awt.headless=true $X_ARGS" @@ -298,13 +299,17 @@ function testawtswt() { # #testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTEclipseGLCanvas01GLn $* #testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* -#testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* -#testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor02GLn $* +#testswt com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTGLn $* # -# awtswt (testawtswt) +# awtswt (testawtswt) +# Per default (unit tests) all test are performed this way +# with OSX: -XstartOnFirstThread # +#testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTEclipseGLCanvas01GLn $* #testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor03AWTGLn $* +#testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* +#testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTGLn $* # # newt.awt (testawt) @@ -321,6 +326,9 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cSwingAWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting02AWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting03AWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT $* +#testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aSWT $* +testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01GLCanvasAWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer02NewtCanvasAWT $* @@ -402,7 +410,6 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot $* #linux: -testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor02GLn $* # ?? # osx: #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* diff --git a/make/stub_includes/win32/wingdi.h b/make/stub_includes/win32/wingdi.h index 2d3e33275..7a88582c2 100644 --- a/make/stub_includes/win32/wingdi.h +++ b/make/stub_includes/win32/wingdi.h @@ -44,6 +44,8 @@ WINUSERAPI BOOL WINAPI DestroyWindow(HWND hWnd); WINUSERAPI DWORD WINAPI GetObjectType(HGDIOBJ h); WINUSERAPI BOOL WINAPI IsWindowVisible(HWND hWnd); WINUSERAPI BOOL WINAPI IsWindow(HWND hWnd); +WINUSERAPI HWND WINAPI GetParent(HWND hWnd); +WINUSERAPI HWND WINAPI SetParent(HWND hWndChild,HWND hWndNewParent); WINUSERAPI HANDLE WINAPI GetCurrentProcess(void); WINUSERAPI BOOL WINAPI GetProcessAffinityMask(HANDLE hProcess,PDWORD_PTR lpProcessAffinityMask,PDWORD_PTR lpSystemAffinityMask); diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java index 1d9cf3668..5334d45cf 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java @@ -410,7 +410,7 @@ public class BuildComposablePipeline { output.flush(); output.close(); - System.out.println("wrote to file: " + file); // JAU + System.out.println("wrote to file: " + file); } /** Get the name of the object through which API calls should be routed. */ diff --git a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java index 64ee1c1ad..8d237162c 100644 --- a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java +++ b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java @@ -45,6 +45,7 @@ import javax.media.opengl.GLProfile; import javax.media.opengl.GLRunnable; import javax.media.opengl.Threading; +import jogamp.opengl.Debug; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableHelper; @@ -70,8 +71,12 @@ import com.jogamp.opengl.JoglVersion; /** * Native SWT Canvas implementing GLAutoDrawable + * + *

      Note: To employ custom GLCapabilities, NewtCanvasSWT shall be used instead.

      + * */ public class GLCanvas extends Canvas implements GLAutoDrawable { + private static final boolean DEBUG = Debug.debug("GLCanvas"); /* * Flag for whether the SWT thread should be used for OpenGL calls when in single-threaded mode. This is controlled @@ -87,18 +92,20 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { /* GL Stuff */ private final RecursiveLock lock = LockFactory.createRecursiveLock(); private final GLDrawableHelper helper = new GLDrawableHelper(); + + private final GLContext shareWith; + private final GLCapabilitiesImmutable capsRequested; + private final GLCapabilitiesChooser capsChooser; + private volatile GLDrawable drawable; // volatile: avoid locking for read-only access private GLContext context; /* Native window surface */ private AbstractGraphicsDevice device; - private final long nativeWindowHandle; - private final ProxySurface proxySurface; /* Construction parameters stored for GLAutoDrawable accessor methods */ private int additionalCtxCreationFlags = 0; - private final GLCapabilitiesImmutable glCapsRequested; /* Flag indicating whether an unprocessed reshape is pending. */ private volatile boolean sendReshape; // volatile: maybe written by WindowManager thread w/o locking @@ -218,6 +225,37 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { */ private volatile Rectangle clientArea; + /** + * Creates an instance using {@link #GLCanvas(Composite, int, GLCapabilitiesImmutable, GLCapabilitiesChooser, GLContext)} + * on the SWT thread. + * + * @param parent + * Required (non-null) parent Composite. + * @param style + * Optional SWT style bit-field. The {@link SWT#NO_BACKGROUND} bit is set before passing this up to the + * Canvas constructor, so OpenGL handles the background. + * @param caps + * Optional GLCapabilities. If not provided, the default capabilities for the default GLProfile for the + * graphics device determined by the parent Composite are used. Note that the GLCapabilities that are + * actually used may differ based on the capabilities of the graphics device. + * @param chooser + * Optional GLCapabilitiesChooser to customize the selection of the used GLCapabilities based on the + * requested GLCapabilities, and the available capabilities of the graphics device. + * @param shareWith + * Optional GLContext to share state (textures, vbos, shaders, etc.) with. + * @return a new instance + */ + public static GLCanvas create(final Composite parent, final int style, final GLCapabilitiesImmutable caps, + final GLCapabilitiesChooser chooser, final GLContext shareWith) { + final GLCanvas[] res = new GLCanvas[] { null }; + parent.getDisplay().syncExec(new Runnable() { + public void run() { + res[0] = new GLCanvas( parent, style, caps, chooser, shareWith ); + } + }); + return res[0]; + } + /** * Creates a new SWT GLCanvas. * @@ -250,35 +288,26 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { /* Get the nativewindow-Graphics Device associated with this control (which is determined by the parent Composite). * Note: SWT is owner of the native handle, hence no closing operation will be a NOP. */ device = SWTAccessor.getDevice(this); - /* Since we have no means of querying the screen index yet, assume 0. Good choice due to Xinerama alike settings anyways. */ - final int screenIdx = 0; - /* Native handle for the control, used to associate with GLContext */ - nativeWindowHandle = SWTAccessor.getWindowHandle(this); /* Select default GLCapabilities if none was provided, otherwise clone provided caps to ensure safety */ if(null == caps) { caps = new GLCapabilities(GLProfile.getDefault(device)); } - glCapsRequested = caps; - - final GLDrawableFactory glFactory = GLDrawableFactory.getFactory(caps.getGLProfile()); - - /* Create a NativeWindow proxy for the SWT canvas */ - proxySurface = glFactory.createProxySurface(device, screenIdx, nativeWindowHandle, caps, chooser, swtCanvasUpStreamHook); - - /* Associate a GL surface with the proxy */ - drawable = glFactory.createGLDrawable(proxySurface); - drawable.setRealized(true); - - context = drawable.createContext(shareWith); - + this.capsRequested = caps; + this.capsChooser = chooser; + this.shareWith = shareWith; + + // post create .. when ready + drawable = null; + context = null; + /* Register SWT listeners (e.g. PaintListener) to render/resize GL surface. */ /* TODO: verify that these do not need to be manually de-registered when destroying the SWT component */ addPaintListener(new PaintListener() { @Override public void paintControl(final PaintEvent arg0) { - if (!helper.isExternalAnimatorAnimating()) { - display(); + if ( !helper.isExternalAnimatorAnimating() ) { + display(); // checks: null != drawable } } }); @@ -291,39 +320,93 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { }); } private final ProxySurface.UpstreamSurfaceHook swtCanvasUpStreamHook = new ProxySurface.UpstreamSurfaceHook() { - @Override - public final void create(ProxySurface s) { /* nop */ } - - @Override - public final void destroy(ProxySurface s) { /* nop */ } - - @Override - public final int getWidth(ProxySurface s) { - return clientArea.width; - } - - @Override - public final int getHeight(ProxySurface s) { - return clientArea.height; - } - - @Override - public String toString() { - return "SETUpstreamSurfaceHook[upstream: "+GLCanvas.this.toString()+"]"; - } - + @Override + public final void create(ProxySurface s) { /* nop */ } + + @Override + public final void destroy(ProxySurface s) { /* nop */ } + + @Override + public final int getWidth(ProxySurface s) { + return clientArea.width; + } + + @Override + public final int getHeight(ProxySurface s) { + return clientArea.height; + } + + @Override + public String toString() { + return "SWTCanvasUpstreamSurfaceHook[upstream: "+GLCanvas.this.toString()+", "+clientArea.width+"x"+clientArea.height+"]"; + } }; protected final void updateSizeCheck() { - clientArea = GLCanvas.this.getClientArea(); - if (clientArea != null && - proxySurface.getWidth() != clientArea.width && - proxySurface.getHeight() != clientArea.height) { + final Rectangle oClientArea = clientArea; + final Rectangle nClientArea = GLCanvas.this.getClientArea(); + if ( nClientArea != null && + ( nClientArea.width != oClientArea.width || nClientArea.height != oClientArea.height ) + ) { + clientArea = nClientArea; // write back new value sendReshape = true; // Mark for OpenGL reshape next time the control is painted } - sendReshape = false; + } + + @Override + public void display() { + if( null != drawable || validateDrawableAndContext() ) { + runInGLThread(makeCurrentAndDisplayOnEDTAction); + } } + + /** assumes drawable == null ! */ + protected final boolean validateDrawableAndContext() { + if( GLCanvas.this.isDisposed() ) { + return false; + } + final Rectangle nClientArea = clientArea; + if(0 == nClientArea.width * nClientArea.height) { + return false; + } + + final RecursiveLock _lock = lock; + _lock.lock(); + try { + final GLDrawableFactory glFactory = GLDrawableFactory.getFactory(capsRequested.getGLProfile()); + + /* Native handle for the control, used to associate with GLContext */ + final long nativeWindowHandle = SWTAccessor.getWindowHandle(this); + + /* Create a NativeWindow proxy for the SWT canvas */ + ProxySurface proxySurface = null; + try { + proxySurface = glFactory.createProxySurface(device, 0 /* screenIdx */, nativeWindowHandle, + capsRequested, capsChooser, swtCanvasUpStreamHook); + } catch (GLException gle) { + // not ready yet .. + if(DEBUG) { System.err.println(gle.getMessage()); } + } + + if(null != proxySurface) { + /* Associate a GL surface with the proxy */ + drawable = glFactory.createGLDrawable(proxySurface); + drawable.setRealized(true); + + context = drawable.createContext(shareWith); + } + } finally { + _lock.unlock(); + } + final boolean res = null != drawable; + if(DEBUG && res) { + System.err.println("SWT GLCanvas realized! "+this+", "+drawable); + Thread.dumpStack(); + } + return res; + } + @Override public final Object getUpstreamWidget() { return this; @@ -362,11 +445,6 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { dispose(); } - @Override - public void display() { - runInGLThread(makeCurrentAndDisplayOnEDTAction); - } - @Override public GLAnimatorControl getAnimator() { return helper.getAnimator(); @@ -379,7 +457,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { @Override public GLContext getContext() { - return context; + return null != drawable ? context : null; } @Override @@ -472,7 +550,8 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { @Override public GLCapabilitiesImmutable getChosenGLCapabilities() { - return (GLCapabilitiesImmutable)proxySurface.getGraphicsConfiguration().getChosenCapabilities(); + final GLDrawable _drawable = drawable; + return null != _drawable ? (GLCapabilitiesImmutable)_drawable.getChosenGLCapabilities() : null; } /** @@ -481,7 +560,8 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { * @return Non-null GLCapabilities. */ public GLCapabilitiesImmutable getRequestedGLCapabilities() { - return (GLCapabilitiesImmutable)proxySurface.getGraphicsConfiguration().getRequestedCapabilities(); + final GLDrawable _drawable = drawable; + return null != _drawable ? (GLCapabilitiesImmutable)_drawable.getNativeSurface().getGraphicsConfiguration().getRequestedCapabilities() : null; } @Override @@ -492,7 +572,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { @Override public GLProfile getGLProfile() { - return glCapsRequested.getGLProfile(); + return capsRequested.getGLProfile(); } @Override @@ -523,10 +603,9 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { runInGLThread(makeCurrentAndSwapBuffersOnEDTAction); } - // FIXME: API of update() method ? @Override public void update() { - // FIXME: display(); ? + // don't paint background etc .. nop avoids flickering } @Override @@ -551,7 +630,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { * @see Platform#AWT_AVAILABLE * @see Platform#getOSType() */ - private void runInGLThread(final Runnable action) { + private static void runInGLThread(final Runnable action) { if(Platform.OSType.MACOS == Platform.OS_TYPE) { SWTAccessor.invoke(true, action); } else { diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index e730bc62e..bf6a0ee6e 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -338,7 +338,6 @@ public abstract class GLContextImpl extends GLContext { if (TRACE_SWITCH) { System.err.println(getThreadName() + ": GLContextImpl.destroy.X: obj " + toHexString(hashCode()) + ", ctx " + toHexString(contextHandle) + ", isShared "+GLContextShareSet.isShared(this)+" - "+lock); - Thread.dumpStack(); // JAU } } } finally { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index 0494bb408..ba07d97dc 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -34,16 +34,21 @@ import java.lang.reflect.Method; import org.eclipse.swt.graphics.GCData; import org.eclipse.swt.widgets.Control; +import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.DefaultGraphicsScreen; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowFactory; +import javax.media.nativewindow.VisualIDHolder; import com.jogamp.common.util.ReflectionUtil; import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsDevice; +import com.jogamp.nativewindow.x11.X11GraphicsScreen; import jogamp.nativewindow.macosx.OSXUtil; +import jogamp.nativewindow.x11.X11Lib; public class SWTAccessor { static final Field swt_control_handle; @@ -213,6 +218,26 @@ public class SWTAccessor { } throw new UnsupportedOperationException("n/a for this windowing system: "+NativeWindowFactory.getNativeWindowType(false)); } + public static AbstractGraphicsScreen getScreen(AbstractGraphicsDevice device, int screen) { + if( null != OS_gtk_class ) { + return new X11GraphicsScreen((X11GraphicsDevice)device, screen); + } + if( NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false) || + NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false) ) { + return new DefaultGraphicsScreen(device, screen); + } + throw new UnsupportedOperationException("n/a for this windowing system: "+NativeWindowFactory.getNativeWindowType(false)); + } + public static int getNativeVisualID(AbstractGraphicsDevice device, long windowHandle) { + if( null != OS_gtk_class ) { + return X11Lib.GetVisualIDFromWindow(device.getHandle(), windowHandle); + } + if( NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false) || + NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false) ) { + return VisualIDHolder.VID_UNDEFINED; + } + throw new UnsupportedOperationException("n/a for this windowing system: "+NativeWindowFactory.getNativeWindowType(false)); + } public static long getWindowHandle(Control swtControl) { long handle = getHandle(swtControl); diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index b85ad47f2..6faa9890c 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -561,4 +561,21 @@ public abstract class NativeWindowFactory { } return null; } + + /** + * Returns true if the given visualID is valid for further processing, i.e. OpenGL usage, + * otherwise return false. + *

      + * On certain platforms, i.e. X11, a valid visualID is required at window creation. + * Other platforms may determine it later on, e.g. OSX and Windows.

      + *

      + * If the visualID is {@link VisualIDHolder#VID_UNDEFINED} and the platform requires it + * at creation time (see above), it is not valid for further processing. + *

      + */ + public static boolean isNativeVisualIDValidForProcessing(int visualID) { + return NativeWindowFactory.TYPE_X11 != NativeWindowFactory.getNativeWindowType(false) || + VisualIDHolder.VID_UNDEFINED != visualID ; + } + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 4767dff18..894084fce 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -28,6 +28,7 @@ package jogamp.nativewindow.macosx; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.Point; import jogamp.nativewindow.Debug; @@ -63,8 +64,37 @@ public class OSXUtil { return isNSView0(object); } - public static Point GetLocationOnScreen(long windowOrView, int src_x, int src_y) { - return (Point) GetLocationOnScreen0(windowOrView, src_x, src_y); + /** + * In case the windowOrView is top-level, + * you shall set topLevel to true where + * insets gets into account to compute the client position as follows: + *
      +      if(topLevel) {
      +          // top-level position -> client window position
      +          final Insets insets = GetInsets(windowOrView);
      +          los.setX(los.getX() + insets.getLeftWidth());
      +          los.setY(los.getY() + insets.getTopHeight());
      +      }
      +     * 
      + * @param windowOrView + * @param topLevel + * @param src_x + * @param src_y + * @return the client position + */ + public static Point GetLocationOnScreen(long windowOrView, boolean topLevel, int src_x, int src_y) { + final Point los = (Point) GetLocationOnScreen0(windowOrView, src_x, src_y); + if(topLevel) { + // top-level position -> client window position + final Insets insets = GetInsets(windowOrView); + los.setX(los.getX() + insets.getLeftWidth()); + los.setY(los.getY() + insets.getTopHeight()); + } + return los; + } + + public static Insets GetInsets(long windowOrView) { + return (Insets) GetInsets0(windowOrView); } public static long CreateNSWindow(int x, int y, int width, int height) { @@ -135,6 +165,7 @@ public class OSXUtil { private static native boolean initIDs0(); private static native boolean isNSView0(long object); private static native Object GetLocationOnScreen0(long windowOrView, int src_x, int src_y); + private static native Object GetInsets0(long windowOrView); private static native long CreateNSWindow0(int x, int y, int width, int height); private static native void DestroyNSWindow0(long nsWindow); private static native long GetNSView0(long nsWindow); diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 37fa4c88f..2c853a43d 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -52,12 +52,18 @@ static const char * const ClazzNameRunnable = "java/lang/Runnable"; static jmethodID runnableRunID = NULL; -static const char * const ClazzNamePoint = "javax/media/nativewindow/util/Point"; static const char * const ClazzAnyCstrName = ""; + +static const char * const ClazzNamePoint = "javax/media/nativewindow/util/Point"; static const char * const ClazzNamePointCstrSignature = "(II)V"; static jclass pointClz = NULL; static jmethodID pointCstr = NULL; +static const char * const ClazzNameInsets = "javax/media/nativewindow/util/Insets"; +static const char * const ClazzNameInsetsCstrSignature = "(IIII)V"; +static jclass insetsClz = NULL; +static jmethodID insetsCstr = NULL; + static int _initialized=0; JNIEXPORT jboolean JNICALL @@ -79,6 +85,21 @@ Java_jogamp_nativewindow_macosx_OSXUtil_initIDs0(JNIEnv *env, jclass _unused) { ClazzNamePoint, ClazzAnyCstrName, ClazzNamePointCstrSignature); } + c = (*env)->FindClass(env, ClazzNameInsets); + if(NULL==c) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't find %s", ClazzNameInsets); + } + insetsClz = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==insetsClz) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't use %s", ClazzNameInsets); + } + insetsCstr = (*env)->GetMethodID(env, insetsClz, ClazzAnyCstrName, ClazzNameInsetsCstrSignature); + if(NULL==insetsCstr) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't fetch %s.%s %s", + ClazzNameInsets, ClazzAnyCstrName, ClazzNameInsetsCstrSignature); + } + c = (*env)->FindClass(env, ClazzNameRunnable); if(NULL==c) { NativewindowCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't find %s", ClazzNameRunnable); @@ -154,6 +175,49 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetLocationOnS return res; } +/* + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: getInsets0 + * Signature: (J)Ljavax/media/nativewindow/util/Insets; + */ +JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetInsets0 + (JNIEnv *env, jclass unused, jlong winOrView) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + + NSObject *nsObj = (NSObject*) (intptr_t) winOrView; + NSWindow* win = NULL; + NSView* view = NULL; + jint il,ir,it,ib; + + if( [nsObj isKindOfClass:[NSWindow class]] ) { + win = (NSWindow*) nsObj; + view = [win contentView]; + } else if( nsObj != NULL && [nsObj isKindOfClass:[NSView class]] ) { + view = (NSView*) nsObj; + win = [view window]; + } else { + NativewindowCommon_throwNewRuntimeException(env, "neither win not view %p\n", nsObj); + } + + NSRect frameRect = [win frame]; + NSRect contentRect = [win contentRectForFrameRect: frameRect]; + + // note: this is a simplistic implementation which doesn't take + // into account DPI and scaling factor + CGFloat l = contentRect.origin.x - frameRect.origin.x; + il = (jint)l; // l + ir = (jint)(frameRect.size.width - (contentRect.size.width + l)); // r + it = (jint)(frameRect.size.height - contentRect.size.height); // t + ib = (jint)(contentRect.origin.y - frameRect.origin.y); // b + + jobject res = (*env)->NewObject(env, insetsClz, insetsCstr, il, ir, it, ib); + + [pool release]; + + return res; +} + /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: CreateNSWindow0 @@ -172,6 +236,12 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateNSWindow0 defer: YES]; [myWindow setReleasedWhenClosed: YES]; // default [myWindow setPreservesContentDuringLiveResize: YES]; + // Remove animations +NS_DURING + // Available >= 10.7 - Removes default animations + [myWindow setAnimationBehavior: NSWindowAnimationBehaviorNone]; +NS_HANDLER +NS_ENDHANDLER // invisible .. [myWindow setOpaque: NO]; @@ -229,7 +299,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; CALayer* layer = [[CALayer alloc] init]; - DBG_PRINT("CALayer::CreateCALayer.0: %p %d/%d %dx%d (refcnt %d)\n", layer, x, y, width, height, (int)[layer retainCount]); + DBG_PRINT("CALayer::CreateCALayer.0: %p %d/%d %dx%d (refcnt %d)\n", layer, (int)x, (int)y, (int)width, (int)height, (int)[layer retainCount]); // avoid zero size if(0 == width) { width = 32; } if(0 == height) { height = 32; } diff --git a/src/newt/classes/com/jogamp/newt/Display.java b/src/newt/classes/com/jogamp/newt/Display.java index 7b6849a30..1e9a0e9eb 100644 --- a/src/newt/classes/com/jogamp/newt/Display.java +++ b/src/newt/classes/com/jogamp/newt/Display.java @@ -141,6 +141,23 @@ public abstract class Display { */ public abstract String getType(); + /** + * Sets a new {@link EDTUtil} and returns the previous one. + *

      + * If newEDTUtil is null, + * the device's default EDTUtil is created and used. + *

      + *

      + * If a previous one exists and it differs from the new one, + * it's being stopped, wait-until-idle and reset to allow restart. + *

      + *

      + * If newEDTUtil is not null and equals the previous one, + * null is returned and no change is being made. + *

      + */ + public abstract EDTUtil setEDTUtil(EDTUtil newEDTUtil); + public abstract EDTUtil getEDTUtil(); public abstract boolean isEDTRunning(); diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index cd0e9aab6..6f0028a77 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -263,17 +263,35 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto private final FocusPropertyChangeListener focusPropertyChangeListener = new FocusPropertyChangeListener(); private volatile KeyboardFocusManager keyboardFocusManager = null; - /** sets a new NEWT child, provoking reparenting. */ - private NewtCanvasAWT setNEWTChild(Window child) { - if(newtChild!=child) { - newtChild = child; - if(isDisplayable()) { - // reparent right away, addNotify has been called already - final java.awt.Container cont = AWTMisc.getContainer(this); - reparentWindow( (null!=child) ? true : false, cont ); - } + /** + * Sets a new NEWT child, provoking reparenting. + *

      + * A previously detached newChild will be released to top-level status + * and made invisible. + *

      + *

      + * Note: When switching NEWT child's, detaching the previous first via setNEWTChild(null) + * produced much cleaner visual results. + *

      + * @return the previous attached newt child. + */ + public Window setNEWTChild(Window newChild) { + final Window prevChild = newtChild; + if(DEBUG) { + System.err.println("NewtCanvasAWT.setNEWTChild.0: win "+newtWinHandleToHexString(prevChild)+" -> "+newtWinHandleToHexString(newChild)); + } + final java.awt.Container cont = AWTMisc.getContainer(this); + // remove old one + if(null != newtChild) { + reparentWindow( false, cont ); + newtChild = null; } - return this; + // add new one, reparent only if ready + newtChild = newChild; + if( isDisplayable() && null != newChild) { + reparentWindow( true, cont ); + } + return prevChild; } /** @return the current NEWT child */ @@ -306,13 +324,13 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto awtKeyAdapter.removeFrom(this); awtKeyAdapter = null; } - newtChild.setKeyboardFocusHandler(null); if(null != keyboardFocusManager) { keyboardFocusManager.removePropertyChangeListener("focusOwner", focusPropertyChangeListener); keyboardFocusManager = null; } if( null != newtChild ) { + newtChild.setKeyboardFocusHandler(null); if(attach) { if(null == jawtWindow.getGraphicsConfiguration()) { throw new InternalError("XXX"); @@ -360,7 +378,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto // if ( isShowing() == true ) -> Container is already visible. System.err.println("NewtCanvasAWT.addNotify: "+newtChild+", "+this+", visible "+isVisible()+", showing "+isShowing()+ ", displayable "+isDisplayable()+" -> "+cont); - } + } reparentWindow(true, cont); } @@ -375,6 +393,12 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto ols.detachSurfaceLayer(); } reparentWindow(false, cont); + + if(null != jawtWindow) { + NewtFactoryAWT.destroyNativeWindow(jawtWindow); + jawtWindow=null; + } + super.removeNotify(); } @@ -382,14 +406,19 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto if(null==newtChild) { return; // nop } + if(DEBUG) { + System.err.println("NewtCanvasAWT.reparentWindow.0: add="+add+", win "+newtWinHandleToHexString(newtChild)+", EDTUtil: cur "+newtChild.getScreen().getDisplay().getEDTUtil()); + } newtChild.setFocusAction(null); // no AWT focus traversal .. if(add) { - jawtWindow = NewtFactoryAWT.getNativeWindow(this, newtChild.getRequestedCapabilities()); - jawtWindow.setShallUseOffscreenLayer(shallUseOffscreenLayer); if(DEBUG) { System.err.println("NewtCanvasAWT.reparentWindow: newtChild: "+newtChild); } + if(null == jawtWindow) { + jawtWindow = NewtFactoryAWT.getNativeWindow(this, newtChild.getRequestedCapabilities()); + jawtWindow.setShallUseOffscreenLayer(shallUseOffscreenLayer); + } final int w; final int h; if(isPreferredSizeSet()) { @@ -413,7 +442,6 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto newtChild.setVisible(true); configureNewtChild(true); newtChild.sendWindowEvent(WindowEvent.EVENT_WINDOW_RESIZED); // trigger a resize/relayout to listener - newtChild.windowRepaint(0, 0, w, h); // force this AWT Canvas to be focus-able, // since this it is completely covered by the newtChild (z-order). @@ -422,10 +450,9 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto configureNewtChild(false); newtChild.setVisible(false); newtChild.reparentWindow(null); - if(null != jawtWindow) { - NewtFactoryAWT.destroyNativeWindow(jawtWindow); - jawtWindow=null; - } + } + if(DEBUG) { + System.err.println("NewtCanvasAWT.reparentWindow.X: add="+add+", win "+newtWinHandleToHexString(newtChild)+", EDTUtil: cur "+newtChild.getScreen().getDisplay().getEDTUtil()); } } @@ -451,7 +478,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto NewtFactoryAWT.destroyNativeWindow(jawtWindow); jawtWindow=null; } - newtChild.setVisible(false); + newtChild.setVisible(false); newtChild.reparentWindow(null); newtChild.destroy(); newtChild=null; @@ -569,5 +596,12 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } } } + + static String newtWinHandleToHexString(Window w) { + return null != w ? toHexString(w.getWindowHandle()) : "nil"; + } + static String toHexString(long l) { + return "0x"+Long.toHexString(l); + } } diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index 2205aec8e..d662a743a 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -480,7 +480,6 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind } if(Window.DEBUG_IMPLEMENTATION) { System.err.println("GLWindow.setVisibleActionPost("+visible+", "+nativeWindowCreated+") "+WindowImpl.getThreadName()+", fin: dt "+ (System.nanoTime()-t0)/1e6 +"ms"); - Thread.dumpStack(); // JAU } } diff --git a/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java new file mode 100644 index 000000000..f45b864fa --- /dev/null +++ b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java @@ -0,0 +1,508 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + + +package com.jogamp.newt.swt; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.Capabilities; +import javax.media.nativewindow.CapabilitiesImmutable; +import javax.media.nativewindow.GraphicsConfigurationFactory; +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindow; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.NativeWindowFactory; +import javax.media.nativewindow.SurfaceUpdatedListener; +import javax.media.nativewindow.WindowClosingProtocol; +import javax.media.nativewindow.util.Insets; +import javax.media.nativewindow.util.InsetsImmutable; +import javax.media.nativewindow.util.Point; + +import jogamp.nativewindow.macosx.OSXUtil; +import jogamp.newt.Debug; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ControlAdapter; +import org.eclipse.swt.events.ControlEvent; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.swt.widgets.Composite; + +import com.jogamp.nativewindow.swt.SWTAccessor; +import com.jogamp.newt.Display; +import com.jogamp.newt.Window; +import com.jogamp.newt.event.WindowEvent; +import com.jogamp.newt.util.EDTUtil; + +public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { + private static final boolean DEBUG = Debug.debug("Window"); + private static final boolean isOSX = NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false); + + /** SWT EDTUtil associated w/ parent's SWT Display */ + private final EDTUtil swtEDTUtil; + + private final AbstractGraphicsScreen screen; + + private WindowClosingMode newtChildCloseOp = WindowClosingMode.DISPOSE_ON_CLOSE; + private volatile Rectangle clientArea; + + private volatile SWTNativeWindow nativeWindow; + private volatile Window newtChild = null; + + /** + * Creates an instance using {@link #NewtCanvasSWT(Composite, int, Window)} + * on the SWT thread. + * + *

      + * Note: The NEWT child {@link Display}'s {@link EDTUtil} is being set to an SWT conform implementation + * via {@link Display#setEDTUtil(EDTUtil)}. + *

      + * + * @param parent the SWT composite + * @param style additional styles to SWT#NO_BACKGROUND + * @param child optional preassigned {@link #Window}, maybe null + * @return a new instance + */ + public static NewtCanvasSWT create(final Composite parent, final int style, final Window child) { + final NewtCanvasSWT[] res = new NewtCanvasSWT[] { null }; + parent.getDisplay().syncExec( new Runnable() { + public void run() { + res[0] = new NewtCanvasSWT( parent, style, child); + } + }); + return res[0]; + } + + /** + * Instantiates a NewtCanvas with a NEWT child. + * + *

      + * Note: The NEWT child {@link Display}'s {@link EDTUtil} is being set to an SWT conform implementation + * via {@link Display#setEDTUtil(EDTUtil)}. + *

      + * + * @param parent the SWT composite + * @param style additional styles to SWT#NO_BACKGROUND + * @param child optional preassigned {@link #Window}, maybe null + */ + public NewtCanvasSWT(final Composite parent, final int style, Window child) { + super(parent, style | SWT.NO_BACKGROUND); + + swtEDTUtil = new SWTEDTUtil(parent.getDisplay()); + + SWTAccessor.setRealized(this, true); + + clientArea = getClientArea(); + + final AbstractGraphicsDevice device = SWTAccessor.getDevice(this); + screen = SWTAccessor.getScreen(device, 0); + nativeWindow = null; + + if(null != child) { + setNEWTChild(child); + } + + /* Register SWT listeners (e.g. PaintListener) to render/resize GL surface. */ + /* TODO: verify that these do not need to be manually de-registered when destroying the SWT component */ + addPaintListener(new PaintListener() { + @Override + public void paintControl(final PaintEvent arg0) { + if( null != nativeWindow || validateNative() ) { + if( null !=newtChild ) { + newtChild.windowRepaint(0, 0, clientArea.width, clientArea.height); + } + } + } + }); + + addControlListener(new ControlAdapter() { + @Override + public void controlResized(final ControlEvent arg0) { + updateSizeCheck(); + } + }); + } + + /** assumes nativeWindow == null ! */ + protected final boolean validateNative() { + if( isDisposed() ) { + return false; + } + updateSizeCheck(); + final Rectangle nClientArea = clientArea; + if(0 == nClientArea.width * nClientArea.height) { + return false; + } + + /* Native handle for the control, used to associate with GLContext */ + final long nativeWindowHandle = SWTAccessor.getWindowHandle(this); + final int visualID = SWTAccessor.getNativeVisualID(screen.getDevice(), nativeWindowHandle); + final boolean visualIDValid = NativeWindowFactory.isNativeVisualIDValidForProcessing(visualID); + if(DEBUG) { + System.err.println("NewtCanvasSWT.validateNative() windowHandle 0x"+Long.toHexString(nativeWindowHandle)+", visualID 0x"+Integer.toHexString(visualID)+", valid "+visualIDValid); + } + if( visualIDValid ) { + /* Get the nativewindow-Graphics Device associated with this control (which is determined by the parent Composite). + * Note: SWT is owner of the native handle, hence no closing operation will be a NOP. */ + final CapabilitiesImmutable caps = new Capabilities(); + final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(screen.getDevice(), caps); + final AbstractGraphicsConfiguration config = factory.chooseGraphicsConfiguration( caps, caps, null, screen, visualID ); + if(DEBUG) { + System.err.println("NewtCanvasSWT.validateNative() factory: "+factory+", windowHandle 0x"+Long.toHexString(nativeWindowHandle)+", visualID 0x"+Integer.toHexString(visualID)+", chosen config: "+config); + // Thread.dumpStack(); + } + if (null == config) { + throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); + } + + nativeWindow = new SWTNativeWindow(config, nativeWindowHandle); + reparentWindow( true ); + } + + return null != nativeWindow; + } + + protected final void updateSizeCheck() { + final Rectangle oClientArea = clientArea; + final Rectangle nClientArea = getClientArea(); + if ( nClientArea != null && + ( nClientArea.width != oClientArea.width || nClientArea.height != oClientArea.height ) + ) { + clientArea = nClientArea; // write back new value + if( null != newtChild ) { + newtChild.setSize(clientArea.width, clientArea.height); + } + } + } + + @Override + public void update() { + // don't paint background etc .. nop avoids flickering + } + + /** + * Destroys this resource: + *
        + *
      • Make the NEWT Child invisible
      • + *
      • Disconnects the NEWT Child from this Canvas NativeWindow, reparent to NULL
      • + *
      • Issues destroy() on the NEWT Child
      • + *
      • Remove reference to the NEWT Child
      • + *
      + * @see Window#destroy() + */ + @Override + public void dispose() { + if( null != newtChild ) { + if(DEBUG) { + System.err.println("NewtCanvasSWT.dispose.0: EDTUtil cur "+newtChild.getScreen().getDisplay().getEDTUtil()+ + ",\n\t"+newtChild); + } + configureNewtChild(false); + newtChild.setVisible(false); + newtChild.reparentWindow(null); + newtChild.destroy(); + newtChild = null; + } + nativeWindow = null; + super.dispose(); + } + + /** @return this SWT Canvas NativeWindow representation, may be null in case it has not been realized. */ + public NativeWindow getNativeWindow() { return nativeWindow; } + + public WindowClosingMode getDefaultCloseOperation() { + return newtChildCloseOp; // FIXME + } + + public WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) { + return newtChildCloseOp = op; // FIXME + } + + + boolean isParent() { + return null!=newtChild ; + } + + boolean isFullscreen() { + return null != newtChild && newtChild.isFullscreen(); + } + + /** + * Sets a new NEWT child, provoking reparenting. + *

      + * A previously detached newChild will be released to top-level status + * and made invisible. + *

      + *

      + * Note: When switching NEWT child's, detaching the previous first via setNEWTChild(null) + * produced much cleaner visual results. + *

      + *

      + * Note: The NEWT child {@link Display}'s {@link EDTUtil} is being set to an SWT conform implementation + * via {@link Display#setEDTUtil(EDTUtil)}. + *

      + * @return the previous attached newt child. + */ + public Window setNEWTChild(final Window newChild) { + final Window prevChild = newtChild; + if(DEBUG) { + System.err.println("NewtCanvasSWT.setNEWTChild.0: win "+newtWinHandleToHexString(prevChild)+" -> "+newtWinHandleToHexString(newChild)); + } + // remove old one + if(null != newtChild) { + reparentWindow( false ); + newtChild = null; + } + // add new one, reparent only if ready + newtChild = newChild; + if(null != nativeWindow && null != newChild) { + reparentWindow( true ); + } + return prevChild; + } + + /** @return the current NEWT child */ + public Window getNEWTChild() { + return newtChild; + } + + @Override + public boolean setParent(Composite parent) { + return super.setParent(parent); + } + + /* package */ void configureNewtChild(boolean attach) { + + if( null != newtChild ) { + newtChild.setKeyboardFocusHandler(null); + if(attach) { + newtChildCloseOp = newtChild.setDefaultCloseOperation(WindowClosingMode.DO_NOTHING_ON_CLOSE); + } else { + newtChild.setFocusAction(null); + newtChild.setDefaultCloseOperation(newtChildCloseOp); + } + } + } + + void reparentWindow(boolean add) { + if( null == newtChild ) { + return; // nop + } + if(DEBUG) { + System.err.println("NewtCanvasSWT.reparentWindow.0: add="+add+", win "+newtWinHandleToHexString(newtChild)+", EDTUtil: cur "+newtChild.getScreen().getDisplay().getEDTUtil()); + } + + newtChild.setFocusAction(null); // no AWT focus traversal .. + if(add) { + updateSizeCheck(); + final int w = clientArea.width; + final int h = clientArea.height; + + newtChild.getScreen().getDisplay().setEDTUtil(swtEDTUtil); + + newtChild.setSize(w, h); + newtChild.reparentWindow(nativeWindow); + newtChild.setVisible(true); + configureNewtChild(true); + newtChild.sendWindowEvent(WindowEvent.EVENT_WINDOW_RESIZED); // trigger a resize/relayout to listener + + // force this SWT Canvas to be focus-able, + // since this it is completely covered by the newtChild (z-order). + setEnabled(true); + } else { + configureNewtChild(false); + newtChild.setVisible(false); + newtChild.reparentWindow(null); + } + if(DEBUG) { + System.err.println("NewtCanvasSWT.reparentWindow.X: add="+add+", win "+newtWinHandleToHexString(newtChild)+", EDTUtil: cur "+newtChild.getScreen().getDisplay().getEDTUtil()); + } + } + + private final void requestFocusNEWTChild() { + if( null != newtChild ) { + newtChild.setFocusAction(null); + newtChild.requestFocus(); + } + } + + @Override + public boolean forceFocus() { + final boolean res = NewtCanvasSWT.super.forceFocus(); + requestFocusNEWTChild(); + return res; + } + + private class SWTNativeWindow implements NativeWindow { + private final AbstractGraphicsConfiguration config; + private final long nativeWindowHandle; + private final InsetsImmutable insets; // only required to allow proper client position calculation on OSX + + public SWTNativeWindow(AbstractGraphicsConfiguration config, long nativeWindowHandle) { + this.config = config; + this.nativeWindowHandle = nativeWindowHandle; + if(isOSX) { + this.insets = OSXUtil.GetInsets(nativeWindowHandle); + } else { + this.insets = new Insets(0, 0, 0, 0); + } + } + + @Override + public int lockSurface() throws NativeWindowException, RuntimeException { + return NativeSurface.LOCK_SUCCESS; + } + + @Override + public void unlockSurface() { } + + @Override + public boolean isSurfaceLockedByOtherThread() { + return false; + } + + @Override + public Thread getSurfaceLockOwner() { + return null; + } + + @Override + public boolean surfaceSwap() { + return false; + } + + @Override + public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { } + + @Override + public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { + } + + @Override + public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { } + + @Override + public long getSurfaceHandle() { + return 0; + } + + @Override + public int getWidth() { + return clientArea.width; + } + + @Override + public int getHeight() { + return clientArea.height; + } + + @Override + public AbstractGraphicsConfiguration getGraphicsConfiguration() { + return config; + } + + @Override + public long getDisplayHandle() { + return config.getScreen().getDevice().getHandle(); + } + + @Override + public int getScreenIndex() { + return config.getScreen().getIndex(); + } + + @Override + public void surfaceUpdated(Object updater, NativeSurface ns, long when) { } + + @Override + public void destroy() { } + + @Override + public NativeWindow getParent() { + return null; + } + + @Override + public long getWindowHandle() { + return nativeWindowHandle; + } + + @Override + public InsetsImmutable getInsets() { + return insets; + } + + @Override + public int getX() { + return 0; + } + + @Override + public int getY() { + return 0; + } + + @Override + public Point getLocationOnScreen(Point point) { + if( isOSX ) { + final Point los = OSXUtil.GetLocationOnScreen(nativeWindowHandle, false, 0, 0); + // top-level position -> client window position + los.setX(los.getX() + insets.getLeftWidth()); + los.setY(los.getY() + insets.getTopHeight()); + if(null!=point) { + return point.translate(los); + } else { + return los; + } + } else { + // client position on 'normal' windowing systems is 0/0 + if(null == point) { + point = new Point(0, 0); + } + return point; + } + } + + @Override + public boolean hasFocus() { + return isFocusControl(); + } + }; + + static String newtWinHandleToHexString(Window w) { + return null != w ? toHexString(w.getWindowHandle()) : "nil"; + } + static String toHexString(long l) { + return "0x"+Long.toHexString(l); + } +} + diff --git a/src/newt/classes/com/jogamp/newt/swt/SWTEDTUtil.java b/src/newt/classes/com/jogamp/newt/swt/SWTEDTUtil.java new file mode 100644 index 000000000..3538caad2 --- /dev/null +++ b/src/newt/classes/com/jogamp/newt/swt/SWTEDTUtil.java @@ -0,0 +1,99 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.newt.swt; + +import org.eclipse.swt.widgets.Display; + +import com.jogamp.newt.util.EDTUtil; + +/** + * Simple {@link EDTUtil} implementation utilizing the SWT UI thread + * of the given {@link Display}. + */ +public class SWTEDTUtil implements EDTUtil { + private final Display swtDisplay; + + public SWTEDTUtil(Display swtDisplay) { + this.swtDisplay = swtDisplay; + } + + public final Display getDisplay() { + return swtDisplay; + } + + @Override + public long getPollPeriod() { + return 0; + } + + @Override + public void setPollPeriod(long ms) { + } + + @Override + public void reset() { + } + + @Override + public void start() { + } + + @Override + public boolean isCurrentThreadEDT() { + return swtDisplay.getThread() == Thread.currentThread(); + } + + @Override + public boolean isRunning() { + return true; + } + + @Override + public void invokeStop(Runnable finalTask) { + swtDisplay.syncExec(finalTask); + } + + @Override + public void invoke(boolean wait, Runnable task) { + if(wait) { + swtDisplay.syncExec(task); + } else { + swtDisplay.asyncExec(task); + } + } + + @Override + public void waitUntilIdle() { + // all sync .. + } + + @Override + public void waitUntilStopped() { + // all sync .. + } +} diff --git a/src/newt/classes/jogamp/newt/DisplayImpl.java b/src/newt/classes/jogamp/newt/DisplayImpl.java index b10561c5b..b178bb5d3 100644 --- a/src/newt/classes/jogamp/newt/DisplayImpl.java +++ b/src/newt/classes/jogamp/newt/DisplayImpl.java @@ -101,7 +101,9 @@ public abstract class DisplayImpl extends Display { display.hashCode = display.fqname.hashCode(); displayList.add(display); } - display.createEDTUtil(); + if(null == display.edtUtil) { + display.setEDTUtil(null); // device's default if EDT is used, or null + } if(DEBUG) { System.err.println("Display.create() NEW: "+display+" "+getThreadName()); } @@ -168,15 +170,45 @@ public abstract class DisplayImpl extends Display { return true; } - protected void createEDTUtil() { + protected EDTUtil createEDTUtil() { + final EDTUtil def; if(NewtFactory.useEDT()) { - edtUtil = new DefaultEDTUtil(Thread.currentThread().getThreadGroup(), "Display-"+getFQName(), dispatchMessagesRunnable); + def = new DefaultEDTUtil(Thread.currentThread().getThreadGroup(), "Display-"+getFQName(), dispatchMessagesRunnable); if(DEBUG) { - System.err.println("Display.createNative("+getFQName()+") Create EDTUtil: "+edtUtil.getClass().getName()); + System.err.println("Display.createNative("+getFQName()+") Create EDTUtil: "+def.getClass().getName()); } + } else { + def = null; } + return def; } + @Override + public EDTUtil setEDTUtil(EDTUtil newEDTUtil) { + if(null == newEDTUtil) { + newEDTUtil = createEDTUtil(); + } + if( newEDTUtil == edtUtil ) { + if(DEBUG) { + System.err.println("Display.setEDTUtil: "+newEDTUtil+" - keep!"); + } + return null; // no change + } + final EDTUtil oldEDTUtil = edtUtil; + if(DEBUG) { + System.err.println("Display.setEDTUtil: "+oldEDTUtil+" -> "+newEDTUtil); + } + if(null != oldEDTUtil) { + stopEDT( new Runnable() { public void run() {} } ); + // ready for restart .. + oldEDTUtil.waitUntilStopped(); + oldEDTUtil.reset(); + } + edtUtil = newEDTUtil; + return oldEDTUtil; + } + + @Override public final EDTUtil getEDTUtil() { return edtUtil; } diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index b12e42680..606101ade 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -445,9 +445,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer protected abstract void closeNativeImpl(); /** - * The native implementation must invoke {@link #focusChanged(boolean, boolean)} - * to change the focus state, if force == false. - * This may happen asynchronous within {@link #TIMEOUT_NATIVEWINDOW}. + * Async request which shall be performed within {@link #TIMEOUT_NATIVEWINDOW}. + *

      + * If if force == false the native implementation + * may only request focus if not yet owner.

      + *

      + * {@link #focusChanged(boolean, boolean)} should be called + * to notify about the focus traversal. + *

      * * @param force if true, bypass {@link #focusChanged(boolean, boolean)} and force focus request */ diff --git a/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java b/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java index ce8ed7c49..747e2368e 100644 --- a/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java +++ b/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java @@ -34,6 +34,7 @@ import javax.media.nativewindow.NativeWindow; import jogamp.newt.driver.DriverUpdatePosition; +import com.jogamp.newt.Window; import com.jogamp.newt.event.awt.AWTAdapter; import com.jogamp.newt.event.awt.AWTWindowAdapter; @@ -92,19 +93,20 @@ public class AWTParentWindowAdapter if(DEBUG_IMPLEMENTATION) { System.err.println("AWT: componentResized: "+comp); } - getNewtWindow().runOnEDTIfAvail(false, new Runnable() { + final Window newtWindow = getNewtWindow(); + newtWindow.runOnEDTIfAvail(false, new Runnable() { public void run() { int cw = comp.getWidth(); int ch = comp.getHeight(); if( 0 < cw * ch ) { - if( getNewtWindow().getWidth() != cw || getNewtWindow().getHeight() != ch ) { - getNewtWindow().setSize(cw, ch); - if(comp.isVisible() != getNewtWindow().isVisible()) { - getNewtWindow().setVisible(comp.isVisible()); + if( newtWindow.getWidth() != cw || newtWindow.getHeight() != ch ) { + newtWindow.setSize(cw, ch); + if(comp.isVisible() != newtWindow.isVisible()) { + newtWindow.setVisible(comp.isVisible()); } } - } else if(getNewtWindow().isVisible()) { - getNewtWindow().setVisible(false); + } else if(newtWindow.isVisible()) { + newtWindow.setVisible(false); } }}); } @@ -113,8 +115,9 @@ public class AWTParentWindowAdapter if(DEBUG_IMPLEMENTATION) { System.err.println("AWT: componentMoved: "+e); } - if(getNewtWindow().getDelegatedWindow() instanceof DriverUpdatePosition) { - ((DriverUpdatePosition)getNewtWindow().getDelegatedWindow()).updatePosition(); + final Window newtWindow = getNewtWindow(); + if(newtWindow.getDelegatedWindow() instanceof DriverUpdatePosition) { + ((DriverUpdatePosition)newtWindow.getDelegatedWindow()).updatePosition(); } } diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java b/src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java index 166da5c1c..65f8b4715 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java +++ b/src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java @@ -36,6 +36,7 @@ package jogamp.newt.driver.awt; import com.jogamp.nativewindow.awt.AWTGraphicsDevice; import com.jogamp.newt.NewtFactory; +import com.jogamp.newt.util.EDTUtil; import jogamp.newt.DisplayImpl; @@ -54,13 +55,17 @@ public class AWTDisplay extends DisplayImpl { protected void closeNativeImpl() { } @Override - protected void createEDTUtil() { + protected EDTUtil createEDTUtil() { + final EDTUtil def; if(NewtFactory.useEDT()) { - edtUtil = AWTEDTUtil.getSingleton(); + def = AWTEDTUtil.getSingleton(); if(DEBUG) { - System.err.println("AWTDisplay.createNative("+getFQName()+") Create EDTUtil: "+edtUtil.getClass().getName()); + System.err.println("AWTDisplay.createNative("+getFQName()+") Create EDTUtil: "+def.getClass().getName()); } + } else { + def = null; } + return def; } protected void dispatchMessagesNative() { /* nop */ } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java index 720d4ee4c..27d7a1679 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java @@ -150,7 +150,7 @@ public class MacWindow extends WindowImpl implements MutableSurface, DriverClear System.err.println("MacWindow: clearFocus() - requestFocusParent, isOffscreenInstance "+isOffscreenInstance); } if(!isOffscreenInstance) { - requestFocusParent0(getWindowHandle()); + resignFocus0(getWindowHandle()); } else { focusChanged(false, false); } @@ -360,7 +360,6 @@ public class MacWindow extends WindowImpl implements MutableSurface, DriverClear if(recreate && 0==surfaceHandle) { throw new NativeWindowException("Internal Error - recreate, window but no view"); } - orderOut0(getWindowHandle()); close0(getWindowHandle()); setWindowHandle(0); } else { @@ -397,7 +396,7 @@ public class MacWindow extends WindowImpl implements MutableSurface, DriverClear private native boolean lockSurface0(long window); private native void unlockSurface0(long window); private native void requestFocus0(long window, boolean force); - private native void requestFocusParent0(long window); + private native void resignFocus0(long window); /** in case of a child window, it actually only issues orderBack(..) */ private native void orderOut0(long window); private native void orderFront0(long window); diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java b/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java index 34d76a148..6a8c81f3d 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java +++ b/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java @@ -151,8 +151,8 @@ public class WindowsWindow extends WindowImpl { } protected void closeNativeImpl() { - if (hdc != 0) { - if(windowHandleClose != 0) { + if(windowHandleClose != 0) { + if (hdc != 0) { try { GDI.ReleaseDC(windowHandleClose, hdc); } catch (Throwable t) { @@ -162,11 +162,8 @@ public class WindowsWindow extends WindowImpl { } } } - hdc = 0; - hdc_old = 0; - } - if(windowHandleClose != 0) { try { + GDI.SetParent(windowHandleClose, 0); // detach first, experience hang w/ SWT parent GDI.DestroyWindow(windowHandleClose); } catch (Throwable t) { if(DEBUG_IMPLEMENTATION) { @@ -177,6 +174,8 @@ public class WindowsWindow extends WindowImpl { windowHandleClose = 0; } } + hdc = 0; + hdc_old = 0; } protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { diff --git a/src/newt/native/MacWindow.m b/src/newt/native/MacWindow.m index 01cbd80ec..bbadc9dd0 100644 --- a/src/newt/native/MacWindow.m +++ b/src/newt/native/MacWindow.m @@ -599,6 +599,15 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_MacWindow_createWindow0 } DBG_PRINT( "createWindow0 - is visible.1: %d\n", [myWindow isVisible]); + // Remove animations for child windows + if(NULL != parentWindow) { +NS_DURING + // Available >= 10.7 - Removes default animations + [myWindow setAnimationBehavior: NSWindowAnimationBehaviorNone]; +NS_HANDLER +NS_ENDHANDLER + } + #ifdef VERBOSE_ON int dbgIdx = 1; #endif @@ -734,7 +743,7 @@ NS_ENDHANDLER if(NULL!=pWin) { [mWin detachFromParent: pWin]; } - [mWin orderOut: mWin]; + [mWin performSelectorOnMainThread:@selector(orderOut:) withObject:mWin waitUntilDone:NO]; DBG_PRINT( "windowClose.1 - %p,%d view %p,%d, parent %p\n", mWin, getRetainCount(mWin), mView, getRetainCount(mView), pWin); @@ -742,11 +751,6 @@ NS_ENDHANDLER // Only release window, if release is not yet in process. // E.g. destroyNotifySent:=true set by NewtMacWindow::windowWillClose(), i.e. window-close was clicked. if(!destroyNotifySent) { - // '[mWin close]' causes a crash at exit. - // This probably happens b/c it sends events to the main loop - // but our resources are gone ?! - // However, issuing a simple release seems to work quite well. - // [mWin release]; [mWin performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO]; } @@ -806,11 +810,8 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_requestFocus0 DBG_PRINT( "requestFocus - window: %p, force %d, hasFocus %d (START)\n", mWin, force, hasFocus); [mWin makeFirstResponder: nil]; - [mWin performSelectorOnMainThread:@selector(orderFrontRegardless) withObject:nil waitUntilDone:YES]; - [mWin performSelectorOnMainThread:@selector(makeKeyWindow) withObject:nil waitUntilDone:YES]; - // This will occasionally cause a free of non allocated object crash: - // [mWin orderFrontRegardless]; - // [mWin makeKeyWindow]; + [mWin performSelectorOnMainThread:@selector(orderFrontRegardless) withObject:nil waitUntilDone:NO]; + [mWin performSelectorOnMainThread:@selector(makeKeyWindow) withObject:nil waitUntilDone:NO]; DBG_PRINT( "requestFocus - window: %p, force %d (END)\n", mWin, force); @@ -819,26 +820,27 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_requestFocus0 /* * Class: jogamp_newt_driver_macosx_MacWindow - * Method: requestFocusParent0 + * Method: resignFocus0 * Signature: (J)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_requestFocusParent0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_resignFocus0 (JNIEnv *env, jobject window, jlong w) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; NSWindow* mWin = (NSWindow*) ((intptr_t) w); NSWindow* pWin = [mWin parentWindow]; -#ifdef VERBOSE_ON BOOL hasFocus = [mWin isKeyWindow]; -#endif - DBG_PRINT( "requestFocusParent0 - window: %p, parent: %p, hasFocus %d (START)\n", mWin, pWin, hasFocus ); - if(NULL != pWin) { - [pWin performSelectorOnMainThread:@selector(makeKeyWindow) withObject:nil waitUntilDone:YES]; - // This will occasionally cause a free of non allocated object crash: - // [pWin makeKeyWindow]; + DBG_PRINT( "requestFocusParent0 - window: %p, parent %p, hasFocus %d (START)\n", mWin, pWin, hasFocus ); + if( hasFocus ) { + if(NULL != pWin) { + // [mWin performSelectorOnMainThread:@selector(makeFirstResponder:) withObject:pWin waitUntilDone:NO]; + [pWin performSelectorOnMainThread:@selector(makeKeyWindow) withObject:nil waitUntilDone:NO]; + } else { + [mWin performSelectorOnMainThread:@selector(resignKeyWindow) withObject:nil waitUntilDone:NO]; + } } - DBG_PRINT( "requestFocusParent0 - window: %p, parent: %p (END)\n", mWin, pWin); + DBG_PRINT( "requestFocusParent0 - window: %p (END)\n", mWin); [pool release]; } @@ -856,9 +858,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_orderFront0 DBG_PRINT( "orderFront0 - window: %p (START)\n", win); - [win performSelectorOnMainThread:@selector(orderFrontRegardless) withObject:nil waitUntilDone:YES]; - // This will occasionally cause a free of non allocated object crash: - // [win orderFrontRegardless]; + [win performSelectorOnMainThread:@selector(orderFrontRegardless) withObject:nil waitUntilDone:NO]; DBG_PRINT( "orderFront0 - window: %p (END)\n", win); @@ -880,13 +880,9 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_orderOut0 DBG_PRINT( "orderOut0 - window: (parent %p) %p (START)\n", pWin, mWin); if(NULL == pWin) { - [mWin performSelectorOnMainThread:@selector(orderOut:) withObject:mWin waitUntilDone:YES]; - // This will occasionally cause a free of non allocated object crash: - // [mWin orderOut: mWin]; + [mWin performSelectorOnMainThread:@selector(orderOut:) withObject:mWin waitUntilDone:NO]; } else { - [mWin performSelectorOnMainThread:@selector(orderBack:) withObject:mWin waitUntilDone:YES]; - // This will occasionally cause a free of non allocated object crash: - // [mWin orderBack: mWin]; + [mWin performSelectorOnMainThread:@selector(orderBack:) withObject:mWin waitUntilDone:NO]; } DBG_PRINT( "orderOut0 - window: (parent %p) %p (END)\n", pWin, mWin); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestNewtCanvasSWTGLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestNewtCanvasSWTGLn.java new file mode 100644 index 000000000..6a27e6f27 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestNewtCanvasSWTGLn.java @@ -0,0 +1,233 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.swt; + +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLProfile; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + +import org.junit.Assert; +import org.junit.Assume; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.After; +import org.junit.Test; + +import com.jogamp.nativewindow.swt.SWTAccessor; +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.newt.swt.NewtCanvasSWT; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.jogl.demos.es2.MultisampleDemoES2; +import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.util.Animator; +import com.jogamp.opengl.util.GLReadBufferUtil; +import com.jogamp.opengl.util.texture.TextureIO; + +/** + * Tests that a basic SWT app can open without crashing under different GL profiles + * _and_ custom GLCapabilities. + *

      + * Uses JOGL's NewtCanvasSWT, which allows to be a native container of a NEWT Window.
      + * This method allows utilizing custom GLCapability settings, + * independent from the already instantiated SWT visual. + *

      + *

      + * Note that {@link SWTAccessor#invoke(boolean, Runnable)} is still used to comply w/ + * SWT running on Mac OSX, i.e. to enforce UI action on the main thread. + *

      + */ +public class TestNewtCanvasSWTGLn extends UITestCase { + + static int duration = 250; + + static final int iwidth = 640; + static final int iheight = 480; + + Display display = null; + Shell shell = null; + Composite composite = null; + + @BeforeClass + public static void startup() { + System.out.println( "GLProfile " + GLProfile.glAvailabilityToString() ); + } + + @Before + public void init() { + SWTAccessor.invoke(true, new Runnable() { + public void run() { + display = new Display(); + Assert.assertNotNull( display ); + shell = new Shell( display ); + Assert.assertNotNull( shell ); + shell.setLayout( new FillLayout() ); + composite = new Composite( shell, SWT.NONE ); + composite.setLayout( new FillLayout() ); + Assert.assertNotNull( composite ); + }}); + } + + @After + public void release() { + Assert.assertNotNull( display ); + Assert.assertNotNull( shell ); + Assert.assertNotNull( composite ); + try { + SWTAccessor.invoke(true, new Runnable() { + public void run() { + composite.dispose(); + shell.dispose(); + display.dispose(); + }}); + } + catch( Throwable throwable ) { + throwable.printStackTrace(); + Assume.assumeNoException( throwable ); + } + display = null; + shell = null; + composite = null; + } + + protected void runTestAGL( GLCapabilitiesImmutable caps, GLEventListener demo, + boolean postAttach, boolean useAnimator ) throws InterruptedException { + final GLReadBufferUtil screenshot = new GLReadBufferUtil(false, false); + + final GLWindow glWindow1 = GLWindow.create(caps); + Assert.assertNotNull(glWindow1); + Assert.assertEquals(false, glWindow1.isVisible()); + Assert.assertEquals(false, glWindow1.isNativeValid()); + Assert.assertNull(glWindow1.getParent()); + glWindow1.addGLEventListener(demo); + glWindow1.addGLEventListener(new GLEventListener() { + int displayCount = 0; + public void init(final GLAutoDrawable drawable) { } + public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) { } + public void display(final GLAutoDrawable drawable) { + if(displayCount < 3) { + snapshot(getSimpleTestName("."), displayCount++, null, drawable.getGL(), screenshot, TextureIO.PNG, null); + } + } + public void dispose(final GLAutoDrawable drawable) { } + }); + + final NewtCanvasSWT canvas1 = NewtCanvasSWT.create( composite, 0, postAttach ? null : glWindow1 ); + Assert.assertNotNull( canvas1 ); + + SWTAccessor.invoke(true, new Runnable() { + public void run() { + shell.setText( getSimpleTestName(".") ); + shell.setSize( 640, 480 ); + shell.open(); + } + }); + + if(postAttach) { + canvas1.setNEWTChild(glWindow1); + } + + // canvas1.update(); + + Animator anim; + if(useAnimator) { + anim = new Animator(glWindow1); + anim.start(); + } else { + anim = null; + } + + long lStartTime = System.currentTimeMillis(); + long lEndTime = lStartTime + duration; + try { + while( (System.currentTimeMillis() < lEndTime) && !canvas1.isDisposed() ) { + if( !display.readAndDispatch() ) { + // blocks on linux .. display.sleep(); + Thread.sleep(10); + } + } + } catch( Throwable throwable ) { + throwable.printStackTrace(); + Assume.assumeNoException( throwable ); + } + if(null != anim) { + anim.stop(); + } + + canvas1.dispose(); + } + + @Test + public void preAttach_WithAnimator() throws InterruptedException { + runTestAGL( new GLCapabilities(GLProfile.getGL2ES2()), new GearsES2(), false /* postAttach */, true /* animator */); + } + + @Test + public void preAttach_NoAnimator() throws InterruptedException { + runTestAGL( new GLCapabilities(GLProfile.getGL2ES2()), new GearsES2(), false /* postAttach */, false /* animator */); + } + + @Test + public void postAttach_WithAnimator() throws InterruptedException { + runTestAGL( new GLCapabilities(GLProfile.getGL2ES2()), new GearsES2(), true /* postAttach */, true /* animator */); + } + + @Test + public void test_MultisampleAndAlpha() throws InterruptedException { + GLCapabilities caps = new GLCapabilities(GLProfile.getGL2ES2()); + caps.setSampleBuffers(true); + caps.setNumSamples(2); + runTestAGL( caps, new MultisampleDemoES2(true), false /* postAttach */, false /* animator */); + } + + static int atoi(String a) { + int i=0; + try { + i = Integer.parseInt(a); + } catch (Exception ex) { ex.printStackTrace(); } + return i; + } + + public static void main(String args[]) { + for(int i=0; i - * Uses JOGL's SWTAccessor only. - *

      - * @author Wade Walker, et.al. - */ -public class TestSWTAccessor02GLn extends UITestCase { - - static int duration = 250; - - static final int iwidth = 640; - static final int iheight = 480; - - Display display = null; - Shell shell = null; - Composite composite = null; - - @BeforeClass - public static void startup() { - System.out.println( "GLProfile " + GLProfile.glAvailabilityToString() ); - } - - @Before - public void init() { - SWTAccessor.invoke(true, new Runnable() { - public void run() { - display = new Display(); - Assert.assertNotNull( display ); - shell = new Shell( display ); - Assert.assertNotNull( shell ); - shell.setLayout( new FillLayout() ); - composite = new Composite( shell, SWT.NONE ); - composite.setLayout( new FillLayout() ); - Assert.assertNotNull( composite ); - }}); - } - - @After - public void release() { - Assert.assertNotNull( display ); - Assert.assertNotNull( shell ); - Assert.assertNotNull( composite ); - try { - SWTAccessor.invoke(true, new Runnable() { - public void run() { - composite.dispose(); - shell.dispose(); - display.dispose(); - }}); - } - catch( Throwable throwable ) { - throwable.printStackTrace(); - Assume.assumeNoException( throwable ); - } - display = null; - shell = null; - composite = null; - } - - protected void runTestAGL( GLProfile glprofile ) throws InterruptedException { - GLCapabilities caps = new GLCapabilities(glprofile); - GLDrawableFactory factory = GLDrawableFactory.getFactory(glprofile); - - // need SWT.NO_BACKGROUND to prevent SWT from clearing the window - // at the wrong times (we use glClear for this instead) - final Canvas canvas = new Canvas( composite, SWT.NO_BACKGROUND); - Assert.assertNotNull( canvas ); - SWTAccessor.setRealized(canvas, true); - - AbstractGraphicsDevice device = SWTAccessor.getDevice(canvas); - long nativeWindowHandle = SWTAccessor.getWindowHandle(canvas); - System.err.println("*** device: " + device); - System.err.println("*** window handle: 0x" + Long.toHexString(nativeWindowHandle)); - - final SWTUpstreamHook swtUpstreamHook = new SWTUpstreamHook(canvas); - canvas.addControlListener(swtUpstreamHook); - - final ProxySurface proxySurface = factory.createProxySurface(device, 0, nativeWindowHandle, caps, null, swtUpstreamHook); - Assert.assertNotNull( proxySurface ); - System.err.println("*** ProxySurface: " + proxySurface); - - final GLDrawable drawable = factory.createGLDrawable(proxySurface); - Assert.assertNotNull( drawable ); - drawable.setRealized(true); - System.err.println("*** Drawable: " + drawable); - Assert.assertTrue( drawable.isRealized() ); - - final GLContext glcontext = drawable.createContext(null); - // trigger native creation .. - if( GLContext.CONTEXT_NOT_CURRENT < glcontext.makeCurrent() ) { - glcontext.release(); - } - - final boolean[] sizeMissing = new boolean[] { false }; - - // fix the viewport when the user resizes the window - canvas.addListener( SWT.Resize, new Listener() { - public void handleEvent( Event event ) { - Rectangle rectangle = canvas.getClientArea(); - boolean glok=false; - if( GLContext.CONTEXT_NOT_CURRENT < glcontext.makeCurrent() ) { - glok=true; - GL2ES1 gl = glcontext.getGL().getGL2ES1(); - OneTriangle.setup( gl, rectangle.width, rectangle.height ); - glcontext.release(); - } else { - sizeMissing[0] = true; - } - System.err.println("resize: glok " + glok); - } - }); - - // draw the triangle when the OS tells us that any part of the window needs drawing - canvas.addPaintListener( new PaintListener() { - public void paintControl( PaintEvent paintevent ) { - Rectangle rectangle = canvas.getClientArea(); - boolean glok=false; - if( GLContext.CONTEXT_NOT_CURRENT < glcontext.makeCurrent() ) { - glok=true; - GL2ES1 gl = glcontext.getGL().getGL2ES1(); - if(sizeMissing[0]) { - OneTriangle.setup( gl, rectangle.width, rectangle.height); - sizeMissing[0] = false; - } - OneTriangle.render( gl, rectangle.width, rectangle.height); - drawable.swapBuffers(); - glcontext.release(); - } - System.err.println("paint: glok " + glok); - } - }); - - shell.setText( getClass().getName() ); - shell.setSize( 640, 480 ); - shell.open(); - - long lStartTime = System.currentTimeMillis(); - long lEndTime = lStartTime + duration; - try { - while( (System.currentTimeMillis() < lEndTime) && !canvas.isDisposed() ) { - if( !display.readAndDispatch() ) { - // blocks on linux .. display.sleep(); - Thread.sleep(10); - } - } - } catch( Throwable throwable ) { - throwable.printStackTrace(); - Assume.assumeNoException( throwable ); - } - glcontext.destroy(); - drawable.setRealized(false); - canvas.dispose(); - } - private static class SWTUpstreamHook implements ProxySurface.UpstreamSurfaceHook, ControlListener { - private Canvas c; - Rectangle clientArea; - public SWTUpstreamHook(Canvas c) { - this.c = c ; - this.clientArea = c.getClientArea(); - } - @Override - public final void create(ProxySurface s) { /* nop */ } - - @Override - public final void destroy(ProxySurface s) { /* nop */ } - - @Override - public final int getWidth(ProxySurface s) { - return clientArea.width; - } - @Override - public final int getHeight(ProxySurface s) { - return clientArea.width; - } - - @Override - public void controlResized(final ControlEvent arg0) { - clientArea = c.getClientArea(); - } - @Override - public void controlMoved(ControlEvent e) { - } - @Override - public String toString() { - final String us_s = null != c ? c.toString() : "nil"; - return "SETUpstreamSurfaceHook[upstream: "+us_s+"]"; - } - }; - - @Test - public void test() throws InterruptedException { - GLProfile glprofile = GLProfile.getGL2ES1(); - runTestAGL( glprofile ); - } - - static int atoi(String a) { - int i=0; - try { - i = Integer.parseInt(a); - } catch (Exception ex) { ex.printStackTrace(); } - return i; - } - - public static void main(String args[]) { - for(int i=0; i *

      + * Note: To employ custom GLCapabilities, NewtCanvasSWT shall be used. + *

      + *

      * Note that {@link SWTAccessor#invoke(boolean, Runnable)} is still used to comply w/ * SWT running on Mac OSX, i.e. to enforce UI action on the main thread. *

      @@ -116,34 +121,32 @@ public class TestSWTJOGLGLCanvas01GLn extends UITestCase { composite = null; } - protected void runTestAGL( GLProfile glprofile ) throws InterruptedException { - // need SWT.NO_BACKGROUND to prevent SWT from clearing the window - // at the wrong times (we use glClear for this instead) - final GLCapabilitiesImmutable caps = new GLCapabilities( glprofile ); + protected void runTestAGL( GLCapabilitiesImmutable caps, GLEventListener demo ) throws InterruptedException { + final GLReadBufferUtil screenshot = new GLReadBufferUtil(false, false); - final GLCanvas canvas = new GLCanvas( composite, 0, caps, null, null); + final GLCanvas canvas = GLCanvas.create( composite, 0, caps, null, null); Assert.assertNotNull( canvas ); + canvas.addGLEventListener( demo ); canvas.addGLEventListener(new GLEventListener() { - public void init(final GLAutoDrawable drawable) { - System.err.println(Thread.currentThread().getName()+" - SWT Canvas - GLEventListener - init()"); - } - public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) { - System.err.println(Thread.currentThread().getName()+" - SWT Canvas - GLEventListener - reshape()"); - OneTriangle.setup( drawable.getGL().getGL2(), width, height ); - } + int displayCount = 0; + public void init(final GLAutoDrawable drawable) { } + public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) { } public void display(final GLAutoDrawable drawable) { - OneTriangle.render( drawable.getGL().getGL2(), drawable.getWidth(), drawable.getHeight()); + if(displayCount < 3) { + snapshot(getSimpleTestName("."), displayCount++, null, drawable.getGL(), screenshot, TextureIO.PNG, null); + } } - public void dispose(final GLAutoDrawable drawable) { - System.err.println(Thread.currentThread().getName()+" - SWT Canvas - GLEventListener - dispose()"); - } - }); + public void dispose(final GLAutoDrawable drawable) { } + }); - shell.setText( getClass().getName() ); - shell.setSize( 640, 480 ); - shell.open(); - + SWTAccessor.invoke(true, new Runnable() { + public void run() { + shell.setText( getSimpleTestName(".") ); + shell.setSize( 640, 480 ); + shell.open(); + } } ); + long lStartTime = System.currentTimeMillis(); long lEndTime = lStartTime + duration; try { @@ -157,13 +160,15 @@ public class TestSWTJOGLGLCanvas01GLn extends UITestCase { throwable.printStackTrace(); Assume.assumeNoException( throwable ); } - canvas.dispose(); + SWTAccessor.invoke(true, new Runnable() { + public void run() { + canvas.dispose(); + } } ); } @Test public void test() throws InterruptedException { - GLProfile glprofile = GLProfile.getGL2ES1(); - runTestAGL( glprofile ); + runTestAGL( new GLCapabilities(GLProfile.getGL2ES2()), new GearsES2() ); } static int atoi(String a) { diff --git a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01aSWT.java b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01aSWT.java new file mode 100644 index 000000000..11aef7c24 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01aSWT.java @@ -0,0 +1,210 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.newt.parenting; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; + +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLEventListener; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.junit.After; +import org.junit.Assert; +import org.junit.Assume; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.jogamp.nativewindow.swt.SWTAccessor; +import com.jogamp.newt.Window; +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.newt.swt.NewtCanvasSWT; +import com.jogamp.opengl.test.junit.jogl.demos.es2.RedSquareES2; +import com.jogamp.opengl.test.junit.util.MiscUtils; +import com.jogamp.opengl.test.junit.util.UITestCase; + +/** + * Simple visibility test .. + */ +public class TestParenting01aSWT extends UITestCase { + static int width, height; + static long durationPerTest = 800; + static GLCapabilities glCaps; + + Display display = null; + Shell shell = null; + Composite composite1 = null; + + @BeforeClass + public static void initClass() { + width = 640; + height = 480; + glCaps = new GLCapabilities(null); + } + + @Before + public void init() { + SWTAccessor.invoke(true, new Runnable() { + public void run() { + display = new Display(); + Assert.assertNotNull( display ); + shell = new Shell( display ); + Assert.assertNotNull( shell ); + shell.setLayout( new FillLayout() ); + composite1 = new Composite( shell, SWT.NONE ); + composite1.setLayout( new FillLayout() ); + Assert.assertNotNull( composite1 ); + }}); + } + + @After + public void release() { + Assert.assertNotNull( display ); + Assert.assertNotNull( shell ); + Assert.assertNotNull( composite1 ); + try { + SWTAccessor.invoke(true, new Runnable() { + public void run() { + composite1.dispose(); + shell.dispose(); + display.dispose(); + }}); + } + catch( Throwable throwable ) { + throwable.printStackTrace(); + Assume.assumeNoException( throwable ); + } + display = null; + shell = null; + composite1 = null; + } + + @Test + public void testWindowParenting01CreateVisibleDestroy1() throws InterruptedException, InvocationTargetException { + + GLWindow glWindow1 = GLWindow.create(glCaps); + Assert.assertNotNull(glWindow1); + Assert.assertEquals(false, glWindow1.isVisible()); + Assert.assertEquals(false, glWindow1.isNativeValid()); + Assert.assertNull(glWindow1.getParent()); + glWindow1.setTitle("testWindowParenting01CreateVisibleDestroy"); + GLEventListener demo1 = new RedSquareES2(); + setDemoFields(demo1, glWindow1, false); + glWindow1.addGLEventListener(demo1); + + final NewtCanvasSWT canvas1 = NewtCanvasSWT.create( composite1, 0, glWindow1 ); + Assert.assertNotNull(canvas1); + Assert.assertEquals(false, glWindow1.isVisible()); + Assert.assertEquals(false, glWindow1.isNativeValid()); + Assert.assertNull(glWindow1.getParent()); + + SWTAccessor.invoke(true, new Runnable() { + public void run() { + shell.setText( getSimpleTestName(".") ); + shell.setSize( 640, 480 ); + shell.open(); + } + }); + + // visible test + Assert.assertEquals(canvas1.getNativeWindow(),glWindow1.getParent()); + + for(int i=0; i*10 2 + if(detachFirst) { + canvas1.setNEWTChild(null); + canvas2.setNEWTChild(null); + } else { + canvas2.setNEWTChild(null); // free g2 of w2 + } + canvas1.setNEWTChild(glWindow2); // put g2 -> w1. free g1 of w1 + canvas2.setNEWTChild(glWindow1); // put g1 -> w2 + frame1.validate(); + frame2.validate(); + } + }); + break; + case 1: + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + // 2 -> 1 + if(detachFirst) { + canvas1.setNEWTChild(null); + canvas2.setNEWTChild(null); + } else { + canvas2.setNEWTChild(null); + } + canvas1.setNEWTChild(glWindow1); + canvas2.setNEWTChild(glWindow2); + frame1.validate(); + frame2.validate(); + } + }); + break; + } + } + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame1.dispose(); + frame2.dispose(); + } } ); + glWindow1.destroy(); + glWindow2.destroy(); + Assert.assertEquals(false, glWindow1.isNativeValid()); + Assert.assertEquals(false, glWindow2.isNativeValid()); + } + + public static void setDemoFields(GLEventListener demo, GLWindow glWindow, boolean debug) { + Assert.assertNotNull(demo); + Assert.assertNotNull(glWindow); + Window window = glWindow.getDelegatedWindow(); + if(debug) { + MiscUtils.setFieldIfExists(demo, "glDebug", true); + MiscUtils.setFieldIfExists(demo, "glTrace", true); + } + if(!MiscUtils.setFieldIfExists(demo, "window", window)) { + MiscUtils.setFieldIfExists(demo, "glWindow", glWindow); + } + } + + static int atoi(String a) { + int i=0; + try { + i = Integer.parseInt(a); + } catch (Exception ex) { ex.printStackTrace(); } + return i; + } + + public static void main(String args[]) throws IOException { + for(int i=0; i 2 + if(detachFirst) { + canvas1.setNEWTChild(null); + canvas2.setNEWTChild(null); + } else { + canvas2.setNEWTChild(null); // free g2 of w2 + } + canvas1.setNEWTChild(glWindow2); // put g2 -> w1. free g1 of w1 + canvas2.setNEWTChild(glWindow1); // put g1 -> w2 + } } ); + break; + case 1: + SWTAccessor.invoke(true, new Runnable() { + public void run() { + // 2 -> 1 + if(detachFirst) { + canvas1.setNEWTChild(null); + canvas2.setNEWTChild(null); + } else { + canvas2.setNEWTChild(null); + } + canvas1.setNEWTChild(glWindow1); + canvas2.setNEWTChild(glWindow2); + } } ); + break; + } + } + + canvas1.dispose(); + canvas2.dispose(); + Assert.assertEquals(false, glWindow1.isNativeValid()); + Assert.assertEquals(false, glWindow2.isNativeValid()); + } + + public static void setDemoFields(GLEventListener demo, GLWindow glWindow, boolean debug) { + Assert.assertNotNull(demo); + Assert.assertNotNull(glWindow); + Window window = glWindow.getDelegatedWindow(); + if(debug) { + MiscUtils.setFieldIfExists(demo, "glDebug", true); + MiscUtils.setFieldIfExists(demo, "glTrace", true); + } + if(!MiscUtils.setFieldIfExists(demo, "window", window)) { + MiscUtils.setFieldIfExists(demo, "glWindow", glWindow); + } + } + + static int atoi(String a) { + int i=0; + try { + i = Integer.parseInt(a); + } catch (Exception ex) { ex.printStackTrace(); } + return i; + } + + public static void main(String args[]) throws IOException { + for(int i=0; i Date: Fri, 3 Aug 2012 01:38:37 +0300 Subject: Fix X11 Display Connection leak w/ new GLAutoDrawableBase code when used w/ offscreen drawables, reported by Mark Raynsford New common GLAutoDrawableBase missed to close the AbstractGraphicsDevice in case it has been created and dedicated for the passed GLDrawable. This detailed knowledge is only known to the creator, hence it is passed in the constructor and is being passed through all specializations. Further more the new X11/GLX impl. of GLDrawableFactory's 'createMutableSurfaceImpl' always creates it's own private X11 display connection to avoid locking / threading issues. Since the old implementation reused the shared display connection which is prone to threading issues, this bug was not visible before. Also fixed the unit test TestNEWTCloseX11DisplayBug565, now correctly validating that no display connection is left over after a new cycle of create/destroy of onscreen and offscreen drawables. --- make/scripts/tests.sh | 6 ++-- .../com/jogamp/opengl/OffscreenAutoDrawable.java | 13 ++++++-- .../javax/media/opengl/GLAutoDrawableDelegate.java | 14 +++++--- .../classes/jogamp/opengl/GLAutoDrawableBase.java | 39 ++++++++++++++++------ .../jogamp/opengl/GLDrawableFactoryImpl.java | 2 +- src/jogl/classes/jogamp/opengl/GLPbufferImpl.java | 4 +-- .../classes/jogamp/nativewindow/x11/X11Util.java | 2 +- .../classes/com/jogamp/newt/opengl/GLWindow.java | 2 +- .../test/junit/jogl/acore/TestFBODrawableNEWT.java | 2 +- .../jogl/acore/TestGLAutoDrawableDelegateNEWT.java | 2 +- .../acore/TestGLContextDrawableSwitchNEWT.java | 2 +- .../jogl/acore/TestNEWTCloseX11DisplayBug565.java | 8 ++--- 12 files changed, 64 insertions(+), 32 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index af6218968..43d04c6bd 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -61,7 +61,7 @@ function jrun() { #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all -Djogamp.debug.Lock" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all" - D_ARGS="-Dnewt.debug.Window" + #D_ARGS="-Dnewt.debug.Window" #D_ARGS="-Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.EGLDrawableFactory.DontQuery -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.EGLDrawableFactory.QueryNativeTK -Djogl.debug.GLDrawable" @@ -217,7 +217,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFloatUtil01MatrixMatrixMultNOUI $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestNEWTCloseX11DisplayBug565 $* +testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestNEWTCloseX11DisplayBug565 $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $* @@ -328,7 +328,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting03AWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT $* #testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aSWT $* -testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* +#testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01GLCanvasAWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer02NewtCanvasAWT $* diff --git a/src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java b/src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java index 1ea8595c6..8450ffdb0 100644 --- a/src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java +++ b/src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java @@ -28,6 +28,7 @@ package com.jogamp.opengl; +import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.opengl.GLAutoDrawableDelegate; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; @@ -45,8 +46,16 @@ import jogamp.opengl.GLFBODrawableImpl; */ public class OffscreenAutoDrawable extends GLAutoDrawableDelegate { - public OffscreenAutoDrawable(GLDrawable drawable, GLContext context, Object upstreamWidget) { - super(drawable, context, upstreamWidget); + /** + * @param drawable a valid {@link GLDrawable}, may not be realized yet. + * @param context a valid {@link GLContext}, may not be made current (created) yet. + * @param ownDevice pass true if {@link AbstractGraphicsDevice#close()} shall be issued, + * otherwise pass false. Closing the device is required in case + * the drawable is created w/ it's own new instance, e.g. offscreen drawables, + * and no further lifecycle handling is applied. + */ + public OffscreenAutoDrawable(GLDrawable drawable, GLContext context, boolean ownDevice) { + super(drawable, context, null, ownDevice); } /** diff --git a/src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java b/src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java index 76959f3f4..67e81270d 100644 --- a/src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java +++ b/src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java @@ -28,6 +28,8 @@ package javax.media.opengl; +import javax.media.nativewindow.AbstractGraphicsDevice; + import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; @@ -57,12 +59,16 @@ public class GLAutoDrawableDelegate extends GLAutoDrawableBase { public static final boolean DEBUG = Debug.debug("GLAutoDrawableDelegate"); /** - * @param drawable - * @param context + * @param drawable a valid {@link GLDrawable}, may not be realized yet. + * @param context a valid {@link GLContext}, may not be made current (created) yet. * @param upstreamWidget optional UI element holding this instance, see {@link #getUpstreamWidget()}. + * @param ownDevice pass true if {@link AbstractGraphicsDevice#close()} shall be issued, + * otherwise pass false. Closing the device is required in case + * the drawable is created w/ it's own new instance, e.g. offscreen drawables, + * and no further lifecycle handling is applied. */ - public GLAutoDrawableDelegate(GLDrawable drawable, GLContext context, Object upstreamWidget) { - super((GLDrawableImpl)drawable, (GLContextImpl)context); + public GLAutoDrawableDelegate(GLDrawable drawable, GLContext context, Object upstreamWidget, boolean ownDevice) { + super((GLDrawableImpl)drawable, (GLContextImpl)context, ownDevice); this.upstreamWidget = null; } diff --git a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java index fe6d0fd76..cc4e1b434 100644 --- a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java +++ b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java @@ -30,6 +30,8 @@ package jogamp.opengl; import java.io.PrintStream; +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.WindowClosingProtocol; import javax.media.nativewindow.WindowClosingProtocol.WindowClosingMode; @@ -66,13 +68,23 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { protected volatile GLDrawableImpl drawable; // volatile: avoid locking for read-only access protected GLContextImpl context; + protected final boolean ownDevice; protected int additionalCtxCreationFlags = 0; protected volatile boolean sendReshape = false; // volatile: maybe written by WindowManager thread w/o locking protected volatile boolean sendDestroy = false; // volatile: maybe written by WindowManager thread w/o locking - public GLAutoDrawableBase(GLDrawableImpl drawable, GLContextImpl context) { + /** + * @param drawable a valid {@link GLDrawableImpl}, may not be realized yet. + * @param context a valid {@link GLContextImpl}, may not be made current (created) yet. + * @param ownDevice pass true if {@link AbstractGraphicsDevice#close()} shall be issued, + * otherwise pass false. Closing the device is required in case + * the drawable is created w/ it's own new instance, e.g. offscreen drawables, + * and no further lifecycle handling is applied. + */ + public GLAutoDrawableBase(GLDrawableImpl drawable, GLContextImpl context, boolean ownDevice) { this.drawable = drawable; this.context = context; + this.ownDevice = ownDevice; resetFPSCounter(); } @@ -174,7 +186,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { } /** - * Calls {@link #destroyImplInLock()} while claiming the lock. + * Calls {@link #destroyImplInLock()} while claiming the lock. */ protected final void defaultDestroy() { final RecursiveLock lock = getLock(); @@ -200,17 +212,22 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { protected void destroyImplInLock() { final GLContext _context = context; final GLDrawable _drawable = drawable; - if( null != _drawable && _drawable.isRealized() ) { - if( null != _context && _context.isCreated() ) { - // Catch dispose GLExceptions by GLEventListener, just 'print' them - // so we can continue with the destruction. - try { - helper.disposeGL(this, _drawable, _context, null); - } catch (GLException gle) { - gle.printStackTrace(); + if( null != _drawable ) { + if( _drawable.isRealized() ) { + if( null != _context && _context.isCreated() ) { + // Catch dispose GLExceptions by GLEventListener, just 'print' them + // so we can continue with the destruction. + try { + helper.disposeGL(this, _drawable, _context, null); + } catch (GLException gle) { + gle.printStackTrace(); + } } + _drawable.setRealized(false); + } + if( ownDevice ) { + _drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice().close(); } - _drawable.setRealized(false); } context = null; drawable = null; diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index f092288fb..f7808294b 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -245,7 +245,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { if(null==drawable) { throw new GLException("Could not create Pbuffer drawable for: "+device+", "+capsChosen+", "+width+"x"+height); } - return new GLPbufferImpl( drawable, shareWith); + return new GLPbufferImpl( drawable, shareWith, true); } //--------------------------------------------------------------------------- diff --git a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java index 6b64120fe..32f4cb696 100644 --- a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java @@ -58,8 +58,8 @@ import com.jogamp.common.util.locks.RecursiveLock; public class GLPbufferImpl extends GLAutoDrawableBase implements GLPbuffer { private int floatMode; - public GLPbufferImpl(GLDrawableImpl pbufferDrawable, GLContext sharedContext) { - super(pbufferDrawable, null); // drawable := pbufferDrawable + public GLPbufferImpl(GLDrawableImpl pbufferDrawable, GLContext sharedContext, boolean ownDevice) { + super(pbufferDrawable, null, ownDevice); // drawable := pbufferDrawable GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) drawable.getNativeSurface().getGraphicsConfiguration().getChosenCapabilities(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index fcc374751..7b46a1df0 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -255,7 +255,7 @@ public class X11Util { */ public static int shutdown(boolean realXCloseOpenAndPendingDisplays, boolean verbose) { int num=0; - if(DEBUG||verbose||pendingDisplayList.size() > 0) { + if(DEBUG || verbose || openDisplayMap.size() > 0 || pendingDisplayList.size() > 0) { System.err.println("X11Util.Display: Shutdown (close open / pending Displays: "+realXCloseOpenAndPendingDisplays+ ", open (no close attempt): "+openDisplayMap.size()+"/"+openDisplayList.size()+ ", pending (not closed, marked uncloseable): "+pendingDisplayList.size()+")"); diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index d662a743a..0fc1b4e89 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -97,7 +97,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind * Constructor. Do not call this directly -- use {@link #create()} instead. */ protected GLWindow(Window window) { - super(null, null); + super(null, null, false); this.window = (WindowImpl) window; this.window.setHandleDestroyNotify(false); window.addWindowListener(new WindowAdapter() { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java index 1a33845b3..7977347a7 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java @@ -167,7 +167,7 @@ public class TestFBODrawableNEWT extends UITestCase { final FBObject.RenderAttachment depthA = fbo.getDepthAttachment(); Assert.assertNotNull(depthA); - final OffscreenAutoDrawable glad = new OffscreenAutoDrawable(fboDrawable, context, null); + final OffscreenAutoDrawable glad = new OffscreenAutoDrawable(fboDrawable, context, true); glad.addGLEventListener(demo); glad.addGLEventListener(new GLEventListener() { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateNEWT.java index 426b7734f..96d9b2e28 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateNEWT.java @@ -85,7 +85,7 @@ public class TestGLAutoDrawableDelegateNEWT extends UITestCase { Assert.assertTrue(GLContext.CONTEXT_CURRENT_NEW==res || GLContext.CONTEXT_CURRENT==res); context.release(); - final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(drawable, context, window) { + final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(drawable, context, window, false) { @Override protected void destroyImplInLock() { super.destroyImplInLock(); // destroys drawable/context diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitchNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitchNEWT.java index 92b4c5238..cece4c6d5 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitchNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitchNEWT.java @@ -88,7 +88,7 @@ public class TestGLContextDrawableSwitchNEWT extends UITestCase { drawable.setRealized(true); Assert.assertTrue(drawable.isRealized()); - final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(drawable, null, window) { + final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(drawable, null, window, false) { @Override protected void destroyImplInLock() { super.destroyImplInLock(); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNEWTCloseX11DisplayBug565.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNEWTCloseX11DisplayBug565.java index e14d5b800..33a9b7799 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNEWTCloseX11DisplayBug565.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNEWTCloseX11DisplayBug565.java @@ -43,10 +43,10 @@ public class TestNEWTCloseX11DisplayBug565 { if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false)) { final int openD = X11Util.getOpenDisplayConnectionNumber() - open0; - if(openD>1) { + if( openD > 0) { X11Util.dumpOpenDisplayConnections(); X11Util.dumpPendingDisplayConnections(); - Assert.assertTrue("More than 1 new open display connections", false); + Assert.assertEquals("New display connection didn't close", 0, openD); } } } @@ -86,10 +86,10 @@ public class TestNEWTCloseX11DisplayBug565 { if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false)) { final int openD = X11Util.getOpenDisplayConnectionNumber() - open0; - if(openD>1) { + if(openD > 0) { X11Util.dumpOpenDisplayConnections(); X11Util.dumpPendingDisplayConnections(); - Assert.assertTrue("More than 1 new open display connections", false); + Assert.assertEquals("New display connection didn't close", 0, openD); } } } -- cgit v1.2.3 From 43a473b2005d7f59a7f4f5b8bc7ca9ae88b4e894 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 16 Aug 2012 15:58:33 +0200 Subject: EGLDisplayUtil: Workaround (latest) PVR 540 EGL regression where 3nd EGLDisplay's eglInitialize(..) fails ; Fix EGLDrawableFactory.getEGLSurface() - EGLDisplayUtil: Workaround (latest) PVR 540 EGL regression where 3nd EGLDisplay's eglInitialize(..) fails In this case and if eglGetDisplay(..) fails w/ a non EGL_DEFAULT_DEVICE, fall back to EGL_DEFAULT_DEVICE - always. This workaround actually simplifies handling both cases. - Fix EGLDrawableFactory.getEGLSurface() Tests whether a given NativeSurface w/ EGLGraphicsDevice and EGLGraphicsConfiguration has a valid EGL Surface. Only if true, reuse the whole NativeSurface, otherwise construct the missing pieces (device, config and use a WrappedSurface for EGL). --- src/jogl/classes/jogamp/opengl/egl/EGLContext.java | 4 +- .../classes/jogamp/opengl/egl/EGLDisplayUtil.java | 114 ++++++++++++++------- .../classes/jogamp/opengl/egl/EGLDrawable.java | 33 +++--- .../jogamp/opengl/egl/EGLDrawableFactory.java | 27 +++-- .../jogamp/nativewindow/egl/EGLGraphicsDevice.java | 15 +-- 5 files changed, 127 insertions(+), 66 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLContext.java b/src/jogl/classes/jogamp/opengl/egl/EGLContext.java index c5d0df645..919f92c02 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLContext.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLContext.java @@ -209,8 +209,8 @@ public abstract class EGLContext extends GLContextImpl { ",\n\tsharing with 0x" + Long.toHexString(shareWithHandle)); } if (!EGL.eglMakeCurrent(eglDisplay, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) { - throw new GLException("Error making context 0x" + - Long.toHexString(contextHandle) + " current: error code " + EGL.eglGetError()); + throw new GLException("Error making context " + + toHexString(contextHandle) + " current: error code " + toHexString(EGL.eglGetError())); } setGLFunctionAvailability(true, glProfile.usesNativeGLES2() ? 2 : 1, 0, CTX_PROFILE_ES); return true; diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java index 432010f49..dbf35d68c 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java @@ -70,6 +70,14 @@ public class EGLDisplayUtil { return eglDisplay; } + /** + * @param eglDisplay + * @param major + * @param minor + * @return true if the eglDisplay is valid and it's reference counter becomes one and {@link EGL#eglInitialize(long, int[], int, int[], int)} was successful, otherwise false + * + * @see EGL#eglInitialize(long, int[], int, int[], int)} + */ public static synchronized boolean eglInitialize(long eglDisplay, int[] major, int major_offset, int[] minor, int minor_offset) { final boolean res; final int refCnt = eglDisplayCounter.get(eglDisplay) + 1; // 0 + 1 = 1 -> 1st init @@ -80,19 +88,18 @@ public class EGLDisplayUtil { } eglDisplayCounter.put(eglDisplay, refCnt); if(DEBUG) { - System.err.println("EGL.eglInitialize(0x"+Long.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res); + System.err.println("EGLDisplayUtil.eglInitialize1("+EGLContext.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res); } return res; } /** - * * @param eglDisplay * @param major * @param minor - * @return true if the eglDisplay is valid and it's reference counter becomes one and {@link EGL#eglTerminate(long)} was successful, otherwise false + * @return true if the eglDisplay is valid and it's reference counter becomes one and {@link EGL#eglInitialize(long, IntBuffer, IntBuffer)} was successful, otherwise false * - * @see EGL#eglInitialize(long, int[], int, int[], int)} + * @see EGL#eglInitialize(long, IntBuffer, IntBuffer) */ public static synchronized boolean eglInitialize(long eglDisplay, IntBuffer major, IntBuffer minor) { if( EGL.EGL_NO_DISPLAY == eglDisplay) { @@ -104,14 +111,68 @@ public class EGLDisplayUtil { res = EGL.eglInitialize(eglDisplay, major, minor); } else { res = true; + } + if(res) { // map if successfully initialized, only + eglDisplayCounter.put(eglDisplay, refCnt); } - eglDisplayCounter.put(eglDisplay, refCnt); if(DEBUG) { - System.err.println("EGL.eglInitialize(0x"+Long.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res); + System.err.println("EGLDisplayUtil.eglInitialize2("+EGLContext.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res); } return res; } + /** + * @param nativeDisplayID + * @param eglDisplay array of size 1 holding return value if successful, otherwise {@link EGL#EGL_NO_DISPLAY}. + * @param eglErr array of size 1 holding the EGL error value as retrieved by {@link EGL#eglGetError()} if not successful. + * @param major + * @param minor + * @return {@link EGL#EGL_SUCCESS} if successful, otherwise {@link EGL#EGL_BAD_DISPLAY} if {@link #eglGetDisplay(long)} failed + * or {@link EGL#EGL_NOT_INITIALIZED} if {@link #eglInitialize(long, IntBuffer, IntBuffer)} failed. + * + * @see #eglGetDisplay(long) + * @see #eglInitialize(long, IntBuffer, IntBuffer) + */ + public static synchronized int eglGetDisplayAndInitialize(long nativeDisplayID, long[] eglDisplay, int[] eglErr, IntBuffer major, IntBuffer minor) { + eglDisplay[0] = EGL.EGL_NO_DISPLAY; + final long _eglDisplay = EGLDisplayUtil.eglGetDisplay( nativeDisplayID ); + if ( EGL.EGL_NO_DISPLAY == _eglDisplay ) { + eglErr[0] = EGL.eglGetError(); + return EGL.EGL_BAD_DISPLAY; + } + if ( !EGLDisplayUtil.eglInitialize( _eglDisplay, major, minor) ) { + eglErr[0] = EGL.eglGetError(); + return EGL.EGL_NOT_INITIALIZED; + } + eglDisplay[0] = _eglDisplay; + return EGL.EGL_SUCCESS; + } + + /** + * @param nativeDisplayID in/out array of size 1, passing the requested nativeVisualID, may return a different revised nativeVisualID handle + * @return the initialized EGL display ID + * @throws GLException if not successful + */ + public static synchronized long eglGetDisplayAndInitialize(long[] nativeDisplayID) { + final long[] eglDisplay = new long[1]; + final int[] eglError = new int[1]; + int eglRes = EGLDisplayUtil.eglGetDisplayAndInitialize(nativeDisplayID[0], eglDisplay, eglError, null, null); + if( EGL.EGL_SUCCESS == eglRes ) { + return eglDisplay[0]; + } + if( EGL.EGL_DEFAULT_DISPLAY != nativeDisplayID[0] ) { // fallback to DEGAULT_DISPLAY + if(DEBUG) { + System.err.println("EGLDisplayUtil.eglGetAndInitDisplay failed with native "+EGLContext.toHexString(nativeDisplayID[0])+", error "+EGLContext.toHexString(eglRes)+"/"+EGLContext.toHexString(eglError[0])+" - fallback!"); + } + eglRes = EGLDisplayUtil.eglGetDisplayAndInitialize(EGL.EGL_DEFAULT_DISPLAY, eglDisplay, eglError, null, null); + if( EGL.EGL_SUCCESS == eglRes ) { + nativeDisplayID[0] = EGL.EGL_DEFAULT_DISPLAY; + return eglDisplay[0]; + } + } + throw new GLException("Failed to created/initialize EGL display incl. fallback default: native "+EGLContext.toHexString(nativeDisplayID[0])+", error "+EGLContext.toHexString(eglRes)+"/"+EGLContext.toHexString(eglError[0])); + } + /** * @param eglDisplay the EGL display handle * @return true if the eglDisplay is valid and it's reference counter becomes zero and {@link EGL#eglTerminate(long)} was successful, otherwise false @@ -131,21 +192,15 @@ public class EGLDisplayUtil { eglDisplayCounter.put(eglDisplay, refCnt); } if(DEBUG) { - System.err.println("EGL.eglTerminate(0x"+Long.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res); + System.err.println("EGLDisplayUtil.eglTerminate("+EGLContext.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res); + // Thread.dumpStack(); } return res; } public static final EGLGraphicsDevice.EGLDisplayLifecycleCallback eglLifecycleCallback = new EGLGraphicsDevice.EGLDisplayLifecycleCallback() { - public long eglGetAndInitDisplay(long nativeDisplayID) { - long eglDisplay = EGLDisplayUtil.eglGetDisplay(nativeDisplayID); - if (eglDisplay == EGL.EGL_NO_DISPLAY) { - throw new GLException("Failed to created EGL display: 0x"+Long.toHexString(nativeDisplayID)+", error 0x"+Integer.toHexString(EGL.eglGetError())); - } - if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) { - throw new GLException("eglInitialize failed"+", error 0x"+Integer.toHexString(EGL.eglGetError())); - } - return eglDisplay; + public long eglGetAndInitDisplay(long[] nativeDisplayID) { + return eglGetDisplayAndInitialize(nativeDisplayID); } public void eglTerminate(long eglDisplayHandle) { EGLDisplayUtil.eglTerminate(eglDisplayHandle); @@ -161,39 +216,26 @@ public class EGLDisplayUtil { * @see EGLGraphicsDevice#EGLGraphicsDevice(long, long, String, int, com.jogamp.nativewindow.egl.EGLGraphicsDevice.EGLDisplayLifecycleCallback) */ public static EGLGraphicsDevice eglCreateEGLGraphicsDevice(long nativeDisplayID, String connection, int unitID) { - final EGLGraphicsDevice eglDisplay = new EGLGraphicsDevice(nativeDisplayID, 0, connection, unitID, eglLifecycleCallback); + final EGLGraphicsDevice eglDisplay = new EGLGraphicsDevice(nativeDisplayID, EGL.EGL_NO_DISPLAY, connection, unitID, eglLifecycleCallback); eglDisplay.open(); return eglDisplay; } /** * @param surface - * @param allowFallBackToDefault * @return an initialized EGLGraphicsDevice - * @throws GLException if {@link EGL#eglGetDisplay(long)} or {@link EGL#eglInitialize(long, int[], int, int[], int)} fails + * @throws GLException if {@link EGL#eglGetDisplay(long)} or {@link EGL#eglInitialize(long, int[], int, int[], int)} fails incl fallback */ - public static EGLGraphicsDevice eglCreateEGLGraphicsDevice(NativeSurface surface, boolean allowFallBackToDefault) { - long nativeDisplayID; + public static EGLGraphicsDevice eglCreateEGLGraphicsDevice(NativeSurface surface) { + final long nativeDisplayID; if( NativeWindowFactory.TYPE_WINDOWS.equals(NativeWindowFactory.getNativeWindowType(false)) ) { nativeDisplayID = surface.getSurfaceHandle(); // don't even ask .. } else { nativeDisplayID = surface.getDisplayHandle(); // 0 == EGL.EGL_DEFAULT_DISPLAY } - long eglDisplay = EGLDisplayUtil.eglGetDisplay(nativeDisplayID); - if (eglDisplay == EGL.EGL_NO_DISPLAY && nativeDisplayID != EGL.EGL_DEFAULT_DISPLAY && allowFallBackToDefault) { - if(DEBUG) { - System.err.println("EGLDisplayUtil.eglGetDisplay(): Fall back to EGL_DEFAULT_DISPLAY"); - } - nativeDisplayID = EGL.EGL_DEFAULT_DISPLAY; - eglDisplay = EGLDisplayUtil.eglGetDisplay(nativeDisplayID); - } - if (eglDisplay == EGL.EGL_NO_DISPLAY) { - throw new GLException("Failed to created EGL display: "+surface+", error 0x"+Integer.toHexString(EGL.eglGetError())); - } - if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) { - throw new GLException("eglInitialize failed"+", error 0x"+Integer.toHexString(EGL.eglGetError())); - } final AbstractGraphicsDevice adevice = surface.getGraphicsConfiguration().getScreen().getDevice(); - return new EGLGraphicsDevice(nativeDisplayID, eglDisplay, adevice.getConnection(), adevice.getUnitID(), eglLifecycleCallback); + final EGLGraphicsDevice eglDevice = new EGLGraphicsDevice(nativeDisplayID, EGL.EGL_NO_DISPLAY, adevice.getConnection(), adevice.getUnitID(), eglLifecycleCallback); + eglDevice.open(); + return eglDevice; } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java index 383b61f88..0dba4bb09 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java @@ -114,25 +114,30 @@ public abstract class EGLDrawable extends GLDrawableImpl { } } + protected static boolean isValidEGLSurface(EGLGraphicsDevice eglDevice, NativeSurface surface) { + final long eglDisplayHandle = eglDevice.getHandle(); + if (EGL.EGL_NO_DISPLAY == eglDisplayHandle) { + throw new GLException("Invalid EGL display in EGLGraphicsDevice "+eglDevice); + } + boolean eglSurfaceValid = 0 != surface.getSurfaceHandle(); + if(eglSurfaceValid) { + int[] tmp = new int[1]; + eglSurfaceValid = EGL.eglQuerySurface(eglDisplayHandle, surface.getSurfaceHandle(), EGL.EGL_CONFIG_ID, tmp, 0); + if(!eglSurfaceValid) { + if(DEBUG) { + System.err.println(getThreadName() + ": EGLDrawable.isValidEGLSurface eglQuerySuface failed: "+toHexString(EGL.eglGetError())+", "+surface); + } + } + } + return eglSurfaceValid; + } + @Override protected final void setRealizedImpl() { final EGLGraphicsConfiguration eglConfig = (EGLGraphicsConfiguration) surface.getGraphicsConfiguration(); final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) eglConfig.getScreen().getDevice(); if (realized) { - final long eglDisplayHandle = eglDevice.getHandle(); - if (EGL.EGL_NO_DISPLAY == eglDisplayHandle) { - throw new GLException("Invalid EGL display in EGLGraphicsDevice "+eglDevice); - } - int[] tmp = new int[1]; - boolean eglSurfaceValid = 0 != surface.getSurfaceHandle(); - if(eglSurfaceValid) { - eglSurfaceValid = EGL.eglQuerySurface(eglDisplayHandle, surface.getSurfaceHandle(), EGL.EGL_CONFIG_ID, tmp, 0); - if(!eglSurfaceValid) { - if(DEBUG) { - System.err.println(getThreadName() + ": EGLDrawable.setRealizedImpl eglQuerySuface failed: "+toHexString(EGL.eglGetError())+", "+surface); - } - } - } + final boolean eglSurfaceValid = isValidEGLSurface(eglDevice, surface); if(eglSurfaceValid) { // surface holds valid EGLSurface if(DEBUG) { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index c848e3e5c..f7377a648 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -282,7 +282,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { if(null != upstreamSurface) { upstreamSurface.createNotify(); } - eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface, true); + eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface); deviceFromUpstreamSurface = true; } @@ -471,14 +471,27 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { AbstractGraphicsConfiguration aConfig = surface.getGraphicsConfiguration(); AbstractGraphicsDevice aDevice = aConfig.getScreen().getDevice(); if( aDevice instanceof EGLGraphicsDevice && aConfig instanceof EGLGraphicsConfiguration ) { - // already in native EGL format - if(DEBUG) { - System.err.println(getThreadName() + ": getEGLSurface - already in EGL format - use as-is: "+aConfig); + if(EGLDrawable.isValidEGLSurface((EGLGraphicsDevice)aDevice, surface)) { + // already in native EGL format + if(DEBUG) { + System.err.println(getThreadName() + ": getEGLSurface - already valid EGL surface - use as-is: "+aConfig); + } + return surface; } - return surface; } // create EGL instance out of platform native types - final EGLGraphicsDevice eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface, true); + final EGLGraphicsDevice eglDevice; + if( aDevice instanceof EGLGraphicsDevice ) { + eglDevice = (EGLGraphicsDevice) aDevice; + if(DEBUG) { + System.err.println(getThreadName() + ": getEGLSurface - Reusing eglDevice: "+eglDevice); + } + if(0 == eglDevice.getHandle()) { + eglDevice.open(); + } + } else { + eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface); + } final AbstractGraphicsScreen eglScreen = new DefaultGraphicsScreen(eglDevice, aConfig.getScreen().getIndex()); final GLCapabilitiesImmutable capsRequested = (GLCapabilitiesImmutable) aConfig.getRequestedCapabilities(); final EGLGraphicsConfiguration eglConfig; @@ -489,7 +502,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { // 'refresh' the native EGLConfig handle capsChosen.setEGLConfig(EGLGraphicsConfiguration.EGLConfigId2EGLConfig(eglDevice.getHandle(), capsChosen.getEGLConfigID())); if( 0 == capsChosen.getEGLConfig() ) { - throw new GLException("Refreshing native EGLConfig handle failed: "+capsChosen+" of "+aConfig); + throw new GLException("Refreshing native EGLConfig handle failed with error "+EGLContext.toHexString(EGL.eglGetError())+": "+eglDevice+", "+capsChosen+" of "+aConfig); } } eglConfig = new EGLGraphicsConfiguration(eglScreen, capsChosen, capsRequested, null); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java index 389949e90..40042ec81 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java @@ -37,7 +37,7 @@ import javax.media.nativewindow.*; /** Encapsulates a graphics device on EGL platforms. */ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneable { - final long nativeDisplayID; + final long[] nativeDisplayID = new long[1]; final EGLDisplayLifecycleCallback eglLifecycleCallback; /** @@ -51,9 +51,10 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl /** * Implementation should issue an EGL.eglGetDisplay(nativeDisplayID) * inclusive EGL.eglInitialize(eglDisplayHandle, ..) call. - * @param eglDisplayHandle + * @param nativeDisplayID in/out array of size 1, passing the requested nativeVisualID, may return a different revised nativeVisualID handle + * @return the initialized EGL display ID, or 0 if not successful */ - public long eglGetAndInitDisplay(long nativeDisplayID); + public long eglGetAndInitDisplay(long[] nativeDisplayID); /** * Implementation should issue an EGL.eglTerminate(eglDisplayHandle) call. @@ -68,17 +69,17 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl */ public EGLGraphicsDevice(String connection, int unitID) { super(NativeWindowFactory.TYPE_EGL, connection, unitID); - this.nativeDisplayID = 0 ; // EGL.EGL_DEFAULT_DISPLAY + this.nativeDisplayID[0] = 0 ; // EGL.EGL_DEFAULT_DISPLAY this.eglLifecycleCallback = null; } public EGLGraphicsDevice(long nativeDisplayID, long eglDisplay, String connection, int unitID, EGLDisplayLifecycleCallback eglLifecycleCallback) { super(NativeWindowFactory.TYPE_EGL, connection, unitID, eglDisplay); - this.nativeDisplayID = nativeDisplayID; + this.nativeDisplayID[0] = nativeDisplayID; this.eglLifecycleCallback = eglLifecycleCallback; } - public long getNativeDisplayID() { return nativeDisplayID; } + public long getNativeDisplayID() { return nativeDisplayID[0]; } @Override public Object clone() { @@ -113,7 +114,7 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl @Override public String toString() { - return "EGLGraphicsDevice[type EGL, connection "+getConnection()+", unitID "+getUnitID()+", handle 0x"+Long.toHexString(getHandle())+", nativeDisplayID 0x"+Long.toHexString(nativeDisplayID)+"]"; + return "EGLGraphicsDevice[type EGL, connection "+getConnection()+", unitID "+getUnitID()+", handle 0x"+Long.toHexString(getHandle())+", nativeDisplayID 0x"+Long.toHexString(nativeDisplayID[0])+", eglLifecycleCallback "+(null != eglLifecycleCallback)+"]"; } } -- cgit v1.2.3 From 3ab518e90eb4cf82bcb8b990d337a5e4a531136b Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 18 Aug 2012 11:46:01 +0200 Subject: GLProfile/NativeWindowFactory: Remove deprecated argument 'firstUIActionOnProcess' of initSingleton() method The notion of changing the threading behavior of native initialization was deprecated for over a year. The code still contained the bits and pieces, i.e. whether X11Util.initSingletion() is invoked before or after optional AWT initialization. This condition has been removed now and behavior is uniform, i.e. X11Util.initSingletion() is invoked after optional AWT initialization. - Removed GLProfile.initSingleton(boolean firstUIActionOnProcess), use remaining GLProfile.initSingleton() - Removed NativeWindowFactory.isFirstUIActionOnProcess() - Changed NativeWindowFactory.initSingleton(boolean firstUIActionOnProcess) to NativeWindowFactory.initSingleton() --- src/jogl/classes/javax/media/opengl/GLProfile.java | 54 +++++++++------------- .../media/nativewindow/NativeWindowFactory.java | 46 +++++------------- .../nativewindow/NativeWindowFactoryImpl.java | 2 +- .../jogamp/nativewindow/macosx/OSXUtil.java | 12 ++--- .../jogamp/nativewindow/windows/GDIUtil.java | 15 +++--- .../classes/jogamp/nativewindow/x11/X11Util.java | 13 +++--- src/newt/classes/com/jogamp/newt/NewtFactory.java | 2 +- .../classes/com/jogamp/newt/util/MainThread.java | 2 +- .../test/junit/newt/TestRemoteWindow01NEWT.java | 2 +- .../test/junit/newt/TestScreenMode00NEWT.java | 2 +- .../test/junit/newt/TestScreenMode00bNEWT.java | 2 +- .../opengl/test/junit/newt/TestWindows01NEWT.java | 2 +- 12 files changed, 57 insertions(+), 97 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/GLProfile.java b/src/jogl/classes/javax/media/opengl/GLProfile.java index 1e10dc9a6..513ccd101 100644 --- a/src/jogl/classes/javax/media/opengl/GLProfile.java +++ b/src/jogl/classes/javax/media/opengl/GLProfile.java @@ -101,29 +101,29 @@ public class GLProfile { /** * Static initialization of JOGL. + * *

      - * The parameter firstUIActionOnProcess has an impact on concurrent locking,
      - * see {@link javax.media.nativewindow.NativeWindowFactory#initSingleton(boolean) NativeWindowFactory.initSingleton(firstUIActionOnProcess)}. + * This method shall not need to be called for other reasons than having a defined initialization sequence. *

      - *

      - * Applications using this method may place it's call before any other UI invocation - * in the main class's static block or within the main function. - * In such case, applications may pass firstUIActionOnProcess=true to use native toolkit locking.

      - *

      - * RCP Application (Applet's, Webstart, Netbeans, ..) using JOGL are not be able to initialize JOGL - * before the first UI action. - * In such case you shall pass firstUIActionOnProcess=false.

      + * *

      * In case this method is not invoked, GLProfile is initialized implicit by - * the first call to {@link #getDefault()}, {@link #get(java.lang.String)} passing firstUIActionOnProcess=false. + * the first call to {@link #getDefault()}, {@link #get(java.lang.String)}. *

      - * - * @param firstUIActionOnProcess Should be true if called before the first UI action of the running program, - * otherwise false. * - * @deprecated Use {@link #initSingleton()}. This method is subject to be removed in future versions of JOGL. + *

      + * To initialize JOGL at startup ASAP, this method may be invoked in the main class's + * static initializer block, in the static main() method or in the Applet init() method. + *

      + * + *

      + * Since JOGL's initialization is complex and involves multi threading, it is not recommended + * to be have it invoked on the AWT EDT thread. In case all JOGL usage is performed + * on the AWT EDT, invoke this method outside the AWT EDT - see above. + *

      + * */ - public static void initSingleton(final boolean firstUIActionOnProcess) { + public static void initSingleton() { final boolean justInitialized; initLock.lock(); try { @@ -131,7 +131,7 @@ public class GLProfile { initialized = true; justInitialized = true; if(DEBUG) { - System.err.println("GLProfile.initSingleton(firstUIActionOnProcess: "+firstUIActionOnProcess+") - thread "+Thread.currentThread().getName()); + System.err.println("GLProfile.initSingleton() - thread "+Thread.currentThread().getName()); Thread.dumpStack(); } @@ -171,7 +171,7 @@ public class GLProfile { } JNILibLoaderBase.addNativeJarLibs(classesFromJavaJars, "-all", new String[] { "-noawt", "-mobile", "-core" } ); } - initProfilesForDefaultDevices(firstUIActionOnProcess); + initProfilesForDefaultDevices(); return null; } }); @@ -188,17 +188,6 @@ public class GLProfile { } } - /** - * Static initialization of JOGL. - * - *

      - * This method shall not need to be called for other reasons than having a defined initialization sequence. - *

      - */ - public static void initSingleton() { - GLProfile.initSingleton(false); - } - /** * Trigger eager initialization of GLProfiles for the given device, * in case it isn't done yet. @@ -1411,11 +1400,10 @@ public class GLProfile { /** * Tries the profiles implementation and native libraries. */ - private static void initProfilesForDefaultDevices(boolean firstUIActionOnProcess) { - NativeWindowFactory.initSingleton(firstUIActionOnProcess); + private static void initProfilesForDefaultDevices() { + NativeWindowFactory.initSingleton(); if(DEBUG) { - System.err.println("GLProfile.init firstUIActionOnProcess: "+ firstUIActionOnProcess - + ", thread: " + Thread.currentThread().getName()); + System.err.println("GLProfile.init - thread: " + Thread.currentThread().getName()); System.err.println(VersionUtil.getPlatformInfo()); System.err.println(GlueGenVersion.getInstance()); System.err.println(NativeWindowVersion.getInstance()); diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 6faa9890c..94f5d753c 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -99,7 +99,6 @@ public abstract class NativeWindowFactory { private static Constructor x11JAWTToolkitLockConstructor; private static Class x11ToolkitLockClass; private static Constructor x11ToolkitLockConstructor; - private static boolean isFirstUIActionOnProcess; private static boolean requiresToolkitLock; /** Creates a new NativeWindowFactory instance. End users do not @@ -138,9 +137,7 @@ public abstract class NativeWindowFactory { static boolean initialized = false; - private static void initSingletonNativeImpl(final boolean firstUIActionOnProcess, final ClassLoader cl) { - isFirstUIActionOnProcess = firstUIActionOnProcess; - + private static void initSingletonNativeImpl(final ClassLoader cl) { final String clazzName; if( TYPE_X11.equals(nativeWindowingTypePure) ) { clazzName = X11UtilClassName; @@ -152,9 +149,7 @@ public abstract class NativeWindowFactory { clazzName = null; } if( null != clazzName ) { - ReflectionUtil.callStaticMethod(clazzName, "initSingleton", - new Class[] { boolean.class }, - new Object[] { new Boolean(firstUIActionOnProcess) }, cl ); + ReflectionUtil.callStaticMethod(clazzName, "initSingleton", null, null, cl ); final Boolean res = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "requiresToolkitLock", null, null, cl); requiresToolkitLock = res.booleanValue(); @@ -166,24 +161,13 @@ public abstract class NativeWindowFactory { /** * Static one time initialization of this factory.
      * This initialization method must be called once by the program or utilizing modules! - *

      - * The parameter firstUIActionOnProcess has an impact on concurrent locking: - *

        - *
      • {@link #getDefaultToolkitLock() getDefaultToolkitLock() }
      • - *
      • {@link #getDefaultToolkitLock(java.lang.String) getDefaultToolkitLock(type) }
      • - *
      • {@link #createDefaultToolkitLock(java.lang.String, long) createDefaultToolkitLock(type, dpyHandle) }
      • - *
      • {@link #createDefaultToolkitLockNoAWT(java.lang.String, long) createDefaultToolkitLockNoAWT(type, dpyHandle) }
      • - *
      - *

      - * @param firstUIActionOnProcess Should be true if called before the first UI action of the running program, - * otherwise false. */ - public static synchronized void initSingleton(final boolean firstUIActionOnProcess) { + public static synchronized void initSingleton() { if(!initialized) { initialized = true; if(DEBUG) { - System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.initSingleton("+firstUIActionOnProcess+")"); + System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.initSingleton()"); } final ClassLoader cl = NativeWindowFactory.class.getClassLoader(); @@ -197,10 +181,6 @@ public abstract class NativeWindowFactory { nativeWindowingTypeCustom = tmp; } - if(firstUIActionOnProcess) { - // X11 initialization before possible AWT initialization - initSingletonNativeImpl(true, cl); - } isAWTAvailable = false; // may be set to true below if( Platform.AWT_AVAILABLE && @@ -248,10 +228,13 @@ public abstract class NativeWindowFactory { } } } - if(!firstUIActionOnProcess) { - // X11 initialization after possible AWT initialization - initSingletonNativeImpl(false, cl); - } + + // X11 initialization after possible AWT initialization + // This is performed post AWT initialization, allowing AWT to complete the same, + // which may have been triggered before NativeWindow initialization. + // This way behavior is more uniforms across configurations (Applet/RCP, applications, ..). + initSingletonNativeImpl(cl); + registeredFactories = Collections.synchronizedMap(new HashMap, NativeWindowFactory>()); // register our default factory -> NativeWindow @@ -276,7 +259,6 @@ public abstract class NativeWindowFactory { } if(DEBUG) { - System.err.println("NativeWindowFactory firstUIActionOnProcess "+firstUIActionOnProcess); System.err.println("NativeWindowFactory requiresToolkitLock "+requiresToolkitLock); System.err.println("NativeWindowFactory isAWTAvailable "+isAWTAvailable+", defaultFactory "+factory); } @@ -301,12 +283,6 @@ public abstract class NativeWindowFactory { } } - /** @return true if initialized with {@link #initSingleton(boolean) initSingleton(firstUIActionOnProcess==true)}, - otherwise false. */ - public static boolean isFirstUIActionOnProcess() { - return isFirstUIActionOnProcess; - } - /** @return true if the underlying toolkit requires locking, otherwise false. */ public static boolean requiresToolkitLock() { return requiresToolkitLock; diff --git a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java index 9e18439db..2c2a627a4 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java @@ -90,7 +90,7 @@ public class NativeWindowFactoryImpl extends NativeWindowFactory { // Assume Linux, Solaris, etc. Should probably test for these explicitly. windowClassName = "jogamp.nativewindow.jawt.x11.X11JAWTWindow"; } else { - throw new IllegalArgumentException("OS " + Platform.getOSName() + " not yet supported"); + throw new IllegalArgumentException("Native windowing type " + windowingType + " (custom) not yet supported, platform reported native windowing type: "+getNativeWindowType(false)); } nativeWindowConstructor = ReflectionUtil.getConstructor( diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 894084fce..f5f735051 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -38,20 +38,18 @@ public class OSXUtil { private static boolean isInit = false; private static final boolean DEBUG = Debug.debug("OSXUtil"); - public static synchronized void initSingleton(boolean firstX11ActionOnProcess) { + public static synchronized void initSingleton() { if(!isInit) { + if(DEBUG) { + System.out.println("OSXUtil.initSingleton()"); + } if(!NWJNILibLoader.loadNativeWindow("macosx")) { throw new NativeWindowException("NativeWindow MacOSX native library load error."); } if( !initIDs0() ) { throw new NativeWindowException("MacOSX: Could not initialized native stub"); - } - - if(DEBUG) { - System.out.println("OSX.isFirstX11ActionOnProcess: "+firstX11ActionOnProcess); - } - + } isInit = true; } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index d17a1898c..fda1649b6 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -41,24 +41,21 @@ public class GDIUtil { private static RegisteredClassFactory dummyWindowClassFactory; private static boolean isInit = false; - public static synchronized void initSingleton(boolean firstX11ActionOnProcess) { + public static synchronized void initSingleton() { if(!isInit) { synchronized(X11Util.class) { if(!isInit) { - isInit = true; + if(DEBUG) { + System.out.println("GDI.initSingleton()"); + } if(!NWJNILibLoader.loadNativeWindow("win32")) { throw new NativeWindowException("NativeWindow Windows native library load error."); } - if( !initIDs0() ) { throw new NativeWindowException("GDI: Could not initialized native stub"); } - - if(DEBUG) { - System.out.println("GDI.isFirstX11ActionOnProcess: "+firstX11ActionOnProcess); - } - - dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0()); + dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0()); + isInit = true; } } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 7b46a1df0..860238649 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -95,18 +95,20 @@ public class X11Util { private static Object setX11ErrorHandlerLock = new Object(); - @SuppressWarnings("unused") - public static void initSingleton(final boolean firstX11ActionOnProcess) { + public static void initSingleton() { if(!isInit) { synchronized(X11Util.class) { if(!isInit) { isInit = true; + if(DEBUG) { + System.out.println("X11UtilUtil.initSingleton()"); + } if(!NWJNILibLoader.loadNativeWindow("x11")) { throw new NativeWindowException("NativeWindow X11 native library load error."); } - final boolean callXInitThreads = XINITTHREADS_ALWAYS_ENABLED || firstX11ActionOnProcess; - final boolean isXInitThreadsOK = initialize0( XINITTHREADS_ALWAYS_ENABLED || firstX11ActionOnProcess, XERROR_STACKDUMP); + final boolean callXInitThreads = XINITTHREADS_ALWAYS_ENABLED ; + final boolean isXInitThreadsOK = initialize0( callXInitThreads, XERROR_STACKDUMP); isX11LockAvailable = isXInitThreadsOK && !HAS_XLOCKDISPLAY_BUG ; final long dpy = X11Lib.XOpenDisplay(null); @@ -124,8 +126,7 @@ public class X11Util { } if(DEBUG) { - System.err.println("X11Util firstX11ActionOnProcess: "+firstX11ActionOnProcess+ - ", requiresX11Lock "+requiresX11Lock+ + System.err.println("X11Util requiresX11Lock "+requiresX11Lock+ ", XInitThreads [called "+callXInitThreads+", OK "+isXInitThreadsOK+"]"+ ", isX11LockAvailable "+isX11LockAvailable+ ", X11 Display(NULL) <"+nullDisplayName+">"+ diff --git a/src/newt/classes/com/jogamp/newt/NewtFactory.java b/src/newt/classes/com/jogamp/newt/NewtFactory.java index 61dbfb34c..0644c9164 100644 --- a/src/newt/classes/com/jogamp/newt/NewtFactory.java +++ b/src/newt/classes/com/jogamp/newt/NewtFactory.java @@ -52,7 +52,7 @@ public class NewtFactory { // Work-around for initialization order problems on Mac OS X // between native Newt and (apparently) Fmod static { - NativeWindowFactory.initSingleton(false); // last resort .. + NativeWindowFactory.initSingleton(); // last resort .. WindowImpl.init(NativeWindowFactory.getNativeWindowType(true)); } diff --git a/src/newt/classes/com/jogamp/newt/util/MainThread.java b/src/newt/classes/com/jogamp/newt/util/MainThread.java index bbe415b2f..a6e2ae02b 100644 --- a/src/newt/classes/com/jogamp/newt/util/MainThread.java +++ b/src/newt/classes/com/jogamp/newt/util/MainThread.java @@ -101,7 +101,7 @@ public class MainThread { public static final boolean HINT_USE_MAIN_THREAD; static { - NativeWindowFactory.initSingleton(true); + NativeWindowFactory.initSingleton(); NEWTJNILibLoader.loadNEWT(); HINT_USE_MAIN_THREAD = !NativeWindowFactory.isAWTAvailable() || Debug.getBooleanProperty("newt.MainThread.force", true); diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestRemoteWindow01NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestRemoteWindow01NEWT.java index eb652584c..53995e8f7 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestRemoteWindow01NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestRemoteWindow01NEWT.java @@ -47,7 +47,7 @@ public class TestRemoteWindow01NEWT extends UITestCase { @BeforeClass public static void initClass() { - NativeWindowFactory.initSingleton(true); + NativeWindowFactory.initSingleton(); width = 640; height = 480; } diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java index a5b7a76e7..577119bcd 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java @@ -59,7 +59,7 @@ public class TestScreenMode00NEWT extends UITestCase { @BeforeClass public static void initClass() { - NativeWindowFactory.initSingleton(true); + NativeWindowFactory.initSingleton(); width = 640; height = 480; } diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00bNEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00bNEWT.java index e9e66da2c..75a312686 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00bNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00bNEWT.java @@ -57,7 +57,7 @@ public class TestScreenMode00bNEWT extends UITestCase { @BeforeClass public static void initClass() { - NativeWindowFactory.initSingleton(true); + NativeWindowFactory.initSingleton(); width = 640; height = 480; } diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestWindows01NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestWindows01NEWT.java index a99edfadb..bf72348f9 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestWindows01NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestWindows01NEWT.java @@ -45,7 +45,7 @@ public class TestWindows01NEWT extends UITestCase { @BeforeClass public static void initClass() { - NativeWindowFactory.initSingleton(true); + NativeWindowFactory.initSingleton(); width = 256; height = 256; } -- cgit v1.2.3 From a694cadca4ab72481e777222f412f006f973f77e Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 18 Aug 2012 14:12:54 +0200 Subject: NEWT Platform Driver: Uniform impl. class names [DisplayDriver, ScreenDriver, WindowDriver] to reduce complexity and programatic selection. --- make/build-newt.xml | 36 +- make/scripts/tests.sh | 4 +- .../media/nativewindow/NativeWindowFactory.java | 12 +- .../classes/com/jogamp/newt/util/MainThread.java | 2 +- src/newt/classes/jogamp/newt/DisplayImpl.java | 22 +- src/newt/classes/jogamp/newt/ScreenImpl.java | 28 +- src/newt/classes/jogamp/newt/WindowImpl.java | 21 +- .../jogamp/newt/driver/android/AndroidDisplay.java | 66 --- .../jogamp/newt/driver/android/AndroidScreen.java | 138 ------- .../jogamp/newt/driver/android/AndroidWindow.java | 458 --------------------- .../jogamp/newt/driver/android/DisplayDriver.java | 66 +++ .../newt/driver/android/NewtBaseActivity.java | 10 +- .../newt/driver/android/NewtVersionActivity.java | 2 +- .../jogamp/newt/driver/android/ScreenDriver.java | 138 +++++++ .../jogamp/newt/driver/android/WindowDriver.java | 458 +++++++++++++++++++++ .../classes/jogamp/newt/driver/awt/AWTCanvas.java | 1 + .../classes/jogamp/newt/driver/awt/AWTDisplay.java | 73 ---- .../classes/jogamp/newt/driver/awt/AWTScreen.java | 81 ---- .../classes/jogamp/newt/driver/awt/AWTWindow.java | 233 ----------- .../jogamp/newt/driver/awt/DisplayDriver.java | 73 ++++ .../jogamp/newt/driver/awt/ScreenDriver.java | 81 ++++ .../jogamp/newt/driver/awt/WindowDriver.java | 233 +++++++++++ .../jogamp/newt/driver/bcm/egl/Display.java | 85 ---- .../jogamp/newt/driver/bcm/egl/DisplayDriver.java | 85 ++++ .../classes/jogamp/newt/driver/bcm/egl/Screen.java | 75 ---- .../jogamp/newt/driver/bcm/egl/ScreenDriver.java | 75 ++++ .../classes/jogamp/newt/driver/bcm/egl/Window.java | 170 -------- .../jogamp/newt/driver/bcm/egl/WindowDriver.java | 170 ++++++++ .../jogamp/newt/driver/bcm/vc/iv/Display.java | 78 ---- .../newt/driver/bcm/vc/iv/DisplayDriver.java | 78 ++++ .../jogamp/newt/driver/bcm/vc/iv/Screen.java | 73 ---- .../jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java | 73 ++++ .../jogamp/newt/driver/bcm/vc/iv/Window.java | 149 ------- .../jogamp/newt/driver/bcm/vc/iv/WindowDriver.java | 149 +++++++ .../jogamp/newt/driver/intel/gdl/Display.java | 104 ----- .../newt/driver/intel/gdl/DisplayDriver.java | 105 +++++ .../jogamp/newt/driver/intel/gdl/Screen.java | 85 ---- .../jogamp/newt/driver/intel/gdl/ScreenDriver.java | 86 ++++ .../jogamp/newt/driver/intel/gdl/Window.java | 146 ------- .../jogamp/newt/driver/intel/gdl/WindowDriver.java | 147 +++++++ .../classes/jogamp/newt/driver/kd/Display.java | 77 ---- .../jogamp/newt/driver/kd/DisplayDriver.java | 77 ++++ src/newt/classes/jogamp/newt/driver/kd/Screen.java | 75 ---- .../jogamp/newt/driver/kd/ScreenDriver.java | 75 ++++ src/newt/classes/jogamp/newt/driver/kd/Window.java | 163 -------- .../jogamp/newt/driver/kd/WindowDriver.java | 163 ++++++++ .../jogamp/newt/driver/macosx/DisplayDriver.java | 88 ++++ .../jogamp/newt/driver/macosx/MacDisplay.java | 87 ---- .../jogamp/newt/driver/macosx/MacKeyUtil.java | 27 ++ .../jogamp/newt/driver/macosx/MacScreen.java | 143 ------- .../jogamp/newt/driver/macosx/MacWindow.java | 431 ------------------- .../jogamp/newt/driver/macosx/ScreenDriver.java | 143 +++++++ .../jogamp/newt/driver/macosx/WindowDriver.java | 431 +++++++++++++++++++ .../jogamp/newt/driver/windows/DisplayDriver.java | 95 +++++ .../jogamp/newt/driver/windows/ScreenDriver.java | 124 ++++++ .../jogamp/newt/driver/windows/WindowDriver.java | 311 ++++++++++++++ .../jogamp/newt/driver/windows/WindowsDisplay.java | 95 ----- .../jogamp/newt/driver/windows/WindowsScreen.java | 124 ------ .../jogamp/newt/driver/windows/WindowsWindow.java | 311 -------------- .../jogamp/newt/driver/x11/DisplayDriver.java | 171 ++++++++ .../jogamp/newt/driver/x11/ScreenDriver.java | 357 ++++++++++++++++ .../jogamp/newt/driver/x11/WindowDriver.java | 261 ++++++++++++ .../classes/jogamp/newt/driver/x11/X11Display.java | 171 -------- .../classes/jogamp/newt/driver/x11/X11Screen.java | 357 ---------------- .../classes/jogamp/newt/driver/x11/X11Window.java | 261 ------------ src/newt/native/AndroidWindow.c | 18 +- src/newt/native/IntelGDL.c | 24 +- src/newt/native/KDWindow.c | 20 +- src/newt/native/MacWindow.m | 116 +++--- src/newt/native/WindowsWindow.c | 78 ++-- src/newt/native/X11Common.h | 6 +- src/newt/native/X11Display.c | 22 +- src/newt/native/X11Screen.c | 62 +-- src/newt/native/X11Window.c | 42 +- src/newt/native/bcm_egl.c | 16 +- src/newt/native/bcm_vc_iv.c | 30 +- .../opengl/test/android/MovieSimpleActivity0.java | 6 +- .../opengl/test/android/MovieSimpleActivity1.java | 10 +- 78 files changed, 4608 insertions(+), 4629 deletions(-) delete mode 100644 src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java delete mode 100644 src/newt/classes/jogamp/newt/driver/android/AndroidScreen.java delete mode 100644 src/newt/classes/jogamp/newt/driver/android/AndroidWindow.java create mode 100644 src/newt/classes/jogamp/newt/driver/android/DisplayDriver.java create mode 100644 src/newt/classes/jogamp/newt/driver/android/ScreenDriver.java create mode 100644 src/newt/classes/jogamp/newt/driver/android/WindowDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java delete mode 100644 src/newt/classes/jogamp/newt/driver/awt/AWTScreen.java delete mode 100644 src/newt/classes/jogamp/newt/driver/awt/AWTWindow.java create mode 100644 src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java create mode 100644 src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java create mode 100644 src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/bcm/egl/Display.java create mode 100644 src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/bcm/egl/Screen.java create mode 100644 src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/bcm/egl/Window.java create mode 100644 src/newt/classes/jogamp/newt/driver/bcm/egl/WindowDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Display.java create mode 100644 src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Screen.java create mode 100644 src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Window.java create mode 100644 src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/intel/gdl/Display.java create mode 100644 src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/intel/gdl/Screen.java create mode 100644 src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java create mode 100644 src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/kd/Display.java create mode 100644 src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/kd/Screen.java create mode 100644 src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/kd/Window.java create mode 100644 src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java create mode 100644 src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/macosx/MacDisplay.java delete mode 100644 src/newt/classes/jogamp/newt/driver/macosx/MacScreen.java delete mode 100644 src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java create mode 100644 src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java create mode 100644 src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java create mode 100644 src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java create mode 100644 src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java create mode 100644 src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/windows/WindowsDisplay.java delete mode 100644 src/newt/classes/jogamp/newt/driver/windows/WindowsScreen.java delete mode 100644 src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java create mode 100644 src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java create mode 100644 src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java create mode 100644 src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java delete mode 100644 src/newt/classes/jogamp/newt/driver/x11/X11Display.java delete mode 100644 src/newt/classes/jogamp/newt/driver/x11/X11Screen.java delete mode 100644 src/newt/classes/jogamp/newt/driver/x11/X11Window.java (limited to 'src/nativewindow') diff --git a/make/build-newt.xml b/make/build-newt.xml index 0a12374dd..64dccc6ac 100644 --- a/make/build-newt.xml +++ b/make/build-newt.xml @@ -670,30 +670,30 @@ - + - - - + + + - - - - + + + + - - - - - - - - - + + + + + + + + + - + diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 5a8d596df..cccc825ee 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -247,7 +247,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestRedSquareES1NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestWindows01NEWT $* @@ -274,7 +274,7 @@ function testawtswt() { #testawt javax.media.opengl.awt.GLCanvas $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug551AWT $* -testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWT01GLn $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWT01GLn $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestAWTCloseX11DisplayBug565 $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextNewtAWTBug523 $* diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 94f5d753c..867d0733b 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -57,22 +57,22 @@ public abstract class NativeWindowFactory { protected static final boolean DEBUG; /** OpenKODE/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}*/ - public static final String TYPE_EGL = "EGL"; + public static final String TYPE_EGL = "jogamp.newt.driver.kd"; /** Microsoft Windows type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_WINDOWS = "Windows"; + public static final String TYPE_WINDOWS = "jogamp.newt.driver.windows"; /** X11 type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_X11 = "X11"; + public static final String TYPE_X11 = "jogamp.newt.driver.x11"; /** Android/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}*/ - public static final String TYPE_ANDROID = "ANDROID"; + public static final String TYPE_ANDROID = "jogamp.newt.driver.android"; /** Mac OS X type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_MACOSX = "MacOSX"; + public static final String TYPE_MACOSX = "jogamp.newt.driver.macosx"; /** Generic AWT type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_AWT = "AWT"; + public static final String TYPE_AWT = "jogamp.newt.driver.awt"; /** Generic DEFAULT type, where platform implementation don't care, as retrieved with {@link #getNativeWindowType(boolean)} */ public static final String TYPE_DEFAULT = "default"; diff --git a/src/newt/classes/com/jogamp/newt/util/MainThread.java b/src/newt/classes/com/jogamp/newt/util/MainThread.java index a6e2ae02b..9c2f2a0b7 100644 --- a/src/newt/classes/com/jogamp/newt/util/MainThread.java +++ b/src/newt/classes/com/jogamp/newt/util/MainThread.java @@ -74,7 +74,7 @@ import jogamp.newt.NEWTJNILibLoader; * * To support your NEWT Window platform, * you have to pass your main thread actions to {@link #invoke invoke(..)}, - * have a look at the {@link com.jogamp.newt.macosx.MacWindow MacWindow} implementation.
      + * have a look at the {@link jogamp.newt.driver.macosx.WindowDriver NEWT Mac OSX Window} driver implementation.
      * TODO: Some hardcoded dependencies exist in this implementation, * where you have to patch this code or factor it out.

      * diff --git a/src/newt/classes/jogamp/newt/DisplayImpl.java b/src/newt/classes/jogamp/newt/DisplayImpl.java index 867a1f176..bac4031f0 100644 --- a/src/newt/classes/jogamp/newt/DisplayImpl.java +++ b/src/newt/classes/jogamp/newt/DisplayImpl.java @@ -44,7 +44,6 @@ import com.jogamp.newt.util.EDTUtil; import java.util.ArrayList; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.NativeWindowFactory; public abstract class DisplayImpl extends Display { private static int serialno = 1; @@ -52,26 +51,9 @@ public abstract class DisplayImpl extends Display { private static Class getDisplayClass(String type) throws ClassNotFoundException { - Class displayClass = NewtFactory.getCustomClass(type, "Display"); + final Class displayClass = NewtFactory.getCustomClass(type, "DisplayDriver"); if(null==displayClass) { - if (NativeWindowFactory.TYPE_ANDROID == type) { - displayClass = Class.forName("jogamp.newt.driver.android.AndroidDisplay"); - } else if (NativeWindowFactory.TYPE_EGL == type) { - displayClass = Class.forName("jogamp.newt.driver.kd.Display"); - } else if (NativeWindowFactory.TYPE_WINDOWS == type) { - displayClass = Class.forName("jogamp.newt.driver.windows.WindowsDisplay"); - } else if (NativeWindowFactory.TYPE_MACOSX == type) { - displayClass = Class.forName("jogamp.newt.driver.macosx.MacDisplay"); - } else if (NativeWindowFactory.TYPE_X11 == type) { - displayClass = Class.forName("jogamp.newt.driver.x11.X11Display"); - } else if (NativeWindowFactory.TYPE_AWT == type) { - displayClass = Class.forName("jogamp.newt.driver.awt.AWTDisplay"); - } else { - throw new RuntimeException("Unknown display type \"" + type + "\""); - } - } - if(null==displayClass) { - throw new ClassNotFoundException("Failed to find NEWT Display Class <"+type+".Display>"); + throw new ClassNotFoundException("Failed to find NEWT Display Class <"+type+".DisplayDriver>"); } return displayClass; } diff --git a/src/newt/classes/jogamp/newt/ScreenImpl.java b/src/newt/classes/jogamp/newt/ScreenImpl.java index 9f75a0d25..e2c0f746f 100644 --- a/src/newt/classes/jogamp/newt/ScreenImpl.java +++ b/src/newt/classes/jogamp/newt/ScreenImpl.java @@ -90,31 +90,13 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { }); } - @SuppressWarnings("unchecked") - private static Class getScreenClass(String type) throws ClassNotFoundException + private static Class getScreenClass(String type) throws ClassNotFoundException { - Class screenClass = NewtFactory.getCustomClass(type, "Screen"); + final Class screenClass = NewtFactory.getCustomClass(type, "ScreenDriver"); if(null==screenClass) { - if (NativeWindowFactory.TYPE_ANDROID == type) { - screenClass = Class.forName("jogamp.newt.driver.android.AndroidScreen"); - } else if (NativeWindowFactory.TYPE_EGL == type) { - screenClass = Class.forName("jogamp.newt.driver.kd.Screen"); - } else if (NativeWindowFactory.TYPE_WINDOWS == type) { - screenClass = Class.forName("jogamp.newt.driver.windows.WindowsScreen"); - } else if (NativeWindowFactory.TYPE_MACOSX == type) { - screenClass = Class.forName("jogamp.newt.driver.macosx.MacScreen"); - } else if (NativeWindowFactory.TYPE_X11 == type) { - screenClass = Class.forName("jogamp.newt.driver.x11.X11Screen"); - } else if (NativeWindowFactory.TYPE_AWT == type) { - screenClass = Class.forName("jogamp.newt.driver.awt.AWTScreen"); - } else { - throw new RuntimeException("Unknown window type \"" + type + "\""); - } - } - if(null==screenClass) { - throw new ClassNotFoundException("Failed to find NEWT Screen Class <"+type+".Screen>"); + throw new ClassNotFoundException("Failed to find NEWT Screen Class <"+type+".ScreenDriver>"); } - return (Class)screenClass; + return screenClass; } public static Screen create(Display display, int idx) { @@ -133,7 +115,7 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { } } synchronized(screenList) { - Class screenClass = getScreenClass(display.getType()); + Class screenClass = getScreenClass(display.getType()); ScreenImpl screen = (ScreenImpl) screenClass.newInstance(); screen.display = (DisplayImpl) display; idx = screen.validateScreenIndex(idx); diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index 2971fa07e..ad7195944 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -152,26 +152,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer private static Class getWindowClass(String type) throws ClassNotFoundException { - Class windowClass = NewtFactory.getCustomClass(type, "Window"); + final Class windowClass = NewtFactory.getCustomClass(type, "WindowDriver"); if(null==windowClass) { - if (NativeWindowFactory.TYPE_ANDROID == type) { - windowClass = Class.forName("jogamp.newt.driver.android.AndroidWindow"); - } else if (NativeWindowFactory.TYPE_EGL == type) { - windowClass = Class.forName("jogamp.newt.driver.kd.Window"); - } else if (NativeWindowFactory.TYPE_WINDOWS == type) { - windowClass = Class.forName("jogamp.newt.driver.windows.WindowsWindow"); - } else if (NativeWindowFactory.TYPE_MACOSX == type) { - windowClass = Class.forName("jogamp.newt.driver.macosx.MacWindow"); - } else if (NativeWindowFactory.TYPE_X11 == type) { - windowClass = Class.forName("jogamp.newt.driver.x11.X11Window"); - } else if (NativeWindowFactory.TYPE_AWT == type) { - windowClass = Class.forName("jogamp.newt.driver.awt.AWTWindow"); - } else { - throw new NativeWindowException("Unknown window type \"" + type + "\""); - } - } - if(null==windowClass) { - throw new ClassNotFoundException("Failed to find NEWT Window Class <"+type+".Window>"); + throw new ClassNotFoundException("Failed to find NEWT Window Class <"+type+".WindowDriver>"); } return windowClass; } diff --git a/src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java b/src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java deleted file mode 100644 index 0a43c9b8f..000000000 --- a/src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright 2011 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package jogamp.newt.driver.android; - -import jogamp.newt.*; -import jogamp.opengl.egl.*; - -import javax.media.nativewindow.*; - -public class AndroidDisplay extends jogamp.newt.DisplayImpl { - static { - NEWTJNILibLoader.loadNEWT(); - - if (!AndroidWindow.initIDs0()) { - throw new NativeWindowException("Failed to initialize Android NEWT Windowing library"); - } - } - - public static void initSingleton() { - // just exist to ensure static init has been run - } - - - public AndroidDisplay() { - } - - protected void createNativeImpl() { - // EGL Device - aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); - } - - protected void closeNativeImpl() { - aDevice.close(); - } - - protected void dispatchMessagesNative() { - // n/a .. DispatchMessages(); - } -} - diff --git a/src/newt/classes/jogamp/newt/driver/android/AndroidScreen.java b/src/newt/classes/jogamp/newt/driver/android/AndroidScreen.java deleted file mode 100644 index e108ed0bb..000000000 --- a/src/newt/classes/jogamp/newt/driver/android/AndroidScreen.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Copyright 2011 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package jogamp.newt.driver.android; - -import javax.media.nativewindow.*; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; - -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.util.ScreenModeUtil; - -import android.content.Context; -import android.graphics.PixelFormat; -import android.util.DisplayMetrics; -import android.view.Surface; -import android.view.WindowManager; - -public class AndroidScreen extends jogamp.newt.ScreenImpl { - - static { - AndroidDisplay.initSingleton(); - } - - public AndroidScreen() { - } - - protected void createNativeImpl() { - aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); - } - - protected void closeNativeImpl() { } - - protected ScreenMode getCurrentScreenModeImpl() { - final Context ctx = jogamp.common.os.android.StaticContext.getContext(); - final WindowManager wmgr = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); - final DisplayMetrics outMetrics = new DisplayMetrics(); - final android.view.Display aDisplay = wmgr.getDefaultDisplay(); - aDisplay.getMetrics(outMetrics); - - final int arot = aDisplay.getRotation(); - final int nrot = androidRotation2NewtRotation(arot); - int[] props = new int[ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL]; - int offset = 1; // set later for verification of iterator - offset = getScreenSize(outMetrics, nrot, props, offset); - offset = getBpp(aDisplay, props, offset); - offset = getScreenSizeMM(outMetrics, props, offset); - props[offset++] = (int) aDisplay.getRefreshRate(); - props[offset++] = nrot; - props[offset - ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL] = offset; // count - return ScreenModeUtil.streamIn(props, 0); - } - - protected int validateScreenIndex(int idx) { - return 0; // FIXME: only one screen available ? - } - - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - final ScreenMode sm = getCurrentScreenMode(); - virtualSize.setWidth(sm.getRotatedWidth()); - virtualSize.setHeight(sm.getRotatedHeight()); - } - - //---------------------------------------------------------------------- - // Internals only - // - static int androidRotation2NewtRotation(int arot) { - switch(arot) { - case Surface.ROTATION_270: return ScreenMode.ROTATE_270; - case Surface.ROTATION_180: return ScreenMode.ROTATE_180; - case Surface.ROTATION_90: return ScreenMode.ROTATE_90; - case Surface.ROTATION_0: - } - return ScreenMode.ROTATE_0; - } - static int getScreenSize(DisplayMetrics outMetrics, int nrot, int[] props, int offset) { - // swap width and height, since Android reflects rotated dimension, we don't - if (ScreenMode.ROTATE_90 == nrot || ScreenMode.ROTATE_270 == nrot) { - props[offset++] = outMetrics.heightPixels; - props[offset++] = outMetrics.widthPixels; - } else { - props[offset++] = outMetrics.widthPixels; - props[offset++] = outMetrics.heightPixels; - } - return offset; - } - static int getBpp(android.view.Display aDisplay, int[] props, int offset) { - int bpp; - switch(aDisplay.getPixelFormat()) { - case PixelFormat.RGBA_8888: bpp=32; break; - case PixelFormat.RGBX_8888: bpp=32; break; - case PixelFormat.RGB_888: bpp=24; break; - case PixelFormat.RGB_565: bpp=16; break; - case PixelFormat.RGBA_5551: bpp=16; break; - case PixelFormat.RGBA_4444: bpp=16; break; - case PixelFormat.RGB_332: bpp= 8; break; - default: bpp=32; - } - props[offset++] = bpp; - return offset; - } - static int getScreenSizeMM(DisplayMetrics outMetrics, int[] props, int offset) { - final float iw = (float) outMetrics.widthPixels / outMetrics.xdpi; - final float ih = (float) outMetrics.heightPixels / outMetrics.xdpi; - final float mmpi = 25.4f; - props[offset++] = (int) ((iw * mmpi)+0.5); - props[offset++] = (int) ((ih * mmpi)+0.5); - return offset; - } -} - diff --git a/src/newt/classes/jogamp/newt/driver/android/AndroidWindow.java b/src/newt/classes/jogamp/newt/driver/android/AndroidWindow.java deleted file mode 100644 index 73192a07f..000000000 --- a/src/newt/classes/jogamp/newt/driver/android/AndroidWindow.java +++ /dev/null @@ -1,458 +0,0 @@ -/** - * Copyright 2011 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package jogamp.newt.driver.android; - -import jogamp.common.os.android.StaticContext; -import jogamp.newt.driver.android.event.AndroidNewtEventFactory; - -import javax.media.nativewindow.Capabilities; -import javax.media.nativewindow.CapabilitiesImmutable; -import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.VisualIDHolder; -import javax.media.nativewindow.util.Insets; -import javax.media.nativewindow.util.Point; -import javax.media.opengl.GLCapabilitiesChooser; -import javax.media.opengl.GLCapabilitiesImmutable; - -import com.jogamp.nativewindow.egl.EGLGraphicsDevice; - -import jogamp.opengl.egl.EGL; -import jogamp.opengl.egl.EGLGraphicsConfiguration; -import jogamp.opengl.egl.EGLGraphicsConfigurationFactory; - -import android.content.Context; -import android.graphics.PixelFormat; -import android.os.Bundle; -import android.os.IBinder; -import android.os.ResultReceiver; -import android.util.Log; -import android.view.Surface; -import android.view.SurfaceHolder; -import android.view.SurfaceHolder.Callback2; -import android.view.inputmethod.InputMethodManager; -import android.view.SurfaceView; -import android.view.View; - -public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 { - static { - AndroidDisplay.initSingleton(); - } - - public static CapabilitiesImmutable fixCaps(boolean matchFormatPrecise, int format, CapabilitiesImmutable rCaps) { - PixelFormat pf = new PixelFormat(); - PixelFormat.getPixelFormatInfo(format, pf); - final CapabilitiesImmutable res; - int r, g, b, a; - - switch(format) { - case PixelFormat.RGBA_8888: r=8; g=8; b=8; a=8; break; - case PixelFormat.RGBX_8888: r=8; g=8; b=8; a=0; break; - case PixelFormat.RGB_888: r=8; g=8; b=8; a=0; break; - case PixelFormat.RGB_565: r=5; g=6; b=5; a=0; break; - case PixelFormat.RGBA_5551: r=5; g=5; b=5; a=1; break; - case PixelFormat.RGBA_4444: r=4; g=4; b=4; a=4; break; - case PixelFormat.RGB_332: r=3; g=3; b=2; a=0; break; - default: throw new InternalError("Unhandled pixelformat: "+format); - } - final boolean change = matchFormatPrecise || - rCaps.getRedBits() > r && - rCaps.getGreenBits() > g && - rCaps.getBlueBits() > b && - rCaps.getAlphaBits() > a ; - - if(change) { - Capabilities nCaps = (Capabilities) rCaps.cloneMutable(); - nCaps.setRedBits(r); - nCaps.setGreenBits(g); - nCaps.setBlueBits(b); - nCaps.setAlphaBits(a); - res = nCaps; - } else { - res = rCaps; - } - Log.d(MD.TAG, "fixCaps: format: "+format); - Log.d(MD.TAG, "fixCaps: requested: "+rCaps); - Log.d(MD.TAG, "fixCaps: chosen: "+res); - - return res; - } - - public static int getFormat(CapabilitiesImmutable rCaps) { - int fmt = PixelFormat.UNKNOWN; - - if(!rCaps.isBackgroundOpaque()) { - fmt = PixelFormat.TRANSLUCENT; - } else if(rCaps.getRedBits()<=5 && - rCaps.getGreenBits()<=6 && - rCaps.getBlueBits()<=5 && - rCaps.getAlphaBits()==0) { - fmt = PixelFormat.RGB_565; - } - /* else if(rCaps.getRedBits()<=5 && - rCaps.getGreenBits()<=5 && - rCaps.getBlueBits()<=5 && - rCaps.getAlphaBits()==1) { - fmt = PixelFormat.RGBA_5551; // FIXME: Supported ? - } */ - else { - fmt = PixelFormat.RGBA_8888; - } - Log.d(MD.TAG, "getFormat: requested: "+rCaps); - Log.d(MD.TAG, "getFormat: returned: "+fmt); - - return fmt; - } - - public static boolean isAndroidFormatTransparent(int aFormat) { - switch (aFormat) { - case PixelFormat.TRANSLUCENT: - case PixelFormat.TRANSPARENT: - return true; - } - return false; - } - - class AndroidEvents implements View.OnKeyListener, View.OnTouchListener, View.OnFocusChangeListener { - - @Override - public boolean onTouch(View v, android.view.MotionEvent event) { - final com.jogamp.newt.event.MouseEvent[] newtEvents = AndroidNewtEventFactory.createMouseEvents(event, AndroidWindow.this); - if(null != newtEvents) { - focusChanged(false, true); - for(int i=0; i[] getCustomConstructorArgumentTypes() { - return new Class[] { Context.class } ; - } - - public AndroidWindow() { - reset(); - } - - private void reset() { - ownAndroidWindow = false; - androidView = null; - nativeFormat = VisualIDHolder.VID_UNDEFINED; - androidFormat = VisualIDHolder.VID_UNDEFINED; - capsByFormat = null; - surface = null; - surfaceHandle = 0; - eglSurface = 0; - definePosition(0, 0); // default to 0/0 - setBrokenFocusChange(true); - } - - @Override - protected void instantiationFinished() { - final Context ctx = StaticContext.getContext(); - if(null == ctx) { - throw new NativeWindowException("No static [Application] Context has been set. Call StaticContext.setContext(Context) first."); - } - androidView = new MSurfaceView(ctx); - - final AndroidEvents ae = new AndroidEvents(); - androidView.setOnTouchListener(ae); - androidView.setClickable(false); - androidView.setOnKeyListener(ae); - androidView.setOnFocusChangeListener(ae); - androidView.setFocusable(true); - androidView.setFocusableInTouchMode(true); - - final SurfaceHolder sh = androidView.getHolder(); - sh.addCallback(AndroidWindow.this); - sh.setFormat(getFormat(getRequestedCapabilities())); - - // default size -> TBD ! - defineSize(0, 0); - } - - public SurfaceView getAndroidView() { return androidView; } - - @Override - protected boolean canCreateNativeImpl() { - final boolean b = 0 != surfaceHandle; - Log.d(MD.TAG, "canCreateNativeImpl: "+b); - return b; - } - - @Override - protected void createNativeImpl() { - Log.d(MD.TAG, "createNativeImpl 0 - surfaceHandle 0x"+Long.toHexString(surfaceHandle)+ - ", format [a "+androidFormat+", n "+nativeFormat+"], "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()+" - "+Thread.currentThread().getName()); - - if(0!=getParentWindowHandle()) { - throw new NativeWindowException("Window parenting not supported (yet)"); - } - if(0==surfaceHandle) { - throw new InternalError("XXX"); - } - - final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) getScreen().getDisplay().getGraphicsDevice(); - final EGLGraphicsConfiguration eglConfig = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic( - capsByFormat, (GLCapabilitiesImmutable) getRequestedCapabilities(), - (GLCapabilitiesChooser)capabilitiesChooser, getScreen().getGraphicsScreen(), nativeFormat, - isAndroidFormatTransparent(androidFormat)); - if (eglConfig == null) { - throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); - } - final int nativeVisualID = eglConfig.getVisualID(VisualIDHolder.VIDType.NATIVE); - Log.d(MD.TAG, "nativeVisualID 0x"+Integer.toHexString(nativeVisualID)); - if(VisualIDHolder.VID_UNDEFINED != nativeVisualID) { - setSurfaceVisualID0(surfaceHandle, nativeVisualID); - } - - eglSurface = EGL.eglCreateWindowSurface(eglDevice.getHandle(), eglConfig.getNativeConfig(), surfaceHandle, null); - if (EGL.EGL_NO_SURFACE==eglSurface) { - throw new NativeWindowException("Creation of window surface failed: "+eglConfig+", surfaceHandle 0x"+Long.toHexString(surfaceHandle)+", error "+toHexString(EGL.eglGetError())); - } - - // propagate data .. - setGraphicsConfiguration(eglConfig); - setWindowHandle(surfaceHandle); - focusChanged(false, true); - Log.d(MD.TAG, "createNativeImpl X"); - } - - @Override - protected void closeNativeImpl() { - release0(surfaceHandle); - surface = null; - surfaceHandle = 0; - eglSurface = 0; - } - - @Override - public final long getSurfaceHandle() { - return eglSurface; - } - - protected void requestFocusImpl(boolean reparented) { - if(null != androidView) { - Log.d(MD.TAG, "requestFocusImpl: reparented "+reparented); - androidView.post(new Runnable() { - public void run() { - androidView.requestFocus(); - androidView.bringToFront(); - } - }); - } - } - - protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { - if( 0 != ( FLAG_CHANGE_FULLSCREEN & flags) ) { - Log.d(MD.TAG, "reconfigureWindowImpl.setFullscreen post creation (setContentView()) n/a"); - return false; - } - if(width>0 || height>0) { - if(0!=getWindowHandle()) { - Log.d(MD.TAG, "reconfigureWindowImpl.setSize n/a"); - return false; - } - } - if(x>=0 || y>=0) { - Log.d(MD.TAG, "reconfigureWindowImpl.setPos n/a"); - return false; - } - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); - } - return true; - } - - protected Point getLocationOnScreenImpl(int x, int y) { - return new Point(x,y); - } - - protected void updateInsetsImpl(Insets insets) { - // nop .. - } - - //---------------------------------------------------------------------- - // Virtual On-Screen Keyboard / SoftInput - // - - private class KeyboardVisibleReceiver extends ResultReceiver { - public KeyboardVisibleReceiver() { - super(null); - } - - @Override - public void onReceiveResult(int r, Bundle data) { - boolean v = false; - - switch(r) { - case InputMethodManager.RESULT_UNCHANGED_SHOWN: - case InputMethodManager.RESULT_SHOWN: - v = true; - break; - case InputMethodManager.RESULT_HIDDEN: - case InputMethodManager.RESULT_UNCHANGED_HIDDEN: - v = false; - break; - } - Log.d(MD.TAG, "keyboardVisible: "+v); - keyboardVisibilityChanged(v); - } - } - private KeyboardVisibleReceiver keyboardVisibleReceiver = new KeyboardVisibleReceiver(); - - protected final boolean setKeyboardVisibleImpl(boolean visible) { - if(null != androidView) { - final InputMethodManager imm = (InputMethodManager) getAndroidView().getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - final IBinder winid = getAndroidView().getWindowToken(); - if(visible) { - // Show soft-keyboard: - imm.showSoftInput(androidView, 0, keyboardVisibleReceiver); - } else { - // hide keyboard : - imm.hideSoftInputFromWindow(winid, 0, keyboardVisibleReceiver); - } - return visible; - } else { - return false; // nop - } - } - - //---------------------------------------------------------------------- - // Surface Callbacks - // - - public void surfaceCreated(SurfaceHolder holder) { - Log.d(MD.TAG, "surfaceCreated: "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()); - } - - public void surfaceChanged(SurfaceHolder aHolder, int aFormat, int aWidth, int aHeight) { - Log.d(MD.TAG, "surfaceChanged: f "+nativeFormat+" -> "+aFormat+", "+aWidth+"x"+aHeight+", current surfaceHandle: 0x"+Long.toHexString(surfaceHandle)); - if(0!=surfaceHandle && androidFormat != aFormat ) { - // re-create - Log.d(MD.TAG, "surfaceChanged (destroy old)"); - if(!windowDestroyNotify(true)) { - destroy(); - } - surfaceHandle = 0; - surface=null; - } - if(getScreen().isNativeValid()) { - getScreen().getCurrentScreenMode(); // if ScreenMode changed .. trigger ScreenMode event - } - - if(0>getX() || 0>getY()) { - positionChanged(false, 0, 0); - } - - if(0 == surfaceHandle) { - androidFormat = aFormat; - surface = aHolder.getSurface(); - surfaceHandle = getSurfaceHandle0(surface); - acquire0(surfaceHandle); - nativeFormat = getSurfaceVisualID0(surfaceHandle); - final int nWidth = getWidth0(surfaceHandle); - final int nHeight = getHeight0(surfaceHandle); - capsByFormat = (GLCapabilitiesImmutable) fixCaps(true /* matchFormatPrecise */, nativeFormat, getRequestedCapabilities()); - sizeChanged(false, nWidth, nHeight, false); - - Log.d(MD.TAG, "surfaceRealized: isValid: "+surface.isValid()+ - ", new surfaceHandle 0x"+Long.toHexString(surfaceHandle)+ - ", format [a "+androidFormat+"/n "+nativeFormat+"], "+ - getX()+"/"+getY()+" "+nWidth+"x"+nHeight+", visible: "+isVisible()); - - if(isVisible()) { - setVisible(true); - } - } - sizeChanged(false, aWidth, aHeight, false); - windowRepaint(0, 0, aWidth, aHeight); - Log.d(MD.TAG, "surfaceChanged: X"); - } - - public void surfaceDestroyed(SurfaceHolder holder) { - Log.d(MD.TAG, "surfaceDestroyed"); - windowDestroyNotify(true); // actually too late .. however .. - } - - public void surfaceRedrawNeeded(SurfaceHolder holder) { - Log.d(MD.TAG, "surfaceRedrawNeeded"); - windowRepaint(0, 0, getWidth(), getHeight()); - } - - private boolean ownAndroidWindow; - private MSurfaceView androidView; - private int nativeFormat; // chosen current native PixelFormat (suitable for EGL) - private int androidFormat; // chosen current android PixelFormat (-1, -2 ..) - private GLCapabilitiesImmutable capsByFormat; // fixed requestedCaps by PixelFormat - private Surface surface; - private volatile long surfaceHandle; - private long eglSurface; - - class MSurfaceView extends SurfaceView { - public MSurfaceView (Context ctx) { - super(ctx); - setBackgroundDrawable(null); - // setBackgroundColor(Color.TRANSPARENT); - } - } - //---------------------------------------------------------------------- - // Internals only - // - protected static native boolean initIDs0(); - protected static native long getSurfaceHandle0(Surface surface); - protected static native int getSurfaceVisualID0(long surfaceHandle); - protected static native void setSurfaceVisualID0(long surfaceHandle, int nativeVisualID); - protected static native int getWidth0(long surfaceHandle); - protected static native int getHeight0(long surfaceHandle); - protected static native void acquire0(long surfaceHandle); - protected static native void release0(long surfaceHandle); -} diff --git a/src/newt/classes/jogamp/newt/driver/android/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/android/DisplayDriver.java new file mode 100644 index 000000000..a367462c4 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/android/DisplayDriver.java @@ -0,0 +1,66 @@ +/** + * Copyright 2011 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.newt.driver.android; + +import jogamp.newt.*; +import jogamp.opengl.egl.*; + +import javax.media.nativewindow.*; + +public class DisplayDriver extends jogamp.newt.DisplayImpl { + static { + NEWTJNILibLoader.loadNEWT(); + + if (!WindowDriver.initIDs0()) { + throw new NativeWindowException("Failed to initialize Android NEWT Windowing library"); + } + } + + public static void initSingleton() { + // just exist to ensure static init has been run + } + + + public DisplayDriver() { + } + + protected void createNativeImpl() { + // EGL Device + aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + } + + protected void closeNativeImpl() { + aDevice.close(); + } + + protected void dispatchMessagesNative() { + // n/a .. DispatchMessages(); + } +} + diff --git a/src/newt/classes/jogamp/newt/driver/android/NewtBaseActivity.java b/src/newt/classes/jogamp/newt/driver/android/NewtBaseActivity.java index 4537fa963..91c589beb 100644 --- a/src/newt/classes/jogamp/newt/driver/android/NewtBaseActivity.java +++ b/src/newt/classes/jogamp/newt/driver/android/NewtBaseActivity.java @@ -36,7 +36,7 @@ import javax.media.opengl.FPSCounter; import com.jogamp.newt.Window; import com.jogamp.opengl.util.Animator; -import jogamp.newt.driver.android.AndroidWindow; +import jogamp.newt.driver.android.WindowDriver; import android.app.Activity; import android.content.Context; @@ -83,10 +83,10 @@ public class NewtBaseActivity extends Activity { */ public void setContentView(android.view.Window androidWindow, Window newtWindow) { newtWindow = newtWindow.getDelegatedWindow(); - if(newtWindow instanceof AndroidWindow) { + if(newtWindow instanceof WindowDriver) { adaptTheme4Transparency(newtWindow.getRequestedCapabilities()); layoutForNEWTWindow(androidWindow, newtWindow); - AndroidWindow newtAWindow = (AndroidWindow)newtWindow; + WindowDriver newtAWindow = (WindowDriver)newtWindow; androidWindow.setContentView(newtAWindow.getAndroidView()); registerNEWTWindow(newtAWindow); } else { @@ -107,8 +107,8 @@ public class NewtBaseActivity extends Activity { */ public void addContentView(android.view.Window androidWindow, Window newtWindow, android.view.ViewGroup.LayoutParams params) { newtWindow = newtWindow.getDelegatedWindow(); - if(newtWindow instanceof AndroidWindow) { - AndroidWindow newtAWindow = (AndroidWindow)newtWindow; + if(newtWindow instanceof WindowDriver) { + WindowDriver newtAWindow = (WindowDriver)newtWindow; androidWindow.addContentView(newtAWindow.getAndroidView(), params); registerNEWTWindow(newtAWindow); } else { diff --git a/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivity.java b/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivity.java index 36b83337a..a49f1648c 100644 --- a/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivity.java +++ b/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivity.java @@ -69,7 +69,7 @@ public class NewtVersionActivity extends NewtBaseActivity { glWindow.setUndecorated(true); glWindow.setSize(32, 32); glWindow.setPosition(0, 0); - final android.view.View androidGLView = ((AndroidWindow)glWindow.getDelegatedWindow()).getAndroidView(); + final android.view.View androidGLView = ((WindowDriver)glWindow.getDelegatedWindow()).getAndroidView(); viewGroup.addView(androidGLView, new android.widget.FrameLayout.LayoutParams(glWindow.getWidth(), glWindow.getHeight(), Gravity.BOTTOM|Gravity.RIGHT)); registerNEWTWindow(glWindow); diff --git a/src/newt/classes/jogamp/newt/driver/android/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/android/ScreenDriver.java new file mode 100644 index 000000000..795aac5fb --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/android/ScreenDriver.java @@ -0,0 +1,138 @@ +/** + * Copyright 2011 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.newt.driver.android; + +import javax.media.nativewindow.*; +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.Point; + +import com.jogamp.newt.ScreenMode; +import com.jogamp.newt.util.ScreenModeUtil; + +import android.content.Context; +import android.graphics.PixelFormat; +import android.util.DisplayMetrics; +import android.view.Surface; +import android.view.WindowManager; + +public class ScreenDriver extends jogamp.newt.ScreenImpl { + + static { + DisplayDriver.initSingleton(); + } + + public ScreenDriver() { + } + + protected void createNativeImpl() { + aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); + } + + protected void closeNativeImpl() { } + + protected ScreenMode getCurrentScreenModeImpl() { + final Context ctx = jogamp.common.os.android.StaticContext.getContext(); + final WindowManager wmgr = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE); + final DisplayMetrics outMetrics = new DisplayMetrics(); + final android.view.Display aDisplay = wmgr.getDefaultDisplay(); + aDisplay.getMetrics(outMetrics); + + final int arot = aDisplay.getRotation(); + final int nrot = androidRotation2NewtRotation(arot); + int[] props = new int[ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL]; + int offset = 1; // set later for verification of iterator + offset = getScreenSize(outMetrics, nrot, props, offset); + offset = getBpp(aDisplay, props, offset); + offset = getScreenSizeMM(outMetrics, props, offset); + props[offset++] = (int) aDisplay.getRefreshRate(); + props[offset++] = nrot; + props[offset - ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL] = offset; // count + return ScreenModeUtil.streamIn(props, 0); + } + + protected int validateScreenIndex(int idx) { + return 0; // FIXME: only one screen available ? + } + + protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { + virtualOrigin.setX(0); + virtualOrigin.setY(0); + final ScreenMode sm = getCurrentScreenMode(); + virtualSize.setWidth(sm.getRotatedWidth()); + virtualSize.setHeight(sm.getRotatedHeight()); + } + + //---------------------------------------------------------------------- + // Internals only + // + static int androidRotation2NewtRotation(int arot) { + switch(arot) { + case Surface.ROTATION_270: return ScreenMode.ROTATE_270; + case Surface.ROTATION_180: return ScreenMode.ROTATE_180; + case Surface.ROTATION_90: return ScreenMode.ROTATE_90; + case Surface.ROTATION_0: + } + return ScreenMode.ROTATE_0; + } + static int getScreenSize(DisplayMetrics outMetrics, int nrot, int[] props, int offset) { + // swap width and height, since Android reflects rotated dimension, we don't + if (ScreenMode.ROTATE_90 == nrot || ScreenMode.ROTATE_270 == nrot) { + props[offset++] = outMetrics.heightPixels; + props[offset++] = outMetrics.widthPixels; + } else { + props[offset++] = outMetrics.widthPixels; + props[offset++] = outMetrics.heightPixels; + } + return offset; + } + static int getBpp(android.view.Display aDisplay, int[] props, int offset) { + int bpp; + switch(aDisplay.getPixelFormat()) { + case PixelFormat.RGBA_8888: bpp=32; break; + case PixelFormat.RGBX_8888: bpp=32; break; + case PixelFormat.RGB_888: bpp=24; break; + case PixelFormat.RGB_565: bpp=16; break; + case PixelFormat.RGBA_5551: bpp=16; break; + case PixelFormat.RGBA_4444: bpp=16; break; + case PixelFormat.RGB_332: bpp= 8; break; + default: bpp=32; + } + props[offset++] = bpp; + return offset; + } + static int getScreenSizeMM(DisplayMetrics outMetrics, int[] props, int offset) { + final float iw = (float) outMetrics.widthPixels / outMetrics.xdpi; + final float ih = (float) outMetrics.heightPixels / outMetrics.xdpi; + final float mmpi = 25.4f; + props[offset++] = (int) ((iw * mmpi)+0.5); + props[offset++] = (int) ((ih * mmpi)+0.5); + return offset; + } +} + diff --git a/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java new file mode 100644 index 000000000..8ad11b35f --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java @@ -0,0 +1,458 @@ +/** + * Copyright 2011 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.newt.driver.android; + +import jogamp.common.os.android.StaticContext; +import jogamp.newt.driver.android.event.AndroidNewtEventFactory; + +import javax.media.nativewindow.Capabilities; +import javax.media.nativewindow.CapabilitiesImmutable; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.VisualIDHolder; +import javax.media.nativewindow.util.Insets; +import javax.media.nativewindow.util.Point; +import javax.media.opengl.GLCapabilitiesChooser; +import javax.media.opengl.GLCapabilitiesImmutable; + +import com.jogamp.nativewindow.egl.EGLGraphicsDevice; + +import jogamp.opengl.egl.EGL; +import jogamp.opengl.egl.EGLGraphicsConfiguration; +import jogamp.opengl.egl.EGLGraphicsConfigurationFactory; + +import android.content.Context; +import android.graphics.PixelFormat; +import android.os.Bundle; +import android.os.IBinder; +import android.os.ResultReceiver; +import android.util.Log; +import android.view.Surface; +import android.view.SurfaceHolder; +import android.view.SurfaceHolder.Callback2; +import android.view.inputmethod.InputMethodManager; +import android.view.SurfaceView; +import android.view.View; + +public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { + static { + DisplayDriver.initSingleton(); + } + + public static CapabilitiesImmutable fixCaps(boolean matchFormatPrecise, int format, CapabilitiesImmutable rCaps) { + PixelFormat pf = new PixelFormat(); + PixelFormat.getPixelFormatInfo(format, pf); + final CapabilitiesImmutable res; + int r, g, b, a; + + switch(format) { + case PixelFormat.RGBA_8888: r=8; g=8; b=8; a=8; break; + case PixelFormat.RGBX_8888: r=8; g=8; b=8; a=0; break; + case PixelFormat.RGB_888: r=8; g=8; b=8; a=0; break; + case PixelFormat.RGB_565: r=5; g=6; b=5; a=0; break; + case PixelFormat.RGBA_5551: r=5; g=5; b=5; a=1; break; + case PixelFormat.RGBA_4444: r=4; g=4; b=4; a=4; break; + case PixelFormat.RGB_332: r=3; g=3; b=2; a=0; break; + default: throw new InternalError("Unhandled pixelformat: "+format); + } + final boolean change = matchFormatPrecise || + rCaps.getRedBits() > r && + rCaps.getGreenBits() > g && + rCaps.getBlueBits() > b && + rCaps.getAlphaBits() > a ; + + if(change) { + Capabilities nCaps = (Capabilities) rCaps.cloneMutable(); + nCaps.setRedBits(r); + nCaps.setGreenBits(g); + nCaps.setBlueBits(b); + nCaps.setAlphaBits(a); + res = nCaps; + } else { + res = rCaps; + } + Log.d(MD.TAG, "fixCaps: format: "+format); + Log.d(MD.TAG, "fixCaps: requested: "+rCaps); + Log.d(MD.TAG, "fixCaps: chosen: "+res); + + return res; + } + + public static int getFormat(CapabilitiesImmutable rCaps) { + int fmt = PixelFormat.UNKNOWN; + + if(!rCaps.isBackgroundOpaque()) { + fmt = PixelFormat.TRANSLUCENT; + } else if(rCaps.getRedBits()<=5 && + rCaps.getGreenBits()<=6 && + rCaps.getBlueBits()<=5 && + rCaps.getAlphaBits()==0) { + fmt = PixelFormat.RGB_565; + } + /* else if(rCaps.getRedBits()<=5 && + rCaps.getGreenBits()<=5 && + rCaps.getBlueBits()<=5 && + rCaps.getAlphaBits()==1) { + fmt = PixelFormat.RGBA_5551; // FIXME: Supported ? + } */ + else { + fmt = PixelFormat.RGBA_8888; + } + Log.d(MD.TAG, "getFormat: requested: "+rCaps); + Log.d(MD.TAG, "getFormat: returned: "+fmt); + + return fmt; + } + + public static boolean isAndroidFormatTransparent(int aFormat) { + switch (aFormat) { + case PixelFormat.TRANSLUCENT: + case PixelFormat.TRANSPARENT: + return true; + } + return false; + } + + class AndroidEvents implements View.OnKeyListener, View.OnTouchListener, View.OnFocusChangeListener { + + @Override + public boolean onTouch(View v, android.view.MotionEvent event) { + final com.jogamp.newt.event.MouseEvent[] newtEvents = AndroidNewtEventFactory.createMouseEvents(event, WindowDriver.this); + if(null != newtEvents) { + focusChanged(false, true); + for(int i=0; i[] getCustomConstructorArgumentTypes() { + return new Class[] { Context.class } ; + } + + public WindowDriver() { + reset(); + } + + private void reset() { + ownAndroidWindow = false; + androidView = null; + nativeFormat = VisualIDHolder.VID_UNDEFINED; + androidFormat = VisualIDHolder.VID_UNDEFINED; + capsByFormat = null; + surface = null; + surfaceHandle = 0; + eglSurface = 0; + definePosition(0, 0); // default to 0/0 + setBrokenFocusChange(true); + } + + @Override + protected void instantiationFinished() { + final Context ctx = StaticContext.getContext(); + if(null == ctx) { + throw new NativeWindowException("No static [Application] Context has been set. Call StaticContext.setContext(Context) first."); + } + androidView = new MSurfaceView(ctx); + + final AndroidEvents ae = new AndroidEvents(); + androidView.setOnTouchListener(ae); + androidView.setClickable(false); + androidView.setOnKeyListener(ae); + androidView.setOnFocusChangeListener(ae); + androidView.setFocusable(true); + androidView.setFocusableInTouchMode(true); + + final SurfaceHolder sh = androidView.getHolder(); + sh.addCallback(WindowDriver.this); + sh.setFormat(getFormat(getRequestedCapabilities())); + + // default size -> TBD ! + defineSize(0, 0); + } + + public SurfaceView getAndroidView() { return androidView; } + + @Override + protected boolean canCreateNativeImpl() { + final boolean b = 0 != surfaceHandle; + Log.d(MD.TAG, "canCreateNativeImpl: "+b); + return b; + } + + @Override + protected void createNativeImpl() { + Log.d(MD.TAG, "createNativeImpl 0 - surfaceHandle 0x"+Long.toHexString(surfaceHandle)+ + ", format [a "+androidFormat+", n "+nativeFormat+"], "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()+" - "+Thread.currentThread().getName()); + + if(0!=getParentWindowHandle()) { + throw new NativeWindowException("Window parenting not supported (yet)"); + } + if(0==surfaceHandle) { + throw new InternalError("XXX"); + } + + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) getScreen().getDisplay().getGraphicsDevice(); + final EGLGraphicsConfiguration eglConfig = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic( + capsByFormat, (GLCapabilitiesImmutable) getRequestedCapabilities(), + (GLCapabilitiesChooser)capabilitiesChooser, getScreen().getGraphicsScreen(), nativeFormat, + isAndroidFormatTransparent(androidFormat)); + if (eglConfig == null) { + throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); + } + final int nativeVisualID = eglConfig.getVisualID(VisualIDHolder.VIDType.NATIVE); + Log.d(MD.TAG, "nativeVisualID 0x"+Integer.toHexString(nativeVisualID)); + if(VisualIDHolder.VID_UNDEFINED != nativeVisualID) { + setSurfaceVisualID0(surfaceHandle, nativeVisualID); + } + + eglSurface = EGL.eglCreateWindowSurface(eglDevice.getHandle(), eglConfig.getNativeConfig(), surfaceHandle, null); + if (EGL.EGL_NO_SURFACE==eglSurface) { + throw new NativeWindowException("Creation of window surface failed: "+eglConfig+", surfaceHandle 0x"+Long.toHexString(surfaceHandle)+", error "+toHexString(EGL.eglGetError())); + } + + // propagate data .. + setGraphicsConfiguration(eglConfig); + setWindowHandle(surfaceHandle); + focusChanged(false, true); + Log.d(MD.TAG, "createNativeImpl X"); + } + + @Override + protected void closeNativeImpl() { + release0(surfaceHandle); + surface = null; + surfaceHandle = 0; + eglSurface = 0; + } + + @Override + public final long getSurfaceHandle() { + return eglSurface; + } + + protected void requestFocusImpl(boolean reparented) { + if(null != androidView) { + Log.d(MD.TAG, "requestFocusImpl: reparented "+reparented); + androidView.post(new Runnable() { + public void run() { + androidView.requestFocus(); + androidView.bringToFront(); + } + }); + } + } + + protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + if( 0 != ( FLAG_CHANGE_FULLSCREEN & flags) ) { + Log.d(MD.TAG, "reconfigureWindowImpl.setFullscreen post creation (setContentView()) n/a"); + return false; + } + if(width>0 || height>0) { + if(0!=getWindowHandle()) { + Log.d(MD.TAG, "reconfigureWindowImpl.setSize n/a"); + return false; + } + } + if(x>=0 || y>=0) { + Log.d(MD.TAG, "reconfigureWindowImpl.setPos n/a"); + return false; + } + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { + visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); + } + return true; + } + + protected Point getLocationOnScreenImpl(int x, int y) { + return new Point(x,y); + } + + protected void updateInsetsImpl(Insets insets) { + // nop .. + } + + //---------------------------------------------------------------------- + // Virtual On-Screen Keyboard / SoftInput + // + + private class KeyboardVisibleReceiver extends ResultReceiver { + public KeyboardVisibleReceiver() { + super(null); + } + + @Override + public void onReceiveResult(int r, Bundle data) { + boolean v = false; + + switch(r) { + case InputMethodManager.RESULT_UNCHANGED_SHOWN: + case InputMethodManager.RESULT_SHOWN: + v = true; + break; + case InputMethodManager.RESULT_HIDDEN: + case InputMethodManager.RESULT_UNCHANGED_HIDDEN: + v = false; + break; + } + Log.d(MD.TAG, "keyboardVisible: "+v); + keyboardVisibilityChanged(v); + } + } + private KeyboardVisibleReceiver keyboardVisibleReceiver = new KeyboardVisibleReceiver(); + + protected final boolean setKeyboardVisibleImpl(boolean visible) { + if(null != androidView) { + final InputMethodManager imm = (InputMethodManager) getAndroidView().getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + final IBinder winid = getAndroidView().getWindowToken(); + if(visible) { + // Show soft-keyboard: + imm.showSoftInput(androidView, 0, keyboardVisibleReceiver); + } else { + // hide keyboard : + imm.hideSoftInputFromWindow(winid, 0, keyboardVisibleReceiver); + } + return visible; + } else { + return false; // nop + } + } + + //---------------------------------------------------------------------- + // Surface Callbacks + // + + public void surfaceCreated(SurfaceHolder holder) { + Log.d(MD.TAG, "surfaceCreated: "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()); + } + + public void surfaceChanged(SurfaceHolder aHolder, int aFormat, int aWidth, int aHeight) { + Log.d(MD.TAG, "surfaceChanged: f "+nativeFormat+" -> "+aFormat+", "+aWidth+"x"+aHeight+", current surfaceHandle: 0x"+Long.toHexString(surfaceHandle)); + if(0!=surfaceHandle && androidFormat != aFormat ) { + // re-create + Log.d(MD.TAG, "surfaceChanged (destroy old)"); + if(!windowDestroyNotify(true)) { + destroy(); + } + surfaceHandle = 0; + surface=null; + } + if(getScreen().isNativeValid()) { + getScreen().getCurrentScreenMode(); // if ScreenMode changed .. trigger ScreenMode event + } + + if(0>getX() || 0>getY()) { + positionChanged(false, 0, 0); + } + + if(0 == surfaceHandle) { + androidFormat = aFormat; + surface = aHolder.getSurface(); + surfaceHandle = getSurfaceHandle0(surface); + acquire0(surfaceHandle); + nativeFormat = getSurfaceVisualID0(surfaceHandle); + final int nWidth = getWidth0(surfaceHandle); + final int nHeight = getHeight0(surfaceHandle); + capsByFormat = (GLCapabilitiesImmutable) fixCaps(true /* matchFormatPrecise */, nativeFormat, getRequestedCapabilities()); + sizeChanged(false, nWidth, nHeight, false); + + Log.d(MD.TAG, "surfaceRealized: isValid: "+surface.isValid()+ + ", new surfaceHandle 0x"+Long.toHexString(surfaceHandle)+ + ", format [a "+androidFormat+"/n "+nativeFormat+"], "+ + getX()+"/"+getY()+" "+nWidth+"x"+nHeight+", visible: "+isVisible()); + + if(isVisible()) { + setVisible(true); + } + } + sizeChanged(false, aWidth, aHeight, false); + windowRepaint(0, 0, aWidth, aHeight); + Log.d(MD.TAG, "surfaceChanged: X"); + } + + public void surfaceDestroyed(SurfaceHolder holder) { + Log.d(MD.TAG, "surfaceDestroyed"); + windowDestroyNotify(true); // actually too late .. however .. + } + + public void surfaceRedrawNeeded(SurfaceHolder holder) { + Log.d(MD.TAG, "surfaceRedrawNeeded"); + windowRepaint(0, 0, getWidth(), getHeight()); + } + + private boolean ownAndroidWindow; + private MSurfaceView androidView; + private int nativeFormat; // chosen current native PixelFormat (suitable for EGL) + private int androidFormat; // chosen current android PixelFormat (-1, -2 ..) + private GLCapabilitiesImmutable capsByFormat; // fixed requestedCaps by PixelFormat + private Surface surface; + private volatile long surfaceHandle; + private long eglSurface; + + class MSurfaceView extends SurfaceView { + public MSurfaceView (Context ctx) { + super(ctx); + setBackgroundDrawable(null); + // setBackgroundColor(Color.TRANSPARENT); + } + } + //---------------------------------------------------------------------- + // Internals only + // + protected static native boolean initIDs0(); + protected static native long getSurfaceHandle0(Surface surface); + protected static native int getSurfaceVisualID0(long surfaceHandle); + protected static native void setSurfaceVisualID0(long surfaceHandle, int nativeVisualID); + protected static native int getWidth0(long surfaceHandle); + protected static native int getHeight0(long surfaceHandle); + protected static native void acquire0(long surfaceHandle); + protected static native void release0(long surfaceHandle); +} diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java b/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java index a7950048a..b3fdcad41 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java +++ b/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java @@ -1,5 +1,6 @@ /* * Copyright (c) 2008 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 diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java b/src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java deleted file mode 100644 index 65f8b4715..000000000 --- a/src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.awt; - -import com.jogamp.nativewindow.awt.AWTGraphicsDevice; -import com.jogamp.newt.NewtFactory; -import com.jogamp.newt.util.EDTUtil; - -import jogamp.newt.DisplayImpl; - -public class AWTDisplay extends DisplayImpl { - public AWTDisplay() { - } - - protected void createNativeImpl() { - aDevice = AWTGraphicsDevice.createDefault(); - } - - protected void setAWTGraphicsDevice(AWTGraphicsDevice d) { - aDevice = d; - } - - protected void closeNativeImpl() { } - - @Override - protected EDTUtil createEDTUtil() { - final EDTUtil def; - if(NewtFactory.useEDT()) { - def = AWTEDTUtil.getSingleton(); - if(DEBUG) { - System.err.println("AWTDisplay.createNative("+getFQName()+") Create EDTUtil: "+def.getClass().getName()); - } - } else { - def = null; - } - return def; - } - - protected void dispatchMessagesNative() { /* nop */ } -} - diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTScreen.java b/src/newt/classes/jogamp/newt/driver/awt/AWTScreen.java deleted file mode 100644 index a3c0281b1..000000000 --- a/src/newt/classes/jogamp/newt/driver/awt/AWTScreen.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.awt; - -import java.awt.DisplayMode; - -import jogamp.newt.ScreenImpl; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; - -import com.jogamp.nativewindow.awt.AWTGraphicsDevice; -import com.jogamp.nativewindow.awt.AWTGraphicsScreen; - -public class AWTScreen extends ScreenImpl { - public AWTScreen() { - } - - protected void createNativeImpl() { - aScreen = new AWTGraphicsScreen((AWTGraphicsDevice)display.getGraphicsDevice()); - } - - protected void setAWTGraphicsScreen(AWTGraphicsScreen s) { - aScreen = s; - } - - /** - * Used by AWTWindow .. - */ - @Override - protected void updateVirtualScreenOriginAndSize() { - super.updateVirtualScreenOriginAndSize(); - } - - protected void closeNativeImpl() { } - - protected int validateScreenIndex(int idx) { - return idx; // pass through ... - } - - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - final DisplayMode mode = ((AWTGraphicsDevice)getDisplay().getGraphicsDevice()).getGraphicsDevice().getDisplayMode(); - if(null != mode) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(mode.getWidth()); - virtualSize.setHeight(mode.getHeight()); - } - } - -} diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTWindow.java b/src/newt/classes/jogamp/newt/driver/awt/AWTWindow.java deleted file mode 100644 index 2b2fed545..000000000 --- a/src/newt/classes/jogamp/newt/driver/awt/AWTWindow.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.awt; - -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Frame; -import java.awt.Insets; - -import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.util.Point; - -import jogamp.newt.WindowImpl; - -import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration; -import com.jogamp.nativewindow.awt.AWTGraphicsDevice; -import com.jogamp.nativewindow.awt.AWTGraphicsScreen; -import com.jogamp.newt.event.awt.AWTKeyAdapter; -import com.jogamp.newt.event.awt.AWTMouseAdapter; -import com.jogamp.newt.event.awt.AWTWindowAdapter; - -/** An implementation of the Newt Window class built using the - AWT. This is provided for convenience of porting to platforms - supporting Java SE. */ - -public class AWTWindow extends WindowImpl { - - public AWTWindow() { - this(null); - } - - public static Class[] getCustomConstructorArgumentTypes() { - return new Class[] { Container.class } ; - } - - public AWTWindow(Container container) { - super(); - this.container = container; - if(container instanceof Frame) { - frame = (Frame) container; - } - } - - private boolean owningFrame; - private Container container = null; - private Frame frame = null; // same instance as container, just for impl. convenience - private AWTCanvas canvas; - - protected void requestFocusImpl(boolean reparented) { - container.requestFocus(); - } - - @Override - protected void setTitleImpl(final String title) { - if (frame != null) { - frame.setTitle(title); - } - } - - protected void createNativeImpl() { - if(0!=getParentWindowHandle()) { - throw new RuntimeException("Window parenting not supported in AWT, use AWTWindow(Frame) cstr for wrapping instead"); - } - - if(null==container) { - frame = new Frame(); - container = frame; - owningFrame=true; - } else { - owningFrame=false; - defineSize(container.getWidth(), container.getHeight()); - definePosition(container.getX(), container.getY()); - } - if(null!=frame) { - frame.setTitle(getTitle()); - } - container.setLayout(new BorderLayout()); - canvas = new AWTCanvas(capsRequested, AWTWindow.this.capabilitiesChooser); - - addWindowListener(new LocalWindowListener()); - - new AWTMouseAdapter(this).addTo(canvas); // fwd all AWT Mouse events to here - new AWTKeyAdapter(this).addTo(canvas); // fwd all AWT Key events to here - - // canvas.addComponentListener(listener); - container.add(canvas, BorderLayout.CENTER); - container.setSize(getWidth(), getHeight()); - container.setLocation(getX(), getY()); - new AWTWindowAdapter(this).addTo(container); // fwd all AWT Window events to here - - reconfigureWindowImpl(getX(), getY(), getWidth(), getHeight(), getReconfigureFlags(FLAG_CHANGE_VISIBILITY | FLAG_CHANGE_DECORATION, true)); - // throws exception if failed .. - - setWindowHandle(1); // just a marker .. - } - - protected void closeNativeImpl() { - setWindowHandle(0); // just a marker .. - if(null!=container) { - container.setVisible(false); - container.remove(canvas); - container.setEnabled(false); - canvas.setEnabled(false); - } - if(owningFrame && null!=frame) { - frame.dispose(); - owningFrame=false; - frame = null; - } - } - - @Override - public boolean hasDeviceChanged() { - boolean res = canvas.hasDeviceChanged(); - if(res) { - final AWTGraphicsConfiguration cfg = canvas.getAWTGraphicsConfiguration(); - if (null == cfg) { - throw new NativeWindowException("Error Device change null GraphicsConfiguration: "+this); - } - setGraphicsConfiguration(cfg); - - // propagate new info .. - ((AWTScreen)getScreen()).setAWTGraphicsScreen((AWTGraphicsScreen)cfg.getScreen()); - ((AWTDisplay)getScreen().getDisplay()).setAWTGraphicsDevice((AWTGraphicsDevice)cfg.getScreen().getDevice()); - - ((AWTScreen)getScreen()).updateVirtualScreenOriginAndSize(); - } - return res; - } - - protected void updateInsetsImpl(javax.media.nativewindow.util.Insets insets) { - Insets contInsets = container.getInsets(); - insets.setLeftWidth(contInsets.left); - insets.setRightWidth(contInsets.right); - insets.setTopHeight(contInsets.top); - insets.setBottomHeight(contInsets.bottom); - } - - protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { - if(0 != ( FLAG_CHANGE_DECORATION & flags) && null!=frame) { - if(!container.isDisplayable()) { - frame.setUndecorated(isUndecorated()); - } else { - if(DEBUG_IMPLEMENTATION) { - System.err.println("AWTWindow can't undecorate already created frame"); - } - } - } - - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - container.setVisible(0 != ( FLAG_IS_VISIBLE & flags)); - } - - container.setLocation(x, y); - Insets insets = container.getInsets(); - container.setSize(width + insets.left + insets.right, - height + insets.top + insets.bottom); - - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - if( 0 != ( FLAG_IS_VISIBLE & flags ) ) { - if( !hasDeviceChanged() ) { - // oops ?? - final AWTGraphicsConfiguration cfg = canvas.getAWTGraphicsConfiguration(); - if(null == cfg) { - throw new NativeWindowException("Error: !hasDeviceChanged && null == GraphicsConfiguration: "+this); - } - setGraphicsConfiguration(cfg); - } - } - visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); - } - - return true; - } - - protected Point getLocationOnScreenImpl(int x, int y) { - java.awt.Point ap = canvas.getLocationOnScreen(); - ap.translate(x, y); - return new Point((int)(ap.getX()+0.5),(int)(ap.getY()+0.5)); - } - - @Override - public Object getWrappedWindow() { - return canvas; - } - - class LocalWindowListener extends com.jogamp.newt.event.WindowAdapter { - @Override - public void windowMoved(com.jogamp.newt.event.WindowEvent e) { - if(null!=container) { - definePosition(container.getX(), container.getY()); - } - } - @Override - public void windowResized(com.jogamp.newt.event.WindowEvent e) { - if(null!=canvas) { - defineSize(canvas.getWidth(), canvas.getHeight()); - } - } - } -} diff --git a/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java new file mode 100644 index 000000000..39d96585b --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2008 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. + * + */ + +package jogamp.newt.driver.awt; + +import com.jogamp.nativewindow.awt.AWTGraphicsDevice; +import com.jogamp.newt.NewtFactory; +import com.jogamp.newt.util.EDTUtil; + +import jogamp.newt.DisplayImpl; + +public class DisplayDriver extends DisplayImpl { + public DisplayDriver() { + } + + protected void createNativeImpl() { + aDevice = AWTGraphicsDevice.createDefault(); + } + + protected void setAWTGraphicsDevice(AWTGraphicsDevice d) { + aDevice = d; + } + + protected void closeNativeImpl() { } + + @Override + protected EDTUtil createEDTUtil() { + final EDTUtil def; + if(NewtFactory.useEDT()) { + def = AWTEDTUtil.getSingleton(); + if(DEBUG) { + System.err.println("AWTDisplay.createNative("+getFQName()+") Create EDTUtil: "+def.getClass().getName()); + } + } else { + def = null; + } + return def; + } + + protected void dispatchMessagesNative() { /* nop */ } +} + diff --git a/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java new file mode 100644 index 000000000..6b1283a00 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2008 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. + * + */ + +package jogamp.newt.driver.awt; + +import java.awt.DisplayMode; + +import jogamp.newt.ScreenImpl; +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.Point; + +import com.jogamp.nativewindow.awt.AWTGraphicsDevice; +import com.jogamp.nativewindow.awt.AWTGraphicsScreen; + +public class ScreenDriver extends ScreenImpl { + public ScreenDriver() { + } + + protected void createNativeImpl() { + aScreen = new AWTGraphicsScreen((AWTGraphicsDevice)display.getGraphicsDevice()); + } + + protected void setAWTGraphicsScreen(AWTGraphicsScreen s) { + aScreen = s; + } + + /** + * Used by AWTWindow .. + */ + @Override + protected void updateVirtualScreenOriginAndSize() { + super.updateVirtualScreenOriginAndSize(); + } + + protected void closeNativeImpl() { } + + protected int validateScreenIndex(int idx) { + return idx; // pass through ... + } + + protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { + final DisplayMode mode = ((AWTGraphicsDevice)getDisplay().getGraphicsDevice()).getGraphicsDevice().getDisplayMode(); + if(null != mode) { + virtualOrigin.setX(0); + virtualOrigin.setY(0); + virtualSize.setWidth(mode.getWidth()); + virtualSize.setHeight(mode.getHeight()); + } + } + +} diff --git a/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java new file mode 100644 index 000000000..1723ffee5 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2008 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. + * + */ + +package jogamp.newt.driver.awt; + +import java.awt.BorderLayout; +import java.awt.Container; +import java.awt.Frame; +import java.awt.Insets; + +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.util.Point; + +import jogamp.newt.WindowImpl; + +import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration; +import com.jogamp.nativewindow.awt.AWTGraphicsDevice; +import com.jogamp.nativewindow.awt.AWTGraphicsScreen; +import com.jogamp.newt.event.awt.AWTKeyAdapter; +import com.jogamp.newt.event.awt.AWTMouseAdapter; +import com.jogamp.newt.event.awt.AWTWindowAdapter; + +/** An implementation of the Newt Window class built using the + AWT. This is provided for convenience of porting to platforms + supporting Java SE. */ + +public class WindowDriver extends WindowImpl { + + public WindowDriver() { + this(null); + } + + public static Class[] getCustomConstructorArgumentTypes() { + return new Class[] { Container.class } ; + } + + public WindowDriver(Container container) { + super(); + this.container = container; + if(container instanceof Frame) { + frame = (Frame) container; + } + } + + private boolean owningFrame; + private Container container = null; + private Frame frame = null; // same instance as container, just for impl. convenience + private AWTCanvas canvas; + + protected void requestFocusImpl(boolean reparented) { + container.requestFocus(); + } + + @Override + protected void setTitleImpl(final String title) { + if (frame != null) { + frame.setTitle(title); + } + } + + protected void createNativeImpl() { + if(0!=getParentWindowHandle()) { + throw new RuntimeException("Window parenting not supported in AWT, use AWTWindow(Frame) cstr for wrapping instead"); + } + + if(null==container) { + frame = new Frame(); + container = frame; + owningFrame=true; + } else { + owningFrame=false; + defineSize(container.getWidth(), container.getHeight()); + definePosition(container.getX(), container.getY()); + } + if(null!=frame) { + frame.setTitle(getTitle()); + } + container.setLayout(new BorderLayout()); + canvas = new AWTCanvas(capsRequested, WindowDriver.this.capabilitiesChooser); + + addWindowListener(new LocalWindowListener()); + + new AWTMouseAdapter(this).addTo(canvas); // fwd all AWT Mouse events to here + new AWTKeyAdapter(this).addTo(canvas); // fwd all AWT Key events to here + + // canvas.addComponentListener(listener); + container.add(canvas, BorderLayout.CENTER); + container.setSize(getWidth(), getHeight()); + container.setLocation(getX(), getY()); + new AWTWindowAdapter(this).addTo(container); // fwd all AWT Window events to here + + reconfigureWindowImpl(getX(), getY(), getWidth(), getHeight(), getReconfigureFlags(FLAG_CHANGE_VISIBILITY | FLAG_CHANGE_DECORATION, true)); + // throws exception if failed .. + + setWindowHandle(1); // just a marker .. + } + + protected void closeNativeImpl() { + setWindowHandle(0); // just a marker .. + if(null!=container) { + container.setVisible(false); + container.remove(canvas); + container.setEnabled(false); + canvas.setEnabled(false); + } + if(owningFrame && null!=frame) { + frame.dispose(); + owningFrame=false; + frame = null; + } + } + + @Override + public boolean hasDeviceChanged() { + boolean res = canvas.hasDeviceChanged(); + if(res) { + final AWTGraphicsConfiguration cfg = canvas.getAWTGraphicsConfiguration(); + if (null == cfg) { + throw new NativeWindowException("Error Device change null GraphicsConfiguration: "+this); + } + setGraphicsConfiguration(cfg); + + // propagate new info .. + ((ScreenDriver)getScreen()).setAWTGraphicsScreen((AWTGraphicsScreen)cfg.getScreen()); + ((DisplayDriver)getScreen().getDisplay()).setAWTGraphicsDevice((AWTGraphicsDevice)cfg.getScreen().getDevice()); + + ((ScreenDriver)getScreen()).updateVirtualScreenOriginAndSize(); + } + return res; + } + + protected void updateInsetsImpl(javax.media.nativewindow.util.Insets insets) { + Insets contInsets = container.getInsets(); + insets.setLeftWidth(contInsets.left); + insets.setRightWidth(contInsets.right); + insets.setTopHeight(contInsets.top); + insets.setBottomHeight(contInsets.bottom); + } + + protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + if(0 != ( FLAG_CHANGE_DECORATION & flags) && null!=frame) { + if(!container.isDisplayable()) { + frame.setUndecorated(isUndecorated()); + } else { + if(DEBUG_IMPLEMENTATION) { + System.err.println("AWTWindow can't undecorate already created frame"); + } + } + } + + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { + container.setVisible(0 != ( FLAG_IS_VISIBLE & flags)); + } + + container.setLocation(x, y); + Insets insets = container.getInsets(); + container.setSize(width + insets.left + insets.right, + height + insets.top + insets.bottom); + + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { + if( 0 != ( FLAG_IS_VISIBLE & flags ) ) { + if( !hasDeviceChanged() ) { + // oops ?? + final AWTGraphicsConfiguration cfg = canvas.getAWTGraphicsConfiguration(); + if(null == cfg) { + throw new NativeWindowException("Error: !hasDeviceChanged && null == GraphicsConfiguration: "+this); + } + setGraphicsConfiguration(cfg); + } + } + visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); + } + + return true; + } + + protected Point getLocationOnScreenImpl(int x, int y) { + java.awt.Point ap = canvas.getLocationOnScreen(); + ap.translate(x, y); + return new Point((int)(ap.getX()+0.5),(int)(ap.getY()+0.5)); + } + + @Override + public Object getWrappedWindow() { + return canvas; + } + + class LocalWindowListener extends com.jogamp.newt.event.WindowAdapter { + @Override + public void windowMoved(com.jogamp.newt.event.WindowEvent e) { + if(null!=container) { + definePosition(container.getX(), container.getY()); + } + } + @Override + public void windowResized(com.jogamp.newt.event.WindowEvent e) { + if(null!=canvas) { + defineSize(canvas.getWidth(), canvas.getHeight()); + } + } + } +} diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/Display.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/Display.java deleted file mode 100644 index f08890da6..000000000 --- a/src/newt/classes/jogamp/newt/driver/bcm/egl/Display.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright (c) 2012 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. - * - */ - -package jogamp.newt.driver.bcm.egl; - -import javax.media.nativewindow.AbstractGraphicsDevice; -import javax.media.nativewindow.NativeWindowException; - -import jogamp.newt.NEWTJNILibLoader; -import jogamp.opengl.egl.EGL; - -import com.jogamp.nativewindow.egl.EGLGraphicsDevice; - -public class Display extends jogamp.newt.DisplayImpl { - - static { - NEWTJNILibLoader.loadNEWT(); - - if (!Window.initIDs()) { - throw new NativeWindowException("Failed to initialize BCEGL Window jmethodIDs"); - } - } - - public static void initSingleton() { - // just exist to ensure static init has been run - } - - - public Display() { - } - - protected void createNativeImpl() { - final long handle = CreateDisplay(Screen.fixedWidth, Screen.fixedHeight); - if (handle == EGL.EGL_NO_DISPLAY) { - throw new NativeWindowException("BC EGL CreateDisplay failed"); - } - aDevice = new EGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, handle, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT, null); - } - - protected void closeNativeImpl() { - if (aDevice.getHandle() != EGL.EGL_NO_DISPLAY) { - DestroyDisplay(aDevice.getHandle()); - } - } - - protected void dispatchMessagesNative() { - // n/a .. DispatchMessages(); - } - - private native long CreateDisplay(int width, int height); - private native void DestroyDisplay(long dpy); - private native void DispatchMessages(); -} - diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java new file mode 100644 index 000000000..65ca63eec --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2012 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. + * + */ + +package jogamp.newt.driver.bcm.egl; + +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeWindowException; + +import jogamp.newt.NEWTJNILibLoader; +import jogamp.opengl.egl.EGL; + +import com.jogamp.nativewindow.egl.EGLGraphicsDevice; + +public class DisplayDriver extends jogamp.newt.DisplayImpl { + + static { + NEWTJNILibLoader.loadNEWT(); + + if (!WindowDriver.initIDs()) { + throw new NativeWindowException("Failed to initialize BCEGL Window jmethodIDs"); + } + } + + public static void initSingleton() { + // just exist to ensure static init has been run + } + + + public DisplayDriver() { + } + + protected void createNativeImpl() { + final long handle = CreateDisplay(ScreenDriver.fixedWidth, ScreenDriver.fixedHeight); + if (handle == EGL.EGL_NO_DISPLAY) { + throw new NativeWindowException("BC EGL CreateDisplay failed"); + } + aDevice = new EGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, handle, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT, null); + } + + protected void closeNativeImpl() { + if (aDevice.getHandle() != EGL.EGL_NO_DISPLAY) { + DestroyDisplay(aDevice.getHandle()); + } + } + + protected void dispatchMessagesNative() { + // n/a .. DispatchMessages(); + } + + private native long CreateDisplay(int width, int height); + private native void DestroyDisplay(long dpy); + private native void DispatchMessages(); +} + diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/Screen.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/Screen.java deleted file mode 100644 index 909444d24..000000000 --- a/src/newt/classes/jogamp/newt/driver/bcm/egl/Screen.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright (c) 2012 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. - * - */ - -package jogamp.newt.driver.bcm.egl; - -import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; - -public class Screen extends jogamp.newt.ScreenImpl { - - static { - Display.initSingleton(); - } - - - public Screen() { - } - - protected void createNativeImpl() { - aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); - } - - protected void closeNativeImpl() { } - - protected int validateScreenIndex(int idx) { - return 0; // only one screen available - } - - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(fixedWidth); // FIXME - virtualSize.setHeight(fixedHeight); // FIXME - } - - //---------------------------------------------------------------------- - // Internals only - // - - static final int fixedWidth = 1920; // FIXME - static final int fixedHeight = 1080; // FIXME -} - diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java new file mode 100644 index 000000000..deb2a534b --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2012 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. + * + */ + +package jogamp.newt.driver.bcm.egl; + +import javax.media.nativewindow.DefaultGraphicsScreen; +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.Point; + +public class ScreenDriver extends jogamp.newt.ScreenImpl { + + static { + DisplayDriver.initSingleton(); + } + + + public ScreenDriver() { + } + + protected void createNativeImpl() { + aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); + } + + protected void closeNativeImpl() { } + + protected int validateScreenIndex(int idx) { + return 0; // only one screen available + } + + protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { + virtualOrigin.setX(0); + virtualOrigin.setY(0); + virtualSize.setWidth(fixedWidth); // FIXME + virtualSize.setHeight(fixedHeight); // FIXME + } + + //---------------------------------------------------------------------- + // Internals only + // + + static final int fixedWidth = 1920; // FIXME + static final int fixedHeight = 1080; // FIXME +} + diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/Window.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/Window.java deleted file mode 100644 index 87170e4ab..000000000 --- a/src/newt/classes/jogamp/newt/driver/bcm/egl/Window.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright (c) 2012 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. - * - */ - -package jogamp.newt.driver.bcm.egl; - -import javax.media.nativewindow.AbstractGraphicsConfiguration; -import javax.media.nativewindow.GraphicsConfigurationFactory; -import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.VisualIDHolder; -import javax.media.nativewindow.util.Insets; -import javax.media.nativewindow.util.Point; -import javax.media.opengl.GLCapabilitiesImmutable; - -import jogamp.opengl.egl.EGLGraphicsConfiguration; - -public class Window extends jogamp.newt.WindowImpl { - static { - Display.initSingleton(); - } - - public Window() { - } - - protected void createNativeImpl() { - if(0!=getParentWindowHandle()) { - throw new RuntimeException("Window parenting not supported (yet)"); - } - // query a good configuration, however chose the final one by the native queried egl-cfg-id - // after creation at {@link #windowCreated(int, int, int)}. - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); - if (null == cfg) { - throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); - } - setGraphicsConfiguration(cfg); - setSizeImpl(getScreen().getWidth(), getScreen().getHeight()); - - setWindowHandle(realizeWindow(true, getWidth(), getHeight())); - if (0 == getWindowHandle()) { - throw new NativeWindowException("Error native Window Handle is null"); - } - } - - protected void closeNativeImpl() { - if(0!=windowHandleClose) { - CloseWindow(getDisplayHandle(), windowHandleClose); - } - } - - protected void requestFocusImpl(boolean reparented) { } - - protected void setSizeImpl(int width, int height) { - if(0!=getWindowHandle()) { - // n/a in BroadcomEGL - System.err.println("BCEGL Window.setSizeImpl n/a in BroadcomEGL with realized window"); - } else { - defineSize(width, height); - } - } - - protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { - if(0!=getWindowHandle()) { - if(0 != ( FLAG_CHANGE_FULLSCREEN & flags)) { - if( 0 != ( FLAG_IS_FULLSCREEN & flags) ) { - // n/a in BroadcomEGL - System.err.println("setFullscreen n/a in BroadcomEGL"); - return false; - } - } - } - if(width>0 || height>0) { - if(0!=getWindowHandle()) { - // n/a in BroadcomEGL - System.err.println("BCEGL Window.setSizeImpl n/a in BroadcomEGL with realized window"); - } else { - defineSize((width>0)?width:getWidth(), (height>0)?height:getHeight()); - } - } - if(x>=0 || y>=0) { - System.err.println("BCEGL Window.setPositionImpl n/a in BroadcomEGL"); - } - - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); - } - return true; - } - - protected Point getLocationOnScreenImpl(int x, int y) { - return new Point(x,y); - } - - protected void updateInsetsImpl(Insets insets) { - // nop .. - } - - @Override - public boolean surfaceSwap() { - SwapWindow(getDisplayHandle(), getWindowHandle()); - return true; - } - - //---------------------------------------------------------------------- - // Internals only - // - - protected static native boolean initIDs(); - private native long CreateWindow(long eglDisplayHandle, boolean chromaKey, int width, int height); - private native void CloseWindow(long eglDisplayHandle, long eglWindowHandle); - private native void SwapWindow(long eglDisplayHandle, long eglWindowHandle); - - - private long realizeWindow(boolean chromaKey, int width, int height) { - if(DEBUG_IMPLEMENTATION) { - System.err.println("BCEGL Window.realizeWindow() with: chroma "+chromaKey+", "+width+"x"+height+", "+getGraphicsConfiguration()); - } - long handle = CreateWindow(getDisplayHandle(), chromaKey, width, height); - if (0 == handle) { - throw new NativeWindowException("Error native Window Handle is null"); - } - windowHandleClose = handle; - return handle; - } - - private void windowCreated(int cfgID, int width, int height) { - defineSize(width, height); - GLCapabilitiesImmutable capsReq = (GLCapabilitiesImmutable) getGraphicsConfiguration().getRequestedCapabilities(); - final AbstractGraphicsConfiguration cfg = EGLGraphicsConfiguration.create(capsReq, getScreen().getGraphicsScreen(), cfgID); - if (null == cfg) { - throw new NativeWindowException("Error creating EGLGraphicsConfiguration from id: "+cfgID+", "+this); - } - setGraphicsConfiguration(cfg); - if(DEBUG_IMPLEMENTATION) { - System.err.println("BCEGL Window.windowCreated(): "+toHexString(cfgID)+", "+width+"x"+height+", "+cfg); - } - } - - private long windowHandleClose; -} diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/WindowDriver.java new file mode 100644 index 000000000..49d3d98ba --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/bcm/egl/WindowDriver.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2012 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. + * + */ + +package jogamp.newt.driver.bcm.egl; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.GraphicsConfigurationFactory; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.VisualIDHolder; +import javax.media.nativewindow.util.Insets; +import javax.media.nativewindow.util.Point; +import javax.media.opengl.GLCapabilitiesImmutable; + +import jogamp.opengl.egl.EGLGraphicsConfiguration; + +public class WindowDriver extends jogamp.newt.WindowImpl { + static { + DisplayDriver.initSingleton(); + } + + public WindowDriver() { + } + + protected void createNativeImpl() { + if(0!=getParentWindowHandle()) { + throw new RuntimeException("Window parenting not supported (yet)"); + } + // query a good configuration, however chose the final one by the native queried egl-cfg-id + // after creation at {@link #windowCreated(int, int, int)}. + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); + if (null == cfg) { + throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); + } + setGraphicsConfiguration(cfg); + setSizeImpl(getScreen().getWidth(), getScreen().getHeight()); + + setWindowHandle(realizeWindow(true, getWidth(), getHeight())); + if (0 == getWindowHandle()) { + throw new NativeWindowException("Error native Window Handle is null"); + } + } + + protected void closeNativeImpl() { + if(0!=windowHandleClose) { + CloseWindow(getDisplayHandle(), windowHandleClose); + } + } + + protected void requestFocusImpl(boolean reparented) { } + + protected void setSizeImpl(int width, int height) { + if(0!=getWindowHandle()) { + // n/a in BroadcomEGL + System.err.println("BCEGL Window.setSizeImpl n/a in BroadcomEGL with realized window"); + } else { + defineSize(width, height); + } + } + + protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + if(0!=getWindowHandle()) { + if(0 != ( FLAG_CHANGE_FULLSCREEN & flags)) { + if( 0 != ( FLAG_IS_FULLSCREEN & flags) ) { + // n/a in BroadcomEGL + System.err.println("setFullscreen n/a in BroadcomEGL"); + return false; + } + } + } + if(width>0 || height>0) { + if(0!=getWindowHandle()) { + // n/a in BroadcomEGL + System.err.println("BCEGL Window.setSizeImpl n/a in BroadcomEGL with realized window"); + } else { + defineSize((width>0)?width:getWidth(), (height>0)?height:getHeight()); + } + } + if(x>=0 || y>=0) { + System.err.println("BCEGL Window.setPositionImpl n/a in BroadcomEGL"); + } + + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { + visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); + } + return true; + } + + protected Point getLocationOnScreenImpl(int x, int y) { + return new Point(x,y); + } + + protected void updateInsetsImpl(Insets insets) { + // nop .. + } + + @Override + public boolean surfaceSwap() { + SwapWindow(getDisplayHandle(), getWindowHandle()); + return true; + } + + //---------------------------------------------------------------------- + // Internals only + // + + protected static native boolean initIDs(); + private native long CreateWindow(long eglDisplayHandle, boolean chromaKey, int width, int height); + private native void CloseWindow(long eglDisplayHandle, long eglWindowHandle); + private native void SwapWindow(long eglDisplayHandle, long eglWindowHandle); + + + private long realizeWindow(boolean chromaKey, int width, int height) { + if(DEBUG_IMPLEMENTATION) { + System.err.println("BCEGL Window.realizeWindow() with: chroma "+chromaKey+", "+width+"x"+height+", "+getGraphicsConfiguration()); + } + long handle = CreateWindow(getDisplayHandle(), chromaKey, width, height); + if (0 == handle) { + throw new NativeWindowException("Error native Window Handle is null"); + } + windowHandleClose = handle; + return handle; + } + + private void windowCreated(int cfgID, int width, int height) { + defineSize(width, height); + GLCapabilitiesImmutable capsReq = (GLCapabilitiesImmutable) getGraphicsConfiguration().getRequestedCapabilities(); + final AbstractGraphicsConfiguration cfg = EGLGraphicsConfiguration.create(capsReq, getScreen().getGraphicsScreen(), cfgID); + if (null == cfg) { + throw new NativeWindowException("Error creating EGLGraphicsConfiguration from id: "+cfgID+", "+this); + } + setGraphicsConfiguration(cfg); + if(DEBUG_IMPLEMENTATION) { + System.err.println("BCEGL Window.windowCreated(): "+toHexString(cfgID)+", "+width+"x"+height+", "+cfg); + } + } + + private long windowHandleClose; +} diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Display.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Display.java deleted file mode 100644 index 62af02abb..000000000 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Display.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright 2012 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package jogamp.newt.driver.bcm.vc.iv; - -import javax.media.nativewindow.AbstractGraphicsDevice; -import javax.media.nativewindow.NativeWindowException; - -import jogamp.newt.DisplayImpl; -import jogamp.newt.NEWTJNILibLoader; -import jogamp.opengl.egl.EGL; -import jogamp.opengl.egl.EGLDisplayUtil; - -public class Display extends DisplayImpl { - static { - NEWTJNILibLoader.loadNEWT(); - - if (!Display.initIDs()) { - throw new NativeWindowException("Failed to initialize bcm.vc.iv Display jmethodIDs"); - } - if (!Screen.initIDs()) { - throw new NativeWindowException("Failed to initialize bcm.vc.iv Screen jmethodIDs"); - } - if (!Window.initIDs()) { - throw new NativeWindowException("Failed to initialize bcm.vc.iv Window jmethodIDs"); - } - } - - public static void initSingleton() { - // just exist to ensure static init has been run - } - - - public Display() { - } - - protected void createNativeImpl() { - // FIXME: map name to EGL_*_DISPLAY - aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); - } - - protected void closeNativeImpl() { - aDevice.close(); - } - - protected void dispatchMessagesNative() { - DispatchMessages(); - } - - protected static native boolean initIDs(); - private native void DispatchMessages(); -} - diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java new file mode 100644 index 000000000..08c5c573c --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java @@ -0,0 +1,78 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.newt.driver.bcm.vc.iv; + +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeWindowException; + +import jogamp.newt.DisplayImpl; +import jogamp.newt.NEWTJNILibLoader; +import jogamp.opengl.egl.EGL; +import jogamp.opengl.egl.EGLDisplayUtil; + +public class DisplayDriver extends DisplayImpl { + static { + NEWTJNILibLoader.loadNEWT(); + + if (!DisplayDriver.initIDs()) { + throw new NativeWindowException("Failed to initialize bcm.vc.iv Display jmethodIDs"); + } + if (!ScreenDriver.initIDs()) { + throw new NativeWindowException("Failed to initialize bcm.vc.iv Screen jmethodIDs"); + } + if (!WindowDriver.initIDs()) { + throw new NativeWindowException("Failed to initialize bcm.vc.iv Window jmethodIDs"); + } + } + + public static void initSingleton() { + // just exist to ensure static init has been run + } + + + public DisplayDriver() { + } + + protected void createNativeImpl() { + // FIXME: map name to EGL_*_DISPLAY + aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + } + + protected void closeNativeImpl() { + aDevice.close(); + } + + protected void dispatchMessagesNative() { + DispatchMessages(); + } + + protected static native boolean initIDs(); + private native void DispatchMessages(); +} + diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Screen.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Screen.java deleted file mode 100644 index 484d4bf81..000000000 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Screen.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright 2012 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package jogamp.newt.driver.bcm.vc.iv; - -import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; - -import jogamp.newt.ScreenImpl; - -public class Screen extends ScreenImpl { - static { - Display.initSingleton(); - } - - public Screen() { - } - - protected void createNativeImpl() { - aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); - initNative(); - } - - protected void closeNativeImpl() { } - - protected int validateScreenIndex(int idx) { - return 0; // only one screen available - } - - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(cachedWidth); - virtualSize.setHeight(cachedHeight); - } - - protected void setScreenSize(int width, int height) { - cachedWidth = width; - cachedHeight = height; - } - - private static int cachedWidth = 0; - private static int cachedHeight = 0; - - protected static native boolean initIDs(); - protected native void initNative(); -} diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java new file mode 100644 index 000000000..787d1a1b4 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java @@ -0,0 +1,73 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.newt.driver.bcm.vc.iv; + +import javax.media.nativewindow.DefaultGraphicsScreen; +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.Point; + +import jogamp.newt.ScreenImpl; + +public class ScreenDriver extends ScreenImpl { + static { + DisplayDriver.initSingleton(); + } + + public ScreenDriver() { + } + + protected void createNativeImpl() { + aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); + initNative(); + } + + protected void closeNativeImpl() { } + + protected int validateScreenIndex(int idx) { + return 0; // only one screen available + } + + protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { + virtualOrigin.setX(0); + virtualOrigin.setY(0); + virtualSize.setWidth(cachedWidth); + virtualSize.setHeight(cachedHeight); + } + + protected void setScreenSize(int width, int height) { + cachedWidth = width; + cachedHeight = height; + } + + private static int cachedWidth = 0; + private static int cachedHeight = 0; + + protected static native boolean initIDs(); + protected native void initNative(); +} diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Window.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Window.java deleted file mode 100644 index 3d00949de..000000000 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/Window.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright 2012 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package jogamp.newt.driver.bcm.vc.iv; - -import javax.media.nativewindow.AbstractGraphicsConfiguration; -import javax.media.nativewindow.GraphicsConfigurationFactory; -import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.VisualIDHolder; -import javax.media.nativewindow.util.Insets; -import javax.media.nativewindow.util.Point; - -import jogamp.newt.WindowImpl; -import jogamp.newt.driver.linux.LinuxMouseTracker; - -public class Window extends WindowImpl { - private static final String WINDOW_CLASS_NAME = "NewtWindow"; - - static { - Display.initSingleton(); - } - - public Window() { - } - - protected void createNativeImpl() { - if(0!=getParentWindowHandle()) { - throw new RuntimeException("Window parenting not supported (yet)"); - } - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); - if (null == cfg) { - throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); - } - setGraphicsConfiguration(cfg); - - nativeWindowHandle = CreateWindow(getWidth(), getHeight()); - if (nativeWindowHandle == 0) { - throw new NativeWindowException("Error creating egl window: "+cfg); - } - setVisible0(nativeWindowHandle, false); - setWindowHandle(nativeWindowHandle); - if (0 == getWindowHandle()) { - throw new NativeWindowException("Error native Window Handle is null"); - } - windowHandleClose = nativeWindowHandle; - addWindowListener(LinuxMouseTracker.getSingleton()); - focusChanged(false, true); - } - - protected void closeNativeImpl() { - removeWindowListener(LinuxMouseTracker.getSingleton()); - - if(0!=windowHandleClose) { - CloseWindow(windowHandleClose, windowUserData); - windowUserData=0; - } - } - - protected void requestFocusImpl(boolean reparented) { - focusChanged(false, true); - } - - protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - setVisible0(nativeWindowHandle, 0 != ( FLAG_IS_VISIBLE & flags)); - visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); - } - - if(0!=nativeWindowHandle) { - if(0 != ( FLAG_CHANGE_FULLSCREEN & flags)) { - final boolean fs = 0 != ( FLAG_IS_FULLSCREEN & flags) ; - setFullScreen0(nativeWindowHandle, fs); - if(fs) { - return true; - } - } - // int _x=(x>=0)?x:this.x; - // int _y=(x>=0)?y:this.y; - width=(width>0)?width:getWidth(); - height=(height>0)?height:getHeight(); - if(width>0 || height>0) { - setSize0(nativeWindowHandle, width, height); - } - if(x>=0 || y>=0) { - System.err.println("setPosition n/a in KD"); - } - } - - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); - } - - return true; - } - - protected Point getLocationOnScreenImpl(int x, int y) { - return new Point(x,y); - } - - protected void updateInsetsImpl(Insets insets) { - // nop .. - } - - //---------------------------------------------------------------------- - // Internals only - // - - protected static native boolean initIDs(); - private native long CreateWindow(int width, int height); - private native long RealizeWindow(long eglWindowHandle); - private native int CloseWindow(long eglWindowHandle, long userData); - private native void setVisible0(long eglWindowHandle, boolean visible); - private native void setSize0(long eglWindowHandle, int width, int height); - private native void setFullScreen0(long eglWindowHandle, boolean fullscreen); - - private void windowCreated(long userData) { - windowUserData=userData; - } - - private long nativeWindowHandle; - private long windowHandleClose; - private long windowUserData; -} diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java new file mode 100644 index 000000000..6d4f36964 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java @@ -0,0 +1,149 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.newt.driver.bcm.vc.iv; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.GraphicsConfigurationFactory; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.VisualIDHolder; +import javax.media.nativewindow.util.Insets; +import javax.media.nativewindow.util.Point; + +import jogamp.newt.WindowImpl; +import jogamp.newt.driver.linux.LinuxMouseTracker; + +public class WindowDriver extends WindowImpl { + private static final String WINDOW_CLASS_NAME = "NewtWindow"; + + static { + DisplayDriver.initSingleton(); + } + + public WindowDriver() { + } + + protected void createNativeImpl() { + if(0!=getParentWindowHandle()) { + throw new RuntimeException("Window parenting not supported (yet)"); + } + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); + if (null == cfg) { + throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); + } + setGraphicsConfiguration(cfg); + + nativeWindowHandle = CreateWindow(getWidth(), getHeight()); + if (nativeWindowHandle == 0) { + throw new NativeWindowException("Error creating egl window: "+cfg); + } + setVisible0(nativeWindowHandle, false); + setWindowHandle(nativeWindowHandle); + if (0 == getWindowHandle()) { + throw new NativeWindowException("Error native Window Handle is null"); + } + windowHandleClose = nativeWindowHandle; + addWindowListener(LinuxMouseTracker.getSingleton()); + focusChanged(false, true); + } + + protected void closeNativeImpl() { + removeWindowListener(LinuxMouseTracker.getSingleton()); + + if(0!=windowHandleClose) { + CloseWindow(windowHandleClose, windowUserData); + windowUserData=0; + } + } + + protected void requestFocusImpl(boolean reparented) { + focusChanged(false, true); + } + + protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { + setVisible0(nativeWindowHandle, 0 != ( FLAG_IS_VISIBLE & flags)); + visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); + } + + if(0!=nativeWindowHandle) { + if(0 != ( FLAG_CHANGE_FULLSCREEN & flags)) { + final boolean fs = 0 != ( FLAG_IS_FULLSCREEN & flags) ; + setFullScreen0(nativeWindowHandle, fs); + if(fs) { + return true; + } + } + // int _x=(x>=0)?x:this.x; + // int _y=(x>=0)?y:this.y; + width=(width>0)?width:getWidth(); + height=(height>0)?height:getHeight(); + if(width>0 || height>0) { + setSize0(nativeWindowHandle, width, height); + } + if(x>=0 || y>=0) { + System.err.println("setPosition n/a in KD"); + } + } + + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { + visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); + } + + return true; + } + + protected Point getLocationOnScreenImpl(int x, int y) { + return new Point(x,y); + } + + protected void updateInsetsImpl(Insets insets) { + // nop .. + } + + //---------------------------------------------------------------------- + // Internals only + // + + protected static native boolean initIDs(); + private native long CreateWindow(int width, int height); + private native long RealizeWindow(long eglWindowHandle); + private native int CloseWindow(long eglWindowHandle, long userData); + private native void setVisible0(long eglWindowHandle, boolean visible); + private native void setSize0(long eglWindowHandle, int width, int height); + private native void setFullScreen0(long eglWindowHandle, boolean fullscreen); + + private void windowCreated(long userData) { + windowUserData=userData; + } + + private long nativeWindowHandle; + private long windowHandleClose; + private long windowUserData; +} diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/Display.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/Display.java deleted file mode 100644 index 20e151eb3..000000000 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/Display.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.intel.gdl; - -import jogamp.newt.*; -import javax.media.nativewindow.*; - -public class Display extends jogamp.newt.DisplayImpl { - static int initCounter = 0; - - static { - NEWTJNILibLoader.loadNEWT(); - - if (!Screen.initIDs()) { - throw new NativeWindowException("Failed to initialize GDL Screen jmethodIDs"); - } - if (!Window.initIDs()) { - throw new NativeWindowException("Failed to initialize GDL Window jmethodIDs"); - } - } - - public static void initSingleton() { - // just exist to ensure static init has been run - } - - - public Display() { - } - - protected void createNativeImpl() { - synchronized(Display.class) { - if(0==initCounter) { - displayHandle = CreateDisplay(); - if(0==displayHandle) { - throw new NativeWindowException("Couldn't initialize GDL Display"); - } - } - initCounter++; - } - aDevice = new DefaultGraphicsDevice(NativeWindowFactory.TYPE_DEFAULT, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT, displayHandle); - } - - protected void closeNativeImpl() { - if(0==displayHandle) { - throw new NativeWindowException("displayHandle null; initCnt "+initCounter); - } - synchronized(Display.class) { - if(initCounter>0) { - initCounter--; - if(0==initCounter) { - DestroyDisplay(displayHandle); - } - } - } - } - - protected void dispatchMessagesNative() { - if(0!=displayHandle) { - DispatchMessages(displayHandle, focusedWindow); - } - } - - protected void setFocus(Window focus) { - focusedWindow = focus; - } - - private long displayHandle = 0; - private Window focusedWindow = null; - private native long CreateDisplay(); - private native void DestroyDisplay(long displayHandle); - private native void DispatchMessages(long displayHandle, Window focusedWindow); -} - diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java new file mode 100644 index 000000000..97c384d33 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2012 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. + * + */ + +package jogamp.newt.driver.intel.gdl; + +import jogamp.newt.*; +import javax.media.nativewindow.*; + +public class DisplayDriver extends jogamp.newt.DisplayImpl { + static int initCounter = 0; + + static { + NEWTJNILibLoader.loadNEWT(); + + if (!ScreenDriver.initIDs()) { + throw new NativeWindowException("Failed to initialize GDL Screen jmethodIDs"); + } + if (!WindowDriver.initIDs()) { + throw new NativeWindowException("Failed to initialize GDL Window jmethodIDs"); + } + } + + public static void initSingleton() { + // just exist to ensure static init has been run + } + + + public DisplayDriver() { + } + + protected void createNativeImpl() { + synchronized(DisplayDriver.class) { + if(0==initCounter) { + displayHandle = CreateDisplay(); + if(0==displayHandle) { + throw new NativeWindowException("Couldn't initialize GDL Display"); + } + } + initCounter++; + } + aDevice = new DefaultGraphicsDevice(NativeWindowFactory.TYPE_DEFAULT, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT, displayHandle); + } + + protected void closeNativeImpl() { + if(0==displayHandle) { + throw new NativeWindowException("displayHandle null; initCnt "+initCounter); + } + synchronized(DisplayDriver.class) { + if(initCounter>0) { + initCounter--; + if(0==initCounter) { + DestroyDisplay(displayHandle); + } + } + } + } + + protected void dispatchMessagesNative() { + if(0!=displayHandle) { + DispatchMessages(displayHandle, focusedWindow); + } + } + + protected void setFocus(WindowDriver focus) { + focusedWindow = focus; + } + + private long displayHandle = 0; + private WindowDriver focusedWindow = null; + private native long CreateDisplay(); + private native void DestroyDisplay(long displayHandle); + private native void DispatchMessages(long displayHandle, WindowDriver focusedWindow); +} + diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/Screen.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/Screen.java deleted file mode 100644 index 66ad1c691..000000000 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/Screen.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.intel.gdl; - -import javax.media.nativewindow.AbstractGraphicsDevice; -import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; - -public class Screen extends jogamp.newt.ScreenImpl { - - static { - Display.initSingleton(); - } - - public Screen() { - } - - protected void createNativeImpl() { - AbstractGraphicsDevice adevice = getDisplay().getGraphicsDevice(); - GetScreenInfo(adevice.getHandle(), screen_idx); - aScreen = new DefaultGraphicsScreen(adevice, screen_idx); - } - - protected void closeNativeImpl() { } - - protected int validateScreenIndex(int idx) { - return 0; // only one screen available - } - - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(cachedWidth); - virtualSize.setHeight(cachedHeight); - } - - //---------------------------------------------------------------------- - // Internals only - // - - protected static native boolean initIDs(); - private native void GetScreenInfo(long displayHandle, int screen_idx); - - // called by GetScreenInfo() .. - private void screenCreated(int width, int height) { - cachedWidth = width; - cachedHeight = height; - } - - private static int cachedWidth = 0; - private static int cachedHeight = 0; -} - diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java new file mode 100644 index 000000000..8eed14dde --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2012 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. + * + */ + +package jogamp.newt.driver.intel.gdl; + +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.DefaultGraphicsScreen; +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.Point; + +public class ScreenDriver extends jogamp.newt.ScreenImpl { + + static { + DisplayDriver.initSingleton(); + } + + public ScreenDriver() { + } + + protected void createNativeImpl() { + AbstractGraphicsDevice adevice = getDisplay().getGraphicsDevice(); + GetScreenInfo(adevice.getHandle(), screen_idx); + aScreen = new DefaultGraphicsScreen(adevice, screen_idx); + } + + protected void closeNativeImpl() { } + + protected int validateScreenIndex(int idx) { + return 0; // only one screen available + } + + protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { + virtualOrigin.setX(0); + virtualOrigin.setY(0); + virtualSize.setWidth(cachedWidth); + virtualSize.setHeight(cachedHeight); + } + + //---------------------------------------------------------------------- + // Internals only + // + + protected static native boolean initIDs(); + private native void GetScreenInfo(long displayHandle, int screen_idx); + + // called by GetScreenInfo() .. + private void screenCreated(int width, int height) { + cachedWidth = width; + cachedHeight = height; + } + + private static int cachedWidth = 0; + private static int cachedHeight = 0; +} + diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java deleted file mode 100644 index d5c75abd4..000000000 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.intel.gdl; - -import javax.media.nativewindow.*; -import javax.media.nativewindow.util.Insets; -import javax.media.nativewindow.util.Point; - -public class Window extends jogamp.newt.WindowImpl { - static { - Display.initSingleton(); - } - - public Window() { - } - - static long nextWindowHandle = 1; - - protected void createNativeImpl() { - if(0!=getParentWindowHandle()) { - throw new NativeWindowException("GDL Window does not support window parenting"); - } - final AbstractGraphicsScreen aScreen = getScreen().getGraphicsScreen(); - final AbstractGraphicsDevice aDevice = getScreen().getDisplay().getGraphicsDevice(); - - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(aDevice, capsRequested).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, aScreen, VisualIDHolder.VID_UNDEFINED); - if (null == cfg) { - throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); - } - setGraphicsConfiguration(cfg); - - synchronized(Window.class) { - setWindowHandle(nextWindowHandle++); // just a marker - - surfaceHandle = CreateSurface(aDevice.getHandle(), getScreen().getWidth(), getScreen().getHeight(), getX(), getY(), getWidth(), getHeight()); - if (surfaceHandle == 0) { - throw new NativeWindowException("Error creating window"); - } - } - } - - protected void closeNativeImpl() { - if(0!=surfaceHandle) { - synchronized(Window.class) { - CloseSurface(getDisplayHandle(), surfaceHandle); - } - surfaceHandle = 0; - ((Display)getScreen().getDisplay()).setFocus(null); - } - } - - protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { - Screen screen = (Screen) getScreen(); - - if(width>screen.getWidth()) { - width=screen.getWidth(); - } - if(height>screen.getHeight()) { - height=screen.getHeight(); - } - if((x+width)>screen.getWidth()) { - x=screen.getWidth()-width; - } - if((y+height)>screen.getHeight()) { - y=screen.getHeight()-height; - } - - if(0!=surfaceHandle) { - SetBounds0(surfaceHandle, getScreen().getWidth(), getScreen().getHeight(), x, y, width, height); - } - - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - if(0 != ( FLAG_IS_VISIBLE & flags)) { - ((Display)getScreen().getDisplay()).setFocus(this); - } - visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); - } - - return true; - } - - protected void requestFocusImpl(boolean reparented) { - ((Display)getScreen().getDisplay()).setFocus(this); - } - - @Override - public final long getSurfaceHandle() { - return surfaceHandle; - } - - protected Point getLocationOnScreenImpl(int x, int y) { - return new Point(x,y); - } - - protected void updateInsetsImpl(Insets insets) { - // nop .. - } - - //---------------------------------------------------------------------- - // Internals only - // - - protected static native boolean initIDs(); - private native long CreateSurface(long displayHandle, int scrn_width, int scrn_height, int x, int y, int width, int height); - private native void CloseSurface(long displayHandle, long surfaceHandle); - private native void SetBounds0(long surfaceHandle, int scrn_width, int scrn_height, int x, int y, int width, int height); - - private void updateBounds(int x, int y, int width, int height) { - definePosition(x, y); - defineSize(width, height); - } - - private long surfaceHandle; -} diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java new file mode 100644 index 000000000..98335f192 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2012 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. + * + */ + +package jogamp.newt.driver.intel.gdl; + +import javax.media.nativewindow.*; +import javax.media.nativewindow.util.Insets; +import javax.media.nativewindow.util.Point; + +public class WindowDriver extends jogamp.newt.WindowImpl { + static { + DisplayDriver.initSingleton(); + } + + public WindowDriver() { + } + + static long nextWindowHandle = 1; + + protected void createNativeImpl() { + if(0!=getParentWindowHandle()) { + throw new NativeWindowException("GDL Window does not support window parenting"); + } + final AbstractGraphicsScreen aScreen = getScreen().getGraphicsScreen(); + final AbstractGraphicsDevice aDevice = getScreen().getDisplay().getGraphicsDevice(); + + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(aDevice, capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, aScreen, VisualIDHolder.VID_UNDEFINED); + if (null == cfg) { + throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); + } + setGraphicsConfiguration(cfg); + + synchronized(WindowDriver.class) { + setWindowHandle(nextWindowHandle++); // just a marker + + surfaceHandle = CreateSurface(aDevice.getHandle(), getScreen().getWidth(), getScreen().getHeight(), getX(), getY(), getWidth(), getHeight()); + if (surfaceHandle == 0) { + throw new NativeWindowException("Error creating window"); + } + } + } + + protected void closeNativeImpl() { + if(0!=surfaceHandle) { + synchronized(WindowDriver.class) { + CloseSurface(getDisplayHandle(), surfaceHandle); + } + surfaceHandle = 0; + ((DisplayDriver)getScreen().getDisplay()).setFocus(null); + } + } + + protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + ScreenDriver screen = (ScreenDriver) getScreen(); + + if(width>screen.getWidth()) { + width=screen.getWidth(); + } + if(height>screen.getHeight()) { + height=screen.getHeight(); + } + if((x+width)>screen.getWidth()) { + x=screen.getWidth()-width; + } + if((y+height)>screen.getHeight()) { + y=screen.getHeight()-height; + } + + if(0!=surfaceHandle) { + SetBounds0(surfaceHandle, getScreen().getWidth(), getScreen().getHeight(), x, y, width, height); + } + + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { + if(0 != ( FLAG_IS_VISIBLE & flags)) { + ((DisplayDriver)getScreen().getDisplay()).setFocus(this); + } + visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); + } + + return true; + } + + protected void requestFocusImpl(boolean reparented) { + ((DisplayDriver)getScreen().getDisplay()).setFocus(this); + } + + @Override + public final long getSurfaceHandle() { + return surfaceHandle; + } + + protected Point getLocationOnScreenImpl(int x, int y) { + return new Point(x,y); + } + + protected void updateInsetsImpl(Insets insets) { + // nop .. + } + + //---------------------------------------------------------------------- + // Internals only + // + + protected static native boolean initIDs(); + private native long CreateSurface(long displayHandle, int scrn_width, int scrn_height, int x, int y, int width, int height); + private native void CloseSurface(long displayHandle, long surfaceHandle); + private native void SetBounds0(long surfaceHandle, int scrn_width, int scrn_height, int x, int y, int width, int height); + + private void updateBounds(int x, int y, int width, int height) { + definePosition(x, y); + defineSize(width, height); + } + + private long surfaceHandle; +} diff --git a/src/newt/classes/jogamp/newt/driver/kd/Display.java b/src/newt/classes/jogamp/newt/driver/kd/Display.java deleted file mode 100644 index a58ad477a..000000000 --- a/src/newt/classes/jogamp/newt/driver/kd/Display.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright (c) 2012 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. - * - */ - -package jogamp.newt.driver.kd; - -import javax.media.nativewindow.AbstractGraphicsDevice; -import javax.media.nativewindow.NativeWindowException; - -import jogamp.newt.DisplayImpl; -import jogamp.newt.NEWTJNILibLoader; -import jogamp.opengl.egl.EGL; -import jogamp.opengl.egl.EGLDisplayUtil; - -public class Display extends DisplayImpl { - static { - NEWTJNILibLoader.loadNEWT(); - - if (!Window.initIDs()) { - throw new NativeWindowException("Failed to initialize kd.Window jmethodIDs"); - } - } - - public static void initSingleton() { - // just exist to ensure static init has been run - } - - - public Display() { - } - - protected void createNativeImpl() { - // FIXME: map name to EGL_*_DISPLAY - aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); - } - - protected void closeNativeImpl() { - aDevice.close(); - } - - protected void dispatchMessagesNative() { - DispatchMessages(); - } - - private native void DispatchMessages(); -} - diff --git a/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java new file mode 100644 index 000000000..745be5dae --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2012 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. + * + */ + +package jogamp.newt.driver.kd; + +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeWindowException; + +import jogamp.newt.DisplayImpl; +import jogamp.newt.NEWTJNILibLoader; +import jogamp.opengl.egl.EGL; +import jogamp.opengl.egl.EGLDisplayUtil; + +public class DisplayDriver extends DisplayImpl { + static { + NEWTJNILibLoader.loadNEWT(); + + if (!WindowDriver.initIDs()) { + throw new NativeWindowException("Failed to initialize kd.Window jmethodIDs"); + } + } + + public static void initSingleton() { + // just exist to ensure static init has been run + } + + + public DisplayDriver() { + } + + protected void createNativeImpl() { + // FIXME: map name to EGL_*_DISPLAY + aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + } + + protected void closeNativeImpl() { + aDevice.close(); + } + + protected void dispatchMessagesNative() { + DispatchMessages(); + } + + private native void DispatchMessages(); +} + diff --git a/src/newt/classes/jogamp/newt/driver/kd/Screen.java b/src/newt/classes/jogamp/newt/driver/kd/Screen.java deleted file mode 100644 index 53f5890b2..000000000 --- a/src/newt/classes/jogamp/newt/driver/kd/Screen.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright (c) 2012 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. - * - */ - -package jogamp.newt.driver.kd; - -import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; - -import jogamp.newt.ScreenImpl; - -public class Screen extends ScreenImpl { - static { - Display.initSingleton(); - } - - public Screen() { - } - - protected void createNativeImpl() { - aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); - } - - protected void closeNativeImpl() { } - - protected int validateScreenIndex(int idx) { - return 0; // only one screen available - } - - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(cachedWidth); - virtualSize.setHeight(cachedHeight); - } - - protected void sizeChanged(int w, int h) { - cachedWidth = w; - cachedHeight = h; - } - - private static int cachedWidth = 0; - private static int cachedHeight = 0; -} diff --git a/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java new file mode 100644 index 000000000..656bcf5c9 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2012 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. + * + */ + +package jogamp.newt.driver.kd; + +import javax.media.nativewindow.DefaultGraphicsScreen; +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.Point; + +import jogamp.newt.ScreenImpl; + +public class ScreenDriver extends ScreenImpl { + static { + DisplayDriver.initSingleton(); + } + + public ScreenDriver() { + } + + protected void createNativeImpl() { + aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); + } + + protected void closeNativeImpl() { } + + protected int validateScreenIndex(int idx) { + return 0; // only one screen available + } + + protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { + virtualOrigin.setX(0); + virtualOrigin.setY(0); + virtualSize.setWidth(cachedWidth); + virtualSize.setHeight(cachedHeight); + } + + protected void sizeChanged(int w, int h) { + cachedWidth = w; + cachedHeight = h; + } + + private static int cachedWidth = 0; + private static int cachedHeight = 0; +} diff --git a/src/newt/classes/jogamp/newt/driver/kd/Window.java b/src/newt/classes/jogamp/newt/driver/kd/Window.java deleted file mode 100644 index ce65040c3..000000000 --- a/src/newt/classes/jogamp/newt/driver/kd/Window.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright (c) 2012 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. - * - */ - -package jogamp.newt.driver.kd; - -import javax.media.nativewindow.AbstractGraphicsConfiguration; -import javax.media.nativewindow.GraphicsConfigurationFactory; -import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.VisualIDHolder; -import javax.media.nativewindow.VisualIDHolder.VIDType; -import javax.media.nativewindow.util.Insets; -import javax.media.nativewindow.util.Point; -import javax.media.opengl.GLCapabilitiesImmutable; - -import jogamp.newt.WindowImpl; -import jogamp.opengl.egl.EGLGraphicsConfiguration; - -public class Window extends WindowImpl { - private static final String WINDOW_CLASS_NAME = "NewtWindow"; - - static { - Display.initSingleton(); - } - - public Window() { - } - - protected void createNativeImpl() { - if(0!=getParentWindowHandle()) { - throw new RuntimeException("Window parenting not supported (yet)"); - } - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); - if (null == cfg) { - throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); - } - setGraphicsConfiguration(cfg); - - GLCapabilitiesImmutable eglCaps = (GLCapabilitiesImmutable) cfg.getChosenCapabilities(); - int eglConfigID = eglCaps.getVisualID(VIDType.EGL_CONFIG); - long eglConfig = EGLGraphicsConfiguration.EGLConfigId2EGLConfig(getDisplayHandle(), eglConfigID); - - eglWindowHandle = CreateWindow(getDisplayHandle(), eglConfig); - if (eglWindowHandle == 0) { - throw new NativeWindowException("Error creating egl window: "+cfg+", eglConfigID "+eglConfigID+", eglConfig 0x"+Long.toHexString(eglConfig)); - } - setVisible0(eglWindowHandle, false); - setWindowHandle(RealizeWindow(eglWindowHandle)); - if (0 == getWindowHandle()) { - throw new NativeWindowException("Error native Window Handle is null"); - } - windowHandleClose = eglWindowHandle; - } - - protected void closeNativeImpl() { - if(0!=windowHandleClose) { - CloseWindow(windowHandleClose, windowUserData); - windowUserData=0; - } - } - - protected void requestFocusImpl(boolean reparented) { } - - protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - setVisible0(eglWindowHandle, 0 != ( FLAG_IS_VISIBLE & flags)); - visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); - } - - if(0!=eglWindowHandle) { - if(0 != ( FLAG_CHANGE_FULLSCREEN & flags)) { - final boolean fs = 0 != ( FLAG_IS_FULLSCREEN & flags) ; - setFullScreen0(eglWindowHandle, fs); - if(fs) { - return true; - } - } - // int _x=(x>=0)?x:this.x; - // int _y=(x>=0)?y:this.y; - width=(width>0)?width:getWidth(); - height=(height>0)?height:getHeight(); - if(width>0 || height>0) { - setSize0(eglWindowHandle, width, height); - } - if(x>=0 || y>=0) { - System.err.println("setPosition n/a in KD"); - } - } - - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); - } - - return true; - } - - protected Point getLocationOnScreenImpl(int x, int y) { - return new Point(x,y); - } - - protected void updateInsetsImpl(Insets insets) { - // nop .. - } - - //---------------------------------------------------------------------- - // Internals only - // - - protected static native boolean initIDs(); - private native long CreateWindow(long displayHandle, long eglConfig); - private native long RealizeWindow(long eglWindowHandle); - private native int CloseWindow(long eglWindowHandle, long userData); - private native void setVisible0(long eglWindowHandle, boolean visible); - private native void setSize0(long eglWindowHandle, int width, int height); - private native void setFullScreen0(long eglWindowHandle, boolean fullscreen); - - private void windowCreated(long userData) { - windowUserData=userData; - } - - @Override - protected void sizeChanged(boolean defer, int newWidth, int newHeight, boolean force) { - if(isFullscreen()) { - ((Screen)getScreen()).sizeChanged(getWidth(), getHeight()); - } - super.sizeChanged(defer, newWidth, newHeight, force); - } - - private long eglWindowHandle; - private long windowHandleClose; - private long windowUserData; -} diff --git a/src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java new file mode 100644 index 000000000..c733a3e94 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2012 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. + * + */ + +package jogamp.newt.driver.kd; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.GraphicsConfigurationFactory; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.VisualIDHolder; +import javax.media.nativewindow.VisualIDHolder.VIDType; +import javax.media.nativewindow.util.Insets; +import javax.media.nativewindow.util.Point; +import javax.media.opengl.GLCapabilitiesImmutable; + +import jogamp.newt.WindowImpl; +import jogamp.opengl.egl.EGLGraphicsConfiguration; + +public class WindowDriver extends WindowImpl { + private static final String WINDOW_CLASS_NAME = "NewtWindow"; + + static { + DisplayDriver.initSingleton(); + } + + public WindowDriver() { + } + + protected void createNativeImpl() { + if(0!=getParentWindowHandle()) { + throw new RuntimeException("Window parenting not supported (yet)"); + } + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); + if (null == cfg) { + throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); + } + setGraphicsConfiguration(cfg); + + GLCapabilitiesImmutable eglCaps = (GLCapabilitiesImmutable) cfg.getChosenCapabilities(); + int eglConfigID = eglCaps.getVisualID(VIDType.EGL_CONFIG); + long eglConfig = EGLGraphicsConfiguration.EGLConfigId2EGLConfig(getDisplayHandle(), eglConfigID); + + eglWindowHandle = CreateWindow(getDisplayHandle(), eglConfig); + if (eglWindowHandle == 0) { + throw new NativeWindowException("Error creating egl window: "+cfg+", eglConfigID "+eglConfigID+", eglConfig 0x"+Long.toHexString(eglConfig)); + } + setVisible0(eglWindowHandle, false); + setWindowHandle(RealizeWindow(eglWindowHandle)); + if (0 == getWindowHandle()) { + throw new NativeWindowException("Error native Window Handle is null"); + } + windowHandleClose = eglWindowHandle; + } + + protected void closeNativeImpl() { + if(0!=windowHandleClose) { + CloseWindow(windowHandleClose, windowUserData); + windowUserData=0; + } + } + + protected void requestFocusImpl(boolean reparented) { } + + protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { + setVisible0(eglWindowHandle, 0 != ( FLAG_IS_VISIBLE & flags)); + visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); + } + + if(0!=eglWindowHandle) { + if(0 != ( FLAG_CHANGE_FULLSCREEN & flags)) { + final boolean fs = 0 != ( FLAG_IS_FULLSCREEN & flags) ; + setFullScreen0(eglWindowHandle, fs); + if(fs) { + return true; + } + } + // int _x=(x>=0)?x:this.x; + // int _y=(x>=0)?y:this.y; + width=(width>0)?width:getWidth(); + height=(height>0)?height:getHeight(); + if(width>0 || height>0) { + setSize0(eglWindowHandle, width, height); + } + if(x>=0 || y>=0) { + System.err.println("setPosition n/a in KD"); + } + } + + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { + visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); + } + + return true; + } + + protected Point getLocationOnScreenImpl(int x, int y) { + return new Point(x,y); + } + + protected void updateInsetsImpl(Insets insets) { + // nop .. + } + + //---------------------------------------------------------------------- + // Internals only + // + + protected static native boolean initIDs(); + private native long CreateWindow(long displayHandle, long eglConfig); + private native long RealizeWindow(long eglWindowHandle); + private native int CloseWindow(long eglWindowHandle, long userData); + private native void setVisible0(long eglWindowHandle, boolean visible); + private native void setSize0(long eglWindowHandle, int width, int height); + private native void setFullScreen0(long eglWindowHandle, boolean fullscreen); + + private void windowCreated(long userData) { + windowUserData=userData; + } + + @Override + protected void sizeChanged(boolean defer, int newWidth, int newHeight, boolean force) { + if(isFullscreen()) { + ((ScreenDriver)getScreen()).sizeChanged(getWidth(), getHeight()); + } + super.sizeChanged(defer, newWidth, newHeight, force); + } + + private long eglWindowHandle; + private long windowHandleClose; + private long windowUserData; +} diff --git a/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java new file mode 100644 index 000000000..1a3f14859 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2012 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. + * + */ + +package jogamp.newt.driver.macosx; + +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeWindowException; + +import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; + +import jogamp.newt.DisplayImpl; +import jogamp.newt.NEWTJNILibLoader; + +public class DisplayDriver extends DisplayImpl { + static { + NEWTJNILibLoader.loadNEWT(); + + if(!initNSApplication0()) { + throw new NativeWindowException("Failed to initialize native Application hook"); + } + if(!WindowDriver.initIDs0()) { + throw new NativeWindowException("Failed to initialize jmethodIDs"); + } + if(DEBUG) { + System.err.println("MacDisplay.init App and IDs OK "+Thread.currentThread().getName()); + } + } + + public static void initSingleton() { + // just exist to ensure static init has been run + } + + public DisplayDriver() { + } + + protected void dispatchMessagesNative() { + // nop + } + + protected void createNativeImpl() { + aDevice = new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); + } + + protected void closeNativeImpl() { } + + public static void runNSApplication() { + runNSApplication0(); + } + public static void stopNSApplication() { + stopNSApplication0(); + } + + private static native boolean initNSApplication0(); + private static native void runNSApplication0(); + private static native void stopNSApplication0(); +} + diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacDisplay.java b/src/newt/classes/jogamp/newt/driver/macosx/MacDisplay.java deleted file mode 100644 index 18f8d9538..000000000 --- a/src/newt/classes/jogamp/newt/driver/macosx/MacDisplay.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.macosx; - -import javax.media.nativewindow.AbstractGraphicsDevice; -import javax.media.nativewindow.NativeWindowException; - -import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; - -import jogamp.newt.DisplayImpl; -import jogamp.newt.NEWTJNILibLoader; - -public class MacDisplay extends DisplayImpl { - static { - NEWTJNILibLoader.loadNEWT(); - - if(!initNSApplication0()) { - throw new NativeWindowException("Failed to initialize native Application hook"); - } - if(!MacWindow.initIDs0()) { - throw new NativeWindowException("Failed to initialize jmethodIDs"); - } - if(DEBUG) { - System.err.println("MacDisplay.init App and IDs OK "+Thread.currentThread().getName()); - } - } - - public static void initSingleton() { - // just exist to ensure static init has been run - } - - public MacDisplay() { - } - - protected void dispatchMessagesNative() { - // nop - } - - protected void createNativeImpl() { - aDevice = new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); - } - - protected void closeNativeImpl() { } - - public static void runNSApplication() { - runNSApplication0(); - } - public static void stopNSApplication() { - stopNSApplication0(); - } - - private static native boolean initNSApplication0(); - private static native void runNSApplication0(); - private static native void stopNSApplication0(); -} - diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacKeyUtil.java b/src/newt/classes/jogamp/newt/driver/macosx/MacKeyUtil.java index 46625f7a9..d39e0027b 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/MacKeyUtil.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/MacKeyUtil.java @@ -1,3 +1,30 @@ +/** + * Copyright 2011 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ package jogamp.newt.driver.macosx; import com.jogamp.newt.event.KeyEvent; diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacScreen.java b/src/newt/classes/jogamp/newt/driver/macosx/MacScreen.java deleted file mode 100644 index b9c725fd4..000000000 --- a/src/newt/classes/jogamp/newt/driver/macosx/MacScreen.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright (c) 2011 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. - * - */ - -package jogamp.newt.driver.macosx; - -import java.util.List; - -import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.DimensionImmutable; -import javax.media.nativewindow.util.Point; - -import jogamp.newt.ScreenImpl; - -import com.jogamp.common.util.IntObjectHashMap; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.util.ScreenModeUtil; - -public class MacScreen extends ScreenImpl { - - // caching native CGDisplayScreenSize() results, since it's ridiculous slow (~6 ms each call) - private static IntObjectHashMap/**/ scrnIdx2Dimension; - - static { - MacDisplay.initSingleton(); - scrnIdx2Dimension = new IntObjectHashMap(); - scrnIdx2Dimension.setKeyNotFoundValue(null); - } - - public MacScreen() { - } - - protected void createNativeImpl() { - aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); - } - - protected void closeNativeImpl() { } - - private static native int getWidthImpl0(int scrn_idx); - private static native int getHeightImpl0(int scrn_idx); - - private int[] getScreenModeIdx(int idx) { - // caching native CGDisplayScreenSize() results, since it's ridiculous slow (~6 ms each call) - DimensionImmutable dim = (DimensionImmutable) scrnIdx2Dimension.get(screen_idx); - if(null == dim) { - int[] res = getScreenSizeMM0(screen_idx); - if(null == res || 0 == res.length) { - return null; - } - dim = new Dimension(res[0], res[1]); - scrnIdx2Dimension.put(screen_idx, dim); - } - - int[] modeProps = getScreenMode0(screen_idx, idx, dim.getWidth(), dim.getHeight()); - if (null == modeProps || 0 == modeProps.length) { - return null; - } - if(modeProps.length < ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL) { - throw new RuntimeException("properties array too short, should be >= "+ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL+", is "+modeProps.length); - } - return modeProps; - } - - private int nativeModeIdx; - - protected int[] getScreenModeFirstImpl() { - nativeModeIdx = 0; - return getScreenModeNextImpl(); - } - - protected int[] getScreenModeNextImpl() { - int[] modeProps = getScreenModeIdx(nativeModeIdx); - if (null != modeProps && 0 < modeProps.length) { - nativeModeIdx++; - return modeProps; - } - return null; - } - - protected ScreenMode getCurrentScreenModeImpl() { - int[] modeProps = getScreenModeIdx(-1); - if (null != modeProps && 0 < modeProps.length) { - return ScreenModeUtil.streamIn(modeProps, 0); - } - return null; - } - - protected boolean setCurrentScreenModeImpl(final ScreenMode screenMode) { - final List screenModes = this.getScreenModesOrig(); - final int screenModeIdx = screenModes.indexOf(screenMode); - if(0>screenModeIdx) { - throw new RuntimeException("ScreenMode not element of ScreenMode list: "+screenMode); - } - final int nativeModeIdx = getScreenModesIdx2NativeIdx().get(screenModeIdx); - return setScreenMode0(screen_idx, nativeModeIdx); - } - - protected int validateScreenIndex(int idx) { - return idx; - } - - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(getWidthImpl0(screen_idx)); - virtualSize.setHeight(getHeightImpl0(screen_idx)); - } - - private native int[] getScreenSizeMM0(int screen_idx); - private native int[] getScreenMode0(int screen_index, int mode_index, int widthMM, int heightMM); - private native boolean setScreenMode0(int screen_index, int mode_idx); -} diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java deleted file mode 100644 index 27d7a1679..000000000 --- a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.macosx; - -import javax.media.nativewindow.AbstractGraphicsConfiguration; -import javax.media.nativewindow.GraphicsConfigurationFactory; -import javax.media.nativewindow.NativeWindow; -import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.MutableSurface; -import javax.media.nativewindow.VisualIDHolder; -import javax.media.nativewindow.util.Insets; -import javax.media.nativewindow.util.InsetsImmutable; -import javax.media.nativewindow.util.Point; -import javax.media.nativewindow.util.PointImmutable; - -import jogamp.newt.WindowImpl; -import jogamp.newt.driver.DriverClearFocus; -import jogamp.newt.driver.DriverUpdatePosition; - -import com.jogamp.newt.event.KeyEvent; - -public class MacWindow extends WindowImpl implements MutableSurface, DriverClearFocus, DriverUpdatePosition { - - static { - MacDisplay.initSingleton(); - } - - public MacWindow() { - } - - @Override - protected void createNativeImpl() { - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); - if (null == cfg) { - throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); - } - setGraphicsConfiguration(cfg); - reconfigureWindowImpl(getX(), getY(), getWidth(), getHeight(), getReconfigureFlags(FLAG_CHANGE_VISIBILITY, true)); - if (0 == getWindowHandle()) { - throw new NativeWindowException("Error creating window"); - } - } - - @Override - protected void closeNativeImpl() { - try { - if(DEBUG_IMPLEMENTATION) { System.err.println("MacWindow.CloseAction "+Thread.currentThread().getName()); } - final long handle = getWindowHandle(); - setWindowHandle(0); - surfaceHandle = 0; - sscSurfaceHandle = 0; - isOffscreenInstance = false; - if (0 != handle) { - close0(handle); - } - } catch (Throwable t) { - if(DEBUG_IMPLEMENTATION) { - Exception e = new Exception("Warning: closeNative failed - "+Thread.currentThread().getName(), t); - e.printStackTrace(); - } - } - } - - @Override - protected int lockSurfaceImpl() { - if(!isOffscreenInstance) { - return lockSurface0(getWindowHandle()) ? LOCK_SUCCESS : LOCK_SURFACE_NOT_READY; - } - return LOCK_SUCCESS; - } - - @Override - protected void unlockSurfaceImpl() { - if(!isOffscreenInstance) { - final long h = getWindowHandle(); - if(0 != h) { - unlockSurface0(h); - } - } - } - - @Override - public final long getSurfaceHandle() { - return 0 != sscSurfaceHandle ? sscSurfaceHandle : surfaceHandle; - } - - public void setSurfaceHandle(long surfaceHandle) { - if(DEBUG_IMPLEMENTATION) { - System.err.println("MacWindow.setSurfaceHandle(): 0x"+Long.toHexString(surfaceHandle)); - } - sscSurfaceHandle = surfaceHandle; - if (isNativeValid()) { - if (0 != sscSurfaceHandle) { - orderOut0( 0!=getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle() ); - } /** this is done by recreation! - else if (isVisible()){ - orderFront0( 0!=getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle() ); - } */ - } - } - - @Override - protected void setTitleImpl(final String title) { - setTitle0(getWindowHandle(), title); - } - - protected void requestFocusImpl(boolean force) { - if(!isOffscreenInstance) { - requestFocus0(getWindowHandle(), force); - } else { - focusChanged(false, true); - } - } - - public final void clearFocus() { - if(DEBUG_IMPLEMENTATION) { - System.err.println("MacWindow: clearFocus() - requestFocusParent, isOffscreenInstance "+isOffscreenInstance); - } - if(!isOffscreenInstance) { - resignFocus0(getWindowHandle()); - } else { - focusChanged(false, false); - } - } - - public void updatePosition() { - final Point pS = getTopLevelLocationOnScreen(getX(), getY()); - if(DEBUG_IMPLEMENTATION) { - System.err.println("MacWindow: updatePosition() - isOffscreenInstance "+isOffscreenInstance+", new abs pos: pS "+pS); - } - if( !isOffscreenInstance ) { - setFrameTopLeftPoint0(getParentWindowHandle(), getWindowHandle(), pS.getX(), pS.getY()); - } // else no offscreen position - // no native event (fullscreen, some reparenting) - super.positionChanged(true, getX(), getY()); - } - - - protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { - final Point pS = getTopLevelLocationOnScreen(x, y); - isOffscreenInstance = 0 != sscSurfaceHandle || isOffscreenInstance(this, this.getParent()); - - if(DEBUG_IMPLEMENTATION) { - System.err.println("MacWindow reconfig: "+x+"/"+y+" -> "+pS+" - "+width+"x"+height+ - ", offscreenInstance "+isOffscreenInstance+ - ", "+getReconfigureFlagsAsString(null, flags)); - } - - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && 0 == ( FLAG_IS_VISIBLE & flags) ) { - if ( !isOffscreenInstance ) { - orderOut0(getWindowHandle()); - } - // no native event .. - visibleChanged(true, false); - } - if( 0 == getWindowHandle() && 0 != ( FLAG_IS_VISIBLE & flags) || - 0 != ( FLAG_CHANGE_DECORATION & flags) || - 0 != ( FLAG_CHANGE_PARENTING & flags) || - 0 != ( FLAG_CHANGE_FULLSCREEN & flags) ) { - createWindow(isOffscreenInstance, 0 != getWindowHandle(), pS, width, height, 0 != ( FLAG_IS_FULLSCREEN & flags)); - if(isVisible()) { flags |= FLAG_CHANGE_VISIBILITY; } - } - if(x>=0 && y>=0) { - if( !isOffscreenInstance ) { - setFrameTopLeftPoint0(getParentWindowHandle(), getWindowHandle(), pS.getX(), pS.getY()); - } // else no offscreen position - // no native event (fullscreen, some reparenting) - super.positionChanged(true, x, y); - } - if(width>0 && height>0) { - if( !isOffscreenInstance ) { - setContentSize0(getWindowHandle(), width, height); - } // else offscreen size is realized via recreation - // no native event (fullscreen, some reparenting) - sizeChanged(true, width, height, false); // incl. validation (incl. repositioning) - } - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && 0 != ( FLAG_IS_VISIBLE & flags) ) { - if( !isOffscreenInstance ) { - orderFront0(getWindowHandle()); - } - // no native event .. - visibleChanged(true, true); - } - if( !isOffscreenInstance ) { - setAlwaysOnTop0(getWindowHandle(), 0 != ( FLAG_IS_ALWAYSONTOP & flags)); - } - return true; - } - - protected Point getLocationOnScreenImpl(int x, int y) { - Point p = new Point(x, y); - // min val is 0 - p.setX(Math.max(p.getX(), 0)); - p.setY(Math.max(p.getY(), 0)); - - final NativeWindow parent = getParent(); - if( null != parent && 0 != parent.getWindowHandle() ) { - p.translate(parent.getLocationOnScreen(null)); - } - return p; - } - - private Point getTopLevelLocationOnScreen(int x, int y) { - final InsetsImmutable _insets = getInsets(); // zero if undecorated - // client position -> top-level window position - x -= _insets.getLeftWidth() ; - y -= _insets.getTopHeight() ; - return getLocationOnScreenImpl(x, y); - } - - protected void updateInsetsImpl(Insets insets) { - // nop - using event driven insetsChange(..) - } - - @Override - protected void sizeChanged(boolean defer, int newWidth, int newHeight, boolean force) { - if(getWidth() != newWidth || getHeight() != newHeight) { - final Point p0S = getTopLevelLocationOnScreen(getX(), getY()); - setFrameTopLeftPoint0(getParentWindowHandle(), getWindowHandle(), p0S.getX(), p0S.getY()); - } - super.sizeChanged(defer, newWidth, newHeight, force); - } - - @Override - protected void positionChanged(boolean defer, int newX, int newY) { - // passed coordinates are in screen position of the client area - if(getWindowHandle()!=0) { - // screen position -> window position - Point absPos = new Point(newX, newY); - final NativeWindow parent = getParent(); - if(null != parent) { - absPos.translate( parent.getLocationOnScreen(null).scale(-1, -1) ); - } - super.positionChanged(defer, absPos.getX(), absPos.getY()); - } - } - - @Override - protected boolean setPointerVisibleImpl(final boolean pointerVisible) { - if( !isOffscreenInstance ) { - return setPointerVisible0(getWindowHandle(), hasFocus(), pointerVisible); - } // else may need offscreen solution ? FIXME - return false; - } - - @Override - protected boolean confinePointerImpl(final boolean confine) { - if( !isOffscreenInstance ) { - return confinePointer0(getWindowHandle(), confine); - } // else may need offscreen solution ? FIXME - return false; - } - - @Override - protected void warpPointerImpl(final int x, final int y) { - if( !isOffscreenInstance ) { - warpPointer0(getWindowHandle(), x, y); - } // else may need offscreen solution ? FIXME - } - - @Override - public void sendKeyEvent(int eventType, int modifiers, int keyCode, char keyChar) { - // Note that we send the key char for the key code on this - // platform -- we do not get any useful key codes out of the system - final int keyCode2 = MacKeyUtil.validateKeyCode(keyCode, keyChar); - final boolean valid = validateKeyEvent(eventType, modifiers, keyCode); - if(DEBUG_IMPLEMENTATION) System.err.println("MacWindow.sendKeyEvent "+Thread.currentThread().getName()+" char: 0x"+Integer.toHexString(keyChar)+", code 0x"+Integer.toHexString(keyCode)+" -> 0x"+Integer.toHexString(keyCode2)+", valid "+valid); - if(valid) { - // only deliver keyChar on key Typed events, harmonizing platform behavior - keyChar = KeyEvent.EVENT_KEY_TYPED == eventType ? keyChar : (char)-1; - super.sendKeyEvent(eventType, modifiers, keyCode2, keyChar); - } - } - - @Override - public void enqueueKeyEvent(boolean wait, int eventType, int modifiers, int keyCode, char keyChar) { - // Note that we send the key char for the key code on this - // platform -- we do not get any useful key codes out of the system - final int keyCode2 = MacKeyUtil.validateKeyCode(keyCode, keyChar); - final boolean valid = validateKeyEvent(eventType, modifiers, keyCode); - if(DEBUG_IMPLEMENTATION) System.err.println("MacWindow.enqueueKeyEvent "+Thread.currentThread().getName()+" char: 0x"+Integer.toHexString(keyChar)+", code 0x"+Integer.toHexString(keyCode)+" -> 0x"+Integer.toHexString(keyCode2)+", valid "+valid); - if(valid) { - // only deliver keyChar on key Typed events, harmonizing platform behavior - keyChar = KeyEvent.EVENT_KEY_TYPED == eventType ? keyChar : (char)-1; - super.enqueueKeyEvent(wait, eventType, modifiers, keyCode2, keyChar); - } - } - - private int keyDownModifiers = 0; - private int keyDownCode = 0; - - private boolean validateKeyEvent(int eventType, int modifiers, int keyCode) { - switch(eventType) { - case KeyEvent.EVENT_KEY_PRESSED: - keyDownModifiers = modifiers; - keyDownCode = keyCode; - return true; - case KeyEvent.EVENT_KEY_RELEASED: - return keyDownModifiers == modifiers && keyDownCode == keyCode; - case KeyEvent.EVENT_KEY_TYPED: - final boolean matchKeyDown = keyDownModifiers == modifiers && keyDownCode == keyCode; - keyDownModifiers = 0; - keyDownCode = 0; - return matchKeyDown; - default: - throw new NativeWindowException("Unexpected key event type " + eventType); - } - } - - - //---------------------------------------------------------------------- - // Internals only - // - - private void createWindow(final boolean offscreenInstance, final boolean recreate, - final PointImmutable pS, final int width, final int height, - final boolean fullscreen) { - - if(0!=getWindowHandle() && !recreate) { - return; - } - - try { - if(0!=getWindowHandle()) { - // save the view .. close the window - surfaceHandle = changeContentView0(getParentWindowHandle(), getWindowHandle(), 0); - if(recreate && 0==surfaceHandle) { - throw new NativeWindowException("Internal Error - recreate, window but no view"); - } - close0(getWindowHandle()); - setWindowHandle(0); - } else { - surfaceHandle = 0; - } - setWindowHandle(createWindow0(getParentWindowHandle(), - pS.getX(), pS.getY(), width, height, - (getGraphicsConfiguration().getChosenCapabilities().isBackgroundOpaque() && !offscreenInstance), - fullscreen, - ((isUndecorated() || offscreenInstance) ? - NSBorderlessWindowMask : - NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask), - NSBackingStoreBuffered, - getScreen().getIndex(), surfaceHandle)); - if (getWindowHandle() == 0) { - throw new NativeWindowException("Could create native window "+Thread.currentThread().getName()+" "+this); - } - surfaceHandle = contentView0(getWindowHandle()); - if( offscreenInstance ) { - orderOut0(0!=getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle()); - } else { - setTitle0(getWindowHandle(), getTitle()); - } - } catch (Exception ie) { - ie.printStackTrace(); - } - } - - protected static native boolean initIDs0(); - private native long createWindow0(long parentWindowHandle, int x, int y, int w, int h, - boolean opaque, boolean fullscreen, int windowStyle, - int backingStoreType, - int screen_idx, long view); - private native boolean lockSurface0(long window); - private native void unlockSurface0(long window); - private native void requestFocus0(long window, boolean force); - private native void resignFocus0(long window); - /** in case of a child window, it actually only issues orderBack(..) */ - private native void orderOut0(long window); - private native void orderFront0(long window); - private native void close0(long window); - private native void setTitle0(long window, String title); - private native long contentView0(long window); - private native long changeContentView0(long parentWindowOrViewHandle, long window, long view); - private native void setContentSize0(long window, int w, int h); - private native void setFrameTopLeftPoint0(long parentWindowHandle, long window, int x, int y); - private native void setAlwaysOnTop0(long window, boolean atop); - private static native Object getLocationOnScreen0(long windowHandle, int src_x, int src_y); - private static native boolean setPointerVisible0(long windowHandle, boolean hasFocus, boolean visible); - private static native boolean confinePointer0(long windowHandle, boolean confine); - private static native void warpPointer0(long windowHandle, int x, int y); - - // Window styles - private static final int NSBorderlessWindowMask = 0; - private static final int NSTitledWindowMask = 1 << 0; - private static final int NSClosableWindowMask = 1 << 1; - private static final int NSMiniaturizableWindowMask = 1 << 2; - private static final int NSResizableWindowMask = 1 << 3; - - // Window backing store types - private static final int NSBackingStoreRetained = 0; - private static final int NSBackingStoreNonretained = 1; - private static final int NSBackingStoreBuffered = 2; - - private volatile long surfaceHandle = 0; - private long sscSurfaceHandle = 0; - private boolean isOffscreenInstance = false; - -} diff --git a/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java new file mode 100644 index 000000000..24e60ba0a --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2011 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. + * + */ + +package jogamp.newt.driver.macosx; + +import java.util.List; + +import javax.media.nativewindow.DefaultGraphicsScreen; +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.DimensionImmutable; +import javax.media.nativewindow.util.Point; + +import jogamp.newt.ScreenImpl; + +import com.jogamp.common.util.IntObjectHashMap; +import com.jogamp.newt.ScreenMode; +import com.jogamp.newt.util.ScreenModeUtil; + +public class ScreenDriver extends ScreenImpl { + + // caching native CGDisplayScreenSize() results, since it's ridiculous slow (~6 ms each call) + private static IntObjectHashMap/**/ scrnIdx2Dimension; + + static { + DisplayDriver.initSingleton(); + scrnIdx2Dimension = new IntObjectHashMap(); + scrnIdx2Dimension.setKeyNotFoundValue(null); + } + + public ScreenDriver() { + } + + protected void createNativeImpl() { + aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); + } + + protected void closeNativeImpl() { } + + private static native int getWidthImpl0(int scrn_idx); + private static native int getHeightImpl0(int scrn_idx); + + private int[] getScreenModeIdx(int idx) { + // caching native CGDisplayScreenSize() results, since it's ridiculous slow (~6 ms each call) + DimensionImmutable dim = (DimensionImmutable) scrnIdx2Dimension.get(screen_idx); + if(null == dim) { + int[] res = getScreenSizeMM0(screen_idx); + if(null == res || 0 == res.length) { + return null; + } + dim = new Dimension(res[0], res[1]); + scrnIdx2Dimension.put(screen_idx, dim); + } + + int[] modeProps = getScreenMode0(screen_idx, idx, dim.getWidth(), dim.getHeight()); + if (null == modeProps || 0 == modeProps.length) { + return null; + } + if(modeProps.length < ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL) { + throw new RuntimeException("properties array too short, should be >= "+ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL+", is "+modeProps.length); + } + return modeProps; + } + + private int nativeModeIdx; + + protected int[] getScreenModeFirstImpl() { + nativeModeIdx = 0; + return getScreenModeNextImpl(); + } + + protected int[] getScreenModeNextImpl() { + int[] modeProps = getScreenModeIdx(nativeModeIdx); + if (null != modeProps && 0 < modeProps.length) { + nativeModeIdx++; + return modeProps; + } + return null; + } + + protected ScreenMode getCurrentScreenModeImpl() { + int[] modeProps = getScreenModeIdx(-1); + if (null != modeProps && 0 < modeProps.length) { + return ScreenModeUtil.streamIn(modeProps, 0); + } + return null; + } + + protected boolean setCurrentScreenModeImpl(final ScreenMode screenMode) { + final List screenModes = this.getScreenModesOrig(); + final int screenModeIdx = screenModes.indexOf(screenMode); + if(0>screenModeIdx) { + throw new RuntimeException("ScreenMode not element of ScreenMode list: "+screenMode); + } + final int nativeModeIdx = getScreenModesIdx2NativeIdx().get(screenModeIdx); + return setScreenMode0(screen_idx, nativeModeIdx); + } + + protected int validateScreenIndex(int idx) { + return idx; + } + + protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { + virtualOrigin.setX(0); + virtualOrigin.setY(0); + virtualSize.setWidth(getWidthImpl0(screen_idx)); + virtualSize.setHeight(getHeightImpl0(screen_idx)); + } + + private native int[] getScreenSizeMM0(int screen_idx); + private native int[] getScreenMode0(int screen_index, int mode_index, int widthMM, int heightMM); + private native boolean setScreenMode0(int screen_index, int mode_idx); +} diff --git a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java new file mode 100644 index 000000000..ea48569bf --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java @@ -0,0 +1,431 @@ +/* + * Copyright (c) 2008 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. + * + */ + +package jogamp.newt.driver.macosx; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.GraphicsConfigurationFactory; +import javax.media.nativewindow.NativeWindow; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.MutableSurface; +import javax.media.nativewindow.VisualIDHolder; +import javax.media.nativewindow.util.Insets; +import javax.media.nativewindow.util.InsetsImmutable; +import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.util.PointImmutable; + +import jogamp.newt.WindowImpl; +import jogamp.newt.driver.DriverClearFocus; +import jogamp.newt.driver.DriverUpdatePosition; + +import com.jogamp.newt.event.KeyEvent; + +public class WindowDriver extends WindowImpl implements MutableSurface, DriverClearFocus, DriverUpdatePosition { + + static { + DisplayDriver.initSingleton(); + } + + public WindowDriver() { + } + + @Override + protected void createNativeImpl() { + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, getScreen().getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); + if (null == cfg) { + throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); + } + setGraphicsConfiguration(cfg); + reconfigureWindowImpl(getX(), getY(), getWidth(), getHeight(), getReconfigureFlags(FLAG_CHANGE_VISIBILITY, true)); + if (0 == getWindowHandle()) { + throw new NativeWindowException("Error creating window"); + } + } + + @Override + protected void closeNativeImpl() { + try { + if(DEBUG_IMPLEMENTATION) { System.err.println("MacWindow.CloseAction "+Thread.currentThread().getName()); } + final long handle = getWindowHandle(); + setWindowHandle(0); + surfaceHandle = 0; + sscSurfaceHandle = 0; + isOffscreenInstance = false; + if (0 != handle) { + close0(handle); + } + } catch (Throwable t) { + if(DEBUG_IMPLEMENTATION) { + Exception e = new Exception("Warning: closeNative failed - "+Thread.currentThread().getName(), t); + e.printStackTrace(); + } + } + } + + @Override + protected int lockSurfaceImpl() { + if(!isOffscreenInstance) { + return lockSurface0(getWindowHandle()) ? LOCK_SUCCESS : LOCK_SURFACE_NOT_READY; + } + return LOCK_SUCCESS; + } + + @Override + protected void unlockSurfaceImpl() { + if(!isOffscreenInstance) { + final long h = getWindowHandle(); + if(0 != h) { + unlockSurface0(h); + } + } + } + + @Override + public final long getSurfaceHandle() { + return 0 != sscSurfaceHandle ? sscSurfaceHandle : surfaceHandle; + } + + public void setSurfaceHandle(long surfaceHandle) { + if(DEBUG_IMPLEMENTATION) { + System.err.println("MacWindow.setSurfaceHandle(): 0x"+Long.toHexString(surfaceHandle)); + } + sscSurfaceHandle = surfaceHandle; + if (isNativeValid()) { + if (0 != sscSurfaceHandle) { + orderOut0( 0!=getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle() ); + } /** this is done by recreation! + else if (isVisible()){ + orderFront0( 0!=getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle() ); + } */ + } + } + + @Override + protected void setTitleImpl(final String title) { + setTitle0(getWindowHandle(), title); + } + + protected void requestFocusImpl(boolean force) { + if(!isOffscreenInstance) { + requestFocus0(getWindowHandle(), force); + } else { + focusChanged(false, true); + } + } + + public final void clearFocus() { + if(DEBUG_IMPLEMENTATION) { + System.err.println("MacWindow: clearFocus() - requestFocusParent, isOffscreenInstance "+isOffscreenInstance); + } + if(!isOffscreenInstance) { + resignFocus0(getWindowHandle()); + } else { + focusChanged(false, false); + } + } + + public void updatePosition() { + final Point pS = getTopLevelLocationOnScreen(getX(), getY()); + if(DEBUG_IMPLEMENTATION) { + System.err.println("MacWindow: updatePosition() - isOffscreenInstance "+isOffscreenInstance+", new abs pos: pS "+pS); + } + if( !isOffscreenInstance ) { + setFrameTopLeftPoint0(getParentWindowHandle(), getWindowHandle(), pS.getX(), pS.getY()); + } // else no offscreen position + // no native event (fullscreen, some reparenting) + super.positionChanged(true, getX(), getY()); + } + + + protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + final Point pS = getTopLevelLocationOnScreen(x, y); + isOffscreenInstance = 0 != sscSurfaceHandle || isOffscreenInstance(this, this.getParent()); + + if(DEBUG_IMPLEMENTATION) { + System.err.println("MacWindow reconfig: "+x+"/"+y+" -> "+pS+" - "+width+"x"+height+ + ", offscreenInstance "+isOffscreenInstance+ + ", "+getReconfigureFlagsAsString(null, flags)); + } + + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && 0 == ( FLAG_IS_VISIBLE & flags) ) { + if ( !isOffscreenInstance ) { + orderOut0(getWindowHandle()); + } + // no native event .. + visibleChanged(true, false); + } + if( 0 == getWindowHandle() && 0 != ( FLAG_IS_VISIBLE & flags) || + 0 != ( FLAG_CHANGE_DECORATION & flags) || + 0 != ( FLAG_CHANGE_PARENTING & flags) || + 0 != ( FLAG_CHANGE_FULLSCREEN & flags) ) { + createWindow(isOffscreenInstance, 0 != getWindowHandle(), pS, width, height, 0 != ( FLAG_IS_FULLSCREEN & flags)); + if(isVisible()) { flags |= FLAG_CHANGE_VISIBILITY; } + } + if(x>=0 && y>=0) { + if( !isOffscreenInstance ) { + setFrameTopLeftPoint0(getParentWindowHandle(), getWindowHandle(), pS.getX(), pS.getY()); + } // else no offscreen position + // no native event (fullscreen, some reparenting) + super.positionChanged(true, x, y); + } + if(width>0 && height>0) { + if( !isOffscreenInstance ) { + setContentSize0(getWindowHandle(), width, height); + } // else offscreen size is realized via recreation + // no native event (fullscreen, some reparenting) + sizeChanged(true, width, height, false); // incl. validation (incl. repositioning) + } + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && 0 != ( FLAG_IS_VISIBLE & flags) ) { + if( !isOffscreenInstance ) { + orderFront0(getWindowHandle()); + } + // no native event .. + visibleChanged(true, true); + } + if( !isOffscreenInstance ) { + setAlwaysOnTop0(getWindowHandle(), 0 != ( FLAG_IS_ALWAYSONTOP & flags)); + } + return true; + } + + protected Point getLocationOnScreenImpl(int x, int y) { + Point p = new Point(x, y); + // min val is 0 + p.setX(Math.max(p.getX(), 0)); + p.setY(Math.max(p.getY(), 0)); + + final NativeWindow parent = getParent(); + if( null != parent && 0 != parent.getWindowHandle() ) { + p.translate(parent.getLocationOnScreen(null)); + } + return p; + } + + private Point getTopLevelLocationOnScreen(int x, int y) { + final InsetsImmutable _insets = getInsets(); // zero if undecorated + // client position -> top-level window position + x -= _insets.getLeftWidth() ; + y -= _insets.getTopHeight() ; + return getLocationOnScreenImpl(x, y); + } + + protected void updateInsetsImpl(Insets insets) { + // nop - using event driven insetsChange(..) + } + + @Override + protected void sizeChanged(boolean defer, int newWidth, int newHeight, boolean force) { + if(getWidth() != newWidth || getHeight() != newHeight) { + final Point p0S = getTopLevelLocationOnScreen(getX(), getY()); + setFrameTopLeftPoint0(getParentWindowHandle(), getWindowHandle(), p0S.getX(), p0S.getY()); + } + super.sizeChanged(defer, newWidth, newHeight, force); + } + + @Override + protected void positionChanged(boolean defer, int newX, int newY) { + // passed coordinates are in screen position of the client area + if(getWindowHandle()!=0) { + // screen position -> window position + Point absPos = new Point(newX, newY); + final NativeWindow parent = getParent(); + if(null != parent) { + absPos.translate( parent.getLocationOnScreen(null).scale(-1, -1) ); + } + super.positionChanged(defer, absPos.getX(), absPos.getY()); + } + } + + @Override + protected boolean setPointerVisibleImpl(final boolean pointerVisible) { + if( !isOffscreenInstance ) { + return setPointerVisible0(getWindowHandle(), hasFocus(), pointerVisible); + } // else may need offscreen solution ? FIXME + return false; + } + + @Override + protected boolean confinePointerImpl(final boolean confine) { + if( !isOffscreenInstance ) { + return confinePointer0(getWindowHandle(), confine); + } // else may need offscreen solution ? FIXME + return false; + } + + @Override + protected void warpPointerImpl(final int x, final int y) { + if( !isOffscreenInstance ) { + warpPointer0(getWindowHandle(), x, y); + } // else may need offscreen solution ? FIXME + } + + @Override + public void sendKeyEvent(int eventType, int modifiers, int keyCode, char keyChar) { + // Note that we send the key char for the key code on this + // platform -- we do not get any useful key codes out of the system + final int keyCode2 = MacKeyUtil.validateKeyCode(keyCode, keyChar); + final boolean valid = validateKeyEvent(eventType, modifiers, keyCode); + if(DEBUG_IMPLEMENTATION) System.err.println("MacWindow.sendKeyEvent "+Thread.currentThread().getName()+" char: 0x"+Integer.toHexString(keyChar)+", code 0x"+Integer.toHexString(keyCode)+" -> 0x"+Integer.toHexString(keyCode2)+", valid "+valid); + if(valid) { + // only deliver keyChar on key Typed events, harmonizing platform behavior + keyChar = KeyEvent.EVENT_KEY_TYPED == eventType ? keyChar : (char)-1; + super.sendKeyEvent(eventType, modifiers, keyCode2, keyChar); + } + } + + @Override + public void enqueueKeyEvent(boolean wait, int eventType, int modifiers, int keyCode, char keyChar) { + // Note that we send the key char for the key code on this + // platform -- we do not get any useful key codes out of the system + final int keyCode2 = MacKeyUtil.validateKeyCode(keyCode, keyChar); + final boolean valid = validateKeyEvent(eventType, modifiers, keyCode); + if(DEBUG_IMPLEMENTATION) System.err.println("MacWindow.enqueueKeyEvent "+Thread.currentThread().getName()+" char: 0x"+Integer.toHexString(keyChar)+", code 0x"+Integer.toHexString(keyCode)+" -> 0x"+Integer.toHexString(keyCode2)+", valid "+valid); + if(valid) { + // only deliver keyChar on key Typed events, harmonizing platform behavior + keyChar = KeyEvent.EVENT_KEY_TYPED == eventType ? keyChar : (char)-1; + super.enqueueKeyEvent(wait, eventType, modifiers, keyCode2, keyChar); + } + } + + private int keyDownModifiers = 0; + private int keyDownCode = 0; + + private boolean validateKeyEvent(int eventType, int modifiers, int keyCode) { + switch(eventType) { + case KeyEvent.EVENT_KEY_PRESSED: + keyDownModifiers = modifiers; + keyDownCode = keyCode; + return true; + case KeyEvent.EVENT_KEY_RELEASED: + return keyDownModifiers == modifiers && keyDownCode == keyCode; + case KeyEvent.EVENT_KEY_TYPED: + final boolean matchKeyDown = keyDownModifiers == modifiers && keyDownCode == keyCode; + keyDownModifiers = 0; + keyDownCode = 0; + return matchKeyDown; + default: + throw new NativeWindowException("Unexpected key event type " + eventType); + } + } + + + //---------------------------------------------------------------------- + // Internals only + // + + private void createWindow(final boolean offscreenInstance, final boolean recreate, + final PointImmutable pS, final int width, final int height, + final boolean fullscreen) { + + if(0!=getWindowHandle() && !recreate) { + return; + } + + try { + if(0!=getWindowHandle()) { + // save the view .. close the window + surfaceHandle = changeContentView0(getParentWindowHandle(), getWindowHandle(), 0); + if(recreate && 0==surfaceHandle) { + throw new NativeWindowException("Internal Error - recreate, window but no view"); + } + close0(getWindowHandle()); + setWindowHandle(0); + } else { + surfaceHandle = 0; + } + setWindowHandle(createWindow0(getParentWindowHandle(), + pS.getX(), pS.getY(), width, height, + (getGraphicsConfiguration().getChosenCapabilities().isBackgroundOpaque() && !offscreenInstance), + fullscreen, + ((isUndecorated() || offscreenInstance) ? + NSBorderlessWindowMask : + NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask), + NSBackingStoreBuffered, + getScreen().getIndex(), surfaceHandle)); + if (getWindowHandle() == 0) { + throw new NativeWindowException("Could create native window "+Thread.currentThread().getName()+" "+this); + } + surfaceHandle = contentView0(getWindowHandle()); + if( offscreenInstance ) { + orderOut0(0!=getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle()); + } else { + setTitle0(getWindowHandle(), getTitle()); + } + } catch (Exception ie) { + ie.printStackTrace(); + } + } + + protected static native boolean initIDs0(); + private native long createWindow0(long parentWindowHandle, int x, int y, int w, int h, + boolean opaque, boolean fullscreen, int windowStyle, + int backingStoreType, + int screen_idx, long view); + private native boolean lockSurface0(long window); + private native void unlockSurface0(long window); + private native void requestFocus0(long window, boolean force); + private native void resignFocus0(long window); + /** in case of a child window, it actually only issues orderBack(..) */ + private native void orderOut0(long window); + private native void orderFront0(long window); + private native void close0(long window); + private native void setTitle0(long window, String title); + private native long contentView0(long window); + private native long changeContentView0(long parentWindowOrViewHandle, long window, long view); + private native void setContentSize0(long window, int w, int h); + private native void setFrameTopLeftPoint0(long parentWindowHandle, long window, int x, int y); + private native void setAlwaysOnTop0(long window, boolean atop); + private static native Object getLocationOnScreen0(long windowHandle, int src_x, int src_y); + private static native boolean setPointerVisible0(long windowHandle, boolean hasFocus, boolean visible); + private static native boolean confinePointer0(long windowHandle, boolean confine); + private static native void warpPointer0(long windowHandle, int x, int y); + + // Window styles + private static final int NSBorderlessWindowMask = 0; + private static final int NSTitledWindowMask = 1 << 0; + private static final int NSClosableWindowMask = 1 << 1; + private static final int NSMiniaturizableWindowMask = 1 << 2; + private static final int NSResizableWindowMask = 1 << 3; + + // Window backing store types + private static final int NSBackingStoreRetained = 0; + private static final int NSBackingStoreNonretained = 1; + private static final int NSBackingStoreBuffered = 2; + + private volatile long surfaceHandle = 0; + private long sscSurfaceHandle = 0; + private boolean isOffscreenInstance = false; + +} diff --git a/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java new file mode 100644 index 000000000..579ec5be8 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2008 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. + * + */ + +package jogamp.newt.driver.windows; + +import jogamp.nativewindow.windows.RegisteredClass; +import jogamp.nativewindow.windows.RegisteredClassFactory; +import jogamp.newt.DisplayImpl; +import jogamp.newt.NEWTJNILibLoader; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeWindowException; + +import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; + +public class DisplayDriver extends DisplayImpl { + + private static final String newtClassBaseName = "_newt_clazz" ; + private static RegisteredClassFactory sharedClassFactory; + + static { + NEWTJNILibLoader.loadNEWT(); + + if (!WindowDriver.initIDs0()) { + throw new NativeWindowException("Failed to initialize WindowsWindow jmethodIDs"); + } + sharedClassFactory = new RegisteredClassFactory(newtClassBaseName, WindowDriver.getNewtWndProc0()); + } + + public static void initSingleton() { + // just exist to ensure static init has been run + } + + private RegisteredClass sharedClass; + + public DisplayDriver() { + } + + protected void createNativeImpl() { + sharedClass = sharedClassFactory.getSharedClass(); + aDevice = new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); + } + + protected void closeNativeImpl() { + sharedClassFactory.releaseSharedClass(); + } + + protected void dispatchMessagesNative() { + DispatchMessages0(); + } + + protected long getHInstance() { + return sharedClass.getHandle(); + } + + protected String getWindowClassName() { + return sharedClass.getName(); + } + + //---------------------------------------------------------------------- + // Internals only + // + private static native void DispatchMessages0(); +} + diff --git a/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java new file mode 100644 index 000000000..948b29460 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2008 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. + * + */ +package jogamp.newt.driver.windows; + +import javax.media.nativewindow.DefaultGraphicsScreen; +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.Point; + +import jogamp.newt.ScreenImpl; + +import com.jogamp.newt.ScreenMode; +import com.jogamp.newt.util.ScreenModeUtil; + +public class ScreenDriver extends ScreenImpl { + + static { + DisplayDriver.initSingleton(); + } + + public ScreenDriver() { + } + + protected void createNativeImpl() { + aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); + } + + protected void closeNativeImpl() { + } + + private int[] getScreenModeIdx(int idx) { + int[] modeProps = getScreenMode0(screen_idx, idx); + if (null == modeProps || 0 == modeProps.length) { + return null; + } + if(modeProps.length < ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL) { + throw new RuntimeException("properties array too short, should be >= "+ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL+", is "+modeProps.length); + } + return modeProps; + } + + private int nativeModeIdx; + + protected int[] getScreenModeFirstImpl() { + nativeModeIdx = 0; + return getScreenModeNextImpl(); + } + + protected int[] getScreenModeNextImpl() { + int[] modeProps = getScreenModeIdx(nativeModeIdx); + if (null != modeProps && 0 < modeProps.length) { + nativeModeIdx++; + return modeProps; + } + return null; + } + + protected ScreenMode getCurrentScreenModeImpl() { + int[] modeProps = getScreenModeIdx(-1); + if (null != modeProps && 0 < modeProps.length) { + return ScreenModeUtil.streamIn(modeProps, 0); + } + return null; + } + + protected boolean setCurrentScreenModeImpl(ScreenMode sm) { + return setScreenMode0(screen_idx, + sm.getMonitorMode().getSurfaceSize().getResolution().getWidth(), + sm.getMonitorMode().getSurfaceSize().getResolution().getHeight(), + sm.getMonitorMode().getSurfaceSize().getBitsPerPixel(), + sm.getMonitorMode().getRefreshRate(), + sm.getRotation()); + } + + protected int validateScreenIndex(int idx) { + return 0; // big-desktop, only one screen available + } + + protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { + virtualOrigin.setX(getOriginX0(screen_idx)); + virtualOrigin.setY(getOriginY0(screen_idx)); + virtualSize.setWidth(getWidthImpl0(screen_idx)); + virtualSize.setHeight(getHeightImpl0(screen_idx)); + } + + // Native calls + private native int getOriginX0(int screen_idx); + private native int getOriginY0(int screen_idx); + private native int getWidthImpl0(int scrn_idx); + private native int getHeightImpl0(int scrn_idx); + + private native int[] getScreenMode0(int screen_index, int mode_index); + private native boolean setScreenMode0(int screen_index, int width, int height, int bits, int freq, int rot); +} diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java new file mode 100644 index 000000000..39ea54575 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2008 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. + * + */ + +package jogamp.newt.driver.windows; + +import jogamp.nativewindow.windows.GDI; +import jogamp.nativewindow.windows.GDIUtil; +import jogamp.newt.WindowImpl; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.GraphicsConfigurationFactory; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.VisualIDHolder; +import javax.media.nativewindow.util.Insets; +import javax.media.nativewindow.util.InsetsImmutable; +import javax.media.nativewindow.util.Point; + +import com.jogamp.newt.event.KeyEvent; +import com.jogamp.newt.event.MouseAdapter; +import com.jogamp.newt.event.MouseEvent; + +public class WindowDriver extends WindowImpl { + + private long hmon; + private long hdc; + private long hdc_old; + private long windowHandleClose; + + static { + DisplayDriver.initSingleton(); + } + + public WindowDriver() { + } + + @Override + protected int lockSurfaceImpl() { + if (0 != hdc) { + throw new InternalError("surface not released"); + } + hdc = GDI.GetDC(getWindowHandle()); + hmon = MonitorFromWindow0(getWindowHandle()); + + // return ( 0 == hdc ) ? LOCK_SURFACE_NOT_READY : ( hdc_old != hdc ) ? LOCK_SURFACE_CHANGED : LOCK_SUCCESS ; + if( 0 == hdc ) { + return LOCK_SURFACE_NOT_READY; + } + if( hdc_old == hdc ) { + return LOCK_SUCCESS; + } + if(DEBUG_IMPLEMENTATION) { + System.err.println("WindowsWindow: surface change "+toHexString(hdc_old)+" -> "+toHexString(hdc)); + // Thread.dumpStack(); + } + return LOCK_SURFACE_CHANGED; + } + + @Override + protected void unlockSurfaceImpl() { + if (0 != hdc) { + GDI.ReleaseDC(getWindowHandle(), hdc); + hdc_old = hdc; + hdc=0; + } + } + + @Override + public final long getSurfaceHandle() { + return hdc; + } + + @Override + public boolean hasDeviceChanged() { + if(0!=getWindowHandle()) { + long _hmon = MonitorFromWindow0(getWindowHandle()); + if (hmon != _hmon) { + if(DEBUG_IMPLEMENTATION) { + System.err.println("Info: Window Device Changed "+Thread.currentThread().getName()+ + ", HMON "+toHexString(hmon)+" -> "+toHexString(_hmon)); + // Thread.dumpStack(); + } + hmon = _hmon; + return true; + } + } + return false; + } + + protected void createNativeImpl() { + final ScreenDriver screen = (ScreenDriver) getScreen(); + final DisplayDriver display = (DisplayDriver) screen.getDisplay(); + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, screen.getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); + if (null == cfg) { + throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); + } + setGraphicsConfiguration(cfg); + final int flags = getReconfigureFlags(0, true) & + ( FLAG_IS_ALWAYSONTOP | FLAG_IS_UNDECORATED ) ; + setWindowHandle(CreateWindow0(display.getHInstance(), display.getWindowClassName(), display.getWindowClassName(), + getParentWindowHandle(), getX(), getY(), getWidth(), getHeight(), autoPosition(), flags)); + if (getWindowHandle() == 0) { + throw new NativeWindowException("Error creating window"); + } + windowHandleClose = getWindowHandle(); + addMouseListener(new MouseTracker()); + + if(DEBUG_IMPLEMENTATION) { + Exception e = new Exception("Info: Window new window handle "+Thread.currentThread().getName()+ + " (Parent HWND "+toHexString(getParentWindowHandle())+ + ") : HWND "+toHexString(getWindowHandle())+", "+Thread.currentThread()); + e.printStackTrace(); + } + } + + class MouseTracker extends MouseAdapter { + public void mouseEntered(MouseEvent e) { + WindowDriver.trackPointerLeave0(WindowDriver.this.getWindowHandle()); + } + } + + protected void closeNativeImpl() { + if(windowHandleClose != 0) { + if (hdc != 0) { + try { + GDI.ReleaseDC(windowHandleClose, hdc); + } catch (Throwable t) { + if(DEBUG_IMPLEMENTATION) { + Exception e = new Exception("Warning: closeNativeImpl failed - "+Thread.currentThread().getName(), t); + e.printStackTrace(); + } + } + } + try { + GDI.SetParent(windowHandleClose, 0); // detach first, experience hang w/ SWT parent + GDI.DestroyWindow(windowHandleClose); + } catch (Throwable t) { + if(DEBUG_IMPLEMENTATION) { + Exception e = new Exception("Warning: closeNativeImpl failed - "+Thread.currentThread().getName(), t); + e.printStackTrace(); + } + } finally { + windowHandleClose = 0; + } + } + hdc = 0; + hdc_old = 0; + } + + protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + if(DEBUG_IMPLEMENTATION) { + System.err.println("WindowsWindow reconfig: "+x+"/"+y+" "+width+"x"+height+", "+ + getReconfigureFlagsAsString(null, flags)); + } + + if(0 == ( FLAG_IS_UNDECORATED & flags)) { + final InsetsImmutable i = getInsets(); + + // client position -> top-level window position + x -= i.getLeftWidth() ; + y -= i.getTopHeight() ; + + if(0 top-level window size + width += i.getTotalWidth(); + height += i.getTotalHeight(); + } + } + reconfigureWindow0( getParentWindowHandle(), getWindowHandle(), x, y, width, height, flags); + + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { + visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); + } + return true; + } + + protected void requestFocusImpl(boolean force) { + requestFocus0(getWindowHandle(), force); + } + + @Override + protected void setTitleImpl(final String title) { + setTitle0(getWindowHandle(), title); + } + + @Override + protected boolean setPointerVisibleImpl(final boolean pointerVisible) { + final Boolean[] res = new Boolean[] { Boolean.FALSE }; + + this.runOnEDTIfAvail(true, new Runnable() { + public void run() { + res[0] = Boolean.valueOf(setPointerVisible0(getWindowHandle(), pointerVisible)); + } + }); + return res[0].booleanValue(); + } + + @Override + protected boolean confinePointerImpl(final boolean confine) { + final Boolean[] res = new Boolean[] { Boolean.FALSE }; + + this.runOnEDTIfAvail(true, new Runnable() { + public void run() { + final Point p0 = getLocationOnScreenImpl(0, 0); + res[0] = Boolean.valueOf(confinePointer0(getWindowHandle(), confine, + p0.getX(), p0.getY(), p0.getX()+getWidth(), p0.getY()+getHeight())); + } + }); + return res[0].booleanValue(); + } + + @Override + protected void warpPointerImpl(final int x, final int y) { + this.runOnEDTIfAvail(true, new Runnable() { + public void run() { + final Point sPos = getLocationOnScreenImpl(x, y); + warpPointer0(getWindowHandle(), sPos.getX(), sPos.getY()); + } + }); + return; + } + + protected Point getLocationOnScreenImpl(int x, int y) { + return GDIUtil.GetRelativeLocation( getWindowHandle(), 0 /*root win*/, x, y); + } + + protected void updateInsetsImpl(Insets insets) { + // nop - using event driven insetsChange(..) + } + + private final int validateKeyCode(int eventType, int keyCode) { + switch(eventType) { + case KeyEvent.EVENT_KEY_PRESSED: + lastPressedKeyCode = keyCode; + break; + case KeyEvent.EVENT_KEY_TYPED: + if(-1==keyCode) { + keyCode = lastPressedKeyCode; + } + lastPressedKeyCode = -1; + break; + } + return keyCode; + } + private int lastPressedKeyCode = 0; + + @Override + public void sendKeyEvent(int eventType, int modifiers, int keyCode, char keyChar) { + // Note that we have to regenerate the keyCode for EVENT_KEY_TYPED on this platform + keyCode = validateKeyCode(eventType, keyCode); + super.sendKeyEvent(eventType, modifiers, keyCode, keyChar); + } + + @Override + public void enqueueKeyEvent(boolean wait, int eventType, int modifiers, int keyCode, char keyChar) { + // Note that we have to regenerate the keyCode for EVENT_KEY_TYPED on this platform + keyCode = validateKeyCode(eventType, keyCode); + super.enqueueKeyEvent(wait, eventType, modifiers, keyCode, keyChar); + } + + //---------------------------------------------------------------------- + // Internals only + // + protected static native boolean initIDs0(); + protected static native long getNewtWndProc0(); + + private native long CreateWindow0(long hInstance, String wndClassName, String wndName, + long parentWindowHandle, + int x, int y, int width, int height, boolean autoPosition, int flags); + private native long MonitorFromWindow0(long windowHandle); + private native void reconfigureWindow0(long parentWindowHandle, long windowHandle, + int x, int y, int width, int height, int flags); + private static native void setTitle0(long windowHandle, String title); + private native void requestFocus0(long windowHandle, boolean force); + + private static native boolean setPointerVisible0(long windowHandle, boolean visible); + private static native boolean confinePointer0(long windowHandle, boolean grab, int l, int t, int r, int b); + private static native void warpPointer0(long windowHandle, int x, int y); + private static native void trackPointerLeave0(long windowHandle); +} diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowsDisplay.java b/src/newt/classes/jogamp/newt/driver/windows/WindowsDisplay.java deleted file mode 100644 index 225b115e4..000000000 --- a/src/newt/classes/jogamp/newt/driver/windows/WindowsDisplay.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.windows; - -import jogamp.nativewindow.windows.RegisteredClass; -import jogamp.nativewindow.windows.RegisteredClassFactory; -import jogamp.newt.DisplayImpl; -import jogamp.newt.NEWTJNILibLoader; -import javax.media.nativewindow.AbstractGraphicsDevice; -import javax.media.nativewindow.NativeWindowException; - -import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; - -public class WindowsDisplay extends DisplayImpl { - - private static final String newtClassBaseName = "_newt_clazz" ; - private static RegisteredClassFactory sharedClassFactory; - - static { - NEWTJNILibLoader.loadNEWT(); - - if (!WindowsWindow.initIDs0()) { - throw new NativeWindowException("Failed to initialize WindowsWindow jmethodIDs"); - } - sharedClassFactory = new RegisteredClassFactory(newtClassBaseName, WindowsWindow.getNewtWndProc0()); - } - - public static void initSingleton() { - // just exist to ensure static init has been run - } - - private RegisteredClass sharedClass; - - public WindowsDisplay() { - } - - protected void createNativeImpl() { - sharedClass = sharedClassFactory.getSharedClass(); - aDevice = new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); - } - - protected void closeNativeImpl() { - sharedClassFactory.releaseSharedClass(); - } - - protected void dispatchMessagesNative() { - DispatchMessages0(); - } - - protected long getHInstance() { - return sharedClass.getHandle(); - } - - protected String getWindowClassName() { - return sharedClass.getName(); - } - - //---------------------------------------------------------------------- - // Internals only - // - private static native void DispatchMessages0(); -} - diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowsScreen.java b/src/newt/classes/jogamp/newt/driver/windows/WindowsScreen.java deleted file mode 100644 index f8bce9da3..000000000 --- a/src/newt/classes/jogamp/newt/driver/windows/WindowsScreen.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ -package jogamp.newt.driver.windows; - -import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; - -import jogamp.newt.ScreenImpl; - -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.util.ScreenModeUtil; - -public class WindowsScreen extends ScreenImpl { - - static { - WindowsDisplay.initSingleton(); - } - - public WindowsScreen() { - } - - protected void createNativeImpl() { - aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); - } - - protected void closeNativeImpl() { - } - - private int[] getScreenModeIdx(int idx) { - int[] modeProps = getScreenMode0(screen_idx, idx); - if (null == modeProps || 0 == modeProps.length) { - return null; - } - if(modeProps.length < ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL) { - throw new RuntimeException("properties array too short, should be >= "+ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL+", is "+modeProps.length); - } - return modeProps; - } - - private int nativeModeIdx; - - protected int[] getScreenModeFirstImpl() { - nativeModeIdx = 0; - return getScreenModeNextImpl(); - } - - protected int[] getScreenModeNextImpl() { - int[] modeProps = getScreenModeIdx(nativeModeIdx); - if (null != modeProps && 0 < modeProps.length) { - nativeModeIdx++; - return modeProps; - } - return null; - } - - protected ScreenMode getCurrentScreenModeImpl() { - int[] modeProps = getScreenModeIdx(-1); - if (null != modeProps && 0 < modeProps.length) { - return ScreenModeUtil.streamIn(modeProps, 0); - } - return null; - } - - protected boolean setCurrentScreenModeImpl(ScreenMode sm) { - return setScreenMode0(screen_idx, - sm.getMonitorMode().getSurfaceSize().getResolution().getWidth(), - sm.getMonitorMode().getSurfaceSize().getResolution().getHeight(), - sm.getMonitorMode().getSurfaceSize().getBitsPerPixel(), - sm.getMonitorMode().getRefreshRate(), - sm.getRotation()); - } - - protected int validateScreenIndex(int idx) { - return 0; // big-desktop, only one screen available - } - - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(getOriginX0(screen_idx)); - virtualOrigin.setY(getOriginY0(screen_idx)); - virtualSize.setWidth(getWidthImpl0(screen_idx)); - virtualSize.setHeight(getHeightImpl0(screen_idx)); - } - - // Native calls - private native int getOriginX0(int screen_idx); - private native int getOriginY0(int screen_idx); - private native int getWidthImpl0(int scrn_idx); - private native int getHeightImpl0(int scrn_idx); - - private native int[] getScreenMode0(int screen_index, int mode_index); - private native boolean setScreenMode0(int screen_index, int width, int height, int bits, int freq, int rot); -} diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java b/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java deleted file mode 100644 index 6a8c81f3d..000000000 --- a/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java +++ /dev/null @@ -1,311 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.windows; - -import jogamp.nativewindow.windows.GDI; -import jogamp.nativewindow.windows.GDIUtil; -import jogamp.newt.WindowImpl; - -import javax.media.nativewindow.AbstractGraphicsConfiguration; -import javax.media.nativewindow.GraphicsConfigurationFactory; -import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.VisualIDHolder; -import javax.media.nativewindow.util.Insets; -import javax.media.nativewindow.util.InsetsImmutable; -import javax.media.nativewindow.util.Point; - -import com.jogamp.newt.event.KeyEvent; -import com.jogamp.newt.event.MouseAdapter; -import com.jogamp.newt.event.MouseEvent; - -public class WindowsWindow extends WindowImpl { - - private long hmon; - private long hdc; - private long hdc_old; - private long windowHandleClose; - - static { - WindowsDisplay.initSingleton(); - } - - public WindowsWindow() { - } - - @Override - protected int lockSurfaceImpl() { - if (0 != hdc) { - throw new InternalError("surface not released"); - } - hdc = GDI.GetDC(getWindowHandle()); - hmon = MonitorFromWindow0(getWindowHandle()); - - // return ( 0 == hdc ) ? LOCK_SURFACE_NOT_READY : ( hdc_old != hdc ) ? LOCK_SURFACE_CHANGED : LOCK_SUCCESS ; - if( 0 == hdc ) { - return LOCK_SURFACE_NOT_READY; - } - if( hdc_old == hdc ) { - return LOCK_SUCCESS; - } - if(DEBUG_IMPLEMENTATION) { - System.err.println("WindowsWindow: surface change "+toHexString(hdc_old)+" -> "+toHexString(hdc)); - // Thread.dumpStack(); - } - return LOCK_SURFACE_CHANGED; - } - - @Override - protected void unlockSurfaceImpl() { - if (0 != hdc) { - GDI.ReleaseDC(getWindowHandle(), hdc); - hdc_old = hdc; - hdc=0; - } - } - - @Override - public final long getSurfaceHandle() { - return hdc; - } - - @Override - public boolean hasDeviceChanged() { - if(0!=getWindowHandle()) { - long _hmon = MonitorFromWindow0(getWindowHandle()); - if (hmon != _hmon) { - if(DEBUG_IMPLEMENTATION) { - System.err.println("Info: Window Device Changed "+Thread.currentThread().getName()+ - ", HMON "+toHexString(hmon)+" -> "+toHexString(_hmon)); - // Thread.dumpStack(); - } - hmon = _hmon; - return true; - } - } - return false; - } - - protected void createNativeImpl() { - final WindowsScreen screen = (WindowsScreen) getScreen(); - final WindowsDisplay display = (WindowsDisplay) screen.getDisplay(); - final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, screen.getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); - if (null == cfg) { - throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); - } - setGraphicsConfiguration(cfg); - final int flags = getReconfigureFlags(0, true) & - ( FLAG_IS_ALWAYSONTOP | FLAG_IS_UNDECORATED ) ; - setWindowHandle(CreateWindow0(display.getHInstance(), display.getWindowClassName(), display.getWindowClassName(), - getParentWindowHandle(), getX(), getY(), getWidth(), getHeight(), autoPosition(), flags)); - if (getWindowHandle() == 0) { - throw new NativeWindowException("Error creating window"); - } - windowHandleClose = getWindowHandle(); - addMouseListener(new MouseTracker()); - - if(DEBUG_IMPLEMENTATION) { - Exception e = new Exception("Info: Window new window handle "+Thread.currentThread().getName()+ - " (Parent HWND "+toHexString(getParentWindowHandle())+ - ") : HWND "+toHexString(getWindowHandle())+", "+Thread.currentThread()); - e.printStackTrace(); - } - } - - class MouseTracker extends MouseAdapter { - public void mouseEntered(MouseEvent e) { - WindowsWindow.trackPointerLeave0(WindowsWindow.this.getWindowHandle()); - } - } - - protected void closeNativeImpl() { - if(windowHandleClose != 0) { - if (hdc != 0) { - try { - GDI.ReleaseDC(windowHandleClose, hdc); - } catch (Throwable t) { - if(DEBUG_IMPLEMENTATION) { - Exception e = new Exception("Warning: closeNativeImpl failed - "+Thread.currentThread().getName(), t); - e.printStackTrace(); - } - } - } - try { - GDI.SetParent(windowHandleClose, 0); // detach first, experience hang w/ SWT parent - GDI.DestroyWindow(windowHandleClose); - } catch (Throwable t) { - if(DEBUG_IMPLEMENTATION) { - Exception e = new Exception("Warning: closeNativeImpl failed - "+Thread.currentThread().getName(), t); - e.printStackTrace(); - } - } finally { - windowHandleClose = 0; - } - } - hdc = 0; - hdc_old = 0; - } - - protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { - if(DEBUG_IMPLEMENTATION) { - System.err.println("WindowsWindow reconfig: "+x+"/"+y+" "+width+"x"+height+", "+ - getReconfigureFlagsAsString(null, flags)); - } - - if(0 == ( FLAG_IS_UNDECORATED & flags)) { - final InsetsImmutable i = getInsets(); - - // client position -> top-level window position - x -= i.getLeftWidth() ; - y -= i.getTopHeight() ; - - if(0 top-level window size - width += i.getTotalWidth(); - height += i.getTotalHeight(); - } - } - reconfigureWindow0( getParentWindowHandle(), getWindowHandle(), x, y, width, height, flags); - - if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); - } - return true; - } - - protected void requestFocusImpl(boolean force) { - requestFocus0(getWindowHandle(), force); - } - - @Override - protected void setTitleImpl(final String title) { - setTitle0(getWindowHandle(), title); - } - - @Override - protected boolean setPointerVisibleImpl(final boolean pointerVisible) { - final Boolean[] res = new Boolean[] { Boolean.FALSE }; - - this.runOnEDTIfAvail(true, new Runnable() { - public void run() { - res[0] = Boolean.valueOf(setPointerVisible0(getWindowHandle(), pointerVisible)); - } - }); - return res[0].booleanValue(); - } - - @Override - protected boolean confinePointerImpl(final boolean confine) { - final Boolean[] res = new Boolean[] { Boolean.FALSE }; - - this.runOnEDTIfAvail(true, new Runnable() { - public void run() { - final Point p0 = getLocationOnScreenImpl(0, 0); - res[0] = Boolean.valueOf(confinePointer0(getWindowHandle(), confine, - p0.getX(), p0.getY(), p0.getX()+getWidth(), p0.getY()+getHeight())); - } - }); - return res[0].booleanValue(); - } - - @Override - protected void warpPointerImpl(final int x, final int y) { - this.runOnEDTIfAvail(true, new Runnable() { - public void run() { - final Point sPos = getLocationOnScreenImpl(x, y); - warpPointer0(getWindowHandle(), sPos.getX(), sPos.getY()); - } - }); - return; - } - - protected Point getLocationOnScreenImpl(int x, int y) { - return GDIUtil.GetRelativeLocation( getWindowHandle(), 0 /*root win*/, x, y); - } - - protected void updateInsetsImpl(Insets insets) { - // nop - using event driven insetsChange(..) - } - - private final int validateKeyCode(int eventType, int keyCode) { - switch(eventType) { - case KeyEvent.EVENT_KEY_PRESSED: - lastPressedKeyCode = keyCode; - break; - case KeyEvent.EVENT_KEY_TYPED: - if(-1==keyCode) { - keyCode = lastPressedKeyCode; - } - lastPressedKeyCode = -1; - break; - } - return keyCode; - } - private int lastPressedKeyCode = 0; - - @Override - public void sendKeyEvent(int eventType, int modifiers, int keyCode, char keyChar) { - // Note that we have to regenerate the keyCode for EVENT_KEY_TYPED on this platform - keyCode = validateKeyCode(eventType, keyCode); - super.sendKeyEvent(eventType, modifiers, keyCode, keyChar); - } - - @Override - public void enqueueKeyEvent(boolean wait, int eventType, int modifiers, int keyCode, char keyChar) { - // Note that we have to regenerate the keyCode for EVENT_KEY_TYPED on this platform - keyCode = validateKeyCode(eventType, keyCode); - super.enqueueKeyEvent(wait, eventType, modifiers, keyCode, keyChar); - } - - //---------------------------------------------------------------------- - // Internals only - // - protected static native boolean initIDs0(); - protected static native long getNewtWndProc0(); - - private native long CreateWindow0(long hInstance, String wndClassName, String wndName, - long parentWindowHandle, - int x, int y, int width, int height, boolean autoPosition, int flags); - private native long MonitorFromWindow0(long windowHandle); - private native void reconfigureWindow0(long parentWindowHandle, long windowHandle, - int x, int y, int width, int height, int flags); - private static native void setTitle0(long windowHandle, String title); - private native void requestFocus0(long windowHandle, boolean force); - - private static native boolean setPointerVisible0(long windowHandle, boolean visible); - private static native boolean confinePointer0(long windowHandle, boolean grab, int l, int t, int r, int b); - private static native void warpPointer0(long windowHandle, int x, int y); - private static native void trackPointerLeave0(long windowHandle); -} diff --git a/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java new file mode 100644 index 000000000..714324d63 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2008 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. + * + */ + +package jogamp.newt.driver.x11; + +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.NativeWindowFactory; + +import com.jogamp.nativewindow.x11.X11GraphicsDevice; + +import jogamp.nativewindow.x11.X11Util; +import jogamp.newt.DisplayImpl; +import jogamp.newt.NEWTJNILibLoader; + +public class DisplayDriver extends DisplayImpl { + + static { + NEWTJNILibLoader.loadNEWT(); + + if ( !initIDs0(X11Util.XERROR_STACKDUMP) ) { + throw new NativeWindowException("Failed to initialize X11Display jmethodIDs"); + } + + if (!WindowDriver.initIDs0()) { + throw new NativeWindowException("Failed to initialize X11Window jmethodIDs"); + } + } + + public static void initSingleton() { + // just exist to ensure static init has been run + } + + + public DisplayDriver() { + } + + public String validateDisplayName(String name, long handle) { + return X11Util.validateDisplayName(name, handle); + } + + /** + * {@inheritDoc} + * + * We use a private non-shared X11 Display instance for EDT window operations and one for exposed animation, eg. OpenGL. + *

      + * In case {@link X11Util#HAS_XLOCKDISPLAY_BUG} and {@link X11Util#XINITTHREADS_ALWAYS_ENABLED}, + * we use null locking. Even though this seems not to be rational, it gives most stable results on all platforms. + *

      + *

      + * Otherwise we use basic locking via the constructor {@link X11GraphicsDevice#X11GraphicsDevice(long, int, boolean)}, + * since it is possible to share this device via {@link com.jogamp.newt.NewtFactory#createDisplay(String, boolean)}. + *

      + */ + @SuppressWarnings("unused") + protected void createNativeImpl() { + long handle = X11Util.openDisplay(name); + if( 0 == handle ) { + throw new RuntimeException("Error creating display(Win): "+name); + } + if(USE_SEPARATE_DISPLAY_FOR_EDT) { + edtDisplayHandle = X11Util.openDisplay(name); + if( 0 == edtDisplayHandle ) { + X11Util.closeDisplay(handle); + throw new RuntimeException("Error creating display(EDT): "+name); + } + } else { + edtDisplayHandle = handle; + } + try { + CompleteDisplay0(edtDisplayHandle); + } catch(RuntimeException e) { + closeNativeImpl(); + throw e; + } + + // see API doc above! + if(X11Util.XINITTHREADS_ALWAYS_ENABLED && X11Util.HAS_XLOCKDISPLAY_BUG) { + aDevice = new X11GraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_UNIT, NativeWindowFactory.getNullToolkitLock(), false); + } else { + aDevice = new X11GraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_UNIT, false); + } + } + + protected void closeNativeImpl() { + DisplayRelease0(edtDisplayHandle, javaObjectAtom, windowDeleteAtom); + javaObjectAtom = 0; + windowDeleteAtom = 0; + // closing using ATI driver bug 'same order' + final long handle = getHandle(); + X11Util.closeDisplay(handle); + if(handle != edtDisplayHandle) { + X11Util.closeDisplay(edtDisplayHandle); + } + edtDisplayHandle = 0; + } + + protected void dispatchMessagesNative() { + if(0 != edtDisplayHandle) { + DispatchMessages0(edtDisplayHandle, javaObjectAtom, windowDeleteAtom); + } + } + + protected long getEDTHandle() { return edtDisplayHandle; } + protected long getJavaObjectAtom() { return javaObjectAtom; } + protected long getWindowDeleteAtom() { return windowDeleteAtom; } + + //---------------------------------------------------------------------- + // Internals only + // + private static native boolean initIDs0(boolean debug); + + private native void CompleteDisplay0(long handle); + + private void displayCompleted(long javaObjectAtom, long windowDeleteAtom) { + this.javaObjectAtom=javaObjectAtom; + this.windowDeleteAtom=windowDeleteAtom; + } + private native void DisplayRelease0(long handle, long javaObjectAtom, long windowDeleteAtom); + + private native void DispatchMessages0(long display, long javaObjectAtom, long windowDeleteAtom); + + /** + * 2011/06/14 libX11 1.4.2 and libxcb 1.7 bug 20708 - Multithreading Issues w/ OpenGL, .. + * https://bugs.freedesktop.org/show_bug.cgi?id=20708 + * https://jogamp.org/bugzilla/show_bug.cgi?id=502 + * Affects: Ubuntu 11.04, OpenSuSE 11, .. + * Workaround: Using a separate X11 Display connection for event dispatching (EDT) + */ + private final boolean USE_SEPARATE_DISPLAY_FOR_EDT = true; + + private long edtDisplayHandle; + + /** X11 Window delete atom marker used on EDT */ + private long windowDeleteAtom; + + /** X11 Window java object property used on EDT */ + private long javaObjectAtom; +} + diff --git a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java new file mode 100644 index 000000000..10f6b84da --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java @@ -0,0 +1,357 @@ +/* + * Copyright (c) 2008 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. + * + */ +package jogamp.newt.driver.x11; + +import java.util.List; + +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.Point; + +import jogamp.nativewindow.x11.X11Util; +import jogamp.newt.DisplayImpl; +import jogamp.newt.DisplayImpl.DisplayRunnable; +import jogamp.newt.ScreenImpl; + +import com.jogamp.nativewindow.x11.X11GraphicsDevice; +import com.jogamp.nativewindow.x11.X11GraphicsScreen; +import com.jogamp.newt.ScreenMode; +import com.jogamp.newt.util.ScreenModeUtil; + +public class ScreenDriver extends ScreenImpl { + + static { + DisplayDriver.initSingleton(); + } + + public ScreenDriver() { + } + + protected void createNativeImpl() { + // validate screen index + Long handle = display.runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + public Long run(long dpy) { + return new Long(GetScreen0(dpy, screen_idx)); + } } ); + if (handle.longValue() == 0) { + throw new RuntimeException("Error creating screen: " + screen_idx); + } + aScreen = new X11GraphicsScreen((X11GraphicsDevice) getDisplay().getGraphicsDevice(), screen_idx); + } + + protected void closeNativeImpl() { + } + + private int[] nrotations; + private int nrotation_index; + private int nres_number; + private int nres_index; + private int[] nrates; + private int nrate_index; + private int nmode_number; + + protected int[] getScreenModeFirstImpl() { + return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + public int[] run(long dpy) { + // initialize iterators and static data + nrotations = getAvailableScreenModeRotations0(dpy, screen_idx); + if(null==nrotations || 0==nrotations.length) { + return null; + } + nrotation_index = 0; + + nres_number = getNumScreenModeResolutions0(dpy, screen_idx); + if(0==nres_number) { + return null; + } + nres_index = 0; + + nrates = getScreenModeRates0(dpy, screen_idx, nres_index); + if(null==nrates || 0==nrates.length) { + return null; + } + nrate_index = 0; + + nmode_number = 0; + + return getScreenModeNextImpl(); + } } ); + } + + protected int[] getScreenModeNextImpl() { + // assemble: w x h x bpp x f x r + return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + public int[] run(long dpy) { + /** + System.err.println("******** mode: "+nmode_number); + System.err.println("rot "+nrotation_index); + System.err.println("rate "+nrate_index); + System.err.println("res "+nres_index); */ + + int[] res = getScreenModeResolution0(dpy, screen_idx, nres_index); + if(null==res || 0==res.length) { + return null; + } + if(0>=res[0] || 0>=res[1]) { + throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+nres_index+"/"+nres_number); + } + int rate = nrates[nrate_index]; + if(0>=rate) { + rate = default_sm_rate; + if(DEBUG) { + System.err.println("Invalid rate: "+rate+" at index "+nrate_index+"/"+nrates.length+", using default: "+default_sm_rate); + } + } + int rotation = nrotations[nrotation_index]; + + int[] props = new int[ 1 + ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL ]; + int i = 0; + props[i++] = nres_index; // use resolution index, not unique for native -> ScreenMode + props[i++] = 0; // set later for verification of iterator + props[i++] = res[0]; // width + props[i++] = res[1]; // height + props[i++] = default_sm_bpp; // FIXME + props[i++] = res[2]; // widthmm + props[i++] = res[3]; // heightmm + props[i++] = rate; // rate + props[i++] = rotation; + props[i - ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL] = i - 1; // count without extra element + + nmode_number++; + + // iteration: r -> f -> bpp -> [w x h] + nrotation_index++; + if(nrotation_index == nrotations.length) { + nrotation_index=0; + nrate_index++; + if(null == nrates || nrate_index == nrates.length){ + nres_index++; + if(nres_index == nres_number) { + // done + nrates=null; + nrotations=null; + return null; + } + + nrates = getScreenModeRates0(dpy, screen_idx, nres_index); + if(null==nrates || 0==nrates.length) { + return null; + } + nrate_index = 0; + } + } + + return props; + } } ); + } + + protected ScreenMode getCurrentScreenModeImpl() { + return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + public ScreenMode run(long dpy) { + long screenConfigHandle = getScreenConfiguration0(dpy, screen_idx); + if(0 == screenConfigHandle) { + return null; + } + int[] res; + int rate, rot; + try { + int resNumber = getNumScreenModeResolutions0(dpy, screen_idx); + if(0==resNumber) { + return null; + } + + int resIdx = getCurrentScreenResolutionIndex0(screenConfigHandle); + if(0>resIdx) { + return null; + } + if(resIdx>=resNumber) { + throw new RuntimeException("Invalid resolution index: ! "+resIdx+" < "+resNumber); + } + res = getScreenModeResolution0(dpy, screen_idx, resIdx); + if(null==res || 0==res.length) { + return null; + } + if(0>=res[0] || 0>=res[1]) { + throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+resIdx+"/"+resNumber); + } + rate = getCurrentScreenRate0(screenConfigHandle); + if(0>rate) { + return null; + } + rot = getCurrentScreenRotation0(screenConfigHandle); + if(0>rot) { + return null; + } + } finally { + freeScreenConfiguration0(screenConfigHandle); + } + int[] props = new int[ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL]; + int i = 0; + props[i++] = 0; // set later for verification of iterator + props[i++] = res[0]; // width + props[i++] = res[1]; // height + props[i++] = default_sm_bpp; // FIXME + props[i++] = res[2]; // widthmm + props[i++] = res[3]; // heightmm + props[i++] = rate; // rate + props[i++] = rot; + props[i - ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL] = i; // count + return ScreenModeUtil.streamIn(props, 0); + } } ); + } + + protected boolean setCurrentScreenModeImpl(final ScreenMode screenMode) { + final List screenModes = this.getScreenModesOrig(); + final int screenModeIdx = screenModes.indexOf(screenMode); + if(0>screenModeIdx) { + throw new RuntimeException("ScreenMode not element of ScreenMode list: "+screenMode); + } + final long t0 = System.currentTimeMillis(); + boolean done = runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + public Boolean run(long dpy) { + boolean done = false; + long screenConfigHandle = getScreenConfiguration0(dpy, screen_idx); + if(0 == screenConfigHandle) { + return Boolean.valueOf(done); + } + try { + int resNumber = getNumScreenModeResolutions0(dpy, screen_idx); + int resIdx = getScreenModesIdx2NativeIdx().get(screenModeIdx); + if(0>resIdx || resIdx>=resNumber) { + throw new RuntimeException("Invalid resolution index: ! 0 < "+resIdx+" < "+resNumber+", screenMode["+screenModeIdx+"] "+screenMode); + } + + final int f = screenMode.getMonitorMode().getRefreshRate(); + final int r = screenMode.getRotation(); + + if( setCurrentScreenModeStart0(dpy, screen_idx, screenConfigHandle, resIdx, f, r) ) { + while(!done && System.currentTimeMillis()-t0 < SCREEN_MODE_CHANGE_TIMEOUT) { + done = setCurrentScreenModePollEnd0(dpy, screen_idx, resIdx, f, r); + if(!done) { + try { Thread.sleep(10); } catch (InterruptedException e) { } + } + } + } + } finally { + freeScreenConfiguration0(screenConfigHandle); + } + return Boolean.valueOf(done); + } + }).booleanValue(); + + if(DEBUG || !done) { + System.err.println("X11Screen.setCurrentScreenModeImpl: TO ("+SCREEN_MODE_CHANGE_TIMEOUT+") reached: "+ + (System.currentTimeMillis()-t0)+"ms; Current: "+getCurrentScreenMode()+"; Desired: "+screenMode); + } + return done; + } + + private class XineramaEnabledQuery implements DisplayImpl.DisplayRunnable { + public Boolean run(long dpy) { + return new Boolean(X11Util.XineramaIsEnabled(dpy)); + } + } + private XineramaEnabledQuery xineramaEnabledQuery = new XineramaEnabledQuery(); + + protected int validateScreenIndex(final int idx) { + if(getDisplay().isNativeValid()) { + return runWithLockedDisplayHandle( xineramaEnabledQuery ).booleanValue() ? 0 : idx; + } else { + return runWithTempDisplayHandle( xineramaEnabledQuery ).booleanValue() ? 0 : idx; + } + } + + protected void getVirtualScreenOriginAndSize(final Point virtualOrigin, final Dimension virtualSize) { + display.runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + public Object run(long dpy) { + virtualOrigin.setX(0); + virtualOrigin.setY(0); + virtualSize.setWidth(getWidth0(dpy, screen_idx)); + virtualSize.setHeight(getHeight0(dpy, screen_idx)); + return null; + } } ); + } + + //---------------------------------------------------------------------- + // Internals only + // + private final T runWithLockedDisplayHandle(DisplayRunnable action) { + return display.runWithLockedDisplayHandle(action); + // return runWithTempDisplayHandle(action); + // return runWithoutLock(action); + } + + private final T runWithTempDisplayHandle(DisplayRunnable action) { + final long displayHandle = X11Util.openDisplay(display.getName()); + if(0 == displayHandle) { + throw new RuntimeException("null device"); + } + T res; + try { + res = action.run(displayHandle); + } finally { + X11Util.closeDisplay(displayHandle); + } + return res; + } + private final T runWithoutLock(DisplayRunnable action) { + return action.run(display.getHandle()); + } + + private static native long GetScreen0(long dpy, int scrn_idx); + + private static native int getWidth0(long display, int scrn_idx); + + private static native int getHeight0(long display, int scrn_idx); + + /** @return int[] { rot1, .. } */ + private static native int[] getAvailableScreenModeRotations0(long display, int screen_index); + + private static native int getNumScreenModeResolutions0(long display, int screen_index); + + /** @return int[] { width, height, widthmm, heightmm } */ + private static native int[] getScreenModeResolution0(long display, int screen_index, int mode_index); + + private static native int[] getScreenModeRates0(long display, int screen_index, int mode_index); + + private static native long getScreenConfiguration0(long display, int screen_index); + private static native void freeScreenConfiguration0(long screenConfiguration); + + private static native int getCurrentScreenResolutionIndex0(long screenConfiguration); + private static native int getCurrentScreenRate0(long screenConfiguration); + private static native int getCurrentScreenRotation0(long screenConfiguration); + + /** needs own Display connection for XRANDR event handling */ + private static native boolean setCurrentScreenModeStart0(long display, int screen_index, long screenConfiguration, int mode_index, int freq, int rot); + private static native boolean setCurrentScreenModePollEnd0(long display, int screen_index, int mode_index, int freq, int rot); +} diff --git a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java new file mode 100644 index 000000000..97d1ae3db --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java @@ -0,0 +1,261 @@ +/* + * Copyright (c) 2008 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. + * + */ + +package jogamp.newt.driver.x11; + +import jogamp.nativewindow.x11.X11Lib; +import jogamp.newt.DisplayImpl; +import jogamp.newt.DisplayImpl.DisplayRunnable; +import jogamp.newt.WindowImpl; +import javax.media.nativewindow.*; +import javax.media.nativewindow.VisualIDHolder.VIDType; +import javax.media.nativewindow.util.Insets; +import javax.media.nativewindow.util.InsetsImmutable; +import javax.media.nativewindow.util.Point; + +import com.jogamp.newt.event.MouseEvent; + +public class WindowDriver extends WindowImpl { + private static final String WINDOW_CLASS_NAME = "NewtWindow"; + private static final int X11_WHEEL_ONE_UP_BUTTON = 4; + private static final int X11_WHEEL_ONE_DOWN_BUTTON = 5; + private static final int X11_WHEEL_TWO_UP_BUTTON = 6; + private static final int X11_WHEEL_TWO_DOWN_BUTTON = 7; + + static { + DisplayDriver.initSingleton(); + } + + public WindowDriver() { + } + + protected void createNativeImpl() { + final ScreenDriver screen = (ScreenDriver) getScreen(); + final DisplayDriver display = (DisplayDriver) screen.getDisplay(); + final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice(), capsRequested); + final AbstractGraphicsConfiguration cfg = factory.chooseGraphicsConfiguration( + capsRequested, capsRequested, capabilitiesChooser, screen.getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); + if(DEBUG_IMPLEMENTATION) { + System.err.println("X11Window.createNativeImpl() factory: "+factory+", chosen config: "+cfg); + } + if (null == cfg) { + throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); + } + final int visualID = cfg.getVisualID(VIDType.NATIVE); + if(VisualIDHolder.VID_UNDEFINED == visualID) { + throw new NativeWindowException("Chosen Configuration w/o native visual ID: "+cfg); + } + setGraphicsConfiguration(cfg); + final int flags = getReconfigureFlags(0, true) & + ( FLAG_IS_ALWAYSONTOP | FLAG_IS_UNDECORATED ) ; + setWindowHandle(CreateWindow0(getParentWindowHandle(), + display.getEDTHandle(), screen.getIndex(), visualID, + display.getJavaObjectAtom(), display.getWindowDeleteAtom(), + getX(), getY(), getWidth(), getHeight(), autoPosition(), flags)); + windowHandleClose = getWindowHandle(); + if (0 == windowHandleClose) { + throw new NativeWindowException("Error creating window"); + } + } + + protected void closeNativeImpl() { + if(0!=windowHandleClose && null!=getScreen() ) { + DisplayDriver display = (DisplayDriver) getScreen().getDisplay(); + try { + CloseWindow0(display.getEDTHandle(), windowHandleClose, + display.getJavaObjectAtom(), display.getWindowDeleteAtom()); + } catch (Throwable t) { + if(DEBUG_IMPLEMENTATION) { + Exception e = new Exception("Warning: closeNativeImpl failed - "+Thread.currentThread().getName(), t); + e.printStackTrace(); + } + } finally { + windowHandleClose = 0; + } + } + } + + protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + if(DEBUG_IMPLEMENTATION) { + System.err.println("X11Window reconfig: "+x+"/"+y+" "+width+"x"+height+", "+ + getReconfigureFlagsAsString(null, flags)); + } + if(0 == ( FLAG_IS_UNDECORATED & flags)) { + final InsetsImmutable i = getInsets(); + + // client position -> top-level window position + x -= i.getLeftWidth() ; + y -= i.getTopHeight() ; + } + final DisplayDriver display = (DisplayDriver) getScreen().getDisplay(); + reconfigureWindow0( getDisplayEDTHandle(), getScreenIndex(), + getParentWindowHandle(), getWindowHandle(), display.getWindowDeleteAtom(), + x, y, width, height, flags); + + return true; + } + + protected void reparentNotify(long newParentWindowHandle) { + if(DEBUG_IMPLEMENTATION) { + final long p0 = getParentWindowHandle(); + System.err.println("Window.reparentNotify ("+getThreadName()+"): "+toHexString(p0)+" -> "+toHexString(newParentWindowHandle)); + } + } + + protected void requestFocusImpl(boolean force) { + requestFocus0(getDisplayEDTHandle(), getWindowHandle(), force); + } + + @Override + protected void setTitleImpl(final String title) { + runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + public Object run(long dpy) { + setTitle0(dpy, getWindowHandle(), title); + return null; + } + }); + } + + @Override + protected boolean setPointerVisibleImpl(final boolean pointerVisible) { + return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + public Boolean run(long dpy) { + return Boolean.valueOf(setPointerVisible0(getDisplayEDTHandle(), getWindowHandle(), pointerVisible)); + } + }).booleanValue(); + } + + @Override + protected boolean confinePointerImpl(final boolean confine) { + return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + public Boolean run(long dpy) { + return Boolean.valueOf(confinePointer0(getDisplayEDTHandle(), getWindowHandle(), confine)); + } + }).booleanValue(); + } + + @Override + protected void warpPointerImpl(final int x, final int y) { + runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + public Object run(long dpy) { + warpPointer0(getDisplayEDTHandle(), getWindowHandle(), x, y); + return null; + } + }); + } + + protected Point getLocationOnScreenImpl(final int x, final int y) { + // X11Util.GetRelativeLocation: locks display already ! + return X11Lib.GetRelativeLocation( getScreen().getDisplay().getHandle(), getScreenIndex(), getWindowHandle(), 0 /*root win*/, x, y); + } + + protected void updateInsetsImpl(Insets insets) { + // nop - using event driven insetsChange(..) + } + + protected void doMouseEvent(boolean enqueue, boolean wait, int eventType, int modifiers, + int x, int y, int button, int rotation) { + switch(eventType) { + case MouseEvent.EVENT_MOUSE_PRESSED: + switch(button) { + case X11_WHEEL_ONE_UP_BUTTON: + case X11_WHEEL_ONE_DOWN_BUTTON: + case X11_WHEEL_TWO_UP_BUTTON: + case X11_WHEEL_TWO_DOWN_BUTTON: + // ignore wheel pressed ! + return; + } + break; + case MouseEvent.EVENT_MOUSE_RELEASED: + switch(button) { + case X11_WHEEL_ONE_UP_BUTTON: + eventType = MouseEvent.EVENT_MOUSE_WHEEL_MOVED; + button = 1; + rotation = 1; + break; + case X11_WHEEL_ONE_DOWN_BUTTON: + eventType = MouseEvent.EVENT_MOUSE_WHEEL_MOVED; + button = 1; + rotation = -1; + break; + case X11_WHEEL_TWO_UP_BUTTON: + eventType = MouseEvent.EVENT_MOUSE_WHEEL_MOVED; + button = 2; + rotation = 1; + break; + case X11_WHEEL_TWO_DOWN_BUTTON: + eventType = MouseEvent.EVENT_MOUSE_WHEEL_MOVED; + button = 2; + rotation = -1; + break; + } + break; + } + super.doMouseEvent(enqueue, wait, eventType, modifiers, x, y, button, rotation); + } + + + //---------------------------------------------------------------------- + // Internals only + // + + private static final String getCurrentThreadName() { return Thread.currentThread().getName(); } // Callback for JNI + private static final void dumpStack() { Thread.dumpStack(); } // Callback for JNI + + private final long getDisplayEDTHandle() { + return ((DisplayDriver) getScreen().getDisplay()).getEDTHandle(); + } + private final T runWithLockedDisplayHandle(DisplayRunnable action) { + return ((DisplayImpl) getScreen().getDisplay()).runWithLockedDisplayHandle(action); + // return runWithTempDisplayHandle(action); + } + + protected static native boolean initIDs0(); + + private native long CreateWindow0(long parentWindowHandle, long display, int screen_index, + int visualID, long javaObjectAtom, long windowDeleteAtom, + int x, int y, int width, int height, boolean autoPosition, int flags); + private native void CloseWindow0(long display, long windowHandle, long javaObjectAtom, long windowDeleteAtom); + private native void reconfigureWindow0(long display, int screen_index, long parentWindowHandle, long windowHandle, + long windowDeleteAtom, int x, int y, int width, int height, int flags); + private native void requestFocus0(long display, long windowHandle, boolean force); + + private static native void setTitle0(long display, long windowHandle, String title); + private static native long getParentWindow0(long display, long windowHandle); + private static native boolean setPointerVisible0(long display, long windowHandle, boolean visible); + private static native boolean confinePointer0(long display, long windowHandle, boolean grab); + private static native void warpPointer0(long display, long windowHandle, int x, int y); + + private long windowHandleClose; +} diff --git a/src/newt/classes/jogamp/newt/driver/x11/X11Display.java b/src/newt/classes/jogamp/newt/driver/x11/X11Display.java deleted file mode 100644 index 8243fcf9d..000000000 --- a/src/newt/classes/jogamp/newt/driver/x11/X11Display.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.x11; - -import javax.media.nativewindow.AbstractGraphicsDevice; -import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.NativeWindowFactory; - -import com.jogamp.nativewindow.x11.X11GraphicsDevice; - -import jogamp.nativewindow.x11.X11Util; -import jogamp.newt.DisplayImpl; -import jogamp.newt.NEWTJNILibLoader; - -public class X11Display extends DisplayImpl { - - static { - NEWTJNILibLoader.loadNEWT(); - - if ( !initIDs0(X11Util.XERROR_STACKDUMP) ) { - throw new NativeWindowException("Failed to initialize X11Display jmethodIDs"); - } - - if (!X11Window.initIDs0()) { - throw new NativeWindowException("Failed to initialize X11Window jmethodIDs"); - } - } - - public static void initSingleton() { - // just exist to ensure static init has been run - } - - - public X11Display() { - } - - public String validateDisplayName(String name, long handle) { - return X11Util.validateDisplayName(name, handle); - } - - /** - * {@inheritDoc} - * - * We use a private non-shared X11 Display instance for EDT window operations and one for exposed animation, eg. OpenGL. - *

      - * In case {@link X11Util#HAS_XLOCKDISPLAY_BUG} and {@link X11Util#XINITTHREADS_ALWAYS_ENABLED}, - * we use null locking. Even though this seems not to be rational, it gives most stable results on all platforms. - *

      - *

      - * Otherwise we use basic locking via the constructor {@link X11GraphicsDevice#X11GraphicsDevice(long, int, boolean)}, - * since it is possible to share this device via {@link com.jogamp.newt.NewtFactory#createDisplay(String, boolean)}. - *

      - */ - @SuppressWarnings("unused") - protected void createNativeImpl() { - long handle = X11Util.openDisplay(name); - if( 0 == handle ) { - throw new RuntimeException("Error creating display(Win): "+name); - } - if(USE_SEPARATE_DISPLAY_FOR_EDT) { - edtDisplayHandle = X11Util.openDisplay(name); - if( 0 == edtDisplayHandle ) { - X11Util.closeDisplay(handle); - throw new RuntimeException("Error creating display(EDT): "+name); - } - } else { - edtDisplayHandle = handle; - } - try { - CompleteDisplay0(edtDisplayHandle); - } catch(RuntimeException e) { - closeNativeImpl(); - throw e; - } - - // see API doc above! - if(X11Util.XINITTHREADS_ALWAYS_ENABLED && X11Util.HAS_XLOCKDISPLAY_BUG) { - aDevice = new X11GraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_UNIT, NativeWindowFactory.getNullToolkitLock(), false); - } else { - aDevice = new X11GraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_UNIT, false); - } - } - - protected void closeNativeImpl() { - DisplayRelease0(edtDisplayHandle, javaObjectAtom, windowDeleteAtom); - javaObjectAtom = 0; - windowDeleteAtom = 0; - // closing using ATI driver bug 'same order' - final long handle = getHandle(); - X11Util.closeDisplay(handle); - if(handle != edtDisplayHandle) { - X11Util.closeDisplay(edtDisplayHandle); - } - edtDisplayHandle = 0; - } - - protected void dispatchMessagesNative() { - if(0 != edtDisplayHandle) { - DispatchMessages0(edtDisplayHandle, javaObjectAtom, windowDeleteAtom); - } - } - - protected long getEDTHandle() { return edtDisplayHandle; } - protected long getJavaObjectAtom() { return javaObjectAtom; } - protected long getWindowDeleteAtom() { return windowDeleteAtom; } - - //---------------------------------------------------------------------- - // Internals only - // - private static native boolean initIDs0(boolean debug); - - private native void CompleteDisplay0(long handle); - - private void displayCompleted(long javaObjectAtom, long windowDeleteAtom) { - this.javaObjectAtom=javaObjectAtom; - this.windowDeleteAtom=windowDeleteAtom; - } - private native void DisplayRelease0(long handle, long javaObjectAtom, long windowDeleteAtom); - - private native void DispatchMessages0(long display, long javaObjectAtom, long windowDeleteAtom); - - /** - * 2011/06/14 libX11 1.4.2 and libxcb 1.7 bug 20708 - Multithreading Issues w/ OpenGL, .. - * https://bugs.freedesktop.org/show_bug.cgi?id=20708 - * https://jogamp.org/bugzilla/show_bug.cgi?id=502 - * Affects: Ubuntu 11.04, OpenSuSE 11, .. - * Workaround: Using a separate X11 Display connection for event dispatching (EDT) - */ - private final boolean USE_SEPARATE_DISPLAY_FOR_EDT = true; - - private long edtDisplayHandle; - - /** X11 Window delete atom marker used on EDT */ - private long windowDeleteAtom; - - /** X11 Window java object property used on EDT */ - private long javaObjectAtom; -} - diff --git a/src/newt/classes/jogamp/newt/driver/x11/X11Screen.java b/src/newt/classes/jogamp/newt/driver/x11/X11Screen.java deleted file mode 100644 index 93db854ac..000000000 --- a/src/newt/classes/jogamp/newt/driver/x11/X11Screen.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ -package jogamp.newt.driver.x11; - -import java.util.List; - -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; - -import jogamp.nativewindow.x11.X11Util; -import jogamp.newt.DisplayImpl; -import jogamp.newt.DisplayImpl.DisplayRunnable; -import jogamp.newt.ScreenImpl; - -import com.jogamp.nativewindow.x11.X11GraphicsDevice; -import com.jogamp.nativewindow.x11.X11GraphicsScreen; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.util.ScreenModeUtil; - -public class X11Screen extends ScreenImpl { - - static { - X11Display.initSingleton(); - } - - public X11Screen() { - } - - protected void createNativeImpl() { - // validate screen index - Long handle = display.runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { - public Long run(long dpy) { - return new Long(GetScreen0(dpy, screen_idx)); - } } ); - if (handle.longValue() == 0) { - throw new RuntimeException("Error creating screen: " + screen_idx); - } - aScreen = new X11GraphicsScreen((X11GraphicsDevice) getDisplay().getGraphicsDevice(), screen_idx); - } - - protected void closeNativeImpl() { - } - - private int[] nrotations; - private int nrotation_index; - private int nres_number; - private int nres_index; - private int[] nrates; - private int nrate_index; - private int nmode_number; - - protected int[] getScreenModeFirstImpl() { - return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { - public int[] run(long dpy) { - // initialize iterators and static data - nrotations = getAvailableScreenModeRotations0(dpy, screen_idx); - if(null==nrotations || 0==nrotations.length) { - return null; - } - nrotation_index = 0; - - nres_number = getNumScreenModeResolutions0(dpy, screen_idx); - if(0==nres_number) { - return null; - } - nres_index = 0; - - nrates = getScreenModeRates0(dpy, screen_idx, nres_index); - if(null==nrates || 0==nrates.length) { - return null; - } - nrate_index = 0; - - nmode_number = 0; - - return getScreenModeNextImpl(); - } } ); - } - - protected int[] getScreenModeNextImpl() { - // assemble: w x h x bpp x f x r - return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { - public int[] run(long dpy) { - /** - System.err.println("******** mode: "+nmode_number); - System.err.println("rot "+nrotation_index); - System.err.println("rate "+nrate_index); - System.err.println("res "+nres_index); */ - - int[] res = getScreenModeResolution0(dpy, screen_idx, nres_index); - if(null==res || 0==res.length) { - return null; - } - if(0>=res[0] || 0>=res[1]) { - throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+nres_index+"/"+nres_number); - } - int rate = nrates[nrate_index]; - if(0>=rate) { - rate = default_sm_rate; - if(DEBUG) { - System.err.println("Invalid rate: "+rate+" at index "+nrate_index+"/"+nrates.length+", using default: "+default_sm_rate); - } - } - int rotation = nrotations[nrotation_index]; - - int[] props = new int[ 1 + ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL ]; - int i = 0; - props[i++] = nres_index; // use resolution index, not unique for native -> ScreenMode - props[i++] = 0; // set later for verification of iterator - props[i++] = res[0]; // width - props[i++] = res[1]; // height - props[i++] = default_sm_bpp; // FIXME - props[i++] = res[2]; // widthmm - props[i++] = res[3]; // heightmm - props[i++] = rate; // rate - props[i++] = rotation; - props[i - ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL] = i - 1; // count without extra element - - nmode_number++; - - // iteration: r -> f -> bpp -> [w x h] - nrotation_index++; - if(nrotation_index == nrotations.length) { - nrotation_index=0; - nrate_index++; - if(null == nrates || nrate_index == nrates.length){ - nres_index++; - if(nres_index == nres_number) { - // done - nrates=null; - nrotations=null; - return null; - } - - nrates = getScreenModeRates0(dpy, screen_idx, nres_index); - if(null==nrates || 0==nrates.length) { - return null; - } - nrate_index = 0; - } - } - - return props; - } } ); - } - - protected ScreenMode getCurrentScreenModeImpl() { - return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { - public ScreenMode run(long dpy) { - long screenConfigHandle = getScreenConfiguration0(dpy, screen_idx); - if(0 == screenConfigHandle) { - return null; - } - int[] res; - int rate, rot; - try { - int resNumber = getNumScreenModeResolutions0(dpy, screen_idx); - if(0==resNumber) { - return null; - } - - int resIdx = getCurrentScreenResolutionIndex0(screenConfigHandle); - if(0>resIdx) { - return null; - } - if(resIdx>=resNumber) { - throw new RuntimeException("Invalid resolution index: ! "+resIdx+" < "+resNumber); - } - res = getScreenModeResolution0(dpy, screen_idx, resIdx); - if(null==res || 0==res.length) { - return null; - } - if(0>=res[0] || 0>=res[1]) { - throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+resIdx+"/"+resNumber); - } - rate = getCurrentScreenRate0(screenConfigHandle); - if(0>rate) { - return null; - } - rot = getCurrentScreenRotation0(screenConfigHandle); - if(0>rot) { - return null; - } - } finally { - freeScreenConfiguration0(screenConfigHandle); - } - int[] props = new int[ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL]; - int i = 0; - props[i++] = 0; // set later for verification of iterator - props[i++] = res[0]; // width - props[i++] = res[1]; // height - props[i++] = default_sm_bpp; // FIXME - props[i++] = res[2]; // widthmm - props[i++] = res[3]; // heightmm - props[i++] = rate; // rate - props[i++] = rot; - props[i - ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL] = i; // count - return ScreenModeUtil.streamIn(props, 0); - } } ); - } - - protected boolean setCurrentScreenModeImpl(final ScreenMode screenMode) { - final List screenModes = this.getScreenModesOrig(); - final int screenModeIdx = screenModes.indexOf(screenMode); - if(0>screenModeIdx) { - throw new RuntimeException("ScreenMode not element of ScreenMode list: "+screenMode); - } - final long t0 = System.currentTimeMillis(); - boolean done = runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { - public Boolean run(long dpy) { - boolean done = false; - long screenConfigHandle = getScreenConfiguration0(dpy, screen_idx); - if(0 == screenConfigHandle) { - return Boolean.valueOf(done); - } - try { - int resNumber = getNumScreenModeResolutions0(dpy, screen_idx); - int resIdx = getScreenModesIdx2NativeIdx().get(screenModeIdx); - if(0>resIdx || resIdx>=resNumber) { - throw new RuntimeException("Invalid resolution index: ! 0 < "+resIdx+" < "+resNumber+", screenMode["+screenModeIdx+"] "+screenMode); - } - - final int f = screenMode.getMonitorMode().getRefreshRate(); - final int r = screenMode.getRotation(); - - if( setCurrentScreenModeStart0(dpy, screen_idx, screenConfigHandle, resIdx, f, r) ) { - while(!done && System.currentTimeMillis()-t0 < SCREEN_MODE_CHANGE_TIMEOUT) { - done = setCurrentScreenModePollEnd0(dpy, screen_idx, resIdx, f, r); - if(!done) { - try { Thread.sleep(10); } catch (InterruptedException e) { } - } - } - } - } finally { - freeScreenConfiguration0(screenConfigHandle); - } - return Boolean.valueOf(done); - } - }).booleanValue(); - - if(DEBUG || !done) { - System.err.println("X11Screen.setCurrentScreenModeImpl: TO ("+SCREEN_MODE_CHANGE_TIMEOUT+") reached: "+ - (System.currentTimeMillis()-t0)+"ms; Current: "+getCurrentScreenMode()+"; Desired: "+screenMode); - } - return done; - } - - private class XineramaEnabledQuery implements DisplayImpl.DisplayRunnable { - public Boolean run(long dpy) { - return new Boolean(X11Util.XineramaIsEnabled(dpy)); - } - } - private XineramaEnabledQuery xineramaEnabledQuery = new XineramaEnabledQuery(); - - protected int validateScreenIndex(final int idx) { - if(getDisplay().isNativeValid()) { - return runWithLockedDisplayHandle( xineramaEnabledQuery ).booleanValue() ? 0 : idx; - } else { - return runWithTempDisplayHandle( xineramaEnabledQuery ).booleanValue() ? 0 : idx; - } - } - - protected void getVirtualScreenOriginAndSize(final Point virtualOrigin, final Dimension virtualSize) { - display.runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { - public Object run(long dpy) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(getWidth0(dpy, screen_idx)); - virtualSize.setHeight(getHeight0(dpy, screen_idx)); - return null; - } } ); - } - - //---------------------------------------------------------------------- - // Internals only - // - private final T runWithLockedDisplayHandle(DisplayRunnable action) { - return display.runWithLockedDisplayHandle(action); - // return runWithTempDisplayHandle(action); - // return runWithoutLock(action); - } - - private final T runWithTempDisplayHandle(DisplayRunnable action) { - final long displayHandle = X11Util.openDisplay(display.getName()); - if(0 == displayHandle) { - throw new RuntimeException("null device"); - } - T res; - try { - res = action.run(displayHandle); - } finally { - X11Util.closeDisplay(displayHandle); - } - return res; - } - private final T runWithoutLock(DisplayRunnable action) { - return action.run(display.getHandle()); - } - - private static native long GetScreen0(long dpy, int scrn_idx); - - private static native int getWidth0(long display, int scrn_idx); - - private static native int getHeight0(long display, int scrn_idx); - - /** @return int[] { rot1, .. } */ - private static native int[] getAvailableScreenModeRotations0(long display, int screen_index); - - private static native int getNumScreenModeResolutions0(long display, int screen_index); - - /** @return int[] { width, height, widthmm, heightmm } */ - private static native int[] getScreenModeResolution0(long display, int screen_index, int mode_index); - - private static native int[] getScreenModeRates0(long display, int screen_index, int mode_index); - - private static native long getScreenConfiguration0(long display, int screen_index); - private static native void freeScreenConfiguration0(long screenConfiguration); - - private static native int getCurrentScreenResolutionIndex0(long screenConfiguration); - private static native int getCurrentScreenRate0(long screenConfiguration); - private static native int getCurrentScreenRotation0(long screenConfiguration); - - /** needs own Display connection for XRANDR event handling */ - private static native boolean setCurrentScreenModeStart0(long display, int screen_index, long screenConfiguration, int mode_index, int freq, int rot); - private static native boolean setCurrentScreenModePollEnd0(long display, int screen_index, int mode_index, int freq, int rot); -} diff --git a/src/newt/classes/jogamp/newt/driver/x11/X11Window.java b/src/newt/classes/jogamp/newt/driver/x11/X11Window.java deleted file mode 100644 index 5501f5a3c..000000000 --- a/src/newt/classes/jogamp/newt/driver/x11/X11Window.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright (c) 2008 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. - * - */ - -package jogamp.newt.driver.x11; - -import jogamp.nativewindow.x11.X11Lib; -import jogamp.newt.DisplayImpl; -import jogamp.newt.DisplayImpl.DisplayRunnable; -import jogamp.newt.WindowImpl; -import javax.media.nativewindow.*; -import javax.media.nativewindow.VisualIDHolder.VIDType; -import javax.media.nativewindow.util.Insets; -import javax.media.nativewindow.util.InsetsImmutable; -import javax.media.nativewindow.util.Point; - -import com.jogamp.newt.event.MouseEvent; - -public class X11Window extends WindowImpl { - private static final String WINDOW_CLASS_NAME = "NewtWindow"; - private static final int X11_WHEEL_ONE_UP_BUTTON = 4; - private static final int X11_WHEEL_ONE_DOWN_BUTTON = 5; - private static final int X11_WHEEL_TWO_UP_BUTTON = 6; - private static final int X11_WHEEL_TWO_DOWN_BUTTON = 7; - - static { - X11Display.initSingleton(); - } - - public X11Window() { - } - - protected void createNativeImpl() { - final X11Screen screen = (X11Screen) getScreen(); - final X11Display display = (X11Display) screen.getDisplay(); - final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice(), capsRequested); - final AbstractGraphicsConfiguration cfg = factory.chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, screen.getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); - if(DEBUG_IMPLEMENTATION) { - System.err.println("X11Window.createNativeImpl() factory: "+factory+", chosen config: "+cfg); - } - if (null == cfg) { - throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); - } - final int visualID = cfg.getVisualID(VIDType.NATIVE); - if(VisualIDHolder.VID_UNDEFINED == visualID) { - throw new NativeWindowException("Chosen Configuration w/o native visual ID: "+cfg); - } - setGraphicsConfiguration(cfg); - final int flags = getReconfigureFlags(0, true) & - ( FLAG_IS_ALWAYSONTOP | FLAG_IS_UNDECORATED ) ; - setWindowHandle(CreateWindow0(getParentWindowHandle(), - display.getEDTHandle(), screen.getIndex(), visualID, - display.getJavaObjectAtom(), display.getWindowDeleteAtom(), - getX(), getY(), getWidth(), getHeight(), autoPosition(), flags)); - windowHandleClose = getWindowHandle(); - if (0 == windowHandleClose) { - throw new NativeWindowException("Error creating window"); - } - } - - protected void closeNativeImpl() { - if(0!=windowHandleClose && null!=getScreen() ) { - X11Display display = (X11Display) getScreen().getDisplay(); - try { - CloseWindow0(display.getEDTHandle(), windowHandleClose, - display.getJavaObjectAtom(), display.getWindowDeleteAtom()); - } catch (Throwable t) { - if(DEBUG_IMPLEMENTATION) { - Exception e = new Exception("Warning: closeNativeImpl failed - "+Thread.currentThread().getName(), t); - e.printStackTrace(); - } - } finally { - windowHandleClose = 0; - } - } - } - - protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { - if(DEBUG_IMPLEMENTATION) { - System.err.println("X11Window reconfig: "+x+"/"+y+" "+width+"x"+height+", "+ - getReconfigureFlagsAsString(null, flags)); - } - if(0 == ( FLAG_IS_UNDECORATED & flags)) { - final InsetsImmutable i = getInsets(); - - // client position -> top-level window position - x -= i.getLeftWidth() ; - y -= i.getTopHeight() ; - } - final X11Display display = (X11Display) getScreen().getDisplay(); - reconfigureWindow0( getDisplayEDTHandle(), getScreenIndex(), - getParentWindowHandle(), getWindowHandle(), display.getWindowDeleteAtom(), - x, y, width, height, flags); - - return true; - } - - protected void reparentNotify(long newParentWindowHandle) { - if(DEBUG_IMPLEMENTATION) { - final long p0 = getParentWindowHandle(); - System.err.println("Window.reparentNotify ("+getThreadName()+"): "+toHexString(p0)+" -> "+toHexString(newParentWindowHandle)); - } - } - - protected void requestFocusImpl(boolean force) { - requestFocus0(getDisplayEDTHandle(), getWindowHandle(), force); - } - - @Override - protected void setTitleImpl(final String title) { - runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { - public Object run(long dpy) { - setTitle0(dpy, getWindowHandle(), title); - return null; - } - }); - } - - @Override - protected boolean setPointerVisibleImpl(final boolean pointerVisible) { - return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { - public Boolean run(long dpy) { - return Boolean.valueOf(setPointerVisible0(getDisplayEDTHandle(), getWindowHandle(), pointerVisible)); - } - }).booleanValue(); - } - - @Override - protected boolean confinePointerImpl(final boolean confine) { - return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { - public Boolean run(long dpy) { - return Boolean.valueOf(confinePointer0(getDisplayEDTHandle(), getWindowHandle(), confine)); - } - }).booleanValue(); - } - - @Override - protected void warpPointerImpl(final int x, final int y) { - runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { - public Object run(long dpy) { - warpPointer0(getDisplayEDTHandle(), getWindowHandle(), x, y); - return null; - } - }); - } - - protected Point getLocationOnScreenImpl(final int x, final int y) { - // X11Util.GetRelativeLocation: locks display already ! - return X11Lib.GetRelativeLocation( getScreen().getDisplay().getHandle(), getScreenIndex(), getWindowHandle(), 0 /*root win*/, x, y); - } - - protected void updateInsetsImpl(Insets insets) { - // nop - using event driven insetsChange(..) - } - - protected void doMouseEvent(boolean enqueue, boolean wait, int eventType, int modifiers, - int x, int y, int button, int rotation) { - switch(eventType) { - case MouseEvent.EVENT_MOUSE_PRESSED: - switch(button) { - case X11_WHEEL_ONE_UP_BUTTON: - case X11_WHEEL_ONE_DOWN_BUTTON: - case X11_WHEEL_TWO_UP_BUTTON: - case X11_WHEEL_TWO_DOWN_BUTTON: - // ignore wheel pressed ! - return; - } - break; - case MouseEvent.EVENT_MOUSE_RELEASED: - switch(button) { - case X11_WHEEL_ONE_UP_BUTTON: - eventType = MouseEvent.EVENT_MOUSE_WHEEL_MOVED; - button = 1; - rotation = 1; - break; - case X11_WHEEL_ONE_DOWN_BUTTON: - eventType = MouseEvent.EVENT_MOUSE_WHEEL_MOVED; - button = 1; - rotation = -1; - break; - case X11_WHEEL_TWO_UP_BUTTON: - eventType = MouseEvent.EVENT_MOUSE_WHEEL_MOVED; - button = 2; - rotation = 1; - break; - case X11_WHEEL_TWO_DOWN_BUTTON: - eventType = MouseEvent.EVENT_MOUSE_WHEEL_MOVED; - button = 2; - rotation = -1; - break; - } - break; - } - super.doMouseEvent(enqueue, wait, eventType, modifiers, x, y, button, rotation); - } - - - //---------------------------------------------------------------------- - // Internals only - // - - private static final String getCurrentThreadName() { return Thread.currentThread().getName(); } // Callback for JNI - private static final void dumpStack() { Thread.dumpStack(); } // Callback for JNI - - private final long getDisplayEDTHandle() { - return ((X11Display) getScreen().getDisplay()).getEDTHandle(); - } - private final T runWithLockedDisplayHandle(DisplayRunnable action) { - return ((DisplayImpl) getScreen().getDisplay()).runWithLockedDisplayHandle(action); - // return runWithTempDisplayHandle(action); - } - - protected static native boolean initIDs0(); - - private native long CreateWindow0(long parentWindowHandle, long display, int screen_index, - int visualID, long javaObjectAtom, long windowDeleteAtom, - int x, int y, int width, int height, boolean autoPosition, int flags); - private native void CloseWindow0(long display, long windowHandle, long javaObjectAtom, long windowDeleteAtom); - private native void reconfigureWindow0(long display, int screen_index, long parentWindowHandle, long windowHandle, - long windowDeleteAtom, int x, int y, int width, int height, int flags); - private native void requestFocus0(long display, long windowHandle, boolean force); - - private static native void setTitle0(long display, long windowHandle, String title); - private static native long getParentWindow0(long display, long windowHandle); - private static native boolean setPointerVisible0(long display, long windowHandle, boolean visible); - private static native boolean confinePointer0(long display, long windowHandle, boolean grab); - private static native void warpPointer0(long display, long windowHandle, int x, int y); - - private long windowHandleClose; -} diff --git a/src/newt/native/AndroidWindow.c b/src/newt/native/AndroidWindow.c index fa5765672..94695e1d3 100644 --- a/src/newt/native/AndroidWindow.c +++ b/src/newt/native/AndroidWindow.c @@ -9,7 +9,7 @@ #include #include -#include "jogamp_newt_driver_android_AndroidWindow.h" +#include "jogamp_newt_driver_android_WindowDriver.h" #include #include @@ -23,56 +23,56 @@ #endif -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_android_AndroidWindow_getSurfaceHandle0 +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_android_WindowDriver_getSurfaceHandle0 (JNIEnv *env, jclass clazz, jobject surface) { ANativeWindow * anw = ANativeWindow_fromSurface(env, surface); return (jlong) (intptr_t) anw; } -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_android_AndroidWindow_getSurfaceVisualID0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_android_WindowDriver_getSurfaceVisualID0 (JNIEnv *env, jclass clazz, jlong surfaceHandle) { ANativeWindow * anw = (ANativeWindow *) (intptr_t) surfaceHandle; return (jint) ANativeWindow_getFormat(anw); } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_android_AndroidWindow_setSurfaceVisualID0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_android_WindowDriver_setSurfaceVisualID0 (JNIEnv *env, jclass clazz, jlong surfaceHandle, jint nativeVisualID) { ANativeWindow * anw = (ANativeWindow *) (intptr_t) surfaceHandle; ANativeWindow_setBuffersGeometry(anw, 0, 0, nativeVisualID); } -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_android_AndroidWindow_getWidth0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_android_WindowDriver_getWidth0 (JNIEnv *env, jclass clazz, jlong surfaceHandle) { ANativeWindow * anw = (ANativeWindow *) (intptr_t) surfaceHandle; return (jint) ANativeWindow_getWidth(anw); } -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_android_AndroidWindow_getHeight0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_android_WindowDriver_getHeight0 (JNIEnv *env, jclass clazz, jlong surfaceHandle) { ANativeWindow * anw = (ANativeWindow *) (intptr_t) surfaceHandle; return (jint) ANativeWindow_getHeight(anw); } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_android_AndroidWindow_acquire0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_android_WindowDriver_acquire0 (JNIEnv *env, jclass clazz, jlong surfaceHandle) { ANativeWindow * anw = (ANativeWindow *) (intptr_t) surfaceHandle; ANativeWindow_acquire(anw); } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_android_AndroidWindow_release0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_android_WindowDriver_release0 (JNIEnv *env, jclass clazz, jlong surfaceHandle) { ANativeWindow * anw = (ANativeWindow *) (intptr_t) surfaceHandle; ANativeWindow_release(anw); } -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_android_AndroidWindow_initIDs0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_android_WindowDriver_initIDs0 (JNIEnv *env, jclass clazz) { DBG_PRINT( "initIDs ok\n" ); diff --git a/src/newt/native/IntelGDL.c b/src/newt/native/IntelGDL.c index 690e1123d..a3bf101c5 100644 --- a/src/newt/native/IntelGDL.c +++ b/src/newt/native/IntelGDL.c @@ -37,9 +37,9 @@ #include #include -#include "jogamp_newt_driver_intel_gdl_Display.h" -#include "jogamp_newt_driver_intel_gdl_Screen.h" -#include "jogamp_newt_driver_intel_gdl_Window.h" +#include "jogamp_newt_driver_intel_gdl_DisplayDriver.h" +#include "jogamp_newt_driver_intel_gdl_ScreenDriver.h" +#include "jogamp_newt_driver_intel_gdl_WindowDriver.h" #include "MouseEvent.h" #include "KeyEvent.h" @@ -122,7 +122,7 @@ static void JNI_ThrowNew(JNIEnv *env, const char *throwable, const char* message * Display */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_Display_DispatchMessages +JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_DisplayDriver_DispatchMessages (JNIEnv *env, jobject obj, jlong displayHandle, jobject focusedWindow) { // FIXME: n/a @@ -137,7 +137,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_Display_DispatchMessage } */ } -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_intel_gdl_Display_CreateDisplay +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_intel_gdl_DisplayDriver_CreateDisplay (JNIEnv *env, jobject obj) { gdl_ret_t retval; @@ -170,7 +170,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_intel_gdl_Display_CreateDisplay return (jlong) (intptr_t) p_driver_info; } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_Display_DestroyDisplay +JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_DisplayDriver_DestroyDisplay (JNIEnv *env, jobject obj, jlong displayHandle) { gdl_driver_info_t * p_driver_info = (gdl_driver_info_t *) (intptr_t) displayHandle; @@ -189,7 +189,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_Display_DestroyDisplay * Screen */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_intel_gdl_Screen_initIDs +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_intel_gdl_ScreenDriver_initIDs (JNIEnv *env, jclass clazz) { screenCreatedID = (*env)->GetMethodID(env, clazz, "screenCreated", "(II)V"); @@ -201,7 +201,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_intel_gdl_Screen_initIDs return JNI_TRUE; } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_Screen_GetScreenInfo +JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_ScreenDriver_GetScreenInfo (JNIEnv *env, jobject obj, jlong displayHandle, jint idx) { gdl_driver_info_t * p_driver_info = (gdl_driver_info_t *) (intptr_t) displayHandle; @@ -233,7 +233,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_Screen_GetScreenInfo * Window */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_intel_gdl_Window_initIDs +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_intel_gdl_WindowDriver_initIDs (JNIEnv *env, jclass clazz) { updateBoundsID = (*env)->GetMethodID(env, clazz, "updateBounds", "(IIII)V"); @@ -245,7 +245,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_intel_gdl_Window_initIDs return JNI_TRUE; } -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_intel_gdl_Window_CreateSurface +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_intel_gdl_WindowDriver_CreateSurface (JNIEnv *env, jobject obj, jlong displayHandle, jint scr_width, jint scr_height, jint x, jint y, jint width, jint height) { gdl_driver_info_t * p_driver_info = (gdl_driver_info_t *) (intptr_t) displayHandle; @@ -338,7 +338,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_intel_gdl_Window_CreateSurface return (jlong) (intptr_t) plane; } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_Window_CloseSurface +JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_WindowDriver_CloseSurface (JNIEnv *env, jobject obj, jlong display, jlong surface) { gdl_plane_id_t plane = (gdl_plane_id_t) (intptr_t) surface ; @@ -347,7 +347,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_Window_CloseSurface DBG_PRINT("[CloseSurface] plane %d\n", plane); } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_Window_SetBounds0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_intel_gdl_WindowDriver_SetBounds0 (JNIEnv *env, jobject obj, jlong surface, jint scr_width, jint scr_height, jint x, jint y, jint width, jint height) { gdl_plane_id_t plane = (gdl_plane_id_t) (intptr_t) surface ; diff --git a/src/newt/native/KDWindow.c b/src/newt/native/KDWindow.c index bceb86a85..f1d6aecdf 100644 --- a/src/newt/native/KDWindow.c +++ b/src/newt/native/KDWindow.c @@ -44,7 +44,7 @@ #include #include -#include "jogamp_newt_driver_kd_Window.h" +#include "jogamp_newt_driver_kd_WindowDriver.h" #include "MouseEvent.h" #include "KeyEvent.h" @@ -82,7 +82,7 @@ static jmethodID sendKeyEventID = NULL; * Display */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_Display_DispatchMessages +JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_DisplayDriver_DispatchMessages (JNIEnv *env, jobject obj) { const KDEvent * evt; @@ -180,7 +180,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_Display_DispatchMessages * Window */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_kd_Window_initIDs +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_kd_WindowDriver_initIDs (JNIEnv *env, jclass clazz) { #ifdef VERBOSE_ON @@ -208,7 +208,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_kd_Window_initIDs return JNI_TRUE; } -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_kd_Window_CreateWindow +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_kd_WindowDriver_CreateWindow (JNIEnv *env, jobject obj, jlong display, jlong jeglConfig) { EGLDisplay dpy = (EGLDisplay)(intptr_t)display; @@ -236,7 +236,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_kd_Window_CreateWindow return (jlong) (intptr_t) window; } -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_kd_Window_RealizeWindow +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_kd_WindowDriver_RealizeWindow (JNIEnv *env, jobject obj, jlong window) { KDWindow *w = (KDWindow*) (intptr_t) window; @@ -251,7 +251,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_kd_Window_RealizeWindow return (jlong) (intptr_t) nativeWindow; } -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_kd_Window_CloseWindow +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_kd_WindowDriver_CloseWindow (JNIEnv *env, jobject obj, jlong window, jlong juserData) { KDWindow *w = (KDWindow*) (intptr_t) window; @@ -265,11 +265,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_kd_Window_CloseWindow } /* - * Class: jogamp_newt_driver_kd_Window + * Class: jogamp_newt_driver_kd_WindowDriver * Method: setVisible0 * Signature: (JJZ)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_Window_setVisible0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_WindowDriver_setVisible0 (JNIEnv *env, jobject obj, jlong window, jboolean visible) { KDWindow *w = (KDWindow*) (intptr_t) window; @@ -279,7 +279,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_Window_setVisible0 (*env)->CallVoidMethod(env, obj, visibleChangedID, JNI_FALSE, visible); // FIXME: or defer=true ? } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_Window_setFullScreen0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_WindowDriver_setFullScreen0 (JNIEnv *env, jobject obj, jlong window, jboolean fullscreen) { /** not supported, due to missing NV property .. @@ -296,7 +296,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_Window_setFullScreen0 (void)fullscreen; } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_Window_setSize0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_WindowDriver_setSize0 (JNIEnv *env, jobject obj, jlong window, jint width, jint height) { KDWindow *w = (KDWindow*) (intptr_t) window; diff --git a/src/newt/native/MacWindow.m b/src/newt/native/MacWindow.m index bbadc9dd0..e0330a563 100644 --- a/src/newt/native/MacWindow.m +++ b/src/newt/native/MacWindow.m @@ -33,7 +33,7 @@ #import -#import "jogamp_newt_driver_macosx_MacWindow.h" +#import "jogamp_newt_driver_macosx_WindowDriver.h" #import "NewtMacWindow.h" #import "MouseEvent.h" @@ -155,11 +155,11 @@ NS_ENDHANDLER } /* - * Class: jogamp_newt_driver_macosx_MacDisplay + * Class: jogamp_newt_driver_macosx_DisplayDriver * Method: initIDs * Signature: ()Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacDisplay_initNSApplication0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_DisplayDriver_initNSApplication0 (JNIEnv *env, jclass clazz) { static int initialized = 0; @@ -189,11 +189,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacDisplay_initNSAppli } /* - * Class: jogamp_newt_driver_macosx_MacDisplay + * Class: jogamp_newt_driver_macosx_DisplayDriver * Method: runNSApplication0 * Signature: ()V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacDisplay_runNSApplication0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_DisplayDriver_runNSApplication0 (JNIEnv *env, jclass clazz) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -206,11 +206,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacDisplay_runNSApplicatio } /* - * Class: jogamp_newt_driver_macosx_MacDisplay + * Class: jogamp_newt_driver_macosx_DisplayDriver * Method: stopNSApplication0 * Signature: ()V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacDisplay_stopNSApplication0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_DisplayDriver_stopNSApplication0 (JNIEnv *env, jclass clazz) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -250,11 +250,11 @@ static NSScreen * NewtScreen_getNSScreenByIndex(int screen_idx) { } /* - * Class: jogamp_newt_driver_macosx_MacScreen + * Class: jogamp_newt_driver_macosx_ScreenDriver * Method: getWidthImpl * Signature: (I)I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getWidthImpl0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getWidthImpl0 (JNIEnv *env, jclass clazz, jint screen_idx) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -268,11 +268,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getWidthImpl0 } /* - * Class: jogamp_newt_driver_macosx_MacScreen + * Class: jogamp_newt_driver_macosx_ScreenDriver * Method: getHeightImpl * Signature: (I)I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getHeightImpl0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getHeightImpl0 (JNIEnv *env, jclass clazz, jint screen_idx) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -318,11 +318,11 @@ static long GetDictionaryLong(CFDictionaryRef theDict, const void* key) #define ROTMODES_PER_REALMODE 4 /* - * Class: jogamp_newt_driver_macosx_MacScreen + * Class: jogamp_newt_driver_macosx_ScreenDriver * Method: getScreenSizeMM0 * Signature: (I)[I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getScreenSizeMM0 +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScreenSizeMM0 (JNIEnv *env, jobject obj, jint scrn_idx) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -367,11 +367,11 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getScreenSi } /* - * Class: jogamp_newt_driver_macosx_MacScreen + * Class: jogamp_newt_driver_macosx_ScreenDriver * Method: getScreenMode0 * Signature: (IIII)[I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getScreenMode0 +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScreenMode0 (JNIEnv *env, jobject obj, jint scrn_idx, jint mode_idx, jint widthMM, jint heightMM) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -459,11 +459,11 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getScreenMo } /* - * Class: jogamp_newt_driver_macosx_MacScreen + * Class: jogamp_newt_driver_macosx_ScreenDriver * Method: setScreenMode0 * Signature: (II)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacScreen_setScreenMode0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_setScreenMode0 (JNIEnv *env, jobject object, jint scrn_idx, jint mode_idx) { jboolean res = JNI_TRUE; @@ -504,11 +504,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacScreen_setScreenMod } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: initIDs * Signature: ()Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacWindow_initIDs0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_initIDs0 (JNIEnv *env, jclass clazz) { static int initialized = 0; @@ -519,16 +519,16 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacWindow_initIDs0 jclass c; c = (*env)->FindClass(env, ClazzNamePoint); if(NULL==c) { - NewtCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't find %s", ClazzNamePoint); + NewtCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_WindowDriver_initIDs0: can't find %s", ClazzNamePoint); } pointClz = (jclass)(*env)->NewGlobalRef(env, c); (*env)->DeleteLocalRef(env, c); if(NULL==pointClz) { - NewtCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't use %s", ClazzNamePoint); + NewtCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_WindowDriver_initIDs0: can't use %s", ClazzNamePoint); } pointCstr = (*env)->GetMethodID(env, pointClz, ClazzAnyCstrName, ClazzNamePointCstrSignature); if(NULL==pointCstr) { - NewtCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't fetch %s.%s %s", + NewtCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_WindowDriver_initIDs0: can't fetch %s.%s %s", ClazzNamePoint, ClazzAnyCstrName, ClazzNamePointCstrSignature); } @@ -541,11 +541,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacWindow_initIDs0 } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: createWindow0 * Signature: (JIIIIZIIIJ)J */ -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_MacWindow_createWindow0 +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_createWindow0 (JNIEnv *env, jobject jthis, jlong parent, jint x, jint y, jint w, jint h, jboolean opaque, jboolean fullscreen, jint styleMask, jint bufferingType, jint screen_idx, jlong jview) { @@ -698,11 +698,11 @@ NS_ENDHANDLER /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: close0 * Signature: (J)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_close0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_close0 (JNIEnv *env, jobject unused, jlong window) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -761,11 +761,11 @@ NS_ENDHANDLER } /* - * Class: Java_jogamp_newt_driver_macosx_MacWindow + * Class: Java_jogamp_newt_driver_macosx_WindowDriver * Method: lockSurface0 * Signature: (J)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacWindow_lockSurface0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_lockSurface0 (JNIEnv *env, jclass clazz, jlong window) { NewtMacWindow *mWin = (NewtMacWindow*) ((intptr_t) window); @@ -779,11 +779,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacWindow_lockSurface0 } /* - * Class: Java_jogamp_newt_driver_macosx_MacWindow + * Class: Java_jogamp_newt_driver_macosx_WindowDriver * Method: unlockSurface0 * Signature: (J)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_unlockSurface0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_unlockSurface0 (JNIEnv *env, jclass clazz, jlong window) { NewtMacWindow *mWin = (NewtMacWindow*) ((intptr_t) window); @@ -794,11 +794,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_unlockSurface0 } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: requestFocus0 * Signature: (JZ)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_requestFocus0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_requestFocus0 (JNIEnv *env, jobject window, jlong w, jboolean force) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -819,11 +819,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_requestFocus0 } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: resignFocus0 * Signature: (J)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_resignFocus0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_resignFocus0 (JNIEnv *env, jobject window, jlong w) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -846,11 +846,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_resignFocus0 } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: orderFront0 * Signature: (J)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_orderFront0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_orderFront0 (JNIEnv *env, jobject unused, jlong window) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -866,11 +866,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_orderFront0 } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: orderOut * Signature: (J)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_orderOut0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_orderOut0 (JNIEnv *env, jobject unused, jlong window) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -891,11 +891,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_orderOut0 } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: setTitle0 * Signature: (JLjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_setTitle0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_setTitle0 (JNIEnv *env, jobject unused, jlong window, jstring title) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -913,11 +913,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_setTitle0 } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: contentView * Signature: (J)J */ -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_MacWindow_contentView0 +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_contentView0 (JNIEnv *env, jobject unused, jlong window) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -934,11 +934,11 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_MacWindow_contentView0 } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: changeContentView * Signature: (J)J */ -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_MacWindow_changeContentView0 +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_changeContentView0 (JNIEnv *env, jobject jthis, jlong parentWindowOrView, jlong window, jlong jview) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -977,11 +977,11 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_MacWindow_changeContentVi } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: setContentSize * Signature: (JII)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_setContentSize0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_setContentSize0 (JNIEnv *env, jobject unused, jlong window, jint w, jint h) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -998,11 +998,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_setContentSize0 } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: setFrameTopLeftPoint * Signature: (JJII)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_setFrameTopLeftPoint0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_setFrameTopLeftPoint0 (JNIEnv *env, jobject unused, jlong parent, jlong window, jint x, jint y) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -1027,11 +1027,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_setFrameTopLeftP } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: setAlwaysOnTop0 * Signature: (JZ)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_setAlwaysOnTop0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_setAlwaysOnTop0 (JNIEnv *env, jobject unused, jlong window, jboolean atop) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -1051,11 +1051,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_setAlwaysOnTop0 } /* - * Class: jogamp_newt_driver_macosx_MacWindow + * Class: jogamp_newt_driver_macosx_WindowDriver * Method: getLocationOnScreen0 * Signature: (JII)Ljavax/media/nativewindow/util/Point; */ -JNIEXPORT jobject JNICALL Java_jogamp_newt_driver_macosx_MacWindow_getLocationOnScreen0 +JNIEXPORT jobject JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_getLocationOnScreen0 (JNIEnv *env, jclass unused, jlong win, jint src_x, jint src_y) { NSObject *nsObj = (NSObject*) ((intptr_t) win); @@ -1072,11 +1072,11 @@ JNIEXPORT jobject JNICALL Java_jogamp_newt_driver_macosx_MacWindow_getLocationOn } /* - * Class: Java_jogamp_newt_driver_macosx_MacWindow + * Class: Java_jogamp_newt_driver_macosx_WindowDriver * Method: setPointerVisible0 * Signature: (JZ)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacWindow_setPointerVisible0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_setPointerVisible0 (JNIEnv *env, jclass clazz, jlong window, jboolean hasFocus, jboolean mouseVisible) { NewtMacWindow *mWin = (NewtMacWindow*) ((intptr_t) window); @@ -1086,11 +1086,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacWindow_setPointerVi } /* - * Class: Java_jogamp_newt_driver_macosx_MacWindow + * Class: Java_jogamp_newt_driver_macosx_WindowDriver * Method: confinePointer0 * Signature: (JZ)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacWindow_confinePointer0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_confinePointer0 (JNIEnv *env, jclass clazz, jlong window, jboolean confine) { NewtMacWindow *mWin = (NewtMacWindow*) ((intptr_t) window); @@ -1099,11 +1099,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacWindow_confinePoint } /* - * Class: Java_jogamp_newt_driver_macosx_MacWindow + * Class: Java_jogamp_newt_driver_macosx_WindowDriver * Method: warpPointer0 * Signature: (JJII)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_warpPointer0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_warpPointer0 (JNIEnv *env, jclass clazz, jlong window, jint x, jint y) { NewtMacWindow *mWin = (NewtMacWindow*) ((intptr_t) window); diff --git a/src/newt/native/WindowsWindow.c b/src/newt/native/WindowsWindow.c index 6d9c04dc3..40252f59b 100644 --- a/src/newt/native/WindowsWindow.c +++ b/src/newt/native/WindowsWindow.c @@ -81,9 +81,9 @@ #define DISPLAY_DEVICE_ACTIVE 0x00000001 #endif -#include "jogamp_newt_driver_windows_WindowsDisplay.h" -#include "jogamp_newt_driver_windows_WindowsScreen.h" -#include "jogamp_newt_driver_windows_WindowsWindow.h" +#include "jogamp_newt_driver_windows_DisplayDriver.h" +#include "jogamp_newt_driver_windows_ScreenDriver.h" +#include "jogamp_newt_driver_windows_WindowDriver.h" #include "Window.h" #include "MouseEvent.h" @@ -1011,11 +1011,11 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, } /* - * Class: jogamp_newt_driver_windows_WindowsDisplay + * Class: jogamp_newt_driver_windows_DisplayDriver * Method: DispatchMessages * Signature: ()V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsDisplay_DispatchMessages0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_DisplayDriver_DispatchMessages0 (JNIEnv *env, jclass clazz) { int i = 0; @@ -1040,11 +1040,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsDisplay_DispatchMe } /* - * Class: jogamp_newt_driver_windows_WindowsScreen + * Class: jogamp_newt_driver_windows_ScreenDriver * Method: getOriginX0 * Signature: (I)I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getOriginX0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getOriginX0 (JNIEnv *env, jobject obj, jint scrn_idx) { if( GetSystemMetrics( SM_CMONITORS) > 1) { @@ -1055,11 +1055,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getOriginX0 } /* - * Class: jogamp_newt_driver_windows_WindowsScreen + * Class: jogamp_newt_driver_windows_ScreenDriver * Method: getOriginY0 * Signature: (I)I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getOriginY0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getOriginY0 (JNIEnv *env, jobject obj, jint scrn_idx) { if( GetSystemMetrics( SM_CMONITORS ) > 1) { @@ -1070,11 +1070,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getOriginY0 } /* - * Class: jogamp_newt_driver_windows_WindowsScreen + * Class: jogamp_newt_driver_windows_ScreenDriver * Method: getWidthImpl * Signature: (I)I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getWidthImpl0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getWidthImpl0 (JNIEnv *env, jobject obj, jint scrn_idx) { if( GetSystemMetrics( SM_CMONITORS) > 1) { @@ -1085,11 +1085,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getWidthImp } /* - * Class: jogamp_newt_driver_windows_WindowsScreen + * Class: jogamp_newt_driver_windows_ScreenDriver * Method: getHeightImpl * Signature: (I)I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getHeightImpl0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getHeightImpl0 (JNIEnv *env, jobject obj, jint scrn_idx) { if( GetSystemMetrics( SM_CMONITORS ) > 1) { @@ -1173,11 +1173,11 @@ static HDC NewtScreen_createDisplayDC(LPCTSTR displayDeviceName) { } /* - * Class: jogamp_newt_driver_windows_WindowsScreen + * Class: jogamp_newt_driver_windows_ScreenDriver * Method: getScreenMode0 * Signature: (II)[I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getScreenMode0 +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getScreenMode0 (JNIEnv *env, jobject obj, jint scrn_idx, jint mode_idx) { DISPLAY_DEVICE device; @@ -1246,11 +1246,11 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getScr } /* - * Class: jogamp_newt_driver_windows_WindowsScreen + * Class: jogamp_newt_driver_windows_ScreenDriver * Method: setScreenMode0 * Signature: (IIIIII)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_setScreenMode0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_setScreenMode0 (JNIEnv *env, jobject object, jint scrn_idx, jint width, jint height, jint bits, jint rate, jint rot) { DISPLAY_DEVICE device; @@ -1283,11 +1283,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_setScre } /* - * Class: jogamp_newt_driver_windows_WindowsWindow + * Class: jogamp_newt_driver_windows_WindowDriver * Method: initIDs0 * Signature: ()Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_initIDs0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowDriver_initIDs0 (JNIEnv *env, jclass clazz) { NewtCommon_init(env); @@ -1324,11 +1324,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_initIDs } /* - * Class: jogamp_newt_driver_windows_WindowsWindow + * Class: jogamp_newt_driver_windows_WindowDriver * Method: getNewtWndProc0 * Signature: ()J */ -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_getNewtWndProc0 +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowDriver_getNewtWndProc0 (JNIEnv *env, jclass clazz) { return (jlong) (intptr_t) wndProc; @@ -1366,10 +1366,10 @@ static void NewtWindow_setVisiblePosSize(HWND hwnd, BOOL atop, BOOL visible, } /* - * Class: jogamp_newt_driver_windows_WindowsWindow + * Class: jogamp_newt_driver_windows_WindowDriver * Method: CreateWindow */ -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_CreateWindow0 +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowDriver_CreateWindow0 (JNIEnv *env, jobject obj, jlong hInstance, jstring jWndClassName, jstring jWndName, jlong parent, @@ -1473,11 +1473,11 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_CreateWind } /* - * Class: jogamp_newt_driver_windows_WindowsWindow + * Class: jogamp_newt_driver_windows_WindowDriver * Method: MonitorFromWindow * Signature: (J)J */ -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_MonitorFromWindow0 +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowDriver_MonitorFromWindow0 (JNIEnv *env, jobject obj, jlong window) { #if (_WIN32_WINNT >= 0x0500 || _WIN32_WINDOWS >= 0x0410 || WINVER >= 0x0500) && !defined(_WIN32_WCE) @@ -1506,11 +1506,11 @@ static jboolean NewtWindows_setFullScreen(jboolean fullscreen) } /* - * Class: jogamp_newt_driver_windows_WindowsWindow + * Class: jogamp_newt_driver_windows_WindowDriver * Method: reconfigureWindow0 * Signature: (JJIIIII)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_reconfigureWindow0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowDriver_reconfigureWindow0 (JNIEnv *env, jobject obj, jlong parent, jlong window, jint x, jint y, jint width, jint height, jint flags) { @@ -1591,11 +1591,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_reconfigure } /* - * Class: jogamp_newt_driver_windows_WindowsWindow + * Class: jogamp_newt_driver_windows_WindowDriver * Method: setTitle * Signature: (JLjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_setTitle0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowDriver_setTitle0 (JNIEnv *env, jclass clazz, jlong window, jstring title) { HWND hwnd = (HWND) (intptr_t) window; @@ -1609,11 +1609,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_setTitle0 } /* - * Class: jogamp_newt_driver_windows_WindowsWindow + * Class: jogamp_newt_driver_windows_WindowDriver * Method: requestFocus * Signature: (JZ)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_requestFocus0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowDriver_requestFocus0 (JNIEnv *env, jobject obj, jlong window, jboolean force) { DBG_PRINT("*** WindowsWindow: RequestFocus0\n"); @@ -1621,11 +1621,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_requestFocu } /* - * Class: Java_jogamp_newt_driver_windows_WindowsWindow + * Class: Java_jogamp_newt_driver_windows_WindowDriver * Method: setPointerVisible0 * Signature: (JJZ)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_setPointerVisible0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowDriver_setPointerVisible0 (JNIEnv *env, jclass clazz, jlong window, jboolean mouseVisible) { HWND hwnd = (HWND) (intptr_t) window; @@ -1660,11 +1660,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_setPoin } /* - * Class: Java_jogamp_newt_driver_windows_WindowsWindow + * Class: Java_jogamp_newt_driver_windows_WindowDriver * Method: confinePointer0 * Signature: (JJZIIII)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_confinePointer0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowDriver_confinePointer0 (JNIEnv *env, jclass clazz, jlong window, jboolean confine, jint l, jint t, jint r, jint b) { HWND hwnd = (HWND) (intptr_t) window; @@ -1686,11 +1686,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_confine } /* - * Class: Java_jogamp_newt_driver_windows_WindowsWindow + * Class: Java_jogamp_newt_driver_windows_WindowDriver * Method: warpPointer0 * Signature: (JJII)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_warpPointer0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowDriver_warpPointer0 (JNIEnv *env, jclass clazz, jlong window, jint x, jint y) { DBG_PRINT( "*** WindowsWindow: warpPointer0: %d/%d\n", x, y); @@ -1698,11 +1698,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_warpPointer } /* - * Class: Java_jogamp_newt_driver_windows_WindowsWindow + * Class: Java_jogamp_newt_driver_windows_WindowDriver * Method: trackPointerLeave0 * Signature: (J)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_trackPointerLeave0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowDriver_trackPointerLeave0 (JNIEnv *env, jclass clazz, jlong window) { HWND hwnd = (HWND) (intptr_t) window; diff --git a/src/newt/native/X11Common.h b/src/newt/native/X11Common.h index 982255b8a..128b6b6f1 100644 --- a/src/newt/native/X11Common.h +++ b/src/newt/native/X11Common.h @@ -45,9 +45,9 @@ #include -#include "jogamp_newt_driver_x11_X11Screen.h" -#include "jogamp_newt_driver_x11_X11Display.h" -#include "jogamp_newt_driver_x11_X11Window.h" +#include "jogamp_newt_driver_x11_ScreenDriver.h" +#include "jogamp_newt_driver_x11_DisplayDriver.h" +#include "jogamp_newt_driver_x11_WindowDriver.h" #include "Window.h" #include "MouseEvent.h" diff --git a/src/newt/native/X11Display.c b/src/newt/native/X11Display.c index ce7d9a0e1..3157538c3 100644 --- a/src/newt/native/X11Display.c +++ b/src/newt/native/X11Display.c @@ -34,7 +34,7 @@ jclass X11NewtWindowClazz = NULL; jmethodID insetsChangedID = NULL; jmethodID visibleChangedID = NULL; -static const char * const ClazzNameX11NewtWindow = "jogamp/newt/driver/x11/X11Window"; +static const char * const ClazzNameX11NewtWindow = "jogamp/newt/driver/x11/WindowDriver"; static jmethodID displayCompletedID = NULL; @@ -264,11 +264,11 @@ static jint X11InputState2NewtModifiers(unsigned int xstate) { */ /* - * Class: jogamp_newt_driver_x11_X11Display + * Class: jogamp_newt_driver_x11_DisplayDriver * Method: initIDs * Signature: (Z)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Display_initIDs0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_initIDs0 (JNIEnv *env, jclass clazz, jboolean debug) { jclass c; @@ -281,12 +281,12 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Display_initIDs0 if(NULL==X11NewtWindowClazz) { c = (*env)->FindClass(env, ClazzNameX11NewtWindow); if(NULL==c) { - NewtCommon_FatalError(env, "NEWT X11Window: can't find %s", ClazzNameX11NewtWindow); + NewtCommon_FatalError(env, "NEWT X11Display: can't find %s", ClazzNameX11NewtWindow); } X11NewtWindowClazz = (jclass)(*env)->NewGlobalRef(env, c); (*env)->DeleteLocalRef(env, c); if(NULL==X11NewtWindowClazz) { - NewtCommon_FatalError(env, "NEWT X11Window: can't use %s", ClazzNameX11NewtWindow); + NewtCommon_FatalError(env, "NEWT X11Display: can't use %s", ClazzNameX11NewtWindow); } } @@ -331,11 +331,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Display_initIDs0 } /* - * Class: jogamp_newt_driver_x11_X11Display + * Class: jogamp_newt_driver_x11_DisplayDriver * Method: CompleteDisplay * Signature: (J)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_CompleteDisplay0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_CompleteDisplay0 (JNIEnv *env, jobject obj, jlong display) { Display * dpy = (Display *)(intptr_t)display; @@ -366,11 +366,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_CompleteDisplay0 } /* - * Class: jogamp_newt_driver_x11_X11Display + * Class: jogamp_newt_driver_x11_DisplayDriver * Method: DisplayRelease0 * Signature: (JJJ)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_DisplayRelease0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_DisplayRelease0 (JNIEnv *env, jobject obj, jlong display, jlong javaObjectAtom, jlong windowDeleteAtom) { Display * dpy = (Display *)(intptr_t)display; @@ -390,11 +390,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_DisplayRelease0 } /* - * Class: jogamp_newt_driver_x11_X11Display + * Class: jogamp_newt_driver_x11_DisplayDriver * Method: DispatchMessages * Signature: (JIJJ)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_DispatchMessages0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessages0 (JNIEnv *env, jobject obj, jlong display, jlong javaObjectAtom, jlong windowDeleteAtom) { Display * dpy = (Display *) (intptr_t) display; diff --git a/src/newt/native/X11Screen.c b/src/newt/native/X11Screen.c index 698eed89d..334c39727 100644 --- a/src/newt/native/X11Screen.c +++ b/src/newt/native/X11Screen.c @@ -36,11 +36,11 @@ #endif /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: GetScreen * Signature: (JI)J */ -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Screen_GetScreen0 +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_GetScreen0 (JNIEnv *env, jclass clazz, jlong display, jint screen_index) { Display * dpy = (Display *)(intptr_t)display; @@ -60,14 +60,14 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Screen_GetScreen0 return (jlong) (intptr_t) scrn; } -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getWidth0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_getWidth0 (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) { Display * dpy = (Display *) (intptr_t) display; return (jint) DisplayWidth( dpy, scrn_idx); } -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getHeight0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_getHeight0 (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) { Display * dpy = (Display *) (intptr_t) display; @@ -112,11 +112,11 @@ static int NewtScreen_XRotation2Degree(JNIEnv *env, int xrotation) { } /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: getAvailableScreenModeRotations0 * Signature: (JI)I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getAvailableScreenModeRotations0 +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_getAvailableScreenModeRotations0 (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) { Display *dpy = (Display *) (intptr_t) display; @@ -162,11 +162,11 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getAvailableSc } /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: getNumScreenModeResolution0 * Signature: (JI)I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getNumScreenModeResolutions0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_getNumScreenModeResolutions0 (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) { Display *dpy = (Display *) (intptr_t) display; @@ -177,7 +177,7 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getNumScreenModeRes #endif if(False == NewtScreen_hasRANDR(dpy)) { - DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getNumScreenModeResolutions0: RANDR not available\n"); + DBG_PRINT("Java_jogamp_newt_driver_x11_ScreenDriver_getNumScreenModeResolutions0: RANDR not available\n"); return 0; } @@ -200,17 +200,17 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getNumScreenModeRes } /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: getScreenModeResolutions0 * Signature: (JII)[I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenModeResolution0 +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_getScreenModeResolution0 (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx, jint resMode_idx) { Display *dpy = (Display *) (intptr_t) display; if(False == NewtScreen_hasRANDR(dpy)) { - DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getScreenModeResolution0: RANDR not available\n"); + DBG_PRINT("Java_jogamp_newt_driver_x11_ScreenDriver_getScreenModeResolution0: RANDR not available\n"); return (*env)->NewIntArray(env, 0); } @@ -242,17 +242,17 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenModeR } /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: getScreenModeRates0 * Signature: (JII)[I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenModeRates0 +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_getScreenModeRates0 (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx, jint resMode_idx) { Display *dpy = (Display *) (intptr_t) display; if(False == NewtScreen_hasRANDR(dpy)) { - DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getScreenModeRates0: RANDR not available\n"); + DBG_PRINT("Java_jogamp_newt_driver_x11_ScreenDriver_getScreenModeRates0: RANDR not available\n"); return (*env)->NewIntArray(env, 0); } @@ -285,11 +285,11 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenModeR } /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: getScreenConfiguration0 * Signature: (JI)J */ -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenConfiguration0 +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_getScreenConfiguration0 (JNIEnv *env, jclass clazz, jlong display, jint screen_idx) { Display *dpy = (Display *) (intptr_t) display; @@ -301,7 +301,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenConfigura #endif if(False == NewtScreen_hasRANDR(dpy)) { - DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getScreenConfiguration0: RANDR not available\n"); + DBG_PRINT("Java_jogamp_newt_driver_x11_ScreenDriver_getScreenConfiguration0: RANDR not available\n"); return 0; } #ifdef DBG_PERF @@ -320,22 +320,22 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenConfigura } /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: freeScreenConfiguration0 * Signature: (J)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Screen_freeScreenConfiguration0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_freeScreenConfiguration0 (JNIEnv *env, jclass clazz, jlong screenConfiguration) { XRRFreeScreenConfigInfo( (XRRScreenConfiguration *) (intptr_t) screenConfiguration ); } /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: getCurrentScreenRate0 * Signature: (J)I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenRate0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_getCurrentScreenRate0 (JNIEnv *env, jclass clazz, jlong screenConfiguration) { XRRScreenConfiguration *conf = (XRRScreenConfiguration *) (intptr_t) screenConfiguration; @@ -347,11 +347,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenRat } /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: getCurrentScreenRotation0 * Signature: (J)I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenRotation0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_getCurrentScreenRotation0 (JNIEnv *env, jclass clazz, jlong screenConfiguration) { XRRScreenConfiguration *conf = (XRRScreenConfiguration *) (intptr_t) screenConfiguration; @@ -364,11 +364,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenRot /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: getCurrentScreenResolutionIndex0 * Signature: (J)I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenResolutionIndex0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_getCurrentScreenResolutionIndex0 (JNIEnv *env, jclass clazz, jlong screenConfiguration) { XRRScreenConfiguration *conf = (XRRScreenConfiguration *) (intptr_t) screenConfiguration; @@ -383,11 +383,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenRes } /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: setCurrentScreenModeStart0 * Signature: (JIJIII)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Screen_setCurrentScreenModeStart0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_setCurrentScreenModeStart0 (JNIEnv *env, jclass clazz, jlong display, jint screen_idx, jlong screenConfiguration, jint resMode_idx, jint freq, jint rotation) { Display *dpy = (Display *) (intptr_t) display; @@ -432,11 +432,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Screen_setCurrentScree } /* - * Class: jogamp_newt_driver_x11_X11Screen + * Class: jogamp_newt_driver_x11_ScreenDriver * Method: setCurrentScreenModePollEnd0 * Signature: (J)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Screen_setCurrentScreenModePollEnd0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_setCurrentScreenModePollEnd0 (JNIEnv *env, jclass clazz, jlong display, jint screen_idx, jint resMode_idx, jint freq, jint rotation) { Display *dpy = (Display *) (intptr_t) display; @@ -445,7 +445,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Screen_setCurrentScree XRRScreenChangeNotifyEvent * scn_event = (XRRScreenChangeNotifyEvent *) &evt; if(False == NewtScreen_hasRANDR(dpy)) { - DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_setCurrentScreenModePollEnd0: RANDR not available\n"); + DBG_PRINT("Java_jogamp_newt_driver_x11_ScreenDriver_setCurrentScreenModePollEnd0: RANDR not available\n"); return JNI_FALSE; } diff --git a/src/newt/native/X11Window.c b/src/newt/native/X11Window.c index daf9f2b53..59862f463 100644 --- a/src/newt/native/X11Window.c +++ b/src/newt/native/X11Window.c @@ -467,11 +467,11 @@ static void NewtWindows_requestFocus (JNIEnv *env, jobject window, Display *dpy, */ /* - * Class: jogamp_newt_driver_x11_X11Window + * Class: jogamp_newt_driver_x11_WindowDriver * Method: initIDs * Signature: ()Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Window_initIDs0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_WindowDriver_initIDs0 (JNIEnv *env, jclass clazz) { return JNI_TRUE; @@ -505,10 +505,10 @@ static void NewtWindows_setPosSize(Display *dpy, Window w, jint x, jint y, jint } /* - * Class: jogamp_newt_driver_x11_X11Window + * Class: jogamp_newt_driver_x11_WindowDriver * Method: CreateWindow */ -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Window_CreateWindow0 +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CreateWindow0 (JNIEnv *env, jobject obj, jlong parent, jlong display, jint screen_index, jint visualID, jlong javaObjectAtom, jlong windowDeleteAtom, @@ -666,11 +666,11 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Window_CreateWindow0 } /* - * Class: jogamp_newt_driver_x11_X11Window + * Class: jogamp_newt_driver_x11_WindowDriver * Method: CloseWindow * Signature: (JJ)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_CloseWindow0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CloseWindow0 (JNIEnv *env, jobject obj, jlong display, jlong window, jlong javaObjectAtom, jlong windowDeleteAtom) { Display * dpy = (Display *) (intptr_t) display; @@ -703,7 +703,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_CloseWindow0 NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); // Drain all events related to this window .. - Java_jogamp_newt_driver_x11_X11Display_DispatchMessages0(env, obj, display, javaObjectAtom, windowDeleteAtom); + Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessages0(env, obj, display, javaObjectAtom, windowDeleteAtom); XDestroyWindow(dpy, w); XSync(dpy, False); @@ -729,11 +729,11 @@ static Bool WaitForReparentNotify( Display *dpy, XEvent *event, XPointer arg ) { */ /* - * Class: jogamp_newt_driver_x11_X11Window + * Class: jogamp_newt_driver_x11_WindowDriver * Method: reconfigureWindow0 * Signature: (JIJJIIIII)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_reconfigureWindow0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_reconfigureWindow0 (JNIEnv *env, jobject obj, jlong jdisplay, jint screen_index, jlong jparent, jlong jwindow, jlong windowDeleteAtom, jint x, jint y, jint width, jint height, jint flags) @@ -869,33 +869,33 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_reconfigureWindow0 } /* - * Class: jogamp_newt_driver_x11_X11Window + * Class: jogamp_newt_driver_x11_WindowDriver * Method: requestFocus0 * Signature: (JJZ)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_requestFocus0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_requestFocus0 (JNIEnv *env, jobject obj, jlong display, jlong window, jboolean force) { NewtWindows_requestFocus ( env, obj, (Display *) (intptr_t) display, (Window)window, force ) ; } /* - * Class: jogamp_newt_driver_x11_X11Window + * Class: jogamp_newt_driver_x11_WindowDriver * Method: getParentWindow0 * Signature: (JJ)J */ -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Window_getParentWindow0 +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_WindowDriver_getParentWindow0 (JNIEnv *env, jclass clazz, jlong display, jlong window) { return (jlong) NewtWindows_getParent ((Display *) (intptr_t) display, (Window)window); } /* - * Class: Java_jogamp_newt_driver_x11_X11Window + * Class: Java_jogamp_newt_driver_x11_WindowDriver * Method: setTitle0 * Signature: (JJLjava/lang/String;)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_setTitle0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_setTitle0 (JNIEnv *env, jclass clazz, jlong display, jlong window, jstring title) { Display * dpy = (Display *) (intptr_t) display; @@ -942,11 +942,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_setTitle0 } /* - * Class: Java_jogamp_newt_driver_x11_X11Window + * Class: Java_jogamp_newt_driver_x11_WindowDriver * Method: setPointerVisible0 * Signature: (JJZ)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Window_setPointerVisible0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_WindowDriver_setPointerVisible0 (JNIEnv *env, jclass clazz, jlong display, jlong window, jboolean mouseVisible) { static char noData[] = { 0,0,0,0,0,0,0,0 }; @@ -976,11 +976,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Window_setPointerVisib } /* - * Class: Java_jogamp_newt_driver_x11_X11Window + * Class: Java_jogamp_newt_driver_x11_WindowDriver * Method: confinePointer0 * Signature: (JJZ)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Window_confinePointer0 +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_WindowDriver_confinePointer0 (JNIEnv *env, jclass clazz, jlong display, jlong window, jboolean confine) { Display * dpy = (Display *) (intptr_t) display; @@ -999,11 +999,11 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Window_confinePointer0 } /* - * Class: Java_jogamp_newt_driver_x11_X11Window + * Class: Java_jogamp_newt_driver_x11_WindowDriver * Method: warpPointer0 * Signature: (JJII)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_warpPointer0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_warpPointer0 (JNIEnv *env, jclass clazz, jlong display, jlong window, jint x, jint y) { Display * dpy = (Display *) (intptr_t) display; diff --git a/src/newt/native/bcm_egl.c b/src/newt/native/bcm_egl.c index 79ebd20e0..9b960d278 100644 --- a/src/newt/native/bcm_egl.c +++ b/src/newt/native/bcm_egl.c @@ -37,7 +37,7 @@ #include #include -#include "jogamp_newt_driver_bcm_egl_Window.h" +#include "jogamp_newt_driver_bcm_egl_WindowDriver.h" #include "MouseEvent.h" #include "KeyEvent.h" @@ -67,7 +67,7 @@ static jmethodID windowCreatedID = NULL; * Display */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_egl_Display_DispatchMessages +JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_egl_DisplayDriver_DispatchMessages (JNIEnv *env, jobject obj) { // FIXME: n/a @@ -75,7 +75,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_egl_Display_DispatchMessages (void) obj; } -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_bcm_egl_Display_CreateDisplay +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_bcm_egl_DisplayDriver_CreateDisplay (JNIEnv *env, jobject obj, jint width, jint height) { (void) env; @@ -89,7 +89,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_bcm_egl_Display_CreateDisplay return (jlong) (intptr_t) dpy; } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_egl_Display_DestroyDisplay +JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_egl_DisplayDriver_DestroyDisplay (JNIEnv *env, jobject obj, jlong display) { EGLDisplay dpy = (EGLDisplay)(intptr_t)display; @@ -106,7 +106,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_egl_Display_DestroyDisplay * Window */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_egl_Window_initIDs +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_egl_WindowDriver_initIDs (JNIEnv *env, jclass clazz) { windowCreatedID = (*env)->GetMethodID(env, clazz, "windowCreated", "(III)V"); @@ -118,7 +118,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_egl_Window_initIDs return JNI_TRUE; } -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_bcm_egl_Window_CreateWindow +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_bcm_egl_WindowDriver_CreateWindow (JNIEnv *env, jobject obj, jlong display, jboolean chromaKey, jint width, jint height) { EGLDisplay dpy = (EGLDisplay)(intptr_t)display; @@ -162,7 +162,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_bcm_egl_Window_CreateWindow return (jlong) (intptr_t) window; } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_egl_Window_CloseWindow +JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_egl_WindowDriver_CloseWindow (JNIEnv *env, jobject obj, jlong display, jlong window) { EGLDisplay dpy = (EGLDisplay) (intptr_t) display; @@ -175,7 +175,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_egl_Window_CloseWindow DBG_PRINT( "[CloseWindow] X\n"); } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_egl_Window_SwapWindow +JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_egl_WindowDriver_SwapWindow (JNIEnv *env, jobject obj, jlong display, jlong window) { EGLDisplay dpy = (EGLDisplay) (intptr_t) display; diff --git a/src/newt/native/bcm_vc_iv.c b/src/newt/native/bcm_vc_iv.c index 09ab8a634..e41745e14 100644 --- a/src/newt/native/bcm_vc_iv.c +++ b/src/newt/native/bcm_vc_iv.c @@ -32,9 +32,9 @@ #include "bcm_vc_iv.h" -#include "jogamp_newt_driver_bcm_vc_iv_Display.h" -#include "jogamp_newt_driver_bcm_vc_iv_Screen.h" -#include "jogamp_newt_driver_bcm_vc_iv_Window.h" +#include "jogamp_newt_driver_bcm_vc_iv_DisplayDriver.h" +#include "jogamp_newt_driver_bcm_vc_iv_ScreenDriver.h" +#include "jogamp_newt_driver_bcm_vc_iv_WindowDriver.h" #define VERBOSE_ON 1 @@ -57,7 +57,7 @@ static jmethodID sendKeyEventID = NULL; * Display */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Display_initIDs +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_vc_iv_DisplayDriver_initIDs (JNIEnv *env, jclass clazz) { bcm_host_init(); @@ -66,7 +66,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Display_initIDs return JNI_TRUE; } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Display_DispatchMessages +JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_DisplayDriver_DispatchMessages (JNIEnv *env, jobject obj) { } @@ -75,7 +75,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Display_DispatchMessage * Screen */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Screen_initIDs +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_vc_iv_ScreenDriver_initIDs (JNIEnv *env, jclass clazz) { uint32_t screen_width; @@ -91,7 +91,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Screen_initIDs return JNI_TRUE; } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Screen_initNative +JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_ScreenDriver_initNative (JNIEnv *env, jobject obj) { uint32_t screen_width; @@ -109,7 +109,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Screen_initNative * Window */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Window_initIDs +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_vc_iv_WindowDriver_initIDs (JNIEnv *env, jclass clazz) { windowCreatedID = (*env)->GetMethodID(env, clazz, "windowCreated", "(J)V"); @@ -131,7 +131,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Window_initIDs return JNI_TRUE; } -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Window_CreateWindow +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_bcm_vc_iv_WindowDriver_CreateWindow (JNIEnv *env, jobject obj, jint width, jint height) { int32_t success = 0; @@ -166,13 +166,13 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Window_CreateWindow return (jlong) (intptr_t) nativeWindowPtr; } -JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Window_RealizeWindow +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_bcm_vc_iv_WindowDriver_RealizeWindow (JNIEnv *env, jobject obj, jlong window) { return (jlong) (intptr_t) 0; } -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Window_CloseWindow +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_bcm_vc_iv_WindowDriver_CloseWindow (JNIEnv *env, jobject obj, jlong window, jlong juserData) { EGL_DISPMANX_WINDOW_T * nativeWindowPtr = (EGL_DISPMANX_WINDOW_T *) (intptr_t) window ; @@ -181,21 +181,21 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Window_CloseWindow } /* - * Class: jogamp_newt_driver_bcm_vc_iv_Window + * Class: jogamp_newt_driver_bcm_vc_iv_WindowDriver * Method: setVisible0 * Signature: (JJZ)V */ -JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Window_setVisible0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_WindowDriver_setVisible0 (JNIEnv *env, jobject obj, jlong window, jboolean visible) { } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Window_setFullScreen0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_WindowDriver_setFullScreen0 (JNIEnv *env, jobject obj, jlong window, jboolean fullscreen) { } -JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_Window_setSize0 +JNIEXPORT void JNICALL Java_jogamp_newt_driver_bcm_vc_iv_WindowDriver_setSize0 (JNIEnv *env, jobject obj, jlong window, jint width, jint height) { // FIXME RESIZE (*env)->CallVoidMethod(env, obj, sizeChangedID, JNI_FALSE, (jint) width, (jint) height, JNI_FALSE); diff --git a/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity0.java b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity0.java index 11babf187..89395e309 100644 --- a/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity0.java +++ b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity0.java @@ -34,11 +34,11 @@ import java.util.Arrays; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLProfile; -import jogamp.newt.driver.android.AndroidWindow; import jogamp.newt.driver.android.NewtBaseActivity; import com.jogamp.common.util.IOUtil; import com.jogamp.newt.NewtFactory; +import com.jogamp.newt.Window; import com.jogamp.newt.event.MouseAdapter; import com.jogamp.newt.event.MouseEvent; import com.jogamp.newt.opengl.GLWindow; @@ -55,8 +55,8 @@ public class MovieSimpleActivity0 extends NewtBaseActivity { MouseAdapter toFrontMouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { Object src = e.getSource(); - if(src instanceof AndroidWindow) { - ((AndroidWindow)src).requestFocus(false); + if(src instanceof Window) { + ((Window)src).requestFocus(false); } } }; diff --git a/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity1.java b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity1.java index a5e5f4ccb..a7fefd838 100644 --- a/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity1.java +++ b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity1.java @@ -36,11 +36,11 @@ import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLProfile; import javax.media.opengl.GLRunnable; -import jogamp.newt.driver.android.AndroidWindow; import jogamp.newt.driver.android.NewtBaseActivity; import com.jogamp.common.util.IOUtil; import com.jogamp.newt.NewtFactory; +import com.jogamp.newt.Window; import com.jogamp.newt.event.MouseAdapter; import com.jogamp.newt.event.MouseEvent; import com.jogamp.newt.opengl.GLWindow; @@ -59,8 +59,8 @@ public class MovieSimpleActivity1 extends NewtBaseActivity { MouseAdapter toFrontMouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { Object src = e.getSource(); - if(src instanceof AndroidWindow) { - ((AndroidWindow)src).requestFocus(false); + if(src instanceof Window) { + ((Window)src).requestFocus(false); } } }; @@ -121,7 +121,7 @@ public class MovieSimpleActivity1 extends NewtBaseActivity { final GLWindow glWindowMain = GLWindow.create(scrn, capsMain); { final int padding = mPlayerHUD ? 32 : 0; - final android.view.View androidView = ((AndroidWindow)glWindowMain.getDelegatedWindow()).getAndroidView(); + final android.view.View androidView = ((jogamp.newt.driver.android.WindowDriver)glWindowMain.getDelegatedWindow()).getAndroidView(); glWindowMain.setSize(scrn.getWidth()-padding, scrn.getHeight()-padding); glWindowMain.setUndecorated(true); // setContentView(getWindow(), glWindowMain); @@ -168,7 +168,7 @@ public class MovieSimpleActivity1 extends NewtBaseActivity { viewGroup.post(new Runnable() { public void run() { - final android.view.View androidView = ((AndroidWindow)glWindowHUD.getDelegatedWindow()).getAndroidView(); + final android.view.View androidView = ((jogamp.newt.driver.android.WindowDriver)glWindowHUD.getDelegatedWindow()).getAndroidView(); // addContentView(getWindow(), glWindowHUD, new android.view.ViewGroup.LayoutParams(glWindowHUD.getWidth(), glWindowHUD.getHeight())); viewGroup.addView(androidView, new android.widget.FrameLayout.LayoutParams(glWindowHUD.getWidth(), glWindowHUD.getHeight(), Gravity.TOP|Gravity.LEFT)); registerNEWTWindow(glWindowHUD); -- cgit v1.2.3 From c5835a2e19a84cb08957d6c742e4334d578c3c66 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 18 Aug 2012 14:52:32 +0200 Subject: NativeWindowFactory.getNativeWindowType(..): Return canonical string representation allowing proper use of ref. comparison '==', instead of 'String.equals()' Also make NativeWindowFactory's instances of nativeWindowingTypePure and nativeWindowingTypeCustom static final. --- .../com/jogamp/opengl/util/texture/Texture.java | 2 +- .../javax/media/opengl/GLDrawableFactory.java | 14 ++--- src/jogl/classes/jogamp/opengl/ThreadingImpl.java | 3 +- .../classes/jogamp/opengl/egl/EGLDisplayUtil.java | 2 +- .../jogamp/opengl/egl/EGLDrawableFactory.java | 2 +- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 36 ++++++----- .../nativewindow/GraphicsConfigurationFactory.java | 2 +- .../media/nativewindow/NativeWindowFactory.java | 72 +++++++++++----------- .../nativewindow/NativeWindowFactoryImpl.java | 11 ++-- .../jogamp/nativewindow/jawt/JAWTJNILibLoader.java | 2 +- 10 files changed, 76 insertions(+), 70 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java b/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java index e7bf87a36..15dd19ea9 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java @@ -1089,7 +1089,7 @@ public class Texture { // Prefer GL_ARB_texture_rectangle on ATI hardware on Mac OS X // due to software fallbacks - if (NativeWindowFactory.TYPE_MACOSX.equals(NativeWindowFactory.getNativeWindowType(false))) { + if (NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false)) { String vendor = gl.glGetString(GL.GL_VENDOR); if (vendor != null && vendor.startsWith("ATI")) { return true; diff --git a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java index 9a0d2cb99..fbdc51022 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java @@ -123,16 +123,16 @@ public abstract class GLDrawableFactory { private static final void initSingletonImpl() { registerFactoryShutdownHook(); - final String nativeOSType = NativeWindowFactory.getNativeWindowType(true); + final String nwt = NativeWindowFactory.getNativeWindowType(true); GLDrawableFactory tmp = null; String factoryClassName = Debug.getProperty("jogl.gldrawablefactory.class.name", true); ClassLoader cl = GLDrawableFactory.class.getClassLoader(); if (null == factoryClassName) { - if ( nativeOSType.equals(NativeWindowFactory.TYPE_X11) ) { + if ( nwt == NativeWindowFactory.TYPE_X11 ) { factoryClassName = "jogamp.opengl.x11.glx.X11GLXDrawableFactory"; - } else if ( nativeOSType.equals(NativeWindowFactory.TYPE_WINDOWS) ) { + } else if ( nwt == NativeWindowFactory.TYPE_WINDOWS ) { factoryClassName = "jogamp.opengl.windows.wgl.WindowsWGLDrawableFactory"; - } else if ( nativeOSType.equals(NativeWindowFactory.TYPE_MACOSX) ) { + } else if ( nwt == NativeWindowFactory.TYPE_MACOSX ) { if(ReflectionUtil.isClassAvailable(macosxFactoryClassNameAWTCGL, cl)) { factoryClassName = macosxFactoryClassNameAWTCGL; } else { @@ -141,19 +141,19 @@ public abstract class GLDrawableFactory { } else { // may use egl*Factory .. if (GLProfile.DEBUG) { - System.err.println("GLDrawableFactory.static - No native OS Factory for: "+nativeOSType+"; May use EGLDrawableFactory, if available." ); + System.err.println("GLDrawableFactory.static - No native Windowing Factory for: "+nwt+"; May use EGLDrawableFactory, if available." ); } } } if (null != factoryClassName) { if (GLProfile.DEBUG) { - System.err.println("GLDrawableFactory.static - Native OS Factory for: "+nativeOSType+": "+factoryClassName); + System.err.println("GLDrawableFactory.static - Native OS Factory for: "+nwt+": "+factoryClassName); } try { tmp = (GLDrawableFactory) ReflectionUtil.createInstance(factoryClassName, cl); } catch (JogampRuntimeException jre) { if (GLProfile.DEBUG) { - System.err.println("Info: GLDrawableFactory.static - Native Platform: "+nativeOSType+" - not available: "+factoryClassName); + System.err.println("Info: GLDrawableFactory.static - Native Platform: "+nwt+" - not available: "+factoryClassName); jre.printStackTrace(); } } diff --git a/src/jogl/classes/jogamp/opengl/ThreadingImpl.java b/src/jogl/classes/jogamp/opengl/ThreadingImpl.java index 61a47675f..d55a2c976 100644 --- a/src/jogl/classes/jogamp/opengl/ThreadingImpl.java +++ b/src/jogl/classes/jogamp/opengl/ThreadingImpl.java @@ -89,8 +89,7 @@ public class ThreadingImpl { // problems. hasAWT = GLProfile.isAWTAvailable(); - String osType = NativeWindowFactory.getNativeWindowType(false); - _isX11 = NativeWindowFactory.TYPE_X11.equals(osType); + _isX11 = NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false); // default setting singleThreaded = true; diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java index dbf35d68c..18d2f830d 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java @@ -228,7 +228,7 @@ public class EGLDisplayUtil { */ public static EGLGraphicsDevice eglCreateEGLGraphicsDevice(NativeSurface surface) { final long nativeDisplayID; - if( NativeWindowFactory.TYPE_WINDOWS.equals(NativeWindowFactory.getNativeWindowType(false)) ) { + if( NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false) ) { nativeDisplayID = surface.getSurfaceHandle(); // don't even ask .. } else { nativeDisplayID = surface.getDisplayHandle(); // 0 == EGL.EGL_DEFAULT_DISPLAY diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index 50b480210..f2e836e3c 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -103,7 +103,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { EGLGraphicsConfigurationFactory.registerFactory(); // Check for other underlying stuff .. - if(NativeWindowFactory.TYPE_X11.equals(NativeWindowFactory.getNativeWindowType(true))) { + if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(true)) { try { ReflectionUtil.createInstance("jogamp.opengl.x11.glx.X11GLXGraphicsConfigurationFactory", EGLDrawableFactory.class.getClassLoader()); } catch (JogampRuntimeException jre) { /* n/a .. */ } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index ba07d97dc..1cc796086 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -83,7 +83,9 @@ public class SWTAccessor { static { Field f = null; - if(NativeWindowFactory.TYPE_MACOSX != NativeWindowFactory.getNativeWindowType(false) ) { + final String nwt = NativeWindowFactory.getNativeWindowType(false); + + if(NativeWindowFactory.TYPE_MACOSX != nwt ) { try { f = Control.class.getField(str_handle); } catch (Exception ex) { @@ -124,7 +126,7 @@ public class SWTAccessor { Class c=null; Method m1=null, m2=null, m3=null, m4=null, m5=null; Class handleType = swt_uses_long_handles ? long.class : int.class ; - if( NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false) ) { + if( NativeWindowFactory.TYPE_X11 == nwt ) { try { c = ReflectionUtil.getClass(str_OS_gtk_class, false, SWTAccessor.class.getClassLoader()); m1 = c.getDeclaredMethod(str_gtk_widget_realize, handleType); @@ -210,33 +212,36 @@ public class SWTAccessor { long displayHandle = callStaticMethodL2L(OS_gdk_x11_drawable_get_xdisplay, widgedHandle); return new X11GraphicsDevice(displayHandle, AbstractGraphicsDevice.DEFAULT_UNIT, false); } - if( NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false) ) { + final String nwt = NativeWindowFactory.getNativeWindowType(false); + if( NativeWindowFactory.TYPE_WINDOWS == nwt ) { return new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); } - if( NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false) ) { + if( NativeWindowFactory.TYPE_MACOSX == nwt ) { return new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); } - throw new UnsupportedOperationException("n/a for this windowing system: "+NativeWindowFactory.getNativeWindowType(false)); + throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } public static AbstractGraphicsScreen getScreen(AbstractGraphicsDevice device, int screen) { if( null != OS_gtk_class ) { return new X11GraphicsScreen((X11GraphicsDevice)device, screen); - } - if( NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false) || - NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false) ) { + } + final String nwt = NativeWindowFactory.getNativeWindowType(false); + if( NativeWindowFactory.TYPE_WINDOWS == nwt || + NativeWindowFactory.TYPE_MACOSX == nwt ) { return new DefaultGraphicsScreen(device, screen); } - throw new UnsupportedOperationException("n/a for this windowing system: "+NativeWindowFactory.getNativeWindowType(false)); + throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } public static int getNativeVisualID(AbstractGraphicsDevice device, long windowHandle) { if( null != OS_gtk_class ) { return X11Lib.GetVisualIDFromWindow(device.getHandle(), windowHandle); } - if( NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false) || - NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false) ) { + final String nwt = NativeWindowFactory.getNativeWindowType(false); + if( NativeWindowFactory.TYPE_WINDOWS == nwt || + NativeWindowFactory.TYPE_MACOSX == nwt ) { return VisualIDHolder.VID_UNDEFINED; } - throw new UnsupportedOperationException("n/a for this windowing system: "+NativeWindowFactory.getNativeWindowType(false)); + throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } public static long getWindowHandle(Control swtControl) { @@ -245,11 +250,12 @@ public class SWTAccessor { long widgedHandle = callStaticMethodL2L(OS_GTK_WIDGET_WINDOW, handle); return callStaticMethodL2L(OS_gdk_x11_drawable_get_xid, widgedHandle); } - if( NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false) || - NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false) ) { + final String nwt = NativeWindowFactory.getNativeWindowType(false); + if( NativeWindowFactory.TYPE_WINDOWS == nwt || + NativeWindowFactory.TYPE_MACOSX == nwt ) { return handle; } - throw new UnsupportedOperationException("n/a for this windowing system: "+NativeWindowFactory.getNativeWindowType(false)); + throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } public static long newGC(final Control swtControl, final GCData gcData) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java index c3fdc6798..9694f2491 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java @@ -129,7 +129,7 @@ public abstract class GraphicsConfigurationFactory { // well as X11GraphicsDevices in non-AWT situations) registerFactory(defaultDeviceCapsType.deviceType, defaultDeviceCapsType.capsType, new DefaultGraphicsConfigurationFactoryImpl()); - if (NativeWindowFactory.TYPE_X11.equals(NativeWindowFactory.getNativeWindowType(true))) { + if (NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(true)) { try { ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.X11GraphicsConfigurationFactory", "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader()); diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 867d0733b..afcd0a008 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -56,33 +56,34 @@ import com.jogamp.common.util.ReflectionUtil; public abstract class NativeWindowFactory { protected static final boolean DEBUG; - /** OpenKODE/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}*/ - public static final String TYPE_EGL = "jogamp.newt.driver.kd"; + /** OpenKODE/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}.*/ + public static final String TYPE_EGL = "jogamp.newt.driver.kd".intern(); - /** Microsoft Windows type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_WINDOWS = "jogamp.newt.driver.windows"; + /** Microsoft Windows type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_WINDOWS = "jogamp.newt.driver.windows".intern(); - /** X11 type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_X11 = "jogamp.newt.driver.x11"; + /** X11 type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_X11 = "jogamp.newt.driver.x11".intern(); - /** Android/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}*/ - public static final String TYPE_ANDROID = "jogamp.newt.driver.android"; + /** Android/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}.*/ + public static final String TYPE_ANDROID = "jogamp.newt.driver.android".intern(); - /** Mac OS X type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_MACOSX = "jogamp.newt.driver.macosx"; + /** Mac OS X type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_MACOSX = "jogamp.newt.driver.macosx".intern(); - /** Generic AWT type, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_AWT = "jogamp.newt.driver.awt"; + /** Generic AWT type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_AWT = "jogamp.newt.driver.awt".intern(); - /** Generic DEFAULT type, where platform implementation don't care, as retrieved with {@link #getNativeWindowType(boolean)} */ - public static final String TYPE_DEFAULT = "default"; + /** Generic DEFAULT type, where platform implementation don't care, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_DEFAULT = "default".intern(); + private static final String nativeWindowingTypePure; // canonical String via String.intern() + private static final String nativeWindowingTypeCustom; // canonical String via String.intern() + private static NativeWindowFactory defaultFactory; private static Map, NativeWindowFactory> registeredFactories; private static Class nativeWindowClass; - private static String nativeWindowingTypePure; - private static String nativeWindowingTypeCustom; private static boolean isAWTAvailable; private static final String JAWTUtilClassName = "jogamp.nativewindow.jawt.JAWTUtil" ; @@ -133,17 +134,26 @@ public abstract class NativeWindowFactory { System.err.println(Thread.currentThread().getName()+" - Info: NativeWindowFactory."); // Thread.dumpStack(); } + + // Gather the windowing TK first + nativeWindowingTypePure = _getNativeWindowingType(); + final String tmp = Debug.getProperty("nativewindow.ws.name", true); + if(null==tmp || tmp.length()==0) { + nativeWindowingTypeCustom = nativeWindowingTypePure; + } else { + nativeWindowingTypeCustom = tmp.intern(); // canonical representation + } } static boolean initialized = false; private static void initSingletonNativeImpl(final ClassLoader cl) { final String clazzName; - if( TYPE_X11.equals(nativeWindowingTypePure) ) { + if( TYPE_X11 == nativeWindowingTypePure ) { clazzName = X11UtilClassName; - } else if( TYPE_WINDOWS.equals(nativeWindowingTypePure) ) { + } else if( TYPE_WINDOWS == nativeWindowingTypePure ) { clazzName = GDIClassName; - } else if( TYPE_MACOSX.equals(nativeWindowingTypePure) ) { + } else if( TYPE_MACOSX == nativeWindowingTypePure ) { clazzName = OSXUtilClassName; } else { clazzName = null; @@ -172,15 +182,6 @@ public abstract class NativeWindowFactory { final ClassLoader cl = NativeWindowFactory.class.getClassLoader(); - // Gather the windowing OS first - nativeWindowingTypePure = _getNativeWindowingType(); - String tmp = Debug.getProperty("nativewindow.ws.name", true); - if(null==tmp || tmp.length()==0) { - nativeWindowingTypeCustom = nativeWindowingTypePure; - } else { - nativeWindowingTypeCustom = tmp; - } - isAWTAvailable = false; // may be set to true below if( Platform.AWT_AVAILABLE && @@ -293,7 +294,8 @@ public abstract class NativeWindowFactory { /** * @param useCustom if false return the native value, if true return a custom value if set, otherwise fallback to the native value. - * @return a define native window type, like {@link #TYPE_X11}, .. + * @return the native window type, e.g. {@link #TYPE_X11}, which is canonical via {@link String#intern()}. + * Hence {@link String#equals(Object)} and == produce the same result. */ public static String getNativeWindowType(boolean useCustom) { return useCustom?nativeWindowingTypeCustom:nativeWindowingTypePure; @@ -301,13 +303,13 @@ public abstract class NativeWindowFactory { /** Don't know if we shall add this factory here .. public static AbstractGraphicsDevice createGraphicsDevice(String type, String connection, int unitID, long handle, ToolkitLock locker) { - if(type.equals(TYPE_EGL)) { + if(TYPE_EGL == type) { return new - } else if(type.equals(TYPE_X11)) { - } else if(type.equals(TYPE_WINDOWS)) { - } else if(type.equals(TYPE_MACOSX)) { - } else if(type.equals(TYPE_AWT)) { - } else if(type.equals(TYPE_DEFAULT)) { + } else if(TYPE_X11 == type) { + } else if(TYPE_WINDOWS == type) { + } else if(TYPE_MACOSX == type)) { + } else if(TYPE_AWT == type) { + } else if(TYPE_DEFAULT == type) { } } */ diff --git a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java index 2c2a627a4..29564da3b 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java @@ -39,7 +39,6 @@ import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ToolkitLock; -import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; import com.jogamp.common.util.ReflectionUtil.AWTNames; @@ -76,17 +75,17 @@ public class NativeWindowFactoryImpl extends NativeWindowFactory { private NativeWindow getAWTNativeWindow(Object winObj, AbstractGraphicsConfiguration config) { if (nativeWindowConstructor == null) { try { - String windowingType = getNativeWindowType(true); - String windowClassName = null; + final String windowingType = getNativeWindowType(true); + final String windowClassName; // We break compile-time dependencies on the AWT here to // make it easier to run this code on mobile devices - if (windowingType.equals(TYPE_WINDOWS)) { + if (TYPE_WINDOWS == windowingType) { windowClassName = "jogamp.nativewindow.jawt.windows.WindowsJAWTWindow"; - } else if (windowingType.equals(TYPE_MACOSX)) { + } else if (TYPE_MACOSX == windowingType) { windowClassName = "jogamp.nativewindow.jawt.macosx.MacOSXJAWTWindow"; - } else if (windowingType.equals(TYPE_X11)) { + } else if (TYPE_X11 == windowingType) { // Assume Linux, Solaris, etc. Should probably test for these explicitly. windowClassName = "jogamp.nativewindow.jawt.x11.X11JAWTWindow"; } else { diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java index 2377c2be6..f579da217 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java @@ -60,7 +60,7 @@ public class JAWTJNILibLoader extends NWJNILibLoader { // ensure references from jogl_awt shared object // will succeed since JAWT shared object isn't in // default library path - if ( ! NativeWindowFactory.TYPE_MACOSX.equals( NativeWindowFactory.getNativeWindowType(false) ) ) { + if ( NativeWindowFactory.TYPE_MACOSX != NativeWindowFactory.getNativeWindowType(false) ) { try { loadLibrary("jawt", null, true, JAWTJNILibLoader.class.getClassLoader()); } catch (Throwable t) { -- cgit v1.2.3 From 90d45928186f2be99999461cfe45f76a783cc961 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 7 Sep 2012 05:46:22 +0200 Subject: Fix Capabilities ambiguity and explosion of queried available-list; Add FBO availability detection for EGL, WGL and OSX. Introducing Capabilities 'bitmap' boolean, complementing the offscreen modes FBO and PBuffer. This allows: 1 - deterministic setting of the offscreen mode 2 - utilizing auto configuration of offscreen mode, if !onscreen !FBO !PBuffer and !Bitmap 3 - adding 'availability' semantic of 'onscreen' boolean, i.e. if onscree:=1 for a queried instance, the offscreen modes still indicate offscreen availability - see [4] 4 - avoiding explosion of the availability list due to [3], one Capability entry reflect on- and offscreen settings. Add FBO availability detection for EGL, WGL and OSX. Tested manually w/ 'TestGLCapabilities01NEWT' on X11 [NV, ATI], WGL[NV], OSX[NV]. --- make/scripts/tests-x64.bat | 3 +- make/scripts/tests.sh | 51 +++-- .../media/opengl/DefaultGLCapabilitiesChooser.java | 39 ++-- .../classes/javax/media/opengl/GLCapabilities.java | 96 +++++---- .../media/opengl/GLCapabilitiesImmutable.java | 79 +++++-- .../jogamp/opengl/GLDrawableFactoryImpl.java | 6 +- .../jogamp/opengl/GLGraphicsConfigurationUtil.java | 151 +++++++------ .../jogamp/opengl/egl/EGLDrawableFactory.java | 9 +- .../jogamp/opengl/egl/EGLGLCapabilities.java | 18 +- .../opengl/egl/EGLGraphicsConfiguration.java | 68 +++--- .../egl/EGLGraphicsConfigurationFactory.java | 36 ++-- .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 9 +- .../macosx/cgl/MacOSXCGLGraphicsConfiguration.java | 6 +- .../windows/wgl/WindowsPbufferWGLDrawable.java | 15 +- .../wgl/WindowsWGLGraphicsConfiguration.java | 94 ++++----- .../WindowsWGLGraphicsConfigurationFactory.java | 80 +++---- .../x11/glx/X11GLXGraphicsConfiguration.java | 59 ++---- .../glx/X11GLXGraphicsConfigurationFactory.java | 81 +++---- .../javax/media/nativewindow/Capabilities.java | 160 +++++++------- .../media/nativewindow/CapabilitiesImmutable.java | 35 +++- .../nativewindow/DefaultCapabilitiesChooser.java | 9 +- .../junit/jogl/acore/TestGLCapabilities01NEWT.java | 233 +++++++++++++++++++++ .../opengl/test/junit/util/AWTRobotUtil.java | 13 ++ 23 files changed, 881 insertions(+), 469 deletions(-) create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java (limited to 'src/nativewindow') diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat index 6d3e46af6..669e0212e 100755 --- a/make/scripts/tests-x64.bat +++ b/make/scripts/tests-x64.bat @@ -1,6 +1,7 @@ REM scripts\java-win64-dbg.bat jogamp.newt.awt.opengl.VersionApplet REM scripts\java-win64-dbg.bat com.jogamp.newt.opengl.GLWindow REM scripts\java-win64-dbg.bat javax.media.opengl.awt.GLCanvas +scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLCapabilities01NEWT $* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT -time 5000 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestAWT01GLn @@ -39,7 +40,7 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestP REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01AWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aSWT $* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT $* -scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor03AWTGLn $* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index cccc825ee..1314094cf 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -60,10 +60,9 @@ function jrun() { #D_ARGS="-Djogl.debug.GLContext.NoProfileAliasing" #D_ARGS="-Djogamp.debug=all -Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all" + #D_ARGS="-Djogl.fbo.force.none" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all -Djogamp.debug.Lock" #D_ARGS="-Djogl.debug=all" - #D_ARGS="-Dnewt.debug.Window" - #D_ARGS="-Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.EGLDrawableFactory.DontQuery -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.EGLDrawableFactory.QueryNativeTK -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLDebugMessageHandler" @@ -76,7 +75,8 @@ function jrun() { #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.TraceGL -Djogl.debug.GLContext.TraceSwitch -Djogl.debug=all" #D_ARGS="-Djogamp.debug.IOUtil -Djogl.debug.GLSLCode -Djogl.debug.GLMediaPlayer" #D_ARGS="-Djogl.debug.GLArrayData" - #D_ARGS="-Djogl.debug.EGL -Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable" + #D_ARGS="-Djogl.debug.EGLDisplayUtil -Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable" + #D_ARGS="-Djogl.debug.EGLDisplayUtil -Dnativewindow.debug.X11Util" #D_ARGS="-Djogl.debug.GLDrawable" #D_ARGS="-Dnewt.test.Screen.disableScreenMode -Dnewt.debug.Screen" #D_ARGS="-Djogl.debug.ExtensionAvailabilityCache -Djogl.debug=all -Dnativewindow.debug=all -Djogamp.debug.ProcAddressHelper=true -Djogamp.debug.NativeLibrary=true -Djogamp.debug.NativeLibrary.Lookup=true" @@ -107,7 +107,7 @@ function jrun() { #D_ARGS="-Djogl.debug.Animator -Dnewt.debug=all" #D_ARGS="-Dnewt.debug.EDT -Dnewt.debug.Display -Dnativewindow.debug.X11Util -Djogl.debug.GLDrawable -Djogl.debug.GLCanvas" #D_ARGS="-Djogl.debug.GLContext" - #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.CapabilitiesChooser" + #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.CapabilitiesChooser -Djogl.debug.GLDrawable -Djogl.debug.GLProfile" #D_ARGS="-Dnewt.debug.Screen -Dnewt.debug.EDT -Djogamp.debug.Lock" #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.GraphicsConfiguration" #D_ARGS="-Dnewt.debug.EDT" @@ -247,7 +247,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestRedSquareES1NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestWindows01NEWT $* @@ -278,6 +278,7 @@ testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestAWTCloseX11DisplayBug565 $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextNewtAWTBug523 $* +#testawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableDeadlockAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestPBufferDeadlockAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownSharedAWT $* @@ -291,7 +292,8 @@ testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWTAnalyzeBug455 $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWTBug450 $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461OffscreenSupersamplingSwingAWT +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461FBOSupersamplingSwingAWT +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461PBufferSupersamplingSwingAWT #testawt com.jogamp.opengl.test.junit.jogl.glu.TestBug463ScaleImageMemoryAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWTCardLayoutAnimatorStartStopBug532 $* @@ -315,8 +317,8 @@ testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* # # newt.awt (testawt) # -#testawt com.jogamp.opengl.test.junit.jogl.newt.TestSwingAWTRobotUsageBeforeJOGLInitBug411 -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper +#testawt com.jogamp.opengl.test.junit.jogl.newt.TestSwingAWTRobotUsageBeforeJOGLInitBug411 $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper $* #testawt com.jogamp.opengl.test.junit.newt.TestEventSourceNotAWTBug #testawt com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot $* #testawt com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot $* @@ -366,16 +368,32 @@ testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube $* # -# GLSL / FBO / .. +# GLSL # #testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestTransformFeedbackVaryingsBug407NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLSimple01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01 $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMRTNEWT01 $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMix2DemosES2NEWT $* + +# +# FBO / .. +# +testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLCapabilities01NEWT $* + #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable00NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable01bNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable02NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMix2DemosES2NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableMix2DemosES2NEWT $* +#testawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableDeadlockAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461FBOSupersamplingSwingAWT +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMRTNEWT01 $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* # # Graph @@ -411,13 +429,20 @@ testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testawt com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot $* #linux: +# EARMARK removal of shutdown mode! +#testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownSharedAWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownSharedNEWT $* # osx: +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable02NEWT $* +#testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode02NEWT +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01GLCanvasAWT $* - #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01GLCanvasAWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer02NewtCanvasAWT $* + $spath/count-edt-start.sh java-run.log diff --git a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java index 5fa8ce32d..b052769ca 100644 --- a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java +++ b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java @@ -87,20 +87,20 @@ import jogamp.opengl.Debug; public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { private static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.CapabilitiesChooser", true); - final static int NO_SCORE = -9999999; - final static int DOUBLE_BUFFER_MISMATCH_PENALTY = 1000; - final static int OPAQUE_MISMATCH_PENALTY = 750; - final static int STENCIL_MISMATCH_PENALTY = 500; - final static int MULTISAMPLE_MISMATCH_PENALTY = 500; - final static int MULTISAMPLE_EXTENSION_MISMATCH_PENALTY = 250; // just a little drop, no scale + private final static int NO_SCORE = -9999999; + private final static int DOUBLE_BUFFER_MISMATCH_PENALTY = 1000; + private final static int OPAQUE_MISMATCH_PENALTY = 750; + private final static int STENCIL_MISMATCH_PENALTY = 500; + private final static int MULTISAMPLE_MISMATCH_PENALTY = 500; + private final static int MULTISAMPLE_EXTENSION_MISMATCH_PENALTY = 250; // just a little drop, no scale // Pseudo attempt to keep equal rank penalties scale-equivalent // (e.g., stencil mismatch is 3 * accum because there are 3 accum // components) - final static int COLOR_MISMATCH_PENALTY_SCALE = 36; - final static int DEPTH_MISMATCH_PENALTY_SCALE = 6; - final static int ACCUM_MISMATCH_PENALTY_SCALE = 1; - final static int STENCIL_MISMATCH_PENALTY_SCALE = 3; - final static int MULTISAMPLE_MISMATCH_PENALTY_SCALE = 3; + private final static int COLOR_MISMATCH_PENALTY_SCALE = 36; + private final static int DEPTH_MISMATCH_PENALTY_SCALE = 6; + private final static int ACCUM_MISMATCH_PENALTY_SCALE = 1; + private final static int STENCIL_MISMATCH_PENALTY_SCALE = 3; + private final static int MULTISAMPLE_MISMATCH_PENALTY_SCALE = 3; @Override public int chooseCapabilities(final CapabilitiesImmutable desired, @@ -150,11 +150,20 @@ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { if (cur == null) { continue; } - if (gldes.isOnscreen() != cur.isOnscreen()) { - continue; + if (gldes.isOnscreen() && !cur.isOnscreen()) { + continue; // requested onscreen, but n/a } - if (!gldes.isOnscreen() && gldes.isPBuffer() && !cur.isPBuffer()) { - continue; // only skip if requested Offscreen && PBuffer, but no PBuffer available + if (!gldes.isOnscreen()) { + /** FBO is generic .. + if (gldes.isFBO() && !cur.isFBO()) { + continue; // requested FBO, but n/a + } */ + if (gldes.isPBuffer() && !cur.isPBuffer()) { + continue; // requested pBuffer, but n/a + } + if (gldes.isBitmap() && !cur.isBitmap()) { + continue; // requested pBuffer, but n/a + } } if (gldes.getStereo() != cur.getStereo()) { continue; diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilities.java b/src/jogl/classes/javax/media/opengl/GLCapabilities.java index 8845ec665..30a6215e7 100644 --- a/src/jogl/classes/javax/media/opengl/GLCapabilities.java +++ b/src/jogl/classes/javax/media/opengl/GLCapabilities.java @@ -105,20 +105,21 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil @Override public int hashCode() { // 31 * x == (x << 5) - x - int hash = 31 + this.glProfile.hashCode() ; + int hash = super.hashCode(); + hash = ((hash << 5) - hash) + this.glProfile.hashCode() ; + hash = ((hash << 5) - hash) + ( this.hardwareAccelerated ? 1 : 0 ); + hash = ((hash << 5) - hash) + ( this.stereo ? 1 : 0 ); hash = ((hash << 5) - hash) + ( this.isFBO ? 1 : 0 ); hash = ((hash << 5) - hash) + ( this.isPBuffer ? 1 : 0 ); - hash = ((hash << 5) - hash) + ( this.stereo ? 1 : 0 ); - hash = ((hash << 5) - hash) + ( this.hardwareAccelerated ? 1 : 0 ); + hash = ((hash << 5) - hash) + ( this.sampleBuffers ? 1 : 0 ); + hash = ((hash << 5) - hash) + this.getNumSamples(); + hash = ((hash << 5) - hash) + this.sampleExtension.hashCode(); hash = ((hash << 5) - hash) + this.depthBits; hash = ((hash << 5) - hash) + this.stencilBits; hash = ((hash << 5) - hash) + this.accumRedBits; hash = ((hash << 5) - hash) + this.accumGreenBits; hash = ((hash << 5) - hash) + this.accumBlueBits; hash = ((hash << 5) - hash) + this.accumAlphaBits; - hash = ((hash << 5) - hash) + ( this.sampleBuffers ? 1 : 0 ); - hash = ((hash << 5) - hash) + this.numSamples; - hash = ((hash << 5) - hash) + this.sampleExtension.hashCode(); hash = ((hash << 5) - hash) + ( this.pbufferFloatingPointBuffers ? 1 : 0 ); hash = ((hash << 5) - hash) + ( this.pbufferRenderToTexture ? 1 : 0 ); hash = ((hash << 5) - hash) + ( this.pbufferRenderToTextureRectangle ? 1 : 0 ); @@ -148,9 +149,8 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil other.getPbufferFloatingPointBuffers()==pbufferFloatingPointBuffers && other.getPbufferRenderToTexture()==pbufferRenderToTexture && other.getPbufferRenderToTextureRectangle()==pbufferRenderToTextureRectangle; - if(sampleBuffers) { - res = res && - other.getNumSamples()==numSamples && + if(res && sampleBuffers) { + res = other.getNumSamples()==getNumSamples() && other.getSampleExtension().equals(sampleExtension) ; } return res; @@ -222,19 +222,24 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil public void setGLProfile(GLProfile profile) { glProfile=profile; } - + @Override public final boolean isPBuffer() { return isPBuffer; } /** - * Enables or disables pbuffer usage. + * Requesting offscreen pbuffer mode. *

      * If enabled this method also invokes {@link #setOnscreen(int) setOnscreen(false)}. *

      + *

      * Defaults to false. - */ + *

      + *

      + * Requesting offscreen pbuffer mode disables the offscreen auto selection. + *

      + */ public void setPBuffer(boolean enable) { if(enable) { setOnscreen(false); @@ -248,11 +253,16 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil } /** - * Enables or disables FBO usage. + * Requesting offscreen FBO mode. *

      * If enabled this method also invokes {@link #setOnscreen(int) setOnscreen(false)}. *

      + *

      * Defaults to false. + *

      + *

      + * Requesting offscreen FBO mode disables the offscreen auto selection. + *

      */ public void setFBO(boolean enable) { if(enable) { @@ -261,21 +271,6 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil isFBO = enable; } - /** - * Sets whether the drawable surface supports onscreen.
      - * If enabled this method also invokes {@link #setPBuffer(int) setPBuffer(false)} - * and {@link #setFBO(int) setFBO(false)}
      - * Defaults to true. - */ - @Override - public void setOnscreen(boolean onscreen) { - if(onscreen) { - setPBuffer(false); - setFBO(false); - } - super.setOnscreen(onscreen); - } - @Override public final boolean getDoubleBuffered() { return doubleBuffered; @@ -465,9 +460,9 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil sink = new StringBuilder(); } - int samples = sampleBuffers ? numSamples : 0 ; + final int samples = sampleBuffers ? numSamples : 0 ; - super.toString(sink); + super.toString(sink, false); sink.append(", accum-rgba ").append(accumRedBits).append("/").append(accumGreenBits).append("/").append(accumBlueBits).append("/").append(accumAlphaBits); sink.append(", dp/st/ms: ").append(depthBits).append("/").append(stencilBits).append("/").append(samples); @@ -490,20 +485,37 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil sink.append(", sw, "); } sink.append(glProfile); - if(!isOnscreen()) { - if(isFBO) { - sink.append(", fbo"); - } - if(isPBuffer) { - sink.append(", pbuffer [r2t ").append(pbufferRenderToTexture?1:0) - .append(", r2tr ").append(pbufferRenderToTextureRectangle?1:0) - .append(", float ").append(pbufferFloatingPointBuffers?1:0) - .append("]"); - } - if(!isFBO && !isPBuffer) { - sink.append(", pixmap"); + if(isOnscreen()) { + sink.append(", on-scr["); + } else { + sink.append(", offscr["); + } + boolean ns=false; + if(isFBO()) { + sink.append("fbo"); + ns = true; + } + if(isPBuffer()) { + if(ns) { sink.append(", "); } + sink.append("pbuffer [r2t ").append(pbufferRenderToTexture?1:0) + .append(", r2tr ").append(pbufferRenderToTextureRectangle?1:0) + .append(", float ").append(pbufferFloatingPointBuffers?1:0) + .append("]"); + ns = true; + } + if(isBitmap()) { + if(ns) { sink.append(", "); } + sink.append("bitmap"); + ns = true; + } + if(!ns) { // !FBO !PBuffer !Bitmap + if(isOnscreen()) { + sink.append("."); // no additional off-screen modes besides on-screen + } else { + sink.append("auto-cfg"); // auto-config off-screen mode } } + sink.append("]"); return sink; } diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java b/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java index 7e0459b2d..ee261ca01 100644 --- a/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java +++ b/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java @@ -50,7 +50,7 @@ public interface GLCapabilitiesImmutable extends CapabilitiesImmutable { GLProfile getGLProfile(); /** - * Returns the number of bits requested for the accumulation + * Returns the number of bits 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. @@ -58,7 +58,7 @@ public interface GLCapabilitiesImmutable extends CapabilitiesImmutable { int getAccumAlphaBits(); /** - * Returns the number of bits requested for the accumulation + * Returns the number of bits 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. @@ -66,7 +66,7 @@ public interface GLCapabilitiesImmutable extends CapabilitiesImmutable { int getAccumBlueBits(); /** - * Returns the number of bits requested for the accumulation + * Returns the number of bits 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. @@ -74,7 +74,7 @@ public interface GLCapabilitiesImmutable extends CapabilitiesImmutable { int getAccumGreenBits(); /** - * Returns the number of bits requested for the accumulation + * Returns the number of bits 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. @@ -82,74 +82,115 @@ public interface GLCapabilitiesImmutable extends CapabilitiesImmutable { int getAccumRedBits(); /** - * Returns the number of bits requested for the depth buffer. + * Returns the number of depth buffer bits. */ int getDepthBits(); /** - * Indicates whether double-buffering is enabled. + * Returns whether double-buffering is requested, available or chosen. + *

      + * Default is true. + *

      */ boolean getDoubleBuffered(); /** - * Indicates whether hardware acceleration is enabled. + * Returns whether hardware acceleration is requested, available or chosen. + *

      + * Default is true. + *

      */ boolean getHardwareAccelerated(); /** - * Returns the used extension for full-scene antialiasing - * (FSAA), default is {@link #DEFAULT_SAMPLE_EXTENSION}. + * Returns the extension for full-scene antialiasing + * (FSAA). + *

      + * Default is {@link #DEFAULT_SAMPLE_EXTENSION}. + *

      */ String getSampleExtension(); /** * Returns whether sample buffers for full-scene antialiasing - * (FSAA) should be allocated for this drawable. Defaults to - * false. + * (FSAA) should be allocated for this drawable. + *

      + * Default is false. + *

      */ boolean getSampleBuffers(); /** * Returns the number of sample buffers to be allocated if sample - * buffers are enabled, otherwise returns 0. Defaults to 2. + * buffers are enabled, otherwise returns 0. + *

      + * Default is 0 due to disable sample buffers per default. + *

      */ int getNumSamples(); /** * For pbuffers only, returns whether floating-point buffers should - * be used if available. Defaults to false. + * be used if available. + *

      + * Default is false. + *

      */ boolean getPbufferFloatingPointBuffers(); /** * For pbuffers only, returns whether the render-to-texture - * extension should be used if available. Defaults to false. + * extension should be used if available. + *

      + * Default is false. + *

      */ boolean getPbufferRenderToTexture(); /** * For pbuffers only, returns whether the render-to-texture - * extension should be used. Defaults to false. + * extension should be used. + *

      + * Default is false. + *

      */ boolean getPbufferRenderToTextureRectangle(); /** - * Returns the number of bits requested for the stencil buffer. + * Returns the number of stencil buffer bits. + *

      + * Default is 0. + *

      */ int getStencilBits(); /** - * Indicates whether stereo is enabled. + * Returns whether stereo is requested, available or chosen. + *

      + * Default is false. + *

      */ boolean getStereo(); /** - * Indicates whether pbuffer offscreen is used/requested. + * Returns whether pbuffer offscreen mode is requested, available or chosen. + *

      + * Default is false. + *

      + *

      + * For chosen capabilities, only the selected offscreen surface is set to true. + *

      */ boolean isPBuffer(); /** - * Indicates whether FBO offscreen is used/requested. + * Returns whether FBO offscreen mode is requested, available or chosen. + *

      + * Default is false. + *

      + *

      + * For chosen capabilities, only the selected offscreen surface is set to true. + *

      */ boolean isFBO(); diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index 2f2bf5961..e1e253d35 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -271,7 +271,10 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { throw new GLException("No shared device for requested: "+deviceReq); } - if( capsRequested.isFBO() && GLContext.isFBOAvailable(device, capsRequested.getGLProfile()) ) { + final GLCapabilitiesImmutable capsChosen = GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(capsRequested, + GLContext.isFBOAvailable(device, capsRequested.getGLProfile()), + canCreateGLPbuffer(device)); + if( capsChosen.isFBO() ) { device.lock(); try { return createFBODrawableImpl(device, capsRequested, chooser, width, height); @@ -280,7 +283,6 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { } } - final GLCapabilitiesImmutable capsChosen = GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(capsRequested, false, canCreateGLPbuffer(device)); device.lock(); try { return createOffscreenDrawableImpl( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, width, height, null) ); diff --git a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java index 3f38f33bc..d8e5ba31a 100644 --- a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java +++ b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java @@ -28,7 +28,6 @@ package jogamp.opengl; -import java.util.List; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesImmutable; @@ -74,56 +73,60 @@ public class GLGraphicsConfigurationUtil { } /** - * @param isFBO TODO - * @return bitmask representing the input boolean in exclusive or logic, ie only one bit will be set + public static final int getWinAttributeBits(boolean isOnscreen, boolean isFBO, boolean isPBuffer, boolean isBitmap) { + int winattrbits = 0; + if(isOnscreen) { + winattrbits |= WINDOW_BIT; + } + if(isFBO) { + winattrbits |= FBO_BIT; + } + if(isPBuffer ){ + winattrbits |= PBUFFER_BIT; + } + if(isBitmap) { + winattrbits |= BITMAP_BIT; + } + return winattrbits; + } + public static final int getWinAttributeBits(GLCapabilitiesImmutable caps) { + return getWinAttributeBits(caps.isOnscreen(), caps.isFBO(), caps.isPBuffer(), caps.isBitmap()); + } */ + + /** + * @return bitmask representing the input boolean in exclusive or logic, ie only one bit will be set. */ - public static final int getWinAttributeBits(boolean isOnscreen, boolean isPBuffer, boolean isFBO) { + public static final int getExclusiveWinAttributeBits(boolean isOnscreen, boolean isFBO, boolean isPBuffer, boolean isBitmap) { int winattrbits = 0; if(isOnscreen) { winattrbits |= WINDOW_BIT; - } else { - if(isFBO) { - winattrbits |= FBO_BIT; - } - if (!isPBuffer) { - winattrbits |= BITMAP_BIT; - } else { - winattrbits |= PBUFFER_BIT; - } + } else if(isFBO) { + winattrbits |= FBO_BIT; + } else if(isPBuffer ){ + winattrbits |= PBUFFER_BIT; + } else if(isBitmap) { + winattrbits |= BITMAP_BIT; + } + if(0 == winattrbits) { + throw new InternalError("Empty bitmask"); } return winattrbits; } /** - * @see #getWinAttributeBits(boolean, boolean, boolean) + * @see #getExclusiveWinAttributeBits(boolean, boolean, boolean, boolean) */ - public static final int getWinAttributeBits(GLCapabilitiesImmutable caps) { - return getWinAttributeBits(caps.isOnscreen(), caps.isPBuffer(), false); + public static final int getExclusiveWinAttributeBits(GLCapabilitiesImmutable caps) { + return getExclusiveWinAttributeBits(caps.isOnscreen(), caps.isFBO(), caps.isPBuffer(), caps.isBitmap()); } - public static final boolean addGLCapabilitiesPermutations(List capsBucket, GLCapabilitiesImmutable temp, int winattrbits) { - int preSize = capsBucket.size(); - if( 0 != ( WINDOW_BIT & winattrbits ) ) { - GLCapabilities cpy = (GLCapabilities) temp.cloneMutable(); - cpy.setOnscreen(true); - cpy.setPBuffer(false); - cpy.setFBO(false); - capsBucket.add(cpy); - } - if( 0 != ( PBUFFER_BIT & winattrbits ) || 0 != ( FBO_BIT & winattrbits ) ) { - GLCapabilities cpy = (GLCapabilities) temp.cloneMutable(); - cpy.setFBO(0 != ( FBO_BIT & winattrbits )); - cpy.setPBuffer(0 != ( PBUFFER_BIT & winattrbits )); - capsBucket.add(cpy); - } - if( 0 != ( BITMAP_BIT & winattrbits ) ) { - GLCapabilities cpy = (GLCapabilities) temp.cloneMutable(); - cpy.setOnscreen(false); - cpy.setPBuffer(false); - cpy.setFBO(false); - capsBucket.add(cpy); - } - return capsBucket.size() > preSize; + public static final GLCapabilities setWinAttributeBits(GLCapabilities caps, int winattrbits) { + caps.setBitmap ( 0 != ( BITMAP_BIT & winattrbits ) ); + caps.setPBuffer ( 0 != ( PBUFFER_BIT & winattrbits ) ); + caps.setFBO ( 0 != ( FBO_BIT & winattrbits ) ); + // we reflect availability semantics, hence setting onscreen at last (maybe overwritten above)! + caps.setOnscreen( 0 != ( WINDOW_BIT & winattrbits ) ); + return caps; } public static GLCapabilitiesImmutable fixGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean fboAvailable, boolean pbufferAvailable) @@ -131,33 +134,46 @@ public class GLGraphicsConfigurationUtil { if( !capsRequested.isOnscreen() ) { return fixOffscreenGLCapabilities(capsRequested, fboAvailable, pbufferAvailable); } - return fixOnscreenGLCapabilities(capsRequested); + return capsRequested; } public static GLCapabilitiesImmutable fixOnscreenGLCapabilities(GLCapabilitiesImmutable capsRequested) { if( !capsRequested.isOnscreen() ) { // fix caps .. - GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); + final GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); + caps2.setBitmap (false); + caps2.setPBuffer (false); + caps2.setFBO (false); caps2.setOnscreen(true); return caps2; } return capsRequested; } - - public static GLCapabilitiesImmutable fixOffscreenGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean fboAvailable, boolean pbufferAvailable) - { - if( capsRequested.getDoubleBuffered() || - capsRequested.isOnscreen() || - ( fboAvailable != capsRequested.isFBO() ) || - ( pbufferAvailable != capsRequested.isPBuffer() ) ) + + public static boolean isGLCapabilitiesOffscreenAutoSelection(GLCapabilitiesImmutable capsRequested) { + return !capsRequested.isOnscreen() && + !capsRequested.isFBO() && !capsRequested.isPBuffer() && !capsRequested.isBitmap() ; + } + + public static GLCapabilitiesImmutable fixOffscreenGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean fboAvailable, boolean pbufferAvailable) { + final boolean auto = !capsRequested.isFBO() && !capsRequested.isPBuffer() && !capsRequested.isBitmap() ; + + final boolean useFBO = fboAvailable && ( auto || capsRequested.isFBO() ) ; + final boolean usePbuffer = !useFBO && pbufferAvailable && ( auto || capsRequested.isPBuffer() ) ; + final boolean useBitmap = !usePbuffer && ( auto || capsRequested.isBitmap() ) ; + + if( capsRequested.isOnscreen() || + useFBO != capsRequested.isFBO() || + usePbuffer != capsRequested.isPBuffer() || + useBitmap != capsRequested.isBitmap() ) { // fix caps .. - GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); - caps2.setDoubleBuffered(false); // FIXME DBLBUFOFFSCRN + final GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); caps2.setOnscreen(false); - caps2.setFBO( fboAvailable ); - caps2.setPBuffer( pbufferAvailable ); + caps2.setFBO( useFBO ); + caps2.setPBuffer( usePbuffer ); + caps2.setBitmap( useBitmap ); return caps2; } return capsRequested; @@ -165,31 +181,40 @@ public class GLGraphicsConfigurationUtil { public static GLCapabilitiesImmutable fixGLPBufferGLCapabilities(GLCapabilitiesImmutable capsRequested) { - if( capsRequested.getDoubleBuffered() || capsRequested.isOnscreen() || !capsRequested.isPBuffer() || capsRequested.isFBO() ) { + if( capsRequested.isOnscreen() || + !capsRequested.isPBuffer() || + capsRequested.isFBO() ) + { // fix caps .. - GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); - caps2.setDoubleBuffered(false); // FIXME DBLBUFOFFSCRN - we don't need to be single buffered .. + final GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); caps2.setOnscreen(false); - caps2.setPBuffer(true); caps2.setFBO(false); + caps2.setPBuffer(true); + caps2.setBitmap(false); return caps2; } return capsRequested; } /** Fix opaque setting while preserve alpha bits */ - public static GLCapabilitiesImmutable fixOpaqueGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean isOpaque) + public static GLCapabilities fixOpaqueGLCapabilities(GLCapabilities capsRequested, boolean isOpaque) { - GLCapabilities caps2 = null; - if( capsRequested.isBackgroundOpaque() != isOpaque) { final int alphaBits = capsRequested.getAlphaBits(); - caps2 = (GLCapabilities) capsRequested.cloneMutable(); - caps2.setBackgroundOpaque(isOpaque); - caps2.setAlphaBits(alphaBits); - return caps2; + capsRequested.setBackgroundOpaque(isOpaque); + capsRequested.setAlphaBits(alphaBits); } return capsRequested; } + /** Fix double buffered setting */ + public static GLCapabilitiesImmutable fixDoubleBufferedGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean doubleBuffered) + { + if( capsRequested.getDoubleBuffered() != doubleBuffered) { + final GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); + caps2.setDoubleBuffered(doubleBuffered); + return caps2; + } + return capsRequested; + } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index a9e339bea..986b110be 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -290,9 +290,9 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { if(0 < numConfigs.get(0)) { final PointerBuffer configs = PointerBuffer.allocateDirect(numConfigs.get(0)); final IntBuffer attrs = Buffers.newDirectIntBuffer(EGLGraphicsConfiguration.GLCapabilities2AttribList(caps)); - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(true, true, true); + final int winattrmask = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(caps); if( EGL.eglChooseConfig(eglDisplay.getHandle(), attrs, configs, configs.capacity(), numConfigs) && numConfigs.get(0) > 0) { - return EGLGraphicsConfigurationFactory.eglConfigs2GLCaps(caps.getGLProfile(), eglDisplay.getHandle(), configs, numConfigs.get(0), winattrmask, false /* forceTransparentFlag */); + return EGLGraphicsConfigurationFactory.eglConfigs2GLCaps(eglDisplay, caps.getGLProfile(), configs, numConfigs.get(0), winattrmask, false /* forceTransparentFlag */); } } return new ArrayList(0); @@ -649,7 +649,10 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { @Override public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { - final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(requestedCaps, false, canCreateGLPbuffer(deviceReq)); + final GLCapabilitiesImmutable chosenCaps = + GLGraphicsConfigurationUtil.fixDoubleBufferedGLCapabilities( + GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(requestedCaps, false, canCreateGLPbuffer(deviceReq)), + false); return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, width, height, dummySurfaceLifecycleHook); } private static final ProxySurface.UpstreamSurfaceHook dummySurfaceLifecycleHook = new ProxySurface.UpstreamSurfaceHook() { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java b/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java index 70a570174..e513a86cf 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java @@ -33,6 +33,8 @@ import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; +import com.jogamp.nativewindow.egl.EGLGraphicsDevice; + public class EGLGLCapabilities extends GLCapabilities { private long eglcfg; @@ -45,13 +47,13 @@ public class EGLGLCapabilities extends GLCapabilities { * @param eglcfg * @param eglcfgid * @param visualID native visualID if valid, otherwise VisualIDHolder.VID_UNDEFINED - * @param glp desired GLProfile, or null if determined by renderableType + * @param glp desired GLProfile * @param renderableType actual EGL renderableType * * May throw GLException if given GLProfile is not compatible w/ renderableType */ public EGLGLCapabilities(long eglcfg, int eglcfgid, int visualID, GLProfile glp, int renderableType) { - super( ( null != glp ) ? glp : getCompatible(renderableType) ); + super( glp ); this.eglcfg = eglcfg; this.eglcfgid = eglcfgid; if(!isCompatible(glp, renderableType)) { @@ -111,15 +113,15 @@ public class EGLGLCapabilities extends GLCapabilities { return false; } - public static GLProfile getCompatible(int renderableType) { - if(0 != (renderableType & EGL.EGL_OPENGL_ES2_BIT) && GLProfile.isAvailable(GLProfile.GLES2)) { - return GLProfile.get(GLProfile.GLES2); + public static GLProfile getCompatible(EGLGraphicsDevice device, int renderableType) { + if(0 != (renderableType & EGL.EGL_OPENGL_ES2_BIT) && GLProfile.isAvailable(device, GLProfile.GLES2)) { + return GLProfile.get(device, GLProfile.GLES2); } - if(0 != (renderableType & EGL.EGL_OPENGL_ES_BIT) && GLProfile.isAvailable(GLProfile.GLES1)) { - return GLProfile.get(GLProfile.GLES1); + if(0 != (renderableType & EGL.EGL_OPENGL_ES_BIT) && GLProfile.isAvailable(device, GLProfile.GLES1)) { + return GLProfile.get(device, GLProfile.GLES1); } if(0 != (renderableType & EGL.EGL_OPENGL_BIT)) { - return GLProfile.getDefault(); + return GLProfile.getDefault(device); } return null; } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java index 20102547d..135101ff2 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java @@ -37,8 +37,6 @@ package jogamp.opengl.egl; import java.nio.IntBuffer; -import java.util.ArrayList; -import java.util.List; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; @@ -48,6 +46,7 @@ import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.DefaultGLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; @@ -85,7 +84,8 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple } final long cfg = EGLConfigId2EGLConfig(dpy, cfgID); if(0 < cfg) { - final EGLGLCapabilities caps = EGLConfig2Capabilities(capsRequested.getGLProfile(), dpy, cfg, false, capsRequested.isOnscreen(), capsRequested.isPBuffer(), false); + final int winattrmask = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsRequested); + final EGLGLCapabilities caps = EGLConfig2Capabilities((EGLGraphicsDevice)absDevice, capsRequested.getGLProfile(), cfg, winattrmask, false); return new EGLGraphicsConfiguration(absScreen, caps, capsRequested, new DefaultGLCapabilitiesChooser()); } return null; @@ -129,9 +129,10 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple return configs.get(0); } - static int EGLConfigDrawableTypeBits(final long display, final long config) { + static int EGLConfigDrawableTypeBits(final EGLGraphicsDevice device, final GLProfile glp, final long config) { int val = 0; + final long display = device.getHandle(); int[] stype = new int[1]; if(! EGL.eglGetConfigAttrib(display, config, EGL.EGL_SURFACE_TYPE, stype, 0)) { throw new GLException("Could not determine EGL_SURFACE_TYPE"); @@ -146,32 +147,24 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple if ( 0 != ( stype[0] & EGL.EGL_PBUFFER_BIT ) ) { val |= GLGraphicsConfigurationUtil.PBUFFER_BIT; } + if ( GLContext.isFBOAvailable(device, glp) ) { + val |= GLGraphicsConfigurationUtil.FBO_BIT; + } return val; } - public static EGLGLCapabilities EGLConfig2Capabilities(GLProfile glp, long display, long config, - boolean relaxed, boolean onscreen, boolean usePBuffer, boolean forceTransparentFlag) { - List bucket = new ArrayList(); - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, false); - if( EGLConfig2Capabilities(bucket, glp, display, config, winattrmask, forceTransparentFlag) ) { - return (EGLGLCapabilities) bucket.get(0); - } else if ( relaxed && EGLConfig2Capabilities(bucket, glp, display, config, GLGraphicsConfigurationUtil.ALL_BITS, forceTransparentFlag) ) { - return (EGLGLCapabilities) bucket.get(0); - } - return null; - } - - public static boolean EGLConfig2Capabilities(List capsBucket, - GLProfile glp, long display, long config, - int winattrmask, boolean forceTransparentFlag) { - final int allDrawableTypeBits = EGLConfigDrawableTypeBits(display, config); - final int drawableTypeBits = winattrmask & allDrawableTypeBits; - - if( 0 == drawableTypeBits ) { - return false; - } - + /** + * @param device + * @param glp desired GLProfile, may be null + * @param config + * @param winattrmask + * @param forceTransparentFlag + * @return + */ + public static EGLGLCapabilities EGLConfig2Capabilities(EGLGraphicsDevice device, GLProfile glp, long config, + int winattrmask, boolean forceTransparentFlag) { + final long display = device.getHandle(); final IntBuffer val = Buffers.newDirectIntBuffer(1); final int cfgID; final int rType; @@ -183,7 +176,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple // FIXME: this happens on a ATI PC Emulation .. System.err.println("EGL couldn't retrieve ConfigID for config "+toHexString(config)+", error "+toHexString(EGL.eglGetError())); } - return false; + return null; } cfgID = val.get(0); @@ -191,10 +184,10 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple if(DEBUG) { System.err.println("EGL couldn't retrieve EGL_RENDERABLE_TYPE for config "+toHexString(config)+", error "+toHexString(EGL.eglGetError())); } - return false; + return null; } rType = val.get(0); - + if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_NATIVE_VISUAL_ID, val)) { visualID = val.get(0); } else { @@ -203,12 +196,15 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple EGLGLCapabilities caps = null; try { + if(null == glp) { + glp = EGLGLCapabilities.getCompatible(device, rType); + } caps = new EGLGLCapabilities(config, cfgID, visualID, glp, rType); } catch (GLException gle) { if(DEBUG) { System.err.println("config "+toHexString(config)+": "+gle); } - return false; + return null; } if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_CONFIG_CAVEAT, val)) { @@ -270,7 +266,17 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_DEPTH_SIZE, val)) { caps.setDepthBits(val.get(0)); } - return GLGraphicsConfigurationUtil.addGLCapabilitiesPermutations(capsBucket, caps, drawableTypeBits ); + + // Since the passed GLProfile may be null, + // we use EGL_RENDERABLE_TYPE derived profile as created in the EGLGLCapabilities constructor. + final int allDrawableTypeBits = EGLConfigDrawableTypeBits(device, caps.getGLProfile(), config); + final int drawableTypeBits = winattrmask & allDrawableTypeBits; + + if( 0 == drawableTypeBits ) { + return null; + } + + return (EGLGLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(caps, drawableTypeBits); } public static int[] GLCapabilities2AttribList(GLCapabilitiesImmutable caps) { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java index 72dea9ead..d08685dcb 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java @@ -207,7 +207,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact throw new GLException("Graphics configuration get all configs (eglGetConfigs) call failed, error "+toHexString(EGL.eglGetError())); } if (numConfigs.get(0) > 0) { - availableCaps = eglConfigs2GLCaps(null, eglDisplay, configs, numConfigs.get(0), GLGraphicsConfigurationUtil.ALL_BITS, false); + availableCaps = eglConfigs2GLCaps(eglDevice, null, configs, numConfigs.get(0), GLGraphicsConfigurationUtil.ALL_BITS, false); if( null != availableCaps && availableCaps.size() > 1) { Collections.sort(availableCaps, EglCfgIDComparator); } @@ -250,7 +250,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact final EGLDrawableFactory factory = (EGLDrawableFactory) GLDrawableFactory.getEGLFactory(); capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, GLContext.isFBOAvailable(absDevice, glp), factory.canCreateGLPbuffer(absDevice) ); - EGLGraphicsConfiguration res = eglChooseConfig(eglDevice.getHandle(), capsChosen, capsReq, chooser, absScreen, nativeVisualID, forceTransparentFlag); + EGLGraphicsConfiguration res = eglChooseConfig(eglDevice, capsChosen, capsReq, chooser, absScreen, nativeVisualID, forceTransparentFlag); if(null==res) { if(DEBUG) { System.err.println("eglChooseConfig failed with given capabilities "+capsChosen); @@ -274,7 +274,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(DEBUG) { System.err.println("trying fixed caps (1): "+fixedCaps); } - res = eglChooseConfig(eglDevice.getHandle(), fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); + res = eglChooseConfig(eglDevice, fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); } if(null==res) { // @@ -292,7 +292,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(DEBUG) { System.err.println("trying fixed caps (2): "+fixedCaps); } - res = eglChooseConfig(eglDevice.getHandle(), fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); + res = eglChooseConfig(eglDevice, fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); } if(null==res) { // @@ -312,7 +312,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(DEBUG) { System.err.println("trying fixed caps (3): "+fixedCaps); } - res = eglChooseConfig(eglDevice.getHandle(), fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); + res = eglChooseConfig(eglDevice, fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false); } if(null==res) { throw new GLException("Graphics configuration failed [direct caps, eglGetConfig/chooser and fixed-caps(1-3)]"); @@ -324,15 +324,14 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact return res; } - static EGLGraphicsConfiguration eglChooseConfig(long eglDisplay, + static EGLGraphicsConfiguration eglChooseConfig(EGLGraphicsDevice device, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID, boolean forceTransparentFlag) { + final long eglDisplay = device.getHandle(); final GLProfile glp = capsChosen.getGLProfile(); - final boolean onscreen = capsChosen.isOnscreen(); - final boolean usePBuffer = capsChosen.isPBuffer(); - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, false); + final int winattrmask = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsChosen); List availableCaps = null; int recommendedIndex = -1; long recommendedEGLConfig = -1; @@ -345,7 +344,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact throw new GLException("EGLGraphicsConfiguration.eglChooseConfig: Get maxConfigs (eglGetConfigs) no configs"); } if (DEBUG) { - System.err.println("EGLGraphicsConfiguration.eglChooseConfig: eglChooseConfig eglDisplay "+toHexString(eglDisplay)+", nativeVisualID "+toHexString(nativeVisualID)+", onscreen "+onscreen+", usePBuffer "+usePBuffer+", "+capsChosen+", numConfigs "+numConfigs.get(0)); + System.err.println("EGLGraphicsConfiguration.eglChooseConfig: eglChooseConfig eglDisplay "+toHexString(eglDisplay)+", nativeVisualID "+toHexString(nativeVisualID)+", "+capsChosen+", numConfigs "+numConfigs.get(0)); } final IntBuffer attrs = Buffers.newDirectIntBuffer(EGLGraphicsConfiguration.GLCapabilities2AttribList(capsChosen)); @@ -359,7 +358,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact System.err.println("EGLGraphicsConfiguration.eglChooseConfig: #1 eglChooseConfig: false"); } } else if (numConfigs.get(0) > 0) { - availableCaps = eglConfigs2GLCaps(glp, eglDisplay, configs, numConfigs.get(0), winattrmask, forceTransparentFlag); + availableCaps = eglConfigs2GLCaps(device, glp, configs, numConfigs.get(0), winattrmask, forceTransparentFlag); if(availableCaps.size() > 0) { recommendedEGLConfig = configs.get(0); recommendedIndex = 0; @@ -384,7 +383,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact throw new GLException("EGLGraphicsConfiguration.eglChooseConfig: #2 Get all configs (eglGetConfigs) call failed, error "+toHexString(EGL.eglGetError())); } if (numConfigs.get(0) > 0) { - availableCaps = eglConfigs2GLCaps(glp, eglDisplay, configs, numConfigs.get(0), winattrmask, forceTransparentFlag); + availableCaps = eglConfigs2GLCaps(device, glp, configs, numConfigs.get(0), winattrmask, forceTransparentFlag); } } @@ -392,7 +391,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(DEBUG) { // FIXME: this happens on a ATI PC Emulation .. System.err.println("EGLGraphicsConfiguration.eglChooseConfig: #2 Graphics configuration 1st choice and 2nd choice failed - no configs"); - availableCaps = eglConfigs2GLCaps(glp, eglDisplay, configs, numConfigs.get(0), GLGraphicsConfigurationUtil.ALL_BITS, forceTransparentFlag); + availableCaps = eglConfigs2GLCaps(device, glp, configs, numConfigs.get(0), GLGraphicsConfigurationUtil.ALL_BITS, forceTransparentFlag); printCaps("AllCaps", availableCaps, System.err); } return null; @@ -439,12 +438,15 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact return new EGLGraphicsConfiguration(absScreen, chosenCaps, capsRequested, chooser); } - static List eglConfigs2GLCaps(GLProfile glp, long eglDisplay, PointerBuffer configs, int num, int winattrmask, boolean forceTransparentFlag) { - List caps = new ArrayList(num); + static List eglConfigs2GLCaps(EGLGraphicsDevice device, GLProfile glp, PointerBuffer configs, int num, int winattrmask, boolean forceTransparentFlag) { + List bucket = new ArrayList(num); for(int i=0; i caps, PrintStream out) { diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 82525cfde..55aea3a98 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -49,6 +49,7 @@ import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.OffscreenLayerSurface; import javax.media.nativewindow.ProxySurface; +import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLException; @@ -495,8 +496,14 @@ public abstract class MacOSXCGLContext extends GLContextImpl CGL.setContextOpacity(ctx, 0); } - GLCapabilitiesImmutable fixedCaps = MacOSXCGLGraphicsConfiguration.NSPixelFormat2GLCapabilities(chosenCaps.getGLProfile(), pixelFormat); + GLCapabilities fixedCaps = MacOSXCGLGraphicsConfiguration.NSPixelFormat2GLCapabilities(chosenCaps.getGLProfile(), pixelFormat); fixedCaps = GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(fixedCaps, chosenCaps.isBackgroundOpaque()); + if(!fixedCaps.isPBuffer()) { + // not handled, so copy them + fixedCaps.setFBO(chosenCaps.isFBO()); + fixedCaps.setBitmap(chosenCaps.isBitmap()); + fixedCaps.setOnscreen(chosenCaps.isOnscreen()); + } config.setChosenCapabilities(fixedCaps); if(DEBUG) { System.err.println("NS create fixedCaps: "+fixedCaps); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java index 202644bb3..10e8193e2 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java @@ -176,7 +176,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration return CGL.createPixelFormat(cglInternalAttributeToken, off, len, ivalues, 0); } - static GLCapabilitiesImmutable NSPixelFormat2GLCapabilities(GLProfile glp, long pixelFormat) { + static GLCapabilities NSPixelFormat2GLCapabilities(GLProfile glp, long pixelFormat) { return PixelFormat2GLCapabilities(glp, pixelFormat, true); } @@ -233,11 +233,11 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration return fmt.get(0); } - static GLCapabilitiesImmutable CGLPixelFormat2GLCapabilities(long pixelFormat) { + static GLCapabilities CGLPixelFormat2GLCapabilities(long pixelFormat) { return PixelFormat2GLCapabilities(null, pixelFormat, false); } - private static GLCapabilitiesImmutable PixelFormat2GLCapabilities(GLProfile glp, long pixelFormat, boolean nsUsage) { + private static GLCapabilities PixelFormat2GLCapabilities(GLProfile glp, long pixelFormat, boolean nsUsage) { int len = cglInternalAttributeToken.length; int off = 0; if ( !MacOSXCGLContext.isLionOrLater ) { diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java index 175622343..75c1c4441 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java @@ -40,6 +40,7 @@ package jogamp.opengl.windows.wgl; +import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.MutableSurface; @@ -52,6 +53,7 @@ import javax.media.opengl.GLProfile; import jogamp.nativewindow.windows.GDI; import jogamp.opengl.GLDrawableImpl; +import jogamp.opengl.GLGraphicsConfigurationUtil; import jogamp.opengl.windows.wgl.WindowsWGLDrawableFactory.SharedResource; // import javax.media.opengl.GLPbuffer; @@ -127,13 +129,16 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { System.out.println("Pbuffer config: " + config); } + final int winattrPbuffer = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(false /* onscreen */, false /* fbo */, true /* pbuffer */, false /* bitmap */); + int[] iattributes = new int [2*WindowsWGLGraphicsConfiguration.MAX_ATTRIBS]; float[] fattributes = new float[1]; int[] floatModeTmp = new int[1]; int niattribs = 0; - GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable)config.getChosenCapabilities(); - GLProfile glProfile = chosenCaps.getGLProfile(); + final GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable)config.getChosenCapabilities(); + final GLProfile glProfile = chosenCaps.getGLProfile(); + final AbstractGraphicsDevice device = config.getScreen().getDevice(); if (DEBUG) { System.out.println("Pbuffer parentHdc = " + toHexString(sharedHdc)); @@ -175,7 +180,8 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { if (DEBUG) { System.err.println("" + nformats + " suitable pixel formats found"); for (int i = 0; i < nformats; i++) { - WGLGLCapabilities dbgCaps = WindowsWGLGraphicsConfiguration.wglARBPFID2GLCapabilities(sharedResource, sharedHdc, pformats[i], glProfile, false, true); + WGLGLCapabilities dbgCaps = WindowsWGLGraphicsConfiguration.wglARBPFID2GLCapabilities(sharedResource, device, glProfile, + sharedHdc, pformats[i], winattrPbuffer); System.err.println("pixel format " + pformats[i] + " (index " + i + "): " + dbgCaps); } } @@ -239,7 +245,8 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { // Re-query chosen pixel format { - WGLGLCapabilities newCaps = WindowsWGLGraphicsConfiguration.wglARBPFID2GLCapabilities(sharedResource, sharedHdc, pfdid, glProfile, false, true); + WGLGLCapabilities newCaps = WindowsWGLGraphicsConfiguration.wglARBPFID2GLCapabilities(sharedResource, device, glProfile, + sharedHdc, pfdid, winattrPbuffer); if(null == newCaps) { throw new GLException("pbuffer creation error: unable to re-query chosen PFD ID: " + pfdid + ", hdc " + GLDrawableImpl.toHexString(tmpHdc)); } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java index 209589b29..5b21353c3 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java @@ -42,6 +42,7 @@ import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.opengl.GL; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLCapabilitiesChooser; +import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLPbuffer; @@ -104,9 +105,9 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio WGLGLCapabilities caps = null; if(hasARB) { - caps = wglARBPFID2GLCapabilities(sharedResource, hdc, pfdID, glp, onscreen, true /* pbuffer */); + caps = wglARBPFID2GLCapabilities(sharedResource, device, glp, hdc, pfdID, GLGraphicsConfigurationUtil.ALL_BITS); } else { - caps = PFD2GLCapabilities(glp, hdc, pfdID, onscreen); + caps = PFD2GLCapabilities(device, glp, hdc, pfdID, GLGraphicsConfigurationUtil.ALL_BITS); } if(null==caps) { throw new GLException("Couldn't choose Capabilities by: HDC 0x"+Long.toHexString(hdc)+ @@ -304,8 +305,8 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } static WGLGLCapabilities wglARBPFID2GLCapabilities(WindowsWGLDrawableFactory.SharedResource sharedResource, - long hdc, int pfdID, - GLProfile glp, boolean onscreen, boolean usePBuffer) { + AbstractGraphicsDevice device, GLProfile glp, + long hdc, int pfdID, int winattrbits) { if (!sharedResource.hasARBPixelFormat()) { return null; } @@ -319,17 +320,12 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio throw new GLException("wglARBPFID2GLCapabilities: Error getting pixel format attributes for pixel format " + pfdID + " of device context " + toHexString(hdc) + ", werr " + GDI.GetLastError()); } - List bucket = new ArrayList(1); - final int winattrbits = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, false); - if(AttribList2GLCapabilities(bucket, glp, hdc, pfdID, iattributes, niattribs, iresults, winattrbits)) { - return (WGLGLCapabilities) bucket.get(0); - } - return null; + return AttribList2GLCapabilities(device, glp, hdc, pfdID, iattributes, niattribs, iresults, winattrbits); } - static int[] wglChoosePixelFormatARB(long hdc, WindowsWGLDrawableFactory.SharedResource sharedResource, + static int[] wglChoosePixelFormatARB(WindowsWGLDrawableFactory.SharedResource sharedResource, AbstractGraphicsDevice device, GLCapabilitiesImmutable capabilities, - int[] iattributes, int accelerationMode, float[] fattributes) + long hdc, int[] iattributes, int accelerationMode, float[] fattributes) { if ( !WindowsWGLGraphicsConfiguration.GLCapabilities2AttribList(capabilities, @@ -366,27 +362,20 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio + Integer.toHexString(accelerationMode) + ": " + numFormats); for (int i = 0; i < numFormats; i++) { WGLGLCapabilities dbgCaps0 = WindowsWGLGraphicsConfiguration.wglARBPFID2GLCapabilities( - sharedResource, hdc, pformats[i], - capabilities.getGLProfile(), capabilities.isOnscreen(), capabilities.isPBuffer()); + sharedResource, device, capabilities.getGLProfile(), hdc, pformats[i], GLGraphicsConfigurationUtil.ALL_BITS); System.err.println("pixel format " + pformats[i] + " (index " + i + "): " + dbgCaps0); } } return pformats; } - static List wglARBPFIDs2GLCapabilities(WindowsWGLDrawableFactory.SharedResource sharedResource, - long hdc, int[] pfdIDs, GLProfile glp, boolean onscreen, boolean usePBuffer) { - final int winattrbits = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, false); - return wglARBPFIDs2GLCapabilitiesImpl(sharedResource, hdc, pfdIDs, glp, winattrbits); - } - static List wglARBPFIDs2AllGLCapabilities(WindowsWGLDrawableFactory.SharedResource sharedResource, - long hdc, int[] pfdIDs, GLProfile glp) { - return wglARBPFIDs2GLCapabilitiesImpl(sharedResource, hdc, pfdIDs, glp, GLGraphicsConfigurationUtil.ALL_BITS); + AbstractGraphicsDevice device, GLProfile glp, long hdc, int[] pfdIDs) { + return wglARBPFIDs2GLCapabilities(sharedResource, device, glp, hdc, pfdIDs, GLGraphicsConfigurationUtil.ALL_BITS); } - private static List wglARBPFIDs2GLCapabilitiesImpl(WindowsWGLDrawableFactory.SharedResource sharedResource, - long hdc, int[] pfdIDs, GLProfile glp, int winattrbits) { + static List wglARBPFIDs2GLCapabilities(WindowsWGLDrawableFactory.SharedResource sharedResource, + AbstractGraphicsDevice device, GLProfile glp, long hdc, int[] pfdIDs, int winattrbits) { if (!sharedResource.hasARBPixelFormat()) { return null; } @@ -401,7 +390,10 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio for(int i = 0; i= 1 && ((WindowsWGLContext)sharedResource.getContext()).getWGLExt().wglGetPixelFormatAttribivARB(hdc, pfdIDs[i], 0, niattribs, iattributes, 0, iresults, 0) ) { - AttribList2GLCapabilities(bucket, glp, hdc, pfdIDs[i], iattributes, niattribs, iresults, winattrbits); + final GLCapabilitiesImmutable caps = AttribList2GLCapabilities(device, glp, hdc, pfdIDs[i], iattributes, niattribs, iresults, winattrbits); + if(null != caps) { + bucket.add(caps); + } } else if (DEBUG) { System.err.println("wglARBPFIDs2GLCapabilities: Cannot get pixel format attributes for pixel format " + i + "/" + numFormats + ": " + pfdIDs[i] + ", " + @@ -582,7 +574,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return true; } - static int AttribList2DrawableTypeBits(final int[] iattribs, final int niattribs, final int[] iresults) { + static int AttribList2DrawableTypeBits(AbstractGraphicsDevice device, GLProfile glp, final int[] iattribs, final int niattribs, final int[] iresults) { int val = 0; for (int i = 0; i < niattribs; i++) { @@ -599,18 +591,20 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio break; } } + if ( GLContext.isFBOAvailable(device, glp) ) { + val |= GLGraphicsConfigurationUtil.FBO_BIT; + } return val; } - static boolean AttribList2GLCapabilities( List capsBucket, - final GLProfile glp, final long hdc, final int pfdID, final int[] iattribs, - final int niattribs, - final int[] iresults, final int winattrmask) { - final int allDrawableTypeBits = AttribList2DrawableTypeBits(iattribs, niattribs, iresults); + static WGLGLCapabilities AttribList2GLCapabilities(final AbstractGraphicsDevice device, + final GLProfile glp, final long hdc, final int pfdID, + final int[] iattribs, final int niattribs, final int[] iresults, final int winattrmask) { + final int allDrawableTypeBits = AttribList2DrawableTypeBits(device, glp, iattribs, niattribs, iresults); int drawableTypeBits = winattrmask & allDrawableTypeBits; if( 0 == drawableTypeBits ) { - return false; + return null; } PIXELFORMATDESCRIPTOR pfd = createPixelFormatDescriptor(); @@ -618,14 +612,13 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio // remove displayable bits, since pfdID is non displayable drawableTypeBits = drawableTypeBits & ~(GLGraphicsConfigurationUtil.WINDOW_BIT | GLGraphicsConfigurationUtil.BITMAP_BIT); if( 0 == drawableTypeBits ) { - return false; + return null; } // non displayable requested (pbuffer) } - WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); + final WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); res.setValuesByARB(iattribs, niattribs, iresults); - - return GLGraphicsConfigurationUtil.addGLCapabilitiesPermutations(capsBucket, res, drawableTypeBits ); + return (WGLGLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(res, drawableTypeBits); } // @@ -645,7 +638,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return pfdIDs; } - static int PFD2DrawableTypeBits(PIXELFORMATDESCRIPTOR pfd) { + static int PFD2DrawableTypeBits(AbstractGraphicsDevice device, GLProfile glp, PIXELFORMATDESCRIPTOR pfd) { int val = 0; int dwFlags = pfd.getDwFlags(); @@ -656,37 +649,30 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio if( 0 != (GDI.PFD_DRAW_TO_BITMAP & dwFlags ) ) { val |= GLGraphicsConfigurationUtil.BITMAP_BIT; } + if ( GLContext.isFBOAvailable(device, glp) ) { + val |= GLGraphicsConfigurationUtil.FBO_BIT; + } return val; } - static WGLGLCapabilities PFD2GLCapabilities(GLProfile glp, long hdc, int pfdID, boolean onscreen) { - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, false, false); - List capsBucket = new ArrayList(1); - if( PFD2GLCapabilities(capsBucket, glp, hdc, pfdID, winattrmask) ) { - return (WGLGLCapabilities) capsBucket.get(0); - } - return null; - } - - static boolean PFD2GLCapabilities(List capsBucket, final GLProfile glp, final long hdc, final int pfdID, final int winattrmask) { + static WGLGLCapabilities PFD2GLCapabilities(AbstractGraphicsDevice device, final GLProfile glp, final long hdc, final int pfdID, final int winattrmask) { PIXELFORMATDESCRIPTOR pfd = createPixelFormatDescriptor(hdc, pfdID); if(null == pfd) { - return false; + return null; } if ((pfd.getDwFlags() & GDI.PFD_SUPPORT_OPENGL) == 0) { - return false; + return null; } - final int allDrawableTypeBits = PFD2DrawableTypeBits(pfd); + final int allDrawableTypeBits = PFD2DrawableTypeBits(device, glp, pfd); final int drawableTypeBits = winattrmask & allDrawableTypeBits; if( 0 == drawableTypeBits ) { - return false; + return null; } - WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); + final WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); res.setValuesByGDI(); - - return GLGraphicsConfigurationUtil.addGLCapabilitiesPermutations(capsBucket, res, drawableTypeBits ); + return (WGLGLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(res, drawableTypeBits ); } static PIXELFORMATDESCRIPTOR GLCapabilities2PFD(GLCapabilitiesImmutable caps, PIXELFORMATDESCRIPTOR pfd) { diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java index 00ed91bb4..66a5821d3 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java @@ -131,10 +131,10 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat throw new GLException("Error: HDC is null"); } if (sharedResource.hasARBPixelFormat()) { - availableCaps = getAvailableGLCapabilitiesARB(hdc, sharedResource, capsChosen.getGLProfile()); + availableCaps = WindowsWGLGraphicsConfigurationFactory.getAvailableGLCapabilitiesARB(sharedResource, sharedResource.getDevice(), capsChosen.getGLProfile(), hdc); } if( null == availableCaps || availableCaps.isEmpty() ) { - availableCaps = getAvailableGLCapabilitiesGDI(hdc, capsChosen.getGLProfile()); + availableCaps = getAvailableGLCapabilitiesGDI(device, capsChosen.getGLProfile(), hdc); } } finally { if ( sharedResource.needsCurrentContext4ARBPFDQueries() ) { @@ -150,17 +150,20 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat return availableCaps; } - static List getAvailableGLCapabilitiesARB(long hdc, WindowsWGLDrawableFactory.SharedResource sharedResource, GLProfile glProfile) { + static List getAvailableGLCapabilitiesARB(WindowsWGLDrawableFactory.SharedResource sharedResource, AbstractGraphicsDevice device, GLProfile glProfile, long hdc) { int[] pformats = WindowsWGLGraphicsConfiguration.wglAllARBPFIDs((WindowsWGLContext)sharedResource.getContext(), hdc); - return WindowsWGLGraphicsConfiguration.wglARBPFIDs2AllGLCapabilities(sharedResource, hdc, pformats, glProfile); + return WindowsWGLGraphicsConfiguration.wglARBPFIDs2AllGLCapabilities(sharedResource, device, glProfile, hdc, pformats); } - static List getAvailableGLCapabilitiesGDI(long hdc, GLProfile glProfile) { + static List getAvailableGLCapabilitiesGDI(AbstractGraphicsDevice device, GLProfile glProfile, long hdc) { int[] pformats = WindowsWGLGraphicsConfiguration.wglAllGDIPFIDs(hdc); int numFormats = pformats.length; List bucket = new ArrayList(numFormats); for (int i = 0; i < numFormats; i++) { - WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(bucket, glProfile, hdc, pformats[i], GLGraphicsConfigurationUtil.ALL_BITS); + final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(device, glProfile, hdc, pformats[i], GLGraphicsConfigurationUtil.ALL_BITS); + if(null != caps) { + bucket.add(caps); + } } return bucket; } @@ -274,8 +277,8 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } } try { - if( !updateGraphicsConfigurationARB(hdc, extHDC, config, chooser, (WindowsWGLDrawableFactory)factory, pfdIDs) ) { - updateGraphicsConfigurationGDI(hdc, extHDC, config, chooser, pfdIDs); + if( !updateGraphicsConfigurationARB((WindowsWGLDrawableFactory)factory, config, chooser, hdc, extHDC, pfdIDs) ) { + updateGraphicsConfigurationGDI(config, chooser, hdc, extHDC, pfdIDs); } } finally { if (null != sharedContext) { @@ -284,10 +287,10 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } } - private static boolean updateGraphicsConfigurationARB(long hdc, boolean extHDC, WindowsWGLGraphicsConfiguration config, - CapabilitiesChooser chooser, WindowsWGLDrawableFactory factory, int[] pformats) { - AbstractGraphicsDevice device = config.getScreen().getDevice(); - WindowsWGLDrawableFactory.SharedResource sharedResource = factory.getOrCreateSharedResource(device); + private static boolean updateGraphicsConfigurationARB(WindowsWGLDrawableFactory factory, WindowsWGLGraphicsConfiguration config, CapabilitiesChooser chooser, + long hdc, boolean extHDC, int[] pformats) { + final AbstractGraphicsDevice device = config.getScreen().getDevice(); + final WindowsWGLDrawableFactory.SharedResource sharedResource = factory.getOrCreateSharedResource(device); if (null == sharedResource) { if (DEBUG) { @@ -302,11 +305,10 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat return false; } - GLCapabilitiesImmutable capsChosen = (GLCapabilitiesImmutable) config.getChosenCapabilities(); - boolean isOpaque = capsChosen.isBackgroundOpaque() && GDI.DwmIsCompositionEnabled(); - boolean onscreen = capsChosen.isOnscreen(); - boolean usePBuffer = capsChosen.isPBuffer(); - GLProfile glProfile = capsChosen.getGLProfile(); + final GLCapabilitiesImmutable capsChosen = (GLCapabilitiesImmutable) config.getChosenCapabilities(); + final boolean isOpaque = capsChosen.isBackgroundOpaque() && GDI.DwmIsCompositionEnabled(); + final int winattrbits = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsChosen); + final GLProfile glProfile = capsChosen.getGLProfile(); if(DEBUG) { System.err.println("translucency requested: "+(!capsChosen.isBackgroundOpaque())+", compositioning enabled: "+GDI.DwmIsCompositionEnabled()+" -> translucency "+(!isOpaque)); @@ -325,7 +327,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat + ", pixelformat " + presetPFDID); } pixelFormatSet = true; - pixelFormatCaps = WindowsWGLGraphicsConfiguration.wglARBPFID2GLCapabilities(sharedResource, hdc, presetPFDID, glProfile, onscreen, usePBuffer); + pixelFormatCaps = WindowsWGLGraphicsConfiguration.wglARBPFID2GLCapabilities(sharedResource, device, glProfile, hdc, presetPFDID, winattrbits); pixelFormatCaps = (WGLGLCapabilities) GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(pixelFormatCaps, isOpaque); } else { int recommendedIndex = -1; // recommended index @@ -337,17 +339,17 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat int[] iattributes = new int[2 * WindowsWGLGraphicsConfiguration.MAX_ATTRIBS]; float[] fattributes = new float[1]; int accelerationMode = WGLExt.WGL_FULL_ACCELERATION_ARB; - pformats = WindowsWGLGraphicsConfiguration.wglChoosePixelFormatARB(hdc, sharedResource, capsChosen, - iattributes, accelerationMode, fattributes); + pformats = WindowsWGLGraphicsConfiguration.wglChoosePixelFormatARB(sharedResource, device, capsChosen, + hdc, iattributes, accelerationMode, fattributes); if (null == pformats) { accelerationMode = WGLExt.WGL_GENERIC_ACCELERATION_ARB; - pformats = WindowsWGLGraphicsConfiguration.wglChoosePixelFormatARB(hdc, sharedResource, capsChosen, - iattributes, accelerationMode, fattributes); + pformats = WindowsWGLGraphicsConfiguration.wglChoosePixelFormatARB(sharedResource, device, capsChosen, + hdc, iattributes, accelerationMode, fattributes); } if (null == pformats) { accelerationMode = -1; // use what we are offered .. - pformats = WindowsWGLGraphicsConfiguration.wglChoosePixelFormatARB(hdc, sharedResource, capsChosen, - iattributes, accelerationMode, fattributes); + pformats = WindowsWGLGraphicsConfiguration.wglChoosePixelFormatARB(sharedResource, device, capsChosen, + hdc, iattributes, accelerationMode, fattributes); } if (null != pformats) { recommendedIndex = 0; @@ -371,13 +373,13 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } } - List availableCaps = - WindowsWGLGraphicsConfiguration.wglARBPFIDs2GLCapabilities(sharedResource, hdc, pformats, - glProfile, onscreen, usePBuffer); + List availableCaps = + WindowsWGLGraphicsConfiguration.wglARBPFIDs2GLCapabilities(sharedResource, device, glProfile, hdc, pformats, winattrbits); + if( null == availableCaps || 0 == availableCaps.size() ) { if (DEBUG) { System.err.println("updateGraphicsConfigurationARB: wglARBPFIDs2GLCapabilities failed with " + pformats.length + - " pfd ids, onscreen " + onscreen + ", pbuffer " + usePBuffer); + " pfd ids, " + GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrbits).toString()); Thread.dumpStack(); } return false; @@ -385,7 +387,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat if (DEBUG) { System.err.println("updateGraphicsConfigurationARB: " + pformats.length + - " pfd ids, onscreen " + onscreen + ", pbuffer " + usePBuffer + ", " + availableCaps.size() + " glcaps"); + " pfd ids, " + GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrbits).toString() + ", " + availableCaps.size() + " glcaps"); if(0 <= recommendedIndex) { System.err.println("updateGraphicsConfigurationARB: Used wglChoosePixelFormatARB to recommend pixel format " + pformats[recommendedIndex] + ", idx " + recommendedIndex +", "+availableCaps.get(recommendedIndex)); @@ -420,8 +422,8 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat return true; } - private static boolean updateGraphicsConfigurationGDI(long hdc, boolean extHDC, WindowsWGLGraphicsConfiguration config, - CapabilitiesChooser chooser, int[] pformats) { + private static boolean updateGraphicsConfigurationGDI(WindowsWGLGraphicsConfiguration config, CapabilitiesChooser chooser, long hdc, + boolean extHDC, int[] pformats) { GLCapabilitiesImmutable capsChosen = (GLCapabilitiesImmutable) config.getChosenCapabilities(); if(capsChosen.isPBuffer()) { if (DEBUG) { @@ -429,9 +431,11 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } return false; } - boolean onscreen = capsChosen.isOnscreen(); - GLProfile glProfile = capsChosen.getGLProfile(); - + // final boolean onscreen = capsChosen.isOnscreen(); + // final boolean useFBO = capsChosen.isFBO(); + final GLProfile glProfile = capsChosen.getGLProfile(); + final int winattrmask = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsChosen); + List availableCaps = new ArrayList(); int pfdID; // chosen or preset PFD ID WGLGLCapabilities pixelFormatCaps = null; // chosen or preset PFD ID's caps @@ -447,15 +451,17 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat + ", pixelformat " + pfdID); } pixelFormatSet = true; - pixelFormatCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(glProfile, hdc, pfdID, onscreen); + pixelFormatCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(config.getScreen().getDevice(), glProfile, hdc, pfdID, winattrmask); } else { if(null == pformats) { pformats = WindowsWGLGraphicsConfiguration.wglAllGDIPFIDs(hdc); } - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, false, false); for (int i = 0; i < pformats.length; i++) { - WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(availableCaps, glProfile, hdc, pformats[i], winattrmask); + final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(config.getScreen().getDevice(), glProfile, hdc, pformats[i], winattrmask); + if(null != caps) { + availableCaps.add(caps); + } } // 1st choice: get GLCapabilities based on users GLCapabilities setting recommendedIndex as preferred choice diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java index b458fffe1..d169945fe 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java @@ -33,10 +33,6 @@ package jogamp.opengl.x11.glx; -import java.util.ArrayList; -import java.util.List; - -import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.VisualIDHolder; @@ -58,6 +54,7 @@ import jogamp.opengl.GLGraphicsConfigurationUtil; import com.jogamp.common.nio.PointerBuffer; import com.jogamp.nativewindow.x11.X11GraphicsConfiguration; +import com.jogamp.nativewindow.x11.X11GraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsScreen; public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implements Cloneable { @@ -71,7 +68,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem } static X11GLXGraphicsConfiguration create(GLProfile glp, X11GraphicsScreen x11Screen, int fbcfgID) { - final AbstractGraphicsDevice device = x11Screen.getDevice(); + final X11GraphicsDevice device = (X11GraphicsDevice) x11Screen.getDevice(); final long display = device.getHandle(); if(0==display) { throw new GLException("Display null of "+x11Screen); @@ -85,7 +82,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem glp = GLProfile.getDefault(x11Screen.getDevice()); } final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); - final X11GLCapabilities caps = GLXFBConfig2GLCapabilities(glp, device, fbcfg, true, true, true, factory.isGLXMultisampleAvailable(device)); + final X11GLCapabilities caps = GLXFBConfig2GLCapabilities(device, glp, fbcfg, GLGraphicsConfigurationUtil.ALL_BITS, factory.isGLXMultisampleAvailable(device)); if(null==caps) { throw new GLException("GLCapabilities null of "+toHexString(fbcfg)); } @@ -247,7 +244,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem return true; } - static int FBCfgDrawableTypeBits(final AbstractGraphicsDevice device, GLProfile glp, final long fbcfg) { + static int FBCfgDrawableTypeBits(final X11GraphicsDevice device, GLProfile glp, final long fbcfg) { int val = 0; int[] tmp = new int[1]; @@ -268,19 +265,6 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem return val; } - static X11GLCapabilities GLXFBConfig2GLCapabilities(GLProfile glp, AbstractGraphicsDevice device, long fbcfg, - boolean relaxed, boolean onscreen, boolean usePBuffer, - boolean isMultisampleAvailable) { - ArrayList bucket = new ArrayList(); - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, false); - if( GLXFBConfig2GLCapabilities(bucket, glp, device, fbcfg, winattrmask, isMultisampleAvailable) ) { - return (X11GLCapabilities) bucket.get(0); - } else if ( relaxed && GLXFBConfig2GLCapabilities(bucket, glp, device, fbcfg, GLGraphicsConfigurationUtil.ALL_BITS, isMultisampleAvailable) ) { - return (X11GLCapabilities) bucket.get(0); - } - return null; - } - static XRenderDirectFormat XVisual2XRenderMask(long dpy, long visual) { XRenderPictFormat renderPictFmt = X11Lib.XRenderFindVisualFormat(dpy, visual); if(null == renderPictFmt) { @@ -289,9 +273,8 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem return renderPictFmt.getDirect(); } - static boolean GLXFBConfig2GLCapabilities(List capsBucket, - GLProfile glp, AbstractGraphicsDevice device, long fbcfg, - int winattrmask, boolean isMultisampleAvailable) { + static X11GLCapabilities GLXFBConfig2GLCapabilities(X11GraphicsDevice device, GLProfile glp, long fbcfg, + int winattrmask, boolean isMultisampleAvailable) { final int allDrawableTypeBits = FBCfgDrawableTypeBits(device, glp, fbcfg); int drawableTypeBits = winattrmask & allDrawableTypeBits; @@ -307,18 +290,18 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem } if( 0 == drawableTypeBits ) { - return false; + return null; } int[] tmp = new int[1]; if(GLX.GLX_BAD_ATTRIBUTE == GLX.glXGetFBConfigAttrib(display, fbcfg, GLX.GLX_RENDER_TYPE, tmp, 0)) { - return false; + return null; } if( 0 == ( GLX.GLX_RGBA_BIT & tmp[0] ) ) { - return false; // no RGBA -> color index not supported + return null; // no RGBA -> color index not supported } - GLCapabilities res = new X11GLCapabilities(visualInfo, fbcfg, fbcfgid, glp); + X11GLCapabilities res = new X11GLCapabilities(visualInfo, fbcfg, fbcfgid, glp); if (isMultisampleAvailable) { res.setSampleBuffers(glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLE_BUFFERS, tmp, 0) != 0); res.setNumSamples (glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLES, tmp, 0)); @@ -353,7 +336,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem res.setPbufferFloatingPointBuffers(glXGetFBConfig(display, fbcfg, GLXExt.GLX_FLOAT_COMPONENTS_NV, tmp, 0) != GL.GL_FALSE); } catch (Exception e) {} - return GLGraphicsConfigurationUtil.addGLCapabilitiesPermutations(capsBucket, res, drawableTypeBits ); + return (X11GLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(res, drawableTypeBits); } private static String glXGetFBConfigErrorCode(int err) { @@ -408,30 +391,34 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem return res; } - static boolean XVisualInfo2GLCapabilities(List capsBucket, - GLProfile glp, long display, XVisualInfo info, - final int winattrmask, boolean isMultisampleEnabled) { - final int allDrawableTypeBits = GLGraphicsConfigurationUtil.WINDOW_BIT | GLGraphicsConfigurationUtil.BITMAP_BIT ; + static X11GLCapabilities XVisualInfo2GLCapabilities(final X11GraphicsDevice device, GLProfile glp, XVisualInfo info, + final int winattrmask, boolean isMultisampleEnabled) { + final int allDrawableTypeBits = GLGraphicsConfigurationUtil.WINDOW_BIT | + GLGraphicsConfigurationUtil.BITMAP_BIT | + ( GLContext.isFBOAvailable(device, glp) ? GLGraphicsConfigurationUtil.FBO_BIT : 0 ) + ; + final int drawableTypeBits = winattrmask & allDrawableTypeBits; if( 0 == drawableTypeBits ) { - return false; + return null; } + final long display = device.getHandle(); int[] tmp = new int[1]; int val = glXGetConfig(display, info, GLX.GLX_USE_GL, tmp, 0); if (val == 0) { if(DEBUG) { System.err.println("Visual ("+toHexString(info.getVisualid())+") does not support OpenGL"); } - return false; + return null; } val = glXGetConfig(display, info, GLX.GLX_RGBA, tmp, 0); if (val == 0) { if(DEBUG) { System.err.println("Visual ("+toHexString(info.getVisualid())+") does not support RGBA"); } - return false; + return null; } GLCapabilities res = new X11GLCapabilities(info, glp); @@ -470,7 +457,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem res.setAccumBlueBits (glXGetConfig(display, info, GLX.GLX_ACCUM_BLUE_SIZE, tmp, 0)); res.setAccumAlphaBits(glXGetConfig(display, info, GLX.GLX_ACCUM_ALPHA_SIZE, tmp, 0)); - return GLGraphicsConfigurationUtil.addGLCapabilitiesPermutations(capsBucket, res, drawableTypeBits); + return (X11GLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(res, drawableTypeBits); } private static String glXGetConfigErrorCode(int err) { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java index 234b06bdb..3189f933f 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java @@ -152,12 +152,12 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF // Utilizing FBConfig // - AbstractGraphicsDevice absDevice = x11Screen.getDevice(); - long display = absDevice.getHandle(); + final X11GraphicsDevice absDevice = (X11GraphicsDevice) x11Screen.getDevice(); + final long display = absDevice.getHandle(); - int screen = x11Screen.getIndex(); - int[] count = { -1 }; - ArrayList availableCaps = new ArrayList(); + final int screen = x11Screen.getIndex(); + final int[] count = { -1 }; + final ArrayList availableCaps = new ArrayList(); fbcfgsL = GLX.glXChooseFBConfig(display, screen, null, 0, count, 0); if (fbcfgsL == null || fbcfgsL.limit()<=0) { @@ -167,18 +167,19 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF return null; } for (int i = 0; i < fbcfgsL.limit(); i++) { - if( !X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(availableCaps, glProfile, absDevice, fbcfgsL.get(i), GLGraphicsConfigurationUtil.ALL_BITS, isMultisampleAvailable) ) { - if(DEBUG) { - System.err.println("X11GLXGraphicsConfiguration.getAvailableGLCapabilitiesFBConfig: FBConfig invalid (2): ("+x11Screen+"): fbcfg: "+toHexString(fbcfgsL.get(i))); - } + final GLCapabilitiesImmutable caps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(absDevice, glProfile, fbcfgsL.get(i), GLGraphicsConfigurationUtil.ALL_BITS, isMultisampleAvailable); + if(null != caps) { + availableCaps.add(caps); + } else if(DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.getAvailableGLCapabilitiesFBConfig: FBConfig invalid (2): ("+x11Screen+"): fbcfg: "+toHexString(fbcfgsL.get(i))); } } return availableCaps; } static List getAvailableGLCapabilitiesXVisual(X11GraphicsScreen x11Screen, GLProfile glProfile, boolean isMultisampleAvailable) { - AbstractGraphicsDevice absDevice = x11Screen.getDevice(); - long display = absDevice.getHandle(); + final X11GraphicsDevice absDevice = (X11GraphicsDevice) x11Screen.getDevice(); + final long display = absDevice.getHandle(); int screen = x11Screen.getIndex(); @@ -191,10 +192,11 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } ArrayList availableCaps = new ArrayList(); for (int i = 0; i < infos.length; i++) { - if( !X11GLXGraphicsConfiguration.XVisualInfo2GLCapabilities(availableCaps, glProfile, display, infos[i], GLGraphicsConfigurationUtil.ALL_BITS, isMultisampleAvailable) ) { - if(DEBUG) { - System.err.println("X11GLXGraphicsConfiguration.getAvailableGLCapabilitiesXVisual: XVisual invalid: ("+x11Screen+"): fbcfg: "+toHexString(infos[i].getVisualid())); - } + final GLCapabilitiesImmutable caps = X11GLXGraphicsConfiguration.XVisualInfo2GLCapabilities(absDevice, glProfile, infos[i], GLGraphicsConfigurationUtil.ALL_BITS, isMultisampleAvailable); + if(null != caps) { + availableCaps.add(caps); + } if(DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.getAvailableGLCapabilitiesXVisual: XVisual invalid: ("+x11Screen+"): fbcfg: "+toHexString(infos[i].getVisualid())); } } return availableCaps; @@ -238,8 +240,8 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } static X11GLXGraphicsConfiguration fetchGraphicsConfigurationFBConfig(X11GraphicsScreen x11Screen, int fbID, GLProfile glp) { - final AbstractGraphicsDevice absDevice = x11Screen.getDevice(); - final long display = absDevice.getHandle(); + final X11GraphicsDevice x11Device = (X11GraphicsDevice) x11Screen.getDevice(); + final long display = x11Device.getHandle(); final int screen = x11Screen.getIndex(); final long fbcfg = X11GLXGraphicsConfiguration.glXFBConfigID2FBConfig(display, screen, fbID); @@ -251,7 +253,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); - final X11GLCapabilities caps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(glp, absDevice, fbcfg, true, true, true, factory.isGLXMultisampleAvailable(absDevice)); + final X11GLCapabilities caps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(x11Device, glp, fbcfg, GLGraphicsConfigurationUtil.ALL_BITS, factory.isGLXMultisampleAvailable(x11Device)); return new X11GLXGraphicsConfiguration(x11Screen, caps, caps, new DefaultGLCapabilitiesChooser()); } @@ -262,22 +264,19 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF int recommendedIndex = -1; PointerBuffer fbcfgsL = null; GLProfile glProfile = capsChosen.getGLProfile(); - boolean onscreen = capsChosen.isOnscreen(); - boolean usePBuffer = capsChosen.isPBuffer(); - boolean useFBO = capsChosen.isFBO(); // Utilizing FBConfig // - AbstractGraphicsDevice absDevice = x11Screen.getDevice(); - long display = absDevice.getHandle(); + X11GraphicsDevice x11Device = (X11GraphicsDevice) x11Screen.getDevice(); + long display = x11Device.getHandle(); int screen = x11Screen.getIndex(); final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); - final boolean isMultisampleAvailable = factory.isGLXMultisampleAvailable(absDevice); + final boolean isMultisampleAvailable = factory.isGLXMultisampleAvailable(x11Device); int[] attribs = X11GLXGraphicsConfiguration.GLCapabilities2AttribList(capsChosen, true, isMultisampleAvailable, display, screen); int[] count = { -1 }; List availableCaps = new ArrayList(); - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer, useFBO); + final int winattrmask = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsChosen); // 1st choice: get GLCapabilities based on users GLCapabilities setting recommendedIndex as preferred choice, // skipped if xvisualID is given if( VisualIDHolder.VID_UNDEFINED == xvisualID ) { @@ -285,10 +284,11 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } if (fbcfgsL != null && fbcfgsL.limit()>0) { for (int i = 0; i < fbcfgsL.limit(); i++) { - if( !X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(availableCaps, glProfile, absDevice, fbcfgsL.get(i), winattrmask, isMultisampleAvailable) ) { - if(DEBUG) { - System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: FBConfig invalid (1): ("+x11Screen+","+capsChosen+"): fbcfg: "+toHexString(fbcfgsL.get(i))); - } + final GLCapabilitiesImmutable caps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(x11Device, glProfile, fbcfgsL.get(i), winattrmask, isMultisampleAvailable); + if( null != caps ) { + availableCaps.add(caps); + } else if(DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: FBConfig invalid (1): ("+x11Screen+","+capsChosen+"): fbcfg: "+toHexString(fbcfgsL.get(i))); } } if(availableCaps.size() > 0) { @@ -318,10 +318,11 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } for (int i = 0; i < fbcfgsL.limit(); i++) { - if( !X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(availableCaps, glProfile, absDevice, fbcfgsL.get(i), winattrmask, isMultisampleAvailable) ) { - if(DEBUG) { - System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: FBConfig invalid (2): ("+x11Screen+"): fbcfg: "+toHexString(fbcfgsL.get(i))); - } + final GLCapabilitiesImmutable caps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(x11Device, glProfile, fbcfgsL.get(i), winattrmask, isMultisampleAvailable); + if( null != caps ) { + availableCaps.add(caps); + } else if(DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: FBConfig invalid (2): ("+x11Screen+"): fbcfg: "+toHexString(fbcfgsL.get(i))); } } } @@ -374,11 +375,11 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } GLProfile glProfile = capsChosen.getGLProfile(); - final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(capsChosen.isOnscreen(), false /* pbuffer */, false); + final int winattrmask = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsChosen.isOnscreen(), capsChosen.isFBO(), false /* pbuffer */, capsChosen.isBitmap()); List availableCaps = new ArrayList(); int recommendedIndex = -1; - AbstractGraphicsDevice absDevice = x11Screen.getDevice(); + X11GraphicsDevice absDevice = (X11GraphicsDevice) x11Screen.getDevice(); long display = absDevice.getHandle(); int screen = x11Screen.getIndex(); @@ -411,15 +412,15 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } for (int i = 0; i < infos.length; i++) { - if( !X11GLXGraphicsConfiguration.XVisualInfo2GLCapabilities(availableCaps, glProfile, display, infos[i], winattrmask, isMultisampleAvailable) ) { - if(DEBUG) { - System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationXVisual: XVisual invalid: ("+x11Screen+"): fbcfg: "+toHexString(infos[i].getVisualid())); - } - } else { + final GLCapabilitiesImmutable caps = X11GLXGraphicsConfiguration.XVisualInfo2GLCapabilities(absDevice, glProfile, infos[i], winattrmask, isMultisampleAvailable); + if( null != caps ) { + availableCaps.add(caps); // Attempt to find the visual chosenIndex by glXChooseVisual, if not translucent if (capsChosen.isBackgroundOpaque() && recommendedVis != null && recommendedVis.getVisualid() == infos[i].getVisualid()) { recommendedIndex = availableCaps.size() - 1; } + } else if(DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationXVisual: XVisual invalid: ("+x11Screen+"): fbcfg: "+toHexString(infos[i].getVisualid())); } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java index cb33aec5e..50e6ed46c 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java +++ b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java @@ -61,6 +61,9 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { // Switch for on- or offscreen private boolean onscreen = true; + + // offscreen bitmap mode + private boolean isBitmap = false; /** Creates a Capabilities object. All attributes are in a default state. @@ -85,6 +88,8 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { public int hashCode() { // 31 * x == (x << 5) - x int hash = 31 + this.redBits; + hash = ((hash << 5) - hash) + ( this.onscreen ? 1 : 0 ); + hash = ((hash << 5) - hash) + ( this.isBitmap ? 1 : 0 ); hash = ((hash << 5) - hash) + this.greenBits; hash = ((hash << 5) - hash) + this.blueBits; hash = ((hash << 5) - hash) + this.alphaBits; @@ -93,7 +98,6 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { hash = ((hash << 5) - hash) + this.transparentValueGreen; hash = ((hash << 5) - hash) + this.transparentValueBlue; hash = ((hash << 5) - hash) + this.transparentValueAlpha; - hash = ((hash << 5) - hash) + ( this.onscreen ? 1 : 0 ); return hash; } @@ -109,12 +113,13 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { other.getBlueBits()==blueBits && other.getAlphaBits()==alphaBits && other.isBackgroundOpaque()==backgroundOpaque && - other.isOnscreen()==onscreen; - if(!backgroundOpaque) { - res = res && other.getTransparentRedValue()==transparentValueRed && - other.getTransparentGreenValue()==transparentValueGreen && - other.getTransparentBlueValue()==transparentValueBlue && - other.getTransparentAlphaValue()==transparentValueAlpha; + other.isOnscreen()==onscreen && + other.isBitmap()==isBitmap; + if(res && !backgroundOpaque) { + res = other.getTransparentRedValue()==transparentValueRed && + other.getTransparentGreenValue()==transparentValueGreen && + other.getTransparentBlueValue()==transparentValueBlue && + other.getTransparentAlphaValue()==transparentValueAlpha; } return res; @@ -158,9 +163,6 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { } } - /** 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. */ @Override public final int getRedBits() { return redBits; @@ -173,9 +175,6 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { 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. */ @Override public final int getGreenBits() { return greenBits; @@ -188,9 +187,6 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { 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. */ @Override public final int getBlueBits() { return blueBits; @@ -203,9 +199,6 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { 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. */ @Override public final int getAlphaBits() { return alphaBits; @@ -228,10 +221,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { } /** - * Defaults to true, ie. opaque surface. - *

      - * On supported platforms, setting opaque to false may result in a translucent surface.

      - * + * Sets whether the surface shall be opaque or translucent. *

      * Platform implementations may need an alpha component in the surface (eg. Windows), * or expect pre-multiplied alpha values (eg. X11/XRender).
      @@ -240,16 +230,9 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { * Please note that in case alpha is required on the platform the * clear color shall have an alpha lower than 1.0 to allow anything shining through. *

      - * *

      * Mind that translucency may cause a performance penalty - * due to the composite work required by the window manager.

      - * - *

      - * The platform implementation may utilize the transparency RGBA values.
      - * This is true for the original GLX transparency specification, which is no more used today.
      - * Actually these values are currently not used by any implementation, - * so we may mark them deprecated soon, if this doesn't change.
      + * due to the composite work required by the window manager. *

      */ public void setBackgroundOpaque(boolean opaque) { @@ -259,56 +242,65 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { } } - /** Indicates whether the background of this OpenGL context should - be considered opaque. Defaults to true. - - @see #setBackgroundOpaque - */ @Override public final boolean isBackgroundOpaque() { return backgroundOpaque; } - /** Sets whether the drawable surface supports onscreen. - Defaults to true. - */ + /** + * Sets whether the surface shall be on- or offscreen. + *

      + * Defaults to true. + *

      + *

      + * If requesting an offscreen surface without further selection of it's mode, + * e.g. FBO, Pbuffer or {@link #setBitmap(boolean) bitmap}, + * the implementation will choose the best available offscreen mode. + *

      + * @param onscreen + */ public void setOnscreen(boolean onscreen) { this.onscreen=onscreen; } - /** Indicates whether the drawable surface is onscreen. - Defaults to true. - */ @Override public final boolean isOnscreen() { return onscreen; } - /** Gets the transparent red value for the frame buffer configuration. - * This value is undefined if {@link #isBackgroundOpaque()} equals true. - * @see #setTransparentRedValue - */ + /** + * Requesting offscreen bitmap mode. + *

      + * If enabled this method also invokes {@link #setOnscreen(int) setOnscreen(false)}. + *

      + *

      + * Defaults to false. + *

      + *

      + * Requesting offscreen bitmap mode disables the offscreen auto selection. + *

      + */ + public void setBitmap(boolean enable) { + if(enable) { + setOnscreen(false); + } + isBitmap = enable; + } + + @Override + public boolean isBitmap() { + return isBitmap; + } + @Override public final int getTransparentRedValue() { return transparentValueRed; } - /** Gets the transparent green value for the frame buffer configuration. - * This value is undefined if {@link #isBackgroundOpaque()} equals true. - * @see #setTransparentGreenValue - */ @Override public final int getTransparentGreenValue() { return transparentValueGreen; } - /** Gets the transparent blue value for the frame buffer configuration. - * This value is undefined if {@link #isBackgroundOpaque()} equals true. - * @see #setTransparentBlueValue - */ @Override public final int getTransparentBlueValue() { return transparentValueBlue; } - /** Gets the transparent alpha value for the frame buffer configuration. - * This value is undefined if {@link #isBackgroundOpaque()} equals true. - * @see #setTransparentAlphaValue - */ @Override public final int getTransparentAlphaValue() { return transparentValueAlpha; } @@ -342,32 +334,58 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { @Override public StringBuilder toString(StringBuilder sink) { + return toString(sink, true); + } + + /** Returns a textual representation of this Capabilities + object. */ + @Override + public String toString() { + StringBuilder msg = new StringBuilder(); + msg.append("Caps["); + toString(msg); + msg.append("]"); + return msg.toString(); + } + + /** Return a textual representation of this object's on/off screen state. Use the given StringBuffer [optional]. */ + protected StringBuilder onoffScreenToString(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); } if(onscreen) { sink.append("on-scr"); } else { - sink.append("offscr"); + sink.append("offscr["); + } + if(isBitmap) { + sink.append("bitmap"); + } else if(onscreen) { + sink.append("."); // no additional off-screen modes besides on-screen + } else { + sink.append("auto-cfg"); // auto-config off-screen mode + } + sink.append("]"); + + return sink; + } + + protected StringBuilder toString(StringBuilder sink, boolean withOnOffScreen) { + if(null == sink) { + sink = new StringBuilder(); } - sink.append(", rgba 0x").append(toHexString(redBits)).append("/").append(toHexString(greenBits)).append("/").append(toHexString(blueBits)).append("/").append(toHexString(alphaBits)); + sink.append("rgba 0x").append(toHexString(redBits)).append("/").append(toHexString(greenBits)).append("/").append(toHexString(blueBits)).append("/").append(toHexString(alphaBits)); if(backgroundOpaque) { sink.append(", opaque"); } else { sink.append(", trans-rgba 0x").append(toHexString(transparentValueRed)).append("/").append(toHexString(transparentValueGreen)).append("/").append(toHexString(transparentValueBlue)).append("/").append(toHexString(transparentValueAlpha)); } + if(withOnOffScreen) { + sink.append(", "); + onoffScreenToString(sink); + } return sink; } + protected final String toHexString(int val) { return Integer.toHexString(val); } - - /** Returns a textual representation of this Capabilities - object. */ - @Override - public String toString() { - StringBuilder msg = new StringBuilder(); - msg.append("Caps["); - toString(msg); - msg.append("]"); - return msg.toString(); - } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java index b984a4626..b801ab457 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java @@ -39,44 +39,65 @@ import com.jogamp.common.type.WriteCloneable; public interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable, Comparable { /** - * Returns the number of bits requested for the color buffer's red + * Returns the number of bits 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. */ int getRedBits(); /** - * Returns the number of bits requested for the color buffer's green + * Returns the number of bits 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. */ int getGreenBits(); /** - * Returns the number of bits requested for the color buffer's blue + * Returns the number of bits 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. */ int getBlueBits(); /** - * Returns the number of bits requested for the color buffer's alpha + * Returns the number of bits 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. */ int getAlphaBits(); /** - * Indicates whether the background of this OpenGL context should be - * considered opaque. Defaults to true. + * Returns whether an opaque or translucent surface is requested, supported or chosen. + *

      + * Default is true, i.e. opaque. + *

      */ boolean isBackgroundOpaque(); /** - * Indicates whether the drawable surface is onscreen. Defaults to true. + * Returns whether an on- or offscreen surface is requested, available or chosen. + *

      + * Default is true, i.e. onscreen. + *

      + *

      + * Mind that an capabilities intance w/ available semantics + * may show onscreen, but also the offscreen modes FBO, Pbuffer or {@link #setBitmap(boolean) bitmap}. + * This is valid, since one native configuration maybe used for either functionality. + *

      */ boolean isOnscreen(); + /** + * Returns whether bitmap offscreen mode is requested, available or chosen. + *

      + * Default is false. + *

      + *

      + * For chosen capabilities, only the selected offscreen surface is set to true. + *

      + */ + boolean isBitmap(); + /** * Gets the transparent red value for the frame buffer configuration. This * value is undefined if; equals true. diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java index 9d4b112b1..744c7e6d5 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java @@ -68,6 +68,9 @@ import jogamp.nativewindow.Debug; public class DefaultCapabilitiesChooser implements CapabilitiesChooser { private static final boolean DEBUG = Debug.isPropertyDefined("nativewindow.debug.CapabilitiesChooser", true); + private final static int NO_SCORE = -9999999; + private final static int COLOR_MISMATCH_PENALTY_SCALE = 36; + public int chooseCapabilities(final CapabilitiesImmutable desired, final List available, final int windowSystemRecommendedChoice) { @@ -92,8 +95,6 @@ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { // Create score array int[] scores = new int[availnum]; - int NO_SCORE = -9999999; - int COLOR_MISMATCH_PENALTY_SCALE = 36; for (int i = 0; i < availnum; i++) { scores[i] = NO_SCORE; } @@ -103,6 +104,10 @@ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { if (cur == null) { continue; } + if (desired.isOnscreen() && !cur.isOnscreen()) { + continue; // requested onscreen, but n/a + } + int score = 0; // Compute difference in color depth score += (COLOR_MISMATCH_PENALTY_SCALE * diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java new file mode 100644 index 000000000..0782e8915 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java @@ -0,0 +1,233 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.io.IOException; + +import javax.media.nativewindow.CapabilitiesImmutable; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLProfile; + +import org.junit.Assert; +import org.junit.Test; + +import com.jogamp.newt.NewtFactory; +import com.jogamp.newt.Window; +import com.jogamp.opengl.JoglVersion; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.UITestCase; + +public class TestGLCapabilities01NEWT extends UITestCase { + static final int width = 100; + static final int height = 100; + + boolean checkProfile(String profile) { + if( !GLProfile.isAvailable(profile) ) { + System.err.println("Profile "+profile+" n/a"); + return false; + } + return true; + } + + void doTest(GLCapabilities reqGLCaps, GLEventListener demo) throws InterruptedException { + System.out.println("Requested GL Caps: "+reqGLCaps); + + // + // Create native windowing resources .. X11/Win/OSX + // + final Window window = NewtFactory.createWindow(reqGLCaps); + Assert.assertNotNull(window); + window.setSize(width, height); + window.setVisible(true); + Assert.assertTrue(AWTRobotUtil.waitForVisible(window, true)); + Assert.assertTrue(AWTRobotUtil.waitForRealized(window, true)); + System.out.println("Window: "+window.getClass().getName()); + + // Check caps of NativeWindow config w/o GL + final CapabilitiesImmutable chosenCaps = window.getGraphicsConfiguration().getChosenCapabilities(); + System.out.println("Window Caps Pre_GL: "+chosenCaps); + Assert.assertNotNull(chosenCaps); + Assert.assertTrue(chosenCaps.getGreenBits()>5); + Assert.assertTrue(chosenCaps.getBlueBits()>5); + Assert.assertTrue(chosenCaps.getRedBits()>5); + + // + // Create native OpenGL resources .. XGL/WGL/CGL .. + // equivalent to GLAutoDrawable methods: setVisible(true) + // + final GLDrawableFactory factory = GLDrawableFactory.getFactory(reqGLCaps.getGLProfile()); + + final GLDrawable drawable = factory.createGLDrawable(window); + Assert.assertNotNull(drawable); + System.out.println("Drawable Pre-GL(0): "+drawable.getClass().getName()+", "+drawable.getNativeSurface().getClass().getName()); + + // + drawable.setRealized(true); + Assert.assertTrue(drawable.isRealized()); + + System.out.println("Window Caps PostGL : "+window.getGraphicsConfiguration().getChosenCapabilities()); + System.out.println("Drawable Post-GL(1): "+drawable.getClass().getName()+", "+drawable.getNativeSurface().getClass().getName()); + + // Check caps of GLDrawable after realization + final GLCapabilitiesImmutable chosenGLCaps = drawable.getChosenGLCapabilities(); + System.out.println("Chosen GL Caps(1): "+chosenGLCaps); + Assert.assertNotNull(chosenGLCaps); + Assert.assertTrue(chosenGLCaps.getGreenBits()>5); + Assert.assertTrue(chosenGLCaps.getBlueBits()>5); + Assert.assertTrue(chosenGLCaps.getRedBits()>5); + Assert.assertTrue(chosenGLCaps.getDepthBits()>4); + Assert.assertEquals(reqGLCaps.isOnscreen(), chosenGLCaps.isOnscreen()); + Assert.assertEquals(reqGLCaps.isFBO(), chosenGLCaps.isFBO()); + Assert.assertEquals(reqGLCaps.isPBuffer(), chosenGLCaps.isPBuffer()); + Assert.assertEquals(reqGLCaps.isBitmap(), chosenGLCaps.isBitmap()); + if(chosenGLCaps.isOnscreen() || chosenGLCaps.isFBO()) { + // dbl buffer may be disabled w/ offscreen pbuffer and bitmap + Assert.assertEquals(reqGLCaps.getDoubleBuffered(), chosenGLCaps.getDoubleBuffered()); + } + + GLContext context = drawable.createContext(null); + Assert.assertNotNull(context); + int res = context.makeCurrent(); + Assert.assertTrue(GLContext.CONTEXT_CURRENT_NEW==res || GLContext.CONTEXT_CURRENT==res); + context.release(); + + System.out.println("Chosen GL Caps(2): "+drawable.getChosenGLCapabilities()); + System.out.println("Drawable Post-GL(2): "+drawable.getClass().getName()+", "+drawable.getNativeSurface().getClass().getName()); + + drawable.setRealized(false); + window.destroy(); + } + + @Test + public void testAvailableInfo() { + GLDrawableFactory f = GLDrawableFactory.getDesktopFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + f = GLDrawableFactory.getEGLFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + } + + //@Test + public void testGL2OffScreenAutoDblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GL2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); + reqGLCaps.setOnscreen(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + // @Test + public void testGL2OffScreenFBODblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GL2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OnScreenDblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GL2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenPbufferDblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GL2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenBitmapDblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GL2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); + reqGLCaps.setOnscreen(false); + reqGLCaps.setBitmap(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OnScreenDblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GLES2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenPbufferDblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GLES2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + /** Not implemented ! + @Test + public void testES2OffScreenBitmapDblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GLES2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); + reqGLCaps.setOnscreen(false); + reqGLCaps.setBitmap(true); + doTest(reqGLCaps, new GearsES2(1)); + } */ + + public static void main(String args[]) throws IOException { + org.junit.runner.JUnitCore.main(TestGLCapabilities01NEWT.class.getName()); + } + +} diff --git a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java index 35a2d9669..9e96db5e1 100644 --- a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java +++ b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java @@ -38,6 +38,7 @@ import java.awt.Robot; import java.awt.Toolkit; import javax.media.nativewindow.NativeWindow; +import javax.media.opengl.GLDrawable; import javax.media.opengl.awt.GLCanvas; import org.junit.Assert; @@ -494,6 +495,18 @@ public class AWTRobotUtil { return wait Date: Fri, 7 Sep 2012 08:13:06 +0200 Subject: Cleanup shutdown mechanism ; Fix X11/ATI SIGV at shutdown ; EGLDisplayUtil: Check for leaked display handles GLProfile / all shutdown methods: Remove ShutdownType to remove complexity (not required) Proper shutdown sequence: GLProfile - GLDrawableFactory+ - GLContext - NativeWindowFactory - [X11Util, OSXUtil, ..] GLDrawableFactory: Always keep shutdown-hook alive, required for X11Util shutdown (@ JVMShutdown only) X11Util: Shutdown - @ JVMShutdown only - If GL vendor ATI: close pending X11 display connections in proper order of creation. This finally removes the SIGV when shutting down the JVM on X11 w/ ATI driver. EGLDisplayUtil: Add shutdown, allowing to validate whether leaked EGL display handles remain. --- make/scripts/tests-x64.bat | 4 +- make/scripts/tests.sh | 12 +- .../javax/media/opengl/GLDrawableFactory.java | 36 +++--- src/jogl/classes/javax/media/opengl/GLProfile.java | 29 +---- .../classes/jogamp/opengl/egl/EGLDisplayUtil.java | 38 +++++- .../jogamp/opengl/egl/EGLDrawableFactory.java | 22 ++-- .../macosx/cgl/MacOSXCGLDrawableFactory.java | 10 +- .../windows/wgl/WindowsWGLDrawableFactory.java | 10 +- .../opengl/x11/glx/X11GLXDrawableFactory.java | 14 +-- .../media/nativewindow/NativeWindowFactory.java | 42 +++++-- .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 11 +- .../jogamp/nativewindow/macosx/OSXUtil.java | 10 ++ .../jogamp/nativewindow/windows/GDIUtil.java | 10 ++ .../classes/jogamp/nativewindow/x11/X11Util.java | 127 +++++++++++++-------- .../junit/jogl/acore/TestShutdownCompleteAWT.java | 4 +- .../junit/jogl/acore/TestShutdownCompleteNEWT.java | 14 ++- .../junit/jogl/acore/TestShutdownSharedAWT.java | 124 -------------------- .../junit/jogl/acore/TestShutdownSharedNEWT.java | 127 --------------------- .../jogl/demos/es2/newt/TestGearsES2NEWT.java | 13 +-- .../jogl/demos/es2/newt/TestRedSquareES2NEWT.java | 13 +-- .../test/junit/newt/TestScreenMode01NEWT.java | 2 +- 21 files changed, 243 insertions(+), 429 deletions(-) delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownSharedAWT.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownSharedNEWT.java (limited to 'src/nativewindow') diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat index 669e0212e..22cce49aa 100755 --- a/make/scripts/tests-x64.bat +++ b/make/scripts/tests-x64.bat @@ -1,7 +1,9 @@ REM scripts\java-win64-dbg.bat jogamp.newt.awt.opengl.VersionApplet REM scripts\java-win64-dbg.bat com.jogamp.newt.opengl.GLWindow REM scripts\java-win64-dbg.bat javax.media.opengl.awt.GLCanvas -scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLCapabilities01NEWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLCapabilities01NEWT $* +scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT $* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT -time 5000 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestAWT01GLn diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 1314094cf..5668893f7 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -53,6 +53,7 @@ function jrun() { swton=$1 shift + #D_ARGS="-Djogl.disable.opengles" #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.GLSLCode -Dnewt.debug.Window.MouseEvent" #D_ARGS="-Djogl.debug.TraceGL -Djogl.debug.DebugGL -Djogl.debug.GLSLCode" #D_ARGS="-Djogl.debug.FBObject" @@ -217,12 +218,12 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLCapabilities01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFloatUtil01MatrixMatrixMultNOUI $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestNEWTCloseX11DisplayBug565 $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownSharedNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextSurfaceLockNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug00NEWT $* @@ -260,7 +261,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00bNEWT -#testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01NEWT +testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01NEWT #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01bNEWT #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode02NEWT #testnoawt com.jogamp.opengl.test.junit.newt.ManualScreenMode03NEWT @@ -281,7 +282,6 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableDeadlockAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestPBufferDeadlockAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownSharedAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.x11.TestGLXCallsOnAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestSwingAWT01GLn #testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWT03GLCanvasRecreate01 $* @@ -379,7 +379,6 @@ function testawtswt() { # # FBO / .. # -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLCapabilities01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable00NEWT $* @@ -429,11 +428,6 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLCapabilities01NEWT $* #testawt com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot $* #linux: -# EARMARK removal of shutdown mode! -#testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownSharedAWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownSharedNEWT $* # osx: #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable02NEWT $* diff --git a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java index acda45bff..9fd895c1f 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java @@ -55,7 +55,6 @@ import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; -import javax.media.opengl.GLProfile.ShutdownType; import jogamp.opengl.Debug; @@ -106,6 +105,7 @@ public abstract class GLDrawableFactory { // Shutdown hook mechanism for the factory private static boolean factoryShutdownHookRegistered = false; private static Thread factoryShutdownHook = null; + private static volatile boolean isJVMShuttingDown = false; /** * Instantiate singleton factories if available, EGLES1, EGLES2 and the OS native ones. @@ -176,21 +176,24 @@ public abstract class GLDrawableFactory { } } - protected static void shutdown(ShutdownType shutdownType) { + protected static void shutdown() { if (isInit) { // volatile: ok synchronized (GLDrawableFactory.class) { if (isInit) { isInit=false; - unregisterFactoryShutdownHook(); - shutdownImpl(shutdownType); + shutdownImpl(); } } } } - private static void shutdownImpl(ShutdownType shutdownType) { + + private static void shutdownImpl() { + // Following code will _always_ remain in shutdown hook + // due to special semantics of native utils, i.e. X11Utils. + // The latter requires shutdown at JVM-Shutdown only. synchronized(glDrawableFactories) { for(int i=0; i() { @@ -218,20 +224,6 @@ public abstract class GLDrawableFactory { factoryShutdownHookRegistered = true; } - private static synchronized void unregisterFactoryShutdownHook() { - if (!factoryShutdownHookRegistered) { - return; - } - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - Runtime.getRuntime().removeShutdownHook(factoryShutdownHook); - return null; - } - }); - factoryShutdownHookRegistered = false; - } - - protected GLDrawableFactory() { synchronized(glDrawableFactories) { glDrawableFactories.add(this); @@ -244,7 +236,7 @@ public abstract class GLDrawableFactory { protected void enterThreadCriticalZone() {}; protected void leaveThreadCriticalZone() {}; - protected abstract void destroy(ShutdownType shutdownType); + protected abstract void destroy(); /** * Retrieve the default device {@link AbstractGraphicsDevice#getConnection() connection}, diff --git a/src/jogl/classes/javax/media/opengl/GLProfile.java b/src/jogl/classes/javax/media/opengl/GLProfile.java index 513ccd101..23d789afd 100644 --- a/src/jogl/classes/javax/media/opengl/GLProfile.java +++ b/src/jogl/classes/javax/media/opengl/GLProfile.java @@ -198,44 +198,25 @@ public class GLProfile { getProfileMap(device, true); } - /** - * Shutdown type for {@link GLProfile#shutdown(ShutdownType)}. - *

      - * {@link #SHARED_ONLY} For thread based resources only, suitable for eg. {@link java.applet.Applet Applet} restart.
      - * {@link #COMPLETE} Everything.
      - *

      - */ - public enum ShutdownType { - /* Shared thread based resources only, eg. for Applets */ - SHARED_ONLY, - /* Everything */ - COMPLETE; - } - /** * Manual shutdown method, may be called after your last JOGL use * within the running JVM.
      * It releases all temporary created resources, ie issues {@link javax.media.opengl.GLDrawableFactory#shutdown()}.
      * The shutdown implementation is called via the JVM shutdown hook, if not manually invoked.
      *

      - * This method shall not need to be called for other reasons than issuing a proper shutdown of resources. + * This method shall not need to be called for other reasons than issuing a proper shutdown of resources at a defined time. *

      - * @param type the shutdown type, see {@link ShutdownType}. */ - public static void shutdown(ShutdownType type) { + public static void shutdown() { initLock.lock(); try { if(initialized) { // volatile: ok initialized = false; if(DEBUG) { - System.err.println("GLProfile.shutdown(type: "+type+") - thread "+Thread.currentThread().getName()); + System.err.println("GLProfile.shutdown() - thread "+Thread.currentThread().getName()); Thread.dumpStack(); } - GLDrawableFactory.shutdown(type); - if(ShutdownType.COMPLETE == type) { - GLContext.shutdown(); - } - NativeWindowFactory.shutdown(); + GLDrawableFactory.shutdown(); } } finally { initLock.unlock(); @@ -1480,7 +1461,7 @@ public class GLProfile { if(DEBUG) { System.err.println("Info: GLProfile.init - EGL/ES2 ANGLE disabled"); } - eglFactory.destroy(ShutdownType.COMPLETE); + eglFactory.destroy(); eglFactory = null; hasEGLFactory = false; } else { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java index 18d2f830d..ce2e824f5 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java @@ -29,6 +29,7 @@ package jogamp.opengl.egl; import java.nio.IntBuffer; +import java.util.Iterator; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; @@ -51,7 +52,7 @@ import com.jogamp.nativewindow.egl.EGLGraphicsDevice; *

      */ public class EGLDisplayUtil { - protected static final boolean DEBUG = Debug.debug("EGL"); + protected static final boolean DEBUG = Debug.debug("EGLDisplayUtil"); static LongIntHashMap eglDisplayCounter; @@ -60,6 +61,32 @@ public class EGLDisplayUtil { eglDisplayCounter.setKeyNotFoundValue(0); } + /** + * @return number of unclosed EGL Displays.
      + */ + public static int shutdown(boolean verbose) { + if(DEBUG || verbose || eglDisplayCounter.size() > 0 ) { + System.err.println("EGLDisplayUtil.EGLDisplays: Shutdown (open: "+eglDisplayCounter.size()+")"); + if(DEBUG) { + Thread.dumpStack(); + } + if( eglDisplayCounter.size() > 0) { + EGLDisplayUtil.dumpOpenDisplayConnections(); + } + } + + return eglDisplayCounter.size(); + } + + public static void dumpOpenDisplayConnections() { + System.err.println("EGLDisplayUtil: Open EGL Display Connections: "+eglDisplayCounter.size()); + int i=0; + for(Iterator iter = eglDisplayCounter.iterator(); iter.hasNext(); i++) { + final LongIntHashMap.Entry e = iter.next(); + System.err.println("EGLDisplayUtil: Open["+i+"]: 0x"+Long.toHexString(e.key)+": refCnt "+e.value); + } + } + public static long eglGetDisplay(long nativeDisplay_id) { final long eglDisplay = EGL.eglGetDisplay(nativeDisplay_id); if(DEBUG) { @@ -89,6 +116,7 @@ public class EGLDisplayUtil { eglDisplayCounter.put(eglDisplay, refCnt); if(DEBUG) { System.err.println("EGLDisplayUtil.eglInitialize1("+EGLContext.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res); + // Thread.dumpStack(); } return res; } @@ -117,6 +145,7 @@ public class EGLDisplayUtil { } if(DEBUG) { System.err.println("EGLDisplayUtil.eglInitialize2("+EGLContext.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res); + // Thread.dumpStack(); } return res; } @@ -185,12 +214,13 @@ public class EGLDisplayUtil { final int refCnt = eglDisplayCounter.get(eglDisplay) - 1; // 1 - 1 = 0 -> final terminate if(0==refCnt) { // no terminate if still in use or already terminated res = EGL.eglTerminate(eglDisplay); + eglDisplayCounter.remove(eglDisplay); } else { + if(0 < refCnt) { // no negative refCount + eglDisplayCounter.put(eglDisplay, refCnt); + } res = true; } - if(0<=refCnt) { // no negative refCount - eglDisplayCounter.put(eglDisplay, refCnt); - } if(DEBUG) { System.err.println("EGLDisplayUtil.eglTerminate("+EGLContext.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res); // Thread.dumpStack(); diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index 986b110be..292eb17c8 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -64,7 +64,6 @@ import javax.media.opengl.GLDrawable; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; -import javax.media.opengl.GLProfile.ShutdownType; import jogamp.opengl.Debug; import jogamp.opengl.GLDrawableFactoryImpl; @@ -201,13 +200,13 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { @Override - protected final void destroy(ShutdownType shutdownType) { + protected final void destroy() { if(null != sharedMap) { Collection srl = sharedMap.values(); for(Iterator sri = srl.iterator(); sri.hasNext(); ) { SharedResource sr = sri.next(); if(DEBUG) { - System.err.println("EGLDrawableFactory.destroy("+shutdownType+"): "+sr.device.toString()); + System.err.println("EGLDrawableFactory.destroy(): "+sr.device.toString()); } sr.device.close(); } @@ -220,17 +219,16 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { /** * Pulling away the native library may cause havoc .. */ - if(ShutdownType.COMPLETE == shutdownType) { - if(null != eglES1DynamicLookupHelper) { - // eglES1DynamicLookupHelper.destroy(); - eglES1DynamicLookupHelper = null; - } - if(null != eglES2DynamicLookupHelper) { - // eglES2DynamicLookupHelper.destroy(); - eglES2DynamicLookupHelper = null; - } + if(null != eglES1DynamicLookupHelper) { + // eglES1DynamicLookupHelper.destroy(); + eglES1DynamicLookupHelper = null; + } + if(null != eglES2DynamicLookupHelper) { + // eglES2DynamicLookupHelper.destroy(); + eglES2DynamicLookupHelper = null; } EGLGraphicsConfigurationFactory.unregisterFactory(); + EGLDisplayUtil.shutdown(DEBUG); } private HashMap sharedMap = null; diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java index c1b15cac5..591fafc68 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java @@ -60,7 +60,6 @@ import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; -import javax.media.opengl.GLProfile.ShutdownType; import jogamp.nativewindow.macosx.OSXUtil; import jogamp.opengl.DesktopGLDynamicLookupHelper; @@ -124,7 +123,7 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { } @Override - protected final void destroy(ShutdownType shutdownType) { + protected final void destroy() { if(null != sharedMap) { sharedMap.clear(); sharedMap = null; @@ -133,10 +132,9 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { /** * Pulling away the native library may cause havoc .. * - if(ShutdownType.COMPLETE == shutdownType && null != macOSXCGLDynamicLookupHelper) { - macOSXCGLDynamicLookupHelper.destroy(); - macOSXCGLDynamicLookupHelper = null; - } */ + macOSXCGLDynamicLookupHelper.destroy(); + */ + macOSXCGLDynamicLookupHelper = null; } @Override diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java index c414083c4..7ea487523 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java @@ -61,7 +61,6 @@ import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; -import javax.media.opengl.GLProfile.ShutdownType; import jogamp.nativewindow.windows.GDI; import jogamp.nativewindow.windows.GDISurface; @@ -136,7 +135,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { @Override - protected final void destroy(ShutdownType shutdownType) { + protected final void destroy() { if(null != sharedResourceRunner) { sharedResourceRunner.stop(); sharedResourceRunner = null; @@ -149,10 +148,9 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { /** * Pulling away the native library may cause havoc .. * - if(ShutdownType.COMPLETE == shutdownType && null != windowsWGLDynamicLookupHelper) { - windowsWGLDynamicLookupHelper.destroy(); - windowsWGLDynamicLookupHelper = null; - } */ + windowsWGLDynamicLookupHelper.destroy(); + */ + windowsWGLDynamicLookupHelper = null; RegisteredClassFactory.shutdownSharedClasses(); } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index 293ac96f7..bc3e5b793 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -58,7 +58,6 @@ import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; -import javax.media.opengl.GLProfile.ShutdownType; import jogamp.nativewindow.x11.X11Lib; import jogamp.nativewindow.x11.X11Util; @@ -129,7 +128,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { } @Override - protected final void destroy(ShutdownType shutdownType) { + protected final void destroy() { if(null != sharedResourceRunner) { sharedResourceRunner.stop(); sharedResourceRunner = null; @@ -142,14 +141,9 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { /** * Pulling away the native library may cause havoc .. * - if(ShutdownType.COMPLETE == shutdownType && null != x11GLXDynamicLookupHelper) { - x11GLXDynamicLookupHelper.destroy(); - x11GLXDynamicLookupHelper = null; - } */ - - // Don't really close pending Display connections, - // since this may trigger a JVM exception - X11Util.shutdown( false, DEBUG ); + x11GLXDynamicLookupHelper.destroy(); + */ + x11GLXDynamicLookupHelper = null; } @Override diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index afcd0a008..89d476a3b 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -102,6 +102,8 @@ public abstract class NativeWindowFactory { private static Constructor x11ToolkitLockConstructor; private static boolean requiresToolkitLock; + private static volatile boolean isJVMShuttingDown = false; + /** Creates a new NativeWindowFactory instance. End users do not need to call this method. */ protected NativeWindowFactory() { @@ -168,6 +170,22 @@ public abstract class NativeWindowFactory { } } + private static void shutdownNativeImpl(final ClassLoader cl) { + final String clazzName; + if( TYPE_X11 == nativeWindowingTypePure ) { + clazzName = X11UtilClassName; + } else if( TYPE_WINDOWS == nativeWindowingTypePure ) { + clazzName = GDIClassName; + } else if( TYPE_MACOSX == nativeWindowingTypePure ) { + clazzName = OSXUtilClassName; + } else { + clazzName = null; + } + if( null != clazzName ) { + ReflectionUtil.callStaticMethod(clazzName, "shutdown", null, null, cl ); + } + } + /** * Static one time initialization of this factory.
      * This initialization method must be called once by the program or utilizing modules! @@ -268,22 +286,28 @@ public abstract class NativeWindowFactory { } } - public static synchronized void shutdown() { + public static synchronized void shutdown(boolean _isJVMShuttingDown) { + isJVMShuttingDown = _isJVMShuttingDown; + if(DEBUG) { + System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() START: JVM Shutdown "+isJVMShuttingDown); + } if(initialized) { initialized = false; - if(DEBUG) { - System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() START"); + if(null != registeredFactories) { + registeredFactories.clear(); + registeredFactories = null; } - registeredFactories.clear(); - registeredFactories = null; GraphicsConfigurationFactory.shutdown(); - // X11Util.shutdown(..) already called via GLDrawableFactory.shutdown() .. - if(DEBUG) { - System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() END"); - } + } + shutdownNativeImpl(NativeWindowFactory.class.getClassLoader()); // always re-shutdown + if(DEBUG) { + System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() END JVM Shutdown "+isJVMShuttingDown); } } + /** Returns true if the JVM is shutting down, otherwise false. */ + public static final boolean isJVMShuttingDown() { return isJVMShuttingDown; } + /** @return true if the underlying toolkit requires locking, otherwise false. */ public static boolean requiresToolkitLock() { return requiresToolkitLock; diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index 36d7c3727..f1e8a786a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -48,6 +48,7 @@ import java.util.ArrayList; import java.util.Map; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ToolkitLock; import jogamp.nativewindow.Debug; @@ -271,10 +272,18 @@ public class JAWTUtil { } } + /** + * Called by {@link NativeWindowFactory#initSingleton()} + */ public static void initSingleton() { // just exist to ensure static init has been run } - + + /** + * Called by {@link NativeWindowFactory#shutdown()} + */ + public static void shutdown() { + } public static boolean hasJava2D() { return j2dExist; diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index f5f735051..149ebdf4a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -28,6 +28,7 @@ package jogamp.nativewindow.macosx; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.Point; @@ -38,6 +39,9 @@ public class OSXUtil { private static boolean isInit = false; private static final boolean DEBUG = Debug.debug("OSXUtil"); + /** + * Called by {@link NativeWindowFactory#initSingleton()} + */ public static synchronized void initSingleton() { if(!isInit) { if(DEBUG) { @@ -54,6 +58,12 @@ public class OSXUtil { } } + /** + * Called by {@link NativeWindowFactory#shutdown()} + */ + public static void shutdown() { + } + public static boolean requiresToolkitLock() { return false; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index fda1649b6..613c76032 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -29,6 +29,7 @@ package jogamp.nativewindow.windows; import javax.media.nativewindow.util.Point; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.NativeWindowFactory; import jogamp.nativewindow.NWJNILibLoader; import jogamp.nativewindow.Debug; @@ -41,6 +42,9 @@ public class GDIUtil { private static RegisteredClassFactory dummyWindowClassFactory; private static boolean isInit = false; + /** + * Called by {@link NativeWindowFactory#initSingleton()} + */ public static synchronized void initSingleton() { if(!isInit) { synchronized(X11Util.class) { @@ -61,6 +65,12 @@ public class GDIUtil { } } + /** + * Called by {@link NativeWindowFactory#shutdown()} + */ + public static void shutdown() { + } + public static boolean requiresToolkitLock() { return false; } private static RegisteredClass dummyWindowClass = null; diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 860238649..93b7f3487 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -67,13 +67,13 @@ public class X11Util { *

      *

      * You may test this, ie just reverse the destroy order below. - * See also native test: jogl/test/native/displayMultiple02.c + * See also native test: jogl/test-native/displayMultiple02.c *

      *

      * Workaround is to not close them at all if driver vendor is ATI. *

      */ - public static final boolean ATI_HAS_XCLOSEDISPLAY_BUG = true; + public static final boolean ATI_HAS_XCLOSEDISPLAY_BUG = !Debug.isPropertyDefined("nativewindow.debug.X11Util.ATI_HAS_NO_XCLOSEDISPLAY_BUG", true); /** Value is true, best 'stable' results if always using XInitThreads(). */ public static final boolean XINITTHREADS_ALWAYS_ENABLED = true; @@ -95,6 +95,9 @@ public class X11Util { private static Object setX11ErrorHandlerLock = new Object(); + /** + * Called by {@link NativeWindowFactory#initSingleton()} + */ public static void initSingleton() { if(!isInit) { synchronized(X11Util.class) { @@ -138,6 +141,52 @@ public class X11Util { } } + /** + * Cleanup resources. + *

      + * Called by {@link NativeWindowFactory#shutdown()} + *

      + */ + public static void shutdown() { + if(isInit) { + synchronized(X11Util.class) { + if(isInit) { + final boolean isJVMShuttingDown = NativeWindowFactory.isJVMShuttingDown() ; + if(DEBUG || openDisplayMap.size() > 0 || reusableDisplayList.size() > 0 || pendingDisplayList.size() > 0) { + System.err.println("X11Util.Display: Shutdown (JVM shutdown: "+isJVMShuttingDown+ + ", open (no close attempt): "+openDisplayMap.size()+"/"+openDisplayList.size()+ + ", reusable (open, marked uncloseable): "+reusableDisplayList.size()+ + ", pending (post closing): "+pendingDisplayList.size()+ + ")"); + if(DEBUG) { + Thread.dumpStack(); + } + if( openDisplayList.size() > 0) { + X11Util.dumpOpenDisplayConnections(); + } + if( reusableDisplayList.size() > 0 || pendingDisplayList.size() > 0 ) { + X11Util.dumpPendingDisplayConnections(); + } + } + + synchronized(globalLock) { + // Only at JVM shutdown time, since AWT impl. seems to + // dislike closing of X11 Display's (w/ ATI driver). + if( isJVMShuttingDown ) { + isInit = false; + closePendingDisplayConnections(); + openDisplayList.clear(); + reusableDisplayList.clear(); + pendingDisplayList.clear(); + openDisplayMap.clear(); + shutdown0(); + } + } + } + } + } + } + public static synchronized boolean isNativeLockAvailable() { return isX11LockAvailable; } @@ -183,6 +232,7 @@ public class X11Util { private static Object globalLock = new Object(); private static LongObjectHashMap openDisplayMap = new LongObjectHashMap(); // handle -> name private static List openDisplayList = new ArrayList(); + private static List reusableDisplayList = new ArrayList(); private static List pendingDisplayList = new ArrayList(); public static class NamedDisplay { @@ -218,8 +268,7 @@ public class X11Util { public final boolean equals(Object obj) { if(this == obj) { return true; } if(obj instanceof NamedDisplay) { - NamedDisplay n = (NamedDisplay) obj; - return handle == n.handle; + return handle == ((NamedDisplay) obj).handle; } return false; } @@ -246,43 +295,6 @@ public class X11Util { } } - /** - * Cleanup resources. - * If realXCloseOpenAndPendingDisplays is false, - * keep alive all references (open display connection) for restart on same ClassLoader. - * - * @return number of unclosed X11 Displays.
      - * @param realXCloseOpenAndPendingDisplays if true, {@link #closePendingDisplayConnections()} is called. - */ - public static int shutdown(boolean realXCloseOpenAndPendingDisplays, boolean verbose) { - int num=0; - if(DEBUG || verbose || openDisplayMap.size() > 0 || pendingDisplayList.size() > 0) { - System.err.println("X11Util.Display: Shutdown (close open / pending Displays: "+realXCloseOpenAndPendingDisplays+ - ", open (no close attempt): "+openDisplayMap.size()+"/"+openDisplayList.size()+ - ", pending (not closed, marked uncloseable): "+pendingDisplayList.size()+")"); - if(DEBUG) { - Thread.dumpStack(); - } - if( openDisplayList.size() > 0) { - X11Util.dumpOpenDisplayConnections(); - } - if( pendingDisplayList.size() > 0 ) { - X11Util.dumpPendingDisplayConnections(); - } - } - - synchronized(globalLock) { - if(realXCloseOpenAndPendingDisplays) { - closePendingDisplayConnections(); - openDisplayList.clear(); - pendingDisplayList.clear(); - openDisplayMap.clear(); - shutdown0(); - } - } - return num; - } - /** * Closing pending Display connections in reverse order. * @@ -292,9 +304,9 @@ public class X11Util { int num=0; synchronized(globalLock) { if(DEBUG) { - System.err.println("X11Util: Closing Pending X11 Display Connections: "+pendingDisplayList.size()); + System.err.println("X11Util: Closing Pending X11 Display Connections in order of their creation: "+pendingDisplayList.size()); } - for(int i=pendingDisplayList.size()-1; i>=0; i--) { + for(int i=0; i Date: Sat, 8 Sep 2012 19:45:11 +0200 Subject: Fix window mode attribute bit FBO_BIT usage in platform dependent code (map it to native type) ; OSX Caps selection ; WGL/GDI BITMAP fix Fix window mode attribute bit FBO_BIT usage in platform dependent code (map it to native type) All platform dependent winAttrBit mapping: 'nativeType -> winAttrBit' and 'GLCapabilities -> winAttrBits' shall replace FBO_BIT w/ the native type of the wrapper surface, i.e. WINDOW_BIT (X11, WGL, CGL) or PBUFFER_BIT (EGL). This condenses to changes in - EGLGraphicsConfiguration: EGLConfigDrawableTypeBits / GLCapabilities2AttribList - X11GLXGraphicsConfiguration: FBCfgDrawableTypeBits, XVisualInfo2GLCapabilities / GLCapabilities2AttribList - WindowsWGLGraphicsConfiguration: AttribList2DrawableTypeBits, PFD2DrawableTypeBits / GLCapabilities2AttribList - OSX CGL/NS requires changes in MacOSXCGLContext, i.e. fix the surface mode of NSPixelFormat2GLCapabilities, CGLPixelFormat2GLCapabilities results. This change is included in the upcoming commit (class is heavily edited). OSX chooseGraphicsConfigurationStatic: Add missing 'GLGraphicsConfigurationUtil.fixGLCapabilities(..)' call - all platform impl. require to fix the given user caps due to the new offscreen auto selection mode WindowsWGLGraphicsConfiguration*: ARB / GDI updateGraphicsConfiguration*() - ARB method detects early whether it's suitable for given HDC, i.e. in case of BITMAP (it's not here) - GDI methods detect failure while choosing PFD and doesn't care of DOUBLEBUFFER in case of bitmap (fixes BITMAP usage) Capabilities/GLCapabilities: - Fix missing double-buffer check in GLCapabilities.equals() - add 'copyFrom(..)' method copy all data from give caps --- .../classes/javax/media/opengl/GLCapabilities.java | 29 ++ .../jogamp/opengl/GLGraphicsConfigurationUtil.java | 5 +- .../opengl/egl/EGLGraphicsConfiguration.java | 48 +++- .../egl/EGLGraphicsConfigurationFactory.java | 13 +- .../macosx/cgl/MacOSXCGLGraphicsConfiguration.java | 4 +- .../cgl/MacOSXCGLGraphicsConfigurationFactory.java | 32 ++- .../wgl/WindowsWGLGraphicsConfiguration.java | 299 ++++++++++++--------- .../WindowsWGLGraphicsConfigurationFactory.java | 71 +++-- .../x11/glx/X11GLXGraphicsConfiguration.java | 89 +++--- .../glx/X11GLXGraphicsConfigurationFactory.java | 1 - .../javax/media/nativewindow/Capabilities.java | 22 +- .../junit/jogl/acore/TestGLCapabilities01NEWT.java | 65 +++-- 12 files changed, 442 insertions(+), 236 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilities.java b/src/jogl/classes/javax/media/opengl/GLCapabilities.java index 30a6215e7..9b004a0af 100644 --- a/src/jogl/classes/javax/media/opengl/GLCapabilities.java +++ b/src/jogl/classes/javax/media/opengl/GLCapabilities.java @@ -102,6 +102,34 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil } } + /** + * Copies all {@link GLCapabilities} and {@link Capabilities} values + * from source into this instance. + * @return this instance + */ + public GLCapabilities copyFrom(GLCapabilitiesImmutable source) { + super.copyFrom(source); + glProfile = source.getGLProfile(); + isPBuffer = source.isPBuffer(); + isFBO = source.isFBO(); + doubleBuffered = source.getDoubleBuffered(); + stereo = source.getStereo(); + hardwareAccelerated = source.getHardwareAccelerated(); + depthBits = source.getDepthBits(); + stencilBits = source.getStencilBits(); + accumRedBits = source.getAccumRedBits(); + accumGreenBits = source.getAccumGreenBits(); + accumBlueBits = source.getAccumBlueBits(); + accumAlphaBits = source.getAccumAlphaBits(); + sampleBuffers = source.getSampleBuffers(); + pbufferFloatingPointBuffers = source.getPbufferFloatingPointBuffers(); + pbufferRenderToTexture = source.getPbufferRenderToTexture(); + pbufferRenderToTextureRectangle = source.getPbufferRenderToTextureRectangle(); + numSamples = source.getNumSamples(); + sampleExtension = source.getSampleExtension(); + return this; + } + @Override public int hashCode() { // 31 * x == (x << 5) - x @@ -137,6 +165,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil other.getGLProfile()==glProfile && other.isPBuffer()==isPBuffer && other.isFBO()==isFBO && + other.getDoubleBuffered() == doubleBuffered && other.getStereo()==stereo && other.getHardwareAccelerated()==hardwareAccelerated && other.getDepthBits()==depthBits && diff --git a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java index d8e5ba31a..768fc6892 100644 --- a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java +++ b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java @@ -28,7 +28,6 @@ package jogamp.opengl; - import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesImmutable; @@ -37,7 +36,7 @@ public class GLGraphicsConfigurationUtil { public static final int WINDOW_BIT = 1 << 0; public static final int BITMAP_BIT = 1 << 1; public static final int PBUFFER_BIT = 1 << 2; - public static final int FBO_BIT = 1 << 3; + public static final int FBO_BIT = 1 << 3; // generic bit must be mapped to native one at impl. level public static final int ALL_BITS = WINDOW_BIT | BITMAP_BIT | PBUFFER_BIT | FBO_BIT ; public static final StringBuilder winAttributeBits2String(StringBuilder sb, int winattrbits) { @@ -161,7 +160,7 @@ public class GLGraphicsConfigurationUtil { final boolean useFBO = fboAvailable && ( auto || capsRequested.isFBO() ) ; final boolean usePbuffer = !useFBO && pbufferAvailable && ( auto || capsRequested.isPBuffer() ) ; - final boolean useBitmap = !usePbuffer && ( auto || capsRequested.isBitmap() ) ; + final boolean useBitmap = !useFBO && !usePbuffer && ( auto || capsRequested.isBitmap() ) ; if( capsRequested.isOnscreen() || useFBO != capsRequested.isFBO() || diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java index 135101ff2..8ee98072f 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java @@ -46,7 +46,6 @@ import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.DefaultGLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; -import javax.media.opengl.GLContext; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; @@ -129,12 +128,28 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple return configs.get(0); } - static int EGLConfigDrawableTypeBits(final EGLGraphicsDevice device, final GLProfile glp, final long config) { + public static boolean isEGLConfigValid(long display, long config) { + if(0 == config) { + return false; + } + final IntBuffer val = Buffers.newDirectIntBuffer(1); + + // get the configID + if(!EGL.eglGetConfigAttrib(display, config, EGL.EGL_CONFIG_ID, val)) { + final int eglErr = EGL.eglGetError(); + if(DEBUG) { + System.err.println("Info: Couldn't retrieve EGL ConfigID for config "+toHexString(config)+", error "+toHexString(eglErr)); + } + return false; + } + return true; + } + + static int EGLConfigDrawableTypeBits(final EGLGraphicsDevice device, final long config) { int val = 0; - final long display = device.getHandle(); int[] stype = new int[1]; - if(! EGL.eglGetConfigAttrib(display, config, EGL.EGL_SURFACE_TYPE, stype, 0)) { + if(! EGL.eglGetConfigAttrib(device.getHandle(), config, EGL.EGL_SURFACE_TYPE, stype, 0)) { throw new GLException("Could not determine EGL_SURFACE_TYPE"); } @@ -145,12 +160,9 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple val |= GLGraphicsConfigurationUtil.BITMAP_BIT; } if ( 0 != ( stype[0] & EGL.EGL_PBUFFER_BIT ) ) { - val |= GLGraphicsConfigurationUtil.PBUFFER_BIT; - } - if ( GLContext.isFBOAvailable(device, glp) ) { - val |= GLGraphicsConfigurationUtil.FBO_BIT; + val |= GLGraphicsConfigurationUtil.PBUFFER_BIT | + GLGraphicsConfigurationUtil.FBO_BIT; } - return val; } @@ -269,8 +281,8 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple // Since the passed GLProfile may be null, // we use EGL_RENDERABLE_TYPE derived profile as created in the EGLGLCapabilities constructor. - final int allDrawableTypeBits = EGLConfigDrawableTypeBits(device, caps.getGLProfile(), config); - final int drawableTypeBits = winattrmask & allDrawableTypeBits; + final int availableTypeBits = EGLConfigDrawableTypeBits(device, config); + final int drawableTypeBits = winattrmask & availableTypeBits; if( 0 == drawableTypeBits ) { return null; @@ -284,7 +296,19 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple int idx=0; attrs[idx++] = EGL.EGL_SURFACE_TYPE; - attrs[idx++] = caps.isOnscreen() ? ( EGL.EGL_WINDOW_BIT ) : ( caps.isPBuffer() ? EGL.EGL_PBUFFER_BIT : EGL.EGL_PIXMAP_BIT ) ; + final int surfaceType; + if( caps.isOnscreen() ) { + surfaceType = EGL.EGL_WINDOW_BIT; + } else if( caps.isFBO() ) { + surfaceType = EGL.EGL_PBUFFER_BIT; // native replacement! + } else if( caps.isPBuffer() ) { + surfaceType = EGL.EGL_PBUFFER_BIT; + } else if( caps.isBitmap() ) { + surfaceType = EGL.EGL_PIXMAP_BIT; + } else { + throw new GLException("no surface type set in caps: "+caps); + } + attrs[idx++] = surfaceType; attrs[idx++] = EGL.EGL_RED_SIZE; attrs[idx++] = caps.getRedBits(); diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java index d08685dcb..e72255108 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java @@ -324,6 +324,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact return res; } + static EGLGraphicsConfiguration eglChooseConfig(EGLGraphicsDevice device, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, @@ -344,7 +345,12 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact throw new GLException("EGLGraphicsConfiguration.eglChooseConfig: Get maxConfigs (eglGetConfigs) no configs"); } if (DEBUG) { - System.err.println("EGLGraphicsConfiguration.eglChooseConfig: eglChooseConfig eglDisplay "+toHexString(eglDisplay)+", nativeVisualID "+toHexString(nativeVisualID)+", "+capsChosen+", numConfigs "+numConfigs.get(0)); + System.err.println("EGLGraphicsConfiguration.eglChooseConfig: eglChooseConfig eglDisplay "+toHexString(eglDisplay)+ + ", nativeVisualID "+toHexString(nativeVisualID)+ + ", capsChosen "+capsChosen+", winbits "+GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrmask).toString()+ + ", fboAvail "+GLContext.isFBOAvailable(device, glp)+ + ", device "+device+", "+device.getUniqueID()+ + ", numConfigs "+numConfigs.get(0)); } final IntBuffer attrs = Buffers.newDirectIntBuffer(EGLGraphicsConfiguration.GLCapabilities2AttribList(capsChosen)); @@ -432,10 +438,11 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact return null; } final EGLGLCapabilities chosenCaps = (EGLGLCapabilities) availableCaps.get(chosenIndex); + final EGLGraphicsConfiguration res = new EGLGraphicsConfiguration(absScreen, chosenCaps, capsRequested, chooser); if (DEBUG) { - System.err.println("EGLGraphicsConfiguration.eglChooseConfig: X chosen :"+chosenIndex+", eglConfig: "+toHexString(chosenCaps.getEGLConfig())+", "+chosenCaps); + System.err.println("EGLGraphicsConfiguration.eglChooseConfig: X chosen :"+chosenIndex+", eglConfig: "+toHexString(chosenCaps.getEGLConfig())+": "+res); } - return new EGLGraphicsConfiguration(absScreen, chosenCaps, capsRequested, chooser); + return res; } static List eglConfigs2GLCaps(EGLGraphicsDevice device, GLProfile glp, PointerBuffer configs, int num, int winattrmask, boolean forceTransparentFlag) { diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java index 10e8193e2..149927160 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java @@ -280,7 +280,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration if(null == glp) { glp = GLProfile.get(GLProfile.GL2); } - GLCapabilities caps = new GLCapabilities(glp); + final GLCapabilities caps = new GLCapabilities(glp); int alphaBits = 0; for (int i = 0; i < len; i++) { int attr = cglInternalAttributeToken[i+off]; @@ -353,7 +353,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration } } caps.setAlphaBits(alphaBits); - + return caps; } } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java index f138e7557..13faf7090 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java @@ -34,13 +34,19 @@ package jogamp.opengl.macosx.cgl; import jogamp.opengl.GLGraphicsConfigurationFactory; +import jogamp.opengl.GLGraphicsConfigurationUtil; +import jogamp.opengl.x11.glx.X11GLXDrawableFactory; + import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.CapabilitiesChooser; import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawableFactory; /** Subclass of GraphicsConfigurationFactory used when non-AWT tookits @@ -58,13 +64,7 @@ public class MacOSXCGLGraphicsConfigurationFactory extends GLGraphicsConfigurati protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { - return chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, absScreen, false); - } - - static MacOSXCGLGraphicsConfiguration chooseGraphicsConfigurationStatic(CapabilitiesImmutable capsChosen, - CapabilitiesImmutable capsRequested, - CapabilitiesChooser chooser, - AbstractGraphicsScreen absScreen, boolean usePBuffer) { + if (absScreen == null) { throw new IllegalArgumentException("AbstractGraphicsScreen is null"); } @@ -77,11 +77,25 @@ public class MacOSXCGLGraphicsConfigurationFactory extends GLGraphicsConfigurati throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilities objects - requested"); } - if (chooser != null && - !(chooser instanceof GLCapabilitiesChooser)) { + if (chooser != null && !(chooser instanceof GLCapabilitiesChooser)) { throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilitiesChooser objects"); } + + return chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested, (GLCapabilitiesChooser)chooser, absScreen, false); + } + + static MacOSXCGLGraphicsConfiguration chooseGraphicsConfigurationStatic(GLCapabilitiesImmutable capsChosen, + GLCapabilitiesImmutable capsRequested, + GLCapabilitiesChooser chooser, + AbstractGraphicsScreen absScreen, boolean usePBuffer) { + if (absScreen == null) { + throw new IllegalArgumentException("AbstractGraphicsScreen is null"); + } + final MacOSXCGLDrawableFactory factory = (MacOSXCGLDrawableFactory) GLDrawableFactory.getDesktopFactory(); + final AbstractGraphicsDevice device = absScreen.getDevice(); + capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, GLContext.isFBOAvailable(device, capsChosen.getGLProfile()), factory.canCreateGLPbuffer(device) ); + return new MacOSXCGLGraphicsConfiguration(absScreen, (GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested, 0); } } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java index 5b21353c3..4d1069e6b 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java @@ -42,7 +42,6 @@ import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.opengl.GL; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLCapabilitiesChooser; -import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLPbuffer; @@ -58,6 +57,7 @@ import jogamp.nativewindow.windows.PIXELFORMATDESCRIPTOR; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLGraphicsConfigurationUtil; +@SuppressWarnings("deprecation") public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable { protected static final int MAX_PFORMATS = 256; protected static final int MAX_ATTRIBS = 256; @@ -107,7 +107,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio if(hasARB) { caps = wglARBPFID2GLCapabilities(sharedResource, device, glp, hdc, pfdID, GLGraphicsConfigurationUtil.ALL_BITS); } else { - caps = PFD2GLCapabilities(device, glp, hdc, pfdID, GLGraphicsConfigurationUtil.ALL_BITS); + caps = PFD2GLCapabilities(glp, hdc, pfdID, GLGraphicsConfigurationUtil.ALL_BITS); } if(null==caps) { throw new GLException("Couldn't choose Capabilities by: HDC 0x"+Long.toHexString(hdc)+ @@ -186,7 +186,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } } if (DEBUG) { - System.err.println("setPixelFormat (ARB): hdc "+toHexString(hdc) +", "+caps); + System.err.println("setPixelFormat: hdc "+toHexString(hdc) +", "+caps); } setCapsPFD(caps); } @@ -274,36 +274,41 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return true; } - static int[] wglAllARBPFIDs(WindowsWGLContext sharedCtx, long hdc) { + static int wglARBPFDIDCount(WindowsWGLContext sharedCtx, long hdc) { int[] iattributes = new int[1]; int[] iresults = new int[1]; WGLExt wglExt = sharedCtx.getWGLExt(); - iattributes[0] = WGLExt.WGL_NUMBER_PIXEL_FORMATS_ARB; - if (!wglExt.wglGetPixelFormatAttribivARB(hdc, 0, 0, 1, iattributes, 0, iresults, 0)) { + iattributes[0] = WGLExt.WGL_NUMBER_PIXEL_FORMATS_ARB; + // pfdID shall be ignored here (spec), however, pass a valid pdf index '1' below (possible driver bug) + if (!wglExt.wglGetPixelFormatAttribivARB(hdc, 1 /* pfdID */, 0, 1, iattributes, 0, iresults, 0)) { if(DEBUG) { System.err.println("GetPixelFormatAttribivARB: Failed - HDC 0x" + Long.toHexString(hdc) + + ", value "+iresults[0]+ ", LastError: " + GDI.GetLastError()); Thread.dumpStack(); } - return null; + return 0; } - int numFormats = iresults[0]; - if(0 == numFormats) { + final int pfdIDCount = iresults[0]; + if(0 == pfdIDCount) { if(DEBUG) { System.err.println("GetPixelFormatAttribivARB: No formats - HDC 0x" + Long.toHexString(hdc) + ", LastError: " + GDI.GetLastError()); Thread.dumpStack(); } - return null; } - int[] pfdIDs = new int[numFormats]; - for (int i = 0; i < numFormats; i++) { + return pfdIDCount; + } + + static int[] wglAllARBPFDIDs(int pfdIDCount) { + int[] pfdIDs = new int[pfdIDCount]; + for (int i = 0; i < pfdIDCount; i++) { pfdIDs[i] = 1 + i; } return pfdIDs; } - + static WGLGLCapabilities wglARBPFID2GLCapabilities(WindowsWGLDrawableFactory.SharedResource sharedResource, AbstractGraphicsDevice device, GLProfile glp, long hdc, int pfdID, int winattrbits) { @@ -320,7 +325,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio throw new GLException("wglARBPFID2GLCapabilities: Error getting pixel format attributes for pixel format " + pfdID + " of device context " + toHexString(hdc) + ", werr " + GDI.GetLastError()); } - return AttribList2GLCapabilities(device, glp, hdc, pfdID, iattributes, niattribs, iresults, winattrbits); + return AttribList2GLCapabilities(glp, hdc, pfdID, iattributes, niattribs, iresults, winattrbits); } static int[] wglChoosePixelFormatARB(WindowsWGLDrawableFactory.SharedResource sharedResource, AbstractGraphicsDevice device, @@ -369,11 +374,6 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return pformats; } - static List wglARBPFIDs2AllGLCapabilities(WindowsWGLDrawableFactory.SharedResource sharedResource, - AbstractGraphicsDevice device, GLProfile glp, long hdc, int[] pfdIDs) { - return wglARBPFIDs2GLCapabilities(sharedResource, device, glp, hdc, pfdIDs, GLGraphicsConfigurationUtil.ALL_BITS); - } - static List wglARBPFIDs2GLCapabilities(WindowsWGLDrawableFactory.SharedResource sharedResource, AbstractGraphicsDevice device, GLProfile glp, long hdc, int[] pfdIDs, int winattrbits) { if (!sharedResource.hasARBPixelFormat()) { @@ -390,14 +390,24 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio for(int i = 0; i= 1 && ((WindowsWGLContext)sharedResource.getContext()).getWGLExt().wglGetPixelFormatAttribivARB(hdc, pfdIDs[i], 0, niattribs, iattributes, 0, iresults, 0) ) { - final GLCapabilitiesImmutable caps = AttribList2GLCapabilities(device, glp, hdc, pfdIDs[i], iattributes, niattribs, iresults, winattrbits); + final GLCapabilitiesImmutable caps = AttribList2GLCapabilities(glp, hdc, pfdIDs[i], iattributes, niattribs, iresults, winattrbits); if(null != caps) { bucket.add(caps); + if(DEBUG) { + final int j = bucket.size() - 1; + System.err.println("wglARBPFIDs2GLCapabilities: bucket["+i+" -> "+j+"]: "+caps); + } + } else if(DEBUG) { + GLCapabilitiesImmutable skipped = AttribList2GLCapabilities(glp, hdc, pfdIDs[i], iattributes, niattribs, iresults, GLGraphicsConfigurationUtil.ALL_BITS); + System.err.println("wglARBPFIDs2GLCapabilities: bucket["+i+" -> skip]: pfdID "+pfdIDs[i]+", "+skipped+", winattr "+GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrbits).toString()); } } else if (DEBUG) { - System.err.println("wglARBPFIDs2GLCapabilities: Cannot get pixel format attributes for pixel format " + - i + "/" + numFormats + ": " + pfdIDs[i] + ", " + - GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrbits).toString()); + if( 1 > pfdIDs[i] ) { + System.err.println("wglARBPFIDs2GLCapabilities: Invalid pfdID " + i + "/" + numFormats + ": " + pfdIDs[i]); + } else { + System.err.println("wglARBPFIDs2GLCapabilities: Cannot get pixel format attributes for pixel format " + + i + "/" + numFormats + ": " + pfdIDs[i] + ", hdc " + toHexString(hdc)); + } } } return bucket; @@ -412,9 +422,6 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return false; } - boolean onscreen = caps.isOnscreen(); - boolean pbuffer = caps.isPBuffer(); - int niattribs = 0; iattributes[niattribs++] = WGLExt.WGL_SUPPORT_OPENGL_ARB; @@ -423,17 +430,24 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio iattributes[niattribs++] = WGLExt.WGL_ACCELERATION_ARB; iattributes[niattribs++] = accelerationValue; } - if (onscreen) { - iattributes[niattribs++] = WGLExt.WGL_DRAW_TO_WINDOW_ARB; - iattributes[niattribs++] = GL.GL_TRUE; - } else if (pbuffer && sharedResource.hasARBPBuffer()) { - iattributes[niattribs++] = WGLExt.WGL_DRAW_TO_PBUFFER_ARB; - iattributes[niattribs++] = GL.GL_TRUE; + + final boolean usePBuffer = caps.isPBuffer() && sharedResource.hasARBPBuffer() ; + + final int surfaceType; + if( caps.isOnscreen() ) { + surfaceType = WGLExt.WGL_DRAW_TO_WINDOW_ARB; + } else if( caps.isFBO() ) { + surfaceType = WGLExt.WGL_DRAW_TO_WINDOW_ARB; // native replacement! + } else if( usePBuffer ) { + surfaceType = WGLExt.WGL_DRAW_TO_PBUFFER_ARB; + } else if( caps.isBitmap() ) { + surfaceType = WGLExt.WGL_DRAW_TO_BITMAP_ARB; } else { - iattributes[niattribs++] = WGLExt.WGL_DRAW_TO_BITMAP_ARB; - iattributes[niattribs++] = GL.GL_TRUE; + throw new GLException("no surface type set in caps: "+caps); } - + iattributes[niattribs++] = surfaceType; + iattributes[niattribs++] = GL.GL_TRUE; + iattributes[niattribs++] = WGLExt.WGL_DOUBLE_BUFFER_ARB; if (caps.getDoubleBuffered()) { iattributes[niattribs++] = GL.GL_TRUE; @@ -495,7 +509,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio boolean useFloat = caps.getPbufferFloatingPointBuffers(); boolean ati = false; boolean nvidia = false; - if (pbuffer && sharedResource.hasARBPBuffer()) { + if ( usePBuffer ) { // Check some invariants and set up some state if (rect && !rtt) { throw new GLException("Render-to-texture-rectangle requires render-to-texture to be specified"); @@ -574,33 +588,38 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return true; } - static int AttribList2DrawableTypeBits(AbstractGraphicsDevice device, GLProfile glp, final int[] iattribs, final int niattribs, final int[] iresults) { + static int AttribList2DrawableTypeBits(final int[] iattribs, + final int niattribs, final int[] iresults) { int val = 0; for (int i = 0; i < niattribs; i++) { int attr = iattribs[i]; switch (attr) { case WGLExt.WGL_DRAW_TO_WINDOW_ARB: - if(iresults[i] == GL.GL_TRUE) val |= GLGraphicsConfigurationUtil.WINDOW_BIT; + if(iresults[i] == GL.GL_TRUE) { + val |= GLGraphicsConfigurationUtil.WINDOW_BIT | + GLGraphicsConfigurationUtil.FBO_BIT; + } break; case WGLExt.WGL_DRAW_TO_BITMAP_ARB: - if(iresults[i] == GL.GL_TRUE) val |= GLGraphicsConfigurationUtil.BITMAP_BIT; + if(iresults[i] == GL.GL_TRUE) { + val |= GLGraphicsConfigurationUtil.BITMAP_BIT; + } break; case WGLExt.WGL_DRAW_TO_PBUFFER_ARB: - if(iresults[i] == GL.GL_TRUE) val |= GLGraphicsConfigurationUtil.PBUFFER_BIT; + if(iresults[i] == GL.GL_TRUE) { + val |= GLGraphicsConfigurationUtil.PBUFFER_BIT; + } break; } } - if ( GLContext.isFBOAvailable(device, glp) ) { - val |= GLGraphicsConfigurationUtil.FBO_BIT; - } return val; } - static WGLGLCapabilities AttribList2GLCapabilities(final AbstractGraphicsDevice device, - final GLProfile glp, final long hdc, final int pfdID, - final int[] iattribs, final int niattribs, final int[] iresults, final int winattrmask) { - final int allDrawableTypeBits = AttribList2DrawableTypeBits(device, glp, iattribs, niattribs, iresults); + static WGLGLCapabilities AttribList2GLCapabilities(final GLProfile glp, + final long hdc, final int pfdID, final int[] iattribs, + final int niattribs, final int[] iresults, final int winattrmask) { + final int allDrawableTypeBits = AttribList2DrawableTypeBits(iattribs, niattribs, iresults); int drawableTypeBits = winattrmask & allDrawableTypeBits; if( 0 == drawableTypeBits ) { @@ -610,7 +629,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio if (WGLUtil.DescribePixelFormat(hdc, pfdID, PIXELFORMATDESCRIPTOR.size(), pfd) == 0) { // remove displayable bits, since pfdID is non displayable - drawableTypeBits = drawableTypeBits & ~(GLGraphicsConfigurationUtil.WINDOW_BIT | GLGraphicsConfigurationUtil.BITMAP_BIT); + drawableTypeBits = drawableTypeBits & ~(GLGraphicsConfigurationUtil.WINDOW_BIT | GLGraphicsConfigurationUtil.BITMAP_BIT | GLGraphicsConfigurationUtil.FBO_BIT ); if( 0 == drawableTypeBits ) { return null; } @@ -638,32 +657,30 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return pfdIDs; } - static int PFD2DrawableTypeBits(AbstractGraphicsDevice device, GLProfile glp, PIXELFORMATDESCRIPTOR pfd) { + static int PFD2DrawableTypeBits(PIXELFORMATDESCRIPTOR pfd) { int val = 0; int dwFlags = pfd.getDwFlags(); if( 0 != (GDI.PFD_DRAW_TO_WINDOW & dwFlags ) ) { - val |= GLGraphicsConfigurationUtil.WINDOW_BIT; + val |= GLGraphicsConfigurationUtil.WINDOW_BIT | + GLGraphicsConfigurationUtil.FBO_BIT; } if( 0 != (GDI.PFD_DRAW_TO_BITMAP & dwFlags ) ) { val |= GLGraphicsConfigurationUtil.BITMAP_BIT; } - if ( GLContext.isFBOAvailable(device, glp) ) { - val |= GLGraphicsConfigurationUtil.FBO_BIT; - } return val; } - static WGLGLCapabilities PFD2GLCapabilities(AbstractGraphicsDevice device, final GLProfile glp, final long hdc, final int pfdID, final int winattrmask) { + static WGLGLCapabilities PFD2GLCapabilities(final GLProfile glp, final long hdc, final int pfdID, final int winattrmask) { PIXELFORMATDESCRIPTOR pfd = createPixelFormatDescriptor(hdc, pfdID); if(null == pfd) { return null; } if ((pfd.getDwFlags() & GDI.PFD_SUPPORT_OPENGL) == 0) { - return null; + return null; } - final int allDrawableTypeBits = PFD2DrawableTypeBits(device, glp, pfd); + final int allDrawableTypeBits = PFD2DrawableTypeBits(pfd); final int drawableTypeBits = winattrmask & allDrawableTypeBits; if( 0 == drawableTypeBits ) { @@ -673,79 +690,105 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio final WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); res.setValuesByGDI(); return (WGLGLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(res, drawableTypeBits ); - } - - static PIXELFORMATDESCRIPTOR GLCapabilities2PFD(GLCapabilitiesImmutable caps, PIXELFORMATDESCRIPTOR pfd) { - int colorDepth = (caps.getRedBits() + - caps.getGreenBits() + - caps.getBlueBits()); - if (colorDepth < 15) { - throw new GLException("Bit depths < 15 (i.e., non-true-color) not supported"); - } - int pfdFlags = (GDI.PFD_SUPPORT_OPENGL | - GDI.PFD_GENERIC_ACCELERATED); - if (caps.getDoubleBuffered()) { - pfdFlags |= GDI.PFD_DOUBLEBUFFER; - } - if (caps.isOnscreen()) { - pfdFlags |= GDI.PFD_DRAW_TO_WINDOW; - } else { - pfdFlags |= GDI.PFD_DRAW_TO_BITMAP; - } - if (caps.getStereo()) { - pfdFlags |= GDI.PFD_STEREO; - } - pfd.setDwFlags(pfdFlags); - pfd.setIPixelType((byte) GDI.PFD_TYPE_RGBA); - pfd.setCColorBits((byte) colorDepth); - pfd.setCRedBits ((byte) caps.getRedBits()); - pfd.setCGreenBits((byte) caps.getGreenBits()); - pfd.setCBlueBits ((byte) caps.getBlueBits()); - pfd.setCAlphaBits((byte) caps.getAlphaBits()); - int accumDepth = (caps.getAccumRedBits() + - caps.getAccumGreenBits() + - caps.getAccumBlueBits()); - pfd.setCAccumBits ((byte) accumDepth); - pfd.setCAccumRedBits ((byte) caps.getAccumRedBits()); - pfd.setCAccumGreenBits((byte) caps.getAccumGreenBits()); - pfd.setCAccumBlueBits ((byte) caps.getAccumBlueBits()); - pfd.setCAccumAlphaBits((byte) caps.getAccumAlphaBits()); - pfd.setCDepthBits((byte) caps.getDepthBits()); - pfd.setCStencilBits((byte) caps.getStencilBits()); - pfd.setILayerType((byte) GDI.PFD_MAIN_PLANE); - - // n/a with non ARB/GDI method: - // multisample - // opaque - // pbuffer - return pfd; - } - - static PIXELFORMATDESCRIPTOR createPixelFormatDescriptor(long hdc, int pfdID) { - PIXELFORMATDESCRIPTOR pfd = PIXELFORMATDESCRIPTOR.create(); - pfd.setNSize((short) PIXELFORMATDESCRIPTOR.size()); - pfd.setNVersion((short) 1); - if(0 != hdc && 1 <= pfdID) { - if (WGLUtil.DescribePixelFormat(hdc, pfdID, PIXELFORMATDESCRIPTOR.size(), pfd) == 0) { - // Accelerated pixel formats that are non displayable - if(DEBUG) { - System.err.println("Info: Non displayable pixel format " + pfdID + " of device context: error code " + GDI.GetLastError()); - } + } + + static WGLGLCapabilities PFD2GLCapabilitiesNoCheck(final GLProfile glp, final long hdc, final int pfdID) { + PIXELFORMATDESCRIPTOR pfd = createPixelFormatDescriptor(hdc, pfdID); + return PFD2GLCapabilitiesNoCheck(glp, pfd, pfdID); + } + + static WGLGLCapabilities PFD2GLCapabilitiesNoCheck(GLProfile glp, PIXELFORMATDESCRIPTOR pfd, int pfdID) { + if(null == pfd) { return null; } - } - return pfd; - } - - static PIXELFORMATDESCRIPTOR createPixelFormatDescriptor() { - return createPixelFormatDescriptor(0, 0); - } - - public String toString() { - return "WindowsWGLGraphicsConfiguration["+getScreen()+", pfdID " + getPixelFormatID() + ", ARB-Choosen " + isChoosenByARB() + - ",\n\trequested " + getRequestedCapabilities() + - ",\n\tchosen " + getChosenCapabilities() + - "]"; - } + final WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); + res.setValuesByGDI(); + return (WGLGLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(res, PFD2DrawableTypeBits(pfd)); + } + + static PIXELFORMATDESCRIPTOR GLCapabilities2PFD(GLCapabilitiesImmutable caps, PIXELFORMATDESCRIPTOR pfd) { + int colorDepth = (caps.getRedBits() + + caps.getGreenBits() + + caps.getBlueBits()); + if (colorDepth < 15) { + throw new GLException("Bit depths < 15 (i.e., non-true-color) not supported"); + } + int pfdFlags = ( GDI.PFD_SUPPORT_OPENGL | GDI.PFD_GENERIC_ACCELERATED ); + + if( caps.isOnscreen() ) { + pfdFlags |= GDI.PFD_DRAW_TO_WINDOW; + } else if( caps.isFBO() ) { + pfdFlags |= GDI.PFD_DRAW_TO_WINDOW; // native replacement! + } else if( caps.isPBuffer() ) { + pfdFlags |= GDI.PFD_DRAW_TO_BITMAP; // pbuffer n/a, use bitmap + } else if( caps.isBitmap() ) { + pfdFlags |= GDI.PFD_DRAW_TO_BITMAP; + } else { + throw new GLException("no surface type set in caps: "+caps); + } + + if ( caps.getDoubleBuffered() ) { + if( caps.isBitmap() || caps.isPBuffer() ) { + pfdFlags |= GDI.PFD_DOUBLEBUFFER_DONTCARE; // bitmaps probably don't have dbl buffering + } else { + pfdFlags |= GDI.PFD_DOUBLEBUFFER; + } + } + + if (caps.getStereo()) { + pfdFlags |= GDI.PFD_STEREO; + } + pfd.setDwFlags(pfdFlags); + pfd.setIPixelType((byte) GDI.PFD_TYPE_RGBA); + pfd.setCColorBits((byte) colorDepth); + pfd.setCRedBits ((byte) caps.getRedBits()); + pfd.setCGreenBits((byte) caps.getGreenBits()); + pfd.setCBlueBits ((byte) caps.getBlueBits()); + pfd.setCAlphaBits((byte) caps.getAlphaBits()); + int accumDepth = (caps.getAccumRedBits() + + caps.getAccumGreenBits() + + caps.getAccumBlueBits()); + pfd.setCAccumBits ((byte) accumDepth); + pfd.setCAccumRedBits ((byte) caps.getAccumRedBits()); + pfd.setCAccumGreenBits((byte) caps.getAccumGreenBits()); + pfd.setCAccumBlueBits ((byte) caps.getAccumBlueBits()); + pfd.setCAccumAlphaBits((byte) caps.getAccumAlphaBits()); + pfd.setCDepthBits((byte) caps.getDepthBits()); + pfd.setCStencilBits((byte) caps.getStencilBits()); + pfd.setILayerType((byte) GDI.PFD_MAIN_PLANE); + + // n/a with non ARB/GDI method: + // multisample + // opaque + // pbuffer + return pfd; + } + + static PIXELFORMATDESCRIPTOR createPixelFormatDescriptor(long hdc, int pfdID) { + PIXELFORMATDESCRIPTOR pfd = PIXELFORMATDESCRIPTOR.create(); + pfd.setNSize((short) PIXELFORMATDESCRIPTOR.size()); + pfd.setNVersion((short) 1); + if(0 != hdc && 1 <= pfdID) { + if (WGLUtil.DescribePixelFormat(hdc, pfdID, PIXELFORMATDESCRIPTOR.size(), pfd) == 0) { + // Accelerated pixel formats that are non displayable + if(DEBUG) { + System.err.println("Info: Non displayable pixel format " + pfdID + " of device context: error code " + GDI.GetLastError()); + } + return null; + } + } + return pfd; + } + + static PIXELFORMATDESCRIPTOR createPixelFormatDescriptor() { + return createPixelFormatDescriptor(0, 0); + } + + public String toString() { + return "WindowsWGLGraphicsConfiguration["+getScreen()+", pfdID " + getPixelFormatID() + ", ARB-Choosen " + isChoosenByARB() + + ",\n\trequested " + getRequestedCapabilities() + + ",\n\tchosen " + getChosenCapabilities() + + "]"; + } } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java index 66a5821d3..41c9bba02 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java @@ -85,7 +85,11 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilities objects - requested"); } - return chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested, chooser, absScreen); + if (chooser != null && !(chooser instanceof GLCapabilitiesChooser)) { + throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilitiesChooser objects"); + } + + return chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested, (GLCapabilitiesChooser)chooser, absScreen); } static WindowsWGLGraphicsConfiguration createDefaultGraphicsConfiguration(GLCapabilitiesImmutable caps, @@ -95,7 +99,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat static WindowsWGLGraphicsConfiguration chooseGraphicsConfigurationStatic(GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsReq, - CapabilitiesChooser chooser, + GLCapabilitiesChooser chooser, AbstractGraphicsScreen absScreen) { if(null==absScreen) { absScreen = DefaultGraphicsScreen.createDefault(NativeWindowFactory.TYPE_WINDOWS); @@ -151,8 +155,9 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } static List getAvailableGLCapabilitiesARB(WindowsWGLDrawableFactory.SharedResource sharedResource, AbstractGraphicsDevice device, GLProfile glProfile, long hdc) { - int[] pformats = WindowsWGLGraphicsConfiguration.wglAllARBPFIDs((WindowsWGLContext)sharedResource.getContext(), hdc); - return WindowsWGLGraphicsConfiguration.wglARBPFIDs2AllGLCapabilities(sharedResource, device, glProfile, hdc, pformats); + final int pfdIDCount = WindowsWGLGraphicsConfiguration.wglARBPFDIDCount((WindowsWGLContext)sharedResource.getContext(), hdc); + final int[] pformats = WindowsWGLGraphicsConfiguration.wglAllARBPFDIDs(pfdIDCount); + return WindowsWGLGraphicsConfiguration.wglARBPFIDs2GLCapabilities(sharedResource, device, glProfile, hdc, pformats, GLGraphicsConfigurationUtil.ALL_BITS); } static List getAvailableGLCapabilitiesGDI(AbstractGraphicsDevice device, GLProfile glProfile, long hdc) { @@ -160,7 +165,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat int numFormats = pformats.length; List bucket = new ArrayList(numFormats); for (int i = 0; i < numFormats; i++) { - final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(device, glProfile, hdc, pformats[i], GLGraphicsConfigurationUtil.ALL_BITS); + final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(glProfile, hdc, pformats[i], GLGraphicsConfigurationUtil.ALL_BITS); if(null != caps) { bucket.add(caps); } @@ -310,10 +315,20 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat final int winattrbits = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsChosen); final GLProfile glProfile = capsChosen.getGLProfile(); + final int pfdIDCount = WindowsWGLGraphicsConfiguration.wglARBPFDIDCount((WindowsWGLContext)sharedResource.getContext(), hdc); + if(DEBUG) { - System.err.println("translucency requested: "+(!capsChosen.isBackgroundOpaque())+", compositioning enabled: "+GDI.DwmIsCompositionEnabled()+" -> translucency "+(!isOpaque)); + System.err.println("updateGraphicsConfigurationARB: hdc "+toHexString(hdc)+", pfdIDCount(hdc) "+pfdIDCount+", capsChosen "+capsChosen+", "+GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrbits).toString()); + System.err.println("isOpaque "+isOpaque+" (translucency requested: "+(!capsChosen.isBackgroundOpaque())+", compositioning enabled: "+GDI.DwmIsCompositionEnabled()+")"); } + if(0 >= pfdIDCount) { + if (DEBUG) { + System.err.println("updateGraphicsConfigurationARB: failed due to 0 pfdIDs for hdc "+toHexString(hdc)+" - hdc incompatible w/ ARB ext."); + } + return false; + } + WGLGLCapabilities pixelFormatCaps = null; // chosen or preset PFD ID's caps boolean pixelFormatSet = false; // indicates a preset PFD ID [caps] final int presetPFDID = extHDC ? -1 : WGLUtil.GetPixelFormat(hdc) ; @@ -358,7 +373,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat System.err.println("updateGraphicsConfigurationARB: wglChoosePixelFormatARB failed with: "+capsChosen); } // 2nd choice: get all GLCapabilities available, no preferred recommendedIndex available - pformats = WindowsWGLGraphicsConfiguration.wglAllARBPFIDs((WindowsWGLContext)sharedResource.getContext(), hdc); + pformats = WindowsWGLGraphicsConfiguration.wglAllARBPFDIDs(pfdIDCount); if (DEBUG) { final int len = ( null != pformats ) ? pformats.length : 0; System.err.println("updateGraphicsConfigurationARB: NumFormats (wglAllARBPFIDs) " + len); @@ -378,8 +393,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat if( null == availableCaps || 0 == availableCaps.size() ) { if (DEBUG) { - System.err.println("updateGraphicsConfigurationARB: wglARBPFIDs2GLCapabilities failed with " + pformats.length + - " pfd ids, " + GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrbits).toString()); + System.err.println("updateGraphicsConfigurationARB: wglARBPFIDs2GLCapabilities failed with " + pformats.length + " pfd ids"); Thread.dumpStack(); } return false; @@ -436,7 +450,10 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat final GLProfile glProfile = capsChosen.getGLProfile(); final int winattrmask = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsChosen); - List availableCaps = new ArrayList(); + if(DEBUG) { + System.err.println("updateGraphicsConfigurationGDI: capsChosen "+capsChosen+", "+GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrmask).toString()); + } + int pfdID; // chosen or preset PFD ID WGLGLCapabilities pixelFormatCaps = null; // chosen or preset PFD ID's caps boolean pixelFormatSet = false; // indicates a preset PFD ID [caps] @@ -451,17 +468,29 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat + ", pixelformat " + pfdID); } pixelFormatSet = true; - pixelFormatCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(config.getScreen().getDevice(), glProfile, hdc, pfdID, winattrmask); + pixelFormatCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(glProfile, hdc, pfdID, winattrmask); + if(null == pixelFormatCaps) { + throw new GLException("Could not map PFD2GLCaps w/ already chosen pfdID "+pfdID); + } } else { - if(null == pformats) { + final boolean givenPFormats = null != pformats; + if( !givenPFormats ) { pformats = WindowsWGLGraphicsConfiguration.wglAllGDIPFIDs(hdc); } + List availableCaps = new ArrayList(); for (int i = 0; i < pformats.length; i++) { - final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(config.getScreen().getDevice(), glProfile, hdc, pformats[i], winattrmask); + final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(glProfile, hdc, pformats[i], winattrmask); if(null != caps) { availableCaps.add(caps); - } + if(DEBUG) { + final int j = availableCaps.size() - 1; + System.err.println("updateGraphicsConfigurationGDI: availableCaps["+i+" -> "+j+"]: "+caps); + } + } else if(DEBUG) { + GLCapabilitiesImmutable skipped = WindowsWGLGraphicsConfiguration.PFD2GLCapabilitiesNoCheck(glProfile, hdc, pformats[i]); + System.err.println("updateGraphicsConfigurationGDI: availableCaps["+i+" -> skip]: pfdID "+pformats[i]+", "+skipped); + } } // 1st choice: get GLCapabilities based on users GLCapabilities setting recommendedIndex as preferred choice @@ -470,16 +499,21 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat pfdID = WGLUtil.ChoosePixelFormat(hdc, pfd); int recommendedIndex = -1 ; if( 1 <= pfdID ) { - // seek index .. + // seek index .. in all formats _or_ in given formats! for (recommendedIndex = availableCaps.size() - 1 ; 0 <= recommendedIndex && pfdID != ((WGLGLCapabilities) availableCaps.get(recommendedIndex)).getPFDID(); recommendedIndex--) { /* nop */ } + if(DEBUG && 0 > recommendedIndex) { + final GLCapabilitiesImmutable reqPFDCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilitiesNoCheck(glProfile, pfd, pfdID); + final GLCapabilitiesImmutable chosenCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(glProfile, hdc, pfdID, winattrmask); + System.err.println("Chosen PFDID "+pfdID+", but not found in available caps (use given pfdIDs "+givenPFormats+", reqPFDCaps "+reqPFDCaps+", chosenCaps: "+chosenCaps); + } } - // 2nd choice: if no preferred recommendedIndex available if (DEBUG) { - System.err.println("updateGraphicsConfigurationGDI: ChoosePixelFormat(HDC " + toHexString(hdc) + ") = " + pfdID + ", idx " + recommendedIndex + " (LastError: " + GDI.GetLastError() + ")"); + System.err.println("updateGraphicsConfigurationGDI: ChoosePixelFormat(HDC " + toHexString(hdc) + ") = pfdID " + pfdID + ", idx " + recommendedIndex + " (LastError: " + GDI.GetLastError() + ")"); } + // 2nd choice: if no preferred recommendedIndex available int chosenIndex = chooseCapabilities(chooser, capsChosen, availableCaps, recommendedIndex); if ( 0 > chosenIndex ) { if (DEBUG) { @@ -490,8 +524,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } pixelFormatCaps = (WGLGLCapabilities) availableCaps.get(chosenIndex); if (DEBUG) { - System.err.println("chosen pfdID (GDI): native recommended "+ (recommendedIndex+1) + - ", caps " + pixelFormatCaps); + System.err.println("chosen pfdID (GDI): chosenIndex "+ chosenIndex + ", caps " + pixelFormatCaps); } } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java index d169945fe..866fcbbe4 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java @@ -41,7 +41,6 @@ import javax.media.opengl.GL; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; -import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; @@ -67,28 +66,6 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem this.chooser=chooser; } - static X11GLXGraphicsConfiguration create(GLProfile glp, X11GraphicsScreen x11Screen, int fbcfgID) { - final X11GraphicsDevice device = (X11GraphicsDevice) x11Screen.getDevice(); - final long display = device.getHandle(); - if(0==display) { - throw new GLException("Display null of "+x11Screen); - } - final int screen = x11Screen.getIndex(); - final long fbcfg = glXFBConfigID2FBConfig(display, screen, fbcfgID); - if(0==fbcfg) { - throw new GLException("FBConfig null of "+toHexString(fbcfgID)); - } - if(null==glp) { - glp = GLProfile.getDefault(x11Screen.getDevice()); - } - final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); - final X11GLCapabilities caps = GLXFBConfig2GLCapabilities(device, glp, fbcfg, GLGraphicsConfigurationUtil.ALL_BITS, factory.isGLXMultisampleAvailable(device)); - if(null==caps) { - throw new GLException("GLCapabilities null of "+toHexString(fbcfg)); - } - return new X11GLXGraphicsConfiguration(x11Screen, caps, caps, new DefaultGLCapabilitiesChooser()); - } - public Object clone() { return super.clone(); } @@ -123,11 +100,31 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem } } + static X11GLXGraphicsConfiguration create(GLProfile glp, X11GraphicsScreen x11Screen, int fbcfgID) { + final X11GraphicsDevice device = (X11GraphicsDevice) x11Screen.getDevice(); + final long display = device.getHandle(); + if(0==display) { + throw new GLException("Display null of "+x11Screen); + } + final int screen = x11Screen.getIndex(); + final long fbcfg = glXFBConfigID2FBConfig(display, screen, fbcfgID); + if(0==fbcfg) { + throw new GLException("FBConfig null of "+toHexString(fbcfgID)); + } + if(null==glp) { + glp = GLProfile.getDefault(x11Screen.getDevice()); + } + final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); + final X11GLCapabilities caps = GLXFBConfig2GLCapabilities(device, glp, fbcfg, GLGraphicsConfigurationUtil.ALL_BITS, factory.isGLXMultisampleAvailable(device)); + if(null==caps) { + throw new GLException("GLCapabilities null of "+toHexString(fbcfg)); + } + return new X11GLXGraphicsConfiguration(x11Screen, caps, caps, new DefaultGLCapabilitiesChooser()); + } + static int[] GLCapabilities2AttribList(GLCapabilitiesImmutable caps, - boolean forFBAttr, - boolean isMultisampleAvailable, - long display, - int screen) + boolean forFBAttr, boolean isMultisampleAvailable, + long display, int screen) { int colorDepth = (caps.getRedBits() + caps.getGreenBits() + @@ -140,10 +137,21 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem if (forFBAttr) { res[idx++] = GLX.GLX_DRAWABLE_TYPE; - res[idx++] = caps.isOnscreen() ? ( GLX.GLX_WINDOW_BIT ) : ( caps.isPBuffer() ? GLX.GLX_PBUFFER_BIT : GLX.GLX_PIXMAP_BIT ) ; - } - - if (forFBAttr) { + + final int surfaceType; + if( caps.isOnscreen() ) { + surfaceType = GLX.GLX_WINDOW_BIT; + } else if( caps.isFBO() ) { + surfaceType = GLX.GLX_WINDOW_BIT; // native replacement! + } else if( caps.isPBuffer() ) { + surfaceType = GLX.GLX_PBUFFER_BIT; + } else if( caps.isBitmap() ) { + surfaceType = GLX.GLX_PIXMAP_BIT; + } else { + throw new GLException("no surface type set in caps: "+caps); + } + res[idx++] = surfaceType; + res[idx++] = GLX.GLX_RENDER_TYPE; res[idx++] = GLX.GLX_RGBA_BIT; } else { @@ -244,14 +252,15 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem return true; } - static int FBCfgDrawableTypeBits(final X11GraphicsDevice device, GLProfile glp, final long fbcfg) { + static int FBCfgDrawableTypeBits(final X11GraphicsDevice device, final long fbcfg) { int val = 0; int[] tmp = new int[1]; int fbtype = glXGetFBConfig(device.getHandle(), fbcfg, GLX.GLX_DRAWABLE_TYPE, tmp, 0); if ( 0 != ( fbtype & GLX.GLX_WINDOW_BIT ) ) { - val |= GLGraphicsConfigurationUtil.WINDOW_BIT; + val |= GLGraphicsConfigurationUtil.WINDOW_BIT | + GLGraphicsConfigurationUtil.FBO_BIT; } if ( 0 != ( fbtype & GLX.GLX_PIXMAP_BIT ) ) { val |= GLGraphicsConfigurationUtil.BITMAP_BIT; @@ -259,9 +268,6 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem if ( 0 != ( fbtype & GLX.GLX_PBUFFER_BIT ) ) { val |= GLGraphicsConfigurationUtil.PBUFFER_BIT; } - if ( GLContext.isFBOAvailable(device, glp) ) { - val |= GLGraphicsConfigurationUtil.FBO_BIT; - } return val; } @@ -275,7 +281,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem static X11GLCapabilities GLXFBConfig2GLCapabilities(X11GraphicsDevice device, GLProfile glp, long fbcfg, int winattrmask, boolean isMultisampleAvailable) { - final int allDrawableTypeBits = FBCfgDrawableTypeBits(device, glp, fbcfg); + final int allDrawableTypeBits = FBCfgDrawableTypeBits(device, fbcfg); int drawableTypeBits = winattrmask & allDrawableTypeBits; final long display = device.getHandle(); @@ -286,7 +292,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem System.err.println("X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities: Null XVisualInfo for FBConfigID 0x" + Integer.toHexString(fbcfgid)); } // onscreen must have an XVisualInfo - drawableTypeBits = drawableTypeBits & ~GLGraphicsConfigurationUtil.WINDOW_BIT; + drawableTypeBits &= ~(GLGraphicsConfigurationUtil.WINDOW_BIT | GLGraphicsConfigurationUtil.FBO_BIT); } if( 0 == drawableTypeBits ) { @@ -394,10 +400,9 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem static X11GLCapabilities XVisualInfo2GLCapabilities(final X11GraphicsDevice device, GLProfile glp, XVisualInfo info, final int winattrmask, boolean isMultisampleEnabled) { final int allDrawableTypeBits = GLGraphicsConfigurationUtil.WINDOW_BIT | - GLGraphicsConfigurationUtil.BITMAP_BIT | - ( GLContext.isFBOAvailable(device, glp) ? GLGraphicsConfigurationUtil.FBO_BIT : 0 ) - ; - + GLGraphicsConfigurationUtil.BITMAP_BIT | + GLGraphicsConfigurationUtil.FBO_BIT ; + final int drawableTypeBits = winattrmask & allDrawableTypeBits; if( 0 == drawableTypeBits ) { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java index 3189f933f..8086cd26a 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java @@ -210,7 +210,6 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF if (x11Screen == null) { throw new IllegalArgumentException("AbstractGraphicsScreen is null"); } - if (capsChosen == null) { capsChosen = new GLCapabilities(null); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java index 50e6ed46c..5795e8cfe 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java +++ b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java @@ -74,7 +74,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { public Object cloneMutable() { return clone(); } - + @Override public Object clone() { try { @@ -84,6 +84,26 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { } } + /** + * Copies all {@link Capabilities} values + * from source into this instance. + * @return this instance + */ + public Capabilities copyFrom(CapabilitiesImmutable other) { + redBits = other.getRedBits(); + greenBits = other.getGreenBits(); + blueBits = other.getBlueBits(); + alphaBits = other.getAlphaBits(); + backgroundOpaque = other.isBackgroundOpaque(); + onscreen = other.isOnscreen(); + isBitmap = other.isBitmap(); + transparentValueRed = other.getTransparentRedValue(); + transparentValueGreen = other.getTransparentGreenValue(); + transparentValueBlue = other.getTransparentBlueValue(); + transparentValueAlpha = other.getTransparentAlphaValue(); + return this; + } + @Override public int hashCode() { // 31 * x == (x << 5) - x diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java index 0782e8915..cd1107e25 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java @@ -39,6 +39,8 @@ import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; +import jogamp.opengl.GLGraphicsConfigurationUtil; + import org.junit.Assert; import org.junit.Test; @@ -61,9 +63,19 @@ public class TestGLCapabilities01NEWT extends UITestCase { return true; } - void doTest(GLCapabilities reqGLCaps, GLEventListener demo) throws InterruptedException { + void doTest(GLCapabilitiesImmutable reqGLCaps, GLEventListener demo) throws InterruptedException { System.out.println("Requested GL Caps: "+reqGLCaps); - + + final GLCapabilitiesImmutable expGLCaps; + if( GLGraphicsConfigurationUtil.isGLCapabilitiesOffscreenAutoSelection(reqGLCaps) ) { + final GLDrawableFactory f = GLDrawableFactory.getFactory(reqGLCaps.getGLProfile()); + final boolean fboAvailable = true ; // f.canCreateFBO(null, reqGLCaps.getGLProfile()); + final boolean pbufferAvailable = f.canCreateGLPbuffer(null); + expGLCaps = GLGraphicsConfigurationUtil.fixGLCapabilities(reqGLCaps, fboAvailable, pbufferAvailable); + } else { + expGLCaps = reqGLCaps; + } + System.out.println("Expected GL Caps: "+expGLCaps); // // Create native windowing resources .. X11/Win/OSX // @@ -108,13 +120,13 @@ public class TestGLCapabilities01NEWT extends UITestCase { Assert.assertTrue(chosenGLCaps.getBlueBits()>5); Assert.assertTrue(chosenGLCaps.getRedBits()>5); Assert.assertTrue(chosenGLCaps.getDepthBits()>4); - Assert.assertEquals(reqGLCaps.isOnscreen(), chosenGLCaps.isOnscreen()); - Assert.assertEquals(reqGLCaps.isFBO(), chosenGLCaps.isFBO()); - Assert.assertEquals(reqGLCaps.isPBuffer(), chosenGLCaps.isPBuffer()); - Assert.assertEquals(reqGLCaps.isBitmap(), chosenGLCaps.isBitmap()); + Assert.assertEquals(expGLCaps.isOnscreen(), chosenGLCaps.isOnscreen()); + Assert.assertEquals(expGLCaps.isFBO(), chosenGLCaps.isFBO()); + Assert.assertEquals(expGLCaps.isPBuffer(), chosenGLCaps.isPBuffer()); + Assert.assertEquals(expGLCaps.isBitmap(), chosenGLCaps.isBitmap()); if(chosenGLCaps.isOnscreen() || chosenGLCaps.isFBO()) { // dbl buffer may be disabled w/ offscreen pbuffer and bitmap - Assert.assertEquals(reqGLCaps.getDoubleBuffered(), chosenGLCaps.getDoubleBuffered()); + Assert.assertEquals(expGLCaps.getDoubleBuffered(), chosenGLCaps.getDoubleBuffered()); } GLContext context = drawable.createContext(null); @@ -142,33 +154,33 @@ public class TestGLCapabilities01NEWT extends UITestCase { } } - //@Test - public void testGL2OffScreenAutoDblBuf() throws InterruptedException { + @Test + public void testGL2OnScreenDblBuf() throws InterruptedException { if(!checkProfile(GLProfile.GL2)) { return; } final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); - reqGLCaps.setOnscreen(false); doTest(reqGLCaps, new GearsES2(1)); } - - // @Test - public void testGL2OffScreenFBODblBuf() throws InterruptedException { + + @Test + public void testGL2OffScreenAutoDblBuf() throws InterruptedException { if(!checkProfile(GLProfile.GL2)) { return; } final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); reqGLCaps.setOnscreen(false); - reqGLCaps.setFBO(true); doTest(reqGLCaps, new GearsES2(1)); } - + @Test - public void testGL2OnScreenDblBuf() throws InterruptedException { + public void testGL2OffScreenFBODblBuf() throws InterruptedException { if(!checkProfile(GLProfile.GL2)) { return; } final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); doTest(reqGLCaps, new GearsES2(1)); } @@ -203,6 +215,27 @@ public class TestGLCapabilities01NEWT extends UITestCase { doTest(reqGLCaps, new GearsES2(1)); } + @Test + public void testES2OffScreenAutoDblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GLES2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); + reqGLCaps.setOnscreen(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBODblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GLES2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + doTest(reqGLCaps, new GearsES2(1)); + } + @Test public void testES2OffScreenPbufferDblBuf() throws InterruptedException { if(!checkProfile(GLProfile.GLES2)) { -- cgit v1.2.3 From 4dd44b985fe0541be3a3bcd9045d201ed3ca2cc5 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 15 Sep 2012 16:54:52 +0200 Subject: Seamless Integration of an FBObject based GLFBODrawable as GLOffscreenAutoDrawable.FBO and as an OffscreenLayerSurface's drawable (OSX) - Fix Bugs 569 and 599 Summary: ========= The new FBObject based GLFBODrawable implementation allows the seamless utilization of FBO offscreen rendering in single buffer, double buffer and MSAA mode. The GLFBODrawable uses a parent drawable based on a dummy surface to allow a GLOffscreenAutoDrawable.FBO creation or a mutable surface supporting an existing offscreen layer surface (OSX CALayer). Offscreen GLDrawable's and GLOffscreenAutoDrawable's can be selected via the GLCapabilities. If simply !onscreen is selected in the caps instance w/o enabling FBO, PBuffer or Bitmap, the factory will automatically choose regarding availability: FBO > PBuffer > Bitmap Double buffering is supported in MSAA more (intrinsic) and explicit in non MSAA. It is preferred when delivering resources (texture id's or framebuffer names) to a shared GLContext. This is demonstrated in (emulates our OSX CALayer implementation): TestFBOOffThreadSharedContextMix2DemosES2NEWT, TestFBOOnThreadSharedContext1DemoES2NEWT and with the OSX JAWT OffscreenLayerSurface itself. FBO is the preferred choice. +++ Offscreen drawables can be resized while maintaining a bound GLContext (e.g. w/ GLAutoDrawable). Previously both, drawable and context, needed to be destroyed and recreated at offscreen resize. Common implementation in GLDrawableHelper is used in the implementations (NEWT's GLWindow, AWT GLCanvas, SWT GLCanvas). +++ Tested: ======= Manually run all unit tests on: - Linux x86_64 NVidia/AMD/Mesa3d(ES) - OSX x86_64 NVidia - Windows x86_64 NVidia - Android arm Mali-400/Tegra-2 No regressions. Disclaimer: =========== This feature is committed almost in one patch. Both previous commits were introducing / fixing the capabilities behavior: 90d45928186f2be99999461cfe45f76a783cc961 9036376b7806a5fc61590bf49404eb71830de92f I have to appologize for the huge size and impact (files and platforms) of this commit however, I could not find a better way to inject this feature in one sane piece. NativeWindow Details: ===================== Complete decoupling of platform impl. detail of surfaces implementing ProxySurface. Used to generalize dummy surfaces and EGL surfaces on top of a native platform surface. - ProxySurface.UpstreamSurfaceHook -> UpstreamSurfaceHook - abstract class ProxySurface -> interface ProxySurface + ProxySurfaceImpl - Misc. implementations JOGL Details: ===================== FBOObject: API Change / Simplification & Usability - Removed reference counter to remove complexity, allow user to choose. - Add 'dispose' flag for detachColorbuffer(..), allowing to keep attachment alive - Fix equals operation of Attachment - Check pre-exising GL errors - Interface Colobuffer gets lifecycle methods - Add static factory methods to create Attachments w/o FBObject instance - Reset: - Clip min size to 1 - Keep alive samplingSink, i.e. don't issue resetMSAATexture2DSink(..). It gets called at syncFramebuffer()/use(..) later on before actual usage. This allows the consumer to utilize the GL_FRONT buffer until (e.g.) swap. - misc bugfixes GLOffscreenAutoDrawable: API Change - Reloc and interfacing - class com.jogamp.opengl.OffscreenAutoDrawable -> javax.media.opengl.* interfaces GLOffscreenAutoDrawable extends GLAutoDrawable GLOffscreenAutoDrawable.FBO extends GLOffscreenAutoDrawable, GLFBODrawable - Added general implementation and FBO specialization - Replacing GLPBuffer (deprecated) .. usable for any offscreen GLDrawable via factory GLAutoDrawable: - Add 'GLDrawable getDelegatedDrawable()' - Refine documentation of setContext(..), remove disclaimer and fixme tags GLDrawableFactory: - Refine API doc and it's selection mechanism for offscreen. - Add createOffscreenDrawable(..) - Add createOffscreenAutoDrawable(..) - Add canCreateFBO(..) - Mark createGLPbuffer(..) deprectated Mark GLPBuffer deprecated New: GLFBODrawable extends GLDrawable GLCanvas (AWT and SWT): Add offscreen resize support w/o GLContext recreation GLAutoDrawableBase .. GLWindow: - Add offscreen resize support w/o GLContext recreation - Remove double swapBuffer call - GLBase/GLContext: - Add: - boolean hasBasicFBOSupport() - boolean hasFullFBOSupport() - int getMaxRenderbufferSamples() - boolean isTextureFormatBGRA8888Available() GLContext: Fix version detection and hasGLSL() - Version detection in setGLFunctionAvailability(..) - Query GL_VERSION ASAP and parse it and compare w/ given major/minor - Use parsed version if valid and lower than given _or_ given is invalid. - Use validated version for caching (procaddr, ..), version number, etc. - Fix hasGLSL() Since 'isGL2ES2()' is true if 'isGL2()' and the latter simply alows GL 1.*, we confine the result to a GL >= 2.0 on desktops. FIXME: May consider GL 1.5 w/ extensions. - return isGL2ES2(); + return isGLES2() || + isGL3() || + isGL2() && ctxMajorVersion>1 ; GLDrawableImpl: - Add 'associateContext(GLContext, boolean)' allowing impl. to have a (weak) reference list of bound context. This is was pulled up from the OSX specific drawable impl. - swapBuffersImpl() -> swapBuffersImpl(boolean doubleBuffered) and call it regardless of single buffering. This is required to propagate this event to impl. properly, i.e. FBODrawable requires a swap notification. - Clarify 'contextMadeCurrent(..)' protocol GLDrawableHelper: - Add resize and recreate offscreen drawable util method - Simplify required init/reshape calls for GLEventListener - GLGraphicsConfigurationUtil: - fixWinAttribBitsAndHwAccel: Reflect sharede context hw-accel bits - OSX has no offscreen bitmap, use pbuffer - use proper offscreen auto selection if offscreen and no modes are set EGL Context/Drawable/DrawableFactory: Abstract native platform code out of base classes - Use EGLWrappedSurface w/ UpstreamSurfaceHook to handle upstream (X11, WGL, ..) lifecycle - in case the EGL resource is hooked up on it. Invisible dummy surfaces: All platforms - size is now reduced to 64x64 and decoupled of actual generic mutable size - fix device lifecycle, no more leaks +++ OSX ==== Enable support for GLFBODrawableImpl in offscreen CALayer mode - NSOpenGLImpl: hooks to calayer native code - calayer code: - allows pbuffer and texures (FBO) - decouple size and draw calls avoiding flickering - enable auto resize of calayer tree MacOSXCGLContext: - NSOpenGLImpl: - Fix false pbuffer 'usage', validate the pointer - If !pbuffer, copy other window mode bits of caps - MacOSXCGLGraphicsConfiguration: - Only assume pbuffer if !onscreen - Remove reference of native pixelformat pointer Native code: - use 'respondsToSelector:' query before calling 'new' methods avoiding an error message where unsuported (prev. OSX versions) - if monitor refresh-rate is queried 0, set to default 60hz - add missing NSAutoreleasePool decoration +++ Android / NEWT: =============== Issue setVisible(..) w/o wait, i.e. queue on EDT, @Android surfaceChanged() callback. Otherwise we could deadlock: setVisible(..) -> EDT -> setVisibleImpl(..) -> 'GL-display'. the latter may may cause havoc while Android-EDT is blocked [until it's return]. --- doc/TODO.txt | 12 - make/build-jogl.xml | 2 +- .../config/jogl/gl-impl-CustomJavaCode-common.java | 20 + make/scripts/java-win64-dbg.bat | 4 +- make/scripts/tests-x64.bat | 45 +- make/scripts/tests.sh | 50 +- make/stub_includes/opengl/macosx-window-system.h | 11 +- src/jogl/classes/com/jogamp/opengl/FBObject.java | 882 +++++++++++++-------- .../com/jogamp/opengl/GLAutoDrawableDelegate.java | 189 +++++ .../classes/com/jogamp/opengl/GLExtensions.java | 3 + .../com/jogamp/opengl/OffscreenAutoDrawable.java | 112 --- .../classes/com/jogamp/opengl/swt/GLCanvas.java | 41 +- .../classes/javax/media/opengl/GLAutoDrawable.java | 38 +- .../javax/media/opengl/GLAutoDrawableDelegate.java | 144 ---- src/jogl/classes/javax/media/opengl/GLBase.java | 38 + src/jogl/classes/javax/media/opengl/GLContext.java | 97 ++- .../javax/media/opengl/GLDrawableFactory.java | 128 ++- .../classes/javax/media/opengl/GLFBODrawable.java | 173 ++++ .../media/opengl/GLOffscreenAutoDrawable.java | 63 ++ src/jogl/classes/javax/media/opengl/GLPbuffer.java | 6 +- .../classes/javax/media/opengl/awt/GLCanvas.java | 119 +-- .../classes/javax/media/opengl/awt/GLJPanel.java | 13 +- .../classes/jogamp/opengl/GLAutoDrawableBase.java | 76 +- src/jogl/classes/jogamp/opengl/GLContextImpl.java | 175 ++-- .../jogamp/opengl/GLDrawableFactoryImpl.java | 127 +-- .../classes/jogamp/opengl/GLDrawableHelper.java | 185 ++++- src/jogl/classes/jogamp/opengl/GLDrawableImpl.java | 80 +- .../classes/jogamp/opengl/GLFBODrawableImpl.java | 496 ++++++++++-- .../jogamp/opengl/GLGraphicsConfigurationUtil.java | 28 +- .../jogamp/opengl/GLOffscreenAutoDrawableImpl.java | 123 +++ src/jogl/classes/jogamp/opengl/GLPbufferImpl.java | 31 +- src/jogl/classes/jogamp/opengl/egl/EGLContext.java | 6 - .../classes/jogamp/opengl/egl/EGLDrawable.java | 135 ++-- .../jogamp/opengl/egl/EGLDrawableFactory.java | 163 +--- .../opengl/egl/EGLDummyUpstreamSurfaceHook.java | 49 ++ .../jogamp/opengl/egl/EGLExternalContext.java | 11 - .../jogamp/opengl/egl/EGLGLCapabilities.java | 5 +- .../opengl/egl/EGLGraphicsConfiguration.java | 9 +- .../jogamp/opengl/egl/EGLOnscreenContext.java | 11 - .../jogamp/opengl/egl/EGLOnscreenDrawable.java | 4 +- .../jogamp/opengl/egl/EGLPbufferContext.java | 10 - .../jogamp/opengl/egl/EGLPbufferDrawable.java | 8 +- .../jogamp/opengl/egl/EGLUpstreamSurfaceHook.java | 145 +++- .../jogamp/opengl/egl/EGLWrappedSurface.java | 26 + .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 716 ++++++++++------- .../opengl/macosx/cgl/MacOSXCGLDrawable.java | 48 +- .../macosx/cgl/MacOSXCGLDrawableFactory.java | 71 +- .../macosx/cgl/MacOSXCGLGraphicsConfiguration.java | 21 +- .../cgl/MacOSXCGLGraphicsConfigurationFactory.java | 2 +- .../macosx/cgl/MacOSXExternalCGLContext.java | 7 +- .../macosx/cgl/MacOSXOnscreenCGLDrawable.java | 4 +- .../opengl/macosx/cgl/MacOSXPbufferCGLContext.java | 1 + .../macosx/cgl/MacOSXPbufferCGLDrawable.java | 42 +- .../windows/wgl/WindowsExternalWGLContext.java | 4 +- .../windows/wgl/WindowsExternalWGLDrawable.java | 4 +- .../opengl/windows/wgl/WindowsWGLDrawable.java | 43 +- .../windows/wgl/WindowsWGLDrawableFactory.java | 58 +- .../wgl/WindowsWGLGraphicsConfiguration.java | 29 +- .../WindowsWGLGraphicsConfigurationFactory.java | 28 +- .../opengl/x11/glx/X11ExternalGLXContext.java | 4 +- .../opengl/x11/glx/X11ExternalGLXDrawable.java | 5 +- .../jogamp/opengl/x11/glx/X11GLXDrawable.java | 7 +- .../opengl/x11/glx/X11GLXDrawableFactory.java | 63 +- .../x11/glx/X11GLXGraphicsConfiguration.java | 6 +- .../glx/X11GLXGraphicsConfigurationFactory.java | 6 +- .../opengl/x11/glx/X11PbufferGLXDrawable.java | 17 +- .../macosx/MacOSXWindowSystemInterface-calayer.m | 665 ++++++++++++++++ .../macosx/MacOSXWindowSystemInterface-pbuffer.m | 494 ------------ .../native/macosx/MacOSXWindowSystemInterface.m | 40 +- .../DelegatedUpstreamSurfaceHookMutableSize.java | 39 + ...elegatedUpstreamSurfaceHookWithSurfaceSize.java | 54 ++ .../UpstreamSurfaceHookMutableSize.java | 45 ++ .../com/jogamp/nativewindow/WrappedSurface.java | 78 -- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 99 ++- .../jogamp/nativewindow/egl/EGLGraphicsDevice.java | 4 +- .../javax/media/nativewindow/NativeSurface.java | 5 +- .../media/nativewindow/OffscreenLayerSurface.java | 3 + .../javax/media/nativewindow/ProxySurface.java | 266 ++----- .../media/nativewindow/UpstreamSurfaceHook.java | 52 ++ .../jogamp/nativewindow/ProxySurfaceImpl.java | 326 ++++++++ .../jogamp/nativewindow/WrappedSurface.java | 95 +++ .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 84 +- .../macosx/OSXDummyUpstreamSurfaceHook.java | 56 ++ .../jogamp/nativewindow/macosx/OSXUtil.java | 15 + .../windows/GDIDummyUpstreamSurfaceHook.java | 50 ++ .../jogamp/nativewindow/windows/GDISurface.java | 34 +- .../x11/X11DummyUpstreamSurfaceHook.java | 60 ++ src/nativewindow/native/macosx/OSXmisc.m | 189 +++-- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 9 + .../classes/com/jogamp/newt/opengl/GLWindow.java | 25 +- .../classes/com/jogamp/newt/swt/NewtCanvasSWT.java | 3 + src/newt/classes/jogamp/newt/OffscreenWindow.java | 31 +- src/newt/classes/jogamp/newt/WindowImpl.java | 34 +- .../jogamp/newt/driver/android/WindowDriver.java | 2 +- .../jogamp/newt/driver/macosx/WindowDriver.java | 24 +- src/newt/native/MacWindow.m | 49 +- .../test/android/MovieCubeActivityLauncher0.java | 2 + .../android/NEWTGraphUI1pActivityLauncher.java | 22 +- .../jogl/acore/TestFBOAutoDrawableDeadlockAWT.java | 128 +++ .../jogl/acore/TestFBOAutoDrawableFactoryNEWT.java | 375 +++++++++ .../test/junit/jogl/acore/TestFBODrawableNEWT.java | 272 ------- .../test/junit/jogl/acore/TestFBOMRTNEWT01.java | 2 +- .../junit/jogl/acore/TestFBOMix2DemosES2NEWT.java | 2 +- ...tFBOOffThreadSharedContextMix2DemosES2NEWT.java | 298 +++++++ .../TestFBOOnThreadSharedContext1DemoES2NEWT.java | 273 +++++++ .../jogl/acore/TestGLAutoDrawableDelegateNEWT.java | 152 ---- ...estGLAutoDrawableDelegateOnOffscrnCapsNEWT.java | 384 +++++++++ .../TestGLAutoDrawableFactoryOffscrnCapsNEWT.java | 317 ++++++++ ...TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java | 328 ++++++++ ...estGLAutoDrawableGLWindowOnOffscrnCapsNEWT.java | 351 ++++++++ ...LAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT.java | 300 +++++++ .../junit/jogl/acore/TestGLCapabilities01NEWT.java | 266 ------- .../acore/TestGLContextDrawableSwitchNEWT.java | 22 +- .../junit/jogl/acore/TestGLDrawable01NEWT.java | 171 ---- .../jogl/acore/TestGLExtensionQueryOffscreen.java | 19 +- .../jogl/acore/TestNEWTCloseX11DisplayBug565.java | 46 +- .../acore/TestOffscreenLayer01GLCanvasAWT.java | 236 ++++++ .../acore/TestOffscreenLayer02NewtCanvasAWT.java | 233 ++++++ .../junit/jogl/acore/TestPBufferDeadlockAWT.java | 2 + .../junit/jogl/acore/TestSharedContextListAWT.java | 20 +- .../jogl/acore/TestSharedContextListNEWT.java | 20 +- .../jogl/acore/TestSharedContextListNEWT2.java | 14 +- .../jogl/acore/TestSharedContextNewtAWTBug523.java | 17 +- .../jogl/acore/TestSharedContextVBOES1NEWT.java | 20 +- .../jogl/acore/TestSharedContextVBOES2NEWT.java | 20 +- .../jogl/acore/TestSharedContextVBOES2NEWT2.java | 14 +- .../awt/TestBug461FBOSupersamplingSwingAWT.java | 159 ++++ .../TestBug461OffscreenSupersamplingSwingAWT.java | 157 ---- .../TestBug461PBufferSupersamplingSwingAWT.java | 159 ++++ .../junit/jogl/caps/TestMultisampleES1AWT.java | 2 +- .../junit/jogl/caps/TestMultisampleES1NEWT.java | 2 +- .../junit/jogl/caps/TestMultisampleES2NEWT.java | 2 +- .../opengl/test/junit/jogl/demos/es1/GearsES1.java | 6 + .../test/junit/jogl/demos/es1/RedSquareES1.java | 19 +- .../test/junit/jogl/demos/es2/FBOMix2DemosES2.java | 5 +- .../opengl/test/junit/jogl/demos/es2/GearsES2.java | 17 +- .../test/junit/jogl/demos/es2/Mix2TexturesES2.java | 216 +++++ .../test/junit/jogl/demos/es2/RedSquareES2.java | 21 +- .../junit/jogl/demos/es2/awt/TestGearsES2AWT.java | 27 +- .../opengl/test/junit/jogl/demos/gl2/Gears.java | 13 +- .../jogl/demos/gl2/awt/TestGLJPanelAWTBug450.java | 2 +- .../test/junit/jogl/offscreen/ReadBufferBase.java | 2 +- .../test/junit/jogl/swt/TestNewtCanvasSWTGLn.java | 2 +- .../junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java | 2 +- .../TestGLReadBufferUtilTextureIOWrite01AWT.java | 4 +- .../TestGLReadBufferUtilTextureIOWrite01NEWT.java | 16 +- .../TestGLReadBufferUtilTextureIOWrite02AWT.java | 2 +- .../TestGLReadBufferUtilTextureIOWrite02NEWT.java | 2 +- .../util/texture/TestPNGTextureFromFileAWT.java | 2 +- .../util/texture/TestPNGTextureFromFileNEWT.java | 2 +- .../test/junit/newt/TestFocus01SwingAWTRobot.java | 21 +- .../test/junit/newt/TestFocus02SwingAWTRobot.java | 16 +- .../opengl/test/junit/newt/TestWindows01NEWT.java | 1 - .../parenting/NewtAWTReparentingKeyAdapter.java | 2 +- .../TestParentingOffscreenLayer01GLCanvasAWT.java | 211 ----- ...TestParentingOffscreenLayer02NewtCanvasAWT.java | 221 ------ .../opengl/test/junit/util/AWTRobotUtil.java | 39 +- .../opengl/test/junit/util/NEWTGLContext.java | 4 +- .../jogamp/opengl/test/junit/util/UITestCase.java | 109 ++- 159 files changed, 9357 insertions(+), 4643 deletions(-) create mode 100644 src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java delete mode 100644 src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java delete mode 100644 src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java create mode 100644 src/jogl/classes/javax/media/opengl/GLFBODrawable.java create mode 100644 src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java create mode 100644 src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java create mode 100644 src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java create mode 100644 src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java create mode 100644 src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m delete mode 100644 src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m create mode 100644 src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookMutableSize.java create mode 100644 src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookWithSurfaceSize.java create mode 100644 src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSize.java delete mode 100644 src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java create mode 100644 src/nativewindow/classes/javax/media/nativewindow/UpstreamSurfaceHook.java create mode 100644 src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java create mode 100644 src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java create mode 100644 src/nativewindow/classes/jogamp/nativewindow/macosx/OSXDummyUpstreamSurfaceHook.java create mode 100644 src/nativewindow/classes/jogamp/nativewindow/windows/GDIDummyUpstreamSurfaceHook.java create mode 100644 src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOAutoDrawableDeadlockAWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOAutoDrawableFactoryNEWT.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOOffThreadSharedContextMix2DemosES2NEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOOnThreadSharedContext1DemoES2NEWT.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateNEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateOnOffscrnCapsNEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableFactoryOffscrnCapsNEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLDrawable01NEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer02NewtCanvasAWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug461FBOSupersamplingSwingAWT.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug461OffscreenSupersamplingSwingAWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug461PBufferSupersamplingSwingAWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/Mix2TexturesES2.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer01GLCanvasAWT.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer02NewtCanvasAWT.java (limited to 'src/nativewindow') diff --git a/doc/TODO.txt b/doc/TODO.txt index 20a7a9071..0ce1fd3ac 100644 --- a/doc/TODO.txt +++ b/doc/TODO.txt @@ -1,13 +1,6 @@ Version 2.0: -- Fix ES2 detection if it fails (no egl pbuffer on nokia es2) ? - SIGG slides / video -- FBO Drawable w/ given NativeSurface - and OSX w/ JAWT - - Bug 569 - - Bug 599 - -- cleanup jocl build/jar/demos -- clean up . in jar names in all docs and tutorials - ES3 / GL 4.3 @@ -15,11 +8,6 @@ Version 2.0: WIP: -- GLPbuffer -> GLOffscreenAutoDrawable - - GLPbuffer GLDrawableFactory.createPbuffer() -> - GLOffscreenAutoDrawable GLDrawableFactory.createOffsceenAutoDrawable() - - Mark both deprecated! - - Optimize/Fix NIO caching of glMapBuffer/glUnmapBuffer - optimize the NIO caching, i.e. memory range, incr. reference count - _remove_ the cached object w/ decr. ref count, remove object diff --git a/make/build-jogl.xml b/make/build-jogl.xml index 40859845c..a72d6c77c 100644 --- a/make/build-jogl.xml +++ b/make/build-jogl.xml @@ -1375,7 +1375,7 @@ - + diff --git a/make/config/jogl/gl-impl-CustomJavaCode-common.java b/make/config/jogl/gl-impl-CustomJavaCode-common.java index b05ba2643..283a4e623 100644 --- a/make/config/jogl/gl-impl-CustomJavaCode-common.java +++ b/make/config/jogl/gl-impl-CustomJavaCode-common.java @@ -50,6 +50,26 @@ return null; } + @Override + public final boolean hasBasicFBOSupport() { + return _context.hasBasicFBOSupport(); + } + + @Override + public final boolean hasFullFBOSupport() { + return _context.hasFullFBOSupport(); + } + + @Override + public final int getMaxRenderbufferSamples() { + return _context.getMaxRenderbufferSamples(); + } + + @Override + public final boolean isTextureFormatBGRA8888Available() { + return _context.isTextureFormatBGRA8888Available(); + } + @Override public final GLContext getContext() { return _context; diff --git a/make/scripts/java-win64-dbg.bat b/make/scripts/java-win64-dbg.bat index 510ebf4dc..b63438534 100755 --- a/make/scripts/java-win64-dbg.bat +++ b/make/scripts/java-win64-dbg.bat @@ -30,13 +30,15 @@ REM set D_ARGS="-Djogl.debug.ExtensionAvailabilityCache" "-Djogl.debug=all" "-Dn REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.NativeLibrary=true" REM set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.ExtensionAvailabilityCache" "-Djogamp.debug.ProcAddressHelper=true" REM set D_ARGS="-Djogl.debug.GraphicsConfiguration" +REM set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.GLDrawable" "-Dnativewindow.debug.GraphicsConfiguration" REM set D_ARGS="-Djogamp.debug.JNILibLoader=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" "-Djogl.debug.GLProfile=true" REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.Lock" "-Djogamp.debug.Lock.TraceLock" -set D_ARGS="-Djogl.debug=all" "-Dnativewindow.debug=all" +REM set D_ARGS="-Djogl.debug=all" "-Dnativewindow.debug=all" REM set D_ARGS="-Djogl.debug=all" REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch" "-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL" REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch" "-Djogl.windows.useWGLVersionOf5WGLGDIFuncSet" REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch" +set D_ARGS="-Dnewt.debug.Window" REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display" REM set D_ARGS="-Djogl.debug.GLDebugMessageHandler" "-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL" REM set D_ARGS="-Djogl.debug.DebugGL" "-Djogl.debug.GLDebugMessageHandler" "-Djogl.debug.GLSLCode" diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat index 22cce49aa..a4207b696 100755 --- a/make/scripts/tests-x64.bat +++ b/make/scripts/tests-x64.bat @@ -1,9 +1,9 @@ REM scripts\java-win64-dbg.bat jogamp.newt.awt.opengl.VersionApplet REM scripts\java-win64-dbg.bat com.jogamp.newt.opengl.GLWindow REM scripts\java-win64-dbg.bat javax.media.opengl.awt.GLCanvas -REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLCapabilities01NEWT $* -scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $* -REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT $* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLCapabilities01NEWT %* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT %* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT -time 5000 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestAWT01GLn @@ -40,13 +40,13 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestP REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03bAWT -time 100000 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01AWT %* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aSWT $* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT $* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aSWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT %* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor03AWTGLn $* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTGLn $* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor03AWTGLn %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTGLn %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestWindows01NEWT REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT @@ -73,9 +73,9 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.caps.TestMultis REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestBug461OffscreenSupersamplingSwingAWT REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestShaderCompilationBug459AWT -REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol01AWT $* -REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol02NEWT $* -REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol03NewtAWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol01AWT %* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol02NEWT %* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol03NewtAWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT01GLn %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT02GLn %* @@ -96,16 +96,25 @@ REM scripts\java-win64.bat com.jogamp.opengl.test.junit.graph.demos.GPUTextNewtD REM scripts\java-win64.bat com.jogamp.opengl.test.junit.graph.demos.GPURegionNewtDemo01 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.graph.demos.GPURegionNewtDemo02 -REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug00NEWT $* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug01NEWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug00NEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug01NEWT %* -REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT $* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestMapBuffer01NEWT +scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryOffscrnCapsNEWT $* + +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableFactoryNEWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableOffThreadSharedContextES2NEWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBOMix2DemosES2NEWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBOMRTNEWT01 $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableDeadlockAWT $* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.awt.TestBug461FBOSupersamplingSwingAWT REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01 -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT %* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestFBOMRTNEWT01 %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %* diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index ce04ae4dc..d2e2db375 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -32,7 +32,7 @@ MOSX=0 MOSX_MT=0 uname -a | grep -i Darwin && MOSX=1 if [ $MOSX -eq 1 ] ; then - #export NSZombieEnabled=YES + export NSZombieEnabled=YES MOSX_MT=1 fi @@ -56,11 +56,13 @@ function jrun() { #D_ARGS="-Djogl.disable.opengles" #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.GLSLCode -Dnewt.debug.Window.MouseEvent" #D_ARGS="-Djogl.debug.TraceGL -Djogl.debug.DebugGL -Djogl.debug.GLSLCode" + #D_ARGS="-Djogl.debug.FBObject -Djogl.debug.GLContext -Djogl.debug.GLDrawable -Djogl.debug.GLCanvas -Dnewt.debug.Window" #D_ARGS="-Djogl.debug.FBObject" #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.FBObject" #D_ARGS="-Djogl.debug.GLContext.NoProfileAliasing" #D_ARGS="-Djogamp.debug=all -Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" - #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all" + #D_ARGS="-Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" + #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLDrawable -Dnativewindow.debug.GraphicsConfiguration" #D_ARGS="-Djogl.fbo.force.none" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all -Djogamp.debug.Lock" #D_ARGS="-Djogl.debug=all" @@ -208,7 +210,7 @@ function testawtswt() { } # -# newt (testnoawt and testawt) +# core/newt (testnoawt and testawt) # #testnoawt com.jogamp.nativewindow.NativeWindowVersion $* #testnoawt com.jogamp.opengl.JoglVersion $* @@ -237,6 +239,26 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT $* +#testawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryOffscrnCapsNEWT $* + +#testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer01GLCanvasAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer02NewtCanvasAWT $* + +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableFactoryNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOOffThreadSharedContextMix2DemosES2NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOOnThreadSharedContext1DemoES2NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMix2DemosES2NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMRTNEWT01 $* +#testawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableDeadlockAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461FBOSupersamplingSwingAWT + +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* + #testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cSwingAWT $* @@ -331,10 +353,8 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting03AWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT $* #testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aSWT $* -testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* +#testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01GLCanvasAWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer02NewtCanvasAWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestTranslucentParentingAWT $* #testawt com.jogamp.opengl.test.junit.newt.TestCloseNewtAWT #testawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1AWT $* @@ -376,24 +396,6 @@ testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01 $* -# -# FBO / .. -# - -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable00NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable01NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable01bNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable02NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMix2DemosES2NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableMix2DemosES2NEWT $* -#testawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableDeadlockAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461FBOSupersamplingSwingAWT -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMRTNEWT01 $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* - # # Graph # diff --git a/make/stub_includes/opengl/macosx-window-system.h b/make/stub_includes/opengl/macosx-window-system.h index 47b51a509..c627f67de 100644 --- a/make/stub_includes/opengl/macosx-window-system.h +++ b/make/stub_includes/opengl/macosx-window-system.h @@ -13,6 +13,7 @@ #include #include #include +#include typedef int Bool; @@ -51,12 +52,13 @@ NSOpenGLPixelBuffer* createPBuffer(int renderTarget, int internalFormat, int wid Bool destroyPBuffer(NSOpenGLPixelBuffer* pBuffer); void setContextPBuffer(NSOpenGLContext* ctx, NSOpenGLPixelBuffer* pBuffer); void setContextTextureImageToPBuffer(NSOpenGLContext* ctx, NSOpenGLPixelBuffer* pBuffer, GLenum colorBuffer); +Bool isNSOpenGLPixelBuffer(uint64_t object); -// NSOpenGLLayer* createNSOpenGLLayer(NSOpenGLContext* ctx, NSOpenGLPixelFormat* fmt, NSView* view, Bool opaque); -NSOpenGLLayer* createNSOpenGLLayer(NSOpenGLContext* ctx, NSOpenGLPixelFormat* fmt, NSOpenGLPixelBuffer* pbuffer, Bool opaque, int texWidth, int texHeight); +NSOpenGLLayer* createNSOpenGLLayer(NSOpenGLContext* ctx, NSOpenGLPixelFormat* fmt, NSOpenGLPixelBuffer* p, uint32_t texID, Bool opaque, int texWidth, int texHeight); void setNSOpenGLLayerSwapInterval(NSOpenGLLayer* layer, int interval); void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_micros); -void setNSOpenGLLayerNeedsDisplay(NSOpenGLLayer* glLayer); +void flushNSOpenGLLayerPBuffer(NSOpenGLLayer* layer); +void setNSOpenGLLayerNeedsDisplay(NSOpenGLLayer* layer, NSOpenGLPixelBuffer* p, uint32_t texID, int texWidth, int texHeight); void releaseNSOpenGLLayer(NSOpenGLLayer *glLayer); void* getProcAddress(const char *procName); @@ -67,6 +69,3 @@ void setSwapInterval(NSOpenGLContext* ctx, int interval); Bool setGammaRamp(int tableSize, float* redRamp, float* greenRamp, float* blueRamp); void resetGammaRamp(); -/* returns the screen refresh rate in Hz */ -int getScreenRefreshRate(int scrn_idx); - diff --git a/src/jogl/classes/com/jogamp/opengl/FBObject.java b/src/jogl/classes/com/jogamp/opengl/FBObject.java index 8a6495e6b..cc0af29a9 100644 --- a/src/jogl/classes/com/jogamp/opengl/FBObject.java +++ b/src/jogl/classes/com/jogamp/opengl/FBObject.java @@ -35,6 +35,7 @@ import javax.media.opengl.GL; import javax.media.opengl.GL2GL3; import javax.media.opengl.GL3; import javax.media.opengl.GLBase; +import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLContext; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; @@ -61,55 +62,33 @@ public class FBObject { protected static final boolean DEBUG = Debug.debug("FBObject"); private static final boolean forceMinimumFBOSupport = Debug.isPropertyDefined("jogl.fbo.force.min", true); + private static enum DetachAction { NONE, DISPOSE, RECREATE }; + /** - * Returns true if basic FBO support is available, otherwise false. - *

      - * Basic FBO is supported if the context is either GL-ES >= 2.0, GL >= core 3.0 or implements the extensions - * ARB_ES2_compatibility, ARB_framebuffer_object, EXT_framebuffer_object or OES_framebuffer_object. - *

      - *

      - * Basic FBO support may only include one color attachment and no multisampling, - * as well as limited internal formats for renderbuffer. - *

      - * @see GLContext#hasFBO() - */ - public static final boolean supportsBasicFBO(GL gl) { - return gl.getContext().hasFBO(); - } - - /** - * Returns true if full FBO support is available, otherwise false. - *

      - * Full FBO is supported if the context is either GL >= core 3.0 or implements the extensions - * ARB_framebuffer_object, or all of - * EXT_framebuffer_object, EXT_framebuffer_multisample, - * EXT_framebuffer_blit, GL_EXT_packed_depth_stencil. - *

      - *

      - * Full FBO support includes multiple color attachments and multisampling. - *

      + * Marker interface, denotes a color buffer attachment. + *

      Always an instance of {@link Attachment}.

      + *

      Either an instance of {@link ColorAttachment} or {@link TextureAttachment}. */ - public static final boolean supportsFullFBO(GL gl) { - return !forceMinimumFBOSupport && - ( gl.isGL3() || // GL >= 3.0 - gl.isExtensionAvailable(GLExtensions.ARB_framebuffer_object) || // ARB_framebuffer_object - - ( gl.isExtensionAvailable(GLExtensions.EXT_framebuffer_object) && // All EXT_framebuffer_object* - gl.isExtensionAvailable(GLExtensions.EXT_framebuffer_multisample) && - gl.isExtensionAvailable(GLExtensions.EXT_framebuffer_blit) && - gl.isExtensionAvailable(GLExtensions.EXT_packed_depth_stencil) - ) - ) ; - } - - public static final int getMaxSamples(GL gl) { - if( supportsFullFBO(gl) ) { - int[] val = new int[] { 0 } ; - gl.glGetIntegerv(GL2GL3.GL_MAX_SAMPLES, val, 0); - return val[0]; - } else { - return 0; - } + public static interface Colorbuffer { + /** + * Initializes the color buffer and set it's parameter, if uninitialized, i.e. name is zero. + * @return true if newly initialized, otherwise false. + * @throws GLException if buffer generation or setup fails. The just created buffer name will be deleted in this case. + */ + public boolean initialize(GL gl) throws GLException; + + /** + * Releases the color buffer if initialized, i.e. name is not zero. + * @throws GLException if buffer release fails. + */ + public void free(GL gl) throws GLException; + + /** + * Writes the internal format to the given GLCapabilities object. + * @param caps the destination for format bits + * @param rgba8Avail whether rgba8 is available + */ + public void formatToGLCapabilities(GLCapabilities caps, boolean rgba8Avail); } /** Common super class of all attachments */ @@ -155,21 +134,89 @@ public class FBObject { private int name; - /** true if resource is initialized by {@link #initialize(GL)}, hence {@link #free(GL)} is allowed to free the GL resources. */ - protected boolean resourceOwner; - - private int initCounter; - protected Attachment(Type type, int iFormat, int width, int height, int name) { this.type = type; this.format = iFormat; this.width = width; this.height = height; this.name = name; - this.resourceOwner = false; - this.initCounter = 0; } + /** + * Writes the internal format to the given GLCapabilities object. + * @param caps the destination for format bits + * @param rgba8Avail whether rgba8 is available + */ + public final void formatToGLCapabilities(GLCapabilities caps, boolean rgba8Avail) { + final int _format; + switch(format) { + case GL.GL_RGBA: + _format = rgba8Avail ? GL.GL_RGBA8 : GL.GL_RGBA4; + break; + case GL.GL_RGB: + _format = rgba8Avail ? GL.GL_RGB8 : GL.GL_RGB565; + break; + default: + _format = format; + } + switch(_format) { + case GL.GL_RGBA4: + caps.setRedBits(4); + caps.setGreenBits(4); + caps.setBlueBits(4); + caps.setAlphaBits(4); + break; + case GL.GL_RGB5_A1: + caps.setRedBits(5); + caps.setGreenBits(5); + caps.setBlueBits(5); + caps.setAlphaBits(1); + break; + case GL.GL_RGB565: + caps.setRedBits(5); + caps.setGreenBits(6); + caps.setBlueBits(5); + caps.setAlphaBits(0); + break; + case GL.GL_RGB8: + caps.setRedBits(8); + caps.setGreenBits(8); + caps.setBlueBits(8); + caps.setAlphaBits(0); + break; + case GL.GL_RGBA8: + caps.setRedBits(8); + caps.setGreenBits(8); + caps.setBlueBits(8); + caps.setAlphaBits(8); + break; + case GL.GL_DEPTH_COMPONENT16: + caps.setDepthBits(16); + break; + case GL.GL_DEPTH_COMPONENT24: + caps.setDepthBits(24); + break; + case GL.GL_DEPTH_COMPONENT32: + caps.setDepthBits(32); + break; + case GL.GL_STENCIL_INDEX1: + caps.setStencilBits(1); + break; + case GL.GL_STENCIL_INDEX4: + caps.setStencilBits(4); + break; + case GL.GL_STENCIL_INDEX8: + caps.setStencilBits(8); + break; + case GL.GL_DEPTH24_STENCIL8: + caps.setDepthBits(24); + caps.setStencilBits(8); + break; + default: + throw new IllegalArgumentException("format invalid: 0x"+Integer.toHexString(format)); + } + } + /** width of attachment */ public final int getWidth() { return width; } /** height of attachment */ @@ -180,45 +227,31 @@ public class FBObject { public final int getName() { return name; } /* pp */ final void setName(int n) { name = n; } - public final int getInitCounter() { return initCounter; } - /** - * Initializes the attachment buffer and set it's parameter, if uninitialized, i.e. name is zero. - *

      Implementation employs an initialization counter, hence it can be paired recursively with {@link #free(GL)}.

      - * @throws GLException if buffer generation or setup fails. The just created buffer name will be deleted in this case. - */ - public void initialize(GL gl) throws GLException { - initCounter++; - /* - super.initialize(gl); - if(1 == getInitCounter() && 0 == getName() ) { + * Initializes the attachment and set it's parameter, if uninitialized, i.e. name is zero. + *
      +            final boolean init = 0 == name;
      +            if( init ) {
                       do init ..
      -                freeResources = true; // if all OK
                   }
      -            */
      -        }
      +            return init;
      +         * 
      + * @return true if newly initialized, otherwise false. + * @throws GLException if buffer generation or setup fails. The just created buffer name will be deleted in this case. + */ + public abstract boolean initialize(GL gl) throws GLException; /** - * Releases the attachment buffer if initialized, i.e. name is zero. - *

      Implementation employs an initialization counter, hence it can be paired recursively with {@link #initialize(GL)}.

      - * @throws GLException if buffer release fails. - */ - public void free(GL gl) throws GLException { - /* - if(1 == getInitCounter() && freeResources && .. ) { + * Releases the attachment if initialized, i.e. name is not zero. + *
      +            if(0 != name) {
                       do free ..
      -            }
      -            super.free(gl);
      -            */
      -            initCounter--;
      -            if(0 == initCounter) {
      -                resourceOwner = false;
                       name = 0;
                   }
      -            if(DEBUG) {
      -                System.err.println("Attachment.free: "+this);
      -            }
      -        }
      +         * 
      + * @throws GLException if buffer release fails. + */ + public abstract void free(GL gl) throws GLException; /** *

      @@ -232,9 +265,9 @@ public class FBObject { if( ! ( o instanceof Attachment ) ) return false; final Attachment a = (Attachment)o; return type == a.type && - format == a.format || - width == a.width || - height== a.height || + format == a.format && + width == a.width && + height== a.height && name == a.name ; } @@ -259,8 +292,7 @@ public class FBObject { public String toString() { return getClass().getSimpleName()+"[type "+type+", format 0x"+Integer.toHexString(format)+", "+width+"x"+height+ - ", name 0x"+Integer.toHexString(name)+", obj 0x"+Integer.toHexString(objectHashCode())+ - ", resOwner "+resourceOwner+", initCount "+initCounter+"]"; + ", name 0x"+Integer.toHexString(name)+", obj 0x"+Integer.toHexString(objectHashCode())+"]"; } public static Type getType(int attachmentPoint, int maxColorAttachments) { @@ -277,7 +309,7 @@ public class FBObject { } } } - + /** Other renderbuffer attachment which maybe a colorbuffer, depth or stencil. */ public static class RenderAttachment extends Attachment { private int samples; @@ -339,14 +371,13 @@ public class FBObject { } @Override - public void initialize(GL gl) throws GLException { - super.initialize(gl); - if( 1 == getInitCounter() && 0 == getName() ) { + public boolean initialize(GL gl) throws GLException { + final boolean init = 0 == getName(); + if( init ) { + int glerr = checkPreGLError(gl); + final int[] name = new int[] { -1 }; gl.glGenRenderbuffers(1, name, 0); - if( 0 == name[0] ) { - throw new GLException("null renderbuffer, "+this); - } setName(name[0]); gl.glBindRenderbuffer(GL.GL_RENDERBUFFER, getName()); @@ -355,43 +386,37 @@ public class FBObject { } else { gl.glRenderbufferStorage(GL.GL_RENDERBUFFER, format, getWidth(), getHeight()); } - int glerr = gl.glGetError(); + glerr = gl.glGetError(); if(GL.GL_NO_ERROR != glerr) { gl.glDeleteRenderbuffers(1, name, 0); setName(0); throw new GLException("GL Error 0x"+Integer.toHexString(glerr)+" while creating "+this); } - resourceOwner = true; if(DEBUG) { System.err.println("Attachment.init: "+this); } } + return init; } @Override public void free(GL gl) { - if(1 == getInitCounter() && resourceOwner && 0 != getName() ) { - final int[] name = new int[] { getName() }; + final int[] name = new int[] { getName() }; + if( 0 != name[0] ) { gl.glDeleteRenderbuffers(1, name, 0); + setName(0); + if(DEBUG) { + System.err.println("Attachment.free: "+this); + } } - super.free(gl); } public String toString() { return getClass().getSimpleName()+"[type "+type+", format 0x"+Integer.toHexString(format)+", samples "+samples+", "+getWidth()+"x"+getHeight()+ - ", name 0x"+Integer.toHexString(getName())+", obj 0x"+Integer.toHexString(objectHashCode())+ - ", resOwner "+resourceOwner+", initCount "+getInitCounter()+"]"; + ", name 0x"+Integer.toHexString(getName())+", obj 0x"+Integer.toHexString(objectHashCode())+"]"; } } - /** - * Marker interface, denotes a color buffer attachment. - *

      Always an instance of {@link Attachment}.

      - *

      Either an instance of {@link ColorAttachment} or {@link TextureAttachment}. - */ - public static interface Colorbuffer { - } - /** Color render buffer attachment */ public static class ColorAttachment extends RenderAttachment implements Colorbuffer { public ColorAttachment(int iFormat, int samples, int width, int height, int name) { @@ -444,9 +469,11 @@ public class FBObject { * @throws GLException if texture generation and setup fails. The just created texture name will be deleted in this case. */ @Override - public void initialize(GL gl) throws GLException { - super.initialize(gl); - if( 1 == getInitCounter() && 0 == getName() ) { + public boolean initialize(GL gl) throws GLException { + final boolean init = 0 == getName(); + if( init ) { + int glerr = checkPreGLError(gl); + final int[] name = new int[] { -1 }; gl.glGenTextures(1, name, 0); if(0 == name[0]) { @@ -468,31 +495,111 @@ public class FBObject { if( 0 < wrapT ) { gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, wrapT); } - int glerr = gl.glGetError(); + glerr = gl.glGetError(); if(GL.GL_NO_ERROR != glerr) { gl.glDeleteTextures(1, name, 0); setName(0); throw new GLException("GL Error 0x"+Integer.toHexString(glerr)+" while creating "+this); } - resourceOwner = true; - } - if(DEBUG) { - System.err.println("Attachment.init: "+this); + if(DEBUG) { + System.err.println("Attachment.init: "+this); + } } + return init; } @Override public void free(GL gl) { - if(1 == getInitCounter() && resourceOwner && 0 != getName() ) { - final int[] name = new int[] { getName() }; + final int[] name = new int[] { getName() }; + if( 0 != name[0] ) { gl.glDeleteTextures(1, name, 0); + setName(0); + if(DEBUG) { + System.err.println("Attachment.free: "+this); + } } - super.free(gl); + } + } + + /** + * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE}, + * selecting the texture data type and format automatically. + * + *

      Using default min/mag filter {@link GL#GL_NEAREST} and default wrapS/wrapT {@link GL#GL_CLAMP_TO_EDGE}.

      + * + * @param glp the chosen {@link GLProfile} + * @param alpha set to true if you request alpha channel, otherwise false; + * @param width texture width + * @param height texture height + * @return the created and uninitialized color {@link TextureAttachment} + */ + public static final TextureAttachment createColorTextureAttachment(GLProfile glp, boolean alpha, int width, int height) { + return createColorTextureAttachment(glp, alpha, width, height, GL.GL_NEAREST, GL.GL_NEAREST, GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE); + } + + /** + * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE}, + * selecting the texture data type and format automatically. + * + * @param glp the chosen {@link GLProfile} + * @param alpha set to true if you request alpha channel, otherwise false; + * @param width texture width + * @param height texture height + * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER} + * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} + * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S} + * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} + * @return the created and uninitialized color {@link TextureAttachment} + */ + public static final TextureAttachment createColorTextureAttachment(GLProfile glp, boolean alpha, int width, int height, + int magFilter, int minFilter, int wrapS, int wrapT) { + final int textureInternalFormat, textureDataFormat, textureDataType; + if(glp.isGLES()) { + textureInternalFormat = alpha ? GL.GL_RGBA : GL.GL_RGB; + textureDataFormat = alpha ? GL.GL_RGBA : GL.GL_RGB; + textureDataType = GL.GL_UNSIGNED_BYTE; + } else { + textureInternalFormat = alpha ? GL.GL_RGBA8 : GL.GL_RGB8; + textureDataFormat = alpha ? GL.GL_BGRA : GL.GL_RGB; + textureDataType = alpha ? GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV : GL.GL_UNSIGNED_BYTE; + } + return createColorTextureAttachment(textureInternalFormat, width, height, textureDataFormat, textureDataType, magFilter, minFilter, wrapS, wrapT); + } + + /** + * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE}. + * + * @param internalFormat internalFormat parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} + * @param width texture width + * @param height texture height + * @param dataFormat format parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} + * @param dataType type parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} + * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER} + * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} + * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S} + * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} + * @return the created and uninitialized color {@link TextureAttachment} + */ + public static final TextureAttachment createColorTextureAttachment(int internalFormat, int width, int height, int dataFormat, int dataType, + int magFilter, int minFilter, int wrapS, int wrapT) { + return new TextureAttachment(Type.COLOR_TEXTURE, internalFormat, width, height, dataFormat, dataType, + magFilter, minFilter, wrapS, wrapT, 0 /* name */); + } + + private static boolean hasAlpha(int format) { + switch(format) { + case GL.GL_RGBA8: + case GL.GL_RGBA4: + case GL.GL_RGBA: + case GL.GL_BGRA: + case 4: + return true; + default: + return false; } } private boolean initialized; - private boolean basicFBOSupport; private boolean fullFBOSupport; private boolean rgba8Avail; private boolean depth24Avail; @@ -523,6 +630,9 @@ public class FBObject { // private final void validateColorAttachmentPointRange(int point) { + if(!initialized) { + throw new GLException("FBO not initialized"); + } if(maxColorAttachments != colorAttachmentPoints.length) { throw new InternalError("maxColorAttachments "+maxColorAttachments+", array.lenght "+colorAttachmentPoints); } @@ -621,7 +731,6 @@ public class FBObject { this.initialized = false; // TBD @ init - this.basicFBOSupport = false; this.fullFBOSupport = false; this.rgba8Avail = false; this.depth24Avail = false; @@ -657,14 +766,11 @@ public class FBObject { private void init(GL gl, int width, int height, int samples) throws GLException { if(initialized) { throw new GLException("FBO already initialized"); - } - fullFBOSupport = supportsFullFBO(gl); - - if( !fullFBOSupport && !supportsBasicFBO(gl) ) { + } + if( !gl.hasBasicFBOSupport() ) { throw new GLException("FBO not supported w/ context: "+gl.getContext()+", "+this); } - - basicFBOSupport = true; + fullFBOSupport = gl.hasFullFBOSupport(); rgba8Avail = gl.isGL2GL3() || gl.isExtensionAvailable(GLExtensions.OES_rgb8_rgba8); depth24Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_depth24); @@ -680,10 +786,7 @@ public class FBObject { int val[] = new int[1]; - int glerr = gl.glGetError(); - if(DEBUG && GL.GL_NO_ERROR != glerr) { - System.err.println("FBObject.init-preexisting.0 GL Error 0x"+Integer.toHexString(glerr)); - } + int glerr = checkPreGLError(gl); int realMaxColorAttachments = 1; maxColorAttachments = 1; @@ -703,16 +806,7 @@ public class FBObject { colorAttachmentPoints = new Colorbuffer[maxColorAttachments]; colorAttachmentCount = 0; - maxSamples = 0; - if(fullFBOSupport) { - gl.glGetIntegerv(GL2GL3.GL_MAX_SAMPLES, val, 0); - glerr = gl.glGetError(); - if(GL.GL_NO_ERROR == glerr) { - maxSamples = val[0]; - } else if(DEBUG) { - System.err.println("FBObject.init-GL_MAX_SAMPLES query GL Error 0x"+Integer.toHexString(glerr)); - } - } + maxSamples = gl.getMaxRenderbufferSamples(); if(!forceMinimumFBOSupport) { gl.glGetIntegerv(GL.GL_MAX_TEXTURE_SIZE, val, 0); maxTextureSize = val[0]; @@ -733,10 +827,9 @@ public class FBObject { this.samples = samples <= maxSamples ? samples : maxSamples; if(DEBUG) { - System.err.println("FBObject "+width+"x"+height+", "+samples+" -> "+samples+" samples"); - System.err.println("basicFBOSupport: "+basicFBOSupport); + System.err.println("FBObject "+width+"x"+height+", "+samples+" -> "+this.samples+" samples"); System.err.println("fullFBOSupport: "+fullFBOSupport); - System.err.println("maxColorAttachments: "+maxColorAttachments+"/"+realMaxColorAttachments); + System.err.println("maxColorAttachments: "+maxColorAttachments+"/"+realMaxColorAttachments+" [capped/real]"); System.err.println("maxSamples: "+maxSamples); System.err.println("maxTextureSize: "+maxTextureSize); System.err.println("maxRenderbufferSize: "+maxRenderbufferSize); @@ -761,12 +854,8 @@ public class FBObject { throw new GLException("size "+width+"x"+height+" exceeds on of the maxima [texture "+maxTextureSize+", renderbuffer "+maxRenderbufferSize+"]"); } - if(null != samplesSink) { - // init sampling sink - samplesSink.reset(gl, width, height); - resetMSAATexture2DSink(gl); - } - + resetMSAATexture2DSink(gl); + // generate fbo .. gl.glGenFramebuffers(1, val, 0); fbName = val[0]; @@ -780,7 +869,8 @@ public class FBObject { if(!gl.glIsFramebuffer(fbName)) { checkNoError(gl, GL.GL_INVALID_VALUE, "FBObject Init.isFB"); // throws GLException } - bound = true; + bound = true; + samplesSinkDirty = true; initialized = true; updateStatus(gl); @@ -797,7 +887,7 @@ public class FBObject { * to match the new given parameters. *

      *

      - * Currently incompatibility and hence recreation is given if + * Incompatibility and hence recreation is forced if * the size or sample count doesn't match for subsequent calls. *

      * @@ -820,17 +910,17 @@ public class FBObject { * to match the new given parameters. *

      *

      - * Currently incompatibility and hence recreation is given if - * the size or sample count doesn't match for subsequent calls. + * Currently incompatibility and hence recreation of the attachments will be performed + * if the size or sample count doesn't match for subsequent calls. *

      * *

      Leaves the FBO bound state untouched

      * * @param gl the current GL context - * @param newWidth - * @param newHeight + * @param newWidth the new width, it's minimum is capped to 1 + * @param newHeight the new height, it's minimum is capped to 1 * @param newSamples if > 0, MSAA will be used, otherwise no multisampling. Will be capped to {@link #getMaxSamples()}. - * @throws GLException in case of an error + * @throws GLException in case of an error, i.e. size too big, etc .. */ public final void reset(GL gl, int newWidth, int newHeight, int newSamples) { if(!initialized) { @@ -841,13 +931,15 @@ public class FBObject { newSamples = newSamples <= maxSamples ? newSamples : maxSamples; // clamp if( newWidth != width || newHeight != height || newSamples != samples ) { + if(0>=newWidth) { newWidth = 1; } + if(0>=newHeight) { newHeight = 1; } if(newWidth > 2 + maxTextureSize || newHeight> 2 + maxTextureSize || newWidth > maxRenderbufferSize || newHeight> maxRenderbufferSize ) { throw new GLException("size "+width+"x"+height+" exceeds on of the maxima [texture "+maxTextureSize+", renderbuffer "+maxRenderbufferSize+"]"); } if(DEBUG) { - System.err.println("FBObject.reset - START - "+this); + System.err.println("FBObject.reset - START - "+width+"x"+height+", "+samples+" -> "+newWidth+"x"+newHeight+", "+newSamples+"; "+this); } final boolean wasBound = isBound(); @@ -856,11 +948,18 @@ public class FBObject { height = newHeight; samples = newSamples; detachAllImpl(gl, true , true); - resetMSAATexture2DSink(gl); - if(wasBound) { - bind(gl); - } else { + /** + * Postpone reset of samplesSink until syncFramebuffer, + * issued at use(..) method (swapBuffer usually initiates it). + * This allows another thread to still use the 'samplesSinkTexture' + * until swapBuffer happens and does not invalidate the GL_FRONT + * FBO (framebuffer & texture). + resetMSAATexture2DSink(gl); + */ + samplesSinkDirty = true; + + if(!wasBound) { unbind(gl); } @@ -870,6 +969,28 @@ public class FBObject { } } + /** + * Writes the internal format of the attachments to the given GLCapabilities object. + * @param caps the destination for format bits + */ + public final void formatToGLCapabilities(GLCapabilities caps) { + caps.setSampleBuffers(samples > 0); + caps.setNumSamples(samples); + caps.setDepthBits(0); + caps.setStencilBits(0); + + final Colorbuffer cb = samples > 0 ? getSamplingSink() : getColorbuffer(0); + if(null != cb) { + cb.formatToGLCapabilities(caps, rgba8Avail); + } + if(null != depth) { + depth.formatToGLCapabilities(caps, rgba8Avail); + } + if(null != stencil && stencil != depth) { + stencil.formatToGLCapabilities(caps, rgba8Avail); + } + } + /** * Note that the status may reflect an incomplete state during transition of attachments. * @return The FB status. {@link GL.GL_FRAMEBUFFER_COMPLETE} if ok, otherwise return GL FBO error state or -1 @@ -954,6 +1075,15 @@ public class FBObject { } } + private static int checkPreGLError(GL gl) { + int glerr = gl.glGetError(); + if(DEBUG && GL.GL_NO_ERROR != glerr) { + System.err.println("Pre-existing GL error: 0x"+Integer.toHexString(glerr)); + Thread.dumpStack(); + } + return glerr; + } + private final boolean checkNoError(GL gl, int err, String exceptionMessage) throws GLException { if(GL.GL_NO_ERROR != err) { if(null != gl) { @@ -974,7 +1104,7 @@ public class FBObject { } /** - * Attaches a Texture2D Color Buffer to this FBO's instance at the given attachment point, + * Attaches a {@link Colorbuffer}, i.e. {@link TextureAttachment}, to this FBO's instance at the given attachment point, * selecting the texture data type and format automatically. * *

      Using default min/mag filter {@link GL#GL_NEAREST} and default wrapS/wrapT {@link GL#GL_CLAMP_TO_EDGE}.

      @@ -986,13 +1116,15 @@ public class FBObject { * @param alpha set to true if you request alpha channel, otherwise false; * @return TextureAttachment instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown * @throws GLException in case the texture colorbuffer couldn't be allocated or MSAA has been chosen + * @see #createColorTextureAttachment(GLProfile, boolean, int, int) */ public final TextureAttachment attachTexture2D(GL gl, int attachmentPoint, boolean alpha) throws GLException { - return attachTexture2D(gl, attachmentPoint, alpha, GL.GL_NEAREST, GL.GL_NEAREST, GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE); + return (TextureAttachment)attachColorbuffer(gl, attachmentPoint, + createColorTextureAttachment(gl.getGLProfile(), alpha, width, height)); } /** - * Attaches a Texture2D Color Buffer to this FBO's instance at the given attachment point, + * Attaches a {@link Colorbuffer}, i.e. {@link TextureAttachment}, to this FBO's instance at the given attachment point, * selecting the texture data type and format automatically. * *

      Leaves the FBO bound.

      @@ -1006,23 +1138,15 @@ public class FBObject { * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} * @return TextureAttachment instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown * @throws GLException in case the texture colorbuffer couldn't be allocated or MSAA has been chosen + * @see #createColorTextureAttachment(GLProfile, boolean, int, int, int, int, int, int) */ public final TextureAttachment attachTexture2D(GL gl, int attachmentPoint, boolean alpha, int magFilter, int minFilter, int wrapS, int wrapT) throws GLException { - final int textureInternalFormat, textureDataFormat, textureDataType; - if(gl.isGLES()) { - textureInternalFormat = alpha ? GL.GL_RGBA : GL.GL_RGB; - textureDataFormat = alpha ? GL.GL_RGBA : GL.GL_RGB; - textureDataType = GL.GL_UNSIGNED_BYTE; - } else { - textureInternalFormat = alpha ? GL.GL_RGBA8 : GL.GL_RGB8; - textureDataFormat = alpha ? GL.GL_BGRA : GL.GL_RGB; - textureDataType = alpha ? GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV : GL.GL_UNSIGNED_BYTE; - } - return attachTexture2D(gl, attachmentPoint, textureInternalFormat, textureDataFormat, textureDataType, magFilter, minFilter, wrapS, wrapT); + return (TextureAttachment)attachColorbuffer(gl, attachmentPoint, + createColorTextureAttachment(gl.getGLProfile(), alpha, width, height, magFilter, minFilter, wrapS, wrapT)); } /** - * Attaches a Texture2D Color Buffer to this FBO's instance at the given attachment point. + * Attaches a {@link Colorbuffer}, i.e. {@link TextureAttachment}, to this FBO's instance at the given attachment point. * *

      Leaves the FBO bound.

      * @@ -1037,66 +1161,33 @@ public class FBObject { * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} * @return TextureAttachment instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown * @throws GLException in case the texture colorbuffer couldn't be allocated or MSAA has been chosen + * @see #createColorTextureAttachment(int, int, int, int, int, int, int, int, int) */ public final TextureAttachment attachTexture2D(GL gl, int attachmentPoint, int internalFormat, int dataFormat, int dataType, int magFilter, int minFilter, int wrapS, int wrapT) throws GLException { - return attachTexture2D(gl, attachmentPoint, - new TextureAttachment(Type.COLOR_TEXTURE, internalFormat, width, height, dataFormat, dataType, - magFilter, minFilter, wrapS, wrapT, 0 /* name */)); + return (TextureAttachment)attachColorbuffer(gl, attachmentPoint, + createColorTextureAttachment(internalFormat, width, height, dataFormat, dataType, magFilter, minFilter, wrapS, wrapT)); } /** - * Attaches a Texture2D Color Buffer to this FBO's instance at the given attachment point. + * Creates a {@link ColorAttachment}, selecting the format automatically. * - *

      - * In case the passed TextureAttachment texA is uninitialized, i.e. it's texture name is zero, - * a new texture name is generated and setup w/ the texture parameter.
      - * Otherwise, i.e. texture name is not zero, the passed TextureAttachment texA is - * considered complete and assumed matching this FBO requirement. A GL error may occur is the latter is untrue. - *

      - * - *

      Leaves the FBO bound.

      - * - * @param gl the current GL context - * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] - * @param texA the to be attached {@link TextureAttachment}. Maybe complete or uninitialized, see above. - * @return the passed TextureAttachment texA instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown - * @throws GLException in case the texture colorbuffer couldn't be allocated or MSAA has been chosen + * @param alpha set to true if you request alpha channel, otherwise false; + * @return uninitialized ColorAttachment instance describing the new attached colorbuffer */ - public final TextureAttachment attachTexture2D(GL gl, int attachmentPoint, TextureAttachment texA) throws GLException { - validateAddColorAttachment(attachmentPoint, texA); - - if(samples>0) { - removeColorAttachment(attachmentPoint, texA); - throw new GLException("Texture2D not supported w/ MSAA. If you have enabled MSAA with exisiting texture attachments, you may want to detach them via detachAllTexturebuffer(gl)."); - } - - texA.initialize(gl); - addColorAttachment(attachmentPoint, texA); - - bind(gl); - - // Set up the color buffer for use as a renderable texture: - gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, - GL.GL_COLOR_ATTACHMENT0 + attachmentPoint, - GL.GL_TEXTURE_2D, texA.getName(), 0); - - if(!ignoreStatus) { - updateStatus(gl); - if(!isStatusValid()) { - detachColorbuffer(gl, attachmentPoint); - throw new GLException("attachTexture2D "+texA+" at "+attachmentPoint+" failed "+getStatusString()+", "+this); - } - } - if(DEBUG) { - System.err.println("FBObject.attachTexture2D: "+this); + public final ColorAttachment createColorAttachment(boolean alpha) { + final int internalFormat; + if( rgba8Avail ) { + internalFormat = alpha ? GL.GL_RGBA8 : GL.GL_RGB8 ; + } else { + internalFormat = alpha ? GL.GL_RGBA4 : GL.GL_RGB565; } - return texA; + return new ColorAttachment(internalFormat, samples, width, height, 0); } - + /** - * Attaches a Color Buffer to this FBO's instance at the given attachment point, + * Attaches a {@link Colorbuffer}, i.e. {@link ColorAttachment}, to this FBO's instance at the given attachment point, * selecting the format automatically. * *

      Leaves the FBO bound.

      @@ -1106,19 +1197,14 @@ public class FBObject { * @param alpha set to true if you request alpha channel, otherwise false; * @return ColorAttachment instance describing the new attached colorbuffer if bound and configured successfully, otherwise GLException is thrown * @throws GLException in case the colorbuffer couldn't be allocated + * @see #createColorAttachment(boolean) */ public final ColorAttachment attachColorbuffer(GL gl, int attachmentPoint, boolean alpha) throws GLException { - final int internalFormat; - if( rgba8Avail ) { - internalFormat = alpha ? GL.GL_RGBA8 : GL.GL_RGB8 ; - } else { - internalFormat = alpha ? GL.GL_RGBA4 : GL.GL_RGB565; - } - return attachColorbuffer(gl, attachmentPoint, internalFormat); + return (ColorAttachment) attachColorbuffer(gl, attachmentPoint, createColorAttachment(alpha)); } /** - * Attaches a Color Buffer to this FBO's instance at the given attachment point. + * Attaches a {@link Colorbuffer}, i.e. {@link ColorAttachment}, to this FBO's instance at the given attachment point. * *

      Leaves the FBO bound.

      * @@ -1135,46 +1221,80 @@ public class FBObject { throw new IllegalArgumentException("colorformat invalid: 0x"+Integer.toHexString(internalFormat)+", "+this); } - return attachColorbuffer(gl, attachmentPoint, new ColorAttachment(internalFormat, samples, width, height, 0)); + return (ColorAttachment) attachColorbuffer(gl, attachmentPoint, new ColorAttachment(internalFormat, samples, width, height, 0)); } /** - * Attaches a Color Buffer to this FBO's instance at the given attachment point. + * Attaches a {@link Colorbuffer}, i.e. {@link ColorAttachment} or {@link TextureAttachment}, + * to this FBO's instance at the given attachment point. * + *

      + * If {@link Colorbuffer} is a {@link TextureAttachment} and is uninitialized, i.e. it's texture name is zero, + * a new texture name is generated and setup w/ the texture parameter.
      + * Otherwise, i.e. texture name is not zero, the passed TextureAttachment texA is + * considered complete and assumed matching this FBO requirement. A GL error may occur is the latter is untrue. + *

      + * *

      Leaves the FBO bound.

      * * @param gl * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] - * @param colA the template for the new {@link ColorAttachment} - * @return ColorAttachment instance describing the new attached colorbuffer if bound and configured successfully, otherwise GLException is thrown - * @throws GLException in case the colorbuffer couldn't be allocated + * @param colbuf the to be attached {@link Colorbuffer} + * @return newly attached {@link Colorbuffer} instance if bound and configured successfully, otherwise GLException is thrown + * @throws GLException in case the colorbuffer couldn't be allocated or MSAA has been chosen in case of a {@link TextureAttachment} */ - public final ColorAttachment attachColorbuffer(GL gl, int attachmentPoint, ColorAttachment colA) throws GLException { - validateAddColorAttachment(attachmentPoint, colA); - - colA.initialize(gl); - addColorAttachment(attachmentPoint, colA); + public final Colorbuffer attachColorbuffer(GL gl, int attachmentPoint, Colorbuffer colbuf) throws GLException { + validateAddColorAttachment(attachmentPoint, colbuf); - bind(gl); + final boolean initializedColorbuf = colbuf.initialize(gl); + addColorAttachment(attachmentPoint, colbuf); - // Attach the color buffer - gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, - GL.GL_COLOR_ATTACHMENT0 + attachmentPoint, - GL.GL_RENDERBUFFER, colA.getName()); + bind(gl); - if(!ignoreStatus) { - updateStatus(gl); - if(!isStatusValid()) { - detachColorbuffer(gl, attachmentPoint); - throw new GLException("attachColorbuffer "+colA+" at "+attachmentPoint+" failed "+getStatusString()+", "+this); + if(colbuf instanceof TextureAttachment) { + final TextureAttachment texA = (TextureAttachment) colbuf; + + if(samples>0) { + removeColorAttachment(attachmentPoint, texA); + if(initializedColorbuf) { + texA.free(gl); + } + throw new GLException("Texture2D not supported w/ MSAA. If you have enabled MSAA with exisiting texture attachments, you may want to detach them via detachAllTexturebuffer(gl)."); + } + + // Set up the color buffer for use as a renderable texture: + gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, + GL.GL_COLOR_ATTACHMENT0 + attachmentPoint, + GL.GL_TEXTURE_2D, texA.getName(), 0); + + if(!ignoreStatus) { + updateStatus(gl); + if(!isStatusValid()) { + detachColorbuffer(gl, attachmentPoint, true); + throw new GLException("attachTexture2D "+texA+" at "+attachmentPoint+" failed "+getStatusString()+", "+this); + } + } + } else if(colbuf instanceof ColorAttachment) { + final ColorAttachment colA = (ColorAttachment) colbuf; + + // Attach the color buffer + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, + GL.GL_COLOR_ATTACHMENT0 + attachmentPoint, + GL.GL_RENDERBUFFER, colA.getName()); + + if(!ignoreStatus) { + updateStatus(gl); + if(!isStatusValid()) { + detachColorbuffer(gl, attachmentPoint, true); + throw new GLException("attachColorbuffer "+colA+" at "+attachmentPoint+" failed "+getStatusString()+", "+this); + } } } if(DEBUG) { - System.err.println("FBObject.attachColorbuffer: "+this); + System.err.println("FBObject.attachColorbuffer: [attachmentPoint "+attachmentPoint+", colbuf "+colbuf+"]: "+this); } - return colA; + return colbuf; } - /** * Attaches one depth, stencil or packed-depth-stencil buffer to this FBO's instance, @@ -1355,33 +1475,39 @@ public class FBObject { if(!ignoreStatus) { updateStatus(gl); if( !isStatusValid() ) { - detachRenderbuffer(gl, atype); + detachRenderbuffer(gl, atype, true); throw new GLException("renderbuffer attachment failed: "+this.getStatusString()); } } if(DEBUG) { - System.err.println("FBObject.attachRenderbuffer: "+this); - } + System.err.println("FBObject.attachRenderbuffer: [attachmentType "+atype+"]: "+this); + } } /** + * Detaches a {@link Colorbuffer}, i.e. {@link ColorAttachment} or {@link TextureAttachment}. *

      Leaves the FBO bound!

      + * * @param gl - * @param ca + * @param attachmentPoint + * @param dispose true if the Colorbuffer shall be disposed + * @return the detached Colorbuffer * @throws IllegalArgumentException */ - public final void detachColorbuffer(GL gl, int attachmentPoint) throws IllegalArgumentException { - if(null == detachColorbufferImpl(gl, attachmentPoint, false)) { + public final Colorbuffer detachColorbuffer(GL gl, int attachmentPoint, boolean dispose) throws IllegalArgumentException { + final Colorbuffer res = detachColorbufferImpl(gl, attachmentPoint, dispose ? DetachAction.DISPOSE : DetachAction.NONE); + if(null == res) { throw new IllegalArgumentException("ColorAttachment at "+attachmentPoint+", not attached, "+this); } if(DEBUG) { - System.err.println("FBObject.detachColorbuffer: [attachmentPoint "+attachmentPoint+"]: "+this); + System.err.println("FBObject.detachColorbuffer: [attachmentPoint "+attachmentPoint+", dispose "+dispose+"]: "+res+", "+this); } + return res; } - private final Colorbuffer detachColorbufferImpl(GL gl, int attachmentPoint, boolean recreate) { - final Colorbuffer colbuf = colorAttachmentPoints[attachmentPoint]; // shortcut, don't validate here + private final Colorbuffer detachColorbufferImpl(GL gl, int attachmentPoint, DetachAction detachAction) { + Colorbuffer colbuf = colorAttachmentPoints[attachmentPoint]; // shortcut, don't validate here if(null == colbuf) { return null; @@ -1389,6 +1515,8 @@ public class FBObject { bind(gl); + removeColorAttachment(attachmentPoint, colbuf); + if(colbuf instanceof TextureAttachment) { final TextureAttachment texA = (TextureAttachment) colbuf; if( 0 != texA.getName() ) { @@ -1397,11 +1525,22 @@ public class FBObject { GL.GL_TEXTURE_2D, 0, 0); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); } - texA.free(gl); - removeColorAttachment(attachmentPoint, texA); - if(recreate) { - texA.setSize(width, height); - attachTexture2D(gl, attachmentPoint, texA); + switch(detachAction) { + case DISPOSE: + texA.free(gl); + break; + case RECREATE: + texA.free(gl); + if(samples == 0) { + // stay non MSAA + texA.setSize(width, height); + } else { + // switch to MSAA + colbuf = createColorAttachment(hasAlpha(texA.format)); + } + attachColorbuffer(gl, attachmentPoint, colbuf); + break; + default: } } else if(colbuf instanceof ColorAttachment) { final ColorAttachment colA = (ColorAttachment) colbuf; @@ -1410,12 +1549,30 @@ public class FBObject { GL.GL_COLOR_ATTACHMENT0+attachmentPoint, GL.GL_RENDERBUFFER, 0); } - colA.free(gl); - removeColorAttachment(attachmentPoint, colbuf); - if(recreate) { - colA.setSize(width, height); - colA.setSamples(samples); - attachColorbuffer(gl, attachmentPoint, colA); + switch(detachAction) { + case DISPOSE: + colA.free(gl); + break; + case RECREATE: + colA.free(gl); + if(samples > 0) { + // stay MSAA + colA.setSize(width, height); + colA.setSamples(samples); + } else { + // switch to non MSAA + if(null != samplesSinkTexture) { + colbuf = createColorTextureAttachment(samplesSinkTexture.format, width, height, + samplesSinkTexture.dataFormat, samplesSinkTexture.dataType, + samplesSinkTexture.magFilter, samplesSinkTexture.minFilter, + samplesSinkTexture.wrapS, samplesSinkTexture.wrapT); + } else { + colbuf = createColorTextureAttachment(gl.getGLProfile(), true, width, height); + } + } + attachColorbuffer(gl, attachmentPoint, colbuf); + break; + default: } } return colbuf; @@ -1424,10 +1581,14 @@ public class FBObject { /** * * @param gl + * @param dispose true if the Colorbuffer shall be disposed * @param reqAType {@link Type#DEPTH}, {@link Type#DEPTH} or {@link Type#DEPTH_STENCIL} */ - public final void detachRenderbuffer(GL gl, Attachment.Type atype) throws IllegalArgumentException { - detachRenderbufferImpl(gl, atype, false); + public final void detachRenderbuffer(GL gl, Attachment.Type atype, boolean dispose) throws IllegalArgumentException { + detachRenderbufferImpl(gl, atype, dispose ? DetachAction.DISPOSE : DetachAction.NONE); + if(DEBUG) { + System.err.println("FBObject.detachRenderbuffer: [attachmentType "+atype+", dispose "+dispose+"]: "+this); + } } public final boolean isDepthStencilPackedFormat() { @@ -1439,7 +1600,7 @@ public class FBObject { return res; } - private final void detachRenderbufferImpl(GL gl, Attachment.Type atype, boolean recreate) throws IllegalArgumentException { + private final void detachRenderbufferImpl(GL gl, Attachment.Type atype, DetachAction detachAction) throws IllegalArgumentException { switch ( atype ) { case DEPTH: case STENCIL: @@ -1485,8 +1646,14 @@ public class FBObject { if( 0 != depth.getName() ) { gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, 0); } - depth.free(gl); - if(!recreate) { + switch(detachAction) { + case DISPOSE: + case RECREATE: + depth.free(gl); + break; + default: + } + if(DetachAction.RECREATE != detachAction) { depth = null; } break; @@ -1495,8 +1662,14 @@ public class FBObject { if(0 != stencil.getName()) { gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, 0); } - stencil.free(gl); - if(!recreate) { + switch(detachAction) { + case DISPOSE: + case RECREATE: + stencil.free(gl); + break; + default: + } + if(DetachAction.RECREATE != detachAction) { stencil = null; } break; @@ -1506,9 +1679,15 @@ public class FBObject { gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, 0); gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, 0); } - depth.free(gl); - stencil.free(gl); - if(!recreate) { + switch(detachAction) { + case DISPOSE: + case RECREATE: + depth.free(gl); + stencil.free(gl); + break; + default: + } + if(DetachAction.RECREATE != detachAction) { depth = null; stencil = null; } @@ -1516,14 +1695,15 @@ public class FBObject { default: throw new InternalError("XXX"); } - if(recreate) { + if(DetachAction.RECREATE == detachAction) { attachRenderbufferImpl2(gl, action, format); } } } /** - * Detaches all {@link ColorAttachment}s, {@link TextureAttachment}s and {@link RenderAttachment}s. + * Detaches all {@link ColorAttachment}s, {@link TextureAttachment}s and {@link RenderAttachment}s + * and disposes them. *

      Leaves the FBO bound!

      *

      * An attached sampling sink texture will be detached as well, see {@link #getSamplingSink()}. @@ -1538,7 +1718,8 @@ public class FBObject { } /** - * Detaches all {@link ColorAttachment}s and {@link TextureAttachment}s. + * Detaches all {@link ColorAttachment}s and {@link TextureAttachment}s + * and disposes them. *

      Leaves the FBO bound!

      *

      * An attached sampling sink texture will be detached as well, see {@link #getSamplingSink()}. @@ -1553,7 +1734,7 @@ public class FBObject { } /** - * Detaches all {@link TextureAttachment}s + * Detaches all {@link TextureAttachment}s and disposes them. *

      Leaves the FBO bound!

      *

      * An attached sampling sink texture will be detached as well, see {@link #getSamplingSink()}. @@ -1566,30 +1747,33 @@ public class FBObject { } for(int i=0; i reset try { for(int i=0; i0 ) { throw new InternalError("Non zero ColorAttachments "+this); } if(detachNonColorbuffer) { - detachRenderbufferImpl(gl, Attachment.Type.DEPTH_STENCIL, recreate); + detachRenderbufferImpl(gl, Attachment.Type.DEPTH_STENCIL, recreate ? DetachAction.RECREATE : DetachAction.DISPOSE); } if(ignoreStatus) { // post validate updateStatus(gl); @@ -1651,14 +1835,22 @@ public class FBObject { } private final void resetMSAATexture2DSink(GL gl) throws GLException { + if(null == samplesSink ) { + return; // this is the sample sink! + } if(0 == samples) { // MSAA off - if(null != samplesSink) { + if(samplesSink.initialized) { + // cleanup samplesSink.detachAll(gl); } return; } + if(!samplesSink.initialized) { + samplesSink.init(gl, width, height, 0); + } + boolean sampleSinkSizeMismatch = sampleSinkSizeMismatch(); boolean sampleSinkTexMismatch = sampleSinkTexMismatch(); boolean sampleSinkDepthStencilMismatch = sampleSinkDepthStencilMismatch(); @@ -1692,7 +1884,7 @@ public class FBObject { samplesSinkTexture = samplesSink.attachTexture2D(gl, 0, true); } else if( 0 == samplesSinkTexture.getName() ) { samplesSinkTexture.setSize(width, height); - samplesSink.attachTexture2D(gl, 0, samplesSinkTexture); + samplesSink.attachColorbuffer(gl, 0, samplesSinkTexture); } if( sampleSinkDepthStencilMismatch ) { @@ -1768,6 +1960,17 @@ public class FBObject { bound = false; } } + + /** + * Method simply marks this FBO unbound w/o interfering w/ the bound framebuffer as perfomed by {@link #unbind(GL)}. + *

      + * Only use this method if a subsequent {@link #unbind(GL)}, {@link #use(GL, TextureAttachment)} or {@link #bind(GL)} + * follows on any FBO. + *

      + */ + public final void markUnbound() { + bound = false; + } /** * Returns true if framebuffer object is bound via {@link #bind(GL)}, otherwise false. @@ -1785,49 +1988,54 @@ public class FBObject { public final boolean isBound() { return bound; } /** - * Samples the multisampling colorbuffer (msaa-buffer) to it's sink {@link #getSamplingSink()}. - * - *

      The operation is skipped, if no multisampling is used or - * the msaa-buffer has not been flagged dirty by a previous call of {@link #bind(GL)}, - * see {@link #isSamplingBufferDirty()}

      - * - *

      If full FBO is supported, sets the read and write framebuffer individually to default after sampling, hence not disturbing - * an optional operating MSAA FBO, see {@link GLBase#getDefaultReadFramebuffer()} and {@link GLBase#getDefaultDrawFramebuffer()}

      - * - *

      In case you intend to employ {@link GL#glReadPixels(int, int, int, int, int, int, java.nio.Buffer) glReadPixels(..)} + * If multisampling is being used and flagged dirty by a previous call of {@link #bind(GL)} or after initialization, + * the msaa-buffers are sampled to it's sink {@link #getSamplingSink()}. + *

      + * Method also updates the sampling sink configuration (if used). Hence it is recommended to call this + * method after your have initialized the FBO and attached renderbuffer etc for the 1st time. + * Method is called automatically by {@link #use(GL, TextureAttachment)}. + *

      + *

      + * Methos always resets the framebuffer binding to default in the end. + * If full FBO is supported, sets the read and write framebuffer individually to default after sampling, hence not disturbing + * an optional operating MSAA FBO, see {@link GLBase#getDefaultReadFramebuffer()} and {@link GLBase#getDefaultDrawFramebuffer()} + *

      + *

      + * In case you use this FBO w/o the {@link GLFBODrawable} and intend to employ {@link GL#glReadPixels(int, int, int, int, int, int, java.nio.Buffer) glReadPixels(..)} * you may want to call {@link GL#glBindFramebuffer(int, int) glBindFramebuffer}({@link GL2GL3#GL_READ_FRAMEBUFFER}, {@link #getReadFramebuffer()}); *

      - * *

      Leaves the FBO unbound.

      * * @param gl the current GL context * @param ta {@link TextureAttachment} to use, prev. attached w/ {@link #attachTexture2D(GL, int, boolean, int, int, int, int) attachTexture2D(..)} * @throws IllegalArgumentException */ - public final void syncSamplingBuffer(GL gl) { - unbind(gl); + public final void syncFramebuffer(GL gl) { + markUnbound(); if(samples>0 && samplesSinkDirty) { samplesSinkDirty = false; resetMSAATexture2DSink(gl); gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, fbName); gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, samplesSink.getWriteFramebuffer()); - ((GL2GL3)gl).glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, // since MSAA is supported, ugly cast is OK + ((GL2GL3)gl).glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, // since MSAA is supported, casting to GL2GL3 is OK GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST); - if(fullFBOSupport) { - // default read/draw buffers, may utilize GLContext/GLDrawable override of - // GLContext.getDefaultDrawFramebuffer() and GLContext.getDefaultReadFramebuffer() - gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, 0); - gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, 0); - } else { - gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); // default draw buffer - } + } + if(fullFBOSupport) { + // default read/draw buffers, may utilize GLContext/GLDrawable override of + // GLContext.getDefaultDrawFramebuffer() and GLContext.getDefaultReadFramebuffer() + gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, 0); + gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, 0); + } else { + gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); // default draw buffer } } /** * Bind the given texture colorbuffer. * - *

      If multisampling is being used, {@link #syncSamplingBuffer(GL)} is being called.

      + *

      If using multiple texture units, ensure you call {@link GL#glActiveTexture(int)} first!

      + * + *

      {@link #syncFramebuffer(GL)} is being called

      * *

      Leaves the FBO unbound!

      * @@ -1837,11 +2045,7 @@ public class FBObject { */ public final void use(GL gl, TextureAttachment ta) throws IllegalArgumentException { if(null == ta) { throw new IllegalArgumentException("null TextureAttachment, this: "+toString()); } - if(samples > 0 && samplesSinkTexture == ta) { - syncSamplingBuffer(gl); - } else { - unbind(gl); - } + syncFramebuffer(gl); gl.glBindTexture(GL.GL_TEXTURE_2D, ta.getName()); // use it .. } @@ -1855,14 +2059,8 @@ public class FBObject { gl.glBindTexture(GL.GL_TEXTURE_2D, 0); // don't use it } - /** - * Returns true if basic or full FBO is supported, otherwise false. - * @param full true for full FBO supported query, otherwise false for basic FBO support query. - * @see #supportsFullFBO(GL) - * @see #supportsBasicFBO(GL) - * @throws GLException if {@link #init(GL)} hasn't been called. - */ - public final boolean supportsFBO(boolean full) throws GLException { checkInitialized(); return full ? fullFBOSupport : basicFBOSupport; } + /** @see GL#hasFullFBOSupport() */ + public final boolean hasFullFBOSupport() throws GLException { checkInitialized(); return this.fullFBOSupport; } /** * Returns true if renderbuffer accepts internal format {@link GL#GL_RGB8} and {@link GL#GL_RGBA8}, otherwise false. @@ -1878,7 +2076,7 @@ public class FBObject { public final boolean supportsDepth(int bits) throws GLException { checkInitialized(); switch(bits) { - case 16: return basicFBOSupport; + case 16: return true; case 24: return depth24Avail; case 32: return depth32Avail; default: return false; @@ -1913,11 +2111,11 @@ public class FBObject { */ public final int getMaxColorAttachments() throws GLException { checkInitialized(); return maxColorAttachments; } - /** - * Returns the maximum number of samples for multisampling. Maybe zero if multisampling is not supported. - * @throws GLException if {@link #init(GL)} hasn't been called. - */ - public final int getMaxSamples() throws GLException { checkInitialized(); return maxSamples; } + public final int getMaxTextureSize() throws GLException { checkInitialized(); return this.maxTextureSize; } + public final int getMaxRenderbufferSize() throws GLException { checkInitialized(); return this.maxRenderbufferSize; } + + /** @see GL#getMaxRenderbufferSamples() */ + public final int getMaxSamples() throws GLException { checkInitialized(); return this.maxSamples; } /** * Returns true if this instance has been initialized with {@link #reset(GL, int, int)} diff --git a/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java new file mode 100644 index 000000000..38a8deef8 --- /dev/null +++ b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java @@ -0,0 +1,189 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl; + +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.WindowClosingProtocol; +import javax.media.nativewindow.WindowClosingProtocol.WindowClosingMode; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLException; + +import com.jogamp.common.util.locks.LockFactory; +import com.jogamp.common.util.locks.RecursiveLock; + +import jogamp.opengl.GLAutoDrawableBase; +import jogamp.opengl.GLContextImpl; +import jogamp.opengl.GLDrawableImpl; + + +/** + * Fully functional {@link GLAutoDrawable} implementation + * utilizing already created created {@link GLDrawable} and {@link GLContext} instances. + *

      + * Since no native windowing system events are being processed, it is recommended + * to handle at least: + *

        + *
      • {@link com.jogamp.newt.event.WindowListener#windowRepaint(com.jogamp.newt.event.WindowUpdateEvent) repaint} using {@link #windowRepaintOp()}
      • + *
      • {@link com.jogamp.newt.event.WindowListener#windowResized(com.jogamp.newt.event.WindowEvent) resize} using {@link #windowResizedOp()}
      • + *
      • {@link com.jogamp.newt.event.WindowListener#windowDestroyNotify(com.jogamp.newt.event.WindowEvent) destroy-notify} using {@link #windowDestroyNotifyOp()}
      • + *
      + *

      + *

      + * See example {@link com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateNEWT TestGLAutoDrawableDelegateNEWT}. + *

      + */ +public class GLAutoDrawableDelegate extends GLAutoDrawableBase implements GLAutoDrawable { + /** + * @param drawable a valid and already realized {@link GLDrawable} + * @param context a valid {@link GLContext}, may not be made current (created) yet. + * @param upstreamWidget optional UI element holding this instance, see {@link #getUpstreamWidget()}. + * @param ownDevice pass true if {@link AbstractGraphicsDevice#close()} shall be issued, + * otherwise pass false. Closing the device is required in case + * the drawable is created w/ it's own new instance, e.g. offscreen drawables, + * and no further lifecycle handling is applied. + * @param lock optional custom {@link RecursiveLock}. + */ + public GLAutoDrawableDelegate(GLDrawable drawable, GLContext context, Object upstreamWidget, boolean ownDevice, RecursiveLock lock) { + super((GLDrawableImpl)drawable, (GLContextImpl)context, ownDevice); + if(null == drawable) { + throw new IllegalArgumentException("null drawable"); + } + if(null == context) { + throw new IllegalArgumentException("null context"); + } + if(!drawable.isRealized()) { + throw new IllegalArgumentException("drawable not realized"); + } + this.upstreamWidget = upstreamWidget; + this.lock = ( null != lock ) ? lock : LockFactory.createRecursiveLock() ; + } + + // + // expose default methods + // + + /** Default implementation to handle repaint events from the windowing system */ + public final void windowRepaintOp() { + super.defaultWindowRepaintOp(); + } + + /** Implementation to handle resize events from the windowing system. All required locks are being claimed. */ + public final void windowResizedOp(int newWidth, int newHeight) { + super.defaultWindowResizedOp(newWidth, newHeight); + } + + /** + * Implementation to handle destroy notifications from the windowing system. + * + *

      + * If the {@link NativeSurface} does not implement {@link WindowClosingProtocol} + * or {@link WindowClosingMode#DISPOSE_ON_CLOSE} is enabled (default), + * a thread safe destruction is being induced. + *

      + */ + public final void windowDestroyNotifyOp() { + super.defaultWindowDestroyNotifyOp(); + } + + // + // Complete GLAutoDrawable + // + + private Object upstreamWidget; + private final RecursiveLock lock; + + @Override + protected final RecursiveLock getLock() { return lock; } + + @Override + public final Object getUpstreamWidget() { + return upstreamWidget; + } + + /** + * Set the upstream UI toolkit object. + * @see #getUpstreamWidget() + */ + public final void setUpstreamWidget(Object newUpstreamWidget) { + upstreamWidget = newUpstreamWidget; + } + + /** + * {@inheritDoc} + *

      + * This implementation calls {@link #defaultDestroy()}. + *

      + *

      + * User still needs to destroy the upstream window, which details are hidden from this aspect. + * This can be performed by overriding {@link #destroyImplInLock()}. + *

      + */ + @Override + public final void destroy() { + defaultDestroy(); + } + + @Override + protected void destroyImplInLock() { + super.destroyImplInLock(); + } + + @Override + public void display() { + defaultDisplay(); + } + + // + // GLDrawable delegation + // + + @Override + public final GLDrawableFactory getFactory() { + return drawable.getFactory(); + } + + @Override + public final void setRealized(boolean realized) { + } + + @Override + public final void swapBuffers() throws GLException { + defaultSwapBuffers(); + } + + @Override + public String toString() { + return getClass().getSimpleName()+"[ \n\tHelper: " + helper + ", \n\tDrawable: " + drawable + + ", \n\tContext: " + context + ", \n\tUpstreamWidget: "+upstreamWidget+ /** ", \n\tFactory: "+factory+ */ "]"; + } +} diff --git a/src/jogl/classes/com/jogamp/opengl/GLExtensions.java b/src/jogl/classes/com/jogamp/opengl/GLExtensions.java index f7e25fa01..cf81b85ee 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLExtensions.java +++ b/src/jogl/classes/com/jogamp/opengl/GLExtensions.java @@ -72,6 +72,9 @@ public class GLExtensions { public static final String OES_EGL_image_external = "GL_OES_EGL_image_external"; + public static final String ARB_gpu_shader_fp64 = "GL_ARB_gpu_shader_fp64"; + public static final String ARB_shader_objects = "GL_ARB_shader_objects"; + // // Aliased GLX/WGL/.. extensions // diff --git a/src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java b/src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java deleted file mode 100644 index 4caea03b2..000000000 --- a/src/jogl/classes/com/jogamp/opengl/OffscreenAutoDrawable.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright 2012 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package com.jogamp.opengl; - -import javax.media.nativewindow.AbstractGraphicsDevice; -import javax.media.opengl.GLAutoDrawableDelegate; -import javax.media.opengl.GLContext; -import javax.media.opengl.GLDrawable; -import javax.media.opengl.GLException; - -import jogamp.opengl.GLFBODrawableImpl; - -/** - * Platform-independent class exposing FBO offscreen functionality to - * applications. - *

      - * This class distinguishes itself from {@link GLAutoDrawableDelegate} - * with it's {@link #setSize(int, int)} functionality. - *

      - */ -public class OffscreenAutoDrawable extends GLAutoDrawableDelegate { - - /** - * @param drawable a valid {@link GLDrawable}, may not be realized yet. - * @param context a valid {@link GLContext}, may not be made current (created) yet. - * @param ownDevice pass true if {@link AbstractGraphicsDevice#close()} shall be issued, - * otherwise pass false. Closing the device is required in case - * the drawable is created w/ it's own new instance, e.g. offscreen drawables, - * and no further lifecycle handling is applied. - */ - public OffscreenAutoDrawable(GLDrawable drawable, GLContext context, boolean ownDevice) { - super(drawable, context, null, ownDevice); - } - - /** - * Attempts to resize this offscreen auto drawable, if supported - * by the underlying {@link GLDrawable). - * @param newWidth - * @param newHeight - * @return true if resize was executed, otherwise false. - * @throws GLException in case of an error during the resize operation - */ - public boolean setSize(int newWidth, int newHeight) throws GLException { - boolean done = false; - if(drawable instanceof GLFBODrawableImpl) { - Throwable tFBO = null; - Throwable tGL = null; - context.makeCurrent(); - try { - ((GLFBODrawableImpl)drawable).setSize(context.getGL(), newWidth, newHeight); - done = true; - } catch (Throwable t) { - tFBO = t; - } finally { - try { - context.release(); - } catch (Throwable t) { - tGL = t; - } - } - if(null != tFBO) { - throw new GLException("OffscreenAutoDrawable.setSize(..) GLFBODrawableImpl.setSize(..) exception", tFBO); - } - if(null != tGL) { - throw new GLException("OffscreenAutoDrawable.setSize(..) GLContext.release() exception", tGL); - } - } - if(done) { - this.defaultWindowResizedOp(); - return true; - } - return false; - } - - /** - * If the underlying {@link GLDrawable} is an FBO implementation - * and contains an {#link FBObject}, the same is returned. - * Otherwise returns null. - */ - public FBObject getFBObject() { - if(drawable instanceof GLFBODrawableImpl) { - return ((GLFBODrawableImpl)drawable).getFBObject(); - } - return null; - } -} diff --git a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java index 8d237162c..02f62daec 100644 --- a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java +++ b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java @@ -30,6 +30,7 @@ package com.jogamp.opengl.swt; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; import javax.media.opengl.GL; import javax.media.opengl.GLAnimatorControl; import javax.media.opengl.GLAutoDrawable; @@ -48,6 +49,7 @@ import javax.media.opengl.Threading; import jogamp.opengl.Debug; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableHelper; +import jogamp.opengl.GLDrawableImpl; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; @@ -97,8 +99,8 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { private final GLCapabilitiesImmutable capsRequested; private final GLCapabilitiesChooser capsChooser; - private volatile GLDrawable drawable; // volatile: avoid locking for read-only access - private GLContext context; + private volatile GLDrawableImpl drawable; // volatile: avoid locking for read-only access + private GLContextImpl context; /* Native window surface */ private AbstractGraphicsDevice device; @@ -319,7 +321,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { } }); } - private final ProxySurface.UpstreamSurfaceHook swtCanvasUpStreamHook = new ProxySurface.UpstreamSurfaceHook() { + private final UpstreamSurfaceHook swtCanvasUpStreamHook = new UpstreamSurfaceHook() { @Override public final void create(ProxySurface s) { /* nop */ } @@ -349,7 +351,27 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { ( nClientArea.width != oClientArea.width || nClientArea.height != oClientArea.height ) ) { clientArea = nClientArea; // write back new value - sendReshape = true; // Mark for OpenGL reshape next time the control is painted + + GLDrawableImpl _drawable = drawable; + if( null != _drawable ) { + if(DEBUG) { + System.err.println("GLCanvas.sizeChanged: ("+Thread.currentThread().getName()+"): "+nClientArea.width+"x"+nClientArea.height+" - surfaceHandle 0x"+Long.toHexString(getNativeSurface().getSurfaceHandle())); + } + if( ! _drawable.getChosenGLCapabilities().isOnscreen() ) { + final RecursiveLock _lock = lock; + _lock.lock(); + try { + final GLDrawableImpl _drawableNew = GLDrawableHelper.resizeOffscreenDrawable(_drawable, context, nClientArea.width, nClientArea.height); + if(_drawable != _drawableNew) { + // write back + drawable = _drawableNew; + } + } finally { + _lock.unlock(); + } + sendReshape = true; // async if display() doesn't get called below, but avoiding deadlock + } + } } } @@ -391,10 +413,10 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { if(null != proxySurface) { /* Associate a GL surface with the proxy */ - drawable = glFactory.createGLDrawable(proxySurface); + drawable = (GLDrawableImpl) glFactory.createGLDrawable(proxySurface); drawable.setRealized(true); - context = drawable.createContext(shareWith); + context = (GLContextImpl) drawable.createContext(shareWith); } } finally { _lock.unlock(); @@ -455,6 +477,11 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { return helper.getAutoSwapBufferMode(); } + @Override + public final GLDrawable getDelegatedDrawable() { + return drawable; + } + @Override public GLContext getContext() { return null != drawable ? context : null; @@ -502,7 +529,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { _lock.lock(); try { final GLContext oldCtx = context; - final boolean newCtxCurrent = helper.switchContext(drawable, oldCtx, newCtx, additionalCtxCreationFlags); + final boolean newCtxCurrent = GLDrawableHelper.switchContext(drawable, oldCtx, newCtx, additionalCtxCreationFlags); context=(GLContextImpl)newCtx; if(newCtxCurrent) { context.makeCurrent(); diff --git a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java index 0b2c664fe..38f1746f9 100644 --- a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java +++ b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java @@ -114,6 +114,12 @@ public interface GLAutoDrawable extends GLDrawable { * where you drag the window to another monitor. */ public static final boolean SCREEN_CHANGE_ACTION_ENABLED = Debug.getBooleanProperty("jogl.screenchange.action", true); + /** + * If the implementation uses delegation, return the delegated {@link GLDrawable} instance, + * otherwise return this instance. + */ + public GLDrawable getDelegatedDrawable(); + /** * Returns the context associated with this drawable. The returned * context will be synchronized. @@ -124,23 +130,31 @@ public interface GLAutoDrawable extends GLDrawable { /** * Associate a new context to this drawable and also propagates the context/drawable switch by * calling {@link GLContext#setGLDrawable(GLDrawable, boolean) newCtx.setGLDrawable(drawable, true);}. - * drawable might be an inner GLDrawable instance if using such a delegation pattern, - * or this GLAutoDrawable itself. - *

      - * If the old context's drawable was an {@link GLAutoDrawable}, it's reference to the given drawable - * is being cleared by calling - * {@link GLAutoDrawable#setContext(GLContext) ((GLAutoDrawable)oldCtx.getGLDrawable()).setContext(null)}. - *

      + * drawable might be an inner GLDrawable instance if using a delegation pattern, + * or this GLAutoDrawable instance. *

      * If the old or new context was current on this thread, it is being released before switching the drawable. * The new context will be made current afterwards, if it was current before. - * However the user shall take extra care that not other thread - * attempts to make this context current. Otherwise a race condition may happen. + * However the user shall take extra care that no other thread + * attempts to make this context current. + *

      + *

      + * Be aware that the old context is still bound to the drawable, + * and that one context can only be bound to one drawable at one time! *

      *

      - * Disclaimer: Even though the API may allows this functionality in theory, your mileage may vary - * switching the drawable of an already established GLContext, i.e. which is already made current once. - * FIXME: Validate functionality! + * In case you do not intend to use the old context anymore, i.e. + * not assigning it to another drawable, it shall be + * destroyed before setting the new context, i.e.: + *

      +            GLContext oldCtx = glad.getContext();
      +            if(null != oldCtx) {
      +                oldCtx.destroy();
      +            }
      +            glad.setContext(newCtx);            
      +   * 
      + * This is required, since a context must have a valid drawable at all times + * and this API shall not restrict the user in any way. *

      * * @param newCtx the new context diff --git a/src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java b/src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java deleted file mode 100644 index 67e81270d..000000000 --- a/src/jogl/classes/javax/media/opengl/GLAutoDrawableDelegate.java +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Copyright 2012 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package javax.media.opengl; - -import javax.media.nativewindow.AbstractGraphicsDevice; - -import com.jogamp.common.util.locks.LockFactory; -import com.jogamp.common.util.locks.RecursiveLock; - -import jogamp.opengl.Debug; -import jogamp.opengl.GLAutoDrawableBase; -import jogamp.opengl.GLContextImpl; -import jogamp.opengl.GLDrawableImpl; - - -/** - * Fully functional {@link GLAutoDrawable} implementation - * utilizing already created created {@link GLDrawable} and {@link GLContext} instances. - *

      - * Since no native windowing system events are being processed, it is recommended - * to handle at least: - *

        - *
      • {@link com.jogamp.newt.event.WindowListener#windowRepaint(com.jogamp.newt.event.WindowUpdateEvent) repaint} using {@link #defaultWindowRepaintOp()}
      • - *
      • {@link com.jogamp.newt.event.WindowListener#windowResized(com.jogamp.newt.event.WindowEvent) resize} using {@link #defaultWindowResizedOp()}
      • - *
      • {@link com.jogamp.newt.event.WindowListener#windowDestroyNotify(com.jogamp.newt.event.WindowEvent) destroy-notify} using {@link #defaultWindowDestroyNotifyOp()}
      • - *
      - *

      - *

      - * See example {@link com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateNEWT TestGLAutoDrawableDelegateNEWT}. - *

      - */ -public class GLAutoDrawableDelegate extends GLAutoDrawableBase { - public static final boolean DEBUG = Debug.debug("GLAutoDrawableDelegate"); - - /** - * @param drawable a valid {@link GLDrawable}, may not be realized yet. - * @param context a valid {@link GLContext}, may not be made current (created) yet. - * @param upstreamWidget optional UI element holding this instance, see {@link #getUpstreamWidget()}. - * @param ownDevice pass true if {@link AbstractGraphicsDevice#close()} shall be issued, - * otherwise pass false. Closing the device is required in case - * the drawable is created w/ it's own new instance, e.g. offscreen drawables, - * and no further lifecycle handling is applied. - */ - public GLAutoDrawableDelegate(GLDrawable drawable, GLContext context, Object upstreamWidget, boolean ownDevice) { - super((GLDrawableImpl)drawable, (GLContextImpl)context, ownDevice); - this.upstreamWidget = null; - } - - // - // expose default methods - // - - public final void windowRepaintOp() { - super.defaultWindowRepaintOp(); - } - - public final void windowResizedOp() { - super.defaultWindowResizedOp(); - } - - public final void windowDestroyNotifyOp() { - super.defaultWindowDestroyNotifyOp(); - } - - // - // Complete GLAutoDrawable - // - - private final RecursiveLock lock = LockFactory.createRecursiveLock(); // instance wide lock - private final Object upstreamWidget; - - @Override - protected final RecursiveLock getLock() { return lock; } - - @Override - public final Object getUpstreamWidget() { - return upstreamWidget; - } - - /** - * {@inheritDoc} - *

      - * This implementation calls {@link #defaultDestroy()}. - *

      - *

      - * User still needs to destroy the upstream window, which details are hidden from this aspect. - * This can be performed by overriding {@link #destroyImplInLock()}. - *

      - */ - @Override - public final void destroy() { - defaultDestroy(); - } - - @Override - public void display() { - defaultDisplay(); - } - - // - // GLDrawable delegation - // - - @Override - public final GLDrawableFactory getFactory() { - return drawable.getFactory(); - } - - @Override - public final void setRealized(boolean realized) { - } - - @Override - public final void swapBuffers() throws GLException { - defaultSwapBuffers(); - } - -} diff --git a/src/jogl/classes/javax/media/opengl/GLBase.java b/src/jogl/classes/javax/media/opengl/GLBase.java index f5831a72d..9bcee819a 100644 --- a/src/jogl/classes/javax/media/opengl/GLBase.java +++ b/src/jogl/classes/javax/media/opengl/GLBase.java @@ -273,6 +273,42 @@ public interface GLBase { */ public boolean isExtensionAvailable(String glExtensionName); + /** + * Returns true if basic FBO support is available, otherwise false. + *

      + * Basic FBO is supported if the context is either GL-ES >= 2.0, GL >= core 3.0 or implements the extensions + * GL_ARB_ES2_compatibility, GL_ARB_framebuffer_object, GL_EXT_framebuffer_object or GL_OES_framebuffer_object. + *

      + *

      + * Basic FBO support may only include one color attachment and no multisampling, + * as well as limited internal formats for renderbuffer. + *

      + * @see GLContext#hasBasicFBOSupport() + */ + public boolean hasBasicFBOSupport(); + + /** + * Returns true if full FBO support is available, otherwise false. + *

      + * Full FBO is supported if the context is either GL >= core 3.0 or implements the extensions + * ARB_framebuffer_object, or all of + * EXT_framebuffer_object, EXT_framebuffer_multisample, + * EXT_framebuffer_blit, GL_EXT_packed_depth_stencil. + *

      + *

      + * Full FBO support includes multiple color attachments and multisampling. + *

      + * @see GLContext#hasFullFBOSupport() + */ + public boolean hasFullFBOSupport(); + + /** + * Returns the maximum number of FBO RENDERBUFFER samples + * if {@link #hasFullFBOSupport() full FBO is supported}, otherwise false. + * @see GLContext#getMaxRenderbufferSamples() + */ + public int getMaxRenderbufferSamples(); + /** * Returns true if the GL context supports non power of two (NPOT) textures, * otherwise false. @@ -284,6 +320,8 @@ public interface GLBase { */ public boolean isNPOTTextureAvailable(); + public boolean isTextureFormatBGRA8888Available(); + /** Provides a platform-independent way to specify the minimum swap interval for buffer swaps. An argument of 0 disables sync-to-vertical-refresh completely, while an argument of 1 diff --git a/src/jogl/classes/javax/media/opengl/GLContext.java b/src/jogl/classes/javax/media/opengl/GLContext.java index c2f94b9af..a5e639c74 100644 --- a/src/jogl/classes/javax/media/opengl/GLContext.java +++ b/src/jogl/classes/javax/media/opengl/GLContext.java @@ -96,6 +96,9 @@ public abstract class GLContext { */ public static final boolean PROFILE_ALIASING = !Debug.isPropertyDefined("jogl.debug.GLContext.NoProfileAliasing", true); + protected static final boolean FORCE_NO_FBO_SUPPORT = Debug.isPropertyDefined("jogl.fbo.force.none", true); + protected static final boolean FORCE_MIN_FBO_SUPPORT = Debug.isPropertyDefined("jogl.fbo.force.min", true); + public static final boolean DEBUG = Debug.debug("GLContext"); public static final boolean TRACE_SWITCH = Debug.isPropertyDefined("jogl.debug.GLContext.TraceSwitch", true); @@ -127,9 +130,9 @@ public abstract class GLContext { /** GL_ARB_ES2_compatibility implementation related: Context is compatible w/ ES2. Not a cache key. See {@link #isGLES2Compatible()}, {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ protected static final int CTX_IMPL_ES2_COMPAT = 1 << 8; - /** Context supports basic FBO, details see {@link #hasFBO()}. + /** Context supports basic FBO, details see {@link #hasBasicFBOSupport()}. * Not a cache key. - * @see #hasFBO() + * @see #hasBasicFBOSupport() * @see #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile) */ protected static final int CTX_IMPL_FBO = 1 << 9; @@ -178,11 +181,6 @@ public abstract class GLContext { * and made current afterwards. However the user shall take extra care that not other thread * attempts to make this context current. Otherwise a race condition may happen. *

      - *

      - * Disclaimer: Even though the API may allows this functionality in theory, your mileage may vary - * switching the drawable of an already established GLContext, i.e. which is already made current once. - * FIXME: Validate functionality! - *

      * @param readWrite the read/write drawable for framebuffer operations. * @param setWriteOnly if true and if the current read-drawable differs * from the write-drawable ({@link #setGLReadDrawable(GLDrawable)}), @@ -603,12 +601,23 @@ public abstract class GLContext { /** * @return true if impl. is a hardware rasterizer, otherwise false. + * @see #isHardwareRasterizer(AbstractGraphicsDevice, GLProfile) * @see GLProfile#isHardwareRasterizer() */ public final boolean isHardwareRasterizer() { return 0 == ( ctxOptions & CTX_IMPL_ACCEL_SOFT ) ; } + /** + * @return true if context supports GLSL, i.e. is either {@link #isGLES2()}, {@link #isGL3()} or {@link #isGL2()} and major-version > 1. + * @see GLProfile#hasGLSL() + */ + public final boolean hasGLSL() { + return isGLES2() || + isGL3() || + isGL2() && ctxMajorVersion>1 ; + } + /** * Returns true if basic FBO support is available, otherwise false. *

      @@ -620,21 +629,54 @@ public abstract class GLContext { * as well as limited internal formats for renderbuffer. *

      * @see #CTX_IMPL_FBO - * @see com.jogamp.opengl.FBObject#supportsBasicFBO(GL) - * @see com.jogamp.opengl.FBObject#supportsFullFBO(GL) */ - public final boolean hasFBO() { + public final boolean hasBasicFBOSupport() { return 0 != ( ctxOptions & CTX_IMPL_FBO ) ; } + /** + * Returns true if full FBO support is available, otherwise false. + *

      + * Full FBO is supported if the context is either GL >= core 3.0 or implements the extensions + * ARB_framebuffer_object, or all of + * EXT_framebuffer_object, EXT_framebuffer_multisample, + * EXT_framebuffer_blit, GL_EXT_packed_depth_stencil. + *

      + *

      + * Full FBO support includes multiple color attachments and multisampling. + *

      + */ + public final boolean hasFullFBOSupport() { + return !FORCE_MIN_FBO_SUPPORT && hasBasicFBOSupport() && + ( isGL3() || // GL >= 3.0 + isExtensionAvailable(GLExtensions.ARB_framebuffer_object) || // ARB_framebuffer_object + ( isExtensionAvailable(GLExtensions.EXT_framebuffer_object) && // All EXT_framebuffer_object* + isExtensionAvailable(GLExtensions.EXT_framebuffer_multisample) && + isExtensionAvailable(GLExtensions.EXT_framebuffer_blit) && + isExtensionAvailable(GLExtensions.EXT_packed_depth_stencil) + ) + ) ; + } + /** - * @return true if context supports GLSL - * @see GLProfile#hasGLSL() + * Returns the maximum number of FBO RENDERBUFFER samples + * if {@link #hasFullFBOSupport() full FBO is supported}, otherwise false. */ - public final boolean hasGLSL() { - return isGL2ES2() ; + public final int getMaxRenderbufferSamples() { + if( hasFullFBOSupport() ) { + final GL gl = getGL(); + final int[] val = new int[] { 0 } ; + gl.glGetIntegerv(GL2GL3.GL_MAX_SAMPLES, val, 0); + final int glerr = gl.glGetError(); + if(GL.GL_NO_ERROR == glerr) { + return val[0]; + } else if(DEBUG) { + System.err.println("GLContext.getMaxRenderbufferSamples: GL_MAX_SAMPLES query GL Error 0x"+Integer.toHexString(glerr)); + } + } + return 0; } - + /** Note: The GL impl. may return a const value, ie {@link GLES2#isNPOTTextureAvailable()} always returns true. */ public boolean isNPOTTextureAvailable() { return isGL3() || isGLES2Compatible() || isExtensionAvailable(GLExtensions.ARB_texture_non_power_of_two); @@ -1014,6 +1056,9 @@ public abstract class GLContext { validateProfileBits(profile, "profile"); validateProfileBits(resCtp, "resCtp"); + if(FORCE_NO_FBO_SUPPORT) { + resCtp &= ~CTX_IMPL_FBO ; + } if(DEBUG) { System.err.println("GLContext.mapAvailableGLVersion: "+device+": "+getGLVersion(reqMajor, 0, profile, null)+" -> "+getGLVersion(resMajor, resMinor, resCtp, null)); // Thread.dumpStack(); @@ -1197,17 +1242,35 @@ public abstract class GLContext { * FBO feature is implemented in OpenGL, hence it is {@link GLProfile} dependent. *

      *

      - * FBO support is queried as described in {@link #hasFBO()}. + * FBO support is queried as described in {@link #hasBasicFBOSupport()}. *

      * * @param device the device to request whether FBO is available for * @param glp {@link GLProfile} to check for FBO capabilities - * @see GLContext#hasFBO() + * @see GLContext#hasBasicFBOSupport() */ public static final boolean isFBOAvailable(AbstractGraphicsDevice device, GLProfile glp) { return 0 != ( CTX_IMPL_FBO & getAvailableContextProperties(device, glp) ); } + /** + * @return 1 if using a hardware rasterizer, 0 if using a software rasterizer and -1 if not determined yet. + * @see GLContext#isHardwareRasterizer() + * @see GLProfile#isHardwareRasterizer() + */ + public static final int isHardwareRasterizer(AbstractGraphicsDevice device, GLProfile glp) { + final int r; + final int ctp = getAvailableContextProperties(device, glp); + if(0 == ctp) { + r = -1; + } else if( 0 == ( CTX_IMPL_ACCEL_SOFT & ctp ) ) { + r = 1; + } else { + r = 0; + } + return r; + } + /** * @param device the device to request whether the profile is available for * @param reqMajor Key Value either 1, 2, 3 or 4 diff --git a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java index 9fd895c1f..b6e7b0576 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java @@ -48,13 +48,16 @@ import java.util.List; import com.jogamp.common.JogampRuntimeException; import com.jogamp.common.util.ReflectionUtil; +import com.jogamp.opengl.GLAutoDrawableDelegate; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; -import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; +import javax.media.nativewindow.UpstreamSurfaceHook; import jogamp.opengl.Debug; @@ -373,44 +376,63 @@ public abstract class GLDrawableFactory { // Methods to create high-level objects /** - * Returns a GLDrawable according to it's chosen Capabilities,
      + * Returns a GLDrawable according to it's chosen {@link GLCapabilitiesImmutable},
      * which determines pixel format, on- and offscreen incl. PBuffer type. *

      - * The native platform's chosen Capabilties are referenced within the target - * NativeSurface's AbstractGraphicsConfiguration.

      - * - * In case target's {@link javax.media.nativewindow.Capabilities#isOnscreen()} is true,
      - * an onscreen GLDrawable will be realized. + * The chosen {@link GLCapabilitiesImmutable} are referenced within the target + * {@link NativeSurface}'s {@link AbstractGraphicsConfiguration}.

      + *

      *

      - * In case target's {@link javax.media.nativewindow.Capabilities#isOnscreen()} is false,
      - * either a Pbuffer drawable is created if target's {@link javax.media.opengl.GLCapabilities#isPBuffer()} is true,
      - * or a simple pixmap/bitmap drawable is created. The latter is unlikely to be hardware accelerated.
      + * An onscreen GLDrawable is created if {@link CapabilitiesImmutable#isOnscreen() caps.isOnscreen()} is true. + *

      *

      - * + * A FBO drawable is created if both {@link GLCapabilitiesImmutable#isFBO() caps.isFBO()} + * and {@link GLContext#isFBOAvailable(AbstractGraphicsDevice, GLProfile) canCreateFBO(device, caps.getGLProfile())} is true. + *

      + *

      + * A Pbuffer drawable is created if both {@link GLCapabilitiesImmutable#isPBuffer() caps.isPBuffer()} + * and {@link #canCreateGLPbuffer(AbstractGraphicsDevice) canCreateGLPbuffer(device)} is true. + *

      + *

      + * If not onscreen and neither FBO nor Pbuffer is available, + * a simple pixmap/bitmap drawable/surface is created, which is unlikely to be hardware accelerated. + *

      + * * @throws IllegalArgumentException if the passed target is null * @throws GLException if any window system-specific errors caused * the creation of the GLDrawable to fail. * + * @see #canCreateGLPbuffer(AbstractGraphicsDevice) + * @see GLContext#isFBOAvailable(AbstractGraphicsDevice, GLProfile) + * @see javax.media.opengl.GLCapabilities#isOnscreen() + * @see javax.media.opengl.GLCapabilities#isFBO() + * @see javax.media.opengl.GLCapabilities#isPBuffer() * @see javax.media.nativewindow.GraphicsConfigurationFactory#chooseGraphicsConfiguration(Capabilities, CapabilitiesChooser, AbstractGraphicsScreen) */ public abstract GLDrawable createGLDrawable(NativeSurface target) throws IllegalArgumentException, GLException; - + /** - * Creates a Offscreen GLDrawable incl it's offscreen {@link javax.media.nativewindow.NativeSurface} with the given capabilites and dimensions. + * Creates an {@link GLOffscreenAutoDrawable} incl it's offscreen {@link javax.media.nativewindow.NativeSurface} with the given capabilites and dimensions. *

      - * It's {@link AbstractGraphicsConfiguration} is properly set according to the given {@link GLCapabilitiesImmutable}, see below. + * The {@link GLOffscreenAutoDrawable}'s {@link GLDrawable} is realized and it's {@link GLContext} assigned but not yet made current. *

      *

      - * A FBO drawable is created if both {@link javax.media.opengl.GLCapabilities#isFBO() caps.isFBO()} + * In case the passed {@link GLCapabilitiesImmutable} contains default values, i.e. + * {@link GLCapabilitiesImmutable#isOnscreen() caps.isOnscreen()} == true, + * it is auto-configured. The latter will set offscreen and also FBO or Pbuffer, whichever is available in that order. + *

      + *

      + * A FBO based auto drawable, {@link GLOffscreenAutoDrawable.FBO}, is created if both {@link GLCapabilitiesImmutable#isFBO() caps.isFBO()} * and {@link GLContext#isFBOAvailable(AbstractGraphicsDevice, GLProfile) canCreateFBO(device, caps.getGLProfile())} is true. *

      *

      - * A Pbuffer drawable is created if both {@link javax.media.opengl.GLCapabilities#isPBuffer() caps.isPBuffer()} - * and {@link #canCreateGLPbuffer(javax.media.nativewindow.AbstractGraphicsDevice) canCreateGLPbuffer(device)} is true. + * A Pbuffer based auto drawable is created if both {@link GLCapabilitiesImmutable#isPBuffer() caps.isPBuffer()} + * and {@link #canCreateGLPbuffer(AbstractGraphicsDevice) canCreateGLPbuffer(device)} is true. *

      *

      - * If neither FBO nor Pbuffer is available, a simple pixmap/bitmap drawable/surface is created, which is unlikely to be hardware accelerated. + * If neither FBO nor Pbuffer is available, + * a simple pixmap/bitmap auto drawable is created, which is unlikely to be hardware accelerated. *

      * * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared device to be used, may be null for the platform's default device. @@ -418,17 +440,55 @@ public abstract class GLDrawableFactory { * @param chooser the custom chooser, may be null for default * @param width the requested offscreen width * @param height the requested offscreen height + * @return the created and initialized offscreen {@link GLOffscreenAutoDrawable} instance * - * @return the created offscreen GLDrawable + * @throws GLException if any window system-specific errors caused + * the creation of the Offscreen to fail. + * + * @see #createOffscreenDrawable(AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int) + */ + public abstract GLOffscreenAutoDrawable createOffscreenAutoDrawable(AbstractGraphicsDevice device, + GLCapabilitiesImmutable caps, + GLCapabilitiesChooser chooser, + int width, int height, + GLContext shareWith) throws GLException; + /** + * Creates a offscreen {@link GLDrawable} incl it's offscreen {@link javax.media.nativewindow.NativeSurface} with the given capabilites and dimensions. + *

      + * In case the passed {@link GLCapabilitiesImmutable} contains default values, i.e. + * {@link GLCapabilitiesImmutable#isOnscreen() caps.isOnscreen()} == true, + * it is auto-configured. The latter will set offscreen and also FBO or Pbuffer, whichever is available in that order. + *

      + *

      + * A resizeable FBO drawable, {@link GLFBODrawable.Resizeable}, is created if both {@link GLCapabilitiesImmutable#isFBO() caps.isFBO()} + * and {@link GLContext#isFBOAvailable(AbstractGraphicsDevice, GLProfile) canCreateFBO(device, caps.getGLProfile())} is true. + *

      + *

      + * A Pbuffer drawable is created if both {@link GLCapabilitiesImmutable#isPBuffer() caps.isPBuffer()} + * and {@link #canCreateGLPbuffer(AbstractGraphicsDevice) canCreateGLPbuffer(device)} is true. + *

      + *

      + * If neither FBO nor Pbuffer is available, + * a simple pixmap/bitmap drawable is created, which is unlikely to be hardware accelerated. + *

      + * + * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared device to be used, may be null for the platform's default device. + * @param caps the requested GLCapabilties + * @param chooser the custom chooser, may be null for default + * @param width the requested offscreen width + * @param height the requested offscreen height + * + * @return the created offscreen {@link GLDrawable} * * @throws GLException if any window system-specific errors caused * the creation of the Offscreen to fail. + * + * @see #createOffscreenAutoDrawable(AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int, GLContext) */ public abstract GLDrawable createOffscreenDrawable(AbstractGraphicsDevice device, - GLCapabilitiesImmutable capabilities, + GLCapabilitiesImmutable caps, GLCapabilitiesChooser chooser, - int width, int height) - throws GLException; + int width, int height) throws GLException; /** * Creates a proxy {@link NativeSurface} w/ defined surface handle, i.e. a {@link WrappedSurface} or {@link GDISurface} instance. @@ -458,6 +518,21 @@ public abstract class GLDrawableFactory { long windowHandle, GLCapabilitiesImmutable caps, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream); + /** + * Returns true if it is possible to create an framebuffer object (FBO). + *

      + * FBO feature is implemented in OpenGL, hence it is {@link GLProfile} dependent. + *

      + *

      + * FBO support is queried as described in {@link GLContext#hasBasicFBOSupport()}. + *

      + * + * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be null for the platform's default device. + * @param glp {@link GLProfile} to check for FBO capabilities + * @see GLContext#hasBasicFBOSupport() + */ + public abstract boolean canCreateFBO(AbstractGraphicsDevice device, GLProfile glp); + /** * Returns true if it is possible to create a GLPbuffer. Some older * graphics cards do not have this capability. @@ -467,7 +542,10 @@ public abstract class GLDrawableFactory { public abstract boolean canCreateGLPbuffer(AbstractGraphicsDevice device); /** - * Creates a GLPbuffer with the given capabilites and dimensions.

      + * Creates a GLPbuffer {@link GLAutoDrawable} with the given capabilites and dimensions. + *

      + * The GLPbuffer drawable is realized and initialized eagerly. + *

      * * See the note in the overview documentation on * context sharing. @@ -479,10 +557,12 @@ public abstract class GLDrawableFactory { * @param initialHeight initial height of pbuffer * @param shareWith a shared GLContext this GLPbuffer shall use * - * @return the new {@link GLPbuffer} specific {@link GLAutoDrawable} + * @return the created and initialized {@link GLPbuffer} instance * * @throws GLException if any window system-specific errors caused * the creation of the GLPbuffer to fail. + * + * @deprecated {@link GLPbuffer} is deprecated, use {@link #createOffscreenAutoDrawable(AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int, GLContext)} */ public abstract GLPbuffer createGLPbuffer(AbstractGraphicsDevice device, GLCapabilitiesImmutable capabilities, diff --git a/src/jogl/classes/javax/media/opengl/GLFBODrawable.java b/src/jogl/classes/javax/media/opengl/GLFBODrawable.java new file mode 100644 index 000000000..45fd3b686 --- /dev/null +++ b/src/jogl/classes/javax/media/opengl/GLFBODrawable.java @@ -0,0 +1,173 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package javax.media.opengl; + +import javax.media.nativewindow.NativeWindowException; + +import com.jogamp.opengl.FBObject; +import com.jogamp.opengl.FBObject.TextureAttachment; + +/** + * Platform-independent {@link GLDrawable} specialization, + * exposing {@link FBObject} functionality. + * + *

      + * A {@link GLFBODrawable} is uninitialized until a {@link GLContext} is bound + * and made current the first time. + *

      + * + *

      + * MSAA is used if {@link GLCapabilitiesImmutable#getNumSamples() requested}. + *

      + *

      + * Double buffering is used if {@link GLCapabilitiesImmutable#getDoubleBuffered() requested}. + *

      + *

      + * In MSAA mode, it always uses the implicit 2nd {@link FBObject framebuffer} {@link FBObject#getSamplingSinkFBO() sink}. + * Hence double buffering is always the case w/ MSAA. + *

      + *

      + * In non MSAA a second explicit {@link FBObject framebuffer} is being used. + * This method allows compliance w/ the spec, i.e. read and draw framebuffer selection + * and double buffer usage for e.g. {@link GL#glReadPixels(int, int, int, int, int, int, java.nio.Buffer) glReadPixels(..)}. + * This method also allows usage of both textures seperately. + *

      + *

      + * It would be possible to implement double buffering simply using + * {@link FBObject.TextureAttachment texture attachment}s with one {@link FBObject framebuffer}. + * This would require mode selection and hence complicate the API. Besides, it would + * not support differentiation of read and write framebuffer and hence not be spec compliant. + *

      + *

      + * Actual swapping of the {@link FBObject.TextureAttachment texture}s or {@link FBObject framebuffer} + * is performed either in the {@link #contextMadeCurrent(boolean) context current hook} + * or when {@link #swapBuffersImpl(boolean) swapping buffers}, whatever comes first.
      + *

      + */ +public interface GLFBODrawable extends GLDrawable { + // public enum DoubleBufferMode { NONE, TEXTURE, FBO }; // TODO: Add or remove TEXTURE (only) DoubleBufferMode support + + /** + * @return true if initialized, i.e. a {@link GLContext} is bound and made current once, otherwise false. + */ + public boolean isInitialized(); + + /** + * Notify this instance about upstream size change + * to reconfigure the {@link FBObject}. + * @param gl GL context object bound to this drawable, will be made current during operation. + * A prev. current context will be make current after operation. + * @throws GLException if resize operation failed + */ + void resetSize(GL gl) throws GLException; + + /** + * @return the used texture unit + */ + int getTextureUnit(); + + /** + * + * @param unit the texture unit to be used + */ + void setTextureUnit(int unit); + + /** + * Set a new sample size + * @param gl GL context object bound to this drawable, will be made current during operation. + * A prev. current context will be make current after operation. + * @param newSamples new sample size + * @throws GLException if resetting the FBO failed + */ + void setNumSamples(GL gl, int newSamples) throws GLException; + + /** + * @return the number of sample buffers if using MSAA, otherwise 0 + */ + int getNumSamples(); + + /** + * @return the used {@link DoubleBufferMode} + */ + // DoubleBufferMode getDoubleBufferMode(); // TODO: Add or remove TEXTURE (only) DoubleBufferMode support + + /** + * Sets the {@link DoubleBufferMode}. Must be called before {@link #isInitialized() initialization}, + * otherwise an exception is thrown. + *

      + * This call has no effect is MSAA is selected, since MSAA always forces the mode to {@link DoubleBufferMode#FBO FBO}. + * Also setting the mode to {@link DoubleBufferMode#NONE NONE} where double buffering is {@link GLCapabilitiesImmutable#getDoubleBuffered() requested} + * or setting a double buffering mode w/o {@link GLCapabilitiesImmutable#getDoubleBuffered() request} will be ignored. + *

      + *

      + * Since {@link DoubleBufferMode#TEXTURE TEXTURE} mode is currently not implemented, this method has no effect. + *

      + * @throws GLException if already initialized, see {@link #isInitialized()}. + */ + // void setDoubleBufferMode(DoubleBufferMode mode) throws GLException; // TODO: Add or remove TEXTURE (only) DoubleBufferMode support + + /** + * If MSAA is being used and {@link GL#GL_FRONT} is requested, + * the internal {@link FBObject} {@link FBObject#getSamplingSinkFBO() sample sink} is being returned. + * + * @param bufferName {@link GL#GL_FRONT} and {@link GL#GL_BACK} are valid buffer names + * @return the named {@link FBObject} + * @throws IllegalArgumentException if an illegal buffer name is being used + */ + FBObject getFBObject(int bufferName) throws IllegalArgumentException; + + /** + * Returns the named texture buffer. + *

      + * If MSAA is being used, only the {@link GL#GL_FRONT} buffer is accessible + * and an exception is being thrown if {@link GL#GL_BACK} is being requested. + *

      + * @param bufferName {@link GL#GL_FRONT} and {@link GL#GL_BACK} are valid buffer names + * @return the named {@link TextureAttachment} + * @throws IllegalArgumentException if using MSAA and {@link GL#GL_BACK} is requested or an illegal buffer name is being used + */ + FBObject.TextureAttachment getTextureBuffer(int bufferName) throws IllegalArgumentException; + + /** Resizeable {@link GLFBODrawable} specialization */ + public interface Resizeable extends GLFBODrawable { + /** + * Resize this drawable. + *

      + * This drawable is being locked during operation. + *

      + * @param context the {@link GLContext} bound to this drawable, will be made current during operation + * A prev. current context will be make current after operation. + * @param newWidth + * @param newHeight + * @throws NativeWindowException in case the surface could no be locked + * @throws GLException in case an error during the resize operation occurred + */ + void setSize(GLContext context, int newWidth, int newHeight) throws NativeWindowException, GLException; + } +} diff --git a/src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java b/src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java new file mode 100644 index 000000000..6fe76a3f4 --- /dev/null +++ b/src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java @@ -0,0 +1,63 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package javax.media.opengl; + +import javax.media.nativewindow.NativeWindowException; + +import com.jogamp.opengl.FBObject; + +/** + * Platform-independent {@link GLAutoDrawable} specialization, + * exposing offscreen functionality. + *

      + * This class distinguishes itself from {@link GLAutoDrawable} + * with it's {@link #setSize(int, int)} functionality. + *

      + */ +public interface GLOffscreenAutoDrawable extends GLAutoDrawable { + + /** + * Resize this auto drawable. + * @param newWidth + * @param newHeight + * @throws NativeWindowException in case the surface could no be locked + * @throws GLException in case of an error during the resize operation + */ + void setSize(int newWidth, int newHeight) throws NativeWindowException, GLException; + + /** + * Set the upstream UI toolkit object. + * @see #getUpstreamWidget() + */ + void setUpstreamWidget(Object newUpstreamWidget); + + /** {@link FBObject} based {@link GLOffscreenAutoDrawable} specialization */ + public interface FBO extends GLOffscreenAutoDrawable, GLFBODrawable { + } +} diff --git a/src/jogl/classes/javax/media/opengl/GLPbuffer.java b/src/jogl/classes/javax/media/opengl/GLPbuffer.java index 273a992cf..de7731a3b 100644 --- a/src/jogl/classes/javax/media/opengl/GLPbuffer.java +++ b/src/jogl/classes/javax/media/opengl/GLPbuffer.java @@ -45,7 +45,11 @@ package javax.media.opengl; 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 be deprecated in a future release. */ + platforms and may be deprecated in a future release. + + @deprecated Use {@link GLOffscreenAutoDrawable} w/ {@link GLCapabilities#setFBO(boolean)} + via {@link GLDrawableFactory#createOffscreenAutoDrawable(javax.media.nativewindow.AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int, GLContext) GLDrawableFactory.createOffscreenAutoDrawable(..)}. + */ public interface GLPbuffer extends GLAutoDrawable { /** Indicates the GL_APPLE_float_pixels extension is being used for this pbuffer. */ diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 033591fe3..329cf9e3f 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -98,6 +98,7 @@ import jogamp.common.awt.AWTEDTExecutor; import jogamp.opengl.Debug; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableHelper; +import jogamp.opengl.GLDrawableImpl; // FIXME: Subclasses need to call resetGLFunctionAvailability() on their // context whenever the displayChanged() function is called on our @@ -109,6 +110,16 @@ import jogamp.opengl.GLDrawableHelper; interfaces when adding a heavyweight doesn't work either because of Z-ordering or LayoutManager problems. * + *
      Offscreen Layer Remarks
      + * + * {@link OffscreenLayerOption#setShallUseOffscreenLayer(boolean) setShallUseOffscreenLayer(true)} + * maybe called to use an offscreen drawable (FBO or PBuffer) allowing + * the underlying JAWT mechanism to composite the image, if supported. + *

      + * {@link OffscreenLayerOption#setShallUseOffscreenLayer(boolean) setShallUseOffscreenLayer(true)} + * is being called if {@link GLCapabilitiesImmutable#isOnscreen()} is false. + *

      + * *
      Java2D OpenGL Remarks
      * * To avoid any conflicts with a potential Java2D OpenGL context,
      @@ -145,7 +156,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing private final RecursiveLock lock = LockFactory.createRecursiveLock(); private final GLDrawableHelper helper = new GLDrawableHelper(); private AWTGraphicsConfiguration awtConfig; - private volatile GLDrawable drawable; // volatile: avoid locking for read-only access + private volatile GLDrawableImpl drawable; // volatile: avoid locking for read-only access private volatile JAWTWindow jawtWindow; // the JAWTWindow presentation of this AWT Canvas, bound to the 'drawable' lifecycle private GLContextImpl context; private volatile boolean sendReshape = false; // volatile: maybe written by EDT w/o locking @@ -237,6 +248,9 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing // don't allow the user to change data capsReqUser = (GLCapabilitiesImmutable) capsReqUser.cloneMutable(); } + if(!capsReqUser.isOnscreen()) { + setShallUseOffscreenLayer(true); // trigger offscreen layer - if supported + } if(null==device) { GraphicsConfiguration gc = super.getGraphicsConfiguration(); @@ -451,11 +465,9 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing /** Overridden to cause OpenGL rendering to be performed during repaint cycles. Subclasses which override this method must call super.paint() in their paint() method in order to function - properly.

      - - Overrides: -

      paint in class java.awt.Component
      */ - @Override + properly. + */ + @Override public void paint(Graphics g) { if (Beans.isDesignTime()) { // Make GLCanvas behave better in NetBeans GUI builder @@ -544,7 +556,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing jawtWindow.setShallUseOffscreenLayer(shallUseOffscreenLayer); jawtWindow.lockSurface(); try { - drawable = GLDrawableFactory.getFactory(capsReqUser.getGLProfile()).createGLDrawable(jawtWindow); + drawable = (GLDrawableImpl) GLDrawableFactory.getFactory(capsReqUser.getGLProfile()).createGLDrawable(jawtWindow); context = (GLContextImpl) drawable.createContext(shareWith); context.setContextCreationFlags(additionalCtxCreationFlags); } finally { @@ -561,13 +573,15 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing if (!Beans.isDesignTime() && 0 < _drawable.getWidth() * _drawable.getHeight() ) { // make sure drawable realization happens on AWT EDT, due to AWTTree lock - AWTEDTExecutor.singleton.invoke(true, setRealizedOnEDTAction); - sendReshape=true; // ensure a reshape is being send .. - if(DEBUG) { - System.err.println(getThreadName()+": Realized Drawable: "+_drawable.toString()); - Thread.dumpStack(); + AWTEDTExecutor.singleton.invoke(getTreeLock(), true, setRealizedOnEDTAction); + if( _drawable.isRealized() ) { + sendReshape=true; // ensure a reshape is being send .. + if(DEBUG) { + System.err.println(getThreadName()+": Realized Drawable: "+_drawable.toString()); + Thread.dumpStack(); + } + return true; } - return true; } } return false; @@ -575,7 +589,10 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing private Runnable setRealizedOnEDTAction = new Runnable() { @Override public void run() { - drawable.setRealized(true); + final GLDrawable _drawable = drawable; + if ( null != _drawable && 0 < _drawable.getWidth() * _drawable.getHeight() ) { + _drawable.setRealized(true); + } } }; /**

      Overridden to track when this component is removed from a @@ -620,22 +637,37 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing @SuppressWarnings("deprecation") @Override public void reshape(int x, int y, int width, int height) { - super.reshape(x, y, width, height); - final GLDrawable _drawable = drawable; - if(null != _drawable && _drawable.isRealized() && !_drawable.getChosenGLCapabilities().isOnscreen()) { - dispose(true); - } else { - sendReshape = true; + synchronized (getTreeLock()) { // super.reshape(..) claims tree lock, so we do extend it's lock over reshape + super.reshape(x, y, width, height); + + GLDrawableImpl _drawable = drawable; + if( null != _drawable ) { + if(DEBUG) { + System.err.println("GLCanvas.sizeChanged: ("+Thread.currentThread().getName()+"): "+width+"x"+height+" - surfaceHandle 0x"+Long.toHexString(getNativeSurface().getSurfaceHandle())); + } + if( ! _drawable.getChosenGLCapabilities().isOnscreen() ) { + final RecursiveLock _lock = lock; + _lock.lock(); + try { + final GLDrawableImpl _drawableNew = GLDrawableHelper.resizeOffscreenDrawable(_drawable, context, width, height); + if(_drawable != _drawableNew) { + // write back + drawable = _drawableNew; + } + } finally { + _lock.unlock(); + } + } + sendReshape = true; // async if display() doesn't get called below, but avoiding deadlock + } } } - /** Overrides: -

      update in class java.awt.Component
      */ /** * Overridden from Canvas to prevent the AWT's clearing of the * canvas from interfering with the OpenGL rendering. */ - @Override + @Override public void update(Graphics g) { paint(g); } @@ -681,7 +713,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing _lock.lock(); try { final GLContext oldCtx = context; - final boolean newCtxCurrent = helper.switchContext(drawable, oldCtx, newCtx, additionalCtxCreationFlags); + final boolean newCtxCurrent = GLDrawableHelper.switchContext(drawable, oldCtx, newCtx, additionalCtxCreationFlags); context=(GLContextImpl)newCtx; if(newCtxCurrent) { context.makeCurrent(); @@ -692,6 +724,11 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } } + @Override + public final GLDrawable getDelegatedDrawable() { + return drawable; + } + @Override public GLContext getContext() { return context; @@ -866,7 +903,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing if(!disposeRegenerate) { if(null != awtConfig) { - disposeAbstractGraphicsDevice(); + AWTEDTExecutor.singleton.invoke(getTreeLock(), true, disposeAbstractGraphicsDeviceActionOnEDT); } awtConfig=null; } @@ -881,7 +918,13 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } }; - private final Runnable disposeAbstractGraphicsDeviceAction = new Runnable() { + /** + * Disposes the AbstractGraphicsDevice within EDT, + * since resources created (X11: Display), must be destroyed in the same thread, where they have been created. + * + * @see #chooseGraphicsConfiguration(javax.media.opengl.GLCapabilitiesImmutable, javax.media.opengl.GLCapabilitiesImmutable, javax.media.opengl.GLCapabilitiesChooser, java.awt.GraphicsDevice) + */ + private final Runnable disposeAbstractGraphicsDeviceActionOnEDT = new Runnable() { @Override public void run() { if(null != awtConfig) { @@ -900,27 +943,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } } }; - - /** - * Disposes the AbstractGraphicsDevice within EDT, - * since resources created (X11: Display), must be destroyed in the same thread, where they have been created. - * - * @see #chooseGraphicsConfiguration(javax.media.opengl.GLCapabilitiesImmutable, javax.media.opengl.GLCapabilitiesImmutable, javax.media.opengl.GLCapabilitiesChooser, java.awt.GraphicsDevice) - */ - private void disposeAbstractGraphicsDevice() { - if( EventQueue.isDispatchThread() || Thread.holdsLock(getTreeLock()) ) { - disposeAbstractGraphicsDeviceAction.run(); - } else { - try { - EventQueue.invokeAndWait(disposeAbstractGraphicsDeviceAction); - } catch (InvocationTargetException e) { - throw new GLException(e.getTargetException()); - } catch (InterruptedException e) { - throw new GLException(e); - } - } - } - + private final Runnable initAction = new Runnable() { @Override public void run() { @@ -1046,7 +1069,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing * @param device * @return the chosen AWTGraphicsConfiguration * - * @see #disposeAbstractGraphicsDevice() + * @see #disposeAbstractGraphicsDeviceActionOnEDT */ private AWTGraphicsConfiguration chooseGraphicsConfiguration(final GLCapabilitiesImmutable capsChosen, final GLCapabilitiesImmutable capsRequested, diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java index acb8f2183..6d4a5861f 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java @@ -121,7 +121,7 @@ import com.jogamp.opengl.util.GLBuffers; *

      */ -@SuppressWarnings("serial") +@SuppressWarnings({ "serial", "deprecation" }) public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosingProtocol { private static final boolean DEBUG = Debug.debug("GLJPanel"); @@ -396,7 +396,6 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing their reshape() method in order to function properly.

      reshape in class java.awt.Component
      */ - @SuppressWarnings("deprecation") @Override public void reshape(int x, int y, int width, int height) { super.reshape(x, y, width, height); @@ -471,7 +470,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing return null; } final GLContext oldCtx = backend.getContext(); - final boolean newCtxCurrent = helper.switchContext(backend.getDrawable(), oldCtx, newCtx, additionalCtxCreationFlags); + final boolean newCtxCurrent = GLDrawableHelper.switchContext(backend.getDrawable(), oldCtx, newCtx, additionalCtxCreationFlags); backend.setContext(newCtx); if(newCtxCurrent) { newCtx.makeCurrent(); @@ -480,6 +479,14 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } + @Override + public final GLDrawable getDelegatedDrawable() { + if (backend == null) { + return null; + } + return backend.getDrawable(); + } + @Override public GLContext getContext() { if (backend == null) { diff --git a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java index cc4e1b434..07029f143 100644 --- a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java +++ b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java @@ -30,16 +30,15 @@ package jogamp.opengl; import java.io.PrintStream; -import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.WindowClosingProtocol; import javax.media.nativewindow.WindowClosingProtocol.WindowClosingMode; import javax.media.opengl.FPSCounter; import javax.media.opengl.GL; import javax.media.opengl.GLAnimatorControl; import javax.media.opengl.GLAutoDrawable; -import javax.media.opengl.GLAutoDrawableDelegate; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; @@ -49,6 +48,7 @@ import javax.media.opengl.GLProfile; import javax.media.opengl.GLRunnable; import com.jogamp.common.util.locks.RecursiveLock; +import com.jogamp.opengl.GLAutoDrawableDelegate; import com.jogamp.opengl.util.Animator; @@ -61,38 +61,36 @@ import com.jogamp.opengl.util.Animator; * @see GLWindow */ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { - public static final boolean DEBUG = Debug.debug("GLAutoDrawable"); + public static final boolean DEBUG = GLDrawableImpl.DEBUG; protected final GLDrawableHelper helper = new GLDrawableHelper(); protected final FPSCounterImpl fpsCounter = new FPSCounterImpl(); protected volatile GLDrawableImpl drawable; // volatile: avoid locking for read-only access protected GLContextImpl context; - protected final boolean ownDevice; + protected final boolean ownsDevice; protected int additionalCtxCreationFlags = 0; protected volatile boolean sendReshape = false; // volatile: maybe written by WindowManager thread w/o locking protected volatile boolean sendDestroy = false; // volatile: maybe written by WindowManager thread w/o locking /** - * @param drawable a valid {@link GLDrawableImpl}, may not be realized yet. - * @param context a valid {@link GLContextImpl}, may not be made current (created) yet. - * @param ownDevice pass true if {@link AbstractGraphicsDevice#close()} shall be issued, - * otherwise pass false. Closing the device is required in case - * the drawable is created w/ it's own new instance, e.g. offscreen drawables, - * and no further lifecycle handling is applied. + * @param drawable upstream {@link GLDrawableImpl} instance, may be null for lazy initialization + * @param context upstream {@link GLContextImpl} instance, may be null for lazy initialization + * @param ownsDevice pass true if {@link AbstractGraphicsDevice#close()} shall be issued, + * otherwise pass false. Closing the device is required in case + * the drawable is created w/ it's own new instance, e.g. offscreen drawables, + * and no further lifecycle handling is applied. */ - public GLAutoDrawableBase(GLDrawableImpl drawable, GLContextImpl context, boolean ownDevice) { + public GLAutoDrawableBase(GLDrawableImpl drawable, GLContextImpl context, boolean ownsDevice) { this.drawable = drawable; this.context = context; - this.ownDevice = ownDevice; + this.ownsDevice = ownsDevice; resetFPSCounter(); } + /** Returns the recursive lock object of the upstream implementation, which synchronizes multithreaded access. */ protected abstract RecursiveLock getLock(); - /** Returns the delegated GLDrawable */ - public final GLDrawable getDelegatedDrawable() { return drawable; } - /** Default implementation to handle repaint events from the windowing system */ protected final void defaultWindowRepaintOp() { final GLDrawable _drawable = drawable; @@ -103,29 +101,43 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { } } - /** Default implementation to handle resize events from the windowing system */ - protected final void defaultWindowResizedOp() { - final GLDrawable _drawable = drawable; + /** Default implementation to handle resize events from the windowing system. All required locks are being claimed. */ + protected final void defaultWindowResizedOp(int newWidth, int newHeight) throws NativeWindowException, GLException { + GLDrawableImpl _drawable = drawable; if( null!=_drawable ) { if(DEBUG) { - System.err.println("GLAutoDrawableBase.sizeChanged: ("+Thread.currentThread().getName()+"): "+getWidth()+"x"+getHeight()+" - surfaceHandle 0x"+Long.toHexString(getNativeSurface().getSurfaceHandle())); + System.err.println("GLAutoDrawableBase.sizeChanged: ("+Thread.currentThread().getName()+"): "+newWidth+"x"+newHeight+" - surfaceHandle 0x"+Long.toHexString(getNativeSurface().getSurfaceHandle())); + } + if( ! _drawable.getChosenGLCapabilities().isOnscreen() ) { + final RecursiveLock _lock = getLock(); + _lock.lock(); + try { + final GLDrawableImpl _drawableNew = GLDrawableHelper.resizeOffscreenDrawable(_drawable, context, newWidth, newHeight); + if(_drawable != _drawableNew) { + // write back + _drawable = _drawableNew; + drawable = _drawableNew; + } + } finally { + _lock.unlock(); + } } sendReshape = true; // async if display() doesn't get called below, but avoiding deadlock if( _drawable.isRealized() ) { if( !_drawable.getNativeSurface().isSurfaceLockedByOtherThread() && !helper.isAnimatorAnimating() ) { display(); } - } + } } } - + /** * Default implementation to handle destroy notifications from the windowing system. * *

      * If the {@link NativeSurface} does not implement {@link WindowClosingProtocol} * or {@link WindowClosingMode#DISPOSE_ON_CLOSE} is enabled (default), - * {@link #defaultDestroy()} is being called. + * a thread safe destruction is being induced. *

      */ protected final void defaultWindowDestroyNotifyOp() { @@ -174,7 +186,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { ctrl.resume(); } } else if (null != ns && ns.isSurfaceLockedByOtherThread()) { - // surface is locked by another thread + // Surface is locked by another thread. // Flag that destroy should be performed on the next // attempt to display. sendDestroy = true; // async, but avoiding deadlock @@ -225,7 +237,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { } _drawable.setRealized(false); } - if( ownDevice ) { + if( ownsDevice ) { _drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice().close(); } } @@ -238,7 +250,6 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { _lock.lock(); try { if(drawable!=null && context != null) { - drawable.swapBuffers(); helper.invokeGL(drawable, context, defaultSwapAction, defaultInitAction); } } finally { @@ -276,7 +287,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { destroy(); return; } - final RecursiveLock _lock = getLock(); + final RecursiveLock _lock = getLock(); _lock.lock(); try { if( null != context ) { @@ -294,6 +305,11 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { drawable.swapBuffers(); } } ; + @Override + public final GLDrawable getDelegatedDrawable() { + return drawable; + } + @Override public final GLContext getContext() { return context; @@ -305,7 +321,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { lock.lock(); try { final GLContext oldCtx = context; - final boolean newCtxCurrent = helper.switchContext(drawable, oldCtx, newCtx, additionalCtxCreationFlags); + final boolean newCtxCurrent = GLDrawableHelper.switchContext(drawable, oldCtx, newCtx, additionalCtxCreationFlags); context=(GLContextImpl)newCtx; if(newCtxCurrent) { context.makeCurrent(); @@ -529,4 +545,10 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { final GLDrawable _drawable = drawable; return null != _drawable ? _drawable.getHandle() : 0; } + + @Override + public String toString() { + return getClass().getSimpleName()+"[ \n\tHelper: " + helper + ", \n\tDrawable: " + drawable + + ", \n\tContext: " + context + /** ", \n\tWindow: "+window+ ", \n\tFactory: "+factory+ */ "]"; + } } diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index e82756022..050c619fd 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -47,6 +47,7 @@ import java.util.Map; import com.jogamp.common.os.DynamicLookupHelper; import com.jogamp.common.util.ReflectionUtil; +import com.jogamp.common.util.VersionNumber; import com.jogamp.gluegen.runtime.FunctionAddressResolver; import com.jogamp.gluegen.runtime.ProcAddressTable; import com.jogamp.gluegen.runtime.opengl.GLNameResolver; @@ -85,6 +86,7 @@ public abstract class GLContextImpl extends GLContext { private String glRenderer; private String glRendererLowerCase; + private String glVersion; // Tracks creation and initialization of buffer objects to avoid // repeated glGet calls upon glMapBuffer operations @@ -126,6 +128,9 @@ public abstract class GLContextImpl extends GLContext { GLContextShareSet.synchronizeBufferObjectSharing(shareWith, this); this.drawable = drawable; + if(null != drawable) { + drawable.associateContext(this, true); + } this.drawableRead = drawable; this.glDebugHandler = new GLDebugMessageHandler(this); @@ -205,8 +210,10 @@ public abstract class GLContextImpl extends GLContext { if(!setWriteOnly || drawableRead==drawable) { // if !setWriteOnly || !explicitReadDrawable drawableRead = (GLDrawableImpl) readWrite; } - final GLDrawable old = drawable; + final GLDrawableImpl old = drawable; + old.associateContext(this, false); drawable = (GLDrawableImpl) readWrite ; + drawable.associateContext(this, true); if(lockHeld) { makeCurrent(); } @@ -272,7 +279,7 @@ public abstract class GLContextImpl extends GLContext { if( actualRelease ) { if( !inDestruction ) { try { - drawable.contextMadeCurrent(this, false); + contextMadeCurrent(false); } catch (Throwable t) { drawableContextMadeCurrentException = t; } @@ -331,7 +338,8 @@ public abstract class GLContextImpl extends GLContext { makeCurrent(); } try { - drawable.contextRealized(this, false); + contextRealized(false); + drawable.associateContext(this, false); } catch (Throwable t) { drawableContextRealizedException = t; } @@ -514,19 +522,17 @@ public abstract class GLContextImpl extends GLContext { gl = gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Trace", null, gl, new Object[] { System.err } ) ); } - drawable.contextRealized(this, true); + contextRealized(true); if(DEBUG || TRACE_SWITCH) { System.err.println(getThreadName() +": GLContext.ContextSwitch: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+" - switch - CONTEXT_CURRENT_NEW - "+lock); } - } else { - drawable.contextMadeCurrent(this, true); - - if(TRACE_SWITCH) { - System.err.println(getThreadName() +": GLContext.ContextSwitch: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+" - switch - CONTEXT_CURRENT - "+lock); - } + } else if(TRACE_SWITCH) { + System.err.println(getThreadName() +": GLContext.ContextSwitch: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+" - switch - CONTEXT_CURRENT - "+lock); } + contextMadeCurrent(true); + /* FIXME: refactor dependence on Java 2D / JOGL bridge // Try cleaning up any stale server-side OpenGL objects @@ -608,6 +614,20 @@ public abstract class GLContextImpl extends GLContext { } protected abstract void makeCurrentImpl() throws GLException; + /** + * @see GLDrawableImpl#contextRealized(GLContext, boolean) + */ + protected void contextRealized(boolean realized) { + drawable.contextRealized(this, realized); + } + + /** + * @see GLDrawableImpl#contextMadeCurrent(GLContext, boolean) + */ + protected void contextMadeCurrent(boolean current) { + drawable.contextMadeCurrent(this, current); + } + /** * Platform dependent entry point for context creation.
      * @@ -934,52 +954,43 @@ public abstract class GLContextImpl extends GLContext { /** * If major > 0 || minor > 0 : Use passed values, determined at creation time - * If major==0 && minor == 0 : Use GL_VERSION * Otherwise .. don't touch .. */ private final void setContextVersion(int major, int minor, int ctp, boolean setVersionString) { - if (0==ctp) { + if ( 0 == ctp ) { throw new GLException("Invalid GL Version "+major+"."+minor+", ctp "+toHexString(ctp)); } - if(major>0 || minor>0) { - if (!GLContext.isValidGLVersion(major, minor)) { - GLException e = new GLException("Invalid GL Version "+major+"."+minor+", ctp "+toHexString(ctp)); - throw e; - } - ctxMajorVersion = major; - ctxMinorVersion = minor; - ctxOptions = ctp; - if(setVersionString) { - ctxVersionString = getGLVersion(ctxMajorVersion, ctxMinorVersion, ctxOptions, getGL().glGetString(GL.GL_VERSION)); - } - return; + + if (!GLContext.isValidGLVersion(major, minor)) { + throw new GLException("Invalid GL Version "+major+"."+minor+", ctp "+toHexString(ctp)); } - - if(major==0 && minor==0) { - String versionStr = getGL().glGetString(GL.GL_VERSION); - if(null==versionStr) { - throw new GLException("GL_VERSION is NULL: "+this); - } - ctxOptions = ctp; - - // Set version - GLVersionNumber version = new GLVersionNumber(versionStr); + ctxMajorVersion = major; + ctxMinorVersion = minor; + ctxOptions = ctp; + if(setVersionString) { + ctxVersionString = getGLVersion(ctxMajorVersion, ctxMinorVersion, ctxOptions, getGL().glGetString(GL.GL_VERSION)); + } + } + + private static final VersionNumber getGLVersionNumber(int ctp, String glVersionStr) { + if( null != glVersionStr ) { + final GLVersionNumber version = new GLVersionNumber(glVersionStr); if (version.isValid()) { - ctxMajorVersion = version.getMajor(); - ctxMinorVersion = version.getMinor(); - // We cannot promote a non ARB context to >= 3.1, - // reduce it to 3.0 then. - if ( ( ctxMajorVersion>3 || ctxMajorVersion==3 && ctxMinorVersion>=1 ) - && 0 == (ctxOptions & CTX_IS_ARB_CREATED) ) { - ctxMajorVersion = 3; - ctxMinorVersion = 0; - } - if(setVersionString) { - ctxVersionString = getGLVersion(ctxMajorVersion, ctxMinorVersion, ctxOptions, versionStr); - } - return; + int major = version.getMajor(); + int minor = version.getMinor(); + // We cannot promote a non ARB context to >= 3.1, + // reduce it to 3.0 then. + if ( 0 == (ctp & CTX_IS_ARB_CREATED) && + ( major > 3 || major == 3 && minor >= 1 ) ) { + major = 3; + minor = 0; + } + if ( GLContext.isValidGLVersion(major, minor) ) { + return new VersionNumber(major, minor, 0); + } } } + return null; } //---------------------------------------------------------------------- @@ -1019,14 +1030,18 @@ public abstract class GLContextImpl extends GLContext { /** * Pbuffer support; given that this is a GLContext associated with a * pbuffer, binds this pbuffer to its texture target. + * @throws GLException if not implemented (default) + * @deprecated use FBO/GLOffscreenAutoDrawable instead of pbuffer */ - public abstract void bindPbufferToTexture(); + public void bindPbufferToTexture() { throw new GLException("not implemented"); } /** * Pbuffer support; given that this is a GLContext associated with a * pbuffer, releases this pbuffer from its texture target. + * @throws GLException if not implemented (default) + * @deprecated use FBO/GLOffscreenAutoDrawable instead of pbuffer */ - public abstract void releasePbufferFromTexture(); + public void releasePbufferFromTexture() { throw new GLException("not implemented"); } public abstract ByteBuffer glAllocateMemoryNV(int arg0, float arg1, float arg2, float arg3); @@ -1064,7 +1079,7 @@ public abstract class GLContextImpl extends GLContext { table.reset(getDrawableImpl().getGLDynamicLookupHelper() ); } - private final boolean initGLRendererStrings() { + private final boolean initGLRendererAndGLVersionStrings() { final GLDynamicLookupHelper glDynLookupHelper = getDrawableImpl().getGLDynamicLookupHelper(); final long _glGetString = glDynLookupHelper.dynamicLookupFunction("glGetString"); if(0 == _glGetString) { @@ -1083,14 +1098,27 @@ public abstract class GLContextImpl extends GLContext { Thread.dumpStack(); } return false; - } else { - glRenderer = _glRenderer; - glRendererLowerCase = glRenderer.toLowerCase(); - return true; } + glRenderer = _glRenderer; + glRendererLowerCase = glRenderer.toLowerCase(); + + final String _glVersion = glGetStringInt(GL.GL_VERSION, _glGetString); + if(null == _glVersion) { + // FIXME + if(DEBUG) { + System.err.println("Warning: GL_VERSION is NULL."); + Thread.dumpStack(); + } + return false; + } + glVersion = _glVersion; + return true; } } + protected final String getGLVersionString() { + return glVersion; + } protected final String getGLRendererString(boolean lowerCase) { return lowerCase ? glRendererLowerCase : glRenderer; } @@ -1128,17 +1156,44 @@ public abstract class GLContextImpl extends GLContext { final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); - if( !initGLRendererStrings() && DEBUG) { - System.err.println("Warning: intialization of GL renderer strings failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); + { + final boolean initGLRendererAndGLVersionStringsOK = initGLRendererAndGLVersionStrings(); + if(DEBUG) { + if( !initGLRendererAndGLVersionStringsOK ) { + System.err.println("Warning: setGLFunctionAvailability: intialization of GL renderer strings failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); + } else { + System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Given "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); + } + } } if(!isCurrentContextHardwareRasterizer()) { ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT; } - + + // Pick the version from the GL-version string, + // if smaller _or_ given major == 0. + final VersionNumber glVersionNumber; + { + final VersionNumber setGLVersionNumber = new VersionNumber(major, minor, 0); + final VersionNumber strGLVersionNumber = getGLVersionNumber(ctxProfileBits, glVersion); + if( null != strGLVersionNumber && ( strGLVersionNumber.compareTo(setGLVersionNumber) <= 0 || 0 == major ) ) { + glVersionNumber = strGLVersionNumber; + major = glVersionNumber.getMajor(); + minor = glVersionNumber.getMinor(); + } else { + glVersionNumber = setGLVersionNumber; + } + } + if ( !GLContext.isValidGLVersion(major, minor) ) { + throw new GLException("Invalid GL Version "+major+"."+minor+", ctp "+toHexString(ctxProfileBits)+", "+glVersion+", "+glVersionNumber); + } + if( 2 > major ) { // there is no ES2-compat for a profile w/ major < 2 + ctxProfileBits &= ~GLContext.CTX_IMPL_ES2_COMPAT; + } contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits); if (DEBUG) { - System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.0 FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); + System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.0 validated FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion) + ", "+glVersionNumber); } // @@ -1201,6 +1256,10 @@ public abstract class GLContextImpl extends GLContext { ctxProfileBits |= CTX_IMPL_FBO; } + if(FORCE_NO_FBO_SUPPORT) { + ctxProfileBits &= ~CTX_IMPL_FBO ; + } + // // Set GL Version (complete w/ version string) // diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index e1e253d35..4f965f620 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -48,18 +48,21 @@ import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.OffscreenLayerSurface; import javax.media.nativewindow.ProxySurface; import javax.media.nativewindow.MutableSurface; -import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; -import javax.media.opengl.GLCapabilities; +import javax.media.nativewindow.UpstreamSurfaceHook; import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; +import javax.media.opengl.GLFBODrawable; +import javax.media.opengl.GLOffscreenAutoDrawable; import javax.media.opengl.GLPbuffer; import javax.media.opengl.GLProfile; import com.jogamp.nativewindow.MutableGraphicsConfiguration; +import com.jogamp.nativewindow.DelegatedUpstreamSurfaceHookWithSurfaceSize; +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; /** Extends GLDrawableFactory with a few methods for handling @@ -67,6 +70,7 @@ import com.jogamp.nativewindow.MutableGraphicsConfiguration; Independent Bitmaps on Windows, pixmaps on X11). Direct access to these GLDrawables is not supplied directly to end users, though they may be instantiated by the GLJPanel implementation. */ +@SuppressWarnings("deprecation") public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { protected static final boolean DEBUG = GLDrawableImpl.DEBUG; @@ -141,55 +145,53 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(target, true); if(null != ols) { // layered surface -> Offscreen/[FBO|PBuffer] - final GLCapabilities chosenCapsMod = (GLCapabilities) chosenCaps.cloneMutable(); - chosenCapsMod.setOnscreen(false); - chosenCapsMod.setDoubleBuffered(false); - /* if( isFBOAvailable ) { // FIXME JAU: FBO n/a yet - chosenCapsMod.setFBO(true); - } else */ - if( canCreateGLPbuffer(adevice) ) { - chosenCapsMod.setPBuffer(true); - } else { - chosenCapsMod.setFBO(false); - chosenCapsMod.setPBuffer(false); + final boolean isPbufferAvailable = canCreateGLPbuffer(adevice) ; + if(!isPbufferAvailable && !isFBOAvailable) { + throw new GLException("Neither FBO nor Pbuffer is available for "+target); } + final GLCapabilitiesImmutable chosenCapsMod = GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(chosenCaps, isFBOAvailable, isPbufferAvailable); config.setChosenCapabilities(chosenCapsMod); + ols.setChosenCapabilities(chosenCapsMod); if(DEBUG) { - System.err.println("GLDrawableFactoryImpl.createGLDrawable -> OnscreenDrawable -> Offscreen-Layer: "+target); + System.err.println("GLDrawableFactoryImpl.createGLDrawable -> OnscreenDrawable -> Offscreen-Layer"); + System.err.println("chosenCaps: "+chosenCaps); + System.err.println("chosenCapsMod: "+chosenCapsMod); + System.err.println("OffscreenLayerSurface: **** "+ols); + System.err.println("Target: **** "+target); + Thread.dumpStack(); } if( ! ( target instanceof MutableSurface ) ) { throw new IllegalArgumentException("Passed NativeSurface must implement SurfaceChangeable for offscreen layered surface: "+target); } - if( ((GLCapabilitiesImmutable)config.getRequestedCapabilities()).isFBO() && isFBOAvailable ) { - // FIXME JAU: Need to revise passed MutableSurface to work w/ FBO .. - final GLDrawableImpl dummyDrawable = createOnscreenDrawableImpl(target); - result = new GLFBODrawableImpl(this, dummyDrawable, target, target.getWidth(), target.getHeight(), 0 /* textureUnit */); + if( chosenCapsMod.isFBO() && isFBOAvailable ) { + // target surface is already a native one + result = createFBODrawableImpl(target, chosenCapsMod, 0); } else { result = createOffscreenDrawableImpl(target); } } else if(chosenCaps.isOnscreen()) { // onscreen + final GLCapabilitiesImmutable chosenCapsMod = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(chosenCaps); + config.setChosenCapabilities(chosenCapsMod); if(DEBUG) { System.err.println("GLDrawableFactoryImpl.createGLDrawable -> OnscreenDrawable: "+target); } result = createOnscreenDrawableImpl(target); } else { // offscreen - final GLCapabilitiesImmutable reqCaps = (GLCapabilitiesImmutable)config.getRequestedCapabilities(); if(DEBUG) { - System.err.println("GLDrawableFactoryImpl.createGLDrawable -> OffScreenDrawable, FBO req / chosen - avail, PBuffer: "+reqCaps.isFBO()+" / "+chosenCaps.isFBO()+" - "+isFBOAvailable+", "+chosenCaps.isPBuffer()+": "+target); + System.err.println("GLDrawableFactoryImpl.createGLDrawable -> OffScreenDrawable, FBO chosen / avail, PBuffer: "+ + chosenCaps.isFBO()+" / "+isFBOAvailable+", "+chosenCaps.isPBuffer()+": "+target); } if( ! ( target instanceof MutableSurface ) ) { - throw new IllegalArgumentException("Passed NativeSurface must implement SurfaceChangeable for offscreen: "+target); + throw new IllegalArgumentException("Passed NativeSurface must implement MutableSurface for offscreen: "+target); } - if( reqCaps.isFBO() && isFBOAvailable ) { - // FIXME JAU: Need to revise passed MutableSurface to work w/ FBO .. - final GLDrawableImpl dummyDrawable = createOnscreenDrawableImpl(target); - result = new GLFBODrawableImpl(this, dummyDrawable, target, target.getWidth(), target.getHeight(), 0 /* textureUnit */); + if( chosenCaps.isFBO() && isFBOAvailable ) { + // need to hook-up a native dummy surface since source may not have + final ProxySurface dummySurface = createDummySurfaceImpl(adevice, true, chosenCaps, null, 64, 64); + dummySurface.setUpstreamSurfaceHook(new DelegatedUpstreamSurfaceHookWithSurfaceSize(dummySurface.getUpstreamSurfaceHook(), target)); + result = createFBODrawableImpl(dummySurface, chosenCaps, 0); } else { - final GLCapabilities chosenCapsMod = (GLCapabilities) chosenCaps.cloneMutable(); - chosenCapsMod.setDoubleBuffered(false); - config.setChosenCapabilities(chosenCapsMod); result = createOffscreenDrawableImpl(target); } } @@ -211,7 +213,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { //--------------------------------------------------------------------------- // - // PBuffer Offscreen GLDrawable construction + // PBuffer Offscreen GLAutoDrawable construction // @Override @@ -239,7 +241,8 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { GLDrawableImpl drawable = null; device.lock(); try { - drawable = (GLDrawableImpl) createGLDrawable( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, width, height, null) ); + drawable = createOffscreenDrawableImpl( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, + new UpstreamSurfaceHookMutableSize(width, height) ) ); if(null != drawable) { drawable.setRealized(true); } @@ -247,10 +250,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { device.unlock(); } - if(null==drawable) { - throw new GLException("Could not create Pbuffer drawable for: "+device+", "+capsChosen+", "+width+"x"+height); - } - return new GLPbufferImpl( drawable, shareWith, true); + return new GLPbufferImpl( drawable, (GLContextImpl) drawable.createContext(shareWith) ); } //--------------------------------------------------------------------------- @@ -258,6 +258,29 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { // 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, @@ -274,10 +297,13 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { final GLCapabilitiesImmutable capsChosen = GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(capsRequested, GLContext.isFBOAvailable(device, capsRequested.getGLProfile()), canCreateGLPbuffer(device)); + if( capsChosen.isFBO() ) { device.lock(); try { - return createFBODrawableImpl(device, capsRequested, chooser, width, height); + final ProxySurface dummySurface = createDummySurfaceImpl(device, true, capsRequested, null, width, height); + final GLDrawableImpl dummyDrawable = createOnscreenDrawableImpl(dummySurface); + return new GLFBODrawableImpl.ResizeableImpl(this, dummyDrawable, dummySurface, capsChosen, 0); } finally { device.unlock(); } @@ -285,20 +311,17 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { device.lock(); try { - return createOffscreenDrawableImpl( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, width, height, null) ); + return createOffscreenDrawableImpl( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, + new UpstreamSurfaceHookMutableSize(width, height) ) ); } finally { device.unlock(); } } - /** Creates a platform independent offscreen FBO GLDrawable implementation */ - protected GLDrawable createFBODrawableImpl(AbstractGraphicsDevice device, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, - int initialWidth, int initialHeight) { - final GLCapabilitiesImmutable dummyCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(requestedCaps); - final NativeSurface dummySurface = createDummySurfaceImpl(device, true, dummyCaps, null, 64, 64); + /** Creates a platform independent FBO offscreen GLDrawable */ + protected GLFBODrawable createFBODrawableImpl(NativeSurface dummySurface, GLCapabilitiesImmutable fboCaps, int textureUnit) { final GLDrawableImpl dummyDrawable = createOnscreenDrawableImpl(dummySurface); - - return new GLFBODrawableImpl(this, dummyDrawable, dummySurface, initialWidth, initialHeight, 0 /* textureUnit */); + return new GLFBODrawableImpl(this, dummyDrawable, dummySurface, fboCaps, textureUnit); } /** Creates a platform dependent offscreen pbuffer/pixmap GLDrawable implementation */ @@ -318,15 +341,13 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { * @param capsChosen * @param capsRequested * @param chooser the custom chooser, may be null for default - * @param width the initial width - * @param height the initial height - * @param lifecycleHook optional control of the surface's lifecycle + * @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, int width, int height, UpstreamSurfaceHook lifecycleHook); + GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook); /** * A dummy surface is not visible on screen and will not be used to render directly to, @@ -341,9 +362,9 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { * @param width the initial width * @param height the initial height * - * @return the created {@link MutableSurface} instance w/o defined surface handle + * @return the created {@link ProxySurface} instance w/o defined surface handle but platform specific {@link UpstreamSurfaceHook}. */ - public NativeSurface createDummySurface(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, + public ProxySurface createDummySurface(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { final AbstractGraphicsDevice device = getOrCreateSharedDevice(deviceReq); if(null == device) { @@ -369,9 +390,11 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { * otherwise device instance is used as-is. * @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 MutableSurface} instance w/o defined surface handle + * @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 requestedCaps, GLCapabilitiesChooser chooser, int width, int height); diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java index 090c5fe69..bdf0b6d74 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java @@ -43,12 +43,19 @@ package jogamp.opengl; import java.util.ArrayList; import java.util.HashSet; +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; import javax.media.opengl.GLAnimatorControl; import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLException; +import javax.media.opengl.GLFBODrawable; import javax.media.opengl.GLRunnable; import com.jogamp.opengl.util.Animator; @@ -108,24 +115,27 @@ public class GLDrawableHelper { /** * Associate a new context to the drawable and also propagates the context/drawable switch by * calling {@link GLContext#setGLDrawable(GLDrawable, boolean) newCtx.setGLDrawable(drawable, true);}. - *

      - * If the old context's drawable was an {@link GLAutoDrawable}, it's reference to the given drawable - * is being cleared by calling - * {@link GLAutoDrawable#setContext(GLContext) ((GLAutoDrawable)oldCtx.getGLDrawable()).setContext(null)}. - *

      *

      * If the old or new context was current on this thread, it is being released before switching the drawable. *

      + *

      + * Be aware that the old context is still bound to the drawable, + * and that one context can only bound to one drawable at one time! + *

      + *

      + * No locking is being performed on the drawable, caller is required to take care of it. + *

      * * @param drawable the drawable which context is changed - * @param newCtx the new context * @param oldCtx the old context - * @return true if the newt context was current, otherwise false + * @param newCtx the new context + * @param newCtxCreationFlags additional creation flags if newCtx is not null and not been created yet, see {@link GLContext#setContextCreationFlags(int)} + * @return true if the new context was current, otherwise false * * @see GLAutoDrawable#setContext(GLContext) */ - public final boolean switchContext(GLDrawable drawable, GLContext oldCtx, GLContext newCtx, int additionalCtxCreationFlags) { - if(null != oldCtx && oldCtx.isCurrent()) { + public static final boolean switchContext(GLDrawable drawable, GLContext oldCtx, GLContext newCtx, int newCtxCreationFlags) { + if( null != oldCtx && oldCtx.isCurrent() ) { oldCtx.release(); } final boolean newCtxCurrent; @@ -134,17 +144,135 @@ public class GLDrawableHelper { if(newCtxCurrent) { newCtx.release(); } - newCtx.setContextCreationFlags(additionalCtxCreationFlags); + newCtx.setContextCreationFlags(newCtxCreationFlags); newCtx.setGLDrawable(drawable, true); // propagate context/drawable switch } else { newCtxCurrent = false; } - if(null!=oldCtx && oldCtx.getGLDrawable() instanceof GLAutoDrawable) { - ((GLAutoDrawable)oldCtx.getGLDrawable()).setContext(null); - } return newCtxCurrent; } + /** + * If the drawable is not realized, OP is a NOP. + *
        + *
      • release context if current
      • + *
      • destroy old drawable
      • + *
      • create new drawable
      • + *
      • attach new drawable to context
      • + *
      • make context current, if it was current
      • + *
      + *

      + * No locking is being performed, caller is required to take care of it. + *

      + * + * @param drawable + * @param context maybe null + * @return the new drawable + */ + public static final GLDrawableImpl recreateGLDrawable(GLDrawableImpl drawable, GLContext context) { + if( ! drawable.isRealized() ) { + return drawable; + } + final boolean contextCurrent = null != context && context.isCurrent(); + final GLDrawableFactory factory = drawable.getFactory(); + final NativeSurface surface = drawable.getNativeSurface(); + final ProxySurface proxySurface = (surface instanceof ProxySurface) ? (ProxySurface)surface : null; + + if(contextCurrent) { + context.release(); + } + + if(null != proxySurface) { + proxySurface.enableUpstreamSurfaceHookLifecycle(false); + } + try { + drawable.setRealized(false); + drawable = (GLDrawableImpl) factory.createGLDrawable(surface); // [2] + drawable.setRealized(true); + } finally { + if(null != proxySurface) { + proxySurface.enableUpstreamSurfaceHookLifecycle(true); + } + } + + if(null != context) { + context.setGLDrawable(drawable, true); // re-association + } + + if(contextCurrent) { + context.makeCurrent(); + } + return drawable; + } + + /** + * Performs resize operation on the given drawable, assuming it is offscreen. + *

      + * The {@link GLDrawableImpl}'s {@link NativeSurface} is being locked during operation. + * In case the holder is an auto drawable or similar, it's lock shall be claimed by the caller. + *

      + *

      + * May recreate the drawable via {@link #recreateGLDrawable(GLDrawableImpl, GLContext)} + * in case of a a pbuffer- or pixmap-drawable. + *

      + *

      + * FBO drawables are resized w/o drawable destruction. + *

      + *

      + * Offscreen resize operation is validated w/ drawable size in the end. + * An exception is thrown if not successful. + *

      + * + * @param drawable + * @param context + * @param newWidth the new width, it's minimum is capped to 1 + * @param newHeight the new height, it's minimum is capped to 1 + * @return the new drawable in case of an pbuffer/pixmap drawable, otherwise the passed drawable is being returned. + * @throws NativeWindowException is drawable is not offscreen or it's surface lock couldn't be claimed + * @throws GLException may be thrown a resize operation + */ + public static final GLDrawableImpl resizeOffscreenDrawable(GLDrawableImpl drawable, GLContext context, int newWidth, int newHeight) + throws NativeWindowException, GLException + { + if(drawable.getChosenGLCapabilities().isOnscreen()) { + throw new NativeWindowException("Drawable is not offscreen: "+drawable); + } + final NativeSurface ns = drawable.getNativeSurface(); + final int lockRes = ns.lockSurface(); + if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { + throw new NativeWindowException("Could not lock surface of drawable: "+drawable); + } + try { + if(0>=newWidth) { newWidth = 1; } + if(0>=newHeight) { newHeight = 1; } + // propagate new size + if(ns instanceof ProxySurface) { + final ProxySurface ps = (ProxySurface) ns; + final UpstreamSurfaceHook ush = ps.getUpstreamSurfaceHook(); + if(ush instanceof UpstreamSurfaceHook.MutableSize) { + ((UpstreamSurfaceHook.MutableSize)ush).setSize(newWidth, newHeight); + } else if(DEBUG) { // we have to assume UpstreamSurfaceHook contains the new size already, hence size check @ bottom + System.err.println("GLDrawableHelper.resizeOffscreenDrawable: Drawable's offscreen ProxySurface n.a. UpstreamSurfaceHook.MutableSize, but "+ush.getClass().getName()+": "+ush); + } + } else if(DEBUG) { // we have to assume surface contains the new size already, hence size check @ bottom + System.err.println("GLDrawableHelper.resizeOffscreenDrawable: Drawable's offscreen surface n.a. ProxySurface, but "+ns.getClass().getName()+": "+ns); + } + if(drawable instanceof GLFBODrawable) { + if( null != context && context.isCreated() ) { + ((GLFBODrawable) drawable).resetSize(context.getGL()); + } + } else { + drawable = GLDrawableHelper.recreateGLDrawable(drawable, context); + } + } finally { + ns.unlockSurface(); + } + if(drawable.getWidth() != newWidth || drawable.getHeight() != newHeight) { + throw new InternalError("Incomplete resize operation: expected "+newWidth+"x"+newHeight+", has: "+drawable); + } + return drawable; + } + public final void addGLEventListener(GLEventListener listener) { addGLEventListener(-1, listener); } @@ -196,15 +324,11 @@ public class GLDrawableHelper { } } - private final 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 */, false /* checkInit */); - } - return true; + private final void init(GLEventListener l, GLAutoDrawable drawable, boolean sendReshape) { + l.init(drawable); + if(sendReshape) { + reshape(l, drawable, 0, 0, drawable.getWidth(), drawable.getHeight(), true /* setViewport */, false /* checkInit */); } - return false; } /** The default init action to be called once after ctx is being created @ 1st makeCurrent(). */ @@ -214,14 +338,11 @@ public class GLDrawableHelper { 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. + // If make ctx current, 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, true /* sendReshape */) ) { - throw new GLException("GLEventListener "+listener+" already initialized: "+drawable); - } + // hence it must be called unconditional, always. + listenersToBeInit.remove(listener); // remove if exist, avoiding dbl init + init( listener, drawable, true /* sendReshape */); } } } @@ -239,7 +360,9 @@ public class GLDrawableHelper { 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 /* sendReshape */) ; + if( listenersToBeInit.remove(listener) ) { + init( listener, drawable, true /* sendReshape */) ; + } listener.display(drawable); } } @@ -251,7 +374,9 @@ public class GLDrawableHelper { // GLEventListener may need to be init, // in case this one is added after the realization of the GLAutoDrawable synchronized(listenersLock) { - init( listener, drawable, false /* sendReshape */) ; + if( listenersToBeInit.remove(listener) ) { + init( listener, drawable, false /* sendReshape */) ; + } } } if(setViewport) { diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java index abf2bf557..311690f1d 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java @@ -43,6 +43,7 @@ package jogamp.opengl; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.ProxySurface; +import javax.media.opengl.GL; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; @@ -76,31 +77,46 @@ public abstract class GLDrawableImpl implements GLDrawable { if( !realized ) { return; // destroyed already } - final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable)surface.getGraphicsConfiguration().getChosenCapabilities(); - if ( caps.getDoubleBuffered() ) { - if(!surface.surfaceSwap()) { - int lockRes = lockSurface(); // it's recursive, so it's ok within [makeCurrent .. release] - if (NativeSurface.LOCK_SURFACE_NOT_READY == lockRes) { - return; + int lockRes = lockSurface(); // it's recursive, so it's ok within [makeCurrent .. release] + if (NativeSurface.LOCK_SURFACE_NOT_READY == lockRes) { + return; + } + try { + if (NativeSurface.LOCK_SURFACE_CHANGED == lockRes) { + updateHandle(); + } + final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable)surface.getGraphicsConfiguration().getChosenCapabilities(); + if ( caps.getDoubleBuffered() ) { + if(!surface.surfaceSwap()) { + swapBuffersImpl(true); } - try { - if (NativeSurface.LOCK_SURFACE_CHANGED == lockRes) { - updateHandle(); - } - swapBuffersImpl(); - } finally { - unlockSurface(); + } else { + final GLContext ctx = GLContext.getCurrent(); + if(null!=ctx && ctx.getGLDrawable()==this) { + ctx.getGL().glFlush(); } + swapBuffersImpl(false); } - } else { - GLContext ctx = GLContext.getCurrent(); - if(null!=ctx && ctx.getGLDrawable()==this) { - ctx.getGL().glFinish(); - } - } + } finally { + unlockSurface(); + } surface.surfaceUpdated(this, surface, System.currentTimeMillis()); } - protected abstract void swapBuffersImpl(); + + /** + * Platform and implementation depending surface swap. + *

      The surface is locked.

      + *

      + * If doubleBuffered is true, + * an actual platform dependent surface swap shall be executed. + *

      + *

      + * If doubleBuffered is false, + * {@link GL#glFlush()} has been called already and + * the implementation may execute implementation specific code. + *

      + */ + protected abstract void swapBuffersImpl(boolean doubleBuffered); public final static String toHexString(long hex) { return "0x" + Long.toHexString(hex); @@ -181,6 +197,9 @@ public abstract class GLDrawableImpl implements GLDrawable { System.err.println(getThreadName() + ": setRealized: "+getClass().getName()+" "+this.realized+" == "+realizedArg); } } + /** + * Platform specific realization of drawable + */ protected abstract void setRealizedImpl(); /** @@ -189,7 +208,7 @@ public abstract class GLDrawableImpl implements GLDrawable { * If realized is true, the context has just been created and made current. *

      *

      - * If realized is false, the context is still current and will be release and destroyed after this method returns. + * If realized is false, the context is still current and will be released and destroyed after this method returns. *

      *

      * @see #contextMadeCurrent(GLContext, boolean) @@ -199,18 +218,27 @@ public abstract class GLDrawableImpl implements GLDrawable { /** * Callback for special implementations, allowing GLContext to trigger GL related lifecycle: makeCurrent, release. *

      - * Will not be called if {@link #contextRealized(GLContext, boolean)} has been triggered. - *

      - *

      * If current is true, the context has just been made current. *

      *

      * If current is false, the context is still current and will be release after this method returns. *

      + *

      + * Note: Will also be called after {@link #contextRealized(GLContext, boolean) contextRealized(ctx, true)} + * but not at context destruction, i.e. {@link #contextRealized(GLContext, boolean) contextRealized(ctx, false)}. + *

      * @see #contextRealized(GLContext, boolean) */ protected void contextMadeCurrent(GLContext glc, boolean current) { } + /** + * Callback for special implementations, allowing to associate bound context to this drawable (bound == true) + * or to remove such association (bound == false). + * @param ctx the just bounded or unbounded context + * @param bound if true create an association, otherwise remove it + */ + protected void associateContext(GLContext ctx, boolean bound) { } + /** Callback for special implementations, allowing GLContext to fetch a custom default render framebuffer. Defaults to zero.*/ protected int getDefaultDrawFramebuffer() { return 0; } /** Callback for special implementations, allowing GLContext to fetch a custom default read framebuffer. Defaults to zero. */ @@ -245,8 +273,8 @@ public abstract class GLDrawableImpl implements GLDrawable { public String toString() { return getClass().getSimpleName()+"[Realized "+isRealized()+ ",\n\tFactory "+getFactory()+ - ",\n\thandle "+toHexString(getHandle())+ - ",\n\tWindow "+getNativeSurface()+"]"; + ",\n\tHandle "+toHexString(getHandle())+ + ",\n\tSurface "+getNativeSurface()+"]"; } protected static String getThreadName() { diff --git a/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java index 03bc26cbc..de45466f3 100644 --- a/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java @@ -1,142 +1,476 @@ package jogamp.opengl; import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; import javax.media.opengl.GL; -import javax.media.opengl.GL2GL3; +import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLException; +import javax.media.opengl.GLFBODrawable; import com.jogamp.nativewindow.MutableGraphicsConfiguration; import com.jogamp.opengl.FBObject; import com.jogamp.opengl.FBObject.Attachment; +import com.jogamp.opengl.FBObject.Colorbuffer; import com.jogamp.opengl.FBObject.TextureAttachment; /** - * Offscreen GLDrawable implementation using framebuffer object (FBO) - * as it's offscreen rendering mechanism. + * {@link FBObject} offscreen GLDrawable implementation, i.e. {@link GLFBODrawable}. + *

      + * It utilizes the context lifecycle hook {@link #contextRealized(GLContext, boolean)} + * to initialize the {@link FBObject} instance. + *

      + *

      + * It utilizes the context current hook {@link #contextMadeCurrent(GLContext, boolean) contextMadeCurrent(context, true)} + * to {@link FBObject#bind(GL) bind} the FBO. + *

      + * See {@link GLFBODrawable} for double buffering details. * * @see GLDrawableImpl#contextRealized(GLContext, boolean) * @see GLDrawableImpl#contextMadeCurrent(GLContext, boolean) * @see GLDrawableImpl#getDefaultDrawFramebuffer() * @see GLDrawableImpl#getDefaultReadFramebuffer() */ -public class GLFBODrawableImpl extends GLDrawableImpl { - final GLDrawableImpl parent; - final FBObject fbo; - int texUnit; - int samplesTexUnit = 0; - int width=0, height=0, samples=0; - - protected GLFBODrawableImpl(GLDrawableFactoryImpl factory, GLDrawableImpl parent, - NativeSurface surface, int initialWidth, int initialHeight, int textureUnit) { +public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { + protected static final boolean DEBUG = GLDrawableImpl.DEBUG || Debug.debug("FBObject"); + + private final GLDrawableImpl parent; + + private boolean initialized; + private int texUnit; + private int samples; + + private FBObject[] fbos; + private int fboIBack; // points to GL_BACK buffer + private int fboIFront; // points to GL_FRONT buffer + private FBObject pendingFBOReset = null; + private boolean fboBound; + private static final int bufferCount = 2; // number of FBOs for double buffering. TODO: Possible to configure! + + // private DoubleBufferMode doubleBufferMode; // TODO: Add or remove TEXTURE (only) DoubleBufferMode support + + private SwapBufferContext swapBufferContext; + + public static interface SwapBufferContext { + public void swapBuffers(boolean doubleBuffered); + } + + protected GLFBODrawableImpl(GLDrawableFactoryImpl factory, GLDrawableImpl parent, NativeSurface surface, + GLCapabilitiesImmutable fboCaps, int textureUnit) { super(factory, surface, false); + this.initialized = false; + + // Replace the chosen caps of dummy-surface w/ it's clone and copied values of orig FBO caps request. + // The dummy-surface has already been configured, hence value replace is OK + // and due to cloning, the native GLCapability portion is being preserved. + final MutableGraphicsConfiguration msConfig = (MutableGraphicsConfiguration) surface.getGraphicsConfiguration(); + final GLCapabilities fboCapsNative = (GLCapabilities) msConfig.getChosenCapabilities().cloneMutable(); + fboCapsNative.copyFrom(fboCaps); + msConfig.setChosenCapabilities(fboCapsNative); + this.parent = parent; this.texUnit = textureUnit; - final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) surface.getGraphicsConfiguration().getChosenCapabilities(); - this.width = initialWidth; - this.height = initialHeight; - this.samples = caps.getNumSamples(); - this.fbo = new FBObject(); + this.samples = fboCaps.getNumSamples(); + + // default .. // TODO: Add or remove TEXTURE (only) DoubleBufferMode support + // this.doubleBufferMode = ( samples > 0 || fboCaps.getDoubleBuffered() ) ? DoubleBufferMode.FBO : DoubleBufferMode.NONE ; + + this.swapBufferContext = null; } - @Override - protected void contextRealized(GLContext glc, boolean realized) { - final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) surface.getGraphicsConfiguration().getChosenCapabilities(); - final GL gl = glc.getGL(); - if(realized) { - fbo.reset(gl, width, height, samples); - samples = fbo.getNumSamples(); // update, maybe capped + private final void initialize(boolean realize, GL gl) { + if(realize) { + final int maxSamples = gl.getMaxRenderbufferSamples(); + samples = samples <= maxSamples ? samples : maxSamples; + + final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) surface.getGraphicsConfiguration().getChosenCapabilities(); + final int fbosN; if(samples > 0) { - fbo.attachColorbuffer(gl, 0, caps.getAlphaBits()>0); + fbosN = 1; + } else if( caps.getDoubleBuffered() ) { + fbosN = bufferCount; } else { - fbo.attachTexture2D(gl, 0, caps.getAlphaBits()>0); + fbosN = 1; } - if( caps.getStencilBits() > 0 ) { - fbo.attachRenderbuffer(gl, Attachment.Type.DEPTH_STENCIL, 24); - } else { - fbo.attachRenderbuffer(gl, Attachment.Type.DEPTH, 24); + + fbos = new FBObject[fbosN]; + fboIBack = 0; // head + fboIFront = fbos.length - 1; // tail + + for(int i=0; i 0) { + fbos[i].attachColorbuffer(gl, 0, caps.getAlphaBits()>0); + } else { + fbos[i].attachTexture2D(gl, 0, caps.getAlphaBits()>0); + } + if( caps.getStencilBits() > 0 ) { + fbos[i].attachRenderbuffer(gl, Attachment.Type.DEPTH_STENCIL, 24); + } else { + fbos[i].attachRenderbuffer(gl, Attachment.Type.DEPTH, 24); + } } - } else if(null != fbo) { - fbo.destroy(gl); - } - } - - @Override - protected void contextMadeCurrent(GLContext glc, boolean current) { - final GL gl = glc.getGL(); - if(current) { - fbo.bind(gl); + fbos[fboIFront].syncFramebuffer(gl); + fboBound = false; + final GLCapabilities fboCapsNative = (GLCapabilities) surface.getGraphicsConfiguration().getChosenCapabilities(); + fbos[0].formatToGLCapabilities(fboCapsNative); + fboCapsNative.setDoubleBuffered( fboCapsNative.getDoubleBuffered() || samples > 0 ); + + initialized = true; } else { - fbo.unbind(gl); - final TextureAttachment attachment = samples > 0 ? fbo.getSamplingSink() : (TextureAttachment) fbo.getColorbuffer(0) ; - if(null == attachment) { - throw new GLException("Null texture colorbuffer, samples "+samples+", "+fbo.toString()); - } - gl.glActiveTexture(GL.GL_TEXTURE0 + texUnit); - fbo.use(gl, attachment ); - if( samples > 0) { - gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, fbo.getReadFramebuffer()); + initialized = false; + + for(int i=0; i "+newSamples); + } + initialize(false, gl); + samples = newSamples; + initialize(true, gl); + } else { + if(DEBUG) { + System.err.println("GLFBODrawableImpl.reset(): simple reconfig: "+samples+" -> "+newSamples); + } + final int nWidth = getWidth(); + final int nHeight = getHeight(); + samples = newSamples; + pendingFBOReset = ( 1 < fbos.length ) ? fbos[fboIFront] : null; // pending-front reset only w/ double buffering (or zero samples) + for(int i=0; i 0 ) { + res = fbos[0].getSamplingSinkFBO(); + } else { + res = fbos[fboIFront]; + } + break; + case GL.GL_BACK: + res = fbos[fboIBack]; + break; + default: + throw new IllegalArgumentException(illegalBufferName+toHexString(bufferName)); + } + return res; + } + + @Override + public final TextureAttachment getTextureBuffer(int bufferName) throws IllegalArgumentException { + if(!initialized) { + return null; + } + final TextureAttachment res; + switch(bufferName) { + case GL.GL_FRONT: + if( samples > 0 ) { + res = fbos[0].getSamplingSink(); + } else { + res = (TextureAttachment) fbos[fboIFront].getColorbuffer(0); + } + break; + case GL.GL_BACK: + if( samples > 0 ) { + throw new IllegalArgumentException("Cannot access GL_BACK buffer of MSAA FBO: "+this); + } else { + res = (TextureAttachment) fbos[fboIBack].getColorbuffer(0); + } + break; + default: + throw new IllegalArgumentException(illegalBufferName+toHexString(bufferName)); + } + return res; + } + private static final String illegalBufferName = "Only GL_FRONT and GL_BACK buffer are allowed, passed "; + + @Override + public String toString() { + return getClass().getSimpleName()+"[Initialized "+initialized+", realized "+isRealized()+", texUnit "+texUnit+", samples "+samples+ + ",\n\tFactory "+getFactory()+ + ",\n\tHandle "+toHexString(getHandle())+ + ",\n\tCaps "+surface.getGraphicsConfiguration().getChosenCapabilities()+ + ",\n\tfboI back "+fboIBack+", front "+fboIFront+", num "+(initialized ? fbos.length : 0)+ + ",\n\tFBO front read "+getDefaultReadFramebuffer()+", "+getFBObject(GL.GL_FRONT)+ + ",\n\tFBO back write "+getDefaultDrawFramebuffer()+", "+getFBObject(GL.GL_BACK)+ + ",\n\tSurface "+getNativeSurface()+ + "]"; + } + + public static class ResizeableImpl extends GLFBODrawableImpl implements GLFBODrawable.Resizeable { + protected ResizeableImpl(GLDrawableFactoryImpl factory, GLDrawableImpl parent, ProxySurface surface, + GLCapabilitiesImmutable fboCaps, int textureUnit) { + super(factory, parent, surface, fboCaps, textureUnit); + } + + @Override + public final void setSize(GLContext context, int newWidth, int newHeight) throws NativeWindowException, GLException { + if(DEBUG) { + System.err.println("GLFBODrawableImpl.ResizeableImpl setSize: ("+Thread.currentThread().getName()+"): "+newWidth+"x"+newHeight+" - surfaceHandle 0x"+Long.toHexString(getNativeSurface().getSurfaceHandle())); + } + int lockRes = lockSurface(); + if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { + throw new NativeWindowException("Could not lock surface: "+this); + } + try { + // propagate new size + final ProxySurface ps = (ProxySurface) getNativeSurface(); + final UpstreamSurfaceHook ush = ps.getUpstreamSurfaceHook(); + if(ush instanceof UpstreamSurfaceHook.MutableSize) { + ((UpstreamSurfaceHook.MutableSize)ush).setSize(newWidth, newHeight); + } else { + throw new InternalError("GLFBODrawableImpl.ResizableImpl's ProxySurface doesn't hold a UpstreamSurfaceHookMutableSize but "+ush.getClass().getName()+", "+ps+", ush"); + } + if( null != context && context.isCreated() ) { + resetSize(context.getGL()); + } + } finally { + unlockSurface(); + } + } + } } diff --git a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java index 768fc6892..79f96b64a 100644 --- a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java +++ b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java @@ -28,8 +28,12 @@ package jogamp.opengl; +import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; + +import com.jogamp.common.os.Platform; public class GLGraphicsConfigurationUtil { public static final String NV_coverage_sample = "NV_coverage_sample"; @@ -119,26 +123,34 @@ public class GLGraphicsConfigurationUtil { return getExclusiveWinAttributeBits(caps.isOnscreen(), caps.isFBO(), caps.isPBuffer(), caps.isBitmap()); } - public static final GLCapabilities setWinAttributeBits(GLCapabilities caps, int winattrbits) { + public static final GLCapabilities fixWinAttribBitsAndHwAccel(AbstractGraphicsDevice device, int winattrbits, GLCapabilities caps) { caps.setBitmap ( 0 != ( BITMAP_BIT & winattrbits ) ); caps.setPBuffer ( 0 != ( PBUFFER_BIT & winattrbits ) ); caps.setFBO ( 0 != ( FBO_BIT & winattrbits ) ); // we reflect availability semantics, hence setting onscreen at last (maybe overwritten above)! - caps.setOnscreen( 0 != ( WINDOW_BIT & winattrbits ) ); - return caps; - } + caps.setOnscreen( 0 != ( WINDOW_BIT & winattrbits ) ); + final int accel = GLContext.isHardwareRasterizer( device, caps.getGLProfile() ); + if(0 == accel && caps.getHardwareAccelerated() ) { + caps.setHardwareAccelerated(false); + } + + return caps; + } + public static GLCapabilitiesImmutable fixGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean fboAvailable, boolean pbufferAvailable) { if( !capsRequested.isOnscreen() ) { return fixOffscreenGLCapabilities(capsRequested, fboAvailable, pbufferAvailable); - } + } /* we maintain the offscreen mode flags in onscreen mode - else { + return fixOnscreenGLCapabilities(capsRequested); + } */ return capsRequested; } public static GLCapabilitiesImmutable fixOnscreenGLCapabilities(GLCapabilitiesImmutable capsRequested) { - if( !capsRequested.isOnscreen() ) { + if( !capsRequested.isOnscreen() || capsRequested.isFBO() || capsRequested.isPBuffer() || capsRequested.isBitmap() ) { // fix caps .. final GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); caps2.setBitmap (false); @@ -157,9 +169,11 @@ public class GLGraphicsConfigurationUtil { public static GLCapabilitiesImmutable fixOffscreenGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean fboAvailable, boolean pbufferAvailable) { final boolean auto = !capsRequested.isFBO() && !capsRequested.isPBuffer() && !capsRequested.isBitmap() ; + + final boolean requestedPBuffer = capsRequested.isPBuffer() || Platform.getOSType() == Platform.OSType.MACOS ; // no native bitmap for OSX final boolean useFBO = fboAvailable && ( auto || capsRequested.isFBO() ) ; - final boolean usePbuffer = !useFBO && pbufferAvailable && ( auto || capsRequested.isPBuffer() ) ; + final boolean usePbuffer = !useFBO && pbufferAvailable && ( auto || requestedPBuffer ) ; final boolean useBitmap = !useFBO && !usePbuffer && ( auto || capsRequested.isBitmap() ) ; if( capsRequested.isOnscreen() || diff --git a/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java new file mode 100644 index 000000000..7701f209f --- /dev/null +++ b/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java @@ -0,0 +1,123 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.opengl; + +import javax.media.nativewindow.NativeWindowException; +import javax.media.opengl.GL; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLException; +import javax.media.opengl.GLOffscreenAutoDrawable; + +import com.jogamp.common.util.locks.RecursiveLock; +import com.jogamp.opengl.FBObject; +import com.jogamp.opengl.GLAutoDrawableDelegate; + +import jogamp.opengl.GLFBODrawableImpl; + +public class GLOffscreenAutoDrawableImpl extends GLAutoDrawableDelegate implements GLOffscreenAutoDrawable { + + /** + * @param drawable a valid and already realized {@link GLDrawable} + * @param context a valid {@link GLContext}, may not be made current (created) yet. + * @param upstreamWidget optional UI element holding this instance, see {@link #getUpstreamWidget()}. + * @param lock optional upstream lock, may be null + */ + public GLOffscreenAutoDrawableImpl(GLDrawable drawable, GLContext context, Object upstreamWidget, RecursiveLock lock) { + super(drawable, context, upstreamWidget, true, lock); + } + + @Override + public void setSize(int newWidth, int newHeight) throws NativeWindowException, GLException { + this.defaultWindowResizedOp(newWidth, newHeight); + } + + public static class FBOImpl extends GLOffscreenAutoDrawableImpl implements GLOffscreenAutoDrawable.FBO { + /** + * @param drawable a valid and already realized {@link GLDrawable} + * @param context a valid {@link GLContext}, may not be made current (created) yet. + * @param upstreamWidget optional UI element holding this instance, see {@link #getUpstreamWidget()}. + * @param lock optional upstream lock, may be null + */ + public FBOImpl(GLFBODrawableImpl drawable, GLContext context, Object upstreamWidget, RecursiveLock lock) { + super(drawable, context, upstreamWidget, lock); + } + + @Override + public boolean isInitialized() { + return ((GLFBODrawableImpl)drawable).isInitialized(); + } + + @Override + public final int getTextureUnit() { + return ((GLFBODrawableImpl)drawable).getTextureUnit(); + } + + @Override + public final void setTextureUnit(int unit) { + ((GLFBODrawableImpl)drawable).setTextureUnit(unit); + } + + @Override + public final int getNumSamples() { + return ((GLFBODrawableImpl)drawable).getNumSamples(); + } + + @Override + public final void setNumSamples(GL gl, int newSamples) throws GLException { + ((GLFBODrawableImpl)drawable).setNumSamples(gl, newSamples); + windowRepaintOp(); + } + + /** // TODO: Add or remove TEXTURE (only) DoubleBufferMode support + @Override + public DoubleBufferMode getDoubleBufferMode() { + return ((GLFBODrawableImpl)drawable).getDoubleBufferMode(); + } + + @Override + public void setDoubleBufferMode(DoubleBufferMode mode) throws GLException { + ((GLFBODrawableImpl)drawable).setDoubleBufferMode(mode); + } */ + + @Override + public final FBObject getFBObject(int bufferName) { + return ((GLFBODrawableImpl)drawable).getFBObject(bufferName); + } + + public final FBObject.TextureAttachment getTextureBuffer(int bufferName) { + return ((GLFBODrawableImpl)drawable).getTextureBuffer(bufferName); + } + + @Override + public void resetSize(GL gl) throws GLException { + ((GLFBODrawableImpl)drawable).resetSize(gl); + } + } +} diff --git a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java index 32f4cb696..b438131bc 100644 --- a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java @@ -40,9 +40,6 @@ package jogamp.opengl; -import javax.media.opengl.GLCapabilitiesImmutable; -import javax.media.opengl.GLContext; -import javax.media.opengl.GLDrawable; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLPbuffer; @@ -50,36 +47,18 @@ import javax.media.opengl.GLPbuffer; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; -/** Platform-independent class exposing pbuffer functionality to - applications. This class is not exposed in the public API as it - would probably add no value; however it implements the GLDrawable - interface so can be interacted with via its display() method. */ - +@SuppressWarnings("deprecation") public class GLPbufferImpl extends GLAutoDrawableBase implements GLPbuffer { private int floatMode; - public GLPbufferImpl(GLDrawableImpl pbufferDrawable, GLContext sharedContext, boolean ownDevice) { - super(pbufferDrawable, null, ownDevice); // drawable := pbufferDrawable - - GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) - drawable.getNativeSurface().getGraphicsConfiguration().getChosenCapabilities(); - if(caps.isOnscreen()) { - if(caps.isPBuffer()) { - throw new IllegalArgumentException("Error: Given drawable is Onscreen and Pbuffer: "+pbufferDrawable); - } - throw new IllegalArgumentException("Error: Given drawable is Onscreen: "+pbufferDrawable); - } else { - if(!caps.isPBuffer()) { - throw new IllegalArgumentException("Error: Given drawable is not Pbuffer: "+pbufferDrawable); - } - } - context = (GLContextImpl) drawable.createContext(sharedContext); + public GLPbufferImpl(GLDrawableImpl pbufferDrawable, GLContextImpl pbufferContext) { + super(pbufferDrawable, pbufferContext, true); // drawable := pbufferDrawable, context := pbufferContext } // // pbuffer specifics - // - + // + @Override public void bindTexture() { // Doesn't make much sense to try to do this on the event dispatch diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLContext.java b/src/jogl/classes/jogamp/opengl/egl/EGLContext.java index 03d0d650f..06953a8e1 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLContext.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLContext.java @@ -282,12 +282,6 @@ public abstract class EGLContext extends GLContextImpl { return EGL.eglSwapInterval(drawable.getNativeSurface().getDisplayHandle(), interval); } - @Override - public abstract void bindPbufferToTexture(); - - @Override - public abstract void releasePbufferFromTexture(); - // // Accessible .. // diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java index 0dba4bb09..167eebf3a 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java @@ -36,7 +36,8 @@ package jogamp.opengl.egl; -import javax.media.nativewindow.MutableSurface; +import java.nio.IntBuffer; + import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.ProxySurface; @@ -46,10 +47,10 @@ import javax.media.opengl.GLException; import jogamp.opengl.GLDrawableImpl; import jogamp.opengl.GLDynamicLookupHelper; +import com.jogamp.common.nio.Buffers; import com.jogamp.nativewindow.egl.EGLGraphicsDevice; public abstract class EGLDrawable extends GLDrawableImpl { - private boolean ownEGLSurface = false; // for destruction protected EGLDrawable(EGLDrawableFactory factory, NativeSurface component) throws GLException { super(factory, component, false); @@ -58,21 +59,14 @@ public abstract class EGLDrawable extends GLDrawableImpl { @Override public abstract GLContext createContext(GLContext shareWith); - protected abstract long createSurface(EGLGraphicsConfiguration config, long nativeSurfaceHandle); + protected abstract long createSurface(EGLGraphicsConfiguration config, int width, int height, long nativeSurfaceHandle); - private final void recreateSurface() { - final EGLGraphicsConfiguration eglConfig = (EGLGraphicsConfiguration) surface.getGraphicsConfiguration(); - final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) eglConfig.getScreen().getDevice(); - if(DEBUG) { - System.err.println(getThreadName() + ": createSurface using "+eglConfig); - } - if( EGL.EGL_NO_SURFACE != surface.getSurfaceHandle() ) { - EGL.eglDestroySurface(eglDevice.getHandle(), surface.getSurfaceHandle()); - } + private final long createEGLSurface() { + final EGLWrappedSurface eglws = (EGLWrappedSurface) surface; + final EGLGraphicsConfiguration eglConfig = (EGLGraphicsConfiguration) eglws.getGraphicsConfiguration(); + final NativeSurface upstreamSurface = eglws.getUpstreamSurface(); - final EGLUpstreamSurfaceHook upstreamHook = (EGLUpstreamSurfaceHook) ((ProxySurface)surface).getUpstreamSurfaceHook(); - final NativeSurface upstreamSurface = upstreamHook.getUpstreamSurface(); - long eglSurface = createSurface(eglConfig, upstreamSurface.getSurfaceHandle()); + long eglSurface = createSurface(eglConfig, eglws.getWidth(), eglws.getHeight(), upstreamSurface.getSurfaceHandle()); int eglError0; if (EGL.EGL_NO_SURFACE == eglSurface) { @@ -86,7 +80,7 @@ public abstract class EGLDrawable extends GLDrawableImpl { if(DEBUG) { System.err.println(getThreadName() + ": Info: Creation of window surface w/ surface handle failed: "+eglConfig+", error "+toHexString(eglError0)+", retry w/ windowHandle"); } - eglSurface = createSurface(eglConfig, nw.getWindowHandle()); + eglSurface = createSurface(eglConfig, eglws.getWidth(), eglws.getHeight(), nw.getWindowHandle()); if (EGL.EGL_NO_SURFACE == eglSurface) { eglError0 = EGL.eglGetError(); } @@ -99,34 +93,53 @@ public abstract class EGLDrawable extends GLDrawableImpl { if (EGL.EGL_NO_SURFACE == eglSurface) { throw new GLException("Creation of window surface failed: "+eglConfig+", "+surface+", error "+toHexString(eglError0)); } - if(DEBUG) { - System.err.println(getThreadName() + ": setSurface using component: handle "+toHexString(surface.getSurfaceHandle())+" -> "+toHexString(eglSurface)); + System.err.println(getThreadName() + ": createEGLSurface handle "+toHexString(eglSurface)); } - - ((MutableSurface)surface).setSurfaceHandle(eglSurface); + return eglSurface; } @Override protected final void updateHandle() { - if(ownEGLSurface) { - recreateSurface(); + final EGLWrappedSurface eglws = (EGLWrappedSurface) surface; + if(DEBUG) { + System.err.println(getThreadName() + ": updateHandle of "+eglws); + } + if( eglws.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { + if( EGL.EGL_NO_SURFACE != eglws.getSurfaceHandle() ) { + throw new InternalError("Set surface but claimed to be invalid: "+eglws); + } + eglws.setSurfaceHandle( createEGLSurface() ); + } else if( EGL.EGL_NO_SURFACE == eglws.getSurfaceHandle() ) { + throw new InternalError("Nil surface but claimed to be valid: "+eglws); + } + } + + protected void destroyHandle() { + final EGLWrappedSurface eglws = (EGLWrappedSurface) surface; + if(DEBUG) { + System.err.println(getThreadName() + ": destroyHandle of "+eglws); + } + if( EGL.EGL_NO_SURFACE == eglws.getSurfaceHandle() ) { + throw new InternalError("Nil surface but claimed to be valid: "+eglws); + } + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) eglws.getGraphicsConfiguration().getScreen().getDevice(); + if( eglws.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { + EGL.eglDestroySurface(eglDevice.getHandle(), eglws.getSurfaceHandle()); + eglws.setSurfaceHandle(EGL.EGL_NO_SURFACE); } } - protected static boolean isValidEGLSurface(EGLGraphicsDevice eglDevice, NativeSurface surface) { - final long eglDisplayHandle = eglDevice.getHandle(); - if (EGL.EGL_NO_DISPLAY == eglDisplayHandle) { - throw new GLException("Invalid EGL display in EGLGraphicsDevice "+eglDevice); + protected static boolean isValidEGLSurface(long eglDisplayHandle, long surfaceHandle) { + if( 0 == surfaceHandle ) { + return false; } - boolean eglSurfaceValid = 0 != surface.getSurfaceHandle(); - if(eglSurfaceValid) { - int[] tmp = new int[1]; - eglSurfaceValid = EGL.eglQuerySurface(eglDisplayHandle, surface.getSurfaceHandle(), EGL.EGL_CONFIG_ID, tmp, 0); - if(!eglSurfaceValid) { - if(DEBUG) { - System.err.println(getThreadName() + ": EGLDrawable.isValidEGLSurface eglQuerySuface failed: "+toHexString(EGL.eglGetError())+", "+surface); - } + final IntBuffer val = Buffers.newDirectIntBuffer(1); + final boolean eglSurfaceValid = EGL.eglQuerySurface(eglDisplayHandle, surfaceHandle, EGL.EGL_CONFIG_ID, val); + if( !eglSurfaceValid ) { + final int eglErr = EGL.eglGetError(); + if(DEBUG) { + System.err.println(getThreadName() + ": EGLDrawable.isValidEGLSurface eglQuerySuface failed: error "+toHexString(eglErr)+", "+toHexString(surfaceHandle)); } } return eglSurfaceValid; @@ -134,55 +147,19 @@ public abstract class EGLDrawable extends GLDrawableImpl { @Override protected final void setRealizedImpl() { - final EGLGraphicsConfiguration eglConfig = (EGLGraphicsConfiguration) surface.getGraphicsConfiguration(); - final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) eglConfig.getScreen().getDevice(); - if (realized) { - final boolean eglSurfaceValid = isValidEGLSurface(eglDevice, surface); - if(eglSurfaceValid) { - // surface holds valid EGLSurface - if(DEBUG) { - System.err.println(getThreadName() + ": EGLDrawable.setRealizedImpl re-using component's EGLSurface: handle "+toHexString(surface.getSurfaceHandle())); - } - ownEGLSurface=false; - } else { - // EGLSurface is ours - subsequent updateHandle() will issue recreateSurface(); - // However .. let's validate the surface object first - if( ! (surface instanceof ProxySurface) ) { - throw new InternalError("surface not ProxySurface: "+surface.getClass().getName()+", "+surface); - } - final ProxySurface.UpstreamSurfaceHook upstreamHook = ((ProxySurface)surface).getUpstreamSurfaceHook(); - if( null == upstreamHook ) { - throw new InternalError("null upstreamHook of: "+surface); - } - if( ! (upstreamHook instanceof EGLUpstreamSurfaceHook) ) { - throw new InternalError("upstreamHook not EGLUpstreamSurfaceHook: Surface: "+surface.getClass().getName()+", "+surface+"; UpstreamHook: "+upstreamHook.getClass().getName()+", "+upstreamHook); - } - if( null == ((EGLUpstreamSurfaceHook)upstreamHook).getUpstreamSurface() ) { - throw new InternalError("null upstream surface"); - } - ownEGLSurface=true; - if(DEBUG) { - System.err.println(getThreadName() + ": EGLDrawable.setRealizedImpl owning EGLSurface"); - } - } - } else if (ownEGLSurface && surface.getSurfaceHandle() != EGL.EGL_NO_SURFACE) { - if(DEBUG) { - System.err.println(getThreadName() + ": EGLDrawable.setRealized(false): ownSurface "+ownEGLSurface+", "+eglDevice+", eglSurface: "+toHexString(surface.getSurfaceHandle())); - } - // Destroy the window surface - if (!EGL.eglDestroySurface(eglDevice.getHandle(), surface.getSurfaceHandle())) { - throw new GLException("Error destroying window surface (eglDestroySurface)"); - } - ((MutableSurface)surface).setSurfaceHandle(EGL.EGL_NO_SURFACE); + if(DEBUG) { + System.err.println(getThreadName() + ": EGLDrawable.setRealized("+realized+"): NOP - "+surface); } } @Override - protected final void swapBuffersImpl() { - final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) surface.getGraphicsConfiguration().getScreen().getDevice(); - // single-buffer is already filtered out @ GLDrawableImpl#swapBuffers() - if(!EGL.eglSwapBuffers(eglDevice.getHandle(), surface.getSurfaceHandle())) { - throw new GLException("Error swapping buffers, eglError "+toHexString(EGL.eglGetError())+", "+this); + protected final void swapBuffersImpl(boolean doubleBuffered) { + if(doubleBuffered) { + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) surface.getGraphicsConfiguration().getScreen().getDevice(); + // single-buffer is already filtered out @ GLDrawableImpl#swapBuffers() + if(!EGL.eglSwapBuffers(eglDevice.getHandle(), surface.getSurfaceHandle())) { + throw new GLException("Error swapping buffers, eglError "+toHexString(EGL.eglGetError())+", "+this); + } } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index 292eb17c8..e98d69140 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -52,8 +52,7 @@ import javax.media.nativewindow.MutableSurface; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; -import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; -import javax.media.nativewindow.VisualIDHolder.VIDType; +import javax.media.nativewindow.UpstreamSurfaceHook; import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.GL; import javax.media.opengl.GLCapabilities; @@ -65,6 +64,7 @@ import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; +import jogamp.nativewindow.WrappedSurface; import jogamp.opengl.Debug; import jogamp.opengl.GLDrawableFactoryImpl; import jogamp.opengl.GLDrawableImpl; @@ -76,10 +76,11 @@ import com.jogamp.common.nio.Buffers; import com.jogamp.common.nio.PointerBuffer; import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; -import com.jogamp.nativewindow.WrappedSurface; import com.jogamp.nativewindow.egl.EGLGraphicsDevice; public class EGLDrawableFactory extends GLDrawableFactoryImpl { + protected static final boolean DEBUG = GLDrawableFactoryImpl.DEBUG; + /* package */ static final boolean QUERY_EGL_ES = !Debug.isPropertyDefined("jogl.debug.EGLDrawableFactory.DontQuery", true); /* package */ static final boolean QUERY_EGL_ES_NATIVE_TK = Debug.isPropertyDefined("jogl.debug.EGLDrawableFactory.QueryNativeTK", true); @@ -112,7 +113,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } catch (JogampRuntimeException jre) { /* n/a .. */ } } - defaultDevice = new EGLGraphicsDevice(AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + defaultDevice = new EGLGraphicsDevice(); // FIXME: Probably need to move EGL from a static model // to a dynamic one, where there can be 2 instances @@ -310,6 +311,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { try { final GLCapabilities reqCapsAny = new GLCapabilities(glp); reqCapsAny.setRedBits(5); reqCapsAny.setGreenBits(5); reqCapsAny.setBlueBits(5); reqCapsAny.setAlphaBits(0); + reqCapsAny.setDoubleBuffered(false); final GLCapabilitiesImmutable reqCapsPBuffer = GLGraphicsConfigurationUtil.fixGLPBufferGLCapabilities(reqCapsAny); final List availablePBufferCapsL = getAvailableEGLConfigs(sharedEGLDevice, reqCapsPBuffer); hasPBuffer[0] = availablePBufferCapsL.size() > 0; @@ -324,18 +326,20 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } else { final List capsAnyL = getAvailableEGLConfigs(eglDevice, reqCapsAny); if(capsAnyL.size() > 0) { - final GLCapabilitiesImmutable caps = capsAnyL.get(0); - EGLContext.mapStaticGLESVersion(eglDevice, caps); + final GLCapabilitiesImmutable chosenCaps = capsAnyL.get(0); + EGLContext.mapStaticGLESVersion(eglDevice, chosenCaps); if(eglDevice != adevice) { - EGLContext.mapStaticGLESVersion(adevice, caps); + EGLContext.mapStaticGLESVersion(adevice, chosenCaps); } + final EGLGraphicsDevice adeviceEGLDevice = new EGLGraphicsDevice(adevice.getHandle(), EGL.EGL_NO_DISPLAY, adevice.getConnection(), adevice.getUnitID(), null); + EGLContext.mapStaticGLESVersion(adeviceEGLDevice, chosenCaps); success = true; } if(DEBUG) { System.err.println("EGLDrawableFactory.isEGLContextAvailable() no pbuffer config available, detected !pbuffer config: "+success); EGLGraphicsConfigurationFactory.printCaps("!PBufferCaps", capsAnyL, System.err); } - } + } } else { surface = desktopFactory.createDummySurface(adevice, reqCapsAny, null, 64, 64); // X11, WGL, .. dummy window upstreamSurface = ( surface instanceof ProxySurface ) ? (ProxySurface)surface : null ; @@ -361,6 +365,8 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { if(eglDevice != adevice) { context.mapCurrentAvailableGLVersion(adevice); } + final EGLGraphicsDevice adeviceEGLDevice = new EGLGraphicsDevice(adevice.getHandle(), EGL.EGL_NO_DISPLAY, adevice.getConnection(), adevice.getUnitID(), null); + context.mapCurrentAvailableGLVersion(adeviceEGLDevice); success = true; } else { // Oops .. something is wrong @@ -538,70 +544,9 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { if (target == null) { throw new IllegalArgumentException("Null target"); } - return new EGLOnscreenDrawable(this, getEGLSurface(target)); + return new EGLOnscreenDrawable(this, EGLWrappedSurface.get(target)); } - protected static NativeSurface getEGLSurface(NativeSurface surface) { - AbstractGraphicsConfiguration aConfig = surface.getGraphicsConfiguration(); - AbstractGraphicsDevice aDevice = aConfig.getScreen().getDevice(); - if( aDevice instanceof EGLGraphicsDevice && aConfig instanceof EGLGraphicsConfiguration ) { - if(surface instanceof WrappedSurface) { - // already wrapped surface - no wrapped recursion - if(DEBUG) { - System.err.println(getThreadName() + ": getEGLSurface - already wrapped surface - use as-is: "+surface); - } - return surface; - } - if(EGLDrawable.isValidEGLSurface((EGLGraphicsDevice)aDevice, surface)) { - // already in native EGL format - if(DEBUG) { - System.err.println(getThreadName() + ": getEGLSurface - already valid EGL surface - use as-is: "+surface); - } - return surface; - } - } - // create EGL instance out of platform native types - final EGLGraphicsDevice eglDevice; - if( aDevice instanceof EGLGraphicsDevice ) { - eglDevice = (EGLGraphicsDevice) aDevice; - if(DEBUG) { - System.err.println(getThreadName() + ": getEGLSurface - Reusing eglDevice: "+eglDevice); - } - if(0 == eglDevice.getHandle()) { - eglDevice.open(); - } - } else { - eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface); - } - final AbstractGraphicsScreen eglScreen = new DefaultGraphicsScreen(eglDevice, aConfig.getScreen().getIndex()); - final GLCapabilitiesImmutable capsRequested = (GLCapabilitiesImmutable) aConfig.getRequestedCapabilities(); - final EGLGraphicsConfiguration eglConfig; - if( aConfig instanceof EGLGraphicsConfiguration ) { - // Config is already in EGL type - reuse .. - final EGLGLCapabilities capsChosen = (EGLGLCapabilities) aConfig.getChosenCapabilities(); - if( 0 == capsChosen.getEGLConfig() ) { - // 'refresh' the native EGLConfig handle - capsChosen.setEGLConfig(EGLGraphicsConfiguration.EGLConfigId2EGLConfig(eglDevice.getHandle(), capsChosen.getEGLConfigID())); - if( 0 == capsChosen.getEGLConfig() ) { - throw new GLException("Refreshing native EGLConfig handle failed with error "+EGLContext.toHexString(EGL.eglGetError())+": "+eglDevice+", "+capsChosen+" of "+aConfig); - } - } - eglConfig = new EGLGraphicsConfiguration(eglScreen, capsChosen, capsRequested, null); - if(DEBUG) { - System.err.println(getThreadName() + ": getEGLSurface - Reusing chosenCaps: "+eglConfig); - } - } else { - eglConfig = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic( - capsRequested, capsRequested, null, eglScreen, aConfig.getVisualID(VIDType.NATIVE), false); - - if (null == eglConfig) { - throw new GLException("Couldn't create EGLGraphicsConfiguration from "+eglScreen); - } else if(DEBUG) { - System.err.println(getThreadName() + ": getEGLSurface - Chosen eglConfig: "+eglConfig); - } - } - return new WrappedSurface(eglConfig, EGL.EGL_NO_SURFACE, surface.getWidth(), surface.getHeight(), new EGLUpstreamSurfaceHook(surface)); - } static String getThreadName() { return Thread.currentThread().getName(); } @Override @@ -615,7 +560,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { throw new GLException("Non pbuffer not yet implemented"); } // PBuffer GLDrawable Creation - return new EGLPbufferDrawable(this, getEGLSurface(target)); + return new EGLPbufferDrawable(this, EGLWrappedSurface.get(target)); } @Override @@ -628,20 +573,24 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { @Override protected ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, - GLCapabilitiesChooser chooser, int width, int height, UpstreamSurfaceHook lifecycleHook) { + GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { + final boolean ownDevice; final EGLGraphicsDevice device; - if(createNewDevice) { - final EGLGraphicsDevice eglDeviceReq = (EGLGraphicsDevice) deviceReq; - device = EGLDisplayUtil.eglCreateEGLGraphicsDevice(eglDeviceReq.getNativeDisplayID(), deviceReq.getConnection(), deviceReq.getUnitID()); + if(createNewDevice || ! ( deviceReq instanceof EGLGraphicsDevice ) ) { + final long nativeDisplayID = ( deviceReq instanceof EGLGraphicsDevice) ? + ( (EGLGraphicsDevice) deviceReq ).getNativeDisplayID() : deviceReq.getHandle() ; + device = EGLDisplayUtil.eglCreateEGLGraphicsDevice(nativeDisplayID, deviceReq.getConnection(), deviceReq.getUnitID()); + ownDevice = true; } else { device = (EGLGraphicsDevice) deviceReq; + ownDevice = false; } final DefaultGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); final EGLGraphicsConfiguration config = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED, false); if(null == config) { throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); } - return new WrappedSurface(config, 0, width, height, lifecycleHook); + return new WrappedSurface(config, 0, upstreamHook, ownDevice); } @Override @@ -649,54 +598,9 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixDoubleBufferedGLCapabilities( - GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(requestedCaps, false, canCreateGLPbuffer(deviceReq)), - false); - return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, width, height, dummySurfaceLifecycleHook); + GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(requestedCaps, false, canCreateGLPbuffer(deviceReq)), false); + return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, new EGLDummyUpstreamSurfaceHook(width, height)); } - private static final ProxySurface.UpstreamSurfaceHook dummySurfaceLifecycleHook = new ProxySurface.UpstreamSurfaceHook() { - @Override - public final void create(ProxySurface s) { - if( EGL.EGL_NO_SURFACE == s.getSurfaceHandle() ) { - final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) s.getGraphicsConfiguration().getScreen().getDevice(); - if(0 == eglDevice.getHandle()) { - eglDevice.open(); - s.setImplBitfield(ProxySurface.OWN_DEVICE); - } - createPBufferSurfaceImpl(s, false); - if(DEBUG) { - System.err.println("EGLDrawableFactory.dummySurfaceLifecycleHook.create: "+s); - } - } - } - @Override - public final void destroy(ProxySurface s) { - if( EGL.EGL_NO_SURFACE != s.getSurfaceHandle() ) { - final EGLGraphicsConfiguration config = (EGLGraphicsConfiguration) s.getGraphicsConfiguration(); - final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) config.getScreen().getDevice(); - EGL.eglDestroySurface(eglDevice.getHandle(), s.getSurfaceHandle()); - s.setSurfaceHandle(EGL.EGL_NO_SURFACE); - if( 0 != ( ProxySurface.OWN_DEVICE & s.getImplBitfield() ) ) { - eglDevice.close(); - } - if(DEBUG) { - System.err.println("EGLDrawableFactory.dummySurfaceLifecycleHook.create: "+s); - } - } - } - @Override - public final int getWidth(ProxySurface s) { - return s.initialWidth; - } - @Override - public final int getHeight(ProxySurface s) { - return s.initialHeight; - } - @Override - public String toString() { - return "EGLSurfaceLifecycleHook[]"; - } - - }; /** * @param ms {@link MutableSurface} which dimensions and config are being used to create the pbuffer surface. @@ -705,7 +609,9 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { * @return the passed {@link MutableSurface} which now has the EGL pbuffer surface set as it's handle */ protected static MutableSurface createPBufferSurfaceImpl(MutableSurface ms, boolean useTexture) { - final EGLGraphicsConfiguration config = (EGLGraphicsConfiguration) ms.getGraphicsConfiguration(); + return null; + } + protected static long createPBufferSurfaceImpl(EGLGraphicsConfiguration config, int width, int height, boolean useTexture) { final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) config.getScreen().getDevice(); final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); final int texFormat; @@ -720,15 +626,14 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { System.out.println("Pbuffer config: " + config); } - final int[] attrs = EGLGraphicsConfiguration.CreatePBufferSurfaceAttribList(ms.getWidth(), ms.getHeight(), texFormat); + final int[] attrs = EGLGraphicsConfiguration.CreatePBufferSurfaceAttribList(width, height, texFormat); final long surf = EGL.eglCreatePbufferSurface(eglDevice.getHandle(), config.getNativeConfig(), attrs, 0); if (EGL.EGL_NO_SURFACE==surf) { - throw new GLException("Creation of window surface (eglCreatePbufferSurface) failed, dim "+ms.getWidth()+"x"+ms.getHeight()+", error 0x"+Integer.toHexString(EGL.eglGetError())); + throw new GLException("Creation of window surface (eglCreatePbufferSurface) failed, dim "+width+"x"+height+", "+eglDevice+", "+config+", error 0x"+Integer.toHexString(EGL.eglGetError())); } else if(DEBUG) { System.err.println("PBuffer setSurface result: eglSurface 0x"+Long.toHexString(surf)); } - ms.setSurfaceHandle(surf); - return ms; + return surf; } @Override @@ -737,7 +642,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { final EGLGraphicsDevice device = EGLDisplayUtil.eglCreateEGLGraphicsDevice(eglDeviceReq.getNativeDisplayID(), deviceReq.getConnection(), deviceReq.getUnitID()); final DefaultGraphicsScreen screen = new DefaultGraphicsScreen(device, screenIdx); final EGLGraphicsConfiguration cfg = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED, false); - return new WrappedSurface(cfg, windowHandle, 0, 0, upstream); + return new WrappedSurface(cfg, windowHandle, upstream, true); } @Override diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java b/src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java new file mode 100644 index 000000000..b172d4f35 --- /dev/null +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java @@ -0,0 +1,49 @@ +package jogamp.opengl.egl; + +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; +import com.jogamp.nativewindow.egl.EGLGraphicsDevice; + +public class EGLDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize { + /** + * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, + * not the actual dummy surface width. + * The latter is platform specific and small + * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, + * not the actual dummy surface height, + * The latter is platform specific and small + */ + public EGLDummyUpstreamSurfaceHook(int width, int height) { + super(width, height); + } + + @Override + public final void create(ProxySurface s) { + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) s.getGraphicsConfiguration().getScreen().getDevice(); + if(0 == eglDevice.getHandle()) { + eglDevice.open(); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + if( EGL.EGL_NO_SURFACE == s.getSurfaceHandle() ) { + s.setSurfaceHandle( EGLDrawableFactory.createPBufferSurfaceImpl((EGLGraphicsConfiguration)s.getGraphicsConfiguration(), 64, 64, false) ); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); + } + + @Override + public final void destroy(ProxySurface s) { + if( s.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { + final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) s.getGraphicsConfiguration().getScreen().getDevice(); + if( EGL.EGL_NO_SURFACE == s.getSurfaceHandle() ) { + throw new InternalError("Owns upstream surface, but no EGL surface: "+s); + } + EGL.eglDestroySurface(eglDevice.getHandle(), s.getSurfaceHandle()); + s.setSurfaceHandle(EGL.EGL_NO_SURFACE); + s.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + } +} diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLExternalContext.java b/src/jogl/classes/jogamp/opengl/egl/EGLExternalContext.java index 585638d21..84bd705db 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLExternalContext.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLExternalContext.java @@ -79,15 +79,4 @@ public class EGLExternalContext extends EGLContext { @Override protected void destroyImpl() throws GLException { } - - @Override - public void bindPbufferToTexture() { - throw new GLException("Should not call this"); - } - - @Override - public void releasePbufferFromTexture() { - throw new GLException("Should not call this"); - } - } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java b/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java index e513a86cf..f857c6b5c 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java @@ -57,8 +57,8 @@ public class EGLGLCapabilities extends GLCapabilities { this.eglcfg = eglcfg; this.eglcfgid = eglcfgid; if(!isCompatible(glp, renderableType)) { - throw new GLException("Incompatible "+glp+ - " with EGL-RenderableType["+renderableTypeToString(null, renderableType)+"]"); + throw new GLException("Requested GLProfile "+glp+ + " not compatible with EGL-RenderableType["+renderableTypeToString(null, renderableType)+"]"); } this.renderableType = renderableType; this.nativeVisualID = visualID; @@ -131,6 +131,7 @@ public class EGLGLCapabilities extends GLCapabilities { sink = new StringBuilder(); } boolean first=true; + sink.append("0x").append(Integer.toHexString(renderableType)).append(": "); if(0 != (renderableType & EGL.EGL_OPENGL_BIT)) { sink.append("GL"); first=false; } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java index 8ee98072f..7bf201238 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java @@ -211,6 +211,13 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple if(null == glp) { glp = EGLGLCapabilities.getCompatible(device, rType); } + if(!EGLGLCapabilities.isCompatible(glp, rType)) { + if(DEBUG) { + System.err.println("config "+toHexString(config)+": Requested GLProfile "+glp+ + " not compatible with EGL-RenderableType["+EGLGLCapabilities.renderableTypeToString(null, rType)+"]"); + } + return null; + } caps = new EGLGLCapabilities(config, cfgID, visualID, glp, rType); } catch (GLException gle) { if(DEBUG) { @@ -288,7 +295,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple return null; } - return (EGLGLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(caps, drawableTypeBits); + return (EGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, caps); } public static int[] GLCapabilities2AttribList(GLCapabilitiesImmutable caps) { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenContext.java b/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenContext.java index eae47fa92..325ad6142 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenContext.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenContext.java @@ -41,16 +41,5 @@ public class EGLOnscreenContext extends EGLContext { public EGLOnscreenContext(EGLOnscreenDrawable drawable, GLContext shareWith) { super(drawable, shareWith); } - - @Override - public void bindPbufferToTexture() { - throw new GLException("Should not call this"); - } - - @Override - public void releasePbufferFromTexture() { - throw new GLException("Should not call this"); - } - } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenDrawable.java b/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenDrawable.java index d54057775..6440cf1e5 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenDrawable.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLOnscreenDrawable.java @@ -54,8 +54,8 @@ public class EGLOnscreenDrawable extends EGLDrawable { } @Override - protected long createSurface(EGLGraphicsConfiguration config, long nativeSurfaceHandle) { + protected long createSurface(EGLGraphicsConfiguration config, int width, int height, long nativeSurfaceHandle) { return EGL.eglCreateWindowSurface(config.getScreen().getDevice().getHandle(), config.getNativeConfig(), nativeSurfaceHandle, null); - } + } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLPbufferContext.java b/src/jogl/classes/jogamp/opengl/egl/EGLPbufferContext.java index 7175d516f..bb9eeb892 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLPbufferContext.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLPbufferContext.java @@ -46,15 +46,5 @@ public class EGLPbufferContext extends EGLContext { public int getFloatingPointMode() { return 0; // FIXME ?? } - - @Override - public void bindPbufferToTexture() { - throw new GLException("Not yet implemented"); - } - - @Override - public void releasePbufferFromTexture() { - throw new GLException("Not yet implemented"); - } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLPbufferDrawable.java b/src/jogl/classes/jogamp/opengl/egl/EGLPbufferDrawable.java index 4a36625bd..eb7e320c8 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLPbufferDrawable.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLPbufferDrawable.java @@ -52,12 +52,8 @@ public class EGLPbufferDrawable extends EGLDrawable { } @Override - protected long createSurface(EGLGraphicsConfiguration config, long nativeSurfaceHandle) { - final MutableSurface ms = (MutableSurface)getNativeSurface(); - if(config != ms.getGraphicsConfiguration()) { - throw new InternalError("Not same: "+config.hashCode()+", "+ms.getGraphicsConfiguration()+": "+config+", "+ms.getGraphicsConfiguration()); - } - return EGLDrawableFactory.createPBufferSurfaceImpl(ms, useTexture).getSurfaceHandle(); + protected long createSurface(EGLGraphicsConfiguration config, int width, int height, long nativeSurfaceHandle) { + return EGLDrawableFactory.createPBufferSurfaceImpl(config, width, height, false); } @Override diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java b/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java index 42c6e100e..342c4c417 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java @@ -1,38 +1,163 @@ package jogamp.opengl.egl; +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.DefaultGraphicsScreen; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; +import javax.media.nativewindow.VisualIDHolder.VIDType; +import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLException; import com.jogamp.nativewindow.egl.EGLGraphicsDevice; -public class EGLUpstreamSurfaceHook implements ProxySurface.UpstreamSurfaceHook { +public class EGLUpstreamSurfaceHook implements UpstreamSurfaceHook.MutableSize { + protected static final boolean DEBUG = EGLDrawableFactory.DEBUG; private final NativeSurface upstreamSurface; + private final UpstreamSurfaceHook.MutableSize upstreamSurfaceHookMutableSize; public EGLUpstreamSurfaceHook(NativeSurface upstream) { upstreamSurface = upstream; + if(upstreamSurface instanceof ProxySurface) { + final UpstreamSurfaceHook ush = ((ProxySurface)upstreamSurface).getUpstreamSurfaceHook(); + if(ush instanceof UpstreamSurfaceHook.MutableSize) { + // offscreen NativeSurface w/ MutableSize (default) + upstreamSurfaceHookMutableSize = (UpstreamSurfaceHook.MutableSize) ush; + } else { + upstreamSurfaceHookMutableSize = null; + } + } else { + upstreamSurfaceHookMutableSize = null; + } } public final NativeSurface getUpstreamSurface() { return upstreamSurface; } + static String getThreadName() { return Thread.currentThread().getName(); } + + public final void setSize(int width, int height) { + if(null != upstreamSurfaceHookMutableSize) { + upstreamSurfaceHookMutableSize.setSize(width, height); + } + } + @Override public final void create(ProxySurface surface) { + final String dbgPrefix; + if(DEBUG) { + dbgPrefix = getThreadName() + ": EGLUpstreamSurfaceHook.create("+surface.getClass().getSimpleName()+"): "; + System.err.println(dbgPrefix+this); + } else { + dbgPrefix = null; + } + if(upstreamSurface instanceof ProxySurface) { + // propagate createNotify(..) so upstreamSurface will be created ((ProxySurface)upstreamSurface).createNotify(); - if(NativeSurface.LOCK_SURFACE_NOT_READY >= upstreamSurface.lockSurface()) { - throw new GLException("Could not lock: "+upstreamSurface); + } + + // lock upstreamSurface, so it can be used in case EGLDisplay is derived from it! + if(NativeSurface.LOCK_SURFACE_NOT_READY >= upstreamSurface.lockSurface()) { + throw new GLException("Could not lock: "+upstreamSurface); + } + try { + evalUpstreamSurface(dbgPrefix, surface); + } finally { + upstreamSurface.unlockSurface(); + } + } + + private final void evalUpstreamSurface(String dbgPrefix, ProxySurface surface) { + // + // evaluate nature of upstreamSurface, may create EGL instances if required + // + + boolean isEGLSurfaceValid = true; // assume yes + + final AbstractGraphicsConfiguration aConfig = upstreamSurface.getGraphicsConfiguration(); + final AbstractGraphicsDevice aDevice = aConfig.getScreen().getDevice(); + + final EGLGraphicsDevice eglDevice; + if( aDevice instanceof EGLGraphicsDevice ) { + eglDevice = (EGLGraphicsDevice) aDevice; + if(DEBUG) { + System.err.println(dbgPrefix+"Reusing eglDevice: "+eglDevice); + } + if(EGL.EGL_NO_DISPLAY == eglDevice.getHandle()) { + eglDevice.open(); + isEGLSurfaceValid = false; + surface.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + } else { + eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(upstreamSurface); + isEGLSurfaceValid = false; + surface.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + + final GLCapabilitiesImmutable capsRequested = (GLCapabilitiesImmutable) aConfig.getRequestedCapabilities(); + final EGLGraphicsConfiguration eglConfig; + if( aConfig instanceof EGLGraphicsConfiguration ) { + // Config is already in EGL type - reuse .. + final EGLGLCapabilities capsChosen = (EGLGLCapabilities) aConfig.getChosenCapabilities(); + if( !isEGLSurfaceValid || !EGLGraphicsConfiguration.isEGLConfigValid(eglDevice.getHandle(), capsChosen.getEGLConfig()) ) { + // 'refresh' the native EGLConfig handle + capsChosen.setEGLConfig(EGLGraphicsConfiguration.EGLConfigId2EGLConfig(eglDevice.getHandle(), capsChosen.getEGLConfigID())); + if( 0 == capsChosen.getEGLConfig() ) { + throw new GLException("Refreshing native EGLConfig handle failed with error "+EGLContext.toHexString(EGL.eglGetError())+": "+eglDevice+", "+capsChosen+" of "+aConfig); + } + final AbstractGraphicsScreen eglScreen = new DefaultGraphicsScreen(eglDevice, aConfig.getScreen().getIndex()); + eglConfig = new EGLGraphicsConfiguration(eglScreen, capsChosen, capsRequested, null); + if(DEBUG) { + System.err.println(dbgPrefix+"Refreshing eglConfig: "+eglConfig); + } + isEGLSurfaceValid = false; + } else { + eglConfig = (EGLGraphicsConfiguration) aConfig; + if(DEBUG) { + System.err.println(dbgPrefix+"Reusing eglConfig: "+eglConfig); + } + } + } else { + final AbstractGraphicsScreen eglScreen = new DefaultGraphicsScreen(eglDevice, aConfig.getScreen().getIndex()); + eglConfig = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic( + capsRequested, capsRequested, null, eglScreen, aConfig.getVisualID(VIDType.NATIVE), false); + + if (null == eglConfig) { + throw new GLException("Couldn't create EGLGraphicsConfiguration from "+eglScreen); + } else if(DEBUG) { + System.err.println(dbgPrefix+"Chosen eglConfig: "+eglConfig); } + isEGLSurfaceValid = false; } - final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) surface.getGraphicsConfiguration().getScreen().getDevice(); - eglDevice.open(); + surface.setGraphicsConfiguration(eglConfig); + + if(isEGLSurfaceValid) { + isEGLSurfaceValid = EGLDrawable.isValidEGLSurface(eglDevice.getHandle(), upstreamSurface.getSurfaceHandle()); + } + if(isEGLSurfaceValid) { + surface.setSurfaceHandle(upstreamSurface.getSurfaceHandle()); + surface.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + if(DEBUG) { + System.err.println(dbgPrefix+"Fin: Already valid EGL surface - use as-is: "+upstreamSurface); + } + } else { + surface.setSurfaceHandle(EGL.EGL_NO_SURFACE); + surface.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); // create/destroy in EGLDrawable + if(DEBUG) { + System.err.println(dbgPrefix+"Fin: EGL surface n/a - TBD: "+upstreamSurface); + } + } } @Override public final void destroy(ProxySurface surface) { - final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) surface.getGraphicsConfiguration().getScreen().getDevice(); - eglDevice.close(); + if(EGLDrawableFactory.DEBUG) { + System.err.println("EGLUpstreamSurfaceHook.destroy("+surface.getClass().getSimpleName()+"): "+this); + } + surface.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); if(upstreamSurface instanceof ProxySurface) { - upstreamSurface.unlockSurface(); ((ProxySurface)upstreamSurface).destroyNotify(); } } @@ -49,8 +174,8 @@ public class EGLUpstreamSurfaceHook implements ProxySurface.UpstreamSurfaceHook @Override public String toString() { - final String us_s = null != upstreamSurface ? ( upstreamSurface.getClass().getName() + ": " + upstreamSurface ) : "nil"; - return "EGLUpstreamSurfaceHook[upstream: "+us_s+"]"; + final String us_s = null != upstreamSurface ? ( upstreamSurface.getClass().getName() + ": 0x" + Long.toHexString(upstreamSurface.getSurfaceHandle()) ) : "nil"; + return "EGLUpstreamSurfaceHook[ "+ upstreamSurface.getWidth() + "x" + upstreamSurface.getHeight() + ", " + us_s+ "]"; } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java b/src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java new file mode 100644 index 000000000..b36303392 --- /dev/null +++ b/src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java @@ -0,0 +1,26 @@ +package jogamp.opengl.egl; + +import javax.media.nativewindow.NativeSurface; + +import jogamp.nativewindow.WrappedSurface; + +public class EGLWrappedSurface extends WrappedSurface { + + public static EGLWrappedSurface get(NativeSurface surface) { + if(surface instanceof EGLWrappedSurface) { + return (EGLWrappedSurface)surface; + } + return new EGLWrappedSurface(surface); + } + + public EGLWrappedSurface(NativeSurface surface) { + super(surface.getGraphicsConfiguration(), EGL.EGL_NO_SURFACE, new EGLUpstreamSurfaceHook(surface), false /* tbd in UpstreamSurfaceHook */); + if(EGLDrawableFactory.DEBUG) { + System.err.println("EGLWrappedSurface.ctor(): "+this); + } + } + + public final NativeSurface getUpstreamSurface() { + return ((EGLUpstreamSurfaceHook)super.getUpstreamSurfaceHook()).getUpstreamSurface(); + } +} diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 55aea3a98..ec29558d1 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -49,6 +49,7 @@ import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.OffscreenLayerSurface; import javax.media.nativewindow.ProxySurface; +import javax.media.opengl.GL; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; @@ -58,6 +59,7 @@ import javax.media.opengl.GLProfile; import jogamp.nativewindow.macosx.OSXUtil; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableImpl; +import jogamp.opengl.GLFBODrawableImpl; import jogamp.opengl.GLGraphicsConfigurationUtil; import jogamp.opengl.macosx.cgl.MacOSXCGLDrawable.GLBackendType; @@ -76,9 +78,11 @@ public abstract class MacOSXCGLContext extends GLContextImpl boolean isNSContext(); long create(long share, int ctp, int major, int minor); boolean destroy(long ctx); + boolean contextRealized(boolean realized); boolean copyImpl(long src, int mask); boolean makeCurrent(long ctx); boolean release(long ctx); + boolean detachPBuffer(); boolean setSwapInterval(int interval); boolean swapBuffers(); } @@ -279,7 +283,24 @@ public abstract class MacOSXCGLContext extends GLContextImpl throw new GLException("Error destroying OpenGL Context: "+this); } } + + @Override + protected void contextRealized(boolean realized) { + // context stuff depends on drawable stuff + if(realized) { + super.contextRealized(true); // 1) init drawable stuff + impl.contextRealized(true); // 2) init context stuff + } else { + impl.contextRealized(false); // 1) free context stuff + super.contextRealized(false); // 2) free drawable stuff + } + } + + /* pp */ void detachPBuffer() { + impl.detachPBuffer(); + } + @Override protected void copyImpl(GLContext source, int mask) throws GLException { if( isNSContext() != ((MacOSXCGLContext)source).isNSContext() ) { @@ -365,16 +386,6 @@ public abstract class MacOSXCGLContext extends GLContextImpl throw new GLException("Should not call this"); } - @Override - public void bindPbufferToTexture() { - throw new GLException("Should not call this"); - } - - @Override - public void releasePbufferFromTexture() { - throw new GLException("Should not call this"); - } - // Support for "mode switching" as described in MacOSXCGLDrawable public void setOpenGLMode(GLBackendType mode) { if (mode == openGLMode) { @@ -421,323 +432,486 @@ public abstract class MacOSXCGLContext extends GLContextImpl // NSOpenGLContext-based implementation class NSOpenGLImpl implements GLBackendImpl { - long nsOpenGLLayer = 0; - long nsOpenGLLayerPFmt = 0; - float screenVSyncTimeout; // microSec - int vsyncTimeout; // microSec - for nsOpenGLLayer mode - - @Override - public boolean isNSContext() { return true; } - - @Override - public long create(long share, int ctp, int major, int minor) { - long ctx = 0; - final long nsViewHandle; - if(drawable instanceof MacOSXCGLDrawable) { - // we allow null here! (special pbuffer case) - nsViewHandle = ((MacOSXCGLDrawable)MacOSXCGLContext.this.drawable).getNSViewHandle(); - } else { - // we only allow a valid NSView here - final long aHandle = drawable.getHandle(); - if( OSXUtil.isNSView(aHandle) ) { - nsViewHandle = aHandle; - } else { - throw new RuntimeException("Anonymous drawable instance's handle not of type NSView: "+drawable.getClass().getName()+", "+drawable); - } - } - final NativeSurface surface = drawable.getNativeSurface(); - final MacOSXCGLGraphicsConfiguration config = (MacOSXCGLGraphicsConfiguration) surface.getGraphicsConfiguration(); - final OffscreenLayerSurface backingLayerHost = NativeWindowFactory.getOffscreenLayerSurface(surface, true); - - boolean allowIncompleteView = null != backingLayerHost; - if( !allowIncompleteView && surface instanceof ProxySurface ) { - allowIncompleteView = 0 != ( ProxySurface.INVISIBLE_WINDOW & ((ProxySurface)surface).getImplBitfield() ) ; - } - final GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); - long pixelFormat = MacOSXCGLGraphicsConfiguration.GLCapabilities2NSPixelFormat(chosenCaps, ctp, major, minor); - if (pixelFormat == 0) { - if(DEBUG) { - System.err.println("Unable to allocate pixel format with requested GLCapabilities: "+chosenCaps); - } - return 0; - } - config.setChosenPixelFormat(pixelFormat); - int sRefreshRate = CGL.getScreenRefreshRate(drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getIndex()); - screenVSyncTimeout = 1000000f / sRefreshRate; - if(DEBUG) { - System.err.println("NS create OSX>=lion "+isLionOrLater); - System.err.println("NS create allowIncompleteView: "+allowIncompleteView); - System.err.println("NS create backingLayerHost: "+backingLayerHost); - System.err.println("NS create share: "+share); - System.err.println("NS create chosenCaps: "+chosenCaps); - System.err.println("NS create pixelFormat: "+toHexString(pixelFormat)); - System.err.println("NS create drawable native-handle: "+toHexString(drawable.getHandle())); - System.err.println("NS create drawable NSView-handle: "+toHexString(nsViewHandle)); - System.err.println("NS create screen refresh-rate: "+sRefreshRate+" hz, "+screenVSyncTimeout+" micros"); - // Thread.dumpStack(); - } - try { - int[] viewNotReady = new int[1]; - // Try to allocate a context with this - ctx = CGL.createContext(share, - nsViewHandle, allowIncompleteView, - pixelFormat, - chosenCaps.isBackgroundOpaque(), - viewNotReady, 0); - if (0 == ctx) { - if(DEBUG) { - System.err.println("NS create failed: viewNotReady: "+ (1 == viewNotReady[0])); - } - return 0; - } + private OffscreenLayerSurface backingLayerHost = null; + private long nsOpenGLLayer = 0; + private long nsOpenGLLayerPFmt = 0; + private float screenVSyncTimeout; // microSec + private int vsyncTimeout; // microSec - for nsOpenGLLayer mode + private int lastWidth=0, lastHeight=0; // allowing to detect size change + private long lastPBufferHandle = 0; // allowing to detect pbuffer recreation + + @Override + public boolean isNSContext() { return true; } + + @Override + public long create(long share, int ctp, int major, int minor) { + long ctx = 0; + final NativeSurface surface = drawable.getNativeSurface(); + final MacOSXCGLGraphicsConfiguration config = (MacOSXCGLGraphicsConfiguration) surface.getGraphicsConfiguration(); + final GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); + final long nsViewHandle; + final boolean isPBuffer; + final boolean isFBO; + if(drawable instanceof GLFBODrawableImpl) { + nsViewHandle = 0; + isPBuffer = false; + isFBO = true; + if(DEBUG) { + System.err.println("NS create GLFBODrawableImpl drawable: isFBO "+isFBO+", isPBuffer "+isPBuffer+", "+drawable.getClass().getName()+",\n\t"+drawable); + } + } else if(drawable instanceof MacOSXCGLDrawable) { + // we allow null here! (special pbuffer case) + nsViewHandle = ((MacOSXCGLDrawable)MacOSXCGLContext.this.drawable).getNSViewHandle(); + isPBuffer = CGL.isNSOpenGLPixelBuffer(drawable.getHandle()); + isFBO = false; + if(DEBUG) { + System.err.println("NS create MacOSXCGLDrawable drawable handle isFBO "+isFBO+", isPBuffer "+isPBuffer+", "+drawable.getClass().getName()+",\n\t"+drawable); + } + } else { + // we only allow a valid NSView here + final long drawableHandle = drawable.getHandle(); + final boolean isNSView = OSXUtil.isNSView(drawableHandle); + final boolean isNSWindow = OSXUtil.isNSWindow(drawableHandle); + isPBuffer = CGL.isNSOpenGLPixelBuffer(drawableHandle); + isFBO = false; - if (!chosenCaps.isPBuffer() && !chosenCaps.isBackgroundOpaque()) { - // Set the context opacity - CGL.setContextOpacity(ctx, 0); + if(DEBUG) { + System.err.println("NS create Anonymous drawable handle "+toHexString(drawableHandle)+": isNSView "+isNSView+", isNSWindow "+isNSWindow+", isFBO "+isFBO+", isPBuffer "+isPBuffer+", "+drawable.getClass().getName()+",\n\t"+drawable); + } + if( isNSView ) { + nsViewHandle = drawableHandle; + } else if( isNSWindow ) { + nsViewHandle = OSXUtil.GetNSView(drawableHandle); + } else if( isPBuffer ) { + nsViewHandle = 0; + } else { + throw new RuntimeException("Anonymous drawable instance's handle neither NSView, NSWindow nor PBuffer: "+toHexString(drawableHandle)+", "+drawable.getClass().getName()+",\n\t"+drawable); + } } + backingLayerHost = NativeWindowFactory.getOffscreenLayerSurface(surface, true); + boolean allowIncompleteView = null != backingLayerHost; + if( !allowIncompleteView && surface instanceof ProxySurface ) { + allowIncompleteView = ((ProxySurface)surface).containsUpstreamOptionBits( ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE ); + } + long pixelFormat = MacOSXCGLGraphicsConfiguration.GLCapabilities2NSPixelFormat(chosenCaps, ctp, major, minor); + if (pixelFormat == 0) { + if(DEBUG) { + System.err.println("Unable to allocate pixel format with requested GLCapabilities: "+chosenCaps); + } + return 0; + } GLCapabilities fixedCaps = MacOSXCGLGraphicsConfiguration.NSPixelFormat2GLCapabilities(chosenCaps.getGLProfile(), pixelFormat); - fixedCaps = GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(fixedCaps, chosenCaps.isBackgroundOpaque()); - if(!fixedCaps.isPBuffer()) { + if(chosenCaps.isOnscreen() || !fixedCaps.isPBuffer()) { // not handled, so copy them fixedCaps.setFBO(chosenCaps.isFBO()); + fixedCaps.setPBuffer(chosenCaps.isPBuffer()); fixedCaps.setBitmap(chosenCaps.isBitmap()); fixedCaps.setOnscreen(chosenCaps.isOnscreen()); } - config.setChosenCapabilities(fixedCaps); + fixedCaps = GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(fixedCaps, chosenCaps.isBackgroundOpaque()); + int sRefreshRate = OSXUtil.GetScreenRefreshRate(drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getIndex()); + screenVSyncTimeout = 1000000f / sRefreshRate; if(DEBUG) { + System.err.println("NS create OSX>=lion "+isLionOrLater); + System.err.println("NS create allowIncompleteView: "+allowIncompleteView); + System.err.println("NS create backingLayerHost: "+backingLayerHost); + System.err.println("NS create share: "+share); + System.err.println("NS create drawable type: "+drawable.getClass().getName()); + System.err.println("NS create drawable handle: isPBuffer "+isPBuffer+", isFBO "+isFBO); + System.err.println("NS create pixelFormat: "+toHexString(pixelFormat)); + System.err.println("NS create chosenCaps: "+chosenCaps); System.err.println("NS create fixedCaps: "+fixedCaps); + System.err.println("NS create drawable native-handle: "+toHexString(drawable.getHandle())); + System.err.println("NS create drawable NSView-handle: "+toHexString(nsViewHandle)); + System.err.println("NS create screen refresh-rate: "+sRefreshRate+" hz, "+screenVSyncTimeout+" micros"); + // Thread.dumpStack(); } if(fixedCaps.isPBuffer()) { - // Must now associate the pbuffer with our newly-created context - CGL.setContextPBuffer(ctx, drawable.getHandle()); + if(!isPBuffer) { + throw new InternalError("fixedCaps is PBuffer, handle not: "+drawable); + } + } else { + if(isPBuffer) { + throw new InternalError("handle is PBuffer, fixedCaps not: "+drawable); + } } - // - // handled layered surface - // + config.setChosenCapabilities(fixedCaps); + /** if(null != backingLayerHost) { - nsOpenGLLayerPFmt = pixelFormat; - pixelFormat = 0; - final int texWidth, texHeight; - if(drawable instanceof MacOSXPbufferCGLDrawable) { - final MacOSXPbufferCGLDrawable osxPDrawable = (MacOSXPbufferCGLDrawable)drawable; - texWidth = osxPDrawable.getTextureWidth(); - texHeight = osxPDrawable.getTextureHeight(); - } else { - texWidth = drawable.getWidth(); - texHeight = drawable.getHeight(); + backingLayerHost.setChosenCapabilities(fixedCaps); + } */ + + try { + int[] viewNotReady = new int[1]; + // Try to allocate a context with this + ctx = CGL.createContext(share, + nsViewHandle, allowIncompleteView, + pixelFormat, + chosenCaps.isBackgroundOpaque(), + viewNotReady, 0); + if (0 == ctx) { + if(DEBUG) { + System.err.println("NS create failed: viewNotReady: "+ (1 == viewNotReady[0])); + } + return 0; } - if(0>=texWidth || 0>=texHeight || !drawable.isRealized()) { - throw new GLException("Drawable not realized yet or invalid texture size, texSize "+texWidth+"x"+texHeight+", "+drawable); + + if(null != backingLayerHost) { + nsOpenGLLayerPFmt = pixelFormat; + pixelFormat = 0; } - nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, nsOpenGLLayerPFmt, drawable.getHandle(), fixedCaps.isBackgroundOpaque(), texWidth, texHeight); - if (DEBUG) { - System.err.println("NS create nsOpenGLLayer "+toHexString(nsOpenGLLayer)+", texSize "+texWidth+"x"+texHeight+", "+drawable); + + if (chosenCaps.isOnscreen() && !chosenCaps.isBackgroundOpaque()) { + // Set the context opacity + CGL.setContextOpacity(ctx, 0); + } + } finally { + if(0!=pixelFormat) { + CGL.deletePixelFormat(pixelFormat); + pixelFormat = 0; } - backingLayerHost.attachSurfaceLayer(nsOpenGLLayer); - setSwapInterval(1); // enabled per default in layered surface - } - } finally { - if(0!=pixelFormat) { - CGL.deletePixelFormat(pixelFormat); - } - } - return ctx; - } - - @Override - public boolean destroy(long ctx) { - if(0 != nsOpenGLLayer) { - final NativeSurface surface = drawable.getNativeSurface(); - if (DEBUG) { - System.err.println("NS destroy nsOpenGLLayer "+toHexString(nsOpenGLLayer)); - } - final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(surface, true); - if(null != ols && ols.isSurfaceLayerAttached()) { - // still having a valid OLS attached to surface (parent OLS could have been removed) - ols.detachSurfaceLayer(); } - CGL.releaseNSOpenGLLayer(nsOpenGLLayer); - CGL.deletePixelFormat(nsOpenGLLayerPFmt); - nsOpenGLLayerPFmt = 0; - nsOpenGLLayer = 0; + return ctx; } - return CGL.deleteContext(ctx, true); - } - - @Override - public boolean copyImpl(long src, int mask) { - CGL.copyContext(contextHandle, src, mask); - return true; - } - @Override - public boolean makeCurrent(long ctx) { - final long cglCtx = CGL.getCGLContext(ctx); - if(0 == cglCtx) { - throw new InternalError("Null CGLContext for: "+this); + @Override + public boolean destroy(long ctx) { + lastPBufferHandle = 0; + return CGL.deleteContext(ctx, true); } - int err = CGL.CGLLockContext(cglCtx); - if(CGL.kCGLNoError == err) { - return CGL.makeCurrentContext(ctx); - } else if(DEBUG) { - System.err.println("NSGL: Could not lock context: err 0x"+Integer.toHexString(err)+": "+this); + + @Override + public boolean contextRealized(boolean realized) { + if( realized ) { + if( null != backingLayerHost ) { + // + // handled layered surface + // + final GLCapabilitiesImmutable chosenCaps = drawable.getChosenGLCapabilities(); + final long ctx = MacOSXCGLContext.this.getHandle(); + final int texID; + final long drawableHandle = drawable.getHandle(); + if(drawable instanceof GLFBODrawableImpl) { + final GLFBODrawableImpl fbod = (GLFBODrawableImpl)drawable; + texID = fbod.getTextureBuffer(GL.GL_FRONT).getName(); + fbod.setSwapBufferContext(new GLFBODrawableImpl.SwapBufferContext() { + public void swapBuffers(boolean doubleBuffered) { + MacOSXCGLContext.NSOpenGLImpl.this.swapBuffers(); + } } ) ; + lastPBufferHandle = 0; + } else if( chosenCaps.isPBuffer() && CGL.isNSOpenGLPixelBuffer(drawableHandle) ) { + texID = 0; + lastPBufferHandle = drawableHandle; + } else { + throw new GLException("BackingLayerHost w/ unknown handle (!FBO, !PBuffer): "+drawable); + } + lastWidth = drawable.getWidth(); + lastHeight = drawable.getHeight(); + if(0>=lastWidth || 0>=lastHeight || !drawable.isRealized()) { + throw new GLException("Drawable not realized yet or invalid texture size, texSize "+lastWidth+"x"+lastHeight+", "+drawable); + } + nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, nsOpenGLLayerPFmt, lastPBufferHandle, texID, chosenCaps.isBackgroundOpaque(), lastWidth, lastHeight); + if (DEBUG) { + System.err.println("NS create nsOpenGLLayer "+toHexString(nsOpenGLLayer)+" w/ pbuffer "+toHexString(lastPBufferHandle)+", texID "+texID+", texSize "+lastWidth+"x"+lastHeight+", "+drawable); + } + backingLayerHost.attachSurfaceLayer(nsOpenGLLayer); + setSwapInterval(1); // enabled per default in layered surface + } else { + lastWidth = drawable.getWidth(); + lastHeight = drawable.getHeight(); + } + } else { + if( 0 != nsOpenGLLayer ) { + final NativeSurface surface = drawable.getNativeSurface(); + if (DEBUG) { + System.err.println("NS destroy nsOpenGLLayer "+toHexString(nsOpenGLLayer)+", "+drawable); + } + final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(surface, true); + if(null != ols && ols.isSurfaceLayerAttached()) { + // still having a valid OLS attached to surface (parent OLS could have been removed) + ols.detachSurfaceLayer(); + } + CGL.releaseNSOpenGLLayer(nsOpenGLLayer); + nsOpenGLLayer = 0; + } + if(0 != nsOpenGLLayerPFmt) { + CGL.deletePixelFormat(nsOpenGLLayerPFmt); + nsOpenGLLayerPFmt = 0; + } + lastPBufferHandle = 0; + } + backingLayerHost = null; + return true; } - return false; - } - @Override - public boolean release(long ctx) { - try { - gl.glFlush(); // w/o glFlush()/glFinish() OSX < 10.7 (NVidia driver) may freeze - } catch (GLException gle) { - if(DEBUG) { - System.err.println("MacOSXCGLContext.NSOpenGLImpl.release: INFO: glFlush() catched exception:"); - gle.printStackTrace(); + private final void validatePBufferConfig(long ctx) { + final GLCapabilitiesImmutable chosenCaps = drawable.getChosenGLCapabilities(); + final long drawableHandle = drawable.getHandle(); + if(chosenCaps.isPBuffer() && CGL.isNSOpenGLPixelBuffer(drawableHandle) && lastPBufferHandle != drawableHandle) { + // Must associate the pbuffer with our newly-created context + lastPBufferHandle = drawableHandle; + if(0 != drawableHandle) { + CGL.setContextPBuffer(ctx, drawableHandle); + } + if(DEBUG) { + System.err.println("NS.validateDrawableConfig bind pbuffer "+toHexString(drawableHandle)+" -> ctx "+toHexString(ctx)); + } } } - final boolean res = CGL.clearCurrentContext(ctx); - final long cglCtx = CGL.getCGLContext(ctx); - if(0 == cglCtx) { - throw new InternalError("Null CGLContext for: "+this); + + /** Returns true if size has been updated, otherwise false (same size). */ + private final boolean validateDrawableSizeConfig(long ctx) { + final int width = drawable.getWidth(); + final int height = drawable.getHeight(); + if( lastWidth != width || lastHeight != height ) { + lastWidth = drawable.getWidth(); + lastHeight = drawable.getHeight(); + if(DEBUG) { + System.err.println("NS.validateDrawableConfig size changed"); + } + return true; + } + return false; } - final int err = CGL.CGLUnlockContext(cglCtx); - if(DEBUG && CGL.kCGLNoError != err) { - System.err.println("CGL: Could not unlock context: err 0x"+Integer.toHexString(err)+": "+this); + + @Override + public boolean copyImpl(long src, int mask) { + CGL.copyContext(contextHandle, src, mask); + return true; } - return res && CGL.kCGLNoError == err; - } - @Override - public boolean setSwapInterval(int interval) { - if(0 != nsOpenGLLayer) { - CGL.setNSOpenGLLayerSwapInterval(nsOpenGLLayer, interval); - vsyncTimeout = interval * (int)screenVSyncTimeout; - if(DEBUG) { System.err.println("NS setSwapInterval: "+vsyncTimeout+" micros"); } + @Override + public boolean makeCurrent(long ctx) { + final long cglCtx = CGL.getCGLContext(ctx); + if(0 == cglCtx) { + throw new InternalError("Null CGLContext for: "+this); + } + int err = CGL.CGLLockContext(cglCtx); + if(CGL.kCGLNoError == err) { + validatePBufferConfig(ctx); // required to handle pbuffer change ASAP + return CGL.makeCurrentContext(ctx); + } else if(DEBUG) { + System.err.println("NSGL: Could not lock context: err 0x"+Integer.toHexString(err)+": "+this); + } + return false; + } + + @Override + public boolean release(long ctx) { + try { + gl.glFlush(); // w/o glFlush()/glFinish() OSX < 10.7 (NVidia driver) may freeze + } catch (GLException gle) { + if(DEBUG) { + System.err.println("MacOSXCGLContext.NSOpenGLImpl.release: INFO: glFlush() catched exception:"); + gle.printStackTrace(); + } + } + final boolean res = CGL.clearCurrentContext(ctx); + final long cglCtx = CGL.getCGLContext(ctx); + if(0 == cglCtx) { + throw new InternalError("Null CGLContext for: "+this); + } + final int err = CGL.CGLUnlockContext(cglCtx); + if(DEBUG && CGL.kCGLNoError != err) { + System.err.println("CGL: Could not unlock context: err 0x"+Integer.toHexString(err)+": "+this); + } + return res && CGL.kCGLNoError == err; } - CGL.setSwapInterval(contextHandle, interval); - return true; - } - @Override - public boolean swapBuffers() { - if( 0 != nsOpenGLLayer ) { - // If v-sync is disabled, frames will be drawn as quickly as possible - // w/o delay but in sync w/ CALayer. Otherwise wait until next swap interval (v-sync). - CGL.waitUntilNSOpenGLLayerIsReady(nsOpenGLLayer, vsyncTimeout); + @Override + public boolean detachPBuffer() { + if(0 != lastPBufferHandle) { + lastPBufferHandle = 0; + if(0 != nsOpenGLLayer) { + CGL.flushNSOpenGLLayerPBuffer(nsOpenGLLayer); // notify invalid pbuffer + } + // CGL.setContextPBuffer(contextHandle, 0); // doesn't work, i.e. not taking nil + } + return true; } - if(CGL.flushBuffer(contextHandle)) { + + @Override + public boolean setSwapInterval(int interval) { if(0 != nsOpenGLLayer) { - // trigger CALayer to update - CGL.setNSOpenGLLayerNeedsDisplay(nsOpenGLLayer); + CGL.setNSOpenGLLayerSwapInterval(nsOpenGLLayer, interval); + vsyncTimeout = interval * (int)screenVSyncTimeout + 1000; // +1ms + if(DEBUG) { System.err.println("NS setSwapInterval: "+vsyncTimeout+" micros"); } } + CGL.setSwapInterval(contextHandle, interval); return true; } - return false; - } + + private int skipSync=0; + + @Override + public boolean swapBuffers() { + final boolean res; + if( 0 != nsOpenGLLayer ) { + if( validateDrawableSizeConfig(contextHandle) ) { + // skip wait-for-vsync for a few frames if size has changed, + // allowing to update the texture IDs ASAP. + skipSync = 10; + } + + final int texID; + final boolean valid; + if(drawable instanceof GLFBODrawableImpl) { + texID = ((GLFBODrawableImpl)drawable).getTextureBuffer(GL.GL_FRONT).getName(); + valid = 0 != texID; + } else { + texID = 0; + valid = 0 != lastPBufferHandle; + } + if(valid) { + if(0 == skipSync) { + // If v-sync is disabled, frames will be drawn as quickly as possible + // w/o delay but in sync w/ CALayer. Otherwise wait until next swap interval (v-sync). + CGL.waitUntilNSOpenGLLayerIsReady(nsOpenGLLayer, vsyncTimeout); + } else { + skipSync--; + } + res = CGL.flushBuffer(contextHandle); + if(res) { + // trigger CALayer to update incl. possible surface change + CGL.setNSOpenGLLayerNeedsDisplay(nsOpenGLLayer, lastPBufferHandle, texID, lastWidth, lastHeight); + } + } else { + res = true; + } + } else { + res = CGL.flushBuffer(contextHandle); + } + return res; + } + } class CGLImpl implements GLBackendImpl { - @Override - public boolean isNSContext() { return false; } - - @Override - public long create(long share, int ctp, int major, int minor) { - long ctx = 0; - MacOSXCGLGraphicsConfiguration config = (MacOSXCGLGraphicsConfiguration) drawable.getNativeSurface().getGraphicsConfiguration(); - GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable)config.getChosenCapabilities(); - long pixelFormat = MacOSXCGLGraphicsConfiguration.GLCapabilities2CGLPixelFormat(chosenCaps, ctp, major, minor); - if (pixelFormat == 0) { - throw new GLException("Unable to allocate pixel format with requested GLCapabilities"); - } - config.setChosenPixelFormat(pixelFormat); - try { - // Create new context - PointerBuffer ctxPB = PointerBuffer.allocateDirect(1); - if (DEBUG) { - System.err.println("Share context for CGL-based pbuffer context is " + toHexString(share)); + @Override + public boolean isNSContext() { return false; } + + @Override + public long create(long share, int ctp, int major, int minor) { + long ctx = 0; + MacOSXCGLGraphicsConfiguration config = (MacOSXCGLGraphicsConfiguration) drawable.getNativeSurface().getGraphicsConfiguration(); + GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable)config.getChosenCapabilities(); + long pixelFormat = MacOSXCGLGraphicsConfiguration.GLCapabilities2CGLPixelFormat(chosenCaps, ctp, major, minor); + if (pixelFormat == 0) { + throw new GLException("Unable to allocate pixel format with requested GLCapabilities"); } - int res = CGL.CGLCreateContext(pixelFormat, share, ctxPB); - if (res != CGL.kCGLNoError) { - throw new GLException("Error code " + res + " while creating context"); - } - if(chosenCaps.isPBuffer()) { - // Attach newly-created context to the pbuffer - res = CGL.CGLSetPBuffer(ctxPB.get(0), drawable.getHandle(), 0, 0, 0); + try { + // Create new context + PointerBuffer ctxPB = PointerBuffer.allocateDirect(1); + if (DEBUG) { + System.err.println("Share context for CGL-based pbuffer context is " + toHexString(share)); + } + int res = CGL.CGLCreateContext(pixelFormat, share, ctxPB); if (res != CGL.kCGLNoError) { - throw new GLException("Error code " + res + " while attaching context to pbuffer"); + throw new GLException("Error code " + res + " while creating context"); } - } - ctx = ctxPB.get(0); - if(0!=ctx) { - if(DEBUG) { - GLCapabilitiesImmutable caps0 = MacOSXCGLGraphicsConfiguration.CGLPixelFormat2GLCapabilities(pixelFormat); - System.err.println("NS created: "+caps0); + ctx = ctxPB.get(0); + + if (0 != ctx) { + GLCapabilities fixedCaps = MacOSXCGLGraphicsConfiguration.CGLPixelFormat2GLCapabilities(pixelFormat); + fixedCaps = GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(fixedCaps, chosenCaps.isBackgroundOpaque()); + if(chosenCaps.isOnscreen() || !fixedCaps.isPBuffer()) { + // not handled, so copy them + fixedCaps.setFBO(chosenCaps.isFBO()); + fixedCaps.setPBuffer(chosenCaps.isPBuffer()); + fixedCaps.setBitmap(chosenCaps.isBitmap()); + fixedCaps.setOnscreen(chosenCaps.isOnscreen()); + } + config.setChosenCapabilities(fixedCaps); + if(DEBUG) { + System.err.println("CGL create fixedCaps: "+fixedCaps); + } + if(fixedCaps.isPBuffer()) { + // Must now associate the pbuffer with our newly-created context + res = CGL.CGLSetPBuffer(ctx, drawable.getHandle(), 0, 0, 0); + if (res != CGL.kCGLNoError) { + throw new GLException("Error code " + res + " while attaching context to pbuffer"); + } + } } + } finally { + CGL.CGLDestroyPixelFormat(pixelFormat); } - } finally { - CGL.CGLDestroyPixelFormat(pixelFormat); + return ctx; } - return ctx; - } - @Override - public boolean destroy(long ctx) { - return CGL.CGLDestroyContext(ctx) == CGL.kCGLNoError; - } + @Override + public boolean destroy(long ctx) { + return CGL.CGLDestroyContext(ctx) == CGL.kCGLNoError; + } - @Override - public boolean copyImpl(long src, int mask) { - CGL.CGLCopyContext(src, contextHandle, mask); - return true; - } + @Override + public boolean contextRealized(boolean realized) { + return true; + } + + @Override + public boolean copyImpl(long src, int mask) { + CGL.CGLCopyContext(src, contextHandle, mask); + return true; + } - @Override - public boolean makeCurrent(long ctx) { - int err = CGL.CGLLockContext(ctx); - if(CGL.kCGLNoError == err) { - err = CGL.CGLSetCurrentContext(ctx); + @Override + public boolean makeCurrent(long ctx) { + int err = CGL.CGLLockContext(ctx); if(CGL.kCGLNoError == err) { - return true; + err = CGL.CGLSetCurrentContext(ctx); + if(CGL.kCGLNoError == err) { + return true; + } else if(DEBUG) { + System.err.println("CGL: Could not make context current: err 0x"+Integer.toHexString(err)+": "+this); + } } else if(DEBUG) { - System.err.println("CGL: Could not make context current: err 0x"+Integer.toHexString(err)+": "+this); + System.err.println("CGL: Could not lock context: err 0x"+Integer.toHexString(err)+": "+this); } - } else if(DEBUG) { - System.err.println("CGL: Could not lock context: err 0x"+Integer.toHexString(err)+": "+this); + return false; } - return false; - } - @Override - public boolean release(long ctx) { - try { - gl.glFlush(); // w/o glFlush()/glFinish() OSX < 10.7 (NVidia driver) may freeze - } catch (GLException gle) { - if(DEBUG) { - System.err.println("MacOSXCGLContext.CGLImpl.release: INFO: glFlush() catched exception:"); - gle.printStackTrace(); + @Override + public boolean release(long ctx) { + try { + gl.glFlush(); // w/o glFlush()/glFinish() OSX < 10.7 (NVidia driver) may freeze + } catch (GLException gle) { + if(DEBUG) { + System.err.println("MacOSXCGLContext.CGLImpl.release: INFO: glFlush() catched exception:"); + gle.printStackTrace(); + } } + int err = CGL.CGLSetCurrentContext(0); + if(DEBUG && CGL.kCGLNoError != err) { + System.err.println("CGL: Could not release current context: err 0x"+Integer.toHexString(err)+": "+this); + } + int err2 = CGL.CGLUnlockContext(ctx); + if(DEBUG && CGL.kCGLNoError != err2) { + System.err.println("CGL: Could not unlock context: err 0x"+Integer.toHexString(err2)+": "+this); + } + return CGL.kCGLNoError == err && CGL.kCGLNoError == err2; + } + + @Override + public boolean detachPBuffer() { + /* Doesn't work, i.e. not taking NULL + final int res = CGL.CGLSetPBuffer(contextHandle, 0, 0, 0, 0); + if (res != CGL.kCGLNoError) { + throw new GLException("Error code " + res + " while detaching context from pbuffer"); + } */ + return true; } - int err = CGL.CGLSetCurrentContext(0); - if(DEBUG && CGL.kCGLNoError != err) { - System.err.println("CGL: Could not release current context: err 0x"+Integer.toHexString(err)+": "+this); + + @Override + public boolean setSwapInterval(int interval) { + int[] lval = new int[] { interval } ; + CGL.CGLSetParameter(contextHandle, CGL.kCGLCPSwapInterval, lval, 0); + return true; } - int err2 = CGL.CGLUnlockContext(ctx); - if(DEBUG && CGL.kCGLNoError != err2) { - System.err.println("CGL: Could not unlock context: err 0x"+Integer.toHexString(err2)+": "+this); + @Override + public boolean swapBuffers() { + return CGL.kCGLNoError == CGL.CGLFlushDrawable(contextHandle); } - return CGL.kCGLNoError == err && CGL.kCGLNoError == err2; - } - - @Override - public boolean setSwapInterval(int interval) { - int[] lval = new int[] { interval } ; - CGL.CGLSetParameter(contextHandle, CGL.kCGLCPSwapInterval, lval, 0); - return true; - } - @Override - public boolean swapBuffers() { - return CGL.kCGLNoError == CGL.CGLFlushDrawable(contextHandle); - } } } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java index af767f0c3..cc727c8e1 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java @@ -42,10 +42,10 @@ package jogamp.opengl.macosx.cgl; import java.lang.ref.WeakReference; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import javax.media.nativewindow.NativeSurface; +import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; @@ -92,7 +92,7 @@ public abstract class MacOSXCGLDrawable extends GLDrawableImpl { this.id = id; } } - private List> createdContexts = new ArrayList>(); + /* pp */ List> createdContexts = new ArrayList>(); private boolean haveSetOpenGLMode = false; private GLBackendType openGLMode = GLBackendType.NSOPENGL; @@ -110,26 +110,42 @@ public abstract class MacOSXCGLDrawable extends GLDrawableImpl { return GLBackendType.NSOPENGL == openGLMode ? getHandle() : 0; } - protected void registerContext(MacOSXCGLContext ctx) { + @Override + protected void associateContext(GLContext ctx, boolean bound) { // NOTE: we need to keep track of the created contexts in order to // implement swapBuffers() because of how Mac OS X implements its // OpenGL window interface synchronized (createdContexts) { - createdContexts.add(new WeakReference(ctx)); - } + if(bound) { + createdContexts.add(new WeakReference((MacOSXCGLContext)ctx)); + } else { + for(int i=0; i ref = createdContexts.get(i); + final MacOSXCGLContext _ctx = ref.get(); + if( _ctx == null || _ctx == ctx) { + createdContexts.remove(i); + } else { + i++; + } + } + } + } } + @Override - protected final void swapBuffersImpl() { - // single-buffer is already filtered out @ GLDrawableImpl#swapBuffers() - synchronized (createdContexts) { - for (Iterator> iter = createdContexts.iterator(); iter.hasNext(); ) { - WeakReference ref = iter.next(); - MacOSXCGLContext ctx = ref.get(); - if (ctx != null) { - ctx.swapBuffers(); - } else { - iter.remove(); - } + protected final void swapBuffersImpl(boolean doubleBuffered) { + if(doubleBuffered) { + synchronized (createdContexts) { + for(int i=0; i ref = createdContexts.get(i); + final MacOSXCGLContext ctx = ref.get(); + if (ctx != null) { + ctx.swapBuffers(); + i++; + } else { + createdContexts.remove(i); + } + } } } } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java index 591fafc68..e174d38f4 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java @@ -51,7 +51,7 @@ import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.DefaultGraphicsScreen; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.ProxySurface; -import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; +import javax.media.nativewindow.UpstreamSurfaceHook; import javax.media.opengl.GL; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; @@ -61,7 +61,8 @@ import javax.media.opengl.GLDrawable; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; -import jogamp.nativewindow.macosx.OSXUtil; +import jogamp.nativewindow.WrappedSurface; +import jogamp.nativewindow.macosx.OSXDummyUpstreamSurfaceHook; import jogamp.opengl.DesktopGLDynamicLookupHelper; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableFactoryImpl; @@ -71,7 +72,7 @@ import jogamp.opengl.GLGraphicsConfigurationUtil; import com.jogamp.common.JogampRuntimeException; import com.jogamp.common.util.ReflectionUtil; -import com.jogamp.nativewindow.WrappedSurface; +import com.jogamp.nativewindow.MutableGraphicsConfiguration; import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; import com.jogamp.opengl.GLExtensions; @@ -320,9 +321,14 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { @Override protected GLDrawableImpl createOffscreenDrawableImpl(NativeSurface target) { - AbstractGraphicsConfiguration config = target.getGraphicsConfiguration(); - GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); + final MutableGraphicsConfiguration config = (MutableGraphicsConfiguration) target.getGraphicsConfiguration(); + final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); if(!caps.isPBuffer()) { + // Actual implementation is using PBuffer ... + final GLCapabilities modCaps = (GLCapabilities) caps.cloneMutable(); + modCaps.setPBuffer(true); + modCaps.setBitmap(false); + config.setChosenCapabilities(modCaps); return new MacOSXOffscreenCGLDrawable(this, target); } return new MacOSXPbufferCGLDrawable(this, target); @@ -336,7 +342,7 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { @Override protected ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, - GLCapabilitiesChooser chooser, int width, int height, UpstreamSurfaceHook lifecycleHook) { + GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final MacOSXGraphicsDevice device; if(createNewDevice) { device = new MacOSXGraphicsDevice(deviceReq.getUnitID()); @@ -348,68 +354,23 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { if(null == config) { throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); } - return new WrappedSurface(config, 0, width, height, lifecycleHook); + return new WrappedSurface(config, 0, upstreamHook, createNewDevice); } @Override public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(requestedCaps); - return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, width, height, dummySurfaceLifecycleHook); + return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, + new OSXDummyUpstreamSurfaceHook(width, height)); } - private static final ProxySurface.UpstreamSurfaceHook dummySurfaceLifecycleHook = new ProxySurface.UpstreamSurfaceHook() { - long nsWindow = 0; - @Override - public final void create(ProxySurface s) { - if(0 == nsWindow && 0 == s.getSurfaceHandle()) { - nsWindow = OSXUtil.CreateNSWindow(0, 0, s.getWidth(), s.getHeight()); - if(0 == nsWindow) { - throw new GLException("Error NS window 0"); - } - long nsView = OSXUtil.GetNSView(nsWindow); - if(0 == nsView) { - throw new GLException("Error NS view 0"); - } - s.setSurfaceHandle(nsView); - s.setImplBitfield(ProxySurface.INVISIBLE_WINDOW); - if(DEBUG) { - System.err.println("MacOSXCGLDrawableFactory.dummySurfaceLifecycleHook.create: "+s); - } - } - } - @Override - public final void destroy(ProxySurface s) { - if(0 != nsWindow && 0 != s.getSurfaceHandle()) { - OSXUtil.DestroyNSWindow(nsWindow); - nsWindow = 0; - s.setSurfaceHandle(0); - if(DEBUG) { - System.err.println("MacOSXCGLDrawableFactory.dummySurfaceLifecycleHook.destroy: "+s); - } - } - } - @Override - public final int getWidth(ProxySurface s) { - return s.initialWidth; - } - @Override - public final int getHeight(ProxySurface s) { - return s.initialHeight; - } - - @Override - public String toString() { - return "MacOSXLSurfaceLifecycleHook[]"; - } - - }; @Override protected ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { final MacOSXGraphicsDevice device = new MacOSXGraphicsDevice(deviceReq.getUnitID()); final AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, screenIdx); final MacOSXCGLGraphicsConfiguration config = MacOSXCGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen, true); - return new WrappedSurface(config, windowHandle, 0, 0, upstream); + return new WrappedSurface(config, windowHandle, upstream, true); } @Override diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java index 149927160..8866c7ce6 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java @@ -51,23 +51,16 @@ import com.jogamp.common.nio.PointerBuffer; import com.jogamp.nativewindow.MutableGraphicsConfiguration; public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable { - long pixelformat; MacOSXCGLGraphicsConfiguration(AbstractGraphicsScreen screen, - GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, - long pixelformat) { + GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested) { super(screen, capsChosen, capsRequested); - this.pixelformat=pixelformat; } public Object clone() { return super.clone(); } - void setChosenPixelFormat(long pixelformat) { - this.pixelformat=pixelformat; - } - protected static List getAvailableCapabilities(MacOSXCGLDrawableFactory factory, AbstractGraphicsDevice device) { MacOSXCGLDrawableFactory.SharedResource sharedResource = factory.getOrCreateOSXSharedResource(device); if(null == sharedResource) { @@ -114,11 +107,11 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration break; case CGL.kCGLPFAColorFloat: - ivalues[idx] = caps.getPbufferFloatingPointBuffers() ? 1 : 0; + ivalues[idx] = ( !caps.isOnscreen() && caps.isPBuffer() && caps.getPbufferFloatingPointBuffers() ) ? 1 : 0; break; case CGL.NSOpenGLPFAPixelBuffer: - ivalues[idx] = caps.isPBuffer() ? 1 : 0; + ivalues[idx] = ( !caps.isOnscreen() && caps.isPBuffer() ) ? 1 : 0; break; case CGL.NSOpenGLPFADoubleBuffer: @@ -188,11 +181,11 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration attrs[i++] = CGL.kCGLPFAOpenGLProfile; attrs[i++] = MacOSXCGLContext.GLProfile2CGLOGLProfileValue(ctp, major, minor); } - if(caps.isPBuffer()) { + if(!caps.isOnscreen() && caps.isPBuffer()) { attrs[i++] = CGL.kCGLPFAPBuffer; - } - if (caps.getPbufferFloatingPointBuffers()) { - attrs[i++] = CGL.kCGLPFAColorFloat; + if (caps.getPbufferFloatingPointBuffers()) { + attrs[i++] = CGL.kCGLPFAColorFloat; + } } if (caps.getDoubleBuffered()) { attrs[i++] = CGL.kCGLPFADoubleBuffer; diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java index 13faf7090..43a9d0d1a 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java @@ -96,6 +96,6 @@ public class MacOSXCGLGraphicsConfigurationFactory extends GLGraphicsConfigurati capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, GLContext.isFBOAvailable(device, capsChosen.getGLProfile()), factory.canCreateGLPbuffer(device) ); - return new MacOSXCGLGraphicsConfiguration(absScreen, (GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested, 0); + return new MacOSXCGLGraphicsConfiguration(absScreen, (GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested); } } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java index 6be9e386d..65ed5fc15 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java @@ -49,8 +49,8 @@ import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; -import com.jogamp.nativewindow.WrappedSurface; +import jogamp.nativewindow.WrappedSurface; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLContextShareSet; import jogamp.opengl.macosx.cgl.MacOSXCGLDrawable.GLBackendType; @@ -62,7 +62,6 @@ public class MacOSXExternalCGLContext extends MacOSXCGLContext { private MacOSXExternalCGLContext(Drawable drawable, boolean isNSContext, long handle) { super(drawable, null); setOpenGLMode(isNSContext ? GLBackendType.NSOPENGL : GLBackendType.CGL ); - drawable.registerContext(this); this.contextHandle = handle; GLContextShareSet.contextCreated(this); setGLFunctionAvailability(false, 0, 0, CTX_PROFILE_COMPAT); @@ -108,13 +107,13 @@ public class MacOSXExternalCGLContext extends MacOSXCGLContext { } AbstractGraphicsScreen aScreen = DefaultGraphicsScreen.createDefault(NativeWindowFactory.TYPE_MACOSX); - MacOSXCGLGraphicsConfiguration cfg = new MacOSXCGLGraphicsConfiguration(aScreen, caps, caps, pixelFormat); + MacOSXCGLGraphicsConfiguration cfg = new MacOSXCGLGraphicsConfiguration(aScreen, caps, caps); if(0 == currentDrawable) { // set a fake marker stating a valid drawable currentDrawable = 1; } - WrappedSurface ns = new WrappedSurface(cfg, currentDrawable, 64, 64, null); + WrappedSurface ns = new WrappedSurface(cfg, currentDrawable, 64, 64, true); return new MacOSXExternalCGLContext(new Drawable(factory, ns), isNSContext, contextHandle); } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXOnscreenCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXOnscreenCGLDrawable.java index b1e283ebc..ec9628004 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXOnscreenCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXOnscreenCGLDrawable.java @@ -52,9 +52,7 @@ public class MacOSXOnscreenCGLDrawable extends MacOSXCGLDrawable { @Override public GLContext createContext(GLContext shareWith) { - final MacOSXOnscreenCGLContext ctx= new MacOSXOnscreenCGLContext(this, shareWith); - registerContext(ctx); - return ctx; + return new MacOSXOnscreenCGLContext(this, shareWith); } } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLContext.java index 88886ddd2..7e2d8cf10 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLContext.java @@ -39,6 +39,7 @@ import javax.media.opengl.GLPbuffer; import jogamp.opengl.GLContextImpl; +@SuppressWarnings("deprecation") public class MacOSXPbufferCGLContext extends MacOSXCGLContext { // State for render-to-texture and render-to-texture-rectangle support diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java index 8f2f386af..668e463a2 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java @@ -40,6 +40,8 @@ package jogamp.opengl.macosx.cgl; +import java.lang.ref.WeakReference; + import javax.media.nativewindow.DefaultGraphicsConfiguration; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.MutableSurface; @@ -70,9 +72,6 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { // private int textureTarget; // e.g. GL_TEXTURE_2D, GL_TEXTURE_RECTANGLE_NV // private int texture; // actual texture object - // Note that we can not store this in the NativeSurface because the - // semantic is that contains an NSView - protected long pBuffer; protected int pBufferTexTarget, pBufferTexWidth, pBufferTexHeight; public MacOSXPbufferCGLDrawable(GLDrawableFactory factory, NativeSurface target) { @@ -90,9 +89,7 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { @Override public GLContext createContext(GLContext shareWith) { - final MacOSXPbufferCGLContext ctx = new MacOSXPbufferCGLContext(this, shareWith); - registerContext(ctx); - return ctx; + return new MacOSXPbufferCGLContext(this, shareWith); } @Override @@ -101,27 +98,34 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { return 0; } - @Override - public long getHandle() { - return pBuffer; - } - protected int getTextureTarget() { return pBufferTexTarget; } protected int getTextureWidth() { return pBufferTexWidth; } protected int getTextureHeight() { return pBufferTexHeight; } protected void destroyPbuffer() { - if (this.pBuffer != 0) { - NativeSurface ns = getNativeSurface(); + final MutableSurface ms = (MutableSurface) getNativeSurface(); + final long pBuffer = ms.getSurfaceHandle(); + if (0 != pBuffer) { + synchronized (createdContexts) { + for(int i=0; i ref = createdContexts.get(i); + final MacOSXCGLContext ctx = ref.get(); + if (ctx != null) { + ctx.detachPBuffer(); + i++; + } else { + createdContexts.remove(i); + } + } + } impl.destroy(pBuffer); - this.pBuffer = 0; - ((MutableSurface)ns).setSurfaceHandle(0); + ms.setSurfaceHandle(0); } } private void createPbuffer() { - final NativeSurface ns = getNativeSurface(); - final DefaultGraphicsConfiguration config = (DefaultGraphicsConfiguration) ns.getGraphicsConfiguration(); + final MutableSurface ms = (MutableSurface) getNativeSurface(); + final DefaultGraphicsConfiguration config = (DefaultGraphicsConfiguration) ms.getGraphicsConfiguration(); final GLCapabilitiesImmutable capabilities = (GLCapabilitiesImmutable)config.getChosenCapabilities(); final GLProfile glProfile = capabilities.getGLProfile(); MacOSXCGLDrawableFactory.SharedResource sr = ((MacOSXCGLDrawableFactory)factory).getOrCreateOSXSharedResource(config.getScreen().getDevice()); @@ -161,7 +165,7 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { } } - pBuffer = impl.create(pBufferTexTarget, internalFormat, getWidth(), getHeight()); + final long pBuffer = impl.create(pBufferTexTarget, internalFormat, getWidth(), getHeight()); if(DEBUG) { System.err.println("MacOSXPbufferCGLDrawable tex: target "+toHexString(pBufferTexTarget)+ ", pbufferSize "+getWidth()+"x"+getHeight()+ @@ -174,7 +178,7 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { throw new GLException("pbuffer creation error: CGL.createPBuffer() failed"); } - ((MutableSurface)ns).setSurfaceHandle(pBuffer); + ms.setSurfaceHandle(pBuffer); } @Override diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java index 96c1187d3..f6cc2956d 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java @@ -50,8 +50,8 @@ import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; -import com.jogamp.nativewindow.WrappedSurface; +import jogamp.nativewindow.WrappedSurface; import jogamp.nativewindow.windows.GDI; import jogamp.opengl.GLContextShareSet; @@ -102,7 +102,7 @@ public class WindowsExternalWGLContext extends WindowsWGLContext { System.err.println("WindowsExternalWGLContext valid hdc/pfd, retrieved cfg: " + cfg); } } - return new WindowsExternalWGLContext(new Drawable(factory, new WrappedSurface(cfg, hdc, 64, 64, null)), ctx, cfg); + return new WindowsExternalWGLContext(new Drawable(factory, new WrappedSurface(cfg, hdc, 64, 64, true)), ctx, cfg); } @Override diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java index 15bd005dc..f8c237c9e 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java @@ -49,10 +49,10 @@ import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; +import jogamp.nativewindow.WrappedSurface; import jogamp.nativewindow.windows.GDI; import jogamp.nativewindow.windows.GDIUtil; -import com.jogamp.nativewindow.WrappedSurface; public class WindowsExternalWGLDrawable extends WindowsWGLDrawable { @@ -72,7 +72,7 @@ public class WindowsExternalWGLDrawable extends WindowsWGLDrawable { final AbstractGraphicsScreen aScreen = DefaultGraphicsScreen.createDefault(NativeWindowFactory.TYPE_WINDOWS); final WindowsWGLGraphicsConfiguration cfg = WindowsWGLGraphicsConfiguration.createFromExternal(factory, hdc, pfdID, glp, aScreen, true); - return new WindowsExternalWGLDrawable(factory, new WrappedSurface(cfg, hdc, 64, 64, null)); + return new WindowsExternalWGLDrawable(factory, new WrappedSurface(cfg, hdc, 64, 64, true)); } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java index ca7886e7f..3b3f0c123 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java @@ -73,27 +73,28 @@ public abstract class WindowsWGLDrawable extends GLDrawableImpl { } @Override - protected final void swapBuffersImpl() { - // single-buffer is already filtered out @ GLDrawableImpl#swapBuffers() - final long t0; - if (PROFILING) { - t0 = System.currentTimeMillis(); - } else { - t0 = 0; - } - - if (!WGLUtil.SwapBuffers(getHandle()) && (GDI.GetLastError() != GDI.ERROR_SUCCESS)) { - throw new GLException("Error swapping buffers"); - } - - if (PROFILING) { - profilingSwapBuffersTime += System.currentTimeMillis() - t0; - if (++profilingSwapBuffersTicks == PROFILING_TICKS) { - System.err.println("SwapBuffers calls: " + profilingSwapBuffersTime + " ms / " + PROFILING_TICKS + " calls (" + - ((float) profilingSwapBuffersTime / (float) PROFILING_TICKS) + " ms/call)"); - profilingSwapBuffersTime = 0; - profilingSwapBuffersTicks = 0; - } + protected final void swapBuffersImpl(boolean doubleBuffered) { + if(doubleBuffered) { + final long t0; + if (PROFILING) { + t0 = System.currentTimeMillis(); + } else { + t0 = 0; + } + + if (!WGLUtil.SwapBuffers(getHandle()) && (GDI.GetLastError() != GDI.ERROR_SUCCESS)) { + throw new GLException("Error swapping buffers"); + } + + if (PROFILING) { + profilingSwapBuffersTime += System.currentTimeMillis() - t0; + if (++profilingSwapBuffersTicks == PROFILING_TICKS) { + System.err.println("SwapBuffers calls: " + profilingSwapBuffersTime + " ms / " + PROFILING_TICKS + " calls (" + + ((float) profilingSwapBuffersTime / (float) PROFILING_TICKS) + " ms/call)"); + profilingSwapBuffersTime = 0; + profilingSwapBuffersTicks = 0; + } + } } } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java index 7ea487523..91d5c225a 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java @@ -52,7 +52,7 @@ import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.DefaultGraphicsScreen; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.ProxySurface; -import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; +import javax.media.nativewindow.UpstreamSurfaceHook; import javax.media.opengl.GL; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; @@ -62,9 +62,10 @@ import javax.media.opengl.GLDrawable; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; +import jogamp.nativewindow.WrappedSurface; import jogamp.nativewindow.windows.GDI; +import jogamp.nativewindow.windows.GDIDummyUpstreamSurfaceHook; import jogamp.nativewindow.windows.GDISurface; -import jogamp.nativewindow.windows.GDIUtil; import jogamp.nativewindow.windows.RegisteredClassFactory; import jogamp.opengl.DesktopGLDynamicLookupHelper; import jogamp.opengl.GLContextImpl; @@ -79,7 +80,6 @@ import com.jogamp.common.nio.PointerBuffer; import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; import com.jogamp.common.util.VersionNumber; -import com.jogamp.nativewindow.WrappedSurface; import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; import com.jogamp.opengl.GLExtensions; @@ -541,7 +541,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { @Override protected final ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, - GLCapabilitiesChooser chooser, int width, int height, UpstreamSurfaceHook lifecycleHook) { + GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final WindowsGraphicsDevice device; if(createNewDevice) { device = new WindowsGraphicsDevice(deviceReq.getConnection(), deviceReq.getUnitID()); @@ -553,7 +553,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { if(null == config) { throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); } - return new WrappedSurface(config, 0, width, height, lifecycleHook); + return new WrappedSurface(config, 0, upstreamHook, createNewDevice); } @Override @@ -571,57 +571,15 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { if(null == config) { throw new GLException("Choosing GraphicsConfiguration failed w/ "+requestedCaps+" on "+screen); } - return new GDISurface(config, 0, width, height, dummySurfaceLifecycleHook); - } - private static final ProxySurface.UpstreamSurfaceHook dummySurfaceLifecycleHook = new ProxySurface.UpstreamSurfaceHook() { - @Override - public final void create(ProxySurface s) { - final GDISurface ms = (GDISurface)s; - if(0 == ms.getWindowHandle()) { - final long windowHandle = GDIUtil.CreateDummyWindow(0, 0, s.getWidth(), s.getHeight()); - if(0 == windowHandle) { - throw new GLException("Error windowHandle 0, werr: "+GDI.GetLastError()); - } - ms.setWindowHandle(windowHandle); - if(DEBUG) { - System.err.println("WindowsWGLDrawableFactory.dummySurfaceLifecycleHook.create: "+ms); - } - } - } - @Override - public final void destroy(ProxySurface s) { - final GDISurface ms = (GDISurface)s; - if(0 != ms.getWindowHandle()) { - GDI.ShowWindow(ms.getWindowHandle(), GDI.SW_HIDE); - GDIUtil.DestroyDummyWindow(ms.getWindowHandle()); - ms.setWindowHandle(0); - if(DEBUG) { - System.err.println("WindowsWGLDrawableFactory.dummySurfaceLifecycleHook.destroy: "+ms); - } - } - } - @Override - public final int getWidth(ProxySurface s) { - return s.initialWidth; - } - @Override - public final int getHeight(ProxySurface s) { - return s.initialHeight; - } - - @Override - public String toString() { - return "GDISurfaceLifecycleHook[]"; - } - }; - + return new GDISurface(config, 0, new GDIDummyUpstreamSurfaceHook(width, height), createNewDevice); + } @Override protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { final WindowsGraphicsDevice device = new WindowsGraphicsDevice(deviceReq.getConnection(), deviceReq.getUnitID()); final AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, screenIdx); final WindowsWGLGraphicsConfiguration cfg = WindowsWGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen); - return new GDISurface(cfg, windowHandle, 0, 0, upstream); + return new GDISurface(cfg, windowHandle, upstream, true); } @Override diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java index 4d1069e6b..058f4e336 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java @@ -107,7 +107,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio if(hasARB) { caps = wglARBPFID2GLCapabilities(sharedResource, device, glp, hdc, pfdID, GLGraphicsConfigurationUtil.ALL_BITS); } else { - caps = PFD2GLCapabilities(glp, hdc, pfdID, GLGraphicsConfigurationUtil.ALL_BITS); + caps = PFD2GLCapabilities(device, glp, hdc, pfdID, GLGraphicsConfigurationUtil.ALL_BITS); } if(null==caps) { throw new GLException("Couldn't choose Capabilities by: HDC 0x"+Long.toHexString(hdc)+ @@ -325,7 +325,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio throw new GLException("wglARBPFID2GLCapabilities: Error getting pixel format attributes for pixel format " + pfdID + " of device context " + toHexString(hdc) + ", werr " + GDI.GetLastError()); } - return AttribList2GLCapabilities(glp, hdc, pfdID, iattributes, niattribs, iresults, winattrbits); + return AttribList2GLCapabilities(device, glp, hdc, pfdID, iattributes, niattribs, iresults, winattrbits); } static int[] wglChoosePixelFormatARB(WindowsWGLDrawableFactory.SharedResource sharedResource, AbstractGraphicsDevice device, @@ -390,7 +390,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio for(int i = 0; i= 1 && ((WindowsWGLContext)sharedResource.getContext()).getWGLExt().wglGetPixelFormatAttribivARB(hdc, pfdIDs[i], 0, niattribs, iattributes, 0, iresults, 0) ) { - final GLCapabilitiesImmutable caps = AttribList2GLCapabilities(glp, hdc, pfdIDs[i], iattributes, niattribs, iresults, winattrbits); + final GLCapabilitiesImmutable caps = AttribList2GLCapabilities(device, glp, hdc, pfdIDs[i], iattributes, niattribs, iresults, winattrbits); if(null != caps) { bucket.add(caps); if(DEBUG) { @@ -398,7 +398,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio System.err.println("wglARBPFIDs2GLCapabilities: bucket["+i+" -> "+j+"]: "+caps); } } else if(DEBUG) { - GLCapabilitiesImmutable skipped = AttribList2GLCapabilities(glp, hdc, pfdIDs[i], iattributes, niattribs, iresults, GLGraphicsConfigurationUtil.ALL_BITS); + GLCapabilitiesImmutable skipped = AttribList2GLCapabilities(device, glp, hdc, pfdIDs[i], iattributes, niattribs, iresults, GLGraphicsConfigurationUtil.ALL_BITS); System.err.println("wglARBPFIDs2GLCapabilities: bucket["+i+" -> skip]: pfdID "+pfdIDs[i]+", "+skipped+", winattr "+GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrbits).toString()); } } else if (DEBUG) { @@ -616,9 +616,9 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return val; } - static WGLGLCapabilities AttribList2GLCapabilities(final GLProfile glp, - final long hdc, final int pfdID, final int[] iattribs, - final int niattribs, final int[] iresults, final int winattrmask) { + static WGLGLCapabilities AttribList2GLCapabilities(final AbstractGraphicsDevice device, + final GLProfile glp, final long hdc, final int pfdID, + final int[] iattribs, final int niattribs, final int[] iresults, final int winattrmask) { final int allDrawableTypeBits = AttribList2DrawableTypeBits(iattribs, niattribs, iresults); int drawableTypeBits = winattrmask & allDrawableTypeBits; @@ -637,7 +637,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } final WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); res.setValuesByARB(iattribs, niattribs, iresults); - return (WGLGLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(res, drawableTypeBits); + return (WGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); } // @@ -672,7 +672,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return val; } - static WGLGLCapabilities PFD2GLCapabilities(final GLProfile glp, final long hdc, final int pfdID, final int winattrmask) { + static WGLGLCapabilities PFD2GLCapabilities(AbstractGraphicsDevice device, final GLProfile glp, final long hdc, final int pfdID, final int winattrmask) { PIXELFORMATDESCRIPTOR pfd = createPixelFormatDescriptor(hdc, pfdID); if(null == pfd) { return null; @@ -689,21 +689,22 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio final WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); res.setValuesByGDI(); - return (WGLGLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(res, drawableTypeBits ); + return (WGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); } - static WGLGLCapabilities PFD2GLCapabilitiesNoCheck(final GLProfile glp, final long hdc, final int pfdID) { + static WGLGLCapabilities PFD2GLCapabilitiesNoCheck(AbstractGraphicsDevice device, final GLProfile glp, final long hdc, final int pfdID) { PIXELFORMATDESCRIPTOR pfd = createPixelFormatDescriptor(hdc, pfdID); - return PFD2GLCapabilitiesNoCheck(glp, pfd, pfdID); + return PFD2GLCapabilitiesNoCheck(device, glp, pfd, pfdID); } - static WGLGLCapabilities PFD2GLCapabilitiesNoCheck(GLProfile glp, PIXELFORMATDESCRIPTOR pfd, int pfdID) { + static WGLGLCapabilities PFD2GLCapabilitiesNoCheck(AbstractGraphicsDevice device, GLProfile glp, PIXELFORMATDESCRIPTOR pfd, int pfdID) { if(null == pfd) { return null; } final WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); res.setValuesByGDI(); - return (WGLGLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(res, PFD2DrawableTypeBits(pfd)); + + return (WGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, PFD2DrawableTypeBits(pfd), res); } static PIXELFORMATDESCRIPTOR GLCapabilities2PFD(GLCapabilitiesImmutable caps, PIXELFORMATDESCRIPTOR pfd) { diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java index 41c9bba02..d2d1dafc8 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java @@ -113,13 +113,14 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } protected static List getAvailableCapabilities(WindowsWGLDrawableFactory factory, AbstractGraphicsDevice device) { - WindowsWGLDrawableFactory.SharedResource sharedResource = factory.getOrCreateSharedResource(device); + final WindowsWGLDrawableFactory.SharedResource sharedResource = factory.getOrCreateSharedResource(device); if(null == sharedResource) { throw new GLException("Shared resource for device n/a: "+device); } - GLDrawableImpl sharedDrawable = sharedResource.getDrawable(); - GLCapabilitiesImmutable capsChosen = sharedDrawable.getChosenGLCapabilities(); - GLContext sharedContext = sharedResource.getContext(); + final GLDrawableImpl sharedDrawable = sharedResource.getDrawable(); + final GLContext sharedContext = sharedResource.getContext(); + final GLProfile glp = GLProfile.getDefault(device); + List availableCaps = null; if ( sharedResource.needsCurrentContext4ARBPFDQueries() ) { @@ -135,10 +136,10 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat throw new GLException("Error: HDC is null"); } if (sharedResource.hasARBPixelFormat()) { - availableCaps = WindowsWGLGraphicsConfigurationFactory.getAvailableGLCapabilitiesARB(sharedResource, sharedResource.getDevice(), capsChosen.getGLProfile(), hdc); + availableCaps = WindowsWGLGraphicsConfigurationFactory.getAvailableGLCapabilitiesARB(sharedResource, sharedResource.getDevice(), glp, hdc); } if( null == availableCaps || availableCaps.isEmpty() ) { - availableCaps = getAvailableGLCapabilitiesGDI(device, capsChosen.getGLProfile(), hdc); + availableCaps = getAvailableGLCapabilitiesGDI(device, glp, hdc); } } finally { if ( sharedResource.needsCurrentContext4ARBPFDQueries() ) { @@ -165,7 +166,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat int numFormats = pformats.length; List bucket = new ArrayList(numFormats); for (int i = 0; i < numFormats; i++) { - final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(glProfile, hdc, pformats[i], GLGraphicsConfigurationUtil.ALL_BITS); + final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(device, glProfile, hdc, pformats[i], GLGraphicsConfigurationUtil.ALL_BITS); if(null != caps) { bucket.add(caps); } @@ -439,7 +440,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat private static boolean updateGraphicsConfigurationGDI(WindowsWGLGraphicsConfiguration config, CapabilitiesChooser chooser, long hdc, boolean extHDC, int[] pformats) { GLCapabilitiesImmutable capsChosen = (GLCapabilitiesImmutable) config.getChosenCapabilities(); - if(capsChosen.isPBuffer()) { + if( !capsChosen.isOnscreen() && capsChosen.isPBuffer() ) { if (DEBUG) { System.err.println("updateGraphicsConfigurationGDI: no pbuffer supported on GDI: " + capsChosen); } @@ -454,6 +455,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat System.err.println("updateGraphicsConfigurationGDI: capsChosen "+capsChosen+", "+GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrmask).toString()); } + AbstractGraphicsDevice device = config.getScreen().getDevice(); int pfdID; // chosen or preset PFD ID WGLGLCapabilities pixelFormatCaps = null; // chosen or preset PFD ID's caps boolean pixelFormatSet = false; // indicates a preset PFD ID [caps] @@ -468,7 +470,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat + ", pixelformat " + pfdID); } pixelFormatSet = true; - pixelFormatCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(glProfile, hdc, pfdID, winattrmask); + pixelFormatCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(device, glProfile, hdc, pfdID, winattrmask); if(null == pixelFormatCaps) { throw new GLException("Could not map PFD2GLCaps w/ already chosen pfdID "+pfdID); } @@ -480,7 +482,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat List availableCaps = new ArrayList(); for (int i = 0; i < pformats.length; i++) { - final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(glProfile, hdc, pformats[i], winattrmask); + final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(device, glProfile, hdc, pformats[i], winattrmask); if(null != caps) { availableCaps.add(caps); if(DEBUG) { @@ -488,7 +490,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat System.err.println("updateGraphicsConfigurationGDI: availableCaps["+i+" -> "+j+"]: "+caps); } } else if(DEBUG) { - GLCapabilitiesImmutable skipped = WindowsWGLGraphicsConfiguration.PFD2GLCapabilitiesNoCheck(glProfile, hdc, pformats[i]); + GLCapabilitiesImmutable skipped = WindowsWGLGraphicsConfiguration.PFD2GLCapabilitiesNoCheck(device, glProfile, hdc, pformats[i]); System.err.println("updateGraphicsConfigurationGDI: availableCaps["+i+" -> skip]: pfdID "+pformats[i]+", "+skipped); } } @@ -505,8 +507,8 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat recommendedIndex--) { /* nop */ } if(DEBUG && 0 > recommendedIndex) { - final GLCapabilitiesImmutable reqPFDCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilitiesNoCheck(glProfile, pfd, pfdID); - final GLCapabilitiesImmutable chosenCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(glProfile, hdc, pfdID, winattrmask); + final GLCapabilitiesImmutable reqPFDCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilitiesNoCheck(device, glProfile, pfd, pfdID); + final GLCapabilitiesImmutable chosenCaps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(device, glProfile, hdc, pfdID, winattrmask); System.err.println("Chosen PFDID "+pfdID+", but not found in available caps (use given pfdIDs "+givenPFormats+", reqPFDCaps "+reqPFDCaps+", chosenCaps: "+chosenCaps); } } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java index 1f3edbd8a..03a0eefbf 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java @@ -48,10 +48,10 @@ import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; +import jogamp.nativewindow.WrappedSurface; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLContextShareSet; -import com.jogamp.nativewindow.WrappedSurface; import com.jogamp.nativewindow.x11.X11GraphicsScreen; public class X11ExternalGLXContext extends X11GLXContext { @@ -105,7 +105,7 @@ public class X11ExternalGLXContext extends X11GLXContext { cfg = X11GLXGraphicsConfiguration.create(glp, x11Screen, val[0]); } - final WrappedSurface ns = new WrappedSurface(cfg, drawable, w, h, null); + final WrappedSurface ns = new WrappedSurface(cfg, drawable, w, h, true); return new X11ExternalGLXContext(new Drawable(factory, ns), ctx); } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java index 8652e2d4a..ac78c6f4a 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java @@ -45,7 +45,8 @@ import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; -import com.jogamp.nativewindow.WrappedSurface; +import jogamp.nativewindow.WrappedSurface; + import com.jogamp.nativewindow.x11.X11GraphicsScreen; @@ -87,7 +88,7 @@ public class X11ExternalGLXDrawable extends X11GLXDrawable { System.err.println("X11ExternalGLXDrawable: WARNING: forcing GLX_RGBA_TYPE for newly created contexts (current 0x"+Integer.toHexString(val[0])+")"); } } - return new X11ExternalGLXDrawable(factory, new WrappedSurface(cfg, drawable, w, h, null)); + return new X11ExternalGLXDrawable(factory, new WrappedSurface(cfg, drawable, w, h, true)); } @Override diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawable.java index e9912ce9d..8c642777d 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawable.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawable.java @@ -69,9 +69,10 @@ public abstract class X11GLXDrawable extends GLDrawableImpl { } @Override - protected final void swapBuffersImpl() { - // single-buffer is already filtered out @ GLDrawableImpl#swapBuffers() - GLX.glXSwapBuffers(getNativeSurface().getDisplayHandle(), getHandle()); + protected final void swapBuffersImpl(boolean doubleBuffered) { + if(doubleBuffered) { + GLX.glXSwapBuffers(getNativeSurface().getDisplayHandle(), getHandle()); + } } //--------------------------------------------------------------------------- diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index bc3e5b793..fb11f8bba 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -49,7 +49,7 @@ import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; -import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; +import javax.media.nativewindow.UpstreamSurfaceHook; import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesChooser; @@ -59,6 +59,8 @@ import javax.media.opengl.GLDrawable; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; +import jogamp.nativewindow.WrappedSurface; +import jogamp.nativewindow.x11.X11DummyUpstreamSurfaceHook; import jogamp.nativewindow.x11.X11Lib; import jogamp.nativewindow.x11.X11Util; import jogamp.opengl.DesktopGLDynamicLookupHelper; @@ -70,7 +72,6 @@ import jogamp.opengl.GLGraphicsConfigurationUtil; import jogamp.opengl.SharedResourceRunner; import com.jogamp.common.util.VersionNumber; -import com.jogamp.nativewindow.WrappedSurface; import com.jogamp.nativewindow.x11.X11GraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsScreen; @@ -505,7 +506,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { protected final ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, - GLCapabilitiesChooser chooser, int width, int height, UpstreamSurfaceHook lifecycleHook) { + GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final X11GraphicsDevice device; if(createNewDevice) { // Null X11 locking, due to private non-shared Display handle @@ -518,65 +519,15 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { if(null == config) { throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); } - return new WrappedSurface( config, 0, width, height, lifecycleHook); + return new WrappedSurface(config, 0, upstreamHook, createNewDevice); } @Override public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(requestedCaps); - return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, width, height, dummySurfaceLifecycleHook); + return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, new X11DummyUpstreamSurfaceHook(width, height)); } - private static final ProxySurface.UpstreamSurfaceHook dummySurfaceLifecycleHook = new ProxySurface.UpstreamSurfaceHook() { - @Override - public final void create(ProxySurface s) { - if( 0 == s.getSurfaceHandle() ) { - final X11GLXGraphicsConfiguration cfg = (X11GLXGraphicsConfiguration) s.getGraphicsConfiguration(); - final X11GraphicsScreen screen = (X11GraphicsScreen) cfg.getScreen(); - final X11GraphicsDevice device = (X11GraphicsDevice) screen.getDevice(); - if(0 == device.getHandle()) { - device.open(); - s.setImplBitfield(ProxySurface.OWN_DEVICE); - } - final long windowHandle = X11Lib.CreateDummyWindow(device.getHandle(), screen.getIndex(), cfg.getXVisualID(), s.getWidth(), s.getHeight()); - if(0 == windowHandle) { - throw new GLException("Creating dummy window failed w/ "+cfg+", "+s.getWidth()+"x"+s.getHeight()); - } - s.setSurfaceHandle(windowHandle); - if(DEBUG) { - System.err.println("X11GLXDrawableFactory.dummySurfaceLifecycleHook.create: "+s); - } - } - } - @Override - public final void destroy(ProxySurface s) { - if(0 != s.getSurfaceHandle()) { - final X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration) s.getGraphicsConfiguration(); - final X11GraphicsDevice device = (X11GraphicsDevice) config.getScreen().getDevice(); - X11Lib.DestroyDummyWindow(device.getHandle(), s.getSurfaceHandle()); - s.setSurfaceHandle(0); - if( 0 != ( ProxySurface.OWN_DEVICE & s.getImplBitfield() ) ) { - device.close(); - } - if(DEBUG) { - System.err.println("X11GLXDrawableFactory.dummySurfaceLifecycleHook.destroy: "+s); - } - } - } - @Override - public final int getWidth(ProxySurface s) { - return s.initialWidth; - } - @Override - public final int getHeight(ProxySurface s) { - return s.initialHeight; - } - @Override - public String toString() { - return "X11SurfaceLifecycleHook[]"; - } - }; - @Override protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { @@ -593,7 +544,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { if(DEBUG) { System.err.println("X11GLXDrawableFactory.createProxySurfaceImpl 0x"+Long.toHexString(windowHandle)+": "+cfg); } - return new WrappedSurface(cfg, windowHandle, 0, 0, upstream); + return new WrappedSurface(cfg, windowHandle, upstream, true); } @Override diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java index 866fcbbe4..96c3c4123 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java @@ -307,7 +307,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem return null; // no RGBA -> color index not supported } - X11GLCapabilities res = new X11GLCapabilities(visualInfo, fbcfg, fbcfgid, glp); + final X11GLCapabilities res = new X11GLCapabilities(visualInfo, fbcfg, fbcfgid, glp); if (isMultisampleAvailable) { res.setSampleBuffers(glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLE_BUFFERS, tmp, 0) != 0); res.setNumSamples (glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLES, tmp, 0)); @@ -342,7 +342,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem res.setPbufferFloatingPointBuffers(glXGetFBConfig(display, fbcfg, GLXExt.GLX_FLOAT_COMPONENTS_NV, tmp, 0) != GL.GL_FALSE); } catch (Exception e) {} - return (X11GLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(res, drawableTypeBits); + return (X11GLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); } private static String glXGetFBConfigErrorCode(int err) { @@ -462,7 +462,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem res.setAccumBlueBits (glXGetConfig(display, info, GLX.GLX_ACCUM_BLUE_SIZE, tmp, 0)); res.setAccumAlphaBits(glXGetConfig(display, info, GLX.GLX_ACCUM_ALPHA_SIZE, tmp, 0)); - return (X11GLCapabilities) GLGraphicsConfigurationUtil.setWinAttributeBits(res, drawableTypeBits); + return (X11GLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); } private static String glXGetConfigErrorCode(int err) { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java index 8086cd26a..431706e24 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java @@ -129,9 +129,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } final X11GraphicsScreen sharedScreen = (X11GraphicsScreen) sharedResource.getScreen(); final boolean isMultisampleAvailable = factory.isGLXMultisampleAvailable(sharedScreen.getDevice()); - final X11GLXDrawable sharedDrawable = (X11GLXDrawable) sharedResource.getDrawable(); - final GLCapabilitiesImmutable capsChosen = sharedDrawable.getChosenGLCapabilities(); - final GLProfile glp = capsChosen.getGLProfile(); + final GLProfile glp = GLProfile.getDefault(device); List availableCaps = null; @@ -217,7 +215,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, GLContext.isFBOAvailable(x11Device, capsChosen.getGLProfile()), factory.canCreateGLPbuffer(x11Device) ); - boolean usePBuffer = capsChosen.isPBuffer(); + boolean usePBuffer = !capsChosen.isOnscreen() && capsChosen.isPBuffer(); X11GLXGraphicsConfiguration res = null; if( factory.isGLXVersionGreaterEqualOneThree(x11Device) ) { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11PbufferGLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11PbufferGLXDrawable.java index e1fe2f27e..bba2b3513 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11PbufferGLXDrawable.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11PbufferGLXDrawable.java @@ -81,10 +81,11 @@ public class X11PbufferGLXDrawable extends X11GLXDrawable { } private void createPbuffer() { - X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration) getNativeSurface().getGraphicsConfiguration(); - AbstractGraphicsScreen aScreen = config.getScreen(); - AbstractGraphicsDevice aDevice = aScreen.getDevice(); - long display = aDevice.getHandle(); + final MutableSurface ms = (MutableSurface) getNativeSurface(); + final X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration) ms.getGraphicsConfiguration(); + final AbstractGraphicsScreen aScreen = config.getScreen(); + final AbstractGraphicsDevice aDevice = aScreen.getDevice(); + final long display = aDevice.getHandle(); if (DEBUG) { System.out.println("Pbuffer config: " + config); @@ -94,8 +95,6 @@ public class X11PbufferGLXDrawable extends X11GLXDrawable { throw new GLException("Null display"); } - NativeSurface ns = getNativeSurface(); - GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable)config.getChosenCapabilities(); if (chosenCaps.getPbufferRenderToTexture()) { @@ -111,9 +110,9 @@ public class X11PbufferGLXDrawable extends X11GLXDrawable { int[] iattributes = new int[7]; iattributes[niattribs++] = GLX.GLX_PBUFFER_WIDTH; - iattributes[niattribs++] = ns.getWidth(); + iattributes[niattribs++] = ms.getWidth(); iattributes[niattribs++] = GLX.GLX_PBUFFER_HEIGHT; - iattributes[niattribs++] = ns.getHeight(); + iattributes[niattribs++] = ms.getHeight(); iattributes[niattribs++] = GLX.GLX_LARGEST_PBUFFER; // exact iattributes[niattribs++] = 0; iattributes[niattribs++] = 0; @@ -125,7 +124,7 @@ public class X11PbufferGLXDrawable extends X11GLXDrawable { } // Set up instance variables - ((MutableSurface)ns).setSurfaceHandle(pbuffer); + ms.setSurfaceHandle(pbuffer); if (DEBUG) { System.err.println("Created pbuffer " + this); diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m new file mode 100644 index 000000000..63323b76d --- /dev/null +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -0,0 +1,665 @@ +#import "MacOSXWindowSystemInterface.h" +#import +#import +#include "timespec.h" + +// +// CADisplayLink only available on iOS >= 3.1, sad, since it's convenient. +// Use CVDisplayLink otherwise. +// +// #define HAS_CADisplayLink 1 +// + +// lock/sync debug output +// +// #define DBG_SYNC 1 +// +#ifdef DBG_SYNC + // #define SYNC_PRINT(...) NSLog(@ ## __VA_ARGS__) + #define SYNC_PRINT(...) fprintf(stderr, __VA_ARGS__); fflush(stderr) +#else + #define SYNC_PRINT(...) +#endif + +// fps debug output +// +// #define DBG_PERF 1 + +@interface MyNSOpenGLLayer: NSOpenGLLayer +{ +@private + GLfloat gl_texCoords[8]; + +@protected + NSOpenGLContext* parentCtx; + NSOpenGLPixelFormat* parentPixelFmt; + volatile NSOpenGLPixelBuffer* pbuffer; + volatile GLuint textureID; + volatile int texWidth; + volatile int texHeight; +#ifdef HAS_CADisplayLink + CADisplayLink* displayLink; +#else + CVDisplayLinkRef displayLink; +#endif + int tc; + struct timespec tStart; +@public + struct timespec lastWaitTime; + GLint swapInterval; + GLint swapIntervalCounter; + pthread_mutex_t renderLock; + pthread_cond_t renderSignal; + volatile Bool shallDraw; + volatile int newTexWidth; + volatile int newTexHeight; +} + +- (id) setupWithContext: (NSOpenGLContext*) parentCtx + pixelFormat: (NSOpenGLPixelFormat*) pfmt + pbuffer: (NSOpenGLPixelBuffer*) p + texIDArg: (GLuint) texID + opaque: (Bool) opaque + texWidth: (int) texWidth + texHeight: (int) texHeight; + +- (Bool) validateTexSizeWithNewSize; +- (Bool) validateTexSize: (int) _texWidth texHeight: (int) _texHeight; +- (void) setTextureID: (int) _texID; + +- (void) validatePBuffer: (NSOpenGLPixelBuffer*) p; + +- (NSOpenGLContext *)openGLContextForPixelFormat:(NSOpenGLPixelFormat *)pixelFormat; +- (void)disableAnimation; +- (void)pauseAnimation:(Bool)pause; +- (void)deallocPBuffer; +- (void)releaseLayer; +- (void)dealloc; +- (void)setSwapInterval:(int)interval; +- (void)tick; +- (void)waitUntilRenderSignal: (long) to_micros; +- (Bool)isGLSourceValid; + +@end + +#ifndef HAS_CADisplayLink + +static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink, + const CVTimeStamp *inNow, + const CVTimeStamp *inOutputTime, + CVOptionFlags flagsIn, + CVOptionFlags *flagsOut, + void *displayLinkContext) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*)displayLinkContext; + pthread_mutex_lock(&l->renderLock); + if( 0 < l->swapInterval ) { + l->swapIntervalCounter++; + if( l->swapIntervalCounter >= l->swapInterval ) { + SYNC_PRINT("", (int)l->swapIntervalCounter, l->swapInterval); + l->swapIntervalCounter = 0; + pthread_cond_signal(&l->renderSignal); // wake up vsync + } + } + pthread_mutex_unlock(&l->renderLock); + [pool release]; + return kCVReturnSuccess; +} + +#endif + +static const GLfloat gl_verts[] = { + -1.0, -1.0, + -1.0, 1.0, + 1.0, 1.0, + 1.0, -1.0 +}; + +@implementation MyNSOpenGLLayer + +- (id) setupWithContext: (NSOpenGLContext*) _parentCtx + pixelFormat: (NSOpenGLPixelFormat*) _parentPixelFmt + pbuffer: (NSOpenGLPixelBuffer*) p + texIDArg: (GLuint) texID + opaque: (Bool) opaque + texWidth: (int) _texWidth + texHeight: (int) _texHeight; +{ + pthread_mutexattr_t renderLockAttr; + pthread_mutexattr_init(&renderLockAttr); + pthread_mutexattr_settype(&renderLockAttr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&renderLock, &renderLockAttr); // recursive + pthread_cond_init(&renderSignal, NULL); // no attribute + + { + int i; + for(i=0; i<8; i++) { + gl_texCoords[i] = 0.0f; + } + } + parentCtx = _parentCtx; + parentPixelFmt = _parentPixelFmt; + swapInterval = 1; // defaults to on (as w/ new GL profiles) + swapIntervalCounter = 0; + timespec_now(&lastWaitTime); + shallDraw = NO; + newTexWidth = _texWidth; + newTexHeight = _texHeight; + [self validateTexSizeWithNewSize]; + [self setTextureID: texID]; + + pbuffer = p; + if(NULL != pbuffer) { + [pbuffer retain]; + } + + { + // no animations for add/remove/swap sublayers etc + // doesn't work: [self removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] + [self removeAllAnimations]; + } + + // instantiate a deactivated displayLink +#ifdef HAS_CADisplayLink + displayLink = [[CVDisplayLink displayLinkWithTarget:self selector:@selector(setNeedsDisplay)] retain]; +#else + CVReturn cvres; + { + int allDisplaysMask = 0; + int virtualScreen, accelerated, displayMask; + for (virtualScreen = 0; virtualScreen < [parentPixelFmt numberOfVirtualScreens]; virtualScreen++) { + [parentPixelFmt getValues:&displayMask forAttribute:NSOpenGLPFAScreenMask forVirtualScreen:virtualScreen]; + [parentPixelFmt getValues:&accelerated forAttribute:NSOpenGLPFAAccelerated forVirtualScreen:virtualScreen]; + if (accelerated) { + allDisplaysMask |= displayMask; + } + } + cvres = CVDisplayLinkCreateWithOpenGLDisplayMask(allDisplaysMask, &displayLink); + if(kCVReturnSuccess != cvres) { + DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkCreateWithOpenGLDisplayMask %X failed: %d\n", self, allDisplaysMask, cvres); + displayLink = NULL; + } + } + if(NULL != displayLink) { + cvres = CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, [parentCtx CGLContextObj], [parentPixelFmt CGLPixelFormatObj]); + if(kCVReturnSuccess != cvres) { + DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext failed: %d\n", self, cvres); + displayLink = NULL; + } + } + if(NULL != displayLink) { + cvres = CVDisplayLinkSetOutputCallback(displayLink, renderMyNSOpenGLLayer, self); + if(kCVReturnSuccess != cvres) { + DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkSetOutputCallback failed: %d\n", self, cvres); + displayLink = NULL; + } + } +#endif + [self pauseAnimation: YES]; + + [self removeAllAnimations]; + [self setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; + [self setNeedsDisplayOnBoundsChange: YES]; + + [self setOpaque: opaque ? YES : NO]; + + if(NULL != pbuffer) { + DBG_PRINT("MyNSOpenGLLayer::init (pbuffer) %p, ctx %p, pfmt %p, pbuffer %p, opaque %d, pbuffer %dx%d -> tex %dx%d, bounds: %lf/%lf %lfx%lf (refcnt %d)\n", + self, parentCtx, parentPixelFmt, pbuffer, opaque, [pbuffer pixelsWide], [pbuffer pixelsHigh], texWidth, texHeight, + lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, (int)[self retainCount]); + } else { + DBG_PRINT("MyNSOpenGLLayer::init (texture) %p, ctx %p, pfmt %p, opaque %d, tex[id %d, %dx%d], bounds: %lf/%lf %lfx%lf (refcnt %d)\n", + self, parentCtx, parentPixelFmt, opaque, (int)textureID, texWidth, texHeight, + lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, (int)[self retainCount]); + } + return self; +} + +- (Bool) validateTexSizeWithNewSize +{ + return [self validateTexSize: newTexWidth texHeight: newTexHeight]; +} + +- (Bool) validateTexSize: (int) _texWidth texHeight: (int) _texHeight +{ + if(_texHeight != texHeight || _texWidth != texWidth) { + texWidth = _texWidth; + texHeight = _texHeight; + CGRect lRect = [self bounds]; + lRect.origin.x = 0; + lRect.origin.y = 0; + lRect.size.width = texWidth; + lRect.size.height = texHeight; + [self setFrame: lRect]; + + GLfloat texCoordWidth, texCoordHeight; + if(NULL != pbuffer) { + GLenum textureTarget = [pbuffer textureTarget] ; + GLsizei pwidth = [pbuffer pixelsWide]; + GLsizei pheight = [pbuffer pixelsHigh]; + if( GL_TEXTURE_2D == textureTarget ) { + texCoordWidth = (GLfloat)pwidth /(GLfloat)texWidth ; + texCoordHeight = (GLfloat)pheight/(GLfloat)texHeight ; + } else { + texCoordWidth = pwidth; + texCoordHeight = pheight; + } + } else { + texCoordWidth = (GLfloat)1.0f; + texCoordHeight = (GLfloat)1.0f; + } + gl_texCoords[3] = texCoordHeight; + gl_texCoords[5] = texCoordHeight; + gl_texCoords[4] = texCoordWidth; + gl_texCoords[6] = texCoordWidth; + return YES; + } else { + return NO; + } +} + +- (void) setTextureID: (int) _texID +{ + textureID = _texID; +} + +- (void) validatePBuffer: (NSOpenGLPixelBuffer*) p +{ + if( pbuffer != p ) { + DBG_PRINT("MyNSOpenGLLayer::validatePBuffer.0 %p, pbuffer %p, (refcnt %d)\n", self, p, (int)[self retainCount]); + + SYNC_PRINT("{PB-nil}"); + + [self deallocPBuffer]; + + pbuffer = p; + if(NULL != pbuffer) { + [pbuffer retain]; + } + [self setTextureID: 0]; + + shallDraw = NO; + } +} + +/** +- (NSOpenGLPixelFormat *)openGLPixelFormatForDisplayMask:(uint32_t)mask +{ + DBG_PRINT("MyNSOpenGLLayer::openGLPixelFormatForDisplayMask: %p (refcnt %d) - parent-pfmt %p -> new-pfmt %p\n", + self, (int)[self retainCount], parentPixelFmt, parentPixelFmt); + return parentPixelFmt; +} */ + +- (NSOpenGLContext *)openGLContextForPixelFormat:(NSOpenGLPixelFormat *)pixelFormat +{ + NSOpenGLContext * nctx = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:parentCtx]; + DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat: %p (refcnt %d) - pfmt %p, parent %p -> new-ctx %p\n", + self, (int)[self retainCount], pixelFormat, parentCtx, nctx); + return nctx; +} + +- (void)disableAnimation +{ + DBG_PRINT("MyNSOpenGLLayer::disableAnimation: %p (refcnt %d) - displayLink %p\n", self, (int)[self retainCount], displayLink); + pthread_mutex_lock(&renderLock); + [self setAsynchronous: NO]; + if(NULL != displayLink) { +#ifdef HAS_CADisplayLink + [displayLink setPaused: YES]; + [displayLink release]; +#else + CVDisplayLinkStop(displayLink); + CVDisplayLinkRelease(displayLink); +#endif + displayLink = NULL; + } + pthread_mutex_unlock(&renderLock); +} + +- (void)deallocPBuffer +{ + if(NULL != pbuffer) { + NSOpenGLContext* context = [self openGLContext]; + if(NULL!=context) { + [context makeCurrentContext]; + + DBG_PRINT("MyNSOpenGLLayer::deallocPBuffer (with ctx) %p (refcnt %d) - context %p, pbuffer %p, texID %d\n", self, (int)[self retainCount], context, pbuffer, (int)texureID); + + if( 0 != textureID ) { + glDeleteTextures(1, &textureID); + } + [pbuffer release]; + + [context clearDrawable]; + } else { + DBG_PRINT("MyNSOpenGLLayer::deallocPBuffer (w/o ctx) %p (refcnt %d) - context %p, pbuffer %p, texID %d\n", self, (int)[self retainCount], context, pbuffer, (int)texureID); + } + pbuffer = NULL; + [self setTextureID: 0]; + } +} + +- (void)releaseLayer +{ + DBG_PRINT("MyNSOpenGLLayer::releaseLayer.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + pthread_mutex_lock(&renderLock); + [self disableAnimation]; + [self deallocPBuffer]; + [self release]; + DBG_PRINT("MyNSOpenGLLayer::releaseLayer.X: %p (refcnt %d)\n", self, (int)[self retainCount]); + pthread_mutex_unlock(&renderLock); +} + +- (void)dealloc +{ + DBG_PRINT("MyNSOpenGLLayer::dealloc.0 %p (refcnt %d)\n", self, (int)[self retainCount]); + // NSLog(@"MyNSOpenGLLayer::dealloc: %@",[NSThread callStackSymbols]); + + pthread_mutex_lock(&renderLock); + [self disableAnimation]; + [self deallocPBuffer]; + pthread_mutex_unlock(&renderLock); + pthread_cond_destroy(&renderSignal); + pthread_mutex_destroy(&renderLock); + [super dealloc]; + DBG_PRINT("MyNSOpenGLLayer::dealloc.X %p\n", self); +} + +- (Bool)isGLSourceValid +{ + return NULL != pbuffer || 0 != textureID ; +} + +- (void)resizeWithOldSuperlayerSize:(CGSize)size + { + CGRect lRectS = [[self superlayer] bounds]; + + DBG_PRINT("MyNSOpenGLLayer::resizeWithOldSuperlayerSize: %p, texSize %dx%d, bounds: %lfx%lf -> %lfx%lf (refcnt %d)\n", + self, texWidth, texHeight, size.width, size.height, lRectS.size.width, lRectS.size.height, (int)[self retainCount]); + + newTexWidth = lRectS.size.width; + newTexHeight = lRectS.size.height; + shallDraw = YES; + SYNC_PRINT("", newTexWidth, newTexHeight); + + [super resizeWithOldSuperlayerSize: size]; +} + +- (BOOL)canDrawInOpenGLContext:(NSOpenGLContext *)context pixelFormat:(NSOpenGLPixelFormat *)pixelFormat + forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp +{ + SYNC_PRINT("", (int)shallDraw); + return shallDraw; +} + +- (void)drawInOpenGLContext:(NSOpenGLContext *)context pixelFormat:(NSOpenGLPixelFormat *)pixelFormat + forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp +{ + pthread_mutex_unlock(&renderLock); + SYNC_PRINT("<* "); + // NSLog(@"MyNSOpenGLLayer::DRAW: %@",[NSThread callStackSymbols]); + + if( shallDraw && ( NULL != pbuffer || 0 != textureID ) ) { + [context makeCurrentContext]; + + GLenum textureTarget; + + Bool texSizeChanged = [self validateTexSizeWithNewSize]; + + if( NULL != pbuffer ) { + if( texSizeChanged && 0 != textureID ) { + glDeleteTextures(1, &textureID); + [self setTextureID: 0]; + } + textureTarget = [pbuffer textureTarget]; + if( 0 == textureID ) { + glGenTextures(1, &textureID); + glBindTexture(textureTarget, textureID); + glTexParameteri(textureTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(textureTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(textureTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(textureTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } else { + glBindTexture(textureTarget, textureID); + } + [context setTextureImageToPixelBuffer: pbuffer colorBuffer: GL_FRONT]; + } else { + textureTarget = GL_TEXTURE_2D; + glBindTexture(textureTarget, textureID); + } + SYNC_PRINT(" %d*>", (int)textureID); + + glEnable(textureTarget); + + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glVertexPointer(2, GL_FLOAT, 0, gl_verts); + glTexCoordPointer(2, GL_FLOAT, 0, gl_texCoords); + + glDrawArrays(GL_QUADS, 0, 4); + + glDisableClientState(GL_VERTEX_ARRAY); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + + glDisable(textureTarget); + glBindTexture(textureTarget, 0); + + [context clearDrawable]; + + [super drawInOpenGLContext: context pixelFormat: pixelFormat forLayerTime: timeInterval displayTime: timeStamp]; + + } else { + // glClear(GL_COLOR_BUFFER_BIT); + // glBlitFramebuffer(0, 0, texWidth, texHeight, + // 0, 0, texWidth, texHeight, + // GL_COLOR_BUFFER_BIT, GL_NEAREST); + SYNC_PRINT(" 0*>"); + } + + #ifdef DBG_PERF + [self tick]; + #endif + shallDraw = NO; + + if( 0 >= swapInterval ) { + pthread_cond_signal(&renderSignal); // wake up !vsync + SYNC_PRINT(""); + } + SYNC_PRINT("<$>\n"); + pthread_mutex_unlock(&renderLock); +} + +- (void)pauseAnimation:(Bool)pause +{ + DBG_PRINT("MyNSOpenGLLayer::pauseAnimation: %d\n", (int)pause); + [self setAsynchronous: NO]; + if(pause) { + if(NULL != displayLink) { + #ifdef HAS_CADisplayLink + [displayLink setPaused: YES]; + #else + CVDisplayLinkStop(displayLink); + #endif + } + } else { + if(NULL != displayLink) { + #ifdef HAS_CADisplayLink + [displayLink setPaused: NO]; + [displayLink setFrameInterval: swapInterval]; + #else + CVDisplayLinkStart(displayLink); + #endif + } + } + tc = 0; + timespec_now(&tStart); +} + +- (void)setSwapInterval:(int)interval +{ + /** + * v-sync doesn't works w/ NSOpenGLLayer's context .. well :( + * Using CVDisplayLink .. see setSwapInterval() below. + * + GLint si; + [context getValues: &si forParameter: NSOpenGLCPSwapInterval]; + if(si != swapInterval) { + DBG_PRINT("MyNSOpenGLLayer::drawInOpenGLContext %p setSwapInterval: %d -> %d\n", self, si, swapInterval); + [context setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval]; + } + */ + + pthread_mutex_lock(&renderLock); + DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.0: %d - displayLink %p\n", interval, displayLink); + swapInterval = interval; + swapIntervalCounter = 0; + pthread_mutex_unlock(&renderLock); + + if(0 < swapInterval) { + [self pauseAnimation: NO]; + } else { + [self pauseAnimation: YES]; + } + DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.X: %d\n", interval); +} + +-(void)tick +{ + tc++; + if(tc%60==0) { + struct timespec t1, td; + timespec_now(&t1); + timespec_subtract(&td, &t1, &tStart); + long td_ms = timespec_milliseconds(&td); + fprintf(stderr, "NSOpenGLLayer: %ld ms / %d frames, %ld ms / frame, %f fps\n", + td_ms, tc, td_ms/tc, (tc * 1000.0) / (float)td_ms ); + fflush(NULL); + } +} + +- (void)waitUntilRenderSignal: (long) to_micros +{ + BOOL ready = NO; + int wr = 0; + pthread_mutex_lock(&renderLock); + SYNC_PRINT("{W %ld us", to_micros); + do { + if(0 >= swapInterval) { + ready = YES; + } + if(NO == ready) { + #ifdef DBG_SYNC + struct timespec t0, t1, td, td2; + timespec_now(&t0); + #endif + if(0 < to_micros) { + struct timespec to_abs = lastWaitTime; + timespec_addmicros(&to_abs, to_micros); + #ifdef DBG_SYNC + timespec_subtract(&td, &to_abs, &t0); + fprintf(stderr, ", (%ld) / ", timespec_milliseconds(&td)); + #endif + wr = pthread_cond_timedwait(&renderSignal, &renderLock, &to_abs); + #ifdef DBG_SYNC + timespec_now(&t1); + timespec_subtract(&td, &t1, &t0); + timespec_subtract(&td2, &t1, &lastWaitTime); + fprintf(stderr, "(%ld) / (%ld) ms", timespec_milliseconds(&td), timespec_milliseconds(&td2)); + #endif + } else { + pthread_cond_wait (&renderSignal, &renderLock); + #ifdef DBG_SYNC + timespec_now(&t1); + timespec_subtract(&td, &t1, &t0); + timespec_subtract(&td2, &t1, &lastWaitTime); + fprintf(stderr, "(%ld) / (%ld) ms", timespec_milliseconds(&td), timespec_milliseconds(&td2)); + #endif + } + ready = YES; + } + } while (NO == ready && 0 == wr) ; + SYNC_PRINT("-%d-%d-%d}", shallDraw, wr, ready); + timespec_now(&lastWaitTime); + pthread_mutex_unlock(&renderLock); +} + +@end + +NSOpenGLLayer* createNSOpenGLLayer(NSOpenGLContext* ctx, NSOpenGLPixelFormat* fmt, NSOpenGLPixelBuffer* p, uint32_t texID, Bool opaque, int texWidth, int texHeight) { + // This simply crashes after dealloc() has been called .. ie. ref-count -> 0 too early ? + // However using alloc/init, actual dealloc happens at JAWT destruction, hence too later IMHO. + // return [[MyNSOpenGLLayer layer] setupWithContext:ctx pixelFormat: fmt pbuffer: p texIDArg: (GLuint)texID + // opaque: opaque texWidth: texWidth texHeight: texHeight]; + + return [[[MyNSOpenGLLayer alloc] init] setupWithContext:ctx pixelFormat: fmt pbuffer: p texIDArg: (GLuint)texID + opaque: opaque texWidth: texWidth texHeight: texHeight]; +} + +void setNSOpenGLLayerSwapInterval(NSOpenGLLayer* layer, int interval) { + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + [l setSwapInterval: interval]; + [pool release]; +} + +void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_micros) { + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + [l waitUntilRenderSignal: to_micros]; + [pool release]; +} + +void flushNSOpenGLLayerPBuffer(NSOpenGLLayer* layer) { + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + + pthread_mutex_lock(&l->renderLock); + [l validatePBuffer:0]; + pthread_mutex_unlock(&l->renderLock); + + [pool release]; +} + +void setNSOpenGLLayerNeedsDisplay(NSOpenGLLayer* layer, NSOpenGLPixelBuffer* p, uint32_t texID, int texWidth, int texHeight) { + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + Bool shallDraw; + + pthread_mutex_lock(&l->renderLock); + [l validatePBuffer:p]; + // l->newTexWidth = texWidth; + // l->newTexHeight = texHeight; + [l setTextureID: texID]; + shallDraw = [l isGLSourceValid]; + l->shallDraw = shallDraw; + pthread_mutex_unlock(&l->renderLock); + + SYNC_PRINT("", texWidth, texHeight, l->newTexWidth, l->newTexHeight, (int)shallDraw); + if(shallDraw) { + if ( [NSThread isMainThread] == YES ) { + [l setNeedsDisplay]; + } else { + // don't wait - using doublebuffering + [l performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:NO]; + } + } + // DBG_PRINT("MyNSOpenGLLayer::setNSOpenGLLayerNeedsDisplay %p\n", l); + [pool release]; +} + +void releaseNSOpenGLLayer(NSOpenGLLayer* layer) { + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + DBG_PRINT("MyNSOpenGLLayer::releaseNSOpenGLLayer.0: %p\n", l); + + if ( [NSThread isMainThread] == YES ) { + [l releaseLayer]; + } else { + [l performSelectorOnMainThread:@selector(releaseLayer) withObject:nil waitUntilDone:NO]; + } + + DBG_PRINT("MyNSOpenGLLayer::releaseNSOpenGLLayer.X: %p\n", l); + [pool release]; +} + diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m deleted file mode 100644 index b81b43e54..000000000 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m +++ /dev/null @@ -1,494 +0,0 @@ -#import "MacOSXWindowSystemInterface.h" -#import -#import -#include "timespec.h" - -// -// CADisplayLink only available on iOS >= 3.1, sad, since it's convenient. -// Use CVDisplayLink otherwise. -// -// #define HAS_CADisplayLink 1 -// - -// lock/sync debug output -// -// #define DBG_SYNC 1 -// -#ifdef DBG_SYNC - // #define SYNC_PRINT(...) NSLog(@ ## __VA_ARGS__) - #define SYNC_PRINT(...) fprintf(stderr, __VA_ARGS__); fflush(stderr) -#else - #define SYNC_PRINT(...) -#endif - -// fps debug output -// -// #define DBG_PERF 1 - -@interface MyNSOpenGLLayer: NSOpenGLLayer -{ -@protected - NSOpenGLPixelBuffer* pbuffer; - int texWidth; - int texHeight; - GLuint textureID; -#ifdef HAS_CADisplayLink - CADisplayLink* displayLink; -#else - CVDisplayLinkRef displayLink; -#endif - int tc; - struct timespec t0; -@public - struct timespec lastWaitTime; - GLint swapInterval; - GLint swapIntervalCounter; - pthread_mutex_t renderLock; - pthread_cond_t renderSignal; - BOOL shallDraw; -} - -- (id) setupWithContext: (NSOpenGLContext*) ctx - pixelFormat: (NSOpenGLPixelFormat*) pfmt - pbuffer: (NSOpenGLPixelBuffer*) p - opaque: (Bool) opaque - texWidth: (int) texWidth - texHeight: (int) texHeight; - -- (void)deallocTex; -- (void)disableAnimation; -- (void)releaseLayer; -- (void)dealloc; -- (int)getSwapInterval; -- (void)setSwapInterval:(int)interval; -- (void)tick; - -@end - -#ifndef HAS_CADisplayLink - -static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink, - const CVTimeStamp *inNow, - const CVTimeStamp *inOutputTime, - CVOptionFlags flagsIn, - CVOptionFlags *flagsOut, - void *displayLinkContext) -{ - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - MyNSOpenGLLayer* l = (MyNSOpenGLLayer*)displayLinkContext; - pthread_mutex_lock(&l->renderLock); - #ifdef DBG_PERF - [l tick]; - #endif - if(0 < l->swapInterval) { - l->swapIntervalCounter++; - if(l->swapIntervalCounter>=l->swapInterval) { - l->swapIntervalCounter = 0; - pthread_cond_signal(&l->renderSignal); - SYNC_PRINT("S"); - } - } - pthread_mutex_unlock(&l->renderLock); - [pool release]; - return kCVReturnSuccess; -} - -#endif - -@implementation MyNSOpenGLLayer - -- (id) setupWithContext: (NSOpenGLContext*) _ctx - pixelFormat: (NSOpenGLPixelFormat*) _fmt - pbuffer: (NSOpenGLPixelBuffer*) p - opaque: (Bool) opaque - texWidth: (int) _texWidth - texHeight: (int) _texHeight; -{ - pthread_mutexattr_t renderLockAttr; - pthread_mutexattr_init(&renderLockAttr); - pthread_mutexattr_settype(&renderLockAttr, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&renderLock, &renderLockAttr); // recursive - pthread_cond_init(&renderSignal, NULL); // no attribute - - textureID = 0; - swapInterval = 1; // defaults to on (as w/ new GL profiles) - swapIntervalCounter = 0; - timespec_now(&lastWaitTime); - shallDraw = NO; - texWidth = _texWidth; - texHeight = _texHeight; - pbuffer = p; - [pbuffer retain]; - - { - CGRect lRect = CGRectMake(0, 0, texWidth, texHeight); - [self setFrame:lRect]; - - // no animations for add/remove/swap sublayers etc - // doesn't work: [self removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] - [self removeAllAnimations]; - } - - // instantiate a deactivated displayLink -#ifdef HAS_CADisplayLink - displayLink = [[CVDisplayLink displayLinkWithTarget:self selector:@selector(setNeedsDisplay)] retain]; - [displayLink setPaused: YES]; -#else - CVReturn cvres; - { - int allDisplaysMask = 0; - int virtualScreen, accelerated, displayMask; - for (virtualScreen = 0; virtualScreen < [_fmt numberOfVirtualScreens]; virtualScreen++) { - [_fmt getValues:&displayMask forAttribute:NSOpenGLPFAScreenMask forVirtualScreen:virtualScreen]; - [_fmt getValues:&accelerated forAttribute:NSOpenGLPFAAccelerated forVirtualScreen:virtualScreen]; - if (accelerated) { - allDisplaysMask |= displayMask; - } - } - cvres = CVDisplayLinkCreateWithOpenGLDisplayMask(allDisplaysMask, &displayLink); - if(kCVReturnSuccess != cvres) { - DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkCreateWithOpenGLDisplayMask %X failed: %d\n", self, allDisplaysMask, cvres); - displayLink = NULL; - } - } - if(NULL != displayLink) { - cvres = CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, [_ctx CGLContextObj], [_fmt CGLPixelFormatObj]); - if(kCVReturnSuccess != cvres) { - DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext failed: %d\n", self, cvres); - displayLink = NULL; - } - } - if(NULL != displayLink) { - cvres = CVDisplayLinkSetOutputCallback(displayLink, renderMyNSOpenGLLayer, self); - if(kCVReturnSuccess != cvres) { - DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkSetOutputCallback failed: %d\n", self, cvres); - displayLink = NULL; - } - } - if(NULL != displayLink) { - CVDisplayLinkStop(displayLink); - } -#endif - [self setAsynchronous: YES]; - - [self setNeedsDisplayOnBoundsChange: YES]; - - [self setOpaque: opaque ? YES : NO]; - - CGRect lRect = [self frame]; - DBG_PRINT("MyNSOpenGLLayer::init %p, ctx %p, pfmt %p, pbuffer %p, opaque %d, pbuffer %dx%d -> tex %dx%d, frame: %lf/%lf %lfx%lf (refcnt %d)\n", - self, _ctx, _fmt, pbuffer, opaque, [pbuffer pixelsWide], [pbuffer pixelsHigh], texWidth, texHeight, - lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, (int)[self retainCount]); - return self; -} - -- (void)disableAnimation -{ - DBG_PRINT("MyNSOpenGLLayer::disableAnimation: %p (refcnt %d) - displayLink %p\n", self, (int)[self retainCount], displayLink); - pthread_mutex_lock(&renderLock); - [self setAsynchronous: NO]; - if(NULL != displayLink) { -#ifdef HAS_CADisplayLink - [displayLink setPaused: YES]; - [displayLink release]; -#else - CVDisplayLinkStop(displayLink); - CVDisplayLinkRelease(displayLink); -#endif - displayLink = NULL; - } - pthread_mutex_unlock(&renderLock); -} - -- (void)deallocTex -{ - pthread_mutex_lock(&renderLock); - NSOpenGLContext* context = [self openGLContext]; - DBG_PRINT("MyNSOpenGLLayer::deallocTex %p (refcnt %d) - context %p, pbuffer %p\n", self, (int)[self retainCount], context, pbuffer); - if(NULL != pbuffer) { - if(NULL!=context) { - [context makeCurrentContext]; - if(0 != textureID) { - glDeleteTextures(1, &textureID); - textureID = 0; - } - [context clearDrawable]; - } - [pbuffer release]; - pbuffer = NULL; - } - pthread_mutex_unlock(&renderLock); -} - -- (void)releaseLayer -{ - DBG_PRINT("MyNSOpenGLLayer::releaseLayer.0: %p (refcnt %d)\n", self, (int)[self retainCount]); - pthread_mutex_lock(&renderLock); - [self disableAnimation]; - [self deallocTex]; - [self release]; - DBG_PRINT("MyNSOpenGLLayer::releaseLayer.X: %p (refcnt %d)\n", self, (int)[self retainCount]); - pthread_mutex_unlock(&renderLock); -} - -- (void)dealloc -{ - DBG_PRINT("MyNSOpenGLLayer::dealloc.0 %p (refcnt %d)\n", self, (int)[self retainCount]); - // NSLog(@"MyNSOpenGLLayer::dealloc: %@",[NSThread callStackSymbols]); - - [self disableAnimation]; - [self deallocTex]; - pthread_cond_destroy(&renderSignal); - pthread_mutex_destroy(&renderLock); - [super dealloc]; - DBG_PRINT("MyNSOpenGLLayer::dealloc.X %p\n", self); -} - -- (BOOL)canDrawInOpenGLContext:(NSOpenGLContext *)context pixelFormat:(NSOpenGLPixelFormat *)pixelFormat - forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp -{ - // assume both methods 'canDrawInOpenGLContext' and 'drawInOpenGLContext' - // are called from the same thread subsequently - pthread_mutex_lock(&renderLock); - Bool res = NULL != pbuffer && YES == shallDraw; - if(!res) { - SYNC_PRINT("0"); - pthread_mutex_unlock(&renderLock); - } else { - SYNC_PRINT("1"); - } - return res; -} - -- (void)drawInOpenGLContext:(NSOpenGLContext *)context pixelFormat:(NSOpenGLPixelFormat *)pixelFormat - forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp -{ - [context makeCurrentContext]; - - GLenum textureTarget = [pbuffer textureTarget]; - GLfloat texCoordWidth, texCoordHeight; - { - GLsizei pwidth = [pbuffer pixelsWide]; - GLsizei pheight = [pbuffer pixelsHigh]; - texCoordWidth = textureTarget == GL_TEXTURE_2D ? (GLfloat)pwidth /(GLfloat)texWidth : pwidth; - texCoordHeight = textureTarget == GL_TEXTURE_2D ? (GLfloat)pheight/(GLfloat)texHeight : pheight; - } - Bool texCreated = 0 == textureID; - - if(texCreated) { - glGenTextures(1, &textureID); - - CGRect lRect = [self frame]; - DBG_PRINT("MyNSOpenGLLayer::drawInOpenGLContext %p, pbuffer %p %dx%d -> tex %dx%d [%fx%f] id 0x%X target 0x%X, frame: %lf/%lf %lfx%lf (refcnt %d)\n", - self, pbuffer, [pbuffer pixelsWide], [pbuffer pixelsHigh], texWidth, texHeight, texCoordWidth, texCoordHeight, textureID, textureTarget, - lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, (int)[self retainCount]); - } - - glBindTexture(textureTarget, textureID); - - /** - if(texCreated) { - // proper tex size setup - glTexImage2D(textureTarget, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); - } */ - - [context setTextureImageToPixelBuffer: pbuffer colorBuffer: GL_FRONT]; - - glTexParameteri(textureTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(textureTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(textureTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(textureTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - - glEnable(textureTarget); - - static GLfloat verts[] = { - -1.0, -1.0, - -1.0, 1.0, - 1.0, 1.0, - 1.0, -1.0 - }; - - GLfloat tex[] = { - 0.0, 0.0, - 0.0, texCoordHeight, - texCoordWidth, texCoordHeight, - texCoordWidth, 0.0 - }; - - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glVertexPointer(2, GL_FLOAT, 0, verts); - glTexCoordPointer(2, GL_FLOAT, 0, tex); - - glDrawArrays(GL_QUADS, 0, 4); - - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - - glDisable(textureTarget); - glBindTexture(textureTarget, 0); - - [super drawInOpenGLContext: context pixelFormat: pixelFormat forLayerTime: timeInterval displayTime: timeStamp]; - shallDraw = NO; - if(0 >= swapInterval) { - pthread_cond_signal(&renderSignal); // just to wake up - SYNC_PRINT("s"); - } - SYNC_PRINT("$"); - pthread_mutex_unlock(&renderLock); -} - -- (int)getSwapInterval -{ - return swapInterval; -} - -- (void)setSwapInterval:(int)interval -{ - /** - * v-sync doesn't works w/ NSOpenGLLayer's context .. well :( - * Using CVDisplayLink .. see setSwapInterval() below. - * - GLint si; - [context getValues: &si forParameter: NSOpenGLCPSwapInterval]; - if(si != swapInterval) { - DBG_PRINT("MyNSOpenGLLayer::drawInOpenGLContext %p setSwapInterval: %d -> %d\n", self, si, swapInterval); - [context setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval]; - } - } */ - - pthread_mutex_lock(&renderLock); - DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.0: %d - displayLink %p\n", interval, displayLink); - swapInterval = interval; - swapIntervalCounter = 0; - pthread_mutex_unlock(&renderLock); - - if(NULL!=displayLink) { - if(0 < swapInterval) { - tc = 0; - timespec_now(&t0); - - [self setAsynchronous: NO]; - #ifdef HAS_CADisplayLink - [displayLink setPaused: NO]; - [displayLink setFrameInterval: interval]; - #else - DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.1.b.1\n"); - CVDisplayLinkStart(displayLink); - DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.1.b.X\n"); - #endif - } else { - #ifdef HAS_CADisplayLink - [displayLink setPaused: YES]; - #else - DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.0.b.1\n"); - CVDisplayLinkStop(displayLink); - DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.0.b.X\n"); - #endif - [self setAsynchronous: YES]; - } - } - DBG_PRINT("MyNSOpenGLLayer::setSwapInterval.X: %d\n", interval); -} - --(void)tick -{ - tc++; - if(tc%60==0) { - struct timespec t1, td; - timespec_now(&t1); - timespec_subtract(&td, &t1, &t0); - long td_ms = timespec_milliseconds(&td); - fprintf(stderr, "NSOpenGLLayer: %ld ms / %d frames, %ld ms / frame, %f fps\n", - td_ms, tc, td_ms/tc, (tc * 1000.0) / (float)td_ms ); - fflush(NULL); - } -} - -@end - -NSOpenGLLayer* createNSOpenGLLayer(NSOpenGLContext* ctx, NSOpenGLPixelFormat* fmt, NSOpenGLPixelBuffer* p, Bool opaque, int texWidth, int texHeight) { - // This simply crashes after dealloc() has been called .. ie. ref-count -> 0 too early ? - // However using alloc/init, actual dealloc happens at JAWT destruction, hence too later IMHO. - // return [[MyNSOpenGLLayer layer] setupWithContext:ctx pixelFormat: fmt pbuffer: p opaque: opaque texWidth: texWidth texHeight: texHeight]; - - return [[[MyNSOpenGLLayer alloc] init] setupWithContext:ctx pixelFormat: fmt pbuffer: p opaque: opaque texWidth: texWidth texHeight: texHeight]; -} - -void setNSOpenGLLayerSwapInterval(NSOpenGLLayer* layer, int interval) { - MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; - [l setSwapInterval: interval]; -} - -void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_micros) { - MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; - BOOL ready = NO; - int wr = 0; - pthread_mutex_lock(&l->renderLock); - SYNC_PRINT("{"); - do { - if([l getSwapInterval] <= 0) { - ready = !l->shallDraw; - } - if(NO == ready) { - if(0 < to_micros) { - #ifdef DBG_SYNC - struct timespec t0, t1, td, td2; - timespec_now(&t0); - #endif - struct timespec to_abs = l->lastWaitTime; - timespec_addmicros(&to_abs, to_micros); - #ifdef DBG_SYNC - timespec_subtract(&td, &to_abs, &t0); - fprintf(stderr, "(%ld) / ", timespec_milliseconds(&td)); - #endif - wr = pthread_cond_timedwait(&l->renderSignal, &l->renderLock, &to_abs); - #ifdef DBG_SYNC - timespec_now(&t1); - timespec_subtract(&td, &t1, &t0); - timespec_subtract(&td2, &t1, &l->lastWaitTime); - fprintf(stderr, "(%ld) / (%ld) ms", timespec_milliseconds(&td), timespec_milliseconds(&td2)); - #endif - } else { - pthread_cond_wait (&l->renderSignal, &l->renderLock); - } - ready = !l->shallDraw; - } - } while (NO == ready && 0 == wr) ; - SYNC_PRINT("-%d}", ready); - timespec_now(&l->lastWaitTime); - pthread_mutex_unlock(&l->renderLock); -} - -void setNSOpenGLLayerNeedsDisplay(NSOpenGLLayer* layer) { - MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - pthread_mutex_lock(&l->renderLock); - l->shallDraw = YES; - if ( [NSThread isMainThread] == YES ) { - [l setNeedsDisplay]; - } else { - // can't wait, otherwise we may deadlock AWT - [l performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:NO]; - } - SYNC_PRINT("."); - pthread_mutex_unlock(&l->renderLock); - // DBG_PRINT("MyNSOpenGLLayer::setNSOpenGLLayerNeedsDisplay %p\n", l); - [pool release]; -} - -void releaseNSOpenGLLayer(NSOpenGLLayer* layer) { - MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - DBG_PRINT("MyNSOpenGLLayer::releaseNSOpenGLLayer.0: %p\n", l); - - if ( [NSThread isMainThread] == YES ) { - [l releaseLayer]; - } else { - [l performSelectorOnMainThread:@selector(releaseLayer) withObject:nil waitUntilDone:NO]; - } - - DBG_PRINT("MyNSOpenGLLayer::releaseNSOpenGLLayer.X: %p\n", l); - [pool release]; -} - diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m index f774f8f4a..becd41bb2 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m @@ -696,6 +696,11 @@ void setContextTextureImageToPBuffer(NSOpenGLContext* ctx, NSOpenGLPixelBuffer* [pool release]; } +Bool isNSOpenGLPixelBuffer(uint64_t object) { + NSObject *nsObj = (NSObject*) (intptr_t) object; + return [nsObj isMemberOfClass:[NSOpenGLPixelBuffer class]]; +} + #include Bool imagesInitialized = false; static char libGLStr[] = "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib"; @@ -746,38 +751,3 @@ void resetGammaRamp() { CGDisplayRestoreColorSyncSettings(); } -/*** - * The following static functions are copied out of NEWT's OSX impl. - * May need to push code to NativeWindow, to remove duplication. - */ -static NSScreen * NewtScreen_getNSScreenByIndex(int screen_idx) { - NSArray *screens = [NSScreen screens]; - if(screen_idx<0) screen_idx=0; - if(screen_idx>=[screens count]) screen_idx=0; - return (NSScreen *) [screens objectAtIndex: screen_idx]; -} -static CGDirectDisplayID NewtScreen_getCGDirectDisplayIDByNSScreen(NSScreen *screen) { - // Mind: typedef uint32_t CGDirectDisplayID; - however, we assume it's 64bit on 64bit ?! - NSDictionary * dict = [screen deviceDescription]; - NSNumber * val = (NSNumber *) [dict objectForKey: @"NSScreenNumber"]; - // [NSNumber integerValue] returns NSInteger which is 32 or 64 bit native size - return (CGDirectDisplayID) [val integerValue]; -} -static long GetDictionaryLong(CFDictionaryRef theDict, const void* key) -{ - long value = 0; - CFNumberRef numRef; - numRef = (CFNumberRef)CFDictionaryGetValue(theDict, key); - if (numRef != NULL) - CFNumberGetValue(numRef, kCFNumberLongType, &value); - return value; -} -#define CGDDGetModeRefreshRate(mode) GetDictionaryLong((mode), kCGDisplayRefreshRate) - -int getScreenRefreshRate(int scrn_idx) { - NSScreen *screen = NewtScreen_getNSScreenByIndex(scrn_idx); - CGDirectDisplayID display = NewtScreen_getCGDirectDisplayIDByNSScreen(screen); - CFDictionaryRef mode = CGDisplayCurrentMode(display); - return CGDDGetModeRefreshRate(mode); -} - diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookMutableSize.java b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookMutableSize.java new file mode 100644 index 000000000..22c95f3dd --- /dev/null +++ b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookMutableSize.java @@ -0,0 +1,39 @@ +package com.jogamp.nativewindow; + +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +public class DelegatedUpstreamSurfaceHookMutableSize extends UpstreamSurfaceHookMutableSize { + final UpstreamSurfaceHook upstream; + + /** + * @param upstream optional upstream UpstreamSurfaceHook used for {@link #create(ProxySurface)} and {@link #destroy(ProxySurface)}. + * @param width initial width + * @param height initial height + */ + public DelegatedUpstreamSurfaceHookMutableSize(UpstreamSurfaceHook upstream, int width, int height) { + super(width, height); + this.upstream = upstream; + } + + @Override + public final void create(ProxySurface s) { + if(null != upstream) { + upstream.create(s); + } + } + + @Override + public final void destroy(ProxySurface s) { + if(null != upstream) { + upstream.destroy(s); + } + } + + @Override + public String toString() { + return getClass().getSimpleName()+"[ "+ width + "x" + height + ", " + upstream + "]"; + } + +} + diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookWithSurfaceSize.java b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookWithSurfaceSize.java new file mode 100644 index 000000000..85e24582c --- /dev/null +++ b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookWithSurfaceSize.java @@ -0,0 +1,54 @@ +package com.jogamp.nativewindow; + +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +public class DelegatedUpstreamSurfaceHookWithSurfaceSize implements UpstreamSurfaceHook { + final UpstreamSurfaceHook upstream; + final NativeSurface surface; + + /** + * @param upstream optional upstream UpstreamSurfaceHook used for {@link #create(ProxySurface)} and {@link #destroy(ProxySurface)}. + * @param surface mandatory {@link NativeSurface} used for {@link #getWidth(ProxySurface)} and {@link #getHeight(ProxySurface)} + */ + public DelegatedUpstreamSurfaceHookWithSurfaceSize(UpstreamSurfaceHook upstream, NativeSurface surface) { + this.upstream = upstream; + this.surface = surface; + if(null == surface) { + throw new IllegalArgumentException("given surface is null"); + } + } + + @Override + public final void create(ProxySurface s) { + if(null != upstream) { + upstream.create(s); + } + } + + @Override + public final void destroy(ProxySurface s) { + if(null != upstream) { + upstream.destroy(s); + } + } + + @Override + public final int getWidth(ProxySurface s) { + return surface.getWidth(); + } + + @Override + public final int getHeight(ProxySurface s) { + return surface.getHeight(); + } + + @Override + public String toString() { + final String us_s = null != surface ? ( surface.getClass().getName() + ": 0x" + Long.toHexString(surface.getSurfaceHandle()) + " " +surface.getWidth() + "x" + surface.getHeight() ) : "nil"; + return getClass().getSimpleName()+"["+upstream+", "+us_s+"]"; + } + +} + diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSize.java b/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSize.java new file mode 100644 index 000000000..29c540ac4 --- /dev/null +++ b/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSize.java @@ -0,0 +1,45 @@ +package com.jogamp.nativewindow; + +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +public class UpstreamSurfaceHookMutableSize implements UpstreamSurfaceHook.MutableSize { + int width, height; + + /** + * @param width initial width + * @param height initial height + */ + public UpstreamSurfaceHookMutableSize(int width, int height) { + this.width = width; + this.height = height; + } + + @Override + public final void setSize(int width, int height) { + this.width = width; + this.height = height; + } + + @Override + public final int getWidth(ProxySurface s) { + return width; + } + + @Override + public final int getHeight(ProxySurface s) { + return height; + } + @Override + public void create(ProxySurface s) { /* nop */ } + + @Override + public void destroy(ProxySurface s) { /* nop */ } + + @Override + public String toString() { + return getClass().getSimpleName()+"[ "+ width + "x" + height + "]"; + } + +} + diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java b/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java deleted file mode 100644 index b7f6ba45d..000000000 --- a/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package com.jogamp.nativewindow; - -import javax.media.nativewindow.AbstractGraphicsConfiguration; -import javax.media.nativewindow.ProxySurface; - -public class WrappedSurface extends ProxySurface { - protected long surfaceHandle; - - public WrappedSurface(AbstractGraphicsConfiguration cfg, long handle, int initialWidth, int initialHeight, UpstreamSurfaceHook upstream) { - super(cfg, initialWidth, initialHeight, upstream); - surfaceHandle=handle; - } - - @Override - protected void invalidateImpl() { - surfaceHandle = 0; - } - - @Override - public final long getSurfaceHandle() { - return surfaceHandle; - } - - @Override - public final void setSurfaceHandle(long surfaceHandle) { - this.surfaceHandle=surfaceHandle; - } - - @Override - protected final int lockSurfaceImpl() { - return LOCK_SUCCESS; - } - - @Override - protected final void unlockSurfaceImpl() { - } - - @Override - public String toString() { - final UpstreamSurfaceHook ush = getUpstreamSurfaceHook(); - final String ush_s = null != ush ? ( ush.getClass().getName() + ": " + ush ) : "nil"; - - return "WrappedSurface[config " + getPrivateGraphicsConfiguration()+ - ", displayHandle 0x" + Long.toHexString(getDisplayHandle()) + - ", surfaceHandle 0x" + Long.toHexString(getSurfaceHandle()) + - ", size " + getWidth() + "x" + getHeight() + - ", surfaceLock "+surfaceLock+ - ", upstreamSurfaceHook "+ush_s+"]"; - } -} diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index d4b927cf1..a62d08ccf 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -39,12 +39,14 @@ package com.jogamp.nativewindow.awt; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; +import com.jogamp.nativewindow.MutableGraphicsConfiguration; import java.awt.Component; import java.awt.Container; import java.applet.Applet; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowException; @@ -110,21 +112,6 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, this.offscreenSurfaceLayer = 0; } - @Override - public void setShallUseOffscreenLayer(boolean v) { - shallUseOffscreenLayer = v; - } - - @Override - public final boolean getShallUseOffscreenLayer() { - return shallUseOffscreenLayer; - } - - @Override - public final boolean isOffscreenLayerSurfaceEnabled() { - return isOffscreenLayerSurface; - } - protected synchronized void invalidate() { invalidateNative(); jawt = null; @@ -136,26 +123,29 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } protected abstract void invalidateNative(); - protected final void updateBounds(JAWT_Rectangle jawtBounds) { - if(DEBUG) { - final Rectangle jb = new Rectangle(jawtBounds.getX(), jawtBounds.getY(), jawtBounds.getWidth(), jawtBounds.getHeight()); - if(!bounds.equals(jb)) { + protected final boolean updateBounds(JAWT_Rectangle jawtBounds) { + final Rectangle jb = new Rectangle(jawtBounds.getX(), jawtBounds.getY(), jawtBounds.getWidth(), jawtBounds.getHeight()); + final boolean changed = !bounds.equals(jb); + + if(changed) { + if(DEBUG) { System.err.println("JAWTWindow.updateBounds: "+bounds+" -> "+jb); Thread.dumpStack(); } + bounds.setX(jawtBounds.getX()); + bounds.setY(jawtBounds.getY()); + bounds.setWidth(jawtBounds.getWidth()); + bounds.setHeight(jawtBounds.getHeight()); + + if(component instanceof Container) { + java.awt.Insets contInsets = ((Container)component).getInsets(); + insets.setLeftWidth(contInsets.left); + insets.setRightWidth(contInsets.right); + insets.setTopHeight(contInsets.top); + insets.setBottomHeight(contInsets.bottom); + } } - bounds.setX(jawtBounds.getX()); - bounds.setY(jawtBounds.getY()); - bounds.setWidth(jawtBounds.getWidth()); - bounds.setHeight(jawtBounds.getHeight()); - - if(component instanceof Container) { - java.awt.Insets contInsets = ((Container)component).getInsets(); - insets.setLeftWidth(contInsets.left); - insets.setRightWidth(contInsets.right); - insets.setTopHeight(contInsets.top); - insets.setBottomHeight(contInsets.bottom); - } + return changed; } /** @return the JAWT_DrawingSurfaceInfo's (JAWT_Rectangle) bounds, updated with lock */ @@ -181,9 +171,29 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return jawt; } - /** - * {@inheritDoc} - */ + // + // OffscreenLayerOption + // + + @Override + public void setShallUseOffscreenLayer(boolean v) { + shallUseOffscreenLayer = v; + } + + @Override + public final boolean getShallUseOffscreenLayer() { + return shallUseOffscreenLayer; + } + + @Override + public final boolean isOffscreenLayerSurfaceEnabled() { + return isOffscreenLayerSurface; + } + + // + // OffscreenLayerSurface + // + @Override public final void attachSurfaceLayer(final long layerHandle) throws NativeWindowException { if( !isOffscreenLayerSurfaceEnabled() ) { @@ -205,9 +215,6 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } protected abstract void attachSurfaceLayerImpl(final long layerHandle); - /** - * {@inheritDoc} - */ @Override public final void detachSurfaceLayer() throws NativeWindowException { if( !isOffscreenLayerSurfaceEnabled() ) { @@ -232,11 +239,21 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } protected abstract void detachSurfaceLayerImpl(final long layerHandle); + protected final long getAttachedSurfaceLayer() { + return offscreenSurfaceLayer; + } + @Override public final boolean isSurfaceLayerAttached() { return 0 != offscreenSurfaceLayer; } + @Override + public final void setChosenCapabilities(CapabilitiesImmutable caps) { + ((MutableGraphicsConfiguration)getGraphicsConfiguration()).setChosenCapabilities(caps); + getPrivateGraphicsConfiguration().setChosenCapabilities(caps); + } + // // SurfaceUpdateListener // @@ -381,7 +398,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, public final AbstractGraphicsConfiguration getGraphicsConfiguration() { return config.getNativeGraphicsConfiguration(); } - + @Override public final long getDisplayHandle() { return getGraphicsConfiguration().getScreen().getDevice().getHandle(); @@ -393,13 +410,13 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } @Override - public int getWidth() { + public final int getWidth() { return component.getWidth(); } @Override - public int getHeight() { - return component.getHeight(); + public final int getHeight() { + return component.getHeight(); } // diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java index 40042ec81..b824350ff 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java @@ -67,8 +67,8 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl * Note that this is not an open connection, ie no native display handle exist. * This constructor exist to setup a default device connection/unit.
      */ - public EGLGraphicsDevice(String connection, int unitID) { - super(NativeWindowFactory.TYPE_EGL, connection, unitID); + public EGLGraphicsDevice() { + super(NativeWindowFactory.TYPE_EGL, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); this.nativeDisplayID[0] = 0 ; // EGL.EGL_DEFAULT_DISPLAY this.eglLifecycleCallback = null; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java index cec7d4ec3..27462ae70 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java @@ -124,8 +124,11 @@ public interface NativeSurface extends SurfaceUpdatedListener { /** * Provide a mechanism to utilize custom (pre-) swap surface * code. This method is called before the render toolkit (e.g. JOGL) - * swaps the buffer/surface. The implementation may itself apply the swapping, + * swaps the buffer/surface if double buffering is enabled. + *

      + * The implementation may itself apply the swapping, * in which case true shall be returned. + *

      * * @return true if this method completed swapping the surface, * otherwise false, in which case eg the GLDrawable diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index f7dbc6c27..f9800109c 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -50,4 +50,7 @@ public interface OffscreenLayerSurface { /** Returns true if a surface layer is attached, otherwise false. */ public boolean isSurfaceLayerAttached(); + /** Sets the capabilities of this instance, allowing upstream API's to refine it, i.e. OpenGL related settings. */ + public void setChosenCapabilities(CapabilitiesImmutable caps); + } diff --git a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java index 7fc9789c2..395fdc818 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java @@ -1,5 +1,5 @@ /** - * Copyright 2010 JogAmp Community. All rights reserved. + * Copyright 2012 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: @@ -29,242 +29,82 @@ package javax.media.nativewindow; import jogamp.nativewindow.Debug; -import jogamp.nativewindow.SurfaceUpdatedHelper; -import com.jogamp.common.util.locks.LockFactory; -import com.jogamp.common.util.locks.RecursiveLock; - -public abstract class ProxySurface implements NativeSurface, MutableSurface { +/** + * Provides a mutable {@link NativeSurface}, i.e. {@link MutableSurface}, while allowing an + * {@link UpstreamSurfaceHook} to influence the lifecycle and information. + * + * @see UpstreamSurfaceHook + * @see MutableSurface + * @see NativeSurface + */ +public interface ProxySurface extends MutableSurface { public static final boolean DEBUG = Debug.debug("ProxySurface"); /** - * Implementation specific bitvalue stating the upstream's {@link AbstractGraphicsDevice} is owned by this {@link ProxySurface}. - * @see #setImplBitfield(int) - * @see #getImplBitfield() + * Implementation specific bit-value stating this {@link ProxySurface} owns the upstream's surface handle + * @see #addUpstreamOptionBits(int) + * @see #getUpstreamOptionBits() */ - public static final int OWN_DEVICE = 1 << 7; + public static final int OPT_PROXY_OWNS_UPSTREAM_SURFACE = 1 << 6; + + /** + * Implementation specific bit-value stating this {@link ProxySurface} owns the upstream's {@link AbstractGraphicsDevice}. + * @see #addUpstreamOptionBits(int) + * @see #getUpstreamOptionBits() + */ + public static final int OPT_PROXY_OWNS_UPSTREAM_DEVICE = 1 << 7; /** * Implementation specific bitvalue stating the upstream's {@link NativeSurface} is an invisible window, i.e. maybe incomplete. - * @see #setImplBitfield(int) - * @see #getImplBitfield() + * @see #addUpstreamOptionBits(int) + * @see #getUpstreamOptionBits() */ - public static final int INVISIBLE_WINDOW = 1 << 8; + public static final int OPT_UPSTREAM_WINDOW_INVISIBLE = 1 << 8; - /** Interface allowing upstream caller to pass lifecycle actions and size info to a {@link ProxySurface} instance. */ - public interface UpstreamSurfaceHook { - /** called within {@link ProxySurface#createNotify()} within lock, before using surface. */ - public void create(ProxySurface s); - /** called within {@link ProxySurface#destroyNotify()} within lock, before clearing fields. */ - public void destroy(ProxySurface s); + /** Allow redefining the AbstractGraphicsConfiguration */ + public void setGraphicsConfiguration(AbstractGraphicsConfiguration cfg); - /** Returns the width of the upstream surface */ - public int getWidth(ProxySurface s); - /** Returns the height of the upstream surface */ - public int getHeight(ProxySurface s); - } + /** Returns the set {@link UpstreamSurfaceHook}, or null if not set. */ + public UpstreamSurfaceHook getUpstreamSurfaceHook(); - private final SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); - private final AbstractGraphicsConfiguration config; // control access due to delegation - private final UpstreamSurfaceHook upstream; - public final int initialWidth; - public final int initialHeight; - private long surfaceHandle_old; - protected RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); - protected long displayHandle; - protected int scrnIndex; - protected int implBitfield; - /** - * @param cfg the {@link AbstractGraphicsConfiguration} to be used - * @param initialWidth the initial width - * @param initialHeight the initial height + * Sets the {@link UpstreamSurfaceHook} and returns the previous value. */ - protected ProxySurface(AbstractGraphicsConfiguration cfg, int initialWidth, int initialHeight, UpstreamSurfaceHook upstream) { - if(null == cfg) { - throw new IllegalArgumentException("null config"); - } - this.config = cfg; - this.upstream = upstream; - this.initialWidth = initialWidth; - this.initialHeight = initialHeight; - this.displayHandle=config.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); - this.surfaceHandle_old = 0; - this.implBitfield = 0; - } - - public final UpstreamSurfaceHook getUpstreamSurfaceHook() { return upstream; } + public void setUpstreamSurfaceHook(UpstreamSurfaceHook hook); + + /** + * Enables or disables the {@link UpstreamSurfaceHook} lifecycle functions + * {@link UpstreamSurfaceHook#create(ProxySurface)} and {@link UpstreamSurfaceHook#destroy(ProxySurface)}. + *

      + * Use this for small code blocks where the native resources shall not change, + * i.e. resizing a derived (OpenGL) drawable. + *

      + */ + public void enableUpstreamSurfaceHookLifecycle(boolean enable); /** - * If a valid {@link UpstreamSurfaceHook} instance is passed in the - * {@link ProxySurface#ProxySurface(AbstractGraphicsConfiguration, int, int, UpstreamSurfaceHook) constructor}, * {@link UpstreamSurfaceHook#create(ProxySurface)} is being issued and the proxy surface/window handles shall be set. */ - public void createNotify() { - if(null != upstream) { - upstream.create(this); - } - this.displayHandle=config.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); - this.surfaceHandle_old = 0; - } + public void createNotify(); /** - * If a valid {@link UpstreamSurfaceHook} instance is passed in the - * {@link ProxySurface#ProxySurface(AbstractGraphicsConfiguration, int, int, UpstreamSurfaceHook) constructor}, - * {@link UpstreamSurfaceHook#destroy(ProxySurface)} is being issued and all fields are cleared. + * {@link UpstreamSurfaceHook#destroy(ProxySurface)} is being issued and all proxy surface/window handles shall be cleared. */ - public void destroyNotify() { - if(null != upstream) { - upstream.destroy(this); - invalidateImpl(); - } - this.displayHandle = 0; - this.surfaceHandle_old = 0; - } + public void destroyNotify(); - /** - * Must be overridden by implementations allowing having a {@link UpstreamSurfaceHook} being passed. - * @see #destroyNotify() - */ - protected void invalidateImpl() { - throw new InternalError("UpstreamSurfaceHook given, but required method not implemented."); - } + public StringBuilder getUpstreamOptionBits(StringBuilder sink); + public int getUpstreamOptionBits(); - @Override - public final long getDisplayHandle() { - return displayHandle; - } - - protected final AbstractGraphicsConfiguration getPrivateGraphicsConfiguration() { - return config; - } - - @Override - public final AbstractGraphicsConfiguration getGraphicsConfiguration() { - return config.getNativeGraphicsConfiguration(); - } - - @Override - public final int getScreenIndex() { - return getGraphicsConfiguration().getScreen().getIndex(); - } - - @Override - public abstract long getSurfaceHandle(); - - @Override - public abstract void setSurfaceHandle(long surfaceHandle); + /** Returns true if the give bit-mask v is set in this instance upstream-option-bits, otherwise false.*/ + public boolean containsUpstreamOptionBits(int v); - @Override - public final int getWidth() { - if(null != upstream) { - return upstream.getWidth(this); - } - return initialWidth; - } - - @Override - public final int getHeight() { - if(null != upstream) { - return upstream.getHeight(this); - } - return initialHeight; - } - - @Override - public boolean surfaceSwap() { - return false; - } - - @Override - public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { - surfaceUpdatedHelper.addSurfaceUpdatedListener(l); - } - - @Override - public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { - surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); - } - - @Override - public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { - surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); - } - - @Override - public void surfaceUpdated(Object updater, NativeSurface ns, long when) { - surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); - } - - @Override - public int lockSurface() throws NativeWindowException, RuntimeException { - surfaceLock.lock(); - int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? - - if ( LOCK_SURFACE_NOT_READY == res ) { - try { - final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); - adevice.lock(); - try { - res = lockSurfaceImpl(); - if(LOCK_SUCCESS == res && surfaceHandle_old != getSurfaceHandle()) { - res = LOCK_SURFACE_CHANGED; - if(DEBUG) { - System.err.println("ProxySurface: surface change 0x"+Long.toHexString(surfaceHandle_old)+" -> 0x"+Long.toHexString(getSurfaceHandle())); - // Thread.dumpStack(); - } - } - } finally { - if (LOCK_SURFACE_NOT_READY >= res) { - adevice.unlock(); - } - } - } finally { - if (LOCK_SURFACE_NOT_READY >= res) { - surfaceLock.unlock(); - } - } - } - return res; - } - - @Override - public final void unlockSurface() { - surfaceLock.validateLocked(); - surfaceHandle_old = getSurfaceHandle(); - - if (surfaceLock.getHoldCount() == 1) { - final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); - try { - unlockSurfaceImpl(); - } finally { - adevice.unlock(); - } - } - surfaceLock.unlock(); - } - - protected abstract int lockSurfaceImpl(); - - protected abstract void unlockSurfaceImpl() ; - - public final void validateSurfaceLocked() { - surfaceLock.validateLocked(); - } - - @Override - public final boolean isSurfaceLockedByOtherThread() { - return surfaceLock.isLockedByOtherThread(); - } - - @Override - public final Thread getSurfaceLockOwner() { - return surfaceLock.getOwner(); - } + /** Add the given bit-mask to this instance upstream-option-bits using bit-or w/ v.*/ + public void addUpstreamOptionBits(int v); - @Override - public abstract String toString(); + /** Clear the given bit-mask from this instance upstream-option-bits using bit-and w/ ~v*/ + public void clearUpstreamOptionBits(int v); - public int getImplBitfield() { return implBitfield; } - public void setImplBitfield(int v) { implBitfield=v; } + public StringBuilder toString(StringBuilder sink); + public String toString(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/UpstreamSurfaceHook.java b/src/nativewindow/classes/javax/media/nativewindow/UpstreamSurfaceHook.java new file mode 100644 index 000000000..6fe2e5364 --- /dev/null +++ b/src/nativewindow/classes/javax/media/nativewindow/UpstreamSurfaceHook.java @@ -0,0 +1,52 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package javax.media.nativewindow; + +/** + * Interface allowing upstream caller to pass lifecycle actions and size info + * to a {@link ProxySurface} instance. + */ +public interface UpstreamSurfaceHook { + /** called within {@link ProxySurface#createNotify()} within lock, before using surface. */ + public void create(ProxySurface s); + /** called within {@link ProxySurface#destroyNotify()} within lock, before clearing fields. */ + public void destroy(ProxySurface s); + + /** Returns the width of the upstream surface, used if {@link ProxySurface#UPSTREAM_PROVIDES_SIZE} is set. */ + public int getWidth(ProxySurface s); + /** Returns the height of the upstream surface, used if {@link ProxySurface#UPSTREAM_PROVIDES_SIZE} is set. */ + public int getHeight(ProxySurface s); + + /** + * {@link UpstreamSurfaceHook} w/ mutable size, allowing it's {@link ProxySurface} user to resize. + */ + public interface MutableSize extends UpstreamSurfaceHook { + public void setSize(int width, int height); + } +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java new file mode 100644 index 000000000..63f56cbae --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java @@ -0,0 +1,326 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.nativewindow; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.SurfaceUpdatedListener; +import javax.media.nativewindow.UpstreamSurfaceHook; + + +import com.jogamp.common.util.locks.LockFactory; +import com.jogamp.common.util.locks.RecursiveLock; + +public abstract class ProxySurfaceImpl implements ProxySurface { + private final SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); + protected long displayHandle; // convenient ref of config.screen.device.handle + private AbstractGraphicsConfiguration config; // control access due to delegation + private UpstreamSurfaceHook upstream; + private long surfaceHandle_old; + private RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); + private int implBitfield; + private boolean upstreamSurfaceHookLifecycleEnabled; + + /** + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param upstream the {@link UpstreamSurfaceHook} to be used + * @param ownsDevice true if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise false. Owning the device implies closing it at {@link #destroyNotify()}. + */ + protected ProxySurfaceImpl(AbstractGraphicsConfiguration cfg, UpstreamSurfaceHook upstream, boolean ownsDevice) { + if(null == cfg) { + throw new IllegalArgumentException("null AbstractGraphicsConfiguration"); + } + if(null == upstream) { + throw new IllegalArgumentException("null UpstreamSurfaceHook"); + } + this.config = cfg; + this.displayHandle=config.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); + this.upstream = upstream; + this.surfaceHandle_old = 0; + this.implBitfield = 0; + this.upstreamSurfaceHookLifecycleEnabled = true; + if(ownsDevice) { + addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + } + + @Override + public final UpstreamSurfaceHook getUpstreamSurfaceHook() { return upstream; } + + @Override + public void setUpstreamSurfaceHook(UpstreamSurfaceHook hook) { + if(null == hook) { + throw new IllegalArgumentException("null UpstreamSurfaceHook"); + } + upstream = hook; + } + + @Override + public final void enableUpstreamSurfaceHookLifecycle(boolean enable) { + upstreamSurfaceHookLifecycleEnabled = enable; + } + + @Override + public void createNotify() { + if(upstreamSurfaceHookLifecycleEnabled) { + upstream.create(this); + } + this.displayHandle=config.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); + this.surfaceHandle_old = 0; + } + + @Override + public void destroyNotify() { + if(upstreamSurfaceHookLifecycleEnabled) { + upstream.destroy(this); + if( containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ) ) { + final AbstractGraphicsDevice aDevice = getGraphicsConfiguration().getScreen().getDevice(); + aDevice.close(); + clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + invalidateImpl(); + } + this.displayHandle = 0; + this.surfaceHandle_old = 0; + } + + /** + * Must be overridden by implementations allowing having a {@link UpstreamSurfaceHook} being passed. + * @see #destroyNotify() + */ + protected void invalidateImpl() { + throw new InternalError("UpstreamSurfaceHook given, but required method not implemented."); + } + + @Override + public final long getDisplayHandle() { + return displayHandle; + } + + protected final AbstractGraphicsConfiguration getPrivateGraphicsConfiguration() { + return config; + } + + @Override + public final AbstractGraphicsConfiguration getGraphicsConfiguration() { + return config.getNativeGraphicsConfiguration(); + } + + @Override + public final void setGraphicsConfiguration(AbstractGraphicsConfiguration cfg) { + config = cfg; + } + + @Override + public final int getScreenIndex() { + return getGraphicsConfiguration().getScreen().getIndex(); + } + + @Override + public abstract long getSurfaceHandle(); + + @Override + public abstract void setSurfaceHandle(long surfaceHandle); + + @Override + public final int getWidth() { + return upstream.getWidth(this); + } + + @Override + public final int getHeight() { + return upstream.getHeight(this); + } + + @Override + public boolean surfaceSwap() { + return false; + } + + @Override + public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { + surfaceUpdatedHelper.addSurfaceUpdatedListener(l); + } + + @Override + public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { + surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); + } + + @Override + public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { + surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); + } + + @Override + public void surfaceUpdated(Object updater, NativeSurface ns, long when) { + surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); + } + + @Override + public int lockSurface() throws NativeWindowException, RuntimeException { + surfaceLock.lock(); + int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? + + if ( LOCK_SURFACE_NOT_READY == res ) { + try { + final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); + adevice.lock(); + try { + res = lockSurfaceImpl(); + if(LOCK_SUCCESS == res && surfaceHandle_old != getSurfaceHandle()) { + res = LOCK_SURFACE_CHANGED; + if(DEBUG) { + System.err.println("ProxySurfaceImpl: surface change 0x"+Long.toHexString(surfaceHandle_old)+" -> 0x"+Long.toHexString(getSurfaceHandle())); + // Thread.dumpStack(); + } + } + } finally { + if (LOCK_SURFACE_NOT_READY >= res) { + adevice.unlock(); + } + } + } finally { + if (LOCK_SURFACE_NOT_READY >= res) { + surfaceLock.unlock(); + } + } + } + return res; + } + + @Override + public final void unlockSurface() { + surfaceLock.validateLocked(); + surfaceHandle_old = getSurfaceHandle(); + + if (surfaceLock.getHoldCount() == 1) { + final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); + try { + unlockSurfaceImpl(); + } finally { + adevice.unlock(); + } + } + surfaceLock.unlock(); + } + + protected abstract int lockSurfaceImpl(); + + protected abstract void unlockSurfaceImpl() ; + + public final void validateSurfaceLocked() { + surfaceLock.validateLocked(); + } + + @Override + public final boolean isSurfaceLockedByOtherThread() { + return surfaceLock.isLockedByOtherThread(); + } + + @Override + public final Thread getSurfaceLockOwner() { + return surfaceLock.getOwner(); + } + + public final StringBuilder getUpstreamOptionBits(StringBuilder sink) { + if(null == sink) { + sink = new StringBuilder(); + } + sink.append("UOB[ "); + if(0 == implBitfield) { + sink.append("]"); + return sink; + } + boolean needsOr = false; + if( 0 != ( implBitfield & OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { + sink.append("OWNS_SURFACE"); + needsOr = true; + } + if( 0 != ( implBitfield & OPT_PROXY_OWNS_UPSTREAM_DEVICE ) ) { + if(needsOr) { + sink.append(" | "); + } + sink.append("OWNS_DEVICE"); + needsOr = true; + } + if( 0 != ( implBitfield & OPT_UPSTREAM_WINDOW_INVISIBLE ) ) { + if(needsOr) { + sink.append(" | "); + } + sink.append("WINDOW_INVISIBLE"); + needsOr = true; + } + sink.append(" ]"); + return sink; + } + + @Override + public final int getUpstreamOptionBits() { return implBitfield; } + + @Override + public final boolean containsUpstreamOptionBits(int v) { + return v == ( implBitfield & v ) ; + } + + @Override + public final void addUpstreamOptionBits(int v) { implBitfield |= v; } + + @Override + public final void clearUpstreamOptionBits(int v) { implBitfield &= ~v; } + + @Override + public StringBuilder toString(StringBuilder sink) { + if(null == sink) { + sink = new StringBuilder(); + } + sink.append(getUpstreamSurfaceHook()). + append(", displayHandle 0x" + Long.toHexString(getDisplayHandle())). + append(", surfaceHandle 0x" + Long.toHexString(getSurfaceHandle())). + append(", size " + getWidth() + "x" + getHeight()).append(", "); + getUpstreamOptionBits(sink); + sink.append(", surfaceLock "+surfaceLock); + return sink; + } + + @Override + public String toString() { + StringBuilder msg = new StringBuilder(); + msg.append(getClass().getSimpleName()).append("[ "); + toString(msg); + msg.append(" ]"); + return msg.toString(); + } + +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java b/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java new file mode 100644 index 000000000..e544bc61a --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java @@ -0,0 +1,95 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.nativewindow; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; + +public class WrappedSurface extends ProxySurfaceImpl { + protected long surfaceHandle; + + /** + * Utilizes a {@link UpstreamSurfaceHook.MutableSize} to hold the size information, + * which is being passed to the {@link ProxySurface} instance. + * + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param handle the wrapped pre-existing native surface handle, maybe 0 if not yet determined + * @param initialWidth + * @param initialHeight + * @param ownsDevice true if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise false. Owning the device implies closing it at {@link #destroyNotify()}. + */ + public WrappedSurface(AbstractGraphicsConfiguration cfg, long handle, int initialWidth, int initialHeight, boolean ownsDevice) { + super(cfg, new UpstreamSurfaceHookMutableSize(initialWidth, initialHeight), ownsDevice); + surfaceHandle=handle; + } + + /** + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param handle the wrapped pre-existing native surface handle, maybe 0 if not yet determined + * @param upstream the {@link UpstreamSurfaceHook} to be used + * @param ownsDevice true if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise false. + */ + public WrappedSurface(AbstractGraphicsConfiguration cfg, long handle, UpstreamSurfaceHook upstream, boolean ownsDevice) { + super(cfg, upstream, ownsDevice); + surfaceHandle=handle; + } + + @Override + protected void invalidateImpl() { + surfaceHandle = 0; + } + + @Override + public final long getSurfaceHandle() { + return surfaceHandle; + } + + @Override + public final void setSurfaceHandle(long surfaceHandle) { + this.surfaceHandle=surfaceHandle; + } + + @Override + protected final int lockSurfaceImpl() { + return LOCK_SUCCESS; + } + + @Override + protected final void unlockSurfaceImpl() { + } + +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index e81d61e0f..5fd242247 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -51,7 +51,6 @@ import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.MutableSurface; import javax.media.nativewindow.util.Point; -import com.jogamp.nativewindow.MutableGraphicsConfiguration; import com.jogamp.nativewindow.awt.JAWTWindow; import jogamp.nativewindow.jawt.JAWT; @@ -71,17 +70,18 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } protected void invalidateNative() { - surfaceHandle=0; + offscreenSurfaceHandle=0; + offscreenSurfaceHandleSet=false; if(isOffscreenLayerSurfaceEnabled()) { if(0 != rootSurfaceLayerHandle) { OSXUtil.DestroyCALayer(rootSurfaceLayerHandle); rootSurfaceLayerHandle = 0; } - if(0 != drawable) { - OSXUtil.DestroyNSWindow(drawable); - drawable = 0; + if(0 != windowHandle) { + OSXUtil.DestroyNSWindow(windowHandle); } } + windowHandle=0; } protected void attachSurfaceLayerImpl(final long layerHandle) { @@ -92,8 +92,14 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { OSXUtil.RemoveCASublayer(rootSurfaceLayerHandle, layerHandle); } - public long getSurfaceHandle() { - return isOffscreenLayerSurfaceEnabled() ? surfaceHandle : super.getSurfaceHandle() ; + @Override + public final long getWindowHandle() { + return windowHandle; + } + + @Override + public final long getSurfaceHandle() { + return offscreenSurfaceHandleSet ? offscreenSurfaceHandle : drawable /* super.getSurfaceHandle() */ ; } public void setSurfaceHandle(long surfaceHandle) { @@ -103,7 +109,8 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { if(DEBUG) { System.err.println("MacOSXJAWTWindow.setSurfaceHandle(): 0x"+Long.toHexString(surfaceHandle)); } - this.surfaceHandle = surfaceHandle; + this.offscreenSurfaceHandle = surfaceHandle; + this.offscreenSurfaceHandleSet = true; } protected JAWT fetchJAWTImpl() throws NativeWindowException { @@ -167,6 +174,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { unlockSurfaceImpl(); return NativeWindow.LOCK_SURFACE_NOT_READY; } else { + windowHandle = OSXUtil.GetNSWindow(drawable); ret = NativeWindow.LOCK_SUCCESS; } } else { @@ -177,36 +185,46 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { * The actual surface/ca-layer shall be created/attached * by the upper framework (JOGL) since they require more information. */ + String errMsg = null; if(0 == drawable) { - drawable = OSXUtil.CreateNSWindow(0, 0, getBounds().getWidth(), getBounds().getHeight()); - if(0 == drawable) { - unlockSurfaceImpl(); - throw new NativeWindowException("Unable to created dummy NSWindow (layered case)"); + windowHandle = OSXUtil.CreateNSWindow(0, 0, 64, 64); + if(0 == windowHandle) { + errMsg = "Unable to create dummy NSWindow (layered case)"; + } else { + drawable = OSXUtil.GetNSView(windowHandle); + if(0 == drawable) { + errMsg = "Null NSView of NSWindow 0x"+Long.toHexString(windowHandle); + } + } + if(null == errMsg) { + // fix caps reflecting offscreen! (no GL available here ..) + Capabilities caps = (Capabilities) getGraphicsConfiguration().getChosenCapabilities().cloneMutable(); + caps.setOnscreen(false); + setChosenCapabilities(caps); } - // fix caps reflecting offscreen! - Capabilities caps = (Capabilities) getPrivateGraphicsConfiguration().getChosenCapabilities().cloneMutable(); - caps.setOnscreen(false); - getPrivateGraphicsConfiguration().setChosenCapabilities(caps); - caps = (Capabilities) getGraphicsConfiguration().getChosenCapabilities().cloneMutable(); - caps.setOnscreen(false); - ((MutableGraphicsConfiguration)getGraphicsConfiguration()).setChosenCapabilities(caps); } - if(0 == rootSurfaceLayerHandle) { - rootSurfaceLayerHandle = OSXUtil.CreateCALayer(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); - if(0 == rootSurfaceLayerHandle) { - OSXUtil.DestroyNSWindow(drawable); - drawable = 0; - unlockSurfaceImpl(); - throw new NativeWindowException("Could not create root CALayer: "+this); + if(null == errMsg) { + if(0 == rootSurfaceLayerHandle) { + rootSurfaceLayerHandle = OSXUtil.CreateCALayer(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); + if(0 == rootSurfaceLayerHandle) { + errMsg = "Could not create root CALayer"; + } else if(!SetJAWTRootSurfaceLayer0(dsi.getBuffer(), rootSurfaceLayerHandle)) { + errMsg = "Could not set JAWT rootSurfaceLayerHandle 0x"+Long.toHexString(rootSurfaceLayerHandle); + } } - if(!SetJAWTRootSurfaceLayer0(dsi.getBuffer(), rootSurfaceLayerHandle)) { + } + if(null != errMsg) { + if(0 != rootSurfaceLayerHandle) { OSXUtil.DestroyCALayer(rootSurfaceLayerHandle); rootSurfaceLayerHandle = 0; - OSXUtil.DestroyNSWindow(drawable); - drawable = 0; - unlockSurfaceImpl(); - throw new NativeWindowException("Could not set JAWT rootSurfaceLayerHandle: "+this); } + if(0 != windowHandle) { + OSXUtil.DestroyNSWindow(windowHandle); + windowHandle = 0; + } + drawable = 0; + unlockSurfaceImpl(); + throw new NativeWindowException(errMsg+": "+this); } ret = NativeWindow.LOCK_SUCCESS; } @@ -264,7 +282,9 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { private long rootSurfaceLayerHandle = 0; // attached to the JAWT_SurfaceLayer - private long surfaceHandle = 0; + private long windowHandle = 0; + private long offscreenSurfaceHandle = 0; + private boolean offscreenSurfaceHandleSet = false; // Workaround for instance of 4796548 private boolean firstLock = true; diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXDummyUpstreamSurfaceHook.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXDummyUpstreamSurfaceHook.java new file mode 100644 index 000000000..de3206c0c --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXDummyUpstreamSurfaceHook.java @@ -0,0 +1,56 @@ +package jogamp.nativewindow.macosx; + +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; + +public class OSXDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize { + long nsWindow; + + /** + * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, + * not the actual dummy surface width. + * The latter is platform specific and small + * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, + * not the actual dummy surface height, + * The latter is platform specific and small + */ + public OSXDummyUpstreamSurfaceHook(int width, int height) { + super(width, height); + nsWindow = 0; + } + + @Override + public final void create(ProxySurface s) { + if(0 == nsWindow && 0 == s.getSurfaceHandle()) { + nsWindow = OSXUtil.CreateNSWindow(0, 0, 64, 64); + if(0 == nsWindow) { + throw new NativeWindowException("Error NS window 0"); + } + long nsView = OSXUtil.GetNSView(nsWindow); + if(0 == nsView) { + throw new NativeWindowException("Error NS view 0"); + } + s.setSurfaceHandle(nsView); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); + } + + @Override + public final void destroy(ProxySurface s) { + if( s.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { + if( 0 == nsWindow || 0 == s.getSurfaceHandle() ) { + throw new InternalError("Owns upstream surface, but no OSX view/window: "+s+", nsWindow 0x"+Long.toHexString(nsWindow)); + } + OSXUtil.DestroyNSWindow(nsWindow); + nsWindow = 0; + s.setSurfaceHandle(0); + s.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + } + +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 149ebdf4a..b7a83e133 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -72,6 +72,10 @@ public class OSXUtil { return isNSView0(object); } + public static boolean isNSWindow(long object) { + return isNSWindow0(object); + } + /** * In case the windowOrView is top-level, * you shall set topLevel to true where @@ -114,6 +118,9 @@ public class OSXUtil { public static long GetNSView(long nsWindow) { return GetNSView0(nsWindow); } + public static long GetNSWindow(long nsView) { + return GetNSWindow0(nsView); + } public static long CreateCALayer(int x, int y, int width, int height) { return CreateCALayer0(x, y, width, height); @@ -149,6 +156,11 @@ public class OSXUtil { return IsMainThread0(); } + /** Returns the screen refresh rate in Hz. If unavailable, returns 60Hz. */ + public static int GetScreenRefreshRate(int scrn_idx) { + return GetScreenRefreshRate0(scrn_idx); + } + /*** private static boolean isAWTEDTMainThreadInit = false; private static boolean isAWTEDTMainThread; @@ -172,15 +184,18 @@ public class OSXUtil { private static native boolean initIDs0(); private static native boolean isNSView0(long object); + private static native boolean isNSWindow0(long object); private static native Object GetLocationOnScreen0(long windowOrView, int src_x, int src_y); private static native Object GetInsets0(long windowOrView); private static native long CreateNSWindow0(int x, int y, int width, int height); private static native void DestroyNSWindow0(long nsWindow); private static native long GetNSView0(long nsWindow); + private static native long GetNSWindow0(long nsView); private static native long CreateCALayer0(int x, int y, int width, int height); private static native void AddCASublayer0(long rootCALayer, long subCALayer); private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); private static native void RunOnMainThread0(boolean waitUntilDone, Runnable runnable); private static native boolean IsMainThread0(); + private static native int GetScreenRefreshRate0(int scrn_idx); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIDummyUpstreamSurfaceHook.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIDummyUpstreamSurfaceHook.java new file mode 100644 index 000000000..aa5f3dac5 --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIDummyUpstreamSurfaceHook.java @@ -0,0 +1,50 @@ +package jogamp.nativewindow.windows; + +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; + +public class GDIDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize { + /** + * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, + * not the actual dummy surface width. + * The latter is platform specific and small + * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, + * not the actual dummy surface height, + * The latter is platform specific and small + */ + public GDIDummyUpstreamSurfaceHook(int width, int height) { + super(width, height); + } + + @Override + public final void create(ProxySurface s) { + final GDISurface ms = (GDISurface)s; + if(0 == ms.getWindowHandle()) { + final long windowHandle = GDIUtil.CreateDummyWindow(0, 0, 64, 64); + if(0 == windowHandle) { + throw new NativeWindowException("Error windowHandle 0, werr: "+GDI.GetLastError()); + } + ms.setWindowHandle(windowHandle); + ms.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); + } + + @Override + public final void destroy(ProxySurface s) { + final GDISurface ms = (GDISurface)s; + if( ms.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { + if( 0 == ms.getWindowHandle() ) { + throw new InternalError("Owns upstream surface, but no GDI window: "+ms); + } + GDI.ShowWindow(ms.getWindowHandle(), GDI.SW_HIDE); + GDIUtil.DestroyDummyWindow(ms.getWindowHandle()); + ms.setWindowHandle(0); + ms.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + } +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java index e368aa6a1..3db2b5fc9 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java @@ -29,9 +29,13 @@ package jogamp.nativewindow.windows; import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.ProxySurface; -import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; +import javax.media.nativewindow.UpstreamSurfaceHook; + +import jogamp.nativewindow.ProxySurfaceImpl; +import jogamp.nativewindow.windows.GDI; /** @@ -40,12 +44,20 @@ import javax.media.nativewindow.ProxySurface.UpstreamSurfaceHook; * The latter will get and release the HDC. * The size via getWidth()/getHeight() is invalid. */ -public class GDISurface extends ProxySurface { +public class GDISurface extends ProxySurfaceImpl { protected long windowHandle; protected long surfaceHandle; - public GDISurface(AbstractGraphicsConfiguration cfg, long windowHandle, int initialWidth, int initialHeight, UpstreamSurfaceHook upstream) { - super(cfg, initialWidth, initialHeight, upstream); + /** + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param windowHandle the wrapped pre-existing native window handle, maybe 0 if not yet determined + * @param upstream the {@link UpstreamSurfaceHook} to be used + * @param ownsDevice true if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise false. Owning the device implies closing it at {@link #destroyNotify()}. + */ + public GDISurface(AbstractGraphicsConfiguration cfg, long windowHandle, UpstreamSurfaceHook upstream, boolean ownsDevice) { + super(cfg, upstream, ownsDevice); this.windowHandle=windowHandle; this.surfaceHandle=0; } @@ -114,18 +126,4 @@ public class GDISurface extends ProxySurface { final public long getSurfaceHandle() { return surfaceHandle; } - - @Override - final public String toString() { - final UpstreamSurfaceHook ush = getUpstreamSurfaceHook(); - final String ush_s = null != ush ? ( ush.getClass().getName() + ": " + ush ) : "nil"; - return getClass().getSimpleName()+"[config "+getPrivateGraphicsConfiguration()+ - ", displayHandle 0x"+Long.toHexString(getDisplayHandle())+ - ", windowHandle 0x"+Long.toHexString(windowHandle)+ - ", surfaceHandle 0x"+Long.toHexString(getSurfaceHandle())+ - ", size "+getWidth()+"x"+getHeight()+ - ", surfaceLock "+surfaceLock+ - ", upstreamSurfaceHook "+ush_s+"]"; - } - } diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java new file mode 100644 index 000000000..55a29dd5e --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java @@ -0,0 +1,60 @@ +package jogamp.nativewindow.x11; + +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; + +import jogamp.nativewindow.x11.X11Lib; + +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; +import com.jogamp.nativewindow.x11.X11GraphicsConfiguration; +import com.jogamp.nativewindow.x11.X11GraphicsDevice; +import com.jogamp.nativewindow.x11.X11GraphicsScreen; + +public class X11DummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize { + /** + * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, + * not the actual dummy surface width. + * The latter is platform specific and small + * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, + * not the actual dummy surface height, + * The latter is platform specific and small + */ + public X11DummyUpstreamSurfaceHook(int width, int height) { + super(width, height); + } + + @Override + public final void create(ProxySurface s) { + final X11GraphicsConfiguration cfg = (X11GraphicsConfiguration) s.getGraphicsConfiguration(); + final X11GraphicsScreen screen = (X11GraphicsScreen) cfg.getScreen(); + final X11GraphicsDevice device = (X11GraphicsDevice) screen.getDevice(); + if(0 == device.getHandle()) { + device.open(); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + if( 0 == s.getSurfaceHandle() ) { + final long windowHandle = X11Lib.CreateDummyWindow(device.getHandle(), screen.getIndex(), cfg.getXVisualID(), 64, 64); + if(0 == windowHandle) { + throw new NativeWindowException("Creating dummy window failed w/ "+cfg); + } + s.setSurfaceHandle(windowHandle); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); + } + + @Override + public final void destroy(ProxySurface s) { + if( s.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { + final X11GraphicsDevice device = (X11GraphicsDevice) s.getGraphicsConfiguration().getScreen().getDevice(); + if( 0 == s.getSurfaceHandle() ) { + throw new InternalError("Owns upstream surface, but no X11 window: "+s); + } + X11Lib.DestroyDummyWindow(device.getHandle(), s.getSurfaceHandle()); + s.setSurfaceHandle(0); + s.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + } +} diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 2c853a43d..d6ae7ed31 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -119,6 +119,12 @@ Java_jogamp_nativewindow_macosx_OSXUtil_isNSView0(JNIEnv *env, jclass _unused, j return [nsObj isMemberOfClass:[NSView class]]; } +JNIEXPORT jboolean JNICALL +Java_jogamp_nativewindow_macosx_OSXUtil_isNSWindow0(JNIEnv *env, jclass _unused, jlong object) { + NSObject *nsObj = (NSObject*) (intptr_t) object; + return [nsObj isMemberOfClass:[NSWindow class]]; +} + /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: getLocationOnScreen0 @@ -238,8 +244,10 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateNSWindow0 [myWindow setPreservesContentDuringLiveResize: YES]; // Remove animations NS_DURING + if ( [myWindow respondsToSelector:@selector(setAnimationBehavior:)] ) { // Available >= 10.7 - Removes default animations [myWindow setAnimationBehavior: NSWindowAnimationBehaviorNone]; + } NS_HANDLER NS_ENDHANDLER @@ -278,11 +286,28 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSView0 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; NSWindow* win = (NSWindow*) ((intptr_t) window); - DBG_PRINT( "contentView0 - window: %p (START)\n", win); - jlong res = (jlong) ((intptr_t) [win contentView]); - DBG_PRINT( "contentView0 - window: %p (END)\n", win); + DBG_PRINT( "GetNSView(window: %p): %p\n", win, (void*) (intptr_t) res); + + [pool release]; + return res; +} + +/* + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: GetNSWindow0 + * Signature: (J)J + */ +JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 + (JNIEnv *env, jclass unused, jlong view) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSView* v = (NSView*) ((intptr_t) view); + + jlong res = (jlong) ((intptr_t) [v window]); + + DBG_PRINT( "GetNSWindow(view: %p): %p\n", v, (void*) (intptr_t) res); [pool release]; return res; @@ -314,6 +339,8 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 // no animations for add/remove/swap sublayers etc // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] [layer removeAllAnimations]; + [layer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; + [layer setNeedsDisplayOnBoundsChange: YES]; DBG_PRINT("CALayer::CreateCALayer.1: %p %lf/%lf %lfx%lf\n", layer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); DBG_PRINT("CALayer::CreateCALayer.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]); @@ -357,7 +384,11 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 // no animations for add/remove/swap sublayers etc // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] [rootLayer removeAllAnimations]; + [rootLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; + [rootLayer setNeedsDisplayOnBoundsChange: YES]; [subLayer removeAllAnimations]; + [subLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; + [subLayer setNeedsDisplayOnBoundsChange: YES]; }]; DBG_PRINT("CALayer::AddCASublayer0.X: %p . %p (refcnt %d)\n", rootLayer, subLayer, (int)[subLayer retainCount]); JNF_COCOA_EXIT(env); @@ -404,6 +435,63 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyCALayer0 JNF_COCOA_EXIT(env); } +/* + * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow + * Method: SetJAWTRootSurfaceLayer0 + * Signature: (JJ)Z + */ +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_SetJAWTRootSurfaceLayer0 + (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) +{ + JNF_COCOA_ENTER(env); + JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); + if (NULL == dsi) { + NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); + return JNI_FALSE; + } + CALayer* layer = (CALayer*) (intptr_t) caLayer; + [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ + id surfaceLayers = (id )dsi->platformInfo; + DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.0: %p -> %p (refcnt %d)\n", surfaceLayers.layer, layer, (int)[layer retainCount]); + surfaceLayers.layer = layer; // already incr. retain count + DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]); + }]; + JNF_COCOA_EXIT(env); + return JNI_TRUE; +} + +/* + * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow + * Method: UnsetJAWTRootSurfaceLayer0 + * Signature: (JJ)Z +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_UnsetJAWTRootSurfaceLayer0 + (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) +{ + JNF_COCOA_ENTER(env); + JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); + if (NULL == dsi) { + NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); + return JNI_FALSE; + } + CALayer* layer = (CALayer*) (intptr_t) caLayer; + { + id surfaceLayers = (id )dsi->platformInfo; + if(layer != surfaceLayers.layer) { + NativewindowCommon_throwNewRuntimeException(env, "Attached layer %p doesn't match given layer %p\n", surfaceLayers.layer, layer); + return JNI_FALSE; + } + } + // [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ + id surfaceLayers = (id )dsi->platformInfo; + DBG_PRINT("CALayer::detachJAWTSurfaceLayer: (%p) %p -> NULL\n", layer, surfaceLayers.layer); + surfaceLayers.layer = NULL; + [layer release]; + // }]; + JNF_COCOA_EXIT(env); + return JNI_TRUE; +} + */ + @interface MainRunnable : NSObject { @@ -489,60 +577,65 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_IsMainThread0 return ( [NSThread isMainThread] == YES ) ? JNI_TRUE : JNI_FALSE ; } -/* - * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow - * Method: SetJAWTRootSurfaceLayer0 - * Signature: (JJ)Z +/*** + * The following static functions are copied out of NEWT's OSX impl. + * May need to push code to NativeWindow, to remove duplication. */ -JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_SetJAWTRootSurfaceLayer0 - (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) +static NSScreen * NewtScreen_getNSScreenByIndex(int screen_idx) { + NSArray *screens = [NSScreen screens]; + if(screen_idx<0) screen_idx=0; + if(screen_idx>=[screens count]) screen_idx=0; + return (NSScreen *) [screens objectAtIndex: screen_idx]; +} +static CGDirectDisplayID NewtScreen_getCGDirectDisplayIDByNSScreen(NSScreen *screen) { + // Mind: typedef uint32_t CGDirectDisplayID; - however, we assume it's 64bit on 64bit ?! + NSDictionary * dict = [screen deviceDescription]; + NSNumber * val = (NSNumber *) [dict objectForKey: @"NSScreenNumber"]; + // [NSNumber integerValue] returns NSInteger which is 32 or 64 bit native size + return (CGDirectDisplayID) [val integerValue]; +} +static long GetDictionaryLong(CFDictionaryRef theDict, const void* key) { - JNF_COCOA_ENTER(env); - JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); - if (NULL == dsi) { - NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); - return JNI_FALSE; - } - CALayer* layer = (CALayer*) (intptr_t) caLayer; - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - id surfaceLayers = (id )dsi->platformInfo; - DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.0: %p -> %p (refcnt %d)\n", surfaceLayers.layer, layer, (int)[layer retainCount]); - surfaceLayers.layer = layer; // already incr. retain count - DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]); - }]; - JNF_COCOA_EXIT(env); - return JNI_TRUE; + long value = 0; + CFNumberRef numRef; + numRef = (CFNumberRef)CFDictionaryGetValue(theDict, key); + if (numRef != NULL) + CFNumberGetValue(numRef, kCFNumberLongType, &value); + return value; } +#define CGDDGetModeRefreshRate(mode) GetDictionaryLong((mode), kCGDisplayRefreshRate) /* - * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow - * Method: UnsetJAWTRootSurfaceLayer0 - * Signature: (JJ)Z -JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_UnsetJAWTRootSurfaceLayer0 - (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: GetScreenRefreshRate + * Signature: (I)I + */ +JNIEXPORT jint JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetScreenRefreshRate0 + (JNIEnv *env, jclass unused, jint scrn_idx) { + int res = 0; JNF_COCOA_ENTER(env); - JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); - if (NULL == dsi) { - NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); - return JNI_FALSE; - } - CALayer* layer = (CALayer*) (intptr_t) caLayer; - { - id surfaceLayers = (id )dsi->platformInfo; - if(layer != surfaceLayers.layer) { - NativewindowCommon_throwNewRuntimeException(env, "Attached layer %p doesn't match given layer %p\n", surfaceLayers.layer, layer); - return JNI_FALSE; + // NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSScreen *screen = NewtScreen_getNSScreenByIndex((int)scrn_idx); + DBG_PRINT("GetScreenRefreshRate.0: screen %p\n", (void *)screen); + if(NULL != screen) { + CGDirectDisplayID display = NewtScreen_getCGDirectDisplayIDByNSScreen(screen); + DBG_PRINT("GetScreenRefreshRate.1: display %p\n", (void *)display); + if(0 != display) { + CFDictionaryRef mode = CGDisplayCurrentMode(display); + DBG_PRINT("GetScreenRefreshRate.2: mode %p\n", (void *)mode); + if(NULL != mode) { + res = CGDDGetModeRefreshRate(mode); + DBG_PRINT("GetScreenRefreshRate.3: res %d\n", res); + } } } - // [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - id surfaceLayers = (id )dsi->platformInfo; - DBG_PRINT("CALayer::detachJAWTSurfaceLayer: (%p) %p -> NULL\n", layer, surfaceLayers.layer); - surfaceLayers.layer = NULL; - [layer release]; - // }]; + if(0 == res) { + res = 60; // default .. (experienced on OSX 10.6.8) + } + fprintf(stderr, "GetScreenRefreshRate.X: %d\n", res); + // [pool release]; JNF_COCOA_EXIT(env); - return JNI_TRUE; + return res; } - */ diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 6f0028a77..89a749c51 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -68,6 +68,15 @@ import com.jogamp.newt.event.awt.AWTAdapter; import com.jogamp.newt.event.awt.AWTKeyAdapter; import com.jogamp.newt.event.awt.AWTMouseAdapter; +/** + * AWT {@link java.awt.Canvas Canvas} containing a NEWT {@link Window} using native parenting. + * + *
      Offscreen Layer Remarks
      + * + * {@link OffscreenLayerOption#setShallUseOffscreenLayer(boolean) setShallUseOffscreenLayer(true)} + * maybe called to use an offscreen drawable (FBO or PBuffer) allowing + * the underlying JAWT mechanism to composite the image, if supported. + */ @SuppressWarnings("serial") public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProtocol, OffscreenLayerOption { public static final boolean DEBUG = Debug.debug("Window"); diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index 0fc1b4e89..a89ccaedb 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -51,6 +51,7 @@ import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawable; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLException; @@ -97,7 +98,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind * Constructor. Do not call this directly -- use {@link #create()} instead. */ protected GLWindow(Window window) { - super(null, null, false); + super(null, null, false /* always handle device lifecycle ourselves */); this.window = (WindowImpl) window; this.window.setHandleDestroyNotify(false); window.addWindowListener(new WindowAdapter() { @@ -107,8 +108,8 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind } @Override - public void windowResized(WindowEvent e) { - defaultWindowResizedOp(); + public void windowResized(WindowEvent e) { + defaultWindowResizedOp(getWidth(), getHeight()); } @Override @@ -201,11 +202,8 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind @Override public final CapabilitiesImmutable getChosenCapabilities() { - if (drawable == null) { - return window.getChosenCapabilities(); - } - - return drawable.getChosenGLCapabilities(); + final GLDrawable _drawable = drawable; + return null != _drawable ? _drawable.getChosenGLCapabilities() : window.getChosenCapabilities(); } @Override @@ -536,19 +534,24 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind return; } + final boolean done; final RecursiveLock lock = window.getLock(); lock.lock(); // sync: context/drawable could have been recreated/destroyed while animating try { if( null != context ) { // surface is locked/unlocked implicit by context's makeCurrent/release helper.invokeGL(drawable, context, defaultDisplayAction, defaultInitAction); - } else if( 0 display - setVisible(true); + done = true; + } else { + done = false; } } finally { lock.unlock(); } + if( !done && 0 display + setVisible(true); + } } //---------------------------------------------------------------------- diff --git a/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java index cada253bc..36bc3f28f 100644 --- a/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java +++ b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java @@ -63,6 +63,9 @@ import com.jogamp.newt.Window; import com.jogamp.newt.event.WindowEvent; import com.jogamp.newt.util.EDTUtil; +/** + * SWT {@link Canvas} containing a NEWT {@link Window} using native parenting. + */ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { private static final boolean DEBUG = Debug.debug("Window"); private static final boolean isOSX = NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false); diff --git a/src/newt/classes/jogamp/newt/OffscreenWindow.java b/src/newt/classes/jogamp/newt/OffscreenWindow.java index ba98ca3af..c6c1814f6 100644 --- a/src/newt/classes/jogamp/newt/OffscreenWindow.java +++ b/src/newt/classes/jogamp/newt/OffscreenWindow.java @@ -39,20 +39,16 @@ import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.MutableSurface; import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.ProxySurface; import javax.media.nativewindow.VisualIDHolder; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.Point; public class OffscreenWindow extends WindowImpl implements MutableSurface { - long surfaceHandle = 0; - ProxySurface.UpstreamSurfaceHook upstreamHook; - ProxySurface dummySurface; + long surfaceHandle; public OffscreenWindow() { - upstreamHook = null; - dummySurface = null; + surfaceHandle = 0; } static long nextWindowHandle = 0x100; // start here - a marker @@ -62,17 +58,6 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { throw new NativeWindowException("Capabilities is onscreen"); } final AbstractGraphicsScreen aScreen = getScreen().getGraphicsScreen(); - /** Cannot use OpenGL here .. - if(capsRequested instanceof GLCapabilitiesImmutable) { - final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) capsRequested; - if(caps.isFBO() && GLContext.isFBOAvailable(aScreen.getDevice(), caps.getGLProfile()) ) { - final GLDrawableFactoryImpl factory = (GLDrawableFactoryImpl) GLDrawableFactory.getFactory(caps.getGLProfile()); - final GLCapabilitiesImmutable dummyCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(caps); - final ProxySurface dummySurface = factory.createDummySurfaceImpl(aScreen.getDevice(), false, dummyCaps, null, 64, 64); - upstreamHook = dummySurface.getUpstreamSurfaceHook(); - dummySurface.createNotify(); - } - } */ final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(aScreen.getDevice(), capsRequested).chooseGraphicsConfiguration( capsRequested, capsRequested, capabilitiesChooser, aScreen, VisualIDHolder.VID_UNDEFINED); if (null == cfg) { @@ -83,6 +68,7 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { synchronized(OffscreenWindow.class) { setWindowHandle(nextWindowHandle++); } + visibleChanged(false, true); } protected void closeNativeImpl() { @@ -92,11 +78,6 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { @Override public synchronized void destroy() { super.destroy(); - if(null != dummySurface) { - dummySurface.destroyNotify(); - dummySurface = null; - upstreamHook = null; - } surfaceHandle = 0; } @@ -106,10 +87,6 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { @Override public long getSurfaceHandle() { - if(null != dummySurface) { - return dummySurface.getSurfaceHandle(); - // return upstreamHook.getWidth(); - } return surfaceHandle; } @@ -128,8 +105,8 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { } protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + sizeChanged(false, width, height, false); if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - sizeChanged(false, width, height, false); visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); } else { /** diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index ad7195944..c1ac87d38 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -767,11 +767,15 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } - public void setVisible(boolean visible) { + protected void setVisible(boolean wait, boolean visible) { if(DEBUG_IMPLEMENTATION) { System.err.println("Window setVisible: START ("+getThreadName()+") "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle)+", visible: "+this.visible+" -> "+visible+", parentWindowHandle "+toHexString(parentWindowHandle)+", parentWindow "+(null!=parentWindow)); } - runOnEDTIfAvail(true, new VisibleAction(visible)); + runOnEDTIfAvail(wait, new VisibleAction(visible)); + } + + public void setVisible(boolean visible) { + setVisible(true, visible); } private class SetSizeAction implements Runnable { @@ -783,21 +787,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } public final void run() { - boolean recreate = false; final RecursiveLock _lock = windowLock; _lock.lock(); try { if ( !isFullscreen() && ( getWidth() != width || getHeight() != height ) ) { - recreate = isNativeValid() && !getGraphicsConfiguration().getChosenCapabilities().isOnscreen(); if(DEBUG_IMPLEMENTATION) { - System.err.println("Window setSize: START "+getWidth()+"x"+getHeight()+" -> "+width+"x"+height+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle)+", visible "+visible+", recreate "+recreate); - } - if(recreate) { - // will trigger visibleAction:=2 -> create if wasVisible - final boolean wasVisible = WindowImpl.this.visible; - screen.addReference(); // retain screen - destroyAction.run(); - WindowImpl.this.visible = wasVisible; + System.err.println("Window setSize: START "+getWidth()+"x"+getHeight()+" -> "+width+"x"+height+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle)+", visible "+visible); } int visibleAction; // 0 nop, 1 invisible, 2 visible (create) if ( isNativeValid() && 0>=width*height && visible ) { @@ -823,9 +818,6 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } } finally { - if(recreate) { - screen.removeReference(); // bring back ref-count - } _lock.unlock(); } } @@ -940,11 +932,15 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer */ protected static boolean isOffscreenInstance(NativeWindow cWin, NativeWindow pWin) { boolean ofs = false; - if( null != cWin.getGraphicsConfiguration() ) { - ofs = !cWin.getGraphicsConfiguration().getChosenCapabilities().isOnscreen(); + final AbstractGraphicsConfiguration cWinCfg = cWin.getGraphicsConfiguration(); + if( null != cWinCfg ) { + ofs = !cWinCfg.getChosenCapabilities().isOnscreen(); } - if( !ofs && null != pWin && null != pWin.getGraphicsConfiguration() ) { - ofs |= !pWin.getGraphicsConfiguration().getChosenCapabilities().isOnscreen(); + if( !ofs && null != pWin ) { + final AbstractGraphicsConfiguration pWinCfg = pWin.getGraphicsConfiguration(); + if( null != pWinCfg ) { + ofs = !pWinCfg.getChosenCapabilities().isOnscreen(); + } } return ofs; } diff --git a/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java index 276b0d070..f18520630 100644 --- a/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java @@ -428,7 +428,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { getX()+"/"+getY()+" "+nWidth+"x"+nHeight+", visible: "+isVisible()); if(isVisible()) { - setVisible(true); + setVisible(false, true); } } sizeChanged(false, aWidth, aHeight, false); diff --git a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java index ea48569bf..d0c0b8b20 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java @@ -117,6 +117,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl return 0 != sscSurfaceHandle ? sscSurfaceHandle : surfaceHandle; } + @Override public void setSurfaceHandle(long surfaceHandle) { if(DEBUG_IMPLEMENTATION) { System.err.println("MacWindow.setSurfaceHandle(): 0x"+Long.toHexString(surfaceHandle)); @@ -170,13 +171,22 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { - final Point pS = getTopLevelLocationOnScreen(x, y); - isOffscreenInstance = 0 != sscSurfaceHandle || isOffscreenInstance(this, this.getParent()); + final boolean _isOffscreenInstance = isOffscreenInstance(this, this.getParent()); + isOffscreenInstance = 0 != sscSurfaceHandle || _isOffscreenInstance; + final PointImmutable pS = isOffscreenInstance ? new Point(0, 0) : getTopLevelLocationOnScreen(x, y); if(DEBUG_IMPLEMENTATION) { + final AbstractGraphicsConfiguration cWinCfg = this.getGraphicsConfiguration(); + final NativeWindow pWin = getParent(); + final AbstractGraphicsConfiguration pWinCfg = null != pWin ? pWin.getGraphicsConfiguration() : null; System.err.println("MacWindow reconfig: "+x+"/"+y+" -> "+pS+" - "+width+"x"+height+ - ", offscreenInstance "+isOffscreenInstance+ - ", "+getReconfigureFlagsAsString(null, flags)); + ",\n\t parent type "+(null != pWin ? pWin.getClass().getName() : null)+ + ",\n\t this-chosenCaps "+(null != cWinCfg ? cWinCfg.getChosenCapabilities() : null)+ + ",\n\t parent-chosenCaps "+(null != pWinCfg ? pWinCfg.getChosenCapabilities() : null)+ + ", isOffscreenInstance(sscSurfaceHandle "+toHexString(sscSurfaceHandle)+ + ", ioi: "+_isOffscreenInstance+ + ") -> "+isOffscreenInstance+ + "\n\t, "+getReconfigureFlagsAsString(null, flags)); } if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && 0 == ( FLAG_IS_VISIBLE & flags) ) { @@ -190,7 +200,11 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl 0 != ( FLAG_CHANGE_DECORATION & flags) || 0 != ( FLAG_CHANGE_PARENTING & flags) || 0 != ( FLAG_CHANGE_FULLSCREEN & flags) ) { - createWindow(isOffscreenInstance, 0 != getWindowHandle(), pS, width, height, 0 != ( FLAG_IS_FULLSCREEN & flags)); + if(isOffscreenInstance) { + createWindow(true, 0 != getWindowHandle(), pS, 64, 64, false); + } else { + createWindow(false, 0 != getWindowHandle(), pS, width, height, 0 != ( FLAG_IS_FULLSCREEN & flags)); + } if(isVisible()) { flags |= FLAG_CHANGE_VISIBILITY; } } if(x>=0 && y>=0) { diff --git a/src/newt/native/MacWindow.m b/src/newt/native/MacWindow.m index e0330a563..b9c339285 100644 --- a/src/newt/native/MacWindow.m +++ b/src/newt/native/MacWindow.m @@ -94,7 +94,13 @@ static void changeContentView(JNIEnv *env, jobject javaWindowObject, NSView *pvi if(NULL!=oldNSView) { NS_DURING // Available >= 10.5 - Makes the menubar disapear - if([oldNSView isInFullScreenMode]) { + BOOL iifs; + if ( [oldNSView respondsToSelector:@selector(isInFullScreenMode)] ) { + iifs = [oldNSView isInFullScreenMode]; + } else { + iifs = NO; + } + if(iifs && [oldNSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)] ) { [oldNSView exitFullScreenModeWithOptions: NULL]; } NS_HANDLER @@ -430,6 +436,8 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScree if( -1 < mode_idx ) { prop[propIndex++] = mode_idx; } + int refreshRate = CGDDGetModeRefreshRate(mode); + int fRefreshRate = ( 0 < refreshRate ) ? refreshRate : 60; // default .. (experienced on OSX 10.6.8) prop[propIndex++] = 0; // set later for verification of iterator propIndexRes = propIndex; prop[propIndex++] = mWidth; @@ -437,14 +445,14 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScree prop[propIndex++] = CGDDGetModeBitsPerPixel(mode); prop[propIndex++] = widthMM; prop[propIndex++] = heightMM; - prop[propIndex++] = CGDDGetModeRefreshRate(mode); + prop[propIndex++] = fRefreshRate; prop[propIndex++] = ccwRot; prop[propIndex - NUM_SCREEN_MODE_PROPERTIES_ALL] = ( -1 < mode_idx ) ? propIndex-1 : propIndex ; // count == NUM_SCREEN_MODE_PROPERTIES_ALL - DBG_PRINT( "getScreenMode0: Mode %d/%d (%d): %dx%d, %d bpp, %dx%d mm, %d Hz, rot %d ccw\n", + DBG_PRINT( "getScreenMode0: Mode %d/%d (%d): %dx%d, %d bpp, %dx%d mm, %d / %d Hz, rot %d ccw\n", (int)mode_idx, (int)numberOfAvailableModesRots, (int)numberOfAvailableModes, (int)prop[propIndexRes+0], (int)prop[propIndexRes+1], (int)prop[propIndexRes+2], - (int)prop[propIndexRes+3], (int)prop[propIndexRes+4], (int)prop[propIndexRes+5], (int)prop[propIndexRes+6]); + (int)prop[propIndexRes+3], (int)prop[propIndexRes+4], (int)prop[propIndexRes+5], refreshRate, (int)prop[propIndexRes+6]); jintArray properties = (*env)->NewIntArray(env, prop_num); if (properties == NULL) { @@ -516,6 +524,8 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_initIDs0 if(initialized) return JNI_TRUE; initialized = 1; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + jclass c; c = (*env)->FindClass(env, ClazzNamePoint); if(NULL==c) { @@ -537,7 +547,10 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_initIDs0 // printf("Going to sleep for 10 seconds\n"); // sleep(10); - return (jboolean) [NewtMacWindow initNatives: env forClass: clazz]; + BOOL res = [NewtMacWindow initNatives: env forClass: clazz]; + [pool release]; + + return (jboolean) res; } /* @@ -602,8 +615,10 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_createWindow // Remove animations for child windows if(NULL != parentWindow) { NS_DURING - // Available >= 10.7 - Removes default animations - [myWindow setAnimationBehavior: NSWindowAnimationBehaviorNone]; + if ( [myWindow respondsToSelector:@selector(setAnimationBehavior:)] ) { + // Available >= 10.7 - Removes default animations + [myWindow setAnimationBehavior: NSWindowAnimationBehaviorNone]; + } NS_HANDLER NS_ENDHANDLER } @@ -658,8 +673,12 @@ NS_ENDHANDLER NS_DURING // concurrent view rendering // Available >= 10.6 - Makes the menubar disapear - [myWindow setAllowsConcurrentViewDrawing: YES]; - [myView setCanDrawConcurrently: YES]; + if ( [myWindow respondsToSelector:@selector(setAllowsConcurrentViewDrawing:)] ) { + [myWindow setAllowsConcurrentViewDrawing: YES]; + } + if ( [myView respondsToSelector:@selector(setCanDrawConcurrently:)] ) { + [myView setCanDrawConcurrently: YES]; + } NS_HANDLER NS_ENDHANDLER @@ -669,7 +688,9 @@ NS_ENDHANDLER NS_DURING // Available >= 10.5 - Makes the menubar disapear if(fullscreen) { - [myView enterFullScreenMode: myScreen withOptions:NULL]; + if ( [myView respondsToSelector:@selector(enterFullScreenMode:withOptions:)] ) { + [myView enterFullScreenMode: myScreen withOptions:NULL]; + } } NS_HANDLER NS_ENDHANDLER @@ -730,7 +751,13 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_close0 NS_DURING if(NULL!=mView) { // Available >= 10.5 - Makes the menubar disapear - if([mView isInFullScreenMode]) { + BOOL iifs; + if ( [mView respondsToSelector:@selector(isInFullScreenMode)] ) { + iifs = [mView isInFullScreenMode]; + } else { + iifs = NO; + } + if(iifs && [mView respondsToSelector:@selector(exitFullScreenModeWithOptions:)] ) { [mView exitFullScreenModeWithOptions: NULL]; } // Note: mWin's release will also release it's mView! diff --git a/src/test/com/jogamp/opengl/test/android/MovieCubeActivityLauncher0.java b/src/test/com/jogamp/opengl/test/android/MovieCubeActivityLauncher0.java index 4f24fc9b8..c4b74c56f 100644 --- a/src/test/com/jogamp/opengl/test/android/MovieCubeActivityLauncher0.java +++ b/src/test/com/jogamp/opengl/test/android/MovieCubeActivityLauncher0.java @@ -50,6 +50,8 @@ public class MovieCubeActivityLauncher0 extends LauncherUtil.BaseActivityLaunche // props.setProperty("jogamp.debug.NativeLibrary", "true"); // props.setProperty("jogamp.debug.NativeLibrary.Lookup", "true"); // props.setProperty("jogamp.debug.IOUtil", "true"); + // props.setProperty("jogamp.debug.Lock", "true"); + // props.setProperty("jogamp.debug.Lock.TraceLock", "true"); // props.setProperty("nativewindow.debug", "all"); props.setProperty("nativewindow.debug.GraphicsConfiguration", "true"); // props.setProperty("jogl.debug", "all"); diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivityLauncher.java index c75c229a8..576305835 100644 --- a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivityLauncher.java +++ b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivityLauncher.java @@ -14,23 +14,23 @@ public class NEWTGraphUI1pActivityLauncher extends LauncherUtil.BaseActivityLaun final OrderedProperties props = getProperties(); // props.setProperty("jogamp.debug.JNILibLoader", "true"); // props.setProperty("jogamp.debug.NativeLibrary", "true"); - // properties.setProperty("jogamp.debug.NativeLibrary.Lookup", "true"); - // properties.setProperty("jogamp.debug.IOUtil", "true"); - // properties.setProperty("nativewindow.debug", "all"); + // props.setProperty("jogamp.debug.NativeLibrary.Lookup", "true"); + // props.setProperty("jogamp.debug.IOUtil", "true"); + // props.setProperty("nativewindow.debug", "all"); props.setProperty("nativewindow.debug.GraphicsConfiguration", "true"); - // properties.setProperty("jogl.debug", "all"); - // properties.setProperty("jogl.debug.GLProfile", "true"); + // props.setProperty("jogl.debug", "all"); + // props.setProperty("jogl.debug.GLProfile", "true"); props.setProperty("jogl.debug.GLDrawable", "true"); props.setProperty("jogl.debug.GLContext", "true"); props.setProperty("jogl.debug.GLSLCode", "true"); props.setProperty("jogl.debug.CapabilitiesChooser", "true"); - // properties.setProperty("jogl.debug.GLSLState", "true"); - // properties.setProperty("jogl.debug.DebugGL", "true"); - // properties.setProperty("jogl.debug.TraceGL", "true"); - // properties.setProperty("newt.debug", "all"); + // props.setProperty("jogl.debug.GLSLState", "true"); + // props.setProperty("jogl.debug.DebugGL", "true"); + // props.setProperty("jogl.debug.TraceGL", "true"); + // props.setProperty("newt.debug", "all"); props.setProperty("newt.debug.Window", "true"); - // properties.setProperty("newt.debug.Window.MouseEvent", "true"); - // properties.setProperty("newt.debug.Window.KeyEvent", "true"); + // props.setProperty("newt.debug.Window.MouseEvent", "true"); + // props.setProperty("newt.debug.Window.KeyEvent", "true"); } @Override diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOAutoDrawableDeadlockAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOAutoDrawableDeadlockAWT.java new file mode 100644 index 000000000..eab1a37e3 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOAutoDrawableDeadlockAWT.java @@ -0,0 +1,128 @@ +/** + * Copyright 2011 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.awt.EventQueue; +import java.lang.reflect.InvocationTargetException; + +import javax.media.opengl.DefaultGLCapabilitiesChooser; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLOffscreenAutoDrawable; +import javax.media.opengl.GLProfile; + +import jogamp.nativewindow.jawt.JAWTUtil; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.jogamp.common.util.RunnableTask; +import com.jogamp.opengl.test.junit.util.UITestCase; + +public class TestFBOAutoDrawableDeadlockAWT extends UITestCase { + static GLProfile glp; + static int width, height; + + @BeforeClass + public static void initClass() { + glp = GLProfile.getGL2ES2(); + Assert.assertNotNull( glp ); + width = 512; + height = 512; + } + + protected void runTestGL( GLCapabilities caps ) throws InterruptedException, InvocationTargetException { + final GLOffscreenAutoDrawable fbod = GLDrawableFactory.getFactory(caps.getGLProfile()).createOffscreenAutoDrawable( + null, + caps, new DefaultGLCapabilitiesChooser(), + 512, 512, + null + ); + + final boolean[] done = {false}; + final Runnable pbufferCreationAction = new Runnable() { + public void run() { + System.err.println("AA.1"); + fbod.display(); + done[ 0 ] = true; + System.err.println("AA.X"); + } + }; + + EventQueue.invokeAndWait(new Runnable() { + public void run() { + Assert.assertTrue(EventQueue.isDispatchThread()); + JAWTUtil.lockToolkit(); + try { + final RunnableTask rTask = new RunnableTask(pbufferCreationAction, new Object(), false); + System.err.println("BB.0: "+rTask.getSyncObject()); + synchronized (rTask.getSyncObject()) { + System.err.println("BB.1: "+rTask.getSyncObject()); + new Thread(rTask, Thread.currentThread().getName()+"-Pbuffer_Creation").start(); + try { + System.err.println("BB.2"); + rTask.getSyncObject().wait(); + System.err.println("BB.3"); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + System.err.println("BB.X"); + } + } finally { + JAWTUtil.unlockToolkit(); + } + } + }); + Assert.assertTrue(done[0]); + fbod.destroy(); + } + + @Test(timeout = 2000) // 2s timeout + public void testDeadlock() throws InterruptedException, InvocationTargetException { + GLCapabilities caps = new GLCapabilities( glp ); + runTestGL( caps ); + } + + static long duration = 500; // ms + + public static void main( String args[] ) { + for ( int i = 0; i < args.length; i++ ) { + if ( args[ i ].equals( "-time" ) ) { + i++; + try { + duration = Integer.parseInt( args[ i ] ); + } + catch ( Exception ex ) { + ex.printStackTrace(); + } + } + } + org.junit.runner.JUnitCore.main( TestFBOAutoDrawableDeadlockAWT.class.getName() ); + } +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOAutoDrawableFactoryNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOAutoDrawableFactoryNEWT.java new file mode 100644 index 000000000..2dc547f39 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOAutoDrawableFactoryNEWT.java @@ -0,0 +1,375 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.io.IOException; + +import javax.media.opengl.GL; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLOffscreenAutoDrawable; +import javax.media.opengl.GLProfile; + +import org.junit.Assert; +import org.junit.Test; + +import com.jogamp.opengl.FBObject; +import com.jogamp.opengl.test.junit.jogl.demos.es2.FBOMix2DemosES2; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.jogl.demos.es2.MultisampleDemoES2; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.UITestCase; + +/** + * Toolkit agnostic {@link GLOffscreenAutoDrawable.FBO} tests using the + * {@link GLDrawableFactory#createOffscreenAutoDrawable(javax.media.nativewindow.AbstractGraphicsDevice, GLCapabilitiesImmutable, javax.media.opengl.GLCapabilitiesChooser, int, int, GLContext) factory model}. + *

      + * The created {@link GLOffscreenAutoDrawable.FBO} is being used to run the {@link GLEventListener}. + *

      + *

      + * Extensive FBO reconfiguration (size and sample buffer count) and validation are performed. + *

      + */ +public class TestFBOAutoDrawableFactoryNEWT extends UITestCase { + + static final int widthStep = 800/4; + static final int heightStep = 600/4; + volatile int szStep = 2; + + interface MyGLEventListener extends GLEventListener { + void setMakeSnapshot(); + } + + @Test + public void testGL2ES2_Demo1_SingleBuffer_Normal() throws InterruptedException { + final GLProfile glp = GLProfile.getGL2ES2(); + final GLCapabilities caps = new GLCapabilities(glp); + caps.setDoubleBuffered(false); + testGLFBODrawableImpl(caps, new GearsES2(0)); + } + + @Test + public void testGL2ES2_Demo1_DoubleBuffer_Normal() throws InterruptedException { + final GLProfile glp = GLProfile.getGL2ES2(); + final GLCapabilities caps = new GLCapabilities(glp); + caps.setDoubleBuffered(true); // default + testGLFBODrawableImpl(caps, new GearsES2(0)); + } + + @Test + public void testGL2ES2_Demo2MSAA4() throws InterruptedException { + final GLProfile glp = GLProfile.getGL2ES2(); + final GLCapabilities caps = new GLCapabilities(glp); + caps.setSampleBuffers(true); + caps.setNumSamples(4); + testGLFBODrawableImpl(caps, new MultisampleDemoES2(true)); + } + + @Test + public void testGL2ES2_FBODemoMSAA4() throws InterruptedException { + final GLProfile glp = GLProfile.getGL2ES2(); + final FBOMix2DemosES2 demo = new FBOMix2DemosES2(0); + demo.setDoRotation(false); + final GLCapabilities caps = new GLCapabilities(glp); + caps.setSampleBuffers(true); + caps.setNumSamples(4); + testGLFBODrawableImpl(caps, demo); + } + + @Test + public void testEGLES2_Demo0Normal() throws InterruptedException { + if( GLProfile.isAvailable(GLProfile.GLES2) ) { + final GLProfile glp = GLProfile.get(GLProfile.GLES2); + final GLCapabilities caps = new GLCapabilities(glp); + testGLFBODrawableImpl(caps, new GearsES2(0)); + } else { + System.err.println("EGL ES2 n/a"); + } + } + + @Test + public void testEGLES2_Demo0MSAA4() throws InterruptedException { + if( GLProfile.isAvailable(GLProfile.GLES2) ) { + final GLProfile glp = GLProfile.get(GLProfile.GLES2); + final GLCapabilities caps = new GLCapabilities(glp); + caps.setSampleBuffers(true); + caps.setNumSamples(4); + testGLFBODrawableImpl(caps, new GearsES2(0)); + } else { + System.err.println("EGL ES2 n/a"); + } + } + + void testGLFBODrawableImpl(GLCapabilities caps, GLEventListener demo) throws InterruptedException { + caps.setFBO(true); + final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); + final GLOffscreenAutoDrawable.FBO glad = (GLOffscreenAutoDrawable.FBO) + factory.createOffscreenAutoDrawable(null, caps, null, widthStep*szStep, heightStep*szStep, null); + Assert.assertNotNull(glad); + + System.out.println("Realized GLAD: "+glad); + System.out.println("Realized GLAD: "+glad.getChosenGLCapabilities()); + Assert.assertTrue("FBO drawable is initialized before ctx creation", !glad.isInitialized()); + + glad.display(); // initial display incl. init! + { + final GLContext context = glad.getContext(); + Assert.assertNotNull(context); + Assert.assertTrue(context.isCreated()); + } + Assert.assertTrue("FBO drawable is not initialized after ctx creation", glad.isInitialized()); + + // + // FBO incl. MSAA is fully initialized now + // + + final GLCapabilitiesImmutable chosenCaps = glad.getChosenGLCapabilities(); + System.out.println("Init GLAD: "+glad); + System.out.println("Init GLAD: "+chosenCaps); + + final FBObject fboFront = glad.getFBObject(GL.GL_FRONT); + final FBObject fboBack = glad.getFBObject(GL.GL_BACK); + + System.out.println("Init front FBO: "+fboFront); + System.out.println("Init back FBO: "+fboBack); + + Assert.assertTrue("FBO drawable is not initialized before ctx creation", glad.isInitialized()); + Assert.assertTrue("FBO Front is not initialized before ctx creation", fboFront.isInitialized()); + Assert.assertTrue("FBO Back is not initialized before ctx creation", fboBack.isInitialized()); + + if( chosenCaps.getDoubleBuffered() ) { + Assert.assertTrue("FBO are equal: "+fboFront+" == "+fboBack, !fboFront.equals(fboBack)); + Assert.assertNotSame(fboFront, fboBack); + } else { + Assert.assertTrue("FBO are not equal: "+fboFront+" != "+fboBack, fboFront.equals(fboBack)); + Assert.assertSame(fboFront, fboBack); + } + + final FBObject.TextureAttachment texAttachA, texAttachB; + + texAttachA = glad.getTextureBuffer(GL.GL_FRONT); + if(0==glad.getNumSamples()) { + texAttachB = glad.getTextureBuffer(GL.GL_BACK); + } else { + texAttachB = null; + } + + final FBObject.Colorbuffer colorA, colorB; + final FBObject.RenderAttachment depthA, depthB; + + colorA = fboFront.getColorbuffer(0); + Assert.assertNotNull(colorA); + colorB = fboBack.getColorbuffer(0); + Assert.assertNotNull(colorB); + + depthA = fboFront.getDepthAttachment(); + Assert.assertNotNull(depthA); + depthB = fboBack.getDepthAttachment(); + Assert.assertNotNull(depthB); + + glad.display(); // SWAP_ODD + + if( chosenCaps.getDoubleBuffered() ) { + // double buffer or MSAA + Assert.assertTrue("Color attachments are equal: "+colorB+" == "+colorA, !colorB.equals(colorA)); + Assert.assertNotSame(colorB, colorA); + Assert.assertTrue("Depth attachments are equal: "+depthB+" == "+depthA, !depthB.equals(depthA)); + Assert.assertNotSame(depthB, depthA); + } else { + // single buffer + Assert.assertEquals(colorA, colorB); + Assert.assertSame(colorA, colorB); + Assert.assertEquals(depthA, depthB); + Assert.assertSame(depthA, depthB); + } + + Assert.assertEquals(texAttachA, colorA); + Assert.assertSame(texAttachA, colorA); + if(0==glad.getNumSamples()) { + Assert.assertEquals(texAttachB, colorB); + Assert.assertSame(texAttachB, colorB); + } + + if( chosenCaps.getNumSamples() > 0 ) { + // MSAA + FBObject _fboFront = glad.getFBObject(GL.GL_FRONT); + FBObject _fboBack = glad.getFBObject(GL.GL_BACK); + Assert.assertTrue("FBO are not equal: "+fboFront+" != "+_fboFront, fboFront.equals(_fboFront)); + Assert.assertSame(fboFront, _fboFront); + Assert.assertTrue("FBO are not equal: "+fboBack+" != "+_fboBack, fboBack.equals(_fboBack)); + Assert.assertSame(fboBack, _fboBack); + } else if( chosenCaps.getDoubleBuffered() ) { + // real double buffer + FBObject _fboFront = glad.getFBObject(GL.GL_FRONT); + FBObject _fboBack = glad.getFBObject(GL.GL_BACK); + Assert.assertTrue("FBO are not equal: "+fboBack+" != "+_fboFront, fboBack.equals(_fboFront)); + Assert.assertSame(fboBack, _fboFront); + Assert.assertTrue("FBO are not equal: "+fboFront+" != "+_fboBack, fboFront.equals(_fboBack)); + Assert.assertSame(fboFront, _fboBack); + } else { + // single buffer + FBObject _fboFront = glad.getFBObject(GL.GL_FRONT); + FBObject _fboBack = glad.getFBObject(GL.GL_BACK); + Assert.assertTrue("FBO are not equal: "+fboFront+" != "+_fboFront, fboFront.equals(_fboFront)); + Assert.assertSame(fboFront, _fboFront); + Assert.assertTrue("FBO are not equal: "+fboBack+" != "+_fboFront, fboBack.equals(_fboFront)); + Assert.assertSame(fboBack, _fboFront); + Assert.assertTrue("FBO are not equal: "+fboBack+" != "+_fboBack, fboBack.equals(_fboBack)); + Assert.assertSame(fboBack, _fboBack); + Assert.assertTrue("FBO are not equal: "+fboFront+" != "+_fboBack, fboFront.equals(_fboBack)); + Assert.assertSame(fboFront, _fboBack); + } + + glad.addGLEventListener(demo); + + final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); + glad.addGLEventListener(snapshotGLEventListener); + + glad.display(); // - SWAP_EVEN + + // 1 - szStep = 2 + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); // - SWAP_ODD + + // 2, 3 (resize + display) + szStep = 1; + glad.setSize(widthStep*szStep, heightStep*szStep); // SWAP_EVEN + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); // - SWAP_ODD + glad.display(); // - SWAP_EVEN + { + // Check whether the attachment reference are still valid! + final FBObject _fboFront = glad.getFBObject(GL.GL_FRONT); + final FBObject _fboBack = glad.getFBObject(GL.GL_BACK); + System.out.println("Resize1.oldFront: "+fboFront); + System.out.println("Resize1.nowFront: "+_fboFront); + System.out.println("Resize1.oldBack : "+fboBack); + System.out.println("Resize1.nowBack : "+_fboBack); + Assert.assertEquals(fboFront, _fboFront); + Assert.assertSame(fboFront, _fboFront); + Assert.assertEquals(fboBack, _fboBack); + Assert.assertSame(fboBack, _fboBack); + + FBObject.Colorbuffer _color = _fboFront.getColorbuffer(0); + Assert.assertNotNull(_color); + Assert.assertEquals(colorA, _color); + Assert.assertSame(colorA, _color); + + FBObject.RenderAttachment _depth = _fboFront.getDepthAttachment(); + System.err.println("Resize1.oldDepth "+depthA); + System.err.println("Resize1.newDepth "+_depth); + Assert.assertNotNull(_depth); + + Assert.assertEquals(depthA, _depth); + Assert.assertSame(depthA, _depth); + _depth = _fboBack.getDepthAttachment(); + Assert.assertNotNull(_depth); + Assert.assertEquals(depthB, _depth); + Assert.assertSame(depthB, _depth); + + _color = _fboFront.getColorbuffer(colorA); + Assert.assertNotNull(_color); + Assert.assertEquals(colorA, _color); + Assert.assertSame(colorA, _color); + } + + // 4, 5 (resize + display) + szStep = 4; + glad.setSize(widthStep*szStep, heightStep*szStep); // SWAP_ODD + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); // - SWAP_EVEN + glad.display(); // - SWAP_ODD + { + // Check whether the attachment reference are still valid! + final FBObject _fboFront = glad.getFBObject(GL.GL_FRONT); + final FBObject _fboBack = glad.getFBObject(GL.GL_BACK); + System.out.println("Resize2.oldFront: "+fboFront); + System.out.println("Resize2.nowFront: "+_fboFront); + System.out.println("Resize2.oldBack : "+fboBack); + System.out.println("Resize2.nowBack : "+_fboBack); + if(chosenCaps.getDoubleBuffered() && 0==chosenCaps.getNumSamples()) { + // real double buffer + Assert.assertEquals(fboBack, _fboFront); + Assert.assertEquals(fboFront, _fboBack); + } else { + // single or MSAA + Assert.assertEquals(fboFront, _fboFront); + Assert.assertEquals(fboBack, _fboBack); + } + + FBObject.Colorbuffer _color = fboBack.getColorbuffer(0); + Assert.assertNotNull(_color); + Assert.assertEquals(colorB, _color); + Assert.assertSame(colorB, _color); + + FBObject.RenderAttachment _depth = fboBack.getDepthAttachment(); + Assert.assertNotNull(_depth); // MSAA back w/ depth + Assert.assertEquals(depthB, _depth); + Assert.assertSame(depthB, _depth); + + _depth = fboFront.getDepthAttachment(); + Assert.assertNotNull(_depth); + Assert.assertEquals(depthA, _depth); + Assert.assertSame(depthA, _depth); + + _color = fboBack.getColorbuffer(colorB); + Assert.assertNotNull(_color); + Assert.assertEquals(colorB, _color); + Assert.assertSame(colorB, _color); + } + + // 6 + 7 (samples + display) + glad.setNumSamples(glad.getGL(), chosenCaps.getNumSamples() > 0 ? 0 : 4); // triggers repaint + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); // actual screenshot + + // 8, 9 (resize + samples + display) + szStep = 3; + glad.setSize(widthStep*szStep, heightStep*szStep); + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + glad.destroy(); + System.out.println("Fin: "+glad); + } + + public static void main(String args[]) throws IOException { + org.junit.runner.JUnitCore.main(TestFBOAutoDrawableFactoryNEWT.class.getName()); + } + +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java deleted file mode 100644 index 7977347a7..000000000 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBODrawableNEWT.java +++ /dev/null @@ -1,272 +0,0 @@ -/** - * Copyright 2012 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package com.jogamp.opengl.test.junit.jogl.acore; - -import java.io.IOException; - -import javax.media.opengl.GL; -import javax.media.opengl.GLAutoDrawable; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLContext; -import javax.media.opengl.GLDrawable; -import javax.media.opengl.GLDrawableFactory; -import javax.media.opengl.GLEventListener; -import javax.media.opengl.GLProfile; - -import jogamp.opengl.GLFBODrawableImpl; - -import org.junit.Assert; -import org.junit.Test; - -import com.jogamp.opengl.FBObject; -import com.jogamp.opengl.OffscreenAutoDrawable; -import com.jogamp.opengl.test.junit.jogl.demos.es2.FBOMix2DemosES2; -import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; -import com.jogamp.opengl.test.junit.jogl.demos.es2.MultisampleDemoES2; -import com.jogamp.opengl.test.junit.util.UITestCase; -import com.jogamp.opengl.util.GLReadBufferUtil; -import com.jogamp.opengl.util.texture.TextureIO; - -public class TestFBODrawableNEWT extends UITestCase { - - static final int widthStep = 800/4; - static final int heightStep = 600/4; - volatile int szStep = 2; - - @Test - public void testGL2ES2_Demo1Normal() throws InterruptedException { - final GLProfile glp = GLProfile.getGL2ES2(); - final GLCapabilities caps = new GLCapabilities(glp); - testGLFBODrawableImpl(caps, new GearsES2(0)); - } - - @Test - public void testGL2ES2_Demo1MSAA4() throws InterruptedException { - final GLProfile glp = GLProfile.getGL2ES2(); - final GLCapabilities caps = new GLCapabilities(glp); - caps.setSampleBuffers(true); - caps.setNumSamples(4); - testGLFBODrawableImpl(caps, new GearsES2(0)); - } - - @Test - public void testGL2ES2_Demo2Normal() throws InterruptedException { - final GLProfile glp = GLProfile.getGL2ES2(); - final GLCapabilities caps = new GLCapabilities(glp); - testGLFBODrawableImpl(caps, new MultisampleDemoES2(false)); - } - - @Test - public void testGL2ES2_Demo2MSAA4() throws InterruptedException { - final GLProfile glp = GLProfile.getGL2ES2(); - final GLCapabilities caps = new GLCapabilities(glp); - caps.setSampleBuffers(true); - caps.setNumSamples(4); - testGLFBODrawableImpl(caps, new MultisampleDemoES2(true)); - } - - @Test - public void testGL2ES2_FBODemoNormal() throws InterruptedException { - final GLProfile glp = GLProfile.getGL2ES2(); - final FBOMix2DemosES2 demo = new FBOMix2DemosES2(0); - demo.setDoRotation(false); - final GLCapabilities caps = new GLCapabilities(glp); - testGLFBODrawableImpl(caps, demo); - } - - @Test - public void testGL2ES2_FBODemoMSAA4() throws InterruptedException { - final GLProfile glp = GLProfile.getGL2ES2(); - final FBOMix2DemosES2 demo = new FBOMix2DemosES2(0); - demo.setDoRotation(false); - final GLCapabilities caps = new GLCapabilities(glp); - caps.setSampleBuffers(true); - caps.setNumSamples(4); - testGLFBODrawableImpl(caps, demo); - } - - @Test - public void testEGLES2_Demo0Normal() throws InterruptedException { - if( GLProfile.isAvailable(GLProfile.GLES2) ) { - final GLProfile glp = GLProfile.get(GLProfile.GLES2); - final GLCapabilities caps = new GLCapabilities(glp); - testGLFBODrawableImpl(caps, new GearsES2(0)); - } else { - System.err.println("EGL ES2 n/a"); - } - } - - @Test - public void testEGLES2_Demo0MSAA4() throws InterruptedException { - if( GLProfile.isAvailable(GLProfile.GLES2) ) { - final GLProfile glp = GLProfile.get(GLProfile.GLES2); - final GLCapabilities caps = new GLCapabilities(glp); - caps.setSampleBuffers(true); - caps.setNumSamples(4); - testGLFBODrawableImpl(caps, new GearsES2(0)); - } else { - System.err.println("EGL ES2 n/a"); - } - } - - boolean skipShot = false; - - void testGLFBODrawableImpl(GLCapabilities caps, GLEventListener demo) throws InterruptedException { - final GLReadBufferUtil screenshot = new GLReadBufferUtil(false, false); - caps.setFBO(true); - final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); - final GLDrawable fboDrawable = factory.createOffscreenDrawable(null, caps, null, widthStep*szStep, heightStep*szStep); - Assert.assertNotNull(fboDrawable); - Assert.assertTrue("Not an FBO Drawable", fboDrawable instanceof GLFBODrawableImpl); - - fboDrawable.setRealized(true); - Assert.assertTrue(fboDrawable.isRealized()); - - final FBObject fbo = ((GLFBODrawableImpl)fboDrawable).getFBObject(); - - System.out.println("Realized: "+fboDrawable); - System.out.println("Realized: "+fboDrawable.getChosenGLCapabilities()); - System.out.println("Realized: "+fbo); - - final GLContext context = fboDrawable.createContext(null); - Assert.assertNotNull(context); - - int res = context.makeCurrent(); - Assert.assertTrue(GLContext.CONTEXT_CURRENT_NEW==res || GLContext.CONTEXT_CURRENT==res); - context.release(); - - System.out.println("Post Create-Ctx: "+fbo); - final FBObject.Colorbuffer colorA = fbo.getColorbuffer(0); - Assert.assertNotNull(colorA); - final FBObject.RenderAttachment depthA = fbo.getDepthAttachment(); - Assert.assertNotNull(depthA); - - final OffscreenAutoDrawable glad = new OffscreenAutoDrawable(fboDrawable, context, true); - - glad.addGLEventListener(demo); - glad.addGLEventListener(new GLEventListener() { - volatile int displayCount=0; - volatile int reshapeCount=0; - public void init(GLAutoDrawable drawable) {} - public void dispose(GLAutoDrawable drawable) {} - public void display(GLAutoDrawable drawable) { - final GL gl = drawable.getGL(); - // System.err.println(Thread.currentThread().getName()+": ** display: "+displayCount+": step "+szStep+" "+drawable.getWidth()+"x"+drawable.getHeight()); - // System.err.println(Thread.currentThread().getName()+": ** FBO-THIS: "+fbo); - // System.err.println(Thread.currentThread().getName()+": ** FBO-SINK: "+fbo.getSamplingSinkFBO()); - // System.err.println(Thread.currentThread().getName()+": ** drawable-read: "+gl.getDefaultReadFramebuffer()); - if(skipShot) { - skipShot=false; - } else { - snapshot(getSimpleTestName("."), displayCount, "msaa"+fbo.getNumSamples(), gl, screenshot, TextureIO.PNG, null); - } - Assert.assertEquals(drawable.getWidth(), widthStep*szStep); - Assert.assertEquals(drawable.getHeight(), heightStep*szStep); - displayCount++; - } - public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { - System.err.println(Thread.currentThread().getName()+": ** reshape: "+reshapeCount+": step "+szStep+" "+width+"x"+height+" - "+drawable.getWidth()+"x"+drawable.getHeight()); - Assert.assertEquals(drawable.getWidth(), widthStep*szStep); - Assert.assertEquals(drawable.getHeight(), heightStep*szStep); - reshapeCount++; - } - }); - - // 0 - szStep = 2 - glad.display(); - - // 1, 2 (resize + display) - szStep = 1; - skipShot=true; - glad.setSize(widthStep*szStep, heightStep*szStep); - glad.display(); - Assert.assertEquals(glad.getWidth(), widthStep*szStep); - Assert.assertEquals(glad.getHeight(), heightStep*szStep); - { - // Check whether the attachment reference are still valid! - FBObject.Colorbuffer _colorA = fbo.getColorbuffer(0); - Assert.assertNotNull(_colorA); - Assert.assertTrue(colorA == _colorA); - Assert.assertTrue(colorA.equals(_colorA)); - FBObject.RenderAttachment _depthA = fbo.getDepthAttachment(); - Assert.assertNotNull(_depthA); - Assert.assertTrue(depthA == _depthA); - Assert.assertTrue(depthA.equals(_depthA)); - - _colorA = fbo.getColorbuffer(colorA); - Assert.assertNotNull(_colorA); - Assert.assertTrue(colorA == _colorA); - Assert.assertTrue(colorA.equals(_colorA)); - } - - // 3, 4 (resize + display) - szStep = 4; - skipShot=true; - glad.setSize(widthStep*szStep, heightStep*szStep); - glad.display(); - Assert.assertEquals(glad.getWidth(), widthStep*szStep); - Assert.assertEquals(glad.getHeight(), heightStep*szStep); - { - // Check whether the attachment reference are still valid! - FBObject.Colorbuffer _colorA = fbo.getColorbuffer(0); - Assert.assertNotNull(_colorA); - Assert.assertTrue(colorA == _colorA); - final FBObject.RenderAttachment _depthA = fbo.getDepthAttachment(); - Assert.assertNotNull(_depthA); - Assert.assertTrue(depthA == _depthA); - - _colorA = fbo.getColorbuffer(colorA); - Assert.assertNotNull(_colorA); - Assert.assertTrue(colorA == _colorA); - } - - // 5 - glad.display(); - Assert.assertEquals(glad.getWidth(), widthStep*szStep); - Assert.assertEquals(glad.getHeight(), heightStep*szStep); - - // 6, 7 (resize + display) - szStep = 3; - skipShot=true; - glad.setSize(widthStep*szStep, heightStep*szStep); - glad.display(); - Assert.assertEquals(glad.getWidth(), widthStep*szStep); - Assert.assertEquals(glad.getHeight(), heightStep*szStep); - - glad.destroy(); - System.out.println("Fin: "+fboDrawable); - - // final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(fboDrawable, context); - } - - public static void main(String args[]) throws IOException { - org.junit.runner.JUnitCore.main(TestFBODrawableNEWT.class.getName()); - } - -} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMRTNEWT01.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMRTNEWT01.java index f7c83a03b..077baad43 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMRTNEWT01.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMRTNEWT01.java @@ -229,7 +229,7 @@ public class TestFBOMRTNEWT01 extends UITestCase { final NativeSurface ns = gl.getContext().getGLReadDrawable().getNativeSurface(); if(last_snap_size[0] != ns.getWidth() && last_snap_size[1] != ns.getHeight()) { gl.glFinish(); // sync .. no swap buffers yet! - snapshot(getSimpleTestName("."), step_i, null, gl, screenshot, TextureIO.PNG, null); // overwrite ok + snapshot(step_i, null, gl, screenshot, TextureIO.PNG, null); // overwrite ok last_snap_size[0] = ns.getWidth(); last_snap_size[1] = ns.getHeight(); } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMix2DemosES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMix2DemosES2NEWT.java index b384c9327..b3c542c63 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMix2DemosES2NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOMix2DemosES2NEWT.java @@ -106,7 +106,7 @@ public class TestFBOMix2DemosES2NEWT extends UITestCase { if(dw<800) { System.err.println("XXX: "+dw+"x"+dh+", c "+c); if(0 == c%3) { - snapshot(getSimpleTestName("."), i++, "msaa"+demo.getMSAA(), drawable.getGL(), screenshot, TextureIO.PNG, null); + snapshot(i++, "msaa"+demo.getMSAA(), drawable.getGL(), screenshot, TextureIO.PNG, null); } if( 3 == c ) { new Thread() { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOOffThreadSharedContextMix2DemosES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOOffThreadSharedContextMix2DemosES2NEWT.java new file mode 100644 index 000000000..3ecf89bfc --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestFBOOffThreadSharedContextMix2DemosES2NEWT.java @@ -0,0 +1,298 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import com.jogamp.newt.event.WindowEvent; +import com.jogamp.newt.event.WindowAdapter; +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.MiscUtils; +import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.test.junit.util.QuitAdapter; + +import com.jogamp.opengl.util.Animator; +import com.jogamp.opengl.util.FPSAnimator; +import com.jogamp.opengl.util.GLReadBufferUtil; +import com.jogamp.opengl.util.texture.TextureIO; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.jogl.demos.es2.Mix2TexturesES2; +import com.jogamp.opengl.test.junit.jogl.demos.es2.RedSquareES2; + +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.SurfaceUpdatedListener; +import javax.media.opengl.GL; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLOffscreenAutoDrawable; +import javax.media.opengl.GLProfile; + +import org.junit.Assert; +import org.junit.AfterClass; +import org.junit.Test; + +/** + * Toolkit agnostic {@link GLOffscreenAutoDrawable.FBO} tests using the + * {@link GLDrawableFactory#createOffscreenAutoDrawable(javax.media.nativewindow.AbstractGraphicsDevice, GLCapabilitiesImmutable, javax.media.opengl.GLCapabilitiesChooser, int, int, GLContext) factory model}. + *

      + * The created {@link GLOffscreenAutoDrawable.FBO} is being used to run the {@link GLEventListener}. + *

      + *

      + * This test simulates shared off-thread GL context / texture usage, + * where the producer use FBOs and delivers shared textures. + * The receiver blends the shared textures onscreen. + * In detail the test consist of: + *

        + *
      • 2 {@link GLOffscreenAutoDrawable.FBO} double buffered + *
          + *
        • each with their own {@link GLContext}, which is shares the {@link GLWindow} one (see below)
        • + *
        • both run within one {@link FPSAnimator} @ 30fps
        • + *
        • produce a texture
        • + *
        • notify the onscreen renderer about new textureID (swapping double buffer)
        • + *
      • + *
      • 1 onscreen {@link GLWindow} + *
          + *
        • shares it's {@link GLContext} w/ above FBOs
        • + *
        • running within one {@link Animator} at v-sync
        • + *
        • uses the shared FBO textures and blends them onscreen
        • + *
      • + *
      + *

      + */ +public class TestFBOOffThreadSharedContextMix2DemosES2NEWT extends UITestCase { + static long duration = 500; // ms + static int swapInterval = 1; + static boolean showFPS = false; + static boolean forceES2 = false; + static boolean mainRun = false; + + @AfterClass + public static void releaseClass() { + } + + protected void runTestGL(GLCapabilitiesImmutable caps) throws InterruptedException { + final GLReadBufferUtil screenshot = new GLReadBufferUtil(false, false); + System.err.println("requested: vsync "+swapInterval+", "+caps); + + final GLWindow glWindow = GLWindow.create(caps); + Assert.assertNotNull(glWindow); + glWindow.setTitle("Gears NEWT Test (translucent "+!caps.isBackgroundOpaque()+"), swapInterval "+swapInterval); + if(mainRun) { + glWindow.setSize(512, 512); + } else { + glWindow.setSize(256, 256); + } + // eager initialization of context + glWindow.setVisible(true); + glWindow.display(); + + final int fbod1_texUnit = 0; + final int fbod2_texUnit = 1; + + final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); + GLCapabilities fbodCaps = (GLCapabilities) caps.cloneMutable(); + // fbodCaps.setDoubleBuffered(false); + + final Mix2TexturesES2 mixerDemo = new Mix2TexturesES2(1, fbod1_texUnit, fbod2_texUnit); + + // FBOD1 + final GLOffscreenAutoDrawable.FBO fbod1 = (GLOffscreenAutoDrawable.FBO) + factory.createOffscreenAutoDrawable(null, fbodCaps, null, glWindow.getWidth(), glWindow.getHeight(), glWindow.getContext()); + fbod1.setUpstreamWidget(glWindow); // connect the real GLWindow (mouse/key) to offscreen! + fbod1.setTextureUnit(fbod1_texUnit); + { + GearsES2 demo0 = new GearsES2(-1); + fbod1.addGLEventListener(demo0); + demo0.setIgnoreFocus(true); + } + fbod1.getNativeSurface().addSurfaceUpdatedListener(new SurfaceUpdatedListener() { + @Override + public void surfaceUpdated(Object updater, NativeSurface ns, long when) { + mixerDemo.setTexID0(fbod1.getTextureBuffer(GL.GL_FRONT).getName()); + } }); + fbod1.display(); // init + System.err.println("FBOD1 "+fbod1); + Assert.assertTrue(fbod1.isInitialized()); + + // FBOD2 + final GLOffscreenAutoDrawable.FBO fbod2 = (GLOffscreenAutoDrawable.FBO) + factory.createOffscreenAutoDrawable(null, fbodCaps, null, glWindow.getWidth(), glWindow.getHeight(), glWindow.getContext()); + fbod2.setTextureUnit(fbod2_texUnit); + fbod2.addGLEventListener(new RedSquareES2(-1)); + fbod2.getNativeSurface().addSurfaceUpdatedListener(new SurfaceUpdatedListener() { + @Override + public void surfaceUpdated(Object updater, NativeSurface ns, long when) { + mixerDemo.setTexID1(fbod2.getTextureBuffer(GL.GL_FRONT).getName()); + } }); + fbod2.display(); // init + System.err.println("FBOD2 "+fbod2); + Assert.assertTrue(fbod2.isInitialized()); + + // preinit texIDs + mixerDemo.setTexID0(fbod1.getTextureBuffer(GL.GL_FRONT).getName()); + mixerDemo.setTexID1(fbod2.getTextureBuffer(GL.GL_FRONT).getName()); + + glWindow.addGLEventListener(mixerDemo); + glWindow.addGLEventListener(new GLEventListener() { + int i=0, c=0; + public void init(GLAutoDrawable drawable) {} + public void dispose(GLAutoDrawable drawable) {} + public void display(GLAutoDrawable drawable) { + if(mainRun) return; + + final int dw = drawable.getWidth(); + final int dh = drawable.getHeight(); + c++; + + if(dw<800) { + System.err.println("XXX: "+dw+"x"+dh+", c "+c); + if(8 == c) { + snapshot(i++, "msaa"+fbod1.getNumSamples(), drawable.getGL(), screenshot, TextureIO.PNG, null); + } + if(9 == c) { + c=0; + new Thread() { + @Override + public void run() { + glWindow.setSize(dw+256, dh+256); + } }.start(); + } + } + } + public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { + fbod1.setSize(width, height); + fbod2.setSize(width, height); + } + }); + + final FPSAnimator animator0 = new FPSAnimator(30); + animator0.add(fbod1); + animator0.add(fbod2); + + final Animator animator1 = new Animator(); + animator1.add(glWindow); + + QuitAdapter quitAdapter = new QuitAdapter(); + + //glWindow.addKeyListener(new TraceKeyAdapter(quitAdapter)); + //glWindow.addWindowListener(new TraceWindowAdapter(quitAdapter)); + glWindow.addKeyListener(quitAdapter); + glWindow.addWindowListener(quitAdapter); + + glWindow.addWindowListener(new WindowAdapter() { + public void windowResized(WindowEvent e) { + System.err.println("window resized: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()); + } + public void windowMoved(WindowEvent e) { + System.err.println("window moved: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()); + } + }); + + animator0.start(); + animator1.start(); + // glWindow.setSkipContextReleaseThread(animator.getThread()); + + glWindow.setVisible(true); + + System.err.println("NW chosen: "+glWindow.getDelegatedWindow().getChosenCapabilities()); + System.err.println("GL chosen: "+glWindow.getChosenCapabilities()); + System.err.println("window pos/siz: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", "+glWindow.getInsets()); + + animator0.setUpdateFPSFrames(30, showFPS ? System.err : null); + animator1.setUpdateFPSFrames(60, showFPS ? System.err : null); + + while(!quitAdapter.shouldQuit() && animator1.isAnimating() && animator1.getTotalFPSDuration() + * The created {@link GLOffscreenAutoDrawable.FBO} is being used to run the {@link GLEventListener}. + *

      + *

      + * This test simulates shared on-thread GL context / texture usage, + * where the producer uses an FBO and delivers a shared texture. + * The receiver draws the shared texture onscreen. + * In detail the test consist of: + *

        + *
      • 1 {@link GLOffscreenAutoDrawable.FBO} double buffered + *
          + * + *
        • running within common {@link Animator} @ 60fps
        • + *
        • produce a texture
        • + *
        • notify the onscreen renderer about new textureID (swapping double buffer)
        • + *
      • + *
      • 1 onscreen {@link GLWindow} + *
          + *
        • shares it's {@link GLContext} w/ above FBO
        • + *
        • running within common {@link Animator} @ 60fps
        • + *
        • uses the shared FBO texture and draws it onscreen
        • + *
      • + *
      + *

      + */ +public class TestFBOOnThreadSharedContext1DemoES2NEWT extends UITestCase { + static long duration = 500; // ms + static int swapInterval = 1; + static boolean showFPS = false; + static boolean forceES2 = false; + static boolean mainRun = false; + + @AfterClass + public static void releaseClass() { + } + + protected void runTestGL(GLCapabilitiesImmutable caps) throws InterruptedException { + final GLReadBufferUtil screenshot = new GLReadBufferUtil(false, false); + System.err.println("requested: vsync "+swapInterval+", "+caps); + + final GLWindow glWindow = GLWindow.create(caps); + Assert.assertNotNull(glWindow); + glWindow.setTitle("Gears NEWT Test (translucent "+!caps.isBackgroundOpaque()+"), swapInterval "+swapInterval); + if(mainRun) { + glWindow.setSize(512, 512); + } else { + glWindow.setSize(256, 256); + } + // eager initialization of context + glWindow.setVisible(true); + glWindow.display(); + + final int fbod1_texUnit = 0; + + final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); + GLCapabilities fbodCaps = (GLCapabilities) caps.cloneMutable(); + // fbodCaps.setDoubleBuffered(false); + + final Mix2TexturesES2 mixerDemo = new Mix2TexturesES2(1, fbod1_texUnit, 0); + + // FBOD1 + final GLOffscreenAutoDrawable.FBO fbod1 = (GLOffscreenAutoDrawable.FBO) + factory.createOffscreenAutoDrawable(null, fbodCaps, null, glWindow.getWidth(), glWindow.getHeight(), glWindow.getContext()); + fbod1.setUpstreamWidget(glWindow); // connect the real GLWindow (mouse/key) to offscreen! + fbod1.setTextureUnit(fbod1_texUnit); + { + GearsES2 demo0 = new GearsES2(-1); + fbod1.addGLEventListener(demo0); + demo0.setIgnoreFocus(true); + } + fbod1.getNativeSurface().addSurfaceUpdatedListener(new SurfaceUpdatedListener() { + @Override + public void surfaceUpdated(Object updater, NativeSurface ns, long when) { + mixerDemo.setTexID0(fbod1.getTextureBuffer(GL.GL_FRONT).getName()); + } }); + fbod1.display(); // init + System.err.println("FBOD1 "+fbod1); + Assert.assertTrue(fbod1.isInitialized()); + + // preinit texIDs + mixerDemo.setTexID0(fbod1.getTextureBuffer(GL.GL_FRONT).getName()); + + glWindow.addWindowListener(new WindowAdapter() { + @Override + public void windowResized(WindowEvent e) { + fbod1.setSize(glWindow.getWidth(), glWindow.getHeight()); + } + }); + glWindow.addGLEventListener(mixerDemo); + glWindow.addGLEventListener(new GLEventListener() { + int i=0, c=0; + public void init(GLAutoDrawable drawable) {} + public void dispose(GLAutoDrawable drawable) {} + public void display(GLAutoDrawable drawable) { + if(mainRun) return; + + final int dw = drawable.getWidth(); + final int dh = drawable.getHeight(); + c++; + + if(dw<800) { + System.err.println("XXX: "+dw+"x"+dh+", c "+c); + if(8 == c) { + snapshot(i++, "msaa"+fbod1.getNumSamples(), drawable.getGL(), screenshot, TextureIO.PNG, null); + } + if(9 == c) { + c=0; + new Thread() { + @Override + public void run() { + glWindow.setSize(dw+256, dh+256); + } }.start(); + } + } + } + public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } + }); + + final Animator animator1 = new Animator(); + animator1.add(fbod1); + animator1.add(glWindow); + + QuitAdapter quitAdapter = new QuitAdapter(); + + //glWindow.addKeyListener(new TraceKeyAdapter(quitAdapter)); + //glWindow.addWindowListener(new TraceWindowAdapter(quitAdapter)); + glWindow.addKeyListener(quitAdapter); + glWindow.addWindowListener(quitAdapter); + + glWindow.addWindowListener(new WindowAdapter() { + public void windowResized(WindowEvent e) { + System.err.println("window resized: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()); + } + public void windowMoved(WindowEvent e) { + System.err.println("window moved: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()); + } + }); + + animator1.start(); + // glWindow.setSkipContextReleaseThread(animator.getThread()); + + glWindow.setVisible(true); + + System.err.println("NW chosen: "+glWindow.getDelegatedWindow().getChosenCapabilities()); + System.err.println("GL chosen: "+glWindow.getChosenCapabilities()); + System.err.println("window pos/siz: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", "+glWindow.getInsets()); + + animator1.setUpdateFPSFrames(60, showFPS ? System.err : null); + + while(!quitAdapter.shouldQuit() && animator1.isAnimating() && animator1.getTotalFPSDuration() + * Each test creates a {@link GLDrawable} using the + * {@link GLDrawableFactory#createGLDrawable(javax.media.nativewindow.NativeSurface) factory model}. + * The {@link GLContext} is derived {@link GLDrawable#createContext(GLContext) from the drawable}. + *

      + *

      + * Finally a {@link GLAutoDrawableDelegate} is created with the just created {@link GLDrawable} and {@link GLContext}. + * It is being used to run the {@link GLEventListener}. + *

      + */ +public class TestGLAutoDrawableDelegateOnOffscrnCapsNEWT extends UITestCase { + static final int widthStep = 800/4; + static final int heightStep = 600/4; + volatile int szStep = 2; + + static GLCapabilities getCaps(String profile) { + if( !GLProfile.isAvailable(profile) ) { + System.err.println("Profile "+profile+" n/a"); + return null; + } + return new GLCapabilities(GLProfile.get(profile)); + } + + void doTest(GLCapabilitiesImmutable reqGLCaps, GLEventListener demo) throws InterruptedException { + System.out.println("Requested GL Caps: "+reqGLCaps); + final GLDrawableFactory factory = GLDrawableFactory.getFactory(reqGLCaps.getGLProfile()); + + final boolean fboAvailable = factory.canCreateFBO(null, reqGLCaps.getGLProfile()); + final boolean pbufferAvailable = factory.canCreateGLPbuffer(null); + final GLCapabilitiesImmutable expGLCaps = GLGraphicsConfigurationUtil.fixGLCapabilities(reqGLCaps, fboAvailable, pbufferAvailable); + System.out.println("Expected GL Caps: "+expGLCaps); + // + // Create native windowing resources .. X11/Win/OSX + // + final Window window = NewtFactory.createWindow(reqGLCaps); + Assert.assertNotNull(window); + window.setSize(widthStep*szStep, heightStep*szStep); + window.setVisible(true); + Assert.assertTrue(AWTRobotUtil.waitForVisible(window, true)); + Assert.assertTrue(AWTRobotUtil.waitForRealized(window, true)); + System.out.println("Window: "+window.getClass().getName()); + + // Check caps of NativeWindow config w/o GL + final CapabilitiesImmutable chosenCaps = window.getGraphicsConfiguration().getChosenCapabilities(); + System.out.println("Window Caps Pre_GL: "+chosenCaps); + Assert.assertNotNull(chosenCaps); + Assert.assertTrue(chosenCaps.getGreenBits()>5); + Assert.assertTrue(chosenCaps.getBlueBits()>5); + Assert.assertTrue(chosenCaps.getRedBits()>5); + + // + // Create native OpenGL resources .. XGL/WGL/CGL .. + // equivalent to GLAutoDrawable methods: setVisible(true) + // + final GLDrawable drawable = factory.createGLDrawable(window); + Assert.assertNotNull(drawable); + System.out.println("Drawable Pre-GL(0): "+drawable.getClass().getName()+", "+drawable.getNativeSurface().getClass().getName()); + + // + drawable.setRealized(true); + Assert.assertTrue(drawable.isRealized()); + + System.out.println("Window Caps PostGL : "+window.getGraphicsConfiguration().getChosenCapabilities()); + System.out.println("Drawable Post-GL(1): "+drawable.getClass().getName()+", "+drawable.getNativeSurface().getClass().getName()); + + // Check caps of GLDrawable after realization + final GLCapabilitiesImmutable chosenGLCaps = drawable.getChosenGLCapabilities(); + System.out.println("Chosen GL Caps(1): "+chosenGLCaps); + Assert.assertNotNull(chosenGLCaps); + Assert.assertTrue(chosenGLCaps.getGreenBits()>5); + Assert.assertTrue(chosenGLCaps.getBlueBits()>5); + Assert.assertTrue(chosenGLCaps.getRedBits()>5); + Assert.assertTrue(chosenGLCaps.getDepthBits()>4); + Assert.assertEquals(expGLCaps.isOnscreen(), chosenGLCaps.isOnscreen()); + Assert.assertEquals(expGLCaps.isFBO(), chosenGLCaps.isFBO()); + Assert.assertEquals(expGLCaps.isPBuffer(), chosenGLCaps.isPBuffer()); + Assert.assertEquals(expGLCaps.isBitmap(), chosenGLCaps.isBitmap()); + /** Single/Double buffer cannot be checked since result may vary .. + if(chosenGLCaps.isOnscreen() || chosenGLCaps.isFBO()) { + // dbl buffer may be disabled w/ offscreen pbuffer and bitmap + Assert.assertEquals(expGLCaps.getDoubleBuffered(), chosenGLCaps.getDoubleBuffered()); + } */ + + GLContext context = drawable.createContext(null); + Assert.assertNotNull(context); + int res = context.makeCurrent(); + Assert.assertTrue(GLContext.CONTEXT_CURRENT_NEW==res || GLContext.CONTEXT_CURRENT==res); + context.release(); + + System.out.println("Chosen GL Caps(2): "+drawable.getChosenGLCapabilities()); + System.out.println("Chosen GL CTX (2): "+context.getGLVersion()); + System.out.println("Drawable Post-GL(2): "+drawable.getClass().getName()+", "+drawable.getNativeSurface().getClass().getName()); + + final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(drawable, context, window, false, null) { + @Override + protected void destroyImplInLock() { + super.destroyImplInLock(); // destroys drawable/context + window.destroy(); // destroys the actual window, incl. the device + } + }; + + window.addWindowListener(new WindowAdapter() { + @Override + public void windowRepaint(WindowUpdateEvent e) { + glad.windowRepaintOp(); + } + + @Override + public void windowResized(WindowEvent e) { + glad.windowResizedOp(window.getWidth(), window.getHeight()); + } + + @Override + public void windowDestroyNotify(WindowEvent e) { + glad.windowDestroyNotifyOp(); + } + }); + + glad.addGLEventListener(demo); + + final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); + glad.addGLEventListener(snapshotGLEventListener); + + glad.display(); // initial resize/display + + // 1 - szStep = 2 + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + // 2, 3 (resize + display) + szStep = 1; + window.setSize(widthStep*szStep, heightStep*szStep); + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + // 4, 5 (resize + display) + szStep = 4; + window.setSize(widthStep*szStep, heightStep*szStep); + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + Thread.sleep(50); + + glad.destroy(); + System.out.println("Fin Drawable: "+drawable); + System.out.println("Fin Window: "+window); + } + + @Test + public void testAvailableInfo() { + GLDrawableFactory f = GLDrawableFactory.getDesktopFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + f = GLDrawableFactory.getEGLFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + } + + @Test + public void testGL2OnScreenDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OnScreenSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenAutoDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBODblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBOSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenPbufferDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenPbufferSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenBitmapDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setBitmap(true); + doTest(reqGLCaps, new Gears(1)); + } + + @Test + public void testGL2OffScreenBitmapSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setBitmap(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new Gears(1)); + } + + @Test + public void testES2OnScreenDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OnScreenSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenAutoDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBODblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBOSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenPbufferDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenPbufferSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + /** Not implemented ! + @Test + public void testES2OffScreenBitmapDblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GLES2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); + reqGLCaps.setOnscreen(false); + reqGLCaps.setBitmap(true); + doTest(reqGLCaps, new GearsES2(1)); + } */ + + public static void main(String args[]) throws IOException { + org.junit.runner.JUnitCore.main(TestGLAutoDrawableDelegateOnOffscrnCapsNEWT.class.getName()); + } + +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableFactoryOffscrnCapsNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableFactoryOffscrnCapsNEWT.java new file mode 100644 index 000000000..544d74aa5 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableFactoryOffscrnCapsNEWT.java @@ -0,0 +1,317 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.io.IOException; + +import javax.media.nativewindow.CapabilitiesImmutable; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLOffscreenAutoDrawable; +import javax.media.opengl.GLProfile; + +import jogamp.opengl.GLGraphicsConfigurationUtil; + +import org.junit.Assert; +import org.junit.Test; + +import com.jogamp.opengl.JoglVersion; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.UITestCase; + +/** + * Toolkit agnostic {@link GLOffscreenAutoDrawable} tests using the + * {@link GLDrawableFactory#createOffscreenAutoDrawable(javax.media.nativewindow.AbstractGraphicsDevice, GLCapabilitiesImmutable, javax.media.opengl.GLCapabilitiesChooser, int, int, GLContext) factory model}. + *

      + * The created {@link GLOffscreenAutoDrawable} is being used to run the {@link GLEventListener}. + *

      + */ +public class TestGLAutoDrawableFactoryOffscrnCapsNEWT extends UITestCase { + static final int widthStep = 800/4; + static final int heightStep = 600/4; + volatile int szStep = 2; + + static GLCapabilities getCaps(String profile) { + if( !GLProfile.isAvailable(profile) ) { + System.err.println("Profile "+profile+" n/a"); + return null; + } + return new GLCapabilities(GLProfile.get(profile)); + } + + void doTest(GLCapabilitiesImmutable reqGLCaps, GLEventListener demo) throws InterruptedException { + System.out.println("Requested GL Caps: "+reqGLCaps); + final GLDrawableFactory factory = GLDrawableFactory.getFactory(reqGLCaps.getGLProfile()); + + final boolean fboAvailable = factory.canCreateFBO(null, reqGLCaps.getGLProfile()); + final boolean pbufferAvailable = factory.canCreateGLPbuffer(null); + final GLCapabilitiesImmutable expGLCaps = GLGraphicsConfigurationUtil.fixGLCapabilities(reqGLCaps, fboAvailable, pbufferAvailable); + System.out.println("Expected GL Caps: "+expGLCaps); + + // + // Create native OpenGL resources .. XGL/WGL/CGL .. + // equivalent to GLAutoDrawable methods: setVisible(true) + // + final GLOffscreenAutoDrawable glad = factory.createOffscreenAutoDrawable(null, reqGLCaps, null, widthStep*szStep, heightStep*szStep, null); + + Assert.assertNotNull(glad); + System.out.println("Drawable Pre-GL(0): "+glad.getClass().getName()+", "+glad.getNativeSurface().getClass().getName()); + Assert.assertTrue(glad.isRealized()); + + // Check caps of NativeWindow config w/o GL + final CapabilitiesImmutable chosenCaps = glad.getChosenGLCapabilities(); + System.out.println("Drawable Caps Pre_GL : "+chosenCaps); + Assert.assertNotNull(chosenCaps); + Assert.assertTrue(chosenCaps.getGreenBits()>5); + Assert.assertTrue(chosenCaps.getBlueBits()>5); + Assert.assertTrue(chosenCaps.getRedBits()>5); + + glad.display(); // force native context creation + + // Check caps of GLDrawable after realization + final GLCapabilitiesImmutable chosenGLCaps = glad.getChosenGLCapabilities(); + System.out.println("Chosen GL Caps(1): "+chosenGLCaps); + System.out.println("Chosen GL CTX (1): "+glad.getContext().getGLVersion()); + + Assert.assertNotNull(chosenGLCaps); + Assert.assertTrue(chosenGLCaps.getGreenBits()>5); + Assert.assertTrue(chosenGLCaps.getBlueBits()>5); + Assert.assertTrue(chosenGLCaps.getRedBits()>5); + Assert.assertTrue(chosenGLCaps.getDepthBits()>4); + Assert.assertEquals(expGLCaps.isOnscreen(), chosenGLCaps.isOnscreen()); + Assert.assertEquals(expGLCaps.isFBO(), chosenGLCaps.isFBO()); + Assert.assertEquals(expGLCaps.isPBuffer(), chosenGLCaps.isPBuffer()); + Assert.assertEquals(expGLCaps.isBitmap(), chosenGLCaps.isBitmap()); + /** Single/Double buffer cannot be checked since result may vary .. + if(chosenGLCaps.isOnscreen() || chosenGLCaps.isFBO()) { + // dbl buffer may be disabled w/ offscreen pbuffer and bitmap + Assert.assertEquals(expGLCaps.getDoubleBuffered(), chosenGLCaps.getDoubleBuffered()); + } */ + + glad.addGLEventListener(demo); + + final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); + glad.addGLEventListener(snapshotGLEventListener); + + glad.display(); // initial resize/display + + // 1 - szStep = 2 + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + // 2, 3 (resize + display) + szStep = 1; + glad.setSize(widthStep*szStep, heightStep*szStep); + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + // 4, 5 (resize + display) + szStep = 4; + glad.setSize(widthStep*szStep, heightStep*szStep); + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + Thread.sleep(50); + + glad.destroy(); + System.out.println("Fin Drawable: "+glad); + } + + @Test + public void testAvailableInfo() { + GLDrawableFactory f = GLDrawableFactory.getDesktopFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + f = GLDrawableFactory.getEGLFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + } + + @Test + public void testGL2OffScreenAutoDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBODblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBOSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBOStencil() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setStencilBits(1); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBOStencilMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setStencilBits(1); + reqGLCaps.setSampleBuffers(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenPbufferDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenPbufferSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenBitmapDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setBitmap(true); + doTest(reqGLCaps, new Gears(1)); + } + + @Test + public void testGL2OffScreenBitmapSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setBitmap(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new Gears(1)); + } + + @Test + public void testES2OffScreenAutoDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBODblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBOSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenPbufferDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenPbufferSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + /** Not implemented ! + @Test + public void testES2OffScreenBitmapDblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GLES2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); + reqGLCaps.setOnscreen(false); + reqGLCaps.setBitmap(true); + doTest(reqGLCaps, new GearsES2(1)); + } */ + + public static void main(String args[]) throws IOException { + org.junit.runner.JUnitCore.main(TestGLAutoDrawableFactoryOffscrnCapsNEWT.class.getName()); + } + +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java new file mode 100644 index 000000000..64a75716b --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java @@ -0,0 +1,328 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.awt.Dimension; +import java.awt.Frame; +import java.io.IOException; + +import javax.media.nativewindow.CapabilitiesImmutable; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLProfile; +import javax.media.opengl.awt.GLCanvas; + +import jogamp.nativewindow.jawt.JAWTUtil; +import jogamp.opengl.GLGraphicsConfigurationUtil; + +import org.junit.Assert; +import org.junit.Assume; +import org.junit.Test; + +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.opengl.JoglVersion; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.UITestCase; + +/** + * Tests using a NEWT {@link GLWindow} {@link GLAutoDrawable auto drawable} for on- and offscreen cases. + *

      + * The NEWT {@link GLAutoDrawable} is being used to run the {@link GLEventListener}. + *

      + */ +public class TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT extends UITestCase { + static final int widthStep = 800/4; + static final int heightStep = 600/4; + volatile int szStep = 2; + + static GLCapabilities getCaps(String profile) { + if( !GLProfile.isAvailable(profile) ) { + System.err.println("Profile "+profile+" n/a"); + return null; + } + return new GLCapabilities(GLProfile.get(profile)); + } + + static void setGLCanvasSize(final Frame frame, final GLCanvas glc, final int width, final int height) { + try { + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + final Dimension new_sz = new Dimension(width, height); + glc.setMinimumSize(new_sz); + glc.setPreferredSize(new_sz); + glc.setSize(new_sz); + frame.pack(); + frame.validate(); + } } ); + } catch( Throwable throwable ) { + throwable.printStackTrace(); + Assume.assumeNoException( throwable ); + } + } + + static interface MyGLEventListener extends GLEventListener { + void setMakeSnapshot(); + } + + void doTest(GLCapabilitiesImmutable reqGLCaps, GLEventListener demo) throws InterruptedException { + if(reqGLCaps.isOnscreen() && JAWTUtil.isOffscreenLayerRequired()) { + System.err.println("onscreen layer n/a"); + return; + } + if(!reqGLCaps.isOnscreen() && !JAWTUtil.isOffscreenLayerSupported()) { + System.err.println("offscreen layer n/a"); + return; + } + System.out.println("Requested GL Caps: "+reqGLCaps); + final GLDrawableFactory factory = GLDrawableFactory.getFactory(reqGLCaps.getGLProfile()); + + final boolean fboAvailable = factory.canCreateFBO(null, reqGLCaps.getGLProfile()); + final boolean pbufferAvailable = factory.canCreateGLPbuffer(null); + final GLCapabilitiesImmutable expGLCaps = GLGraphicsConfigurationUtil.fixGLCapabilities(reqGLCaps, fboAvailable, pbufferAvailable); + System.out.println("Expected GL Caps: "+expGLCaps); + // + // Create native windowing resources .. X11/Win/OSX + // + final GLCanvas glad = new GLCanvas(reqGLCaps); // will implicit trigger offscreen layer - if !onscreen && supported + Assert.assertNotNull(glad); + Dimension glc_sz = new Dimension(widthStep*szStep, heightStep*szStep); + glad.setMinimumSize(glc_sz); + glad.setPreferredSize(glc_sz); + glad.setSize(glc_sz); + final Frame frame = new Frame(getSimpleTestName(".")); + Assert.assertNotNull(frame); + frame.add(glad); + + try { + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.pack(); + frame.setVisible(true); + }}); + } catch( Throwable throwable ) { + throwable.printStackTrace(); + Assume.assumeNoException( throwable ); + } + + Assert.assertTrue(AWTRobotUtil.waitForVisible(glad, true)); + Assert.assertTrue(AWTRobotUtil.waitForRealized(glad, true)); + System.out.println("Window: "+glad.getClass().getName()); + + // Check caps of NativeWindow config w/o GL + final CapabilitiesImmutable chosenCaps = glad.getChosenGLCapabilities(); + System.out.println("Window Caps Pre_GL: "+chosenCaps); + Assert.assertNotNull(chosenCaps); + Assert.assertTrue(chosenCaps.getGreenBits()>5); + Assert.assertTrue(chosenCaps.getBlueBits()>5); + Assert.assertTrue(chosenCaps.getRedBits()>5); + + glad.display(); // force native context creation + + // + // Create native OpenGL resources .. XGL/WGL/CGL .. + // equivalent to GLAutoDrawable methods: setVisible(true) + // + { + final GLDrawable actualDrawable = glad.getDelegatedDrawable(); + Assert.assertNotNull(actualDrawable); + System.out.println("Drawable Pre-GL(0): "+actualDrawable.getClass().getName()+", "+actualDrawable.getNativeSurface().getClass().getName()); + } + + System.out.println("Window Caps PostGL : "+glad.getChosenGLCapabilities()); + System.out.println("Drawable Post-GL(1): "+glad.getClass().getName()+", "+glad.getNativeSurface().getClass().getName()); + + // Check caps of GLDrawable after realization + final GLCapabilitiesImmutable chosenGLCaps = glad.getChosenGLCapabilities(); + System.out.println("Chosen GL Caps(1): "+chosenGLCaps); + Assert.assertNotNull(chosenGLCaps); + Assert.assertTrue(chosenGLCaps.getGreenBits()>5); + Assert.assertTrue(chosenGLCaps.getBlueBits()>5); + Assert.assertTrue(chosenGLCaps.getRedBits()>5); + Assert.assertTrue(chosenGLCaps.getDepthBits()>4); + Assert.assertEquals(expGLCaps.isOnscreen(), chosenGLCaps.isOnscreen()); + Assert.assertEquals(expGLCaps.isFBO(), chosenGLCaps.isFBO()); + Assert.assertEquals(expGLCaps.isPBuffer(), chosenGLCaps.isPBuffer()); + Assert.assertEquals(expGLCaps.isBitmap(), chosenGLCaps.isBitmap()); + /** Single/Double buffer cannot be checked since result may vary .. + if(chosenGLCaps.isOnscreen() || chosenGLCaps.isFBO()) { + // dbl buffer may be disabled w/ offscreen pbuffer and bitmap + Assert.assertEquals(expGLCaps.getDoubleBuffered(), chosenGLCaps.getDoubleBuffered()); + } */ + + { + GLContext context = glad.getContext(); + System.out.println("Chosen GL CTX (2): "+context.getGLVersion()); + Assert.assertNotNull(context); + Assert.assertTrue(context.isCreated()); + } + + System.out.println("Chosen GL Caps(2): "+glad.getChosenGLCapabilities()); + System.out.println("Drawable Post-GL(2): "+glad.getClass().getName()+", "+glad.getNativeSurface().getClass().getName()); + + glad.addGLEventListener(demo); + + final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); + glad.addGLEventListener(snapshotGLEventListener); + + glad.display(); // initial resize/display + + // 1 - szStep = 2 + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + // 2, 3 (resize + display) + szStep = 1; + setGLCanvasSize(frame, glad, widthStep*szStep, heightStep*szStep); + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + glad.display(); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + // 4, 5 (resize + display) + szStep = 4; + setGLCanvasSize(frame, glad, widthStep*szStep, heightStep*szStep); + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + glad.display(); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + Thread.sleep(50); + + try { + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setVisible(false); + frame.remove(glad); + frame.dispose(); + }}); + } catch( Throwable throwable ) { + throwable.printStackTrace(); + Assume.assumeNoException( throwable ); + } + System.out.println("Fin: "+glad); + } + + @Test + public void testAvailableInfo() { + GLDrawableFactory f = GLDrawableFactory.getDesktopFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + f = GLDrawableFactory.getEGLFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + } + + @Test + public void testGL2OnScreen() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenAuto() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBOMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenPbuffer() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OnScreen() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenAuto() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBOMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenPbuffer() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + + public static void main(String args[]) throws IOException { + org.junit.runner.JUnitCore.main(TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.class.getName()); + } + +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT.java new file mode 100644 index 000000000..37ec44566 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT.java @@ -0,0 +1,351 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.io.IOException; + +import javax.media.nativewindow.CapabilitiesImmutable; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLProfile; + +import jogamp.opengl.GLGraphicsConfigurationUtil; + +import org.junit.Assert; +import org.junit.Test; + +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.opengl.JoglVersion; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.UITestCase; + +/** + * Tests using a NEWT {@link GLWindow} {@link GLAutoDrawable auto drawable} for on- and offscreen cases. + *

      + * The NEWT {@link GLAutoDrawable} is being used to run the {@link GLEventListener}. + *

      + */ +public class TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT extends UITestCase { + static final int widthStep = 800/4; + static final int heightStep = 600/4; + volatile int szStep = 2; + + static interface MyGLEventListener extends GLEventListener { + void setMakeSnapshot(); + } + + static GLCapabilities getCaps(String profile) { + if( !GLProfile.isAvailable(profile) ) { + System.err.println("Profile "+profile+" n/a"); + return null; + } + return new GLCapabilities(GLProfile.get(profile)); + } + + void doTest(GLCapabilitiesImmutable reqGLCaps, GLEventListener demo) throws InterruptedException { + System.out.println("Requested GL Caps: "+reqGLCaps); + final GLDrawableFactory factory = GLDrawableFactory.getFactory(reqGLCaps.getGLProfile()); + + final boolean fboAvailable = factory.canCreateFBO(null, reqGLCaps.getGLProfile()); + final boolean pbufferAvailable = factory.canCreateGLPbuffer(null); + final GLCapabilitiesImmutable expGLCaps = GLGraphicsConfigurationUtil.fixGLCapabilities(reqGLCaps, fboAvailable, pbufferAvailable); + System.out.println("Expected GL Caps: "+expGLCaps); + // + // Create native windowing resources .. X11/Win/OSX + // + final GLWindow glad = GLWindow.create(reqGLCaps); + Assert.assertNotNull(glad); + glad.setSize(widthStep*szStep, heightStep*szStep); + glad.setVisible(true); + Assert.assertTrue(AWTRobotUtil.waitForVisible(glad, true)); + Assert.assertTrue(AWTRobotUtil.waitForRealized(glad, true)); + System.out.println("Window: "+glad.getClass().getName()); + + // Check caps of NativeWindow config w/o GL + final CapabilitiesImmutable chosenCaps = glad.getGraphicsConfiguration().getChosenCapabilities(); + System.out.println("Window Caps Pre_GL: "+chosenCaps); + Assert.assertNotNull(chosenCaps); + Assert.assertTrue(chosenCaps.getGreenBits()>5); + Assert.assertTrue(chosenCaps.getBlueBits()>5); + Assert.assertTrue(chosenCaps.getRedBits()>5); + + // + // Create native OpenGL resources .. XGL/WGL/CGL .. + // equivalent to GLAutoDrawable methods: setVisible(true) + // + { + final GLDrawable actualDrawable = glad.getDelegatedDrawable(); + Assert.assertNotNull(actualDrawable); + System.out.println("Drawable Pre-GL(0): "+actualDrawable.getClass().getName()+", "+actualDrawable.getNativeSurface().getClass().getName()); + } + + System.out.println("Window Caps PostGL : "+glad.getGraphicsConfiguration().getChosenCapabilities()); + System.out.println("Drawable Post-GL(1): "+glad.getClass().getName()+", "+glad.getNativeSurface().getClass().getName()); + + // Check caps of GLDrawable after realization + final GLCapabilitiesImmutable chosenGLCaps = glad.getChosenGLCapabilities(); + System.out.println("Chosen GL Caps(1): "+chosenGLCaps); + Assert.assertNotNull(chosenGLCaps); + Assert.assertTrue(chosenGLCaps.getGreenBits()>5); + Assert.assertTrue(chosenGLCaps.getBlueBits()>5); + Assert.assertTrue(chosenGLCaps.getRedBits()>5); + Assert.assertTrue(chosenGLCaps.getDepthBits()>4); + Assert.assertEquals(expGLCaps.isOnscreen(), chosenGLCaps.isOnscreen()); + Assert.assertEquals(expGLCaps.isFBO(), chosenGLCaps.isFBO()); + Assert.assertEquals(expGLCaps.isPBuffer(), chosenGLCaps.isPBuffer()); + Assert.assertEquals(expGLCaps.isBitmap(), chosenGLCaps.isBitmap()); + /** Single/Double buffer cannot be checked since result may vary .. + if(chosenGLCaps.isOnscreen() || chosenGLCaps.isFBO()) { + // dbl buffer may be disabled w/ offscreen pbuffer and bitmap + Assert.assertEquals(expGLCaps.getDoubleBuffered(), chosenGLCaps.getDoubleBuffered()); + } */ + + glad.display(); + { + GLContext context = glad.getContext(); + System.out.println("Chosen GL CTX (2): "+context.getGLVersion()); + Assert.assertNotNull(context); + Assert.assertTrue(context.isCreated()); + } + + System.out.println("Chosen GL Caps(2): "+glad.getChosenGLCapabilities()); + System.out.println("Drawable Post-GL(2): "+glad.getClass().getName()+", "+glad.getNativeSurface().getClass().getName()); + + glad.addGLEventListener(demo); + + final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); + glad.addGLEventListener(snapshotGLEventListener); + + glad.display(); // initial resize/display + + // 1 - szStep = 2 + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + // 2, 3 (resize + display) + szStep = 1; + glad.setSize(widthStep*szStep, heightStep*szStep); + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + // 4, 5 (resize + display) + szStep = 4; + glad.setSize(widthStep*szStep, heightStep*szStep); + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + Thread.sleep(50); + + glad.destroy(); + System.out.println("Fin: "+glad); + } + + @Test + public void testAvailableInfo() { + GLDrawableFactory f = GLDrawableFactory.getDesktopFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + f = GLDrawableFactory.getEGLFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + } + + @Test + public void testGL2OnScreenDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OnScreenSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenAutoDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBODblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBOSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenPbufferDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenPbufferSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenBitmapDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setBitmap(true); + doTest(reqGLCaps, new Gears(1)); + } + + @Test + public void testGL2OffScreenBitmapSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setBitmap(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new Gears(1)); + } + + @Test + public void testES2OnScreenDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OnScreenSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenAutoDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBODblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBOSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenPbufferDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenPbufferSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setPBuffer(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + /** Not implemented ! + @Test + public void testES2OffScreenBitmapDblBuf() throws InterruptedException { + if(!checkProfile(GLProfile.GLES2)) { + return; + } + final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); + reqGLCaps.setOnscreen(false); + reqGLCaps.setBitmap(true); + doTest(reqGLCaps, new GearsES2(1)); + } */ + + public static void main(String args[]) throws IOException { + org.junit.runner.JUnitCore.main(TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT.class.getName()); + } + +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT.java new file mode 100644 index 000000000..47fc99844 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT.java @@ -0,0 +1,300 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Frame; +import java.io.IOException; + +import javax.media.nativewindow.CapabilitiesImmutable; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLProfile; + +import jogamp.nativewindow.jawt.JAWTUtil; +import jogamp.opengl.GLGraphicsConfigurationUtil; + +import org.junit.Assert; +import org.junit.Assume; +import org.junit.Test; + +import com.jogamp.newt.awt.NewtCanvasAWT; +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.opengl.JoglVersion; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.UITestCase; + +/** + * Tests using a NEWT {@link GLWindow} {@link GLAutoDrawable auto drawable} for on- and offscreen cases. + *

      + * The NEWT {@link GLAutoDrawable} is being used to run the {@link GLEventListener}. + *

      + */ +public class TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT extends UITestCase { + static final int widthStep = 800/4; + static final int heightStep = 600/4; + volatile int szStep = 2; + + static GLCapabilities getCaps(String profile) { + if( !GLProfile.isAvailable(profile) ) { + System.err.println("Profile "+profile+" n/a"); + return null; + } + return new GLCapabilities(GLProfile.get(profile)); + } + + static void setComponentSize(final Frame frame, final Component comp, final int width, final int height) { + try { + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + final Dimension new_sz = new Dimension(width, height); + comp.setMinimumSize(new_sz); + comp.setPreferredSize(new_sz); + comp.setSize(new_sz); + frame.pack(); + frame.validate(); + } } ); + } catch( Throwable throwable ) { + throwable.printStackTrace(); + Assume.assumeNoException( throwable ); + } + } + + static interface MyGLEventListener extends GLEventListener { + void setMakeSnapshot(); + } + + void doTest(boolean offscreenLayer, GLCapabilitiesImmutable reqGLCaps, GLEventListener demo) throws InterruptedException { + if(!offscreenLayer && JAWTUtil.isOffscreenLayerRequired()) { + System.err.println("onscreen layer n/a"); + return; + } + if(offscreenLayer && !JAWTUtil.isOffscreenLayerSupported()) { + System.err.println("offscreen layer n/a"); + return; + } + System.out.println("Requested GL Caps: "+reqGLCaps); + final GLDrawableFactory factory = GLDrawableFactory.getFactory(reqGLCaps.getGLProfile()); + + final boolean fboAvailable = factory.canCreateFBO(null, reqGLCaps.getGLProfile()); + final boolean pbufferAvailable = factory.canCreateGLPbuffer(null); + final GLCapabilitiesImmutable expGLCaps = offscreenLayer ? + GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(reqGLCaps, fboAvailable, pbufferAvailable) : + GLGraphicsConfigurationUtil.fixGLCapabilities(reqGLCaps, fboAvailable, pbufferAvailable); + System.out.println("Expected GL Caps: "+expGLCaps); + + final GLWindow glad = GLWindow.create(reqGLCaps); + Assert.assertNotNull(glad); + + + final NewtCanvasAWT nca = new NewtCanvasAWT(glad); + Assert.assertNotNull(nca); + Dimension size0 = new Dimension(widthStep*szStep, heightStep*szStep); + nca.setShallUseOffscreenLayer(offscreenLayer); // trigger offscreen layer - if supported + nca.setPreferredSize(size0); + nca.setMinimumSize(size0); + nca.setSize(size0); + + final Frame frame = new Frame(getSimpleTestName(".")); + Assert.assertNotNull(frame); + frame.add(nca); + + try { + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.pack(); + frame.setVisible(true); + }}); + } catch( Throwable throwable ) { + throwable.printStackTrace(); + Assume.assumeNoException( throwable ); + } + + Assert.assertTrue(AWTRobotUtil.waitForVisible(glad, true)); + Assert.assertTrue(AWTRobotUtil.waitForRealized(glad, true)); + System.out.println("Window: "+glad.getClass().getName()); + + // Check caps of NativeWindow config w/o GL + final CapabilitiesImmutable chosenCaps = glad.getChosenGLCapabilities(); + System.out.println("Window Caps Pre_GL: "+chosenCaps); + Assert.assertNotNull(chosenCaps); + Assert.assertTrue(chosenCaps.getGreenBits()>5); + Assert.assertTrue(chosenCaps.getBlueBits()>5); + Assert.assertTrue(chosenCaps.getRedBits()>5); + + glad.display(); // force native context creation + + // + // Create native OpenGL resources .. XGL/WGL/CGL .. + // equivalent to GLAutoDrawable methods: setVisible(true) + // + { + final GLDrawable actualDrawable = glad.getDelegatedDrawable(); + Assert.assertNotNull(actualDrawable); + System.out.println("Drawable Pre-GL(0): "+actualDrawable.getClass().getName()+", "+actualDrawable.getNativeSurface().getClass().getName()); + } + + System.out.println("Window Caps PostGL : "+glad.getChosenGLCapabilities()); + System.out.println("Drawable Post-GL(1): "+glad.getClass().getName()+", "+glad.getNativeSurface().getClass().getName()); + + // Check caps of GLDrawable after realization + final GLCapabilitiesImmutable chosenGLCaps = glad.getChosenGLCapabilities(); + System.out.println("Chosen GL Caps(1): "+chosenGLCaps); + Assert.assertNotNull(chosenGLCaps); + Assert.assertTrue(chosenGLCaps.getGreenBits()>5); + Assert.assertTrue(chosenGLCaps.getBlueBits()>5); + Assert.assertTrue(chosenGLCaps.getRedBits()>5); + Assert.assertTrue(chosenGLCaps.getDepthBits()>4); + Assert.assertEquals(expGLCaps.isOnscreen(), chosenGLCaps.isOnscreen()); + Assert.assertEquals(expGLCaps.isFBO(), chosenGLCaps.isFBO()); + Assert.assertEquals(expGLCaps.isPBuffer(), chosenGLCaps.isPBuffer()); + Assert.assertEquals(expGLCaps.isBitmap(), chosenGLCaps.isBitmap()); + /** Single/Double buffer cannot be checked since result may vary .. + if(chosenGLCaps.isOnscreen() || chosenGLCaps.isFBO()) { + // dbl buffer may be disabled w/ offscreen pbuffer and bitmap + Assert.assertEquals(expGLCaps.getDoubleBuffered(), chosenGLCaps.getDoubleBuffered()); + } */ + + { + GLContext context = glad.getContext(); + System.out.println("Chosen GL CTX (2): "+context.getGLVersion()); + Assert.assertNotNull(context); + Assert.assertTrue(context.isCreated()); + } + + System.out.println("Chosen GL Caps(2): "+glad.getChosenGLCapabilities()); + System.out.println("Drawable Post-GL(2): "+glad.getClass().getName()+", "+glad.getNativeSurface().getClass().getName()); + + glad.addGLEventListener(demo); + + final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); + glad.addGLEventListener(snapshotGLEventListener); + + glad.display(); // initial resize/display + + // 1 - szStep = 2 + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + // 2, 3 (resize + display) + szStep = 1; + setComponentSize(frame, nca, widthStep*szStep, heightStep*szStep); + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + glad.display(); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + // 4, 5 (resize + display) + szStep = 4; + setComponentSize(frame, nca, widthStep*szStep, heightStep*szStep); + Assert.assertTrue("Size not reached: Expected "+(widthStep*szStep)+"x"+(heightStep*szStep)+", Is "+glad.getWidth()+"x"+glad.getHeight(), + AWTRobotUtil.waitForSize(glad, widthStep*szStep, heightStep*szStep)); + glad.display(); + snapshotGLEventListener.setMakeSnapshot(); + glad.display(); + + Thread.sleep(50); + + try { + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setVisible(false); + frame.remove(nca); + frame.dispose(); + }}); + } catch( Throwable throwable ) { + throwable.printStackTrace(); + Assume.assumeNoException( throwable ); + } + glad.destroy(); + System.out.println("Fin: "+nca); + System.out.println("Fin: "+glad); + } + + @Test + public void testAvailableInfo() { + GLDrawableFactory f = GLDrawableFactory.getDesktopFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + f = GLDrawableFactory.getEGLFactory(); + if(null != f) { + System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); + } + } + + @Test + public void testGL2OnScreenDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + doTest(false, reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenLayerAuto() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + doTest(true, reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBOMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setFBO(true); + reqGLCaps.setOnscreen(true); // get native NEWT Window, not OffscreenWindow + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(true, reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenPbuffer() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setPBuffer(true); + reqGLCaps.setOnscreen(true); // get native NEWT Window, not OffscreenWindow + doTest(true, reqGLCaps, new GearsES2(1)); + } + + public static void main(String args[]) throws IOException { + org.junit.runner.JUnitCore.main(TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT.class.getName()); + } + +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java deleted file mode 100644 index cd1107e25..000000000 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLCapabilities01NEWT.java +++ /dev/null @@ -1,266 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package com.jogamp.opengl.test.junit.jogl.acore; - -import java.io.IOException; - -import javax.media.nativewindow.CapabilitiesImmutable; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLCapabilitiesImmutable; -import javax.media.opengl.GLContext; -import javax.media.opengl.GLDrawable; -import javax.media.opengl.GLDrawableFactory; -import javax.media.opengl.GLEventListener; -import javax.media.opengl.GLProfile; - -import jogamp.opengl.GLGraphicsConfigurationUtil; - -import org.junit.Assert; -import org.junit.Test; - -import com.jogamp.newt.NewtFactory; -import com.jogamp.newt.Window; -import com.jogamp.opengl.JoglVersion; -import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; -import com.jogamp.opengl.test.junit.util.AWTRobotUtil; -import com.jogamp.opengl.test.junit.util.UITestCase; - -public class TestGLCapabilities01NEWT extends UITestCase { - static final int width = 100; - static final int height = 100; - - boolean checkProfile(String profile) { - if( !GLProfile.isAvailable(profile) ) { - System.err.println("Profile "+profile+" n/a"); - return false; - } - return true; - } - - void doTest(GLCapabilitiesImmutable reqGLCaps, GLEventListener demo) throws InterruptedException { - System.out.println("Requested GL Caps: "+reqGLCaps); - - final GLCapabilitiesImmutable expGLCaps; - if( GLGraphicsConfigurationUtil.isGLCapabilitiesOffscreenAutoSelection(reqGLCaps) ) { - final GLDrawableFactory f = GLDrawableFactory.getFactory(reqGLCaps.getGLProfile()); - final boolean fboAvailable = true ; // f.canCreateFBO(null, reqGLCaps.getGLProfile()); - final boolean pbufferAvailable = f.canCreateGLPbuffer(null); - expGLCaps = GLGraphicsConfigurationUtil.fixGLCapabilities(reqGLCaps, fboAvailable, pbufferAvailable); - } else { - expGLCaps = reqGLCaps; - } - System.out.println("Expected GL Caps: "+expGLCaps); - // - // Create native windowing resources .. X11/Win/OSX - // - final Window window = NewtFactory.createWindow(reqGLCaps); - Assert.assertNotNull(window); - window.setSize(width, height); - window.setVisible(true); - Assert.assertTrue(AWTRobotUtil.waitForVisible(window, true)); - Assert.assertTrue(AWTRobotUtil.waitForRealized(window, true)); - System.out.println("Window: "+window.getClass().getName()); - - // Check caps of NativeWindow config w/o GL - final CapabilitiesImmutable chosenCaps = window.getGraphicsConfiguration().getChosenCapabilities(); - System.out.println("Window Caps Pre_GL: "+chosenCaps); - Assert.assertNotNull(chosenCaps); - Assert.assertTrue(chosenCaps.getGreenBits()>5); - Assert.assertTrue(chosenCaps.getBlueBits()>5); - Assert.assertTrue(chosenCaps.getRedBits()>5); - - // - // Create native OpenGL resources .. XGL/WGL/CGL .. - // equivalent to GLAutoDrawable methods: setVisible(true) - // - final GLDrawableFactory factory = GLDrawableFactory.getFactory(reqGLCaps.getGLProfile()); - - final GLDrawable drawable = factory.createGLDrawable(window); - Assert.assertNotNull(drawable); - System.out.println("Drawable Pre-GL(0): "+drawable.getClass().getName()+", "+drawable.getNativeSurface().getClass().getName()); - - // - drawable.setRealized(true); - Assert.assertTrue(drawable.isRealized()); - - System.out.println("Window Caps PostGL : "+window.getGraphicsConfiguration().getChosenCapabilities()); - System.out.println("Drawable Post-GL(1): "+drawable.getClass().getName()+", "+drawable.getNativeSurface().getClass().getName()); - - // Check caps of GLDrawable after realization - final GLCapabilitiesImmutable chosenGLCaps = drawable.getChosenGLCapabilities(); - System.out.println("Chosen GL Caps(1): "+chosenGLCaps); - Assert.assertNotNull(chosenGLCaps); - Assert.assertTrue(chosenGLCaps.getGreenBits()>5); - Assert.assertTrue(chosenGLCaps.getBlueBits()>5); - Assert.assertTrue(chosenGLCaps.getRedBits()>5); - Assert.assertTrue(chosenGLCaps.getDepthBits()>4); - Assert.assertEquals(expGLCaps.isOnscreen(), chosenGLCaps.isOnscreen()); - Assert.assertEquals(expGLCaps.isFBO(), chosenGLCaps.isFBO()); - Assert.assertEquals(expGLCaps.isPBuffer(), chosenGLCaps.isPBuffer()); - Assert.assertEquals(expGLCaps.isBitmap(), chosenGLCaps.isBitmap()); - if(chosenGLCaps.isOnscreen() || chosenGLCaps.isFBO()) { - // dbl buffer may be disabled w/ offscreen pbuffer and bitmap - Assert.assertEquals(expGLCaps.getDoubleBuffered(), chosenGLCaps.getDoubleBuffered()); - } - - GLContext context = drawable.createContext(null); - Assert.assertNotNull(context); - int res = context.makeCurrent(); - Assert.assertTrue(GLContext.CONTEXT_CURRENT_NEW==res || GLContext.CONTEXT_CURRENT==res); - context.release(); - - System.out.println("Chosen GL Caps(2): "+drawable.getChosenGLCapabilities()); - System.out.println("Drawable Post-GL(2): "+drawable.getClass().getName()+", "+drawable.getNativeSurface().getClass().getName()); - - drawable.setRealized(false); - window.destroy(); - } - - @Test - public void testAvailableInfo() { - GLDrawableFactory f = GLDrawableFactory.getDesktopFactory(); - if(null != f) { - System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); - } - f = GLDrawableFactory.getEGLFactory(); - if(null != f) { - System.err.println(JoglVersion.getDefaultOpenGLInfo(f.getDefaultDevice(), null, true).toString()); - } - } - - @Test - public void testGL2OnScreenDblBuf() throws InterruptedException { - if(!checkProfile(GLProfile.GL2)) { - return; - } - final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); - doTest(reqGLCaps, new GearsES2(1)); - } - - @Test - public void testGL2OffScreenAutoDblBuf() throws InterruptedException { - if(!checkProfile(GLProfile.GL2)) { - return; - } - final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); - reqGLCaps.setOnscreen(false); - doTest(reqGLCaps, new GearsES2(1)); - } - - @Test - public void testGL2OffScreenFBODblBuf() throws InterruptedException { - if(!checkProfile(GLProfile.GL2)) { - return; - } - final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); - reqGLCaps.setOnscreen(false); - reqGLCaps.setFBO(true); - doTest(reqGLCaps, new GearsES2(1)); - } - - @Test - public void testGL2OffScreenPbufferDblBuf() throws InterruptedException { - if(!checkProfile(GLProfile.GL2)) { - return; - } - final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); - reqGLCaps.setOnscreen(false); - reqGLCaps.setPBuffer(true); - doTest(reqGLCaps, new GearsES2(1)); - } - - @Test - public void testGL2OffScreenBitmapDblBuf() throws InterruptedException { - if(!checkProfile(GLProfile.GL2)) { - return; - } - final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GL2)); - reqGLCaps.setOnscreen(false); - reqGLCaps.setBitmap(true); - doTest(reqGLCaps, new GearsES2(1)); - } - - @Test - public void testES2OnScreenDblBuf() throws InterruptedException { - if(!checkProfile(GLProfile.GLES2)) { - return; - } - final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); - doTest(reqGLCaps, new GearsES2(1)); - } - - @Test - public void testES2OffScreenAutoDblBuf() throws InterruptedException { - if(!checkProfile(GLProfile.GLES2)) { - return; - } - final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); - reqGLCaps.setOnscreen(false); - doTest(reqGLCaps, new GearsES2(1)); - } - - @Test - public void testES2OffScreenFBODblBuf() throws InterruptedException { - if(!checkProfile(GLProfile.GLES2)) { - return; - } - final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); - reqGLCaps.setOnscreen(false); - reqGLCaps.setFBO(true); - doTest(reqGLCaps, new GearsES2(1)); - } - - @Test - public void testES2OffScreenPbufferDblBuf() throws InterruptedException { - if(!checkProfile(GLProfile.GLES2)) { - return; - } - final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); - reqGLCaps.setOnscreen(false); - reqGLCaps.setPBuffer(true); - doTest(reqGLCaps, new GearsES2(1)); - } - - /** Not implemented ! - @Test - public void testES2OffScreenBitmapDblBuf() throws InterruptedException { - if(!checkProfile(GLProfile.GLES2)) { - return; - } - final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); - reqGLCaps.setOnscreen(false); - reqGLCaps.setBitmap(true); - doTest(reqGLCaps, new GearsES2(1)); - } */ - - public static void main(String args[]) throws IOException { - org.junit.runner.JUnitCore.main(TestGLCapabilities01NEWT.class.getName()); - } - -} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitchNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitchNEWT.java index cece4c6d5..4c1130498 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitchNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitchNEWT.java @@ -39,13 +39,14 @@ import com.jogamp.newt.event.WindowUpdateEvent; import com.jogamp.newt.opengl.GLWindow; import javax.media.opengl.GLAutoDrawable; -import javax.media.opengl.GLAutoDrawableDelegate; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; + +import com.jogamp.opengl.GLAutoDrawableDelegate; import com.jogamp.opengl.util.Animator; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; @@ -81,14 +82,17 @@ public class TestGLContextDrawableSwitchNEWT extends UITestCase { Assert.assertTrue(AWTRobotUtil.waitForVisible(window, true)); Assert.assertTrue(AWTRobotUtil.waitForRealized(window, true)); - GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); - GLDrawable drawable = factory.createGLDrawable(window); + final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); + final GLDrawable drawable = factory.createGLDrawable(window); Assert.assertNotNull(drawable); drawable.setRealized(true); Assert.assertTrue(drawable.isRealized()); - final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(drawable, null, window, false) { + final GLContext context = drawable.createContext(null); + Assert.assertNotNull(context); + + final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(drawable, context, window, false, null) { @Override protected void destroyImplInLock() { super.destroyImplInLock(); @@ -104,7 +108,7 @@ public class TestGLContextDrawableSwitchNEWT extends UITestCase { } @Override public void windowResized(WindowEvent e) { - glad.windowResizedOp(); + glad.windowResizedOp(window.getWidth(), window.getHeight()); } @Override public void windowDestroyNotify(WindowEvent e) { @@ -123,9 +127,13 @@ public class TestGLContextDrawableSwitchNEWT extends UITestCase { GLAutoDrawable glad1 = createGLAutoDrawable(caps, 64, 64, width, height, quitAdapter); // no GLContext! GLAutoDrawable glad2 = createGLAutoDrawable(caps, 2*64+width, 64, width+100, height+100, quitAdapter); // no GLContext! - // create single context using glad1 and assign it to glad1 + // create single context using glad1 and assign it to glad1, + // after destroying the prev. context! { - GLContext singleCtx = glad1.createContext(null); + final GLContext oldCtx = glad1.getContext(); + Assert.assertNotNull(oldCtx); + oldCtx.destroy(); + final GLContext singleCtx = glad1.createContext(null); Assert.assertNotNull(singleCtx); int res = singleCtx.makeCurrent(); Assert.assertTrue(GLContext.CONTEXT_CURRENT_NEW==res || GLContext.CONTEXT_CURRENT==res); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLDrawable01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLDrawable01NEWT.java deleted file mode 100644 index a6e9cfb07..000000000 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLDrawable01NEWT.java +++ /dev/null @@ -1,171 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package com.jogamp.opengl.test.junit.jogl.acore; - -import java.io.IOException; - -import javax.media.nativewindow.CapabilitiesImmutable; -import javax.media.opengl.GL; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLCapabilitiesImmutable; -import javax.media.opengl.GLContext; -import javax.media.opengl.GLDrawable; -import javax.media.opengl.GLDrawableFactory; -import javax.media.opengl.GLProfile; - -import org.junit.Assert; -import org.junit.Test; - -import com.jogamp.newt.NewtFactory; -import com.jogamp.newt.Window; -import com.jogamp.opengl.test.junit.util.AWTRobotUtil; -import com.jogamp.opengl.test.junit.util.UITestCase; - -public class TestGLDrawable01NEWT extends UITestCase { - static final int width = 200, height = 200; - - void doTest(String profile, boolean onscreen, boolean fbo, boolean pbuffer) throws InterruptedException { - if( !GLProfile.isAvailable(profile) ) { - System.err.println("Profile "+profile+" n/a"); - return; - } - - final GLProfile glp = GLProfile.get(profile); - final GLCapabilities reqGLCaps = new GLCapabilities(glp); - - reqGLCaps.setOnscreen(onscreen); - reqGLCaps.setPBuffer(!onscreen && pbuffer); - reqGLCaps.setFBO(!onscreen && fbo); - reqGLCaps.setDoubleBuffered(onscreen); - // System.out.println("Requested: "+caps); - - // - // Create native windowing resources .. X11/Win/OSX - // - Window window = NewtFactory.createWindow(reqGLCaps); - Assert.assertNotNull(window); - window.setSize(width, height); - window.setVisible(true); - AWTRobotUtil.waitForVisible(window, true); - AWTRobotUtil.waitForRealized(window, true); - // System.out.println("Created: "+window); - - // Check caps of NativeWindow config w/o GL - final CapabilitiesImmutable chosenCaps = window.getGraphicsConfiguration().getChosenCapabilities(); - Assert.assertNotNull(chosenCaps); - Assert.assertTrue(chosenCaps.getGreenBits()>5); - Assert.assertTrue(chosenCaps.getBlueBits()>5); - Assert.assertTrue(chosenCaps.getRedBits()>5); - - // - // Create native OpenGL resources .. XGL/WGL/CGL .. - // equivalent to GLAutoDrawable methods: setVisible(true) - // - final GLDrawableFactory factory = GLDrawableFactory.getFactory(glp); - - final GLDrawable drawable = factory.createGLDrawable(window); - Assert.assertNotNull(drawable); - // System.out.println("Pre: "+drawable); - // - drawable.setRealized(true); - Assert.assertTrue(drawable.isRealized()); - - // Check caps of GLDrawable after realization - final GLCapabilitiesImmutable chosenGLCaps = drawable.getChosenGLCapabilities(); - Assert.assertNotNull(chosenGLCaps); - Assert.assertTrue(chosenGLCaps.getGreenBits()>5); - Assert.assertTrue(chosenGLCaps.getBlueBits()>5); - Assert.assertTrue(chosenGLCaps.getRedBits()>5); - Assert.assertTrue(chosenGLCaps.getDepthBits()>4); - Assert.assertEquals(reqGLCaps.isOnscreen(), chosenGLCaps.isOnscreen()); - Assert.assertEquals(reqGLCaps.isOnscreen(), chosenGLCaps.getDoubleBuffered()); // offscreen shall be !dbl-buffer - // System.out.println("Post: "+drawable); - - GLContext context = drawable.createContext(null); - Assert.assertNotNull(context); - // System.out.println(context); - - int res = context.makeCurrent(); - Assert.assertTrue(GLContext.CONTEXT_CURRENT_NEW==res || GLContext.CONTEXT_CURRENT==res); - - // draw something .. - final GL gl = context.getGL(); - gl.glClearColor(1, 1, 1, 1); - gl.glEnable(GL.GL_DEPTH_TEST); - Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); - gl.glViewport(0, 0, width, height); - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError()); - - drawable.swapBuffers(); - context.release(); - - Thread.sleep(50); - - context.destroy(); - drawable.setRealized(false); - window.destroy(); - // System.out.println("Final: "+window); - } - - @Test - public void testGL2OnScreen() throws InterruptedException { - doTest(GLProfile.GL2, true, false, false); - } - - @Test - public void testES2OnScreen() throws InterruptedException { - doTest(GLProfile.GLES2, true, false, false); - } - - @Test - public void testGL2PBuffer() throws InterruptedException { - doTest(GLProfile.GL2, false, false, true); - } - - @Test - public void testES2PBuffer() throws InterruptedException { - doTest(GLProfile.GLES2, false, false, true); - } - - // @Test // TODO: FBO-Drawable via createGLDrawable and pre-exisiting NativeSurface - public void testGL2FBO() throws InterruptedException { - doTest(GLProfile.GL2, false, true, false); - } - - // @Test // TODO: FBO-Drawable via createGLDrawable and pre-exisiting NativeSurface - public void testES2FBO() throws InterruptedException { - doTest(GLProfile.GLES2, false, true, false); - } - - public static void main(String args[]) throws IOException { - org.junit.runner.JUnitCore.main(TestGLDrawable01NEWT.class.getName()); - } - -} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLExtensionQueryOffscreen.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLExtensionQueryOffscreen.java index e4245ef11..d4f3fece5 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLExtensionQueryOffscreen.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLExtensionQueryOffscreen.java @@ -32,14 +32,11 @@ import java.util.Collections; import java.util.SortedSet; import java.util.TreeSet; -import javax.media.nativewindow.AbstractGraphicsDevice; -import javax.media.opengl.DefaultGLCapabilitiesChooser; import javax.media.opengl.GL; -import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLOffscreenAutoDrawable; import javax.media.opengl.GLProfile; import jogamp.opengl.GLDrawableFactoryImpl; @@ -77,13 +74,11 @@ public class TestGLExtensionQueryOffscreen { @Test public void testJogl2ExtensionCheck2() { - GLCapabilities caps = new GLCapabilities(GLProfile.getDefault()); - GLDrawableFactory factory = GLDrawableFactory.getDesktopFactory(); - GLCapabilitiesChooser glCapsChooser = new DefaultGLCapabilitiesChooser(); - AbstractGraphicsDevice agd = factory.getDefaultDevice(); + final GLCapabilities caps = new GLCapabilities(GLProfile.getDefault()); + final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); + final GLOffscreenAutoDrawable drawable = factory.createOffscreenAutoDrawable(null, caps, null, 256, 256, null); - GLAutoDrawable drawable = factory.createGLPbuffer(agd, caps, glCapsChooser, 256, 256, null); - GLContext context = drawable.getContext(); + final GLContext context = drawable.getContext(); context.makeCurrent(); String extensions; try { @@ -94,8 +89,8 @@ public class TestGLExtensionQueryOffscreen { String[] tabExtensions = extensions.split(" "); SortedSet setExtensions = new TreeSet(); Collections.addAll(setExtensions, tabExtensions); - System.out.println("DefaulContext: "+context); - System.out.println("DefaulContext: "+setExtensions); + System.out.println("DefaultContext: "+context); + System.out.println("DefaultContext: "+setExtensions); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNEWTCloseX11DisplayBug565.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNEWTCloseX11DisplayBug565.java index 33a9b7799..c1b7464e7 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNEWTCloseX11DisplayBug565.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNEWTCloseX11DisplayBug565.java @@ -11,12 +11,14 @@ import javax.media.opengl.DefaultGLCapabilitiesChooser; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLOffscreenAutoDrawable; import javax.media.opengl.GLPbuffer; import javax.media.opengl.GLProfile; /** * Tests the closing the device of GLWindow and GLPBuffer in JOGL */ +@SuppressWarnings("deprecation") public class TestNEWTCloseX11DisplayBug565 { @Test @@ -59,7 +61,7 @@ public class TestNEWTCloseX11DisplayBug565 { @Test - public void testX11WindowMemoryLeakOffscreenWindow() throws Exception { + public void testX11WindowMemoryLeakGLPbuffer() throws Exception { GLProfile.initSingleton(); // ensure shared resource runner is done try { for ( int j = 0; j < 10; j++ ) { @@ -100,6 +102,48 @@ public class TestNEWTCloseX11DisplayBug565 { } } + @Test + public void testX11WindowMemoryLeakFBOAutoDrawable() throws Exception { + GLProfile.initSingleton(); // ensure shared resource runner is done + try { + for ( int j = 0; j < 10; j++ ) { + final int open0; + if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false)) { + open0 = X11Util.getOpenDisplayConnectionNumber(); + } else { + open0 = 0; + } + final GLProfile glp = GLProfile.getDefault( ); + GLCapabilitiesImmutable caps = new GLCapabilities( glp ); + + + GLOffscreenAutoDrawable buffer = GLDrawableFactory.getFactory( glp ).createOffscreenAutoDrawable( + null, + caps, + new DefaultGLCapabilitiesChooser(), + 256, + 256, + null + ); + buffer.display(); + buffer.destroy(); + + if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false)) { + final int openD = X11Util.getOpenDisplayConnectionNumber() - open0; + if(openD > 0) { + X11Util.dumpOpenDisplayConnections(); + X11Util.dumpPendingDisplayConnections(); + Assert.assertEquals("New display connection didn't close", 0, openD); + } + } + } + } + catch ( Exception e ) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + } + public static void main(String args[]) { org.junit.runner.JUnitCore.main(TestNEWTCloseX11DisplayBug565.class.getName()); } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java new file mode 100644 index 000000000..d181800c5 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java @@ -0,0 +1,236 @@ +/** + * Copyright 2011 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Frame; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; + +import javax.media.opengl.GLAnimatorControl; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.awt.GLCanvas; + +import jogamp.nativewindow.jawt.JAWTUtil; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.jogamp.common.os.Platform; +import com.jogamp.newt.Window; +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.MiscUtils; +import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.util.Animator; + +public class TestOffscreenLayer01GLCanvasAWT extends UITestCase { + static boolean useMSAA = false; + static boolean addComp = true; + static int swapInterval = 1; + static boolean shallUseOffscreenPBufferLayer = false; + static boolean noAnimation = false; + static Dimension frameSize0; + static Dimension frameSize1; + static Dimension preferredGLSize; + static long durationPerTest = 1000; + + @BeforeClass + public static void initClass() { + frameSize0 = new Dimension(500,300); + frameSize1 = new Dimension(800,600); + preferredGLSize = new Dimension(400,200); + } + + private void setupFrameAndShow(final Frame f, java.awt.Component comp) throws InterruptedException, InvocationTargetException { + + Container c = new Container(); + c.setLayout(new BorderLayout()); + c.add(new Button("north"), BorderLayout.NORTH); + c.add(new Button("south"), BorderLayout.SOUTH); + c.add(new Button("east"), BorderLayout.EAST); + c.add(new Button("west"), BorderLayout.WEST); + c.add(comp, BorderLayout.CENTER); + + f.setLayout(new BorderLayout()); + f.add(new Button("NORTH"), BorderLayout.NORTH); + f.add(new Button("SOUTH"), BorderLayout.SOUTH); + f.add(new Button("EAST"), BorderLayout.EAST); + f.add(new Button("WEST"), BorderLayout.WEST); + f.add(c, BorderLayout.CENTER); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + f.pack(); + f.validate(); + f.setVisible(true); + }}); + } + + private void end(GLAnimatorControl actrl, final Frame f, Window w) throws InterruptedException, InvocationTargetException { + actrl.stop(); + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + f.dispose(); + } } ); + if(null != w) { + w.destroy(); + } + } + + @Test + public void testInfo00() throws InterruptedException, InvocationTargetException { + System.err.println("Java Version: "+Platform.getJavaVersionNumber()); + System.err.println("OS Version: "+Platform.getOSVersionNumber()); + System.err.println("JAWTUtil.isOffscreenLayerRequired(): "+JAWTUtil.isOffscreenLayerRequired()); + System.err.println("JAWTUtil.isOffscreenLayerSupported(): "+JAWTUtil.isOffscreenLayerSupported()); + } + + @Test + public void testOffscreenLayerGLCanvas_OffscreenLayerWithOnscreenClass() throws InterruptedException, InvocationTargetException { + testOffscreenLayerGLCanvas_Impl(true); + } + + private void testOffscreenLayerGLCanvas_Impl(boolean offscreenLayer) throws InterruptedException, InvocationTargetException { + if(!offscreenLayer && JAWTUtil.isOffscreenLayerRequired()) { + System.err.println("onscreen layer n/a"); + return; + } + if(offscreenLayer && !JAWTUtil.isOffscreenLayerSupported()) { + System.err.println("offscreen layer n/a"); + return; + } + final Frame frame1 = new Frame("AWT Parent Frame"); + + GLCapabilities caps = new GLCapabilities(null); + if(useMSAA) { + caps.setNumSamples(4); + caps.setSampleBuffers(true); + } + if(shallUseOffscreenPBufferLayer) { + caps.setPBuffer(true); + caps.setOnscreen(true); // simulate normal behavior .. + } + final GLCanvas glc = new GLCanvas(caps); + glc.setShallUseOffscreenLayer(offscreenLayer); // trigger offscreen layer - if supported + glc.setPreferredSize(preferredGLSize); + glc.setMinimumSize(preferredGLSize); + glc.setSize(preferredGLSize); + + GearsES2 demo1 = new GearsES2(swapInterval); + if(noAnimation) { + demo1.setDoRotation(false); + } + glc.addGLEventListener(demo1); + + frame1.setSize(frameSize0); + setupFrameAndShow(frame1, glc); + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glc, true)); + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(glc, true)); + Assert.assertEquals(JAWTUtil.isOffscreenLayerSupported() && offscreenLayer, + glc.isOffscreenLayerSurfaceEnabled()); + + GLAnimatorControl animator1 = new Animator(glc); + if(!noAnimation) { + animator1.start(); + } + animator1.setUpdateFPSFrames(60, System.err); + + Thread.sleep(durationPerTest/2); + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame1.setSize(frameSize1); + frame1.pack(); + frame1.validate(); + }}); + + Thread.sleep(durationPerTest/2); + + end(animator1, frame1, null); + } + + public static void setDemoFields(GLEventListener demo, GLWindow glWindow, boolean debug) { + Assert.assertNotNull(demo); + Assert.assertNotNull(glWindow); + Window window = glWindow.getDelegatedWindow(); + if(debug) { + MiscUtils.setFieldIfExists(demo, "glDebug", true); + MiscUtils.setFieldIfExists(demo, "glTrace", true); + } + if(!MiscUtils.setFieldIfExists(demo, "window", window)) { + MiscUtils.setFieldIfExists(demo, "glWindow", glWindow); + } + } + + static int atoi(String a) { + int i=0; + try { + i = Integer.parseInt(a); + } catch (Exception ex) { ex.printStackTrace(); } + return i; + } + + public static void main(String args[]) throws IOException { + for(int i=0; i + * {@link JFrame} . {@link Container}+ . {@link NewtCanvasAWT} . {@link GLWindow} + *

      + *

      + * + Container is the JFrame's implicit root content pane
      + *

      + */ public class TestFocus01SwingAWTRobot extends UITestCase { static int width, height; static long durationPerTest = 10; @@ -125,6 +135,10 @@ public class TestFocus01SwingAWTRobot extends UITestCase { AWTKeyAdapter buttonKA = new AWTKeyAdapter("Button"); button.addKeyListener(buttonKA); eventCountAdapters.add(buttonKA); + AWTMouseAdapter buttonMA = new AWTMouseAdapter("Button"); + button.addMouseListener(buttonMA); + eventCountAdapters.add(buttonMA); + frame1.getContentPane().add(button, BorderLayout.NORTH); frame1.setSize(width, height); javax.swing.SwingUtilities.invokeAndWait(new Runnable() { @@ -158,13 +172,18 @@ public class TestFocus01SwingAWTRobot extends UITestCase { Assert.assertEquals(false, newtCanvasAWTFA.focusGained()); System.err.println("FOCUS AWT Button sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, button, buttonKA); + AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, + button, buttonMA); + AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2, + button, buttonMA); // Request the AWT focus, which should automatically provide the NEWT window with focus. Thread.sleep(100); // allow event sync System.err.println("FOCUS NEWT Canvas/GLWindow request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonFA); - Assert.assertEquals(false, newtCanvasAWTFA.focusGained()); + Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA, + AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA)); System.err.println("FOCUS NEWT Canvas/GLWindow sync"); AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA); Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount()); diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java b/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java index a0efa53ad..d8a9640c1 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java @@ -56,6 +56,15 @@ import java.io.IOException; import com.jogamp.opengl.test.junit.util.*; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +/** + * Testing focus traversal of an AWT component tree with {@link NewtCanvasAWT} attached. + *

      + * {@link JFrame} . {@link JPanel}+ . {@link Container} . {@link NewtCanvasAWT} . {@link GLWindow} + *

      + *

      + * + JPanel is set as JFrame's root content pane
      + *

      + */ public class TestFocus02SwingAWTRobot extends UITestCase { static int width, height; static long durationPerTest = 10; @@ -85,9 +94,6 @@ public class TestFocus02SwingAWTRobot extends UITestCase { ArrayList eventCountAdapters = new ArrayList(); - /** - * JFrame . JPanel . Container . NewtCanvasAWT . GLWindow - */ GLWindow glWindow1 = GLWindow.create(glCaps); glWindow1.setTitle("testWindowParenting01CreateVisibleDestroy"); GLEventListener demo1 = new GearsES2(); @@ -225,7 +231,9 @@ public class TestFocus02SwingAWTRobot extends UITestCase { System.err.println("FOCUS NEWT Canvas/GLWindow request"); EventCountAdapterUtil.reset(eventCountAdapters); AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthInnerFA); - Assert.assertTrue(AWTRobotUtil.waitForFocusCount(false, newtCanvasAWTFA)); + Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA, + AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA)); + Assert.assertEquals(false, newtCanvasAWTFA.focusGained()); Assert.assertEquals(false, buttonNorthOuterFA.focusGained()); Assert.assertEquals(false, jFrame1FA.focusGained()); diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestWindows01NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestWindows01NEWT.java index bf72348f9..e03b5e7d6 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestWindows01NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestWindows01NEWT.java @@ -33,7 +33,6 @@ import org.junit.BeforeClass; import org.junit.Test; import javax.media.nativewindow.*; -import javax.media.nativewindow.util.Point; import com.jogamp.newt.*; import java.io.IOException; diff --git a/src/test/com/jogamp/opengl/test/junit/newt/parenting/NewtAWTReparentingKeyAdapter.java b/src/test/com/jogamp/opengl/test/junit/newt/parenting/NewtAWTReparentingKeyAdapter.java index 473f2f584..f7881615d 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/parenting/NewtAWTReparentingKeyAdapter.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/parenting/NewtAWTReparentingKeyAdapter.java @@ -36,7 +36,7 @@ import com.jogamp.newt.event.KeyAdapter; import com.jogamp.newt.event.KeyEvent; import com.jogamp.newt.opengl.GLWindow; -class NewtAWTReparentingKeyAdapter extends KeyAdapter { +public class NewtAWTReparentingKeyAdapter extends KeyAdapter { Frame frame; NewtCanvasAWT newtCanvasAWT; GLWindow glWindow; diff --git a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer01GLCanvasAWT.java b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer01GLCanvasAWT.java deleted file mode 100644 index 4542fa47e..000000000 --- a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer01GLCanvasAWT.java +++ /dev/null @@ -1,211 +0,0 @@ -/** - * Copyright 2011 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package com.jogamp.opengl.test.junit.newt.parenting; - -import java.awt.BorderLayout; -import java.awt.Button; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Frame; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; - -import javax.media.opengl.GLAnimatorControl; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLEventListener; -import javax.media.opengl.awt.GLCanvas; - -import jogamp.nativewindow.jawt.JAWTUtil; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.jogamp.common.os.Platform; -import com.jogamp.newt.Window; -import com.jogamp.newt.opengl.GLWindow; -import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; -import com.jogamp.opengl.test.junit.util.AWTRobotUtil; -import com.jogamp.opengl.test.junit.util.MiscUtils; -import com.jogamp.opengl.test.junit.util.UITestCase; -import com.jogamp.opengl.util.Animator; - -public class TestParentingOffscreenLayer01GLCanvasAWT extends UITestCase { - static Dimension frameSize0; - static Dimension frameSize1; - static Dimension preferredGLSize; - static Dimension minGLSize; - static long durationPerTest = 1000; - - @BeforeClass - public static void initClass() { - frameSize0 = new Dimension(500,300); - frameSize1 = new Dimension(800,600); - preferredGLSize = new Dimension(400,200); - minGLSize = new Dimension(200,100); - } - - private void setupFrameAndShow(final Frame f, java.awt.Component comp) throws InterruptedException, InvocationTargetException { - - Container c = new Container(); - c.setLayout(new BorderLayout()); - c.add(new Button("north"), BorderLayout.NORTH); - c.add(new Button("south"), BorderLayout.SOUTH); - c.add(new Button("east"), BorderLayout.EAST); - c.add(new Button("west"), BorderLayout.WEST); - c.add(comp, BorderLayout.CENTER); - - f.setLayout(new BorderLayout()); - f.add(new Button("NORTH"), BorderLayout.NORTH); - f.add(new Button("SOUTH"), BorderLayout.SOUTH); - f.add(new Button("EAST"), BorderLayout.EAST); - f.add(new Button("WEST"), BorderLayout.WEST); - f.add(c, BorderLayout.CENTER); - - javax.swing.SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - f.validate(); - f.setVisible(true); - }}); - } - private void end(GLAnimatorControl actrl, final Frame f, Window w) throws InterruptedException, InvocationTargetException { - actrl.stop(); - javax.swing.SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - f.dispose(); - } } ); - if(null != w) { - w.destroy(); - } - } - - @Test - public void testInfo00() throws InterruptedException, InvocationTargetException { - System.err.println("Java Version: "+Platform.getJavaVersionNumber()); - System.err.println("OS Version: "+Platform.getOSVersionNumber()); - System.err.println("JAWTUtil.isOffscreenLayerRequired(): "+JAWTUtil.isOffscreenLayerRequired()); - System.err.println("JAWTUtil.isOffscreenLayerSupported(): "+JAWTUtil.isOffscreenLayerSupported()); - } - - @Test - public void testOnscreenLayerGLCanvas_Onscreen() throws InterruptedException, InvocationTargetException { - testOffscreenLayerGLCanvas_Impl(false); - } - - @Test - public void testOffscreenLayerGLCanvas_OffscreenLayerWithOnscreenClass() throws InterruptedException, InvocationTargetException { - testOffscreenLayerGLCanvas_Impl(true); - } - - private void testOffscreenLayerGLCanvas_Impl(boolean offscreenLayer) throws InterruptedException, InvocationTargetException { - if(!offscreenLayer && JAWTUtil.isOffscreenLayerRequired()) { - System.err.println("onscreen layer n/a"); - return; - } - if(offscreenLayer && !JAWTUtil.isOffscreenLayerSupported()) { - System.err.println("offscreen layer n/a"); - return; - } - final Frame frame1 = new Frame("AWT Parent Frame"); - - GLCapabilities glCaps = new GLCapabilities(null); - final GLCanvas glc = new GLCanvas(glCaps); - glc.setShallUseOffscreenLayer(offscreenLayer); // trigger offscreen layer - if supported - glc.setPreferredSize(preferredGLSize); - glc.setMinimumSize(minGLSize); - - GLEventListener demo1 = new GearsES2(1); - glc.addGLEventListener(demo1); - - frame1.setSize(frameSize0); - setupFrameAndShow(frame1, glc); - Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glc, true)); - Assert.assertEquals(true, AWTRobotUtil.waitForVisible(glc, true)); - Assert.assertEquals(JAWTUtil.isOffscreenLayerSupported() && offscreenLayer, - glc.isOffscreenLayerSurfaceEnabled()); - - GLAnimatorControl animator1 = new Animator(glc); - animator1.start(); - - Thread.sleep(durationPerTest/2); - javax.swing.SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - frame1.setSize(frameSize1); - frame1.validate(); - }}); - - Thread.sleep(durationPerTest/2); - - end(animator1, frame1, null); - } - - public static void setDemoFields(GLEventListener demo, GLWindow glWindow, boolean debug) { - Assert.assertNotNull(demo); - Assert.assertNotNull(glWindow); - Window window = glWindow.getDelegatedWindow(); - if(debug) { - MiscUtils.setFieldIfExists(demo, "glDebug", true); - MiscUtils.setFieldIfExists(demo, "glTrace", true); - } - if(!MiscUtils.setFieldIfExists(demo, "window", window)) { - MiscUtils.setFieldIfExists(demo, "glWindow", glWindow); - } - } - - static int atoi(String a) { - int i=0; - try { - i = Integer.parseInt(a); - } catch (Exception ex) { ex.printStackTrace(); } - return i; - } - - public static void main(String args[]) throws IOException { - for(int i=0; ivisible within TIME_OUT diff --git a/src/test/com/jogamp/opengl/test/junit/util/NEWTGLContext.java b/src/test/com/jogamp/opengl/test/junit/util/NEWTGLContext.java index 3f989bfa4..a76b67d57 100644 --- a/src/test/com/jogamp/opengl/test/junit/util/NEWTGLContext.java +++ b/src/test/com/jogamp/opengl/test/junit/util/NEWTGLContext.java @@ -70,8 +70,8 @@ public class NEWTGLContext { Assert.assertNotNull(window); window.setSize(width, height); window.setVisible(true); - AWTRobotUtil.waitForVisible(window, true); - AWTRobotUtil.waitForRealized(window, true); + Assert.assertTrue(AWTRobotUtil.waitForVisible(window, true)); + Assert.assertTrue(AWTRobotUtil.waitForRealized(window, true)); GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); GLDrawable drawable = factory.createGLDrawable(window); diff --git a/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java b/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java index c07d5b741..c42d9ff62 100644 --- a/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java +++ b/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java @@ -29,12 +29,14 @@ package com.jogamp.opengl.test.junit.util; import java.io.File; -import java.io.PrintWriter; -import java.io.StringWriter; +import java.util.Iterator; +import java.util.List; import javax.media.opengl.GL; +import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLEventListener; import com.jogamp.common.util.locks.SingletonInstance; import com.jogamp.opengl.util.GLReadBufferUtil; @@ -47,6 +49,8 @@ import org.junit.After; import org.junit.AfterClass; import org.junit.Rule; import org.junit.rules.TestName; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.TestClass; public abstract class UITestCase { @@ -58,9 +62,11 @@ public abstract class UITestCase { public static final long SINGLE_INSTANCE_LOCK_TO = 3*60*1000; // wait up to 3 min public static final long SINGLE_INSTANCE_LOCK_POLL = 1000; // poll every 1s - static volatile SingletonInstance singletonInstance; + private static volatile SingletonInstance singletonInstance; - static volatile boolean testSupported = true; + private static volatile boolean testSupported = true; + + private static volatile int maxMethodNameLen = 0; private static final synchronized void initSingletonInstance() { if( null == singletonInstance ) { @@ -77,6 +83,20 @@ public abstract class UITestCase { testSupported = v; } + public int getMaxTestNameLen() { + if(0 == maxMethodNameLen) { + int ml = 0; + final TestClass tc = new TestClass(getClass()); + final List testMethods = tc.getAnnotatedMethods(org.junit.Test.class); + for(Iterator iter=testMethods.iterator(); iter.hasNext(); ) { + final int l = iter.next().getName().length(); + if( ml < l ) { ml = l; } + } + maxMethodNameLen = ml; + } + return maxMethodNameLen; + } + public final String getTestMethodName() { return _unitTestName.getMethodName(); } @@ -120,13 +140,12 @@ public abstract class UITestCase { static final String unsupportedTestMsg = "Test not supported on this platform."; /** - * Takes a snapshot of the drawable's current framebuffer. Example filenames: + * Takes a snapshot of the drawable's current front framebuffer. Example filenames: *
      -     * TestFBODrawableNEWT.test01-F_rgba-I_rgba-S0_default-GL2-n0004-0800x0600.png
      -     * TestFBODrawableNEWT.test01-F_rgba-I_rgba-S0_default-GL2-n0005-0800x0600.png
      +     * TestGLDrawableAutoDelegateOnOffscrnCapsNEWT.testES2OffScreenFBOSglBuf____-n0001-msaa0-GLES2_-sw-fbobject-Bdbl-Frgb__Irgb_-S00_default-0400x0300.png
      +     * TestGLDrawableAutoDelegateOnOffscrnCapsNEWT.testES2OffScreenPbufferDblBuf-n0003-msaa0-GLES2_-sw-pbuffer_-Bdbl-Frgb__Irgb_-S00_default-0200x0150.png
      +     * TestGLDrawableAutoDelegateOnOffscrnCapsNEWT.testGL2OffScreenPbufferSglBuf-n0003-msaa0-GL2___-hw-pbuffer_-Bone-Frgb__Irgb_-S00_default-0200x0150.png
            * 
      - * - * @param simpleTestName will be used as the filename prefix * @param sn sequential number * @param postSNDetail optional detail to be added to the filename after sn * @param gl the current GL context object. It's read drawable is being used as the pixel source and to gather some details which will end up in the filename. @@ -137,30 +156,80 @@ public abstract class UITestCase { * It shall not end with a directory separator, {@link File#separatorChar}. * If null the current working directory is being used. */ - public static void snapshot(String simpleTestName, int sn, String postSNDetail, GL gl, GLReadBufferUtil readBufferUtil, String fileSuffix, String destPath) { + public void snapshot(int sn, String postSNDetail, GL gl, GLReadBufferUtil readBufferUtil, String fileSuffix, String destPath) { if(null == fileSuffix) { fileSuffix = TextureIO.PNG; } - final StringWriter filenameSW = new StringWriter(); - { + final int maxSimpleTestNameLen = getMaxTestNameLen()+getClass().getSimpleName().length()+1; + final String simpleTestName = this.getSimpleTestName("."); + final String filenameBaseName; + { final GLDrawable drawable = gl.getContext().getGLReadDrawable(); final GLCapabilitiesImmutable caps = drawable.getChosenGLCapabilities(); + final String accel = caps.getHardwareAccelerated() ? "hw" : "sw" ; + final String scrnm; + if(caps.isOnscreen()) { + scrnm = "onscreen"; + } else if(caps.isFBO()) { + scrnm = "fbobject"; + } else if(caps.isPBuffer()) { + scrnm = "pbuffer_"; + } else if(caps.isBitmap()) { + scrnm = "bitmap__"; + } else { + scrnm = "unknown_"; + } + final String dblb = caps.getDoubleBuffered() ? "dbl" : "one"; final String F_pfmt = readBufferUtil.hasAlpha() ? "rgba" : "rgb_"; final String pfmt = caps.getAlphaBits() > 0 ? "rgba" : "rgb_"; - final String aaext = caps.getSampleExtension(); final int samples = caps.getNumSamples() ; + final String aaext = caps.getSampleExtension(); postSNDetail = null != postSNDetail ? "-"+postSNDetail : ""; - final PrintWriter pw = new PrintWriter(filenameSW); - pw.printf("%s-n%04d%s-F_%s-I_%s-S%d_%s-%s-%04dx%04d.%s", - simpleTestName, sn, postSNDetail, F_pfmt, pfmt, samples, aaext, drawable.getGLProfile().getName(), - drawable.getWidth(), drawable.getHeight(), fileSuffix); + + filenameBaseName = String.format("%-"+maxSimpleTestNameLen+"s-n%04d%s-%-6s-%s-%s-B%s-F%s_I%s-S%02d_%s-%04dx%04d.%s", + simpleTestName, sn, postSNDetail, drawable.getGLProfile().getName(), accel, + scrnm, dblb, F_pfmt, pfmt, samples, aaext, + drawable.getWidth(), drawable.getHeight(), fileSuffix).replace(' ', '_'); } - final String filename = null != destPath ? destPath + File.separator + filenameSW.toString() : filenameSW.toString(); - System.err.println(Thread.currentThread().getName()+": ** screenshot: "+filename); + final String filename = null != destPath ? destPath + File.separator + filenameBaseName : filenameBaseName; + System.err.println(Thread.currentThread().getName()+": ** screenshot: "+filename+", maxTestNameLen "+maxSimpleTestNameLen+", <"+simpleTestName+">"); gl.glFinish(); // just make sure rendering finished .. if(readBufferUtil.readPixels(gl, false)) { readBufferUtil.write(new File(filename)); } - } + } + + public class SnapshotGLEventListener implements GLEventListener { + private final GLReadBufferUtil screenshot; + private volatile boolean makeShot = false; + private volatile int displayCount=0; + private volatile int reshapeCount=0; + public SnapshotGLEventListener(GLReadBufferUtil screenshot) { + this.screenshot = screenshot; + } + public SnapshotGLEventListener() { + this.screenshot = new GLReadBufferUtil(false, false); + } + + public void init(GLAutoDrawable drawable) {} + public void dispose(GLAutoDrawable drawable) {} + public void display(GLAutoDrawable drawable) { + final GL gl = drawable.getGL(); + System.err.println(Thread.currentThread().getName()+": ** display: "+displayCount+": "+drawable.getWidth()+"x"+drawable.getHeight()+", makeShot "+makeShot); + if(makeShot) { + makeShot=false; + snapshot(displayCount, null, gl, screenshot, TextureIO.PNG, null); + } + displayCount++; + } + public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { + System.err.println(Thread.currentThread().getName()+": ** reshape: "+reshapeCount+": "+width+"x"+height+" - "+drawable.getWidth()+"x"+drawable.getHeight()); + reshapeCount++; + } + public void setMakeSnapshot() { + makeShot=true; + } + }; + } -- cgit v1.2.3 From e30c2c7d06847889d961d12b50e77e4dfd6e525f Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 16 Sep 2012 13:27:06 +0200 Subject: OSX: Capture 'invalid drawable' message cause by NSOpenGLContext::setView(NULL || incomplete-view) ; Add missing [ctx release] in MyNSOpenGLLayer ; Misc NSOpenGLContext::setView(NULL || incomplete-view) was called on 2 occasions: [1] - MacOSXCGLContext native createContext [2] - NSOpenGLLayer internals For [1], we simply don't call setView(..) ourselfs in case view is NULL or incomplete (invisible) For [2], we need to wrap the class 'MyNSOpenGLContext:NSOpenGLContext' and capture setView(NULL) ++ Add missing [ctx release] in MyNSOpenGLLayer, otherwise resource won't get dealloc'ed +++ Misc: - MacOSXCGLContext. contextRealized(true): set pbuffer -> ctx, otherwise 1st makeCurrent call will not catch it - MacOSXOnscreenCGLContext: don't add ContextUpdater to invisible ProxySurface's (dummy window) --- make/scripts/tests.sh | 11 +++- make/stub_includes/opengl/macosx-window-system.h | 2 +- .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 15 +++-- .../macosx/cgl/MacOSXOnscreenCGLContext.java | 19 +++++-- .../macosx/MacOSXWindowSystemInterface-calayer.m | 65 ++++++++++++++++++++-- .../native/macosx/MacOSXWindowSystemInterface.m | 43 ++++++++++---- src/nativewindow/native/macosx/OSXmisc.m | 2 +- .../acore/TestOffscreenLayer01GLCanvasAWT.java | 12 ++++ .../acore/TestOffscreenLayer02NewtCanvasAWT.java | 12 ++++ 9 files changed, 152 insertions(+), 29 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index d2e2db375..5051979d5 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -32,7 +32,13 @@ MOSX=0 MOSX_MT=0 uname -a | grep -i Darwin && MOSX=1 if [ $MOSX -eq 1 ] ; then + echo setup OSX environment vars export NSZombieEnabled=YES + export NSTraceEvents=YES + export OBJC_PRINT_EXCEPTIONS=YES + echo NSZombieEnabled $NSZombieEnabled + echo NSTraceEvents $NSTraceEvents + echo OBJC_PRINT_EXCEPTIONS $OBJC_PRINT_EXCEPTIONS MOSX_MT=1 fi @@ -224,6 +230,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFloatUtil01MatrixMatrixMultNOUI $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestNEWTCloseX11DisplayBug565 $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile00NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT $* @@ -239,14 +246,14 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBODrawableNEWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryOffscrnCapsNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer01GLCanvasAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer02NewtCanvasAWT $* +testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer02NewtCanvasAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableFactoryNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOOffThreadSharedContextMix2DemosES2NEWT $* diff --git a/make/stub_includes/opengl/macosx-window-system.h b/make/stub_includes/opengl/macosx-window-system.h index c627f67de..828e3c01e 100644 --- a/make/stub_includes/opengl/macosx-window-system.h +++ b/make/stub_includes/opengl/macosx-window-system.h @@ -32,7 +32,7 @@ NSView* getNSView(NSOpenGLContext* ctx); NSOpenGLContext* createContext(NSOpenGLContext* shareContext, NSView* nsView, - Bool allowIncompleteView, + Bool incompleteView, NSOpenGLPixelFormat* pixelFormat, Bool opaque, int* viewNotReady); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index ec29558d1..e04955d87 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -490,9 +490,9 @@ public abstract class MacOSXCGLContext extends GLContextImpl } backingLayerHost = NativeWindowFactory.getOffscreenLayerSurface(surface, true); - boolean allowIncompleteView = null != backingLayerHost; - if( !allowIncompleteView && surface instanceof ProxySurface ) { - allowIncompleteView = ((ProxySurface)surface).containsUpstreamOptionBits( ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE ); + boolean incompleteView = null != backingLayerHost; + if( !incompleteView && surface instanceof ProxySurface ) { + incompleteView = ((ProxySurface)surface).containsUpstreamOptionBits( ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE ); } long pixelFormat = MacOSXCGLGraphicsConfiguration.GLCapabilities2NSPixelFormat(chosenCaps, ctp, major, minor); if (pixelFormat == 0) { @@ -514,7 +514,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl screenVSyncTimeout = 1000000f / sRefreshRate; if(DEBUG) { System.err.println("NS create OSX>=lion "+isLionOrLater); - System.err.println("NS create allowIncompleteView: "+allowIncompleteView); + System.err.println("NS create incompleteView: "+incompleteView); System.err.println("NS create backingLayerHost: "+backingLayerHost); System.err.println("NS create share: "+share); System.err.println("NS create drawable type: "+drawable.getClass().getName()); @@ -546,7 +546,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl int[] viewNotReady = new int[1]; // Try to allocate a context with this ctx = CGL.createContext(share, - nsViewHandle, allowIncompleteView, + nsViewHandle, incompleteView, pixelFormat, chosenCaps.isBackgroundOpaque(), viewNotReady, 0); @@ -603,6 +603,9 @@ public abstract class MacOSXCGLContext extends GLContextImpl } else if( chosenCaps.isPBuffer() && CGL.isNSOpenGLPixelBuffer(drawableHandle) ) { texID = 0; lastPBufferHandle = drawableHandle; + if(0 != drawableHandle) { // complete 'validatePBufferConfig(..)' procedure + CGL.setContextPBuffer(ctx, drawableHandle); + } } else { throw new GLException("BackingLayerHost w/ unknown handle (!FBO, !PBuffer): "+drawable); } @@ -648,7 +651,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl private final void validatePBufferConfig(long ctx) { final GLCapabilitiesImmutable chosenCaps = drawable.getChosenGLCapabilities(); final long drawableHandle = drawable.getHandle(); - if(chosenCaps.isPBuffer() && CGL.isNSOpenGLPixelBuffer(drawableHandle) && lastPBufferHandle != drawableHandle) { + if( chosenCaps.isPBuffer() && lastPBufferHandle != drawableHandle && CGL.isNSOpenGLPixelBuffer(drawableHandle) ) { // Must associate the pbuffer with our newly-created context lastPBufferHandle = drawableHandle; if(0 != drawableHandle) { diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXOnscreenCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXOnscreenCGLContext.java index e344fd461..447d18f68 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXOnscreenCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXOnscreenCGLContext.java @@ -39,6 +39,8 @@ package jogamp.opengl.macosx.cgl; +import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.ProxySurface; import javax.media.opengl.GLContext; import javax.media.opengl.GLException; @@ -60,7 +62,7 @@ public class MacOSXOnscreenCGLContext extends MacOSXCGLContext { @Override protected void drawableUpdatedNotify() throws GLException { final int w = drawable.getWidth(); - final int h = drawable.getHeight(); + final int h = drawable.getHeight(); final boolean updateContext = ( 0!=updateHandle && CGL.updateContextNeedsUpdate(updateHandle) ) || w != lastWidth || h != lastHeight; if(updateContext) { @@ -82,9 +84,18 @@ public class MacOSXOnscreenCGLContext extends MacOSXCGLContext { if(0 != updateHandle) { throw new InternalError("XXX1"); } - updateHandle = CGL.updateContextRegister(contextHandle, drawable.getHandle()); - if(0 == updateHandle) { - throw new InternalError("XXX2"); + final boolean incompleteView; + final NativeSurface surface = drawable.getNativeSurface(); + if( surface instanceof ProxySurface ) { + incompleteView = ((ProxySurface)surface).containsUpstreamOptionBits( ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE ); + } else { + incompleteView = false; + } + if(!incompleteView) { + updateHandle = CGL.updateContextRegister(contextHandle, drawable.getHandle()); + if(0 == updateHandle) { + throw new InternalError("XXX2"); + } } } return res; diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index 63323b76d..f3495efff 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -25,6 +25,56 @@ // // #define DBG_PERF 1 +/** + * Capture setView(NULL), which produces a 'invalid drawable' message + * + * Also track lifecycle via DBG_PRINT messages, if VERBOSE is enabled! + */ +@interface MyNSOpenGLContext: NSOpenGLContext +{ +} +- (id)initWithFormat:(NSOpenGLPixelFormat *)format shareContext:(NSOpenGLContext *)share; +- (void)setView:(NSView *)view; +- (void)update; +- (void)dealloc; + +@end + +@implementation MyNSOpenGLContext + +- (id)initWithFormat:(NSOpenGLPixelFormat *)format shareContext:(NSOpenGLContext *)share +{ + DBG_PRINT("MyNSOpenGLContext.initWithFormat.0: format %p, share %p\n", format, share); + MyNSOpenGLContext * o = [super initWithFormat:format shareContext:share]; + DBG_PRINT("MyNSOpenGLContext.initWithFormat.X: new %p\n", o); + return o; +} + +- (void)setView:(NSView *)view +{ + DBG_PRINT("MyNSOpenGLContext.setView: this.0 %p, view %p\n", self, view); + if(NULL != view) { + [super setView:view]; + } + DBG_PRINT("MyNSOpenGLContext.setView.X\n"); +} + +- (void)update +{ + DBG_PRINT("MyNSOpenGLContext.update: this.0 %p, view %p\n", self, [self view]); + [super update]; + DBG_PRINT("MyNSOpenGLContext.update.X\n"); +} + +- (void)dealloc +{ + DBG_PRINT("MyNSOpenGLContext.dealloc: this.0 %p\n", self); + [super dealloc]; + DBG_PRINT("MyNSOpenGLContext.dealloc.X: %p\n", self); +} + +@end + @interface MyNSOpenGLLayer: NSOpenGLLayer { @private @@ -204,6 +254,8 @@ static const GLfloat gl_verts[] = { [self setOpaque: opaque ? YES : NO]; +#ifdef VERBOSE_ON + CGRect lRect = [self bounds]; if(NULL != pbuffer) { DBG_PRINT("MyNSOpenGLLayer::init (pbuffer) %p, ctx %p, pfmt %p, pbuffer %p, opaque %d, pbuffer %dx%d -> tex %dx%d, bounds: %lf/%lf %lfx%lf (refcnt %d)\n", self, parentCtx, parentPixelFmt, pbuffer, opaque, [pbuffer pixelsWide], [pbuffer pixelsHigh], texWidth, texHeight, @@ -213,6 +265,7 @@ static const GLfloat gl_verts[] = { self, parentCtx, parentPixelFmt, opaque, (int)textureID, texWidth, texHeight, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, (int)[self retainCount]); } +#endif return self; } @@ -293,9 +346,10 @@ static const GLfloat gl_verts[] = { - (NSOpenGLContext *)openGLContextForPixelFormat:(NSOpenGLPixelFormat *)pixelFormat { - NSOpenGLContext * nctx = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:parentCtx]; - DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat: %p (refcnt %d) - pfmt %p, parent %p -> new-ctx %p\n", - self, (int)[self retainCount], pixelFormat, parentCtx, nctx); + DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.0: %p (refcnt %d) - pfmt %p, parent %p\n", + self, (int)[self retainCount], pixelFormat, parentCtx); + NSOpenGLContext * nctx = [[MyNSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:parentCtx]; + DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.X: new-ctx %p\n", nctx); return nctx; } @@ -324,7 +378,7 @@ static const GLfloat gl_verts[] = { if(NULL!=context) { [context makeCurrentContext]; - DBG_PRINT("MyNSOpenGLLayer::deallocPBuffer (with ctx) %p (refcnt %d) - context %p, pbuffer %p, texID %d\n", self, (int)[self retainCount], context, pbuffer, (int)texureID); + DBG_PRINT("MyNSOpenGLLayer::deallocPBuffer (with ctx) %p (refcnt %d) - context %p, pbuffer %p, texID %d\n", self, (int)[self retainCount], context, pbuffer, (int)textureID); if( 0 != textureID ) { glDeleteTextures(1, &textureID); @@ -333,7 +387,7 @@ static const GLfloat gl_verts[] = { [context clearDrawable]; } else { - DBG_PRINT("MyNSOpenGLLayer::deallocPBuffer (w/o ctx) %p (refcnt %d) - context %p, pbuffer %p, texID %d\n", self, (int)[self retainCount], context, pbuffer, (int)texureID); + DBG_PRINT("MyNSOpenGLLayer::deallocPBuffer (w/o ctx) %p (refcnt %d) - context %p, pbuffer %p, texID %d\n", self, (int)[self retainCount], context, pbuffer, (int)textureID); } pbuffer = NULL; [self setTextureID: 0]; @@ -346,6 +400,7 @@ static const GLfloat gl_verts[] = { pthread_mutex_lock(&renderLock); [self disableAnimation]; [self deallocPBuffer]; + [[self openGLContext] release]; [self release]; DBG_PRINT("MyNSOpenGLLayer::releaseLayer.X: %p (refcnt %d)\n", self, (int)[self retainCount]); pthread_mutex_unlock(&renderLock); diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m index becd41bb2..48807ee29 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m @@ -446,7 +446,7 @@ NSOpenGLPixelFormat* createPixelFormat(int* iattrs, int niattrs, int* ivalues) { NSOpenGLPixelFormat* fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; // if(fmt == nil) { fallback to a [NSOpenGLView defaultPixelFormat] crashed (SIGSEGV) on 10.6.7/NV } - DBG_PRINT("createPixelFormat.X: pfmt %p\n", fmt); + DBG_PRINT("\ncreatePixelFormat.X: pfmt %p\n", fmt); [pool release]; return fmt; @@ -503,7 +503,7 @@ NSView* getNSView(NSOpenGLContext* ctx) { NSOpenGLContext* createContext(NSOpenGLContext* share, NSView* view, - Bool allowIncompleteView, + Bool incompleteView, NSOpenGLPixelFormat* fmt, Bool opaque, int* viewNotReady) @@ -512,13 +512,13 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, getRendererInfo(); - DBG_PRINT("createContext.0: share %p, view %p, allowIncompleteView %d, pixfmt %p, opaque %d\n", - share, view, (int)allowIncompleteView, fmt, opaque); + DBG_PRINT("createContext.0: share %p, view %p, incompleteView %d, pixfmt %p, opaque %d\n", + share, view, (int)incompleteView, fmt, opaque); if (view != nil) { Bool viewReady = true; - if(!allowIncompleteView) { + if(!incompleteView) { if ([view lockFocusIfCanDraw] == NO) { DBG_PRINT("createContext.1 [view lockFocusIfCanDraw] failed\n"); viewReady = false; @@ -527,7 +527,7 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, if(viewReady) { NSRect frame = [view frame]; if ((frame.size.width == 0) || (frame.size.height == 0)) { - if(!allowIncompleteView) { + if(!incompleteView) { [view unlockFocus]; } DBG_PRINT("createContext.2 view.frame size %dx%d\n", (int)frame.size.width, (int)frame.size.height); @@ -557,8 +557,10 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, GLint zeroOpacity = 0; [ctx setValues:&zeroOpacity forParameter:NSOpenGLCPSurfaceOpacity]; } - [ctx setView:view]; - if(!allowIncompleteView) { + if(!incompleteView) { + DBG_PRINT("createContext.3.0: setView\n"); + [ctx setView:view]; + DBG_PRINT("createContext.3.X: setView\n"); [view unlockFocus]; } } @@ -628,7 +630,12 @@ void setContextOpacity(NSOpenGLContext* ctx, int opacity) { void updateContext(NSOpenGLContext* ctx) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - [ctx update]; + NSView *nsView = [ctx view]; + if(NULL != nsView) { + DBG_PRINT("updateContext.0: ctx %p, ctx.view %p\n", ctx, nsView); + [ctx update]; + DBG_PRINT("updateContext.X\n"); + } [pool release]; } @@ -638,7 +645,10 @@ void copyContext(NSOpenGLContext* dest, NSOpenGLContext* src, int mask) { void* updateContextRegister(NSOpenGLContext* ctx, NSView* view) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + + DBG_PRINT("updateContextRegister.0: ctx %p, view %p\n", ctx, view); ContextUpdater *contextUpdater = [[ContextUpdater alloc] initWithContext: ctx view: view]; + DBG_PRINT("updateContextRegister.X: ctxupd %p\n", contextUpdater); [pool release]; return contextUpdater; } @@ -658,47 +668,60 @@ void updateContextUnregister(void* updater) { ContextUpdater *contextUpdater = (ContextUpdater *)updater; NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + DBG_PRINT("updateContextUnregister.0: ctxupd %p\n", contextUpdater); [contextUpdater release]; + DBG_PRINT("updateContextUnregister.X\n"); [pool release]; } NSOpenGLPixelBuffer* createPBuffer(int renderTarget, int internalFormat, int width, int height) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + DBG_PRINT("createPBuffer.0: renderTarget 0x%x, ifmt 0x%x, %dx%d: \n", renderTarget, internalFormat, width, height); NSOpenGLPixelBuffer* pBuffer = [[NSOpenGLPixelBuffer alloc] initWithTextureTarget:renderTarget textureInternalFormat:internalFormat textureMaxMipMapLevel:0 pixelsWide:width pixelsHigh:height]; + DBG_PRINT("createPBuffer.X: res %p\n", pBuffer); [pool release]; return pBuffer; } Bool destroyPBuffer(NSOpenGLPixelBuffer* pBuffer) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + DBG_PRINT("destroyPBuffer.0: pbuffer %p\n", pBuffer); [pBuffer release]; + DBG_PRINT("destroyPBuffer.X\n"); [pool release]; return true; } void setContextPBuffer(NSOpenGLContext* ctx, NSOpenGLPixelBuffer* pBuffer) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + DBG_PRINT("setContextPBuffer.0: ctx %p, pbuffer %p\n", ctx, pBuffer); [ctx setPixelBuffer: pBuffer cubeMapFace: 0 mipMapLevel: 0 currentVirtualScreen: [ctx currentVirtualScreen]]; + DBG_PRINT("setContextPBuffer.X\n"); [pool release]; } void setContextTextureImageToPBuffer(NSOpenGLContext* ctx, NSOpenGLPixelBuffer* pBuffer, GLenum colorBuffer) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + DBG_PRINT("setContextTextureImageToPBuffer.0: ctx %p, pbuffer %p, colorBuffer 0x%x\n", ctx, pBuffer, (int)colorBuffer); [ctx setTextureImageToPixelBuffer: pBuffer colorBuffer: colorBuffer]; + DBG_PRINT("setContextTextureImageToPBuffer.X\n"); [pool release]; } Bool isNSOpenGLPixelBuffer(uint64_t object) { NSObject *nsObj = (NSObject*) (intptr_t) object; - return [nsObj isMemberOfClass:[NSOpenGLPixelBuffer class]]; + DBG_PRINT("isNSOpenGLPixelBuffer.0: obj %p\n", object); + Bool res = [nsObj isMemberOfClass:[NSOpenGLPixelBuffer class]]; + DBG_PRINT("isNSOpenGLPixelBuffer.X: res %d\n", (int)res); + return res; } #include diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index d6ae7ed31..1cf41fc9d 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -633,7 +633,7 @@ JNIEXPORT jint JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetScreenRefreshR if(0 == res) { res = 60; // default .. (experienced on OSX 10.6.8) } - fprintf(stderr, "GetScreenRefreshRate.X: %d\n", res); + DBG_PRINT(stderr, "GetScreenRefreshRate.X: %d\n", res); // [pool release]; JNF_COCOA_EXIT(env); return res; diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java index d181800c5..3c9afbd2f 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java @@ -33,7 +33,9 @@ import java.awt.Button; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import javax.media.opengl.GLAnimatorControl; @@ -203,6 +205,7 @@ public class TestOffscreenLayer01GLCanvasAWT extends UITestCase { } public static void main(String args[]) throws IOException { + boolean waitForKey = false; for(int i=0; i Date: Mon, 17 Sep 2012 03:30:36 +0200 Subject: Fixes Bug 615 - X11: Use proper screen index/name for shared resources and device denominated 'mutable' surfaces (dummy, offscreen, ..) Fix follows findings of Rob Hatcherson, but instead of parsing the display connection ourself we use the X11 macro 'DefaultScreen(display)' See "The screen number specified in the display_name argument is returned by the DefaultScreen() macro (or the XDefaultScreen() function)." Since I currently have no two-head X11 setup here, only xinerama via virtualbox, pls test / validate. Note: One Display connection may span multiple screens, i.e.: display 'lala:0.1' may span from screen 1 - 3 (non xinerama mode) Discussion: [1] How to validate whether a screen number belongs to one display connection ? We can query ScreenCount(display), however it is not clear what the range would be. [2] With 1 display connection spanning multiple screens, what is/are the proper connection string[s] ? [3] After all, it seems this ancient configuration really cannot beat a modern setup w/ XRandR having Xinerama enabled. The latter is the default anyways. --- make/scripts/tests.sh | 6 ++--- make/stub_includes/x11/window-lib.c | 5 +++- .../opengl/x11/glx/X11GLXDrawableFactory.java | 4 +-- .../jogamp/nativewindow/x11/X11GraphicsDevice.java | 29 +++++++++++++++++++--- .../test/junit/newt/TestRemoteGLWindows01NEWT.java | 1 - 5 files changed, 35 insertions(+), 10 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 05109e52f..9733e3710 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -91,7 +91,7 @@ function jrun() { #D_ARGS="-Dnewt.test.Screen.disableScreenMode -Dnewt.debug.Screen" #D_ARGS="-Djogl.debug.ExtensionAvailabilityCache -Djogl.debug=all -Dnativewindow.debug=all -Djogamp.debug.ProcAddressHelper=true -Djogamp.debug.NativeLibrary=true -Djogamp.debug.NativeLibrary.Lookup=true" #D_ARGS="-Dnewt.debug.MainThread" - D_ARGS="-Dnewt.debug.Window" + #D_ARGS="-Dnewt.debug.Window" #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Dnativewindow.debug.NativeWindow" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Animator -Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.ExtensionAvailabilityCache" @@ -273,7 +273,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.glu.TestGluUnprojectFloatNOUI $* #testnoawt com.jogamp.opengl.test.junit.newt.TestRemoteWindow01NEWT $* -#testnoawt com.jogamp.opengl.test.junit.newt.TestRemoteGLWindows01NEWT $* +testnoawt com.jogamp.opengl.test.junit.newt.TestRemoteGLWindows01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* @@ -350,7 +350,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.newt.TestSwingAWTRobotUsageBeforeJOGLInitBug411 $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper $* #testawt com.jogamp.opengl.test.junit.newt.TestEventSourceNotAWTBug -testawt com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot $* +#testawt com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot $* #testawt com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot $* #testawt com.jogamp.opengl.test.junit.newt.TestListenerCom01AWT #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aAWT $* diff --git a/make/stub_includes/x11/window-lib.c b/make/stub_includes/x11/window-lib.c index bc5df4ae4..1204d033d 100644 --- a/make/stub_includes/x11/window-lib.c +++ b/make/stub_includes/x11/window-lib.c @@ -27,9 +27,12 @@ extern void XLockDisplay(Display *display); extern void XUnlockDisplay(Display *display); -extern Window RootWindow(Display *display, int screen_number); extern int DefaultScreen(Display *display); +extern int ScreenCount(Display *display); + +extern Window RootWindow(Display *display, int screen_number); + extern XVisualInfo *XGetVisualInfo( Display* /* display */, long /* vinfo_mask */, diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index fb11f8bba..ca5cd424b 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -237,7 +237,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { // NativeWindowFactory.getNullToolkitLock(), true); // own non-shared display connection, w/o locking sharedDevice.lock(); try { - final X11GraphicsScreen sharedScreen = new X11GraphicsScreen(sharedDevice, 0); + final X11GraphicsScreen sharedScreen = new X11GraphicsScreen(sharedDevice, sharedDevice.getDefaultScreen()); if(!GLXUtil.isGLXAvailableOnServer(sharedDevice)) { throw new GLException("GLX not available on device/server: "+sharedDevice); @@ -514,7 +514,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { } else { device = (X11GraphicsDevice)deviceReq; } - final X11GraphicsScreen screen = new X11GraphicsScreen(device, 0); + final X11GraphicsScreen screen = new X11GraphicsScreen(device, device.getDefaultScreen()); final X11GLXGraphicsConfiguration config = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED); if(null == config) { throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index 5e4d6f41a..152384980 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -84,11 +84,34 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl handleOwner = owner; } + private static int getDefaultScreenImpl(long dpy) { + return X11Lib.DefaultScreen(dpy); + } + + /** + * Returns the default screen number as referenced by the display connection, i.e. 'somewhere:0.1' -> 1 + *

      + * Implementation uses the XLib macro DefaultScreen(display). + *

      + */ + public int getDefaultScreen() { + final long display = getHandle(); + if(0==display) { + throw new NativeWindowException("null display"); + } + final int ds = getDefaultScreenImpl(display); + if(DEBUG) { + System.err.println(Thread.currentThread().getName() + " - X11GraphicsDevice.getDefaultDisplay() of "+this+": "+ds+", count "+X11Lib.ScreenCount(display)); + } + return ds; + } + public int getDefaultVisualID() { - // It still could be an AWT hold handle .. final long display = getHandle(); - final int scrnIdx = X11Lib.DefaultScreen(display); - return X11Lib.DefaultVisualID(display, scrnIdx); + if(0==display) { + throw new NativeWindowException("null display"); + } + return X11Lib.DefaultVisualID(display, getDefaultScreenImpl(display)); } @Override diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestRemoteGLWindows01NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestRemoteGLWindows01NEWT.java index 35e24403f..ef830b660 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestRemoteGLWindows01NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestRemoteGLWindows01NEWT.java @@ -30,7 +30,6 @@ package com.jogamp.opengl.test.junit.newt; import org.junit.Assert; import org.junit.Assume; -import org.junit.BeforeClass; import org.junit.Test; import javax.media.opengl.*; -- cgit v1.2.3 From 48f033d61dcf6c6d6964457710f6ac273ef4fc58 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 20 Sep 2012 23:18:30 +0200 Subject: NativeWindowFactory/NEWT: Use relative sub-package names in NativeWindowFactory's TYPE_* strings, not NEWT's; NEWTFactory: Use default NEWT package name if rel. 'path'. Use relative sub-package names in NativeWindowFactory's TYPE_* strings, not NEWT's Otherwise NEWT depends solely on NativeWindowFactory strings - Default subpackages denominate a relative path, i.e. start with a dot: '.egl', '.windows', '.x11' - Custom name may be absolute, eg: 'my.company.special.drivers.chip4' NEWTFactory: Use default NEWT package name if relative 'path'. - If NativeWindowFactory type starts w/ dot (rel. path), simply prepend the default NEWT package prefix otherwise use complete package name as-is. --- .../javax/media/nativewindow/NativeWindowFactory.java | 14 +++++++------- src/newt/classes/com/jogamp/newt/NewtFactory.java | 9 ++++++++- 2 files changed, 15 insertions(+), 8 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 89d476a3b..40aaa8a25 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -57,25 +57,25 @@ public abstract class NativeWindowFactory { protected static final boolean DEBUG; /** OpenKODE/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}.*/ - public static final String TYPE_EGL = "jogamp.newt.driver.kd".intern(); + public static final String TYPE_EGL = ".egl".intern(); /** Microsoft Windows type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ - public static final String TYPE_WINDOWS = "jogamp.newt.driver.windows".intern(); + public static final String TYPE_WINDOWS = ".windows".intern(); /** X11 type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ - public static final String TYPE_X11 = "jogamp.newt.driver.x11".intern(); + public static final String TYPE_X11 = ".x11".intern(); /** Android/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}.*/ - public static final String TYPE_ANDROID = "jogamp.newt.driver.android".intern(); + public static final String TYPE_ANDROID = ".android".intern(); /** Mac OS X type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ - public static final String TYPE_MACOSX = "jogamp.newt.driver.macosx".intern(); + public static final String TYPE_MACOSX = ".macosx".intern(); /** Generic AWT type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ - public static final String TYPE_AWT = "jogamp.newt.driver.awt".intern(); + public static final String TYPE_AWT = ".awt".intern(); /** Generic DEFAULT type, where platform implementation don't care, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ - public static final String TYPE_DEFAULT = "default".intern(); + public static final String TYPE_DEFAULT = ".default".intern(); private static final String nativeWindowingTypePure; // canonical String via String.intern() private static final String nativeWindowingTypeCustom; // canonical String via String.intern() diff --git a/src/newt/classes/com/jogamp/newt/NewtFactory.java b/src/newt/classes/com/jogamp/newt/NewtFactory.java index 0644c9164..abae94ab6 100644 --- a/src/newt/classes/com/jogamp/newt/NewtFactory.java +++ b/src/newt/classes/com/jogamp/newt/NewtFactory.java @@ -49,6 +49,8 @@ import jogamp.newt.WindowImpl; public class NewtFactory { public static final boolean DEBUG_IMPLEMENTATION = Debug.debug("Window"); + public static final String DRIVER_DEFAULT_ROOT_PACKAGE = "jogamp.newt.driver"; + // Work-around for initialization order problems on Mac OS X // between native Newt and (apparently) Fmod static { @@ -59,7 +61,12 @@ public class NewtFactory { public static Class getCustomClass(String packageName, String classBaseName) { Class clazz = null; if(packageName!=null && classBaseName!=null) { - final String clazzName = packageName + "." + classBaseName ; + final String clazzName; + if( packageName.startsWith(".") ) { + clazzName = DRIVER_DEFAULT_ROOT_PACKAGE + packageName + "." + classBaseName ; + } else { + clazzName = packageName + "." + classBaseName ; + } try { clazz = Class.forName(clazzName); } catch (Throwable t) { -- cgit v1.2.3 From ba846a478d616327817dd530dbdcd9a786be5b7a Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 21 Sep 2012 22:18:20 +0200 Subject: Fix Bug 621, JVM Crashes During X11 Shutdown while closing all unclosed display connections. This is a regression of JOGL commit f2cfb6119a3663715ed2d572643949b3bef58662 to fix Bug 610. Commit f2cfb6119a3663715ed2d572643949b3bef58662 closed all open display connections at JVM shutdown in order of their creation. This is required IF the driver is the proprietary ATI on X11. X11Util.setMarkAllDisplaysUnclosable(true) is called in this case. However, this behavior causes a SIGSEGV for other GPU driver, i.e. Nvidia :) This fix only closes the pending display connections in their respective order IF X11Util.getMarkAllDisplaysUnclosable() == true. Hence the 'new' cleanup as introduced in the offending commit is only performed on the erroneous ATI driver. Manually tested w/ TestGearsES2AWT, see it's commandline options for details. --- make/scripts/tests.sh | 4 +- .../classes/jogamp/nativewindow/x11/X11Util.java | 45 ++++++++++++---------- .../junit/jogl/demos/es2/awt/TestGearsES2AWT.java | 23 ++++++++++- 3 files changed, 47 insertions(+), 25 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index b8960d518..8a0a638ba 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -322,7 +322,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWT02WindowClosing #testawt com.jogamp.opengl.test.junit.jogl.awt.text.TestAWTTextRendererUseVertexArrayBug464 #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* +testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWTAnalyzeBug455 $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWTBug450 $* @@ -426,7 +426,7 @@ function testawtswt() { # # Security # -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMapBufferRead01NEWT $* # diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 93b7f3487..2ea75c7fb 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -70,7 +70,12 @@ public class X11Util { * See also native test: jogl/test-native/displayMultiple02.c *

      *

      - * Workaround is to not close them at all if driver vendor is ATI. + * Workaround is to not close them at all if driver vendor is ATI + * during operation. + *

      + *

      + * With ATI X11 drivers all connections must be closed at JVM shutdown, + * otherwise a SIGSEGV (after JVM safepoint) will be caused. *

      */ public static final boolean ATI_HAS_XCLOSEDISPLAY_BUG = !Debug.isPropertyDefined("nativewindow.debug.X11Util.ATI_HAS_NO_XCLOSEDISPLAY_BUG", true); @@ -141,6 +146,14 @@ public class X11Util { } } + // not exactly thread safe, but good enough for our purpose, + // which is to tag a NamedDisplay uncloseable after creation. + private static Object globalLock = new Object(); + private static LongObjectHashMap openDisplayMap = new LongObjectHashMap(); // handle -> name + private static List openDisplayList = new ArrayList(); // open, no close attempt + private static List reusableDisplayList = new ArrayList(); // close attempt, marked uncloseable, for reuse + private static List pendingDisplayList = new ArrayList(); // all open (close attempt or reusable) in creation order + /** * Cleanup resources. *

      @@ -156,7 +169,7 @@ public class X11Util { System.err.println("X11Util.Display: Shutdown (JVM shutdown: "+isJVMShuttingDown+ ", open (no close attempt): "+openDisplayMap.size()+"/"+openDisplayList.size()+ ", reusable (open, marked uncloseable): "+reusableDisplayList.size()+ - ", pending (post closing): "+pendingDisplayList.size()+ + ", pending (open in creation order): "+pendingDisplayList.size()+ ")"); if(DEBUG) { Thread.dumpStack(); @@ -227,14 +240,6 @@ public class X11Util { private X11Util() {} - // not exactly thread safe, but good enough for our purpose, - // which is to tag a NamedDisplay uncloseable after creation. - private static Object globalLock = new Object(); - private static LongObjectHashMap openDisplayMap = new LongObjectHashMap(); // handle -> name - private static List openDisplayList = new ArrayList(); - private static List reusableDisplayList = new ArrayList(); - private static List pendingDisplayList = new ArrayList(); - public static class NamedDisplay { final String name; final long handle; @@ -296,23 +301,21 @@ public class X11Util { } /** - * Closing pending Display connections in reverse order. + * Closing pending Display connections in original creation order, if {@link #getMarkAllDisplaysUnclosable()} is true. * * @return number of closed Display connections */ - public static int closePendingDisplayConnections() { + private static int closePendingDisplayConnections() { int num=0; synchronized(globalLock) { - if(DEBUG) { - System.err.println("X11Util: Closing Pending X11 Display Connections in order of their creation: "+pendingDisplayList.size()); - } - for(int i=0; i Date: Thu, 27 Sep 2012 17:33:39 +0200 Subject: Fix Bug 616: X11: Remove XInitThreads() dependency while cleaning up device locking, resulting in a native-lock-free impl. The X11 implementation details of NativeWindow and NEWT used the X11 implicit locking facility XLockDisplay/XUnlockDisplay, enabled via XInitThreads(). The latter useage is complicated within an unsure environment where the initialization point of JOGL is unknown, but XInitThreads() requires to be called once and before any other X11 calls. The solution is simple and thorough, replace native X11 locking w/ 'application level' locking. Following this pattern actually cleans up a pretty messy part of X11 NativeWindow and NEWT, since the generalization of platform independent locking simplifies code. Simply using our RecursiveLock also speeds up locking, since it doesn't require JNI calls down to X11 anymore. It allows us to get rid of X11ToolkitLock and X11JAWTToolkitLock. Using the RecursiveLock also allows us to remove the shortcut of explicitly createing a NullToolkitLocked device for 'private' display connections. All devices use proper locking as claimed in their toolkit util 'requiresToolkitLock()' in X11Util, OSXUtil, .. Further more a bug has been fixed of X11ErrorHandler usage, i.e. we need to keep our handler alive at all times due to async X11 messaging behavior. This allows to remove the redundant code in X11/NEWT. The AbstractGraphicsDevice lifecycle has been fixed as well, i.e. called when closing NEWT's Display for all driver implementations. On the NEWT side the Display's AbstractGraphicsDevice semantics has been clarified, i.e. it's usage for EDT and lifecycle operations. Hence the X11 Display 2nd device for rendering operations has been moved to X11 Window where it belongs - and the X11 Display's default device used for EDT/lifecycle-ops as it should be. This allows running X11/NEWT properly with the default usage, where the Display instance and hence the EDT thread is shared with many Screen and Window. Rendering using NEWT Window is decoupled from it's shared Display lock via it's own native X11 display. Lock free AbstractGraphicsDevice impl. (Windows, OSX, ..) don't require any attention in this regard since they use NullToolkitLock. Tests: ====== This implementation has been tested manually with Mesa3d (soft, Intel), ATI and Nvidia on X11, Windows and OSX w/o any regressions found in any unit test. Issues on ATI: ============== Only on ATI w/o a composite renderer the unit tests expose a driver or WM bug where XCB claims a lack of locking. Setting env. var 'LIBXCB_ALLOW_SLOPPY_LOCK=true' is one workaround if users refuse to enable compositing. We may investigate this issue in more detail later on. --- make/scripts/tests.sh | 50 ++++- .../classes/jogamp/opengl/egl/EGLDisplayUtil.java | 3 +- .../jogamp/opengl/x11/glx/X11GLXContext.java | 37 +--- .../opengl/x11/glx/X11GLXDrawableFactory.java | 13 +- .../jogamp/nativewindow/x11/X11GraphicsDevice.java | 2 +- .../jogamp/nativewindow/x11/X11GraphicsScreen.java | 2 +- .../media/nativewindow/AbstractGraphicsDevice.java | 2 +- .../media/nativewindow/DefaultGraphicsDevice.java | 3 +- .../media/nativewindow/NativeWindowFactory.java | 99 ++------- .../javax/media/nativewindow/ToolkitLock.java | 18 +- .../jogamp/nativewindow/NullToolkitLock.java | 9 + .../jogamp/nativewindow/ResourceToolkitLock.java | 74 +++++++ .../nativewindow/SharedResourceToolkitLock.java | 141 +++++++++++++ .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 3 + .../nativewindow/jawt/x11/X11JAWTToolkitLock.java | 76 ------- .../nativewindow/jawt/x11/X11JAWTWindow.java | 3 +- .../jogamp/nativewindow/x11/X11ToolkitLock.java | 70 ------ .../classes/jogamp/nativewindow/x11/X11Util.java | 119 ++++------- .../awt/X11AWTGraphicsConfigurationFactory.java | 7 +- src/nativewindow/native/x11/Xmisc.c | 38 ++-- src/newt/classes/com/jogamp/newt/Display.java | 35 ++- src/newt/classes/com/jogamp/newt/NewtFactory.java | 2 +- src/newt/classes/com/jogamp/newt/Screen.java | 2 +- src/newt/classes/jogamp/newt/DisplayImpl.java | 79 ++++--- src/newt/classes/jogamp/newt/ScreenImpl.java | 3 +- src/newt/classes/jogamp/newt/WindowImpl.java | 33 +-- .../jogamp/newt/driver/awt/DisplayDriver.java | 4 +- .../jogamp/newt/driver/bcm/egl/DisplayDriver.java | 2 + .../newt/driver/intel/gdl/DisplayDriver.java | 1 + .../jogamp/newt/driver/macosx/DisplayDriver.java | 4 +- .../jogamp/newt/driver/windows/DisplayDriver.java | 1 + .../jogamp/newt/driver/x11/DisplayDriver.java | 65 ++---- .../jogamp/newt/driver/x11/ScreenDriver.java | 31 ++- .../jogamp/newt/driver/x11/WindowDriver.java | 107 +++++++--- src/newt/native/X11Common.h | 1 - src/newt/native/X11Display.c | 91 -------- src/newt/native/X11Window.c | 10 - .../junit/jogl/acore/InitConcurrentBaseNEWT.java | 219 +++++++++++++++++++ .../junit/jogl/acore/TestInitConcurrent01NEWT.java | 78 +++++++ .../junit/jogl/acore/TestInitConcurrent02NEWT.java | 78 +++++++ .../junit/jogl/acore/TestInitConcurrentNEWT.java | 235 --------------------- 41 files changed, 964 insertions(+), 886 deletions(-) create mode 100644 src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java create mode 100644 src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java delete mode 100644 src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTToolkitLock.java delete mode 100644 src/nativewindow/classes/jogamp/nativewindow/x11/X11ToolkitLock.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/InitConcurrentBaseNEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestInitConcurrent01NEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestInitConcurrent02NEWT.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestInitConcurrentNEWT.java (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 8a0a638ba..3dc983072 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -81,6 +81,7 @@ function jrun() { #D_ARGS="-Djogl.debug.GLDebugMessageHandler -Djogl.debug.TraceGL -Djogl.debug.DebugGL -Djogl.debug.GLSLCode -Djogl.debug.GLSLState" #D_ARGS="-Djogl.debug.GLDebugMessageHandler -Djogl.debug.DebugGL -Djogl.debug.TraceGL" #D_ARGS="-Djogamp.debug.NativeLibrary -Djogamp.debug.NativeLibrary.UseCurrentThreadLibLoader" + #D_ARGS="-Djogamp.debug.NativeLibrary" #D_ARGS="-Djogl.1thread=false -Djogl.debug.Threading" #D_ARGS="-Djogl.1thread=true -Djogl.debug.Threading" #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.TraceGL -Djogl.debug.GLContext.TraceSwitch -Djogl.debug=all" @@ -100,7 +101,6 @@ function jrun() { #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile" #D_ARGS="-Djogl.debug.GLProfile" - #D_ARGS="-Dnewt.debug.EDT -Dnativewindow.debug.ToolkitLock.TraceLock -Dnativewindow.debug.NativeWindow" #D_ARGS="-Dnativewindow.debug.NativeWindow" #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT" #D_ARGS="-Dnewt.debug.EDT -Dnewt.debug.Window -Djogl.debug.GLContext" @@ -109,6 +109,7 @@ function jrun() { #D_ARGS="-Dnativewindow.debug.X11Util -Dnativewindow.debug.X11Util.XSync" #D_ARGS="-Dnativewindow.debug.X11Util.XSync -Dnewt.debug.Window" #D_ARGS="-Djogl.debug.GLDrawable -Djogl.debug.GLContext" + #D_ARGS="-Dnativewindow.debug.NativeWindow -Dnativewindow.debug.X11Util" #D_ARGS="-Djogamp.common.utils.locks.Lock.timeout=3000 -Djogamp.debug.Lock -Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogamp.common.utils.locks.Lock.timeout=600000 -Djogamp.debug.Lock -Djogamp.debug.Lock.TraceLock" #D_ARGS="-Djogamp.common.utils.locks.Lock.timeout=600000 -Djogamp.debug.Lock -Djogamp.debug.Lock.TraceLock -Dnativewindow.debug.ToolkitLock.TraceLock" @@ -135,7 +136,9 @@ function jrun() { #D_ARGS="-Djogl.debug.Animator" #D_ARGS="-Dnativewindow.debug=all" #D_ARGS="-Djogl.debug.GLCanvas" - #D_ARGS="-Dnativewindow.debug.ToolkitLock.TraceLock" + #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.X11Util.XSync" + #D_ARGS="-Dnativewindow.debug.X11Util.XSync" + #D_ARGS="-Dnativewindow.debug.ToolkitLock" #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLCode -Djogl.debug.TraceGL" #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLState" #D_ARGS="-Djogamp.debug.JNILibLoader -Djogamp.debug.TempJarCache -Djogamp.debug.JarUtil" @@ -187,6 +190,8 @@ function jrun() { #export LD_LIBRARY_PATH=/opt-linux-x86_64/mesa-7.8.1/lib64:$LD_LIBRARY_PATH #export LD_LIBRARY_PATH=/usr/lib/mesa:/usr/lib32/mesa:$LD_LIBRARY_PATH #export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/mesa:/usr/lib/i386-linux-gnu/mesa:$LD_LIBRARY_PATH + #export LD_LIBRARY_PATH=`pwd`/lib/external/mesa/x86_64-linux-gnu:$LD_LIBRARY_PATH + #export LD_LIBRARY_PATH=`pwd`/lib/external/mesa/x86_64-linux-gnu/gallium:$LD_LIBRARY_PATH echo echo "Test Start: $*" echo @@ -194,10 +199,10 @@ function jrun() { echo echo $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $* #LIBGL_DRIVERS_PATH=/usr/lib/mesa:/usr/lib32/mesa \ - #gdb --args $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $* #LIBGL_DEBUG=verbose INTEL_STRICT_CONFORMANCE=1 INTEL_DEBUG="buf bat" \ #LIBGL_DEBUG=verbose MESA_DEBUG=true INTEL_STRICT_CONFORMANCE=1 \ - #LIBGL_DEBUG=verbose MESA_DEBUG=true LIBGL_ALWAYS_SOFTWARE=true \ + #export LIBGL_DEBUG=verbose MESA_DEBUG=true LIBGL_ALWAYS_SOFTWARE=true + #gdb --args $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $* $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $* echo echo "Test End: $*" @@ -239,7 +244,8 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile00NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextSurfaceLockNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug00NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug01NEWT $* @@ -250,6 +256,38 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* +# x11 no XinitThreads() specific tests (regressions, concurrent behavior) ! +# Deadlock: +# com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT2 - test01 +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT2 $* +# com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT - testEachWithAnimatorSharedOffscreen +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT $* +# +# XCB: +# +# com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState02NEWT - testShaderState01PerformanceDouble +#testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState02NEWT $* +# com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT - testWindowParenting02ReparentTop2WinReparentRecreate +#testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT $* +# com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT - winHopFrame2FrameDirectHop +#testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOOffThreadSharedContextMix2DemosES2NEWT $* + +#testnoawt com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle02NEWT +#testnoawt com.jogamp.opengl.test.junit.newt.TestWindows01NEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent01NEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent02NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMix2DemosES2NEWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT $* +#testnoawt com.jogamp.opengl.test.junit.newt.TestRemoteGLWindows01NEWT $* +#testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTEclipseGLCanvas01GLn $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT2 $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOOffThreadSharedContextMix2DemosES2NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOOnThreadSharedContext1DemoES2NEWT $* + + #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT $* @@ -322,7 +360,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWT02WindowClosing #testawt com.jogamp.opengl.test.junit.jogl.awt.text.TestAWTTextRendererUseVertexArrayBug464 #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT $* -testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWTAnalyzeBug455 $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWTBug450 $* diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java index ce2e824f5..0a603ab8a 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java @@ -71,10 +71,9 @@ public class EGLDisplayUtil { Thread.dumpStack(); } if( eglDisplayCounter.size() > 0) { - EGLDisplayUtil.dumpOpenDisplayConnections(); + dumpOpenDisplayConnections(); } } - return eglDisplayCounter.size(); } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java index e1e25be67..bdccc1047 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java @@ -172,7 +172,6 @@ public abstract class X11GLXContext extends GLContextImpl { glXMakeContextCurrent(display, 0, 0, 0); GLX.glXDestroyContext(display, ctx); } - private static final int ctx_arb_attribs_idx_major = 0; private static final int ctx_arb_attribs_idx_minor = 2; private static final int ctx_arb_attribs_idx_flags = 6; @@ -228,14 +227,14 @@ public abstract class X11GLXContext extends GLContextImpl { X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration)drawable.getNativeSurface().getGraphicsConfiguration(); AbstractGraphicsDevice device = config.getScreen().getDevice(); - long display = device.getHandle(); + final long display = device.getHandle(); try { // critical path, a remote display might not support this command, // hence we need to catch the X11 Error within this block. - X11Lib.XSync(display, false); + X11Util.setX11ErrorHandler(true, DEBUG ? false : true); // make sure X11 error handler is set ctx = _glXExt.glXCreateContextAttribsARB(display, config.getFBConfig(), share, direct, attribs); - X11Lib.XSync(display, false); + if(DEBUG) { X11Lib.XSync(display, false); } } catch (RuntimeException re) { if(DEBUG) { Throwable t = new Throwable(getThreadName()+": Info: X11GLXContext.createContextARBImpl glXCreateContextAttribsARB failed with "+getGLVersion(major, minor, ctp, "@creation"), re); @@ -263,16 +262,6 @@ public abstract class X11GLXContext extends GLContextImpl { @Override protected boolean createImpl(GLContextImpl shareWith) { - // covers the whole context creation loop incl createContextARBImpl and destroyContextARBImpl - X11Util.setX11ErrorHandler(true, DEBUG ? false : true); - try { - return createImplRaw(shareWith); - } finally { - X11Util.setX11ErrorHandler(false, false); - } - } - - private boolean createImplRaw(GLContextImpl shareWith) { boolean direct = true; // try direct always isDirect = false; // fall back @@ -401,14 +390,9 @@ public abstract class X11GLXContext extends GLContextImpl { protected void makeCurrentImpl() throws GLException { long dpy = drawable.getNativeSurface().getDisplayHandle(); - if (GLX.glXGetCurrentContext() != contextHandle) { - X11Util.setX11ErrorHandler(true, DEBUG ? false : true); - try { - if (!glXMakeContextCurrent(dpy, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) { - throw new GLException(getThreadName()+": Error making context current: "+this); - } - } finally { - X11Util.setX11ErrorHandler(false, false); + if (GLX.glXGetCurrentContext() != contextHandle) { + if (!glXMakeContextCurrent(dpy, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) { + throw new GLException(getThreadName()+": Error making context current: "+this); } } } @@ -416,13 +400,8 @@ public abstract class X11GLXContext extends GLContextImpl { @Override protected void releaseImpl() throws GLException { long display = drawable.getNativeSurface().getDisplayHandle(); - X11Util.setX11ErrorHandler(true, DEBUG ? false : true); - try { - if (!glXMakeContextCurrent(display, 0, 0, 0)) { - throw new GLException(getThreadName()+": Error freeing OpenGL context"); - } - } finally { - X11Util.setX11ErrorHandler(false, false); + if (!glXMakeContextCurrent(display, 0, 0, 0)) { + throw new GLException(getThreadName()+": Error freeing OpenGL context"); } } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index ca5cd424b..03c661565 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -47,7 +47,6 @@ import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.NativeSurface; -import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; import javax.media.nativewindow.UpstreamSurfaceHook; import javax.media.nativewindow.VisualIDHolder; @@ -230,11 +229,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { @Override public SharedResourceRunner.Resource createSharedResource(String connection) { - final X11GraphicsDevice sharedDevice = - new X11GraphicsDevice(X11Util.openDisplay(connection), AbstractGraphicsDevice.DEFAULT_UNIT, - true); // own non-shared display connection, w/ locking - // new X11GraphicsDevice(X11Util.openDisplay(connection), AbstractGraphicsDevice.DEFAULT_UNIT, - // NativeWindowFactory.getNullToolkitLock(), true); // own non-shared display connection, w/o locking + final X11GraphicsDevice sharedDevice = new X11GraphicsDevice(X11Util.openDisplay(connection), AbstractGraphicsDevice.DEFAULT_UNIT, true); sharedDevice.lock(); try { final X11GraphicsScreen sharedScreen = new X11GraphicsScreen(sharedDevice, sharedDevice.getDefaultScreen()); @@ -509,8 +504,8 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final X11GraphicsDevice device; if(createNewDevice) { - // Null X11 locking, due to private non-shared Display handle - device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), NativeWindowFactory.getNullToolkitLock(), true); + // Null X11 resource locking, due to private non-shared Display handle + device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), true); } else { device = (X11GraphicsDevice)deviceReq; } @@ -531,7 +526,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { @Override protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { - final X11GraphicsDevice device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), NativeWindowFactory.getNullToolkitLock(), true); + final X11GraphicsDevice device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), true); final X11GraphicsScreen screen = new X11GraphicsScreen(device, screenIdx); final int xvisualID = X11Lib.GetVisualIDFromWindow(device.getHandle(), windowHandle); if(VisualIDHolder.VID_UNDEFINED == xvisualID) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index 152384980..2e4099c1b 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -73,7 +73,7 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl /** * @param display the Display connection - * @param locker custom {@link javax.media.nativewindow.ToolkitLock}, eg to force null locking in NEWT + * @param locker custom {@link javax.media.nativewindow.ToolkitLock}, eg to force null locking w/ private connection * @see DefaultGraphicsDevice#DefaultGraphicsDevice(String, String, int, long, ToolkitLock) */ public X11GraphicsDevice(long display, int unitID, ToolkitLock locker, boolean owner) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java index 5f3c220ca..7ab5bd6aa 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java @@ -63,7 +63,7 @@ public class X11GraphicsScreen extends DefaultGraphicsScreen implements Cloneabl private static int fetchScreen(X11GraphicsDevice device, int screen) { // It still could be an AWT hold handle .. - if(X11Util.XineramaIsEnabled(device.getHandle())) { + if(X11Util.XineramaIsEnabled(device)) { screen = 0; // Xinerama -> 1 screen } return screen; diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java index 756e4451b..5eaaa6613 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java @@ -131,7 +131,7 @@ public interface AbstractGraphicsDevice extends Cloneable { /** * Optionally closing the device if handle is not null. *

      - * The default implementation is a NOP, just setting the handle to null. + * The default implementation {@link ToolkitLock#dispose() dispose} it's {@link ToolkitLock} and sets the handle to null. *

      *

      * Example implementations like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice} diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java index 583fde07f..b16b0c75c 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java @@ -153,6 +153,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice @Override public boolean close() { + toolkitLock.dispose(); if(0 != handle) { handle = 0; return true; @@ -162,7 +163,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice @Override public String toString() { - return getClass().getSimpleName()+"[type "+getType()+", connection "+getConnection()+", unitID "+getUnitID()+", handle 0x"+Long.toHexString(getHandle())+"]"; + return getClass().getSimpleName()+"[type "+getType()+", connection "+getConnection()+", unitID "+getUnitID()+", handle 0x"+Long.toHexString(getHandle())+", "+toolkitLock+"]"; } /** diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 40aaa8a25..4f4bb629b 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -33,7 +33,6 @@ package javax.media.nativewindow; -import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; @@ -43,6 +42,7 @@ import java.util.Map; import jogamp.nativewindow.Debug; import jogamp.nativewindow.NativeWindowFactoryImpl; +import jogamp.nativewindow.ResourceToolkitLock; import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; @@ -93,13 +93,6 @@ public abstract class NativeWindowFactory { private static ToolkitLock jawtUtilJAWTToolkitLock; - public static final String X11JAWTToolkitLockClassName = "jogamp.nativewindow.jawt.x11.X11JAWTToolkitLock" ; - public static final String X11ToolkitLockClassName = "jogamp.nativewindow.x11.X11ToolkitLock" ; - - private static Class x11JAWTToolkitLockClass; - private static Constructor x11JAWTToolkitLockConstructor; - private static Class x11ToolkitLockClass; - private static Constructor x11ToolkitLockConstructor; private static boolean requiresToolkitLock; private static volatile boolean isJVMShuttingDown = false; @@ -266,16 +259,6 @@ public abstract class NativeWindowFactory { // register either our default factory or (if exist) the X11/AWT one -> AWT Component registerFactory(ReflectionUtil.getClass(ReflectionUtil.AWTNames.ComponentClass, false, cl), factory); } - - if( TYPE_X11 == nativeWindowingTypePure ) { - // passing through RuntimeException if not exists intended - x11ToolkitLockClass = ReflectionUtil.getClass(X11ToolkitLockClassName, false, cl); - x11ToolkitLockConstructor = ReflectionUtil.getConstructor(x11ToolkitLockClass, new Class[] { long.class } ); - if( isAWTAvailable() ) { - x11JAWTToolkitLockClass = ReflectionUtil.getClass(X11JAWTToolkitLockClassName, false, cl); - x11JAWTToolkitLockConstructor = ReflectionUtil.getConstructor(x11JAWTToolkitLockClass, new Class[] { long.class } ); - } - } if(DEBUG) { System.err.println("NativeWindowFactory requiresToolkitLock "+requiresToolkitLock); @@ -300,6 +283,7 @@ public abstract class NativeWindowFactory { GraphicsConfigurationFactory.shutdown(); } shutdownNativeImpl(NativeWindowFactory.class.getClassLoader()); // always re-shutdown + // SharedResourceToolkitLock.shutdown(DEBUG); // not used yet if(DEBUG) { System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() END JVM Shutdown "+isJVMShuttingDown); } @@ -358,16 +342,9 @@ public abstract class NativeWindowFactory { /** * Provides the default {@link ToolkitLock} for type, a singleton instance. - *
      *

        - *
      • If {@link #initSingleton(boolean) initSingleton( firstUIActionOnProcess := false )}
      • - *
          - *
        • If AWT-type and native-X11-type and AWT-available
        • - *
            - *
          • return {@link #getAWTToolkitLock()}
          • - *
          - *
        - *
      • Otherwise return {@link #getNullToolkitLock()}
      • + *
      • JAWT {@link ToolkitLock} if required and AWT available, otherwise
      • + *
      • {@link jogamp.nativewindow.NullToolkitLock}
      • *
      */ public static ToolkitLock getDefaultToolkitLock(String type) { @@ -390,84 +367,36 @@ public abstract class NativeWindowFactory { /** * Creates the default {@link ToolkitLock} for type and deviceHandle. - *
      *
        - *
      • If {@link #initSingleton(boolean) initSingleton( firstUIActionOnProcess := false )}
      • - *
          - *
        • If X11 type
        • - *
            - *
          • return {@link jogamp.nativewindow.x11.X11ToolkitLock}
          • - *
          - *
        - *
      • Otherwise return {@link jogamp.nativewindow.NullToolkitLock}
      • + *
      • {@link jogamp.nativewindow.ResourceToolkitLock} if required, otherwise
      • + *
      • {@link jogamp.nativewindow.NullToolkitLock}
      • *
      */ public static ToolkitLock createDefaultToolkitLock(String type, long deviceHandle) { if( requiresToolkitLock() ) { - if( TYPE_X11 == type ) { - if( 0== deviceHandle ) { - throw new RuntimeException("JAWTUtil.createDefaultToolkitLock() called with NULL device but on X11"); - } - return createX11ToolkitLock(deviceHandle); - } + return ResourceToolkitLock.create(); } return NativeWindowFactoryImpl.getNullToolkitLock(); } /** * Creates the default {@link ToolkitLock} for type and deviceHandle. - *
      *
        - *
      • If {@link #initSingleton(boolean) initSingleton( firstUIActionOnProcess := false )}
      • - *
          - *
        • If X11 type
        • - *
            - *
          • If shared-AWT-type and AWT available
          • - *
              - *
            • return {@link jogamp.nativewindow.jawt.x11.X11JAWTToolkitLock}
            • - *
            - *
          • else return {@link jogamp.nativewindow.x11.X11ToolkitLock}
          • - *
          - *
        - *
      • Otherwise return {@link jogamp.nativewindow.NullToolkitLock}
      • + *
      • JAWT {@link ToolkitLock} if required and AWT available,
      • + *
      • {@link jogamp.nativewindow.ResourceToolkitLock} if required, otherwise
      • + *
      • {@link jogamp.nativewindow.NullToolkitLock}
      • *
      */ public static ToolkitLock createDefaultToolkitLock(String type, String sharedType, long deviceHandle) { if( requiresToolkitLock() ) { - if( TYPE_X11 == type ) { - if( 0== deviceHandle ) { - throw new RuntimeException("JAWTUtil.createDefaultToolkitLock() called with NULL device but on X11"); - } - if( TYPE_AWT == sharedType && isAWTAvailable() ) { - return createX11AWTToolkitLock(deviceHandle); - } - return createX11ToolkitLock(deviceHandle); + if( TYPE_AWT == sharedType && isAWTAvailable() ) { + return getAWTToolkitLock(); } + return ResourceToolkitLock.create(); } return NativeWindowFactoryImpl.getNullToolkitLock(); } - - protected static ToolkitLock createX11AWTToolkitLock(long deviceHandle) { - try { - if(DEBUG) { - System.err.println("NativeWindowFactory.createX11AWTToolkitLock(0x"+Long.toHexString(deviceHandle)+")"); - // Thread.dumpStack(); - } - return (ToolkitLock) x11JAWTToolkitLockConstructor.newInstance(new Object[]{new Long(deviceHandle)}); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - - protected static ToolkitLock createX11ToolkitLock(long deviceHandle) { - try { - return (ToolkitLock) x11ToolkitLockConstructor.newInstance(new Object[]{new Long(deviceHandle)}); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - - + /** Returns the appropriate NativeWindowFactory to handle window objects of the given type. The windowClass might be {@link NativeWindow NativeWindow}, in which case the client has diff --git a/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java b/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java index 30f9660f0..18b7cf5d9 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java @@ -33,12 +33,26 @@ import jogamp.nativewindow.Debug; /** * Marker for a singleton global recursive blocking lock implementation, * optionally locking a native windowing toolkit as well. - *
      - * One use case is the AWT locking on X11, see {@link jogamp.nativewindow.jawt.JAWTToolkitLock}. + *

      + * Toolkit locks are created solely via {@link NativeWindowFactory}. + *

      + *

      + * One use case is the AWT locking on X11, see {@link NativeWindowFactory#createDefaultToolkitLock(String, long)}. + *

      */ public interface ToolkitLock { public static final boolean TRACE_LOCK = Debug.isPropertyDefined("nativewindow.debug.ToolkitLock.TraceLock", true); public void lock(); public void unlock(); + + /** + * Dispose this instance. + *

      + * Shall be called when instance is no more required. + *

      + * This allows implementations sharing a lock via resources + * to decrease the reference counter. + */ + public void dispose(); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java index 1af6bf279..e59910138 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java @@ -50,4 +50,13 @@ public class NullToolkitLock implements ToolkitLock { public final void unlock() { if(TRACE_LOCK) { System.err.println("NullToolkitLock.unlock()"); } } + + public final void dispose() { + // nop + } + + public String toString() { + return "NullToolkitLock[]"; + } + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java new file mode 100644 index 000000000..a3b0804fa --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java @@ -0,0 +1,74 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.nativewindow; + +import javax.media.nativewindow.ToolkitLock; + +import com.jogamp.common.util.locks.LockFactory; +import com.jogamp.common.util.locks.RecursiveLock; + +/** + * Implementing a resource based recursive {@link javax.media.nativewindow.ToolkitLock}. + *

      + * A resource handle maybe used within a unique object + * and can be synchronized across threads via an instance of ResourceToolkitLock. + *

      + */ +public class ResourceToolkitLock implements ToolkitLock { + public static final boolean DEBUG = Debug.debug("ToolkitLock"); + + public static final ResourceToolkitLock create() { + return new ResourceToolkitLock(); + } + + private final RecursiveLock lock; + + private ResourceToolkitLock() { + this.lock = LockFactory.createRecursiveLock(); + } + + + public final void lock() { + if(TRACE_LOCK) { System.err.println("ResourceToolkitLock.lock()"); } + lock.lock(); + } + + public final void unlock() { + if(TRACE_LOCK) { System.err.println("ResourceToolkitLock.unlock()"); } + lock.unlock(); + } + + public final void dispose() { + // nop + } + + public String toString() { + return "ResourceToolkitLock[obj 0x"+Integer.toHexString(hashCode())+", isOwner "+lock.isOwner(Thread.currentThread())+", "+lock.toString()+"]"; + } +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java new file mode 100644 index 000000000..5d7ae8abb --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java @@ -0,0 +1,141 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.nativewindow; + +import java.util.Iterator; + +import javax.media.nativewindow.ToolkitLock; + +import com.jogamp.common.util.LongObjectHashMap; +import com.jogamp.common.util.locks.LockFactory; +import com.jogamp.common.util.locks.RecursiveLock; + +/** + * Implementing a shared resource based recursive {@link javax.media.nativewindow.ToolkitLock}. + *

      + * A resource handle maybe used within many objects + * and can be synchronized across threads via an unique instance of SharedResourceToolkitLock. + *

      + *

      + * Implementation holds a synchronized map from handle to reference counted {@link SharedResourceToolkitLock}. + * New elements are added via {@link #get(long)} if new + * and removed via {@link #dispose()} if no more referenced. + *

      + */ +public class SharedResourceToolkitLock implements ToolkitLock { + public static final boolean DEBUG = Debug.debug("ToolkitLock"); + private static final LongObjectHashMap handle2Lock; + static { + handle2Lock = new LongObjectHashMap(); + handle2Lock.setKeyNotFoundValue(null); + } + + /** + * @return number of unclosed EGL Displays.
      + */ + public static int shutdown(boolean verbose) { + if(DEBUG || verbose || handle2Lock.size() > 0 ) { + System.err.println("SharedResourceToolkitLock: Shutdown (open: "+handle2Lock.size()+")"); + if(DEBUG) { + Thread.dumpStack(); + } + if( handle2Lock.size() > 0) { + dumpOpenDisplayConnections(); + } + } + return handle2Lock.size(); + } + + public static void dumpOpenDisplayConnections() { + System.err.println("SharedResourceToolkitLock: Open ResourceToolkitLock's: "+handle2Lock.size()); + int i=0; + for(Iterator iter = handle2Lock.iterator(); iter.hasNext(); i++) { + final LongObjectHashMap.Entry e = iter.next(); + System.err.println("SharedResourceToolkitLock: Open["+i+"]: "+e.value); + } + } + + public static final SharedResourceToolkitLock get(long handle) { + SharedResourceToolkitLock res; + synchronized(handle2Lock) { + res = (SharedResourceToolkitLock) handle2Lock.get(handle); + if( null == res ) { + res = new SharedResourceToolkitLock(handle); + res.refCount++; + handle2Lock.put(handle, res); + if(DEBUG || TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.get() * NEW *: "+res); } + } else { + res.refCount++; + if(DEBUG || TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.get() * EXIST *: "+res); } + } + } + return res; + } + + private final RecursiveLock lock; + private final long handle; + private volatile int refCount; + + private SharedResourceToolkitLock(long handle) { + this.lock = LockFactory.createRecursiveLock(); + this.handle = handle; + this.refCount = 0; + } + + + public final void lock() { + if(TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.lock()"); } + lock.lock(); + } + + public final void unlock() { + if(TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.unlock()"); } + lock.unlock(); + } + + public final void dispose() { + if(0 < refCount) { // volatile OK + synchronized(handle2Lock) { + refCount--; + if(0 == refCount) { + if(DEBUG || TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.dispose() * REMOV *: "+this); } + handle2Lock.remove(handle); + } else { + if(DEBUG || TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.dispose() * DOWN *: "+this); } + } + } + } else { + if(DEBUG || TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.dispose() * NULL *: "+this); } + } + } + + public String toString() { + return "SharedResourceToolkitLock[refCount "+refCount+", handle 0x"+Long.toHexString(handle)+", obj 0x"+Integer.toHexString(hashCode())+", isOwner "+lock.isOwner(Thread.currentThread())+", "+lock.toString()+"]"; + } +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index f1e8a786a..7c934b154 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -237,6 +237,9 @@ public class JAWTUtil { public final void unlock() { JAWTUtil.unlockToolkit(); } + public final void dispose() { + // nop + } }; // trigger native AWT toolkit / properties initialization diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTToolkitLock.java deleted file mode 100644 index 743d371b7..000000000 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTToolkitLock.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ -package jogamp.nativewindow.jawt.x11; - -import jogamp.nativewindow.jawt.*; -import jogamp.nativewindow.x11.X11Lib; -import jogamp.nativewindow.x11.X11Util; -import javax.media.nativewindow.ToolkitLock; - -import com.jogamp.common.util.locks.LockFactory; -import com.jogamp.common.util.locks.RecursiveLock; - -/** - * Implementing a recursive {@link javax.media.nativewindow.ToolkitLock} - * utilizing JAWT's AWT lock via {@link JAWTUtil#lockToolkit()} and {@link X11Util#XLockDisplay(long)}. - *
      - * This strategy should only be used if AWT is using the underlying native windowing toolkit - * in a not intrinsic thread safe manner, e.g. under X11 where no XInitThreads() call - * is issued before any other X11 usage. This is the current situation for e.g. Webstart or Applets. - */ -public class X11JAWTToolkitLock implements ToolkitLock { - long displayHandle; - RecursiveLock lock; - - public X11JAWTToolkitLock(long displayHandle) { - this.displayHandle = displayHandle; - if(!X11Util.isNativeLockAvailable()) { - lock = LockFactory.createRecursiveLock(); - } - } - - public final void lock() { - if(TRACE_LOCK) { System.err.println("X11JAWTToolkitLock.lock() - native: "+(null==lock)); } - JAWTUtil.lockToolkit(); - if(null == lock) { - X11Lib.XLockDisplay(displayHandle); - } else { - lock.lock(); - } - } - - public final void unlock() { - if(TRACE_LOCK) { System.err.println("X11JAWTToolkitLock.unlock() - native: "+(null==lock)); } - if(null == lock) { - X11Lib.XUnlockDisplay(displayHandle); - } else { - lock.unlock(); - } - JAWTUtil.unlockToolkit(); - } -} diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java index 736718de8..467809284 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java @@ -127,7 +127,8 @@ public class X11JAWTWindow extends JAWTWindow { } protected Point getLocationOnScreenNativeImpl(int x, int y) { - return X11Lib.GetRelativeLocation( getDisplayHandle(), getScreenIndex(), getWindowHandle(), 0 /*root win*/, x, y); + // surface is locked and hence the device + return X11Lib.GetRelativeLocation(getDisplayHandle(), getScreenIndex(), getWindowHandle(), 0 /*root win*/, x, y); } // Variables for lockSurface/unlockSurface diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11ToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11ToolkitLock.java deleted file mode 100644 index 5166ef577..000000000 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11ToolkitLock.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ -package jogamp.nativewindow.x11; - -import javax.media.nativewindow.ToolkitLock; - -import com.jogamp.common.util.locks.LockFactory; -import com.jogamp.common.util.locks.RecursiveLock; - -/** - * Implementing a recursive {@link javax.media.nativewindow.ToolkitLock} - * utilizing {@link X11Util#XLockDisplay(long)}. - *
      - * This strategy should not be used in case XInitThreads() is being used, - * or a higher level toolkit lock is required, ie AWT lock. - */ -public class X11ToolkitLock implements ToolkitLock { - long displayHandle; - RecursiveLock lock; - - public X11ToolkitLock(long displayHandle) { - this.displayHandle = displayHandle; - if(!X11Util.isNativeLockAvailable()) { - lock = LockFactory.createRecursiveLock(); - } - } - - public final void lock() { - if(TRACE_LOCK) { System.err.println("X11ToolkitLock.lock() - native: "+(null==lock)); } - if(null == lock) { - X11Lib.XLockDisplay(displayHandle); - } else { - lock.lock(); - } - } - - public final void unlock() { - if(TRACE_LOCK) { System.err.println("X11ToolkitLock.unlock() - native: "+(null==lock)); } - if(null == lock) { - X11Lib.XUnlockDisplay(displayHandle); - } else { - lock.unlock(); - } - } -} diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 2ea75c7fb..60f54eb3c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -42,8 +42,8 @@ import javax.media.nativewindow.NativeWindowFactory; import jogamp.nativewindow.Debug; import jogamp.nativewindow.NWJNILibLoader; - import com.jogamp.common.util.LongObjectHashMap; +import com.jogamp.nativewindow.x11.X11GraphicsDevice; /** * Contains a thread safe X11 utility to retrieve display connections. @@ -80,25 +80,15 @@ public class X11Util { */ public static final boolean ATI_HAS_XCLOSEDISPLAY_BUG = !Debug.isPropertyDefined("nativewindow.debug.X11Util.ATI_HAS_NO_XCLOSEDISPLAY_BUG", true); - /** Value is true, best 'stable' results if always using XInitThreads(). */ - public static final boolean XINITTHREADS_ALWAYS_ENABLED = true; - - /** Value is true, best 'stable' results if not using XLockDisplay/XUnlockDisplay at all. */ - public static final boolean HAS_XLOCKDISPLAY_BUG = true; - public static final boolean DEBUG = Debug.debug("X11Util"); public static final boolean XSYNC_ENABLED = Debug.isPropertyDefined("nativewindow.debug.X11Util.XSync", true); public static final boolean XERROR_STACKDUMP = DEBUG || Debug.isPropertyDefined("nativewindow.debug.X11Util.XErrorStackDump", true); private static final boolean TRACE_DISPLAY_LIFECYCLE = Debug.isPropertyDefined("nativewindow.debug.X11Util.TraceDisplayLifecycle", true); private static String nullDisplayName = null; - private static boolean isX11LockAvailable = false; - private static boolean requiresX11Lock = true; private static volatile boolean isInit = false; private static boolean markAllDisplaysUnclosable = false; // ATI/AMD X11 driver issues - private static int setX11ErrorHandlerRecCount = 0; private static Object setX11ErrorHandlerLock = new Object(); - /** * Called by {@link NativeWindowFactory#initSingleton()} @@ -115,9 +105,7 @@ public class X11Util { throw new NativeWindowException("NativeWindow X11 native library load error."); } - final boolean callXInitThreads = XINITTHREADS_ALWAYS_ENABLED ; - final boolean isXInitThreadsOK = initialize0( callXInitThreads, XERROR_STACKDUMP); - isX11LockAvailable = isXInitThreadsOK && !HAS_XLOCKDISPLAY_BUG ; + final boolean isInitOK = initialize0( XERROR_STACKDUMP ); final long dpy = X11Lib.XOpenDisplay(null); if(0 != dpy) { @@ -134,9 +122,7 @@ public class X11Util { } if(DEBUG) { - System.err.println("X11Util requiresX11Lock "+requiresX11Lock+ - ", XInitThreads [called "+callXInitThreads+", OK "+isXInitThreadsOK+"]"+ - ", isX11LockAvailable "+isX11LockAvailable+ + System.err.println("X11Util init OK "+isInitOK+"]"+ ", X11 Display(NULL) <"+nullDisplayName+">"+ ", XSynchronize Enabled: "+XSYNC_ENABLED); // Thread.dumpStack(); @@ -199,31 +185,14 @@ public class X11Util { } } } - - public static synchronized boolean isNativeLockAvailable() { - return isX11LockAvailable; - } - - public static synchronized boolean requiresToolkitLock() { - return requiresX11Lock; + + public static boolean requiresToolkitLock() { + return true; // JAWT locking: yes, instead of native X11 locking w use a recursive lock. } - + public static void setX11ErrorHandler(boolean onoff, boolean quiet) { synchronized(setX11ErrorHandlerLock) { - if(onoff) { - if(0==setX11ErrorHandlerRecCount) { - setX11ErrorHandler0(true, quiet); - } - setX11ErrorHandlerRecCount++; - } else { - if(0 >= setX11ErrorHandlerRecCount) { - throw new InternalError(); - } - setX11ErrorHandlerRecCount--; - if(0==setX11ErrorHandlerRecCount) { - setX11ErrorHandler0(false, false); - } - } + setX11ErrorHandler0(onoff, quiet); } } @@ -492,52 +461,50 @@ public class X11Util { *******************************/ public static long XOpenDisplay(String arg0) { - NativeWindowFactory.getDefaultToolkitLock().lock(); - try { - long handle = X11Lib.XOpenDisplay(arg0); - if(XSYNC_ENABLED && 0 != handle) { - X11Lib.XSynchronize(handle, true); - } - if(TRACE_DISPLAY_LIFECYCLE) { - System.err.println(Thread.currentThread()+" - X11Util.XOpenDisplay("+arg0+") 0x"+Long.toHexString(handle)); - // Thread.dumpStack(); - } - return handle; - } finally { - NativeWindowFactory.getDefaultToolkitLock().unlock(); + long handle = X11Lib.XOpenDisplay(arg0); + if(XSYNC_ENABLED && 0 != handle) { + X11Lib.XSynchronize(handle, true); + } + if(TRACE_DISPLAY_LIFECYCLE) { + System.err.println(Thread.currentThread()+" - X11Util.XOpenDisplay("+arg0+") 0x"+Long.toHexString(handle)); + // Thread.dumpStack(); } + return handle; } public static int XCloseDisplay(long display) { - NativeWindowFactory.getDefaultToolkitLock().lock(); + if(TRACE_DISPLAY_LIFECYCLE) { + System.err.println(Thread.currentThread()+" - X11Util.XCloseDisplay() 0x"+Long.toHexString(display)); + // Thread.dumpStack(); + } + int res = -1; try { - if(TRACE_DISPLAY_LIFECYCLE) { - System.err.println(Thread.currentThread()+" - X11Util.XCloseDisplay() 0x"+Long.toHexString(display)); - // Thread.dumpStack(); - } - int res = -1; - X11Util.setX11ErrorHandler(true, DEBUG ? false : true); - try { - res = X11Lib.XCloseDisplay(display); - } catch (Exception ex) { - System.err.println("X11Util: Catched Exception:"); - ex.printStackTrace(); - } finally { - X11Util.setX11ErrorHandler(false, false); - } - return res; - } finally { - NativeWindowFactory.getDefaultToolkitLock().unlock(); + res = X11Lib.XCloseDisplay(display); + } catch (Exception ex) { + System.err.println("X11Util: Catched Exception:"); + ex.printStackTrace(); } + return res; } static volatile boolean XineramaFetched = false; static long XineramaLibHandle = 0; static long XineramaQueryFunc = 0; - public static boolean XineramaIsEnabled(long display) { - if(0==display) { - throw new IllegalArgumentException("Display NULL"); + public static boolean XineramaIsEnabled(X11GraphicsDevice device) { + if(null == device) { + throw new IllegalArgumentException("X11 Display device is NULL"); + } + device.lock(); + try { + return XineramaIsEnabled(device.getHandle()); + } finally { + device.unlock(); + } + } + public static boolean XineramaIsEnabled(long displayHandle) { + if( 0 == displayHandle ) { + throw new IllegalArgumentException("X11 Display handle is NULL"); } if(!XineramaFetched) { // volatile: ok synchronized(X11Util.class) { @@ -551,9 +518,9 @@ public class X11Util { } } if(0!=XineramaQueryFunc) { - final boolean res = X11Lib.XineramaIsEnabled(XineramaQueryFunc, display); + final boolean res = X11Lib.XineramaIsEnabled(XineramaQueryFunc, displayHandle); if(DEBUG) { - System.err.println("XineramaIsEnabled: "+res); + System.err.println("XineramaIsEnabled: 0x"+Long.toHexString(displayHandle)+": "+res); } return res; } else if(DEBUG) { @@ -566,7 +533,7 @@ public class X11Util { private static final String getCurrentThreadName() { return Thread.currentThread().getName(); } // Callback for JNI private static final void dumpStack() { Thread.dumpStack(); } // Callback for JNI - private static native boolean initialize0(boolean firstUIActionOnProcess, boolean debug); + private static native boolean initialize0(boolean debug); private static native void shutdown0(); private static native void setX11ErrorHandler0(boolean onoff, boolean quiet); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java b/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java index 1de03e8be..b152f0f97 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java @@ -91,7 +91,7 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac final long displayHandleAWT = X11SunJDKReflection.graphicsDeviceGetDisplay(device); final long displayHandle; - boolean owner = false; + final boolean owner; if(0==displayHandleAWT) { displayHandle = X11Util.openDisplay(null); owner = true; @@ -112,9 +112,8 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac System.err.println(getThreadName()+" - X11AWTGraphicsConfigurationFactory: AWT dpy "+displayName+" / "+toHexString(displayHandleAWT)+", create X11 display "+toHexString(displayHandle)); } } - final ToolkitLock lock = owner ? - NativeWindowFactory.getDefaultToolkitLock(NativeWindowFactory.TYPE_AWT) : // own non-shared X11 display connection, no X11 lock - NativeWindowFactory.createDefaultToolkitLock(NativeWindowFactory.TYPE_X11, NativeWindowFactory.TYPE_AWT, displayHandle); + // Global JAWT lock required - No X11 resource locking due to private display connection + final ToolkitLock lock = NativeWindowFactory.getDefaultToolkitLock(NativeWindowFactory.TYPE_AWT); final X11GraphicsDevice x11Device = new X11GraphicsDevice(displayHandle, AbstractGraphicsDevice.DEFAULT_UNIT, lock, owner); final X11GraphicsScreen x11Screen = new X11GraphicsScreen(x11Device, awtScreen.getIndex()); if(DEBUG) { diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index fcba8580c..afdd413eb 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -178,11 +178,14 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) char threadName[80]; char errCodeStr[80]; char reqCodeStr[80]; - int shallBeDetached = 0; - JNIEnv *jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); + JNIEnv *jniEnv = NULL; + if( errorHandlerDebug || errorHandlerThrowException ) { + jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); + } (void) NativewindowCommon_GetStaticStringMethod(jniEnv, X11UtilClazz, getCurrentThreadNameID, threadName, sizeof(threadName), "n/a"); + snprintf(errCodeStr, sizeof(errCodeStr), "%d", e->request_code); XGetErrorDatabaseText(dpy, "XRequest", errCodeStr, "Unknown", reqCodeStr, sizeof(reqCodeStr)); XGetErrorText(dpy, e->error_code, errCodeStr, sizeof(errCodeStr)); @@ -191,7 +194,7 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) threadName, e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, (int)e->request_code, (int)e->minor_code, reqCodeStr); - if( errorHandlerDebug ) { + if( errorHandlerDebug && NULL != jniEnv ) { (*jniEnv)->CallStaticVoidMethod(jniEnv, X11UtilClazz, dumpStackID); } @@ -246,16 +249,17 @@ static int x11IOErrorHandler(Display *dpy) { const char * dpyName = XDisplayName(NULL); const char * errnoStr = strerror(errno); - char threadName[80]; int shallBeDetached = 0; - JNIEnv *jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); - - (void) NativewindowCommon_GetStaticStringMethod(jniEnv, X11UtilClazz, getCurrentThreadNameID, threadName, sizeof(threadName), "n/a"); + JNIEnv *jniEnv = NULL; - fprintf(stderr, "Nativewindow X11 IOError (Thread %s): Display %p (%s): %s\n", threadName, dpy, dpyName, errnoStr); + fprintf(stderr, "Nativewindow X11 IOError: Display %p (%s): %s\n", dpy, dpyName, errnoStr); (*jniEnv)->CallStaticVoidMethod(jniEnv, X11UtilClazz, dumpStackID); + jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); if (NULL != jniEnv) { + char threadName[80]; + (void) NativewindowCommon_GetStaticStringMethod(jniEnv, X11UtilClazz, getCurrentThreadNameID, threadName, sizeof(threadName), "n/a"); + NativewindowCommon_FatalError(jniEnv, "Nativewindow X11 IOError (Thread %s): Display %p (%s): %s", threadName, dpy, dpyName, errnoStr); if (shallBeDetached) { @@ -305,6 +309,7 @@ Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass clazz, jboo _initClazzAccess(env); x11IOErrorHandlerEnable(1, env); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, 0, 0 /* no dpy, no sync */); _initialized=1; if(JNI_TRUE == debug) { fprintf(stderr, "Info: NativeWindow native init passed\n"); @@ -315,6 +320,7 @@ Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass clazz, jboo JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Util_shutdown0(JNIEnv *env, jclass _unused) { + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, 0 /* no dpy, no sync */); x11IOErrorHandlerEnable(0, env); } @@ -347,7 +353,7 @@ Java_jogamp_nativewindow_x11_X11Lib_XGetVisualInfo1__JJLjava_nio_ByteBuffer_2Lja } NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 1, 0, 0); _res = XGetVisualInfo((Display *) (intptr_t) arg0, (long) arg1, (XVisualInfo *) _ptr2, (int *) _ptr3); - NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 0, 0); count = _ptr3[0]; if (arg3 != NULL) { (*env)->ReleasePrimitiveArrayCritical(env, arg3, _ptr3, 0); @@ -382,7 +388,7 @@ Java_jogamp_nativewindow_x11_X11Lib_GetVisualIDFromWindow(JNIEnv *env, jclass _u } else { r = 0; } - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); return r; } @@ -396,7 +402,7 @@ Java_jogamp_nativewindow_x11_X11Lib_DefaultVisualID(JNIEnv *env, jclass _unused, } NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 1, 0, 0); r = (jint) XVisualIDFromVisual( DefaultVisual( (Display*) (intptr_t) display, screen ) ); - NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 0, 0); return r; } @@ -439,7 +445,7 @@ Java_jogamp_nativewindow_x11_X11Lib_XCloseDisplay__J(JNIEnv *env, jclass _unused } NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, 0, 0); _res = XCloseDisplay((Display *) (intptr_t) display); - NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, 0); return _res; } @@ -497,7 +503,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow if (visual==NULL) { - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); NativewindowCommon_throwNewRuntimeException(env, "could not query Visual by given VisualID, bail out!"); return 0; } @@ -541,7 +547,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow XSelectInput(dpy, window, 0); // no events - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); DBG_PRINT( "X11: [CreateWindow] created window %p on display %p\n", window, dpy); @@ -569,7 +575,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_DestroyDummyWindow XUnmapWindow(dpy, w); XSync(dpy, False); XDestroyWindow(dpy, w); - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); } /* @@ -597,7 +603,7 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_x11_X11Lib_GetRelativeLocatio res = XTranslateCoordinates(dpy, src_win, dest_win, src_x, src_y, &dest_x, &dest_y, &child); - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0); DBG_PRINT( "X11: GetRelativeLocation0: %p %d/%d -> %p %d/%d - ok: %d\n", (void*)src_win, src_x, src_y, (void*)dest_win, dest_x, dest_y, (int)res); diff --git a/src/newt/classes/com/jogamp/newt/Display.java b/src/newt/classes/com/jogamp/newt/Display.java index 1e9a0e9eb..391bccf3d 100644 --- a/src/newt/classes/com/jogamp/newt/Display.java +++ b/src/newt/classes/com/jogamp/newt/Display.java @@ -113,16 +113,22 @@ public abstract class Display { */ public abstract int removeReference(); + /** + * Return the {@link AbstractGraphicsDevice} used for depending resources lifecycle, + * i.e. {@link Screen} and {@link Window}, as well as the event dispatching (EDT). */ public abstract AbstractGraphicsDevice getGraphicsDevice(); /** - * @return the fully qualified Display name, - * which is a key of {@link #getType()} + {@link #getName()} + {@link #getId()} + * Return the handle of the {@link AbstractGraphicsDevice} as returned by {@link #getGraphicsDevice()}. */ - public abstract String getFQName(); - public abstract long getHandle(); + /** + * @return The fully qualified Display name, + * which is a key of {@link #getType()} + {@link #getName()} + {@link #getId()}. + */ + public abstract String getFQName(); + /** * @return this display internal serial id */ @@ -141,6 +147,9 @@ public abstract class Display { */ public abstract String getType(); + /** Return true if this instance is exclusive, i.e. will not be shared. */ + public abstract boolean isExclusive(); + /** * Sets a new {@link EDTUtil} and returns the previous one. *

      @@ -183,11 +192,12 @@ public abstract class Display { * * @param type * @param name - * @param fromIndex start index, then increasing until found or end of list * + * @param fromIndex start index, then increasing until found or end of list + * @paran shared if true, only shared instances are found, otherwise also exclusive * @return */ - public static Display getFirstDisplayOf(String type, String name, int fromIndex) { - return getDisplayOfImpl(type, name, fromIndex, 1); + public static Display getFirstDisplayOf(String type, String name, int fromIndex, boolean shared) { + return getDisplayOfImpl(type, name, fromIndex, 1, shared); } /** @@ -195,19 +205,22 @@ public abstract class Display { * @param type * @param name * @param fromIndex start index, then decreasing until found or end of list. -1 is interpreted as size - 1. + * @paran shared if true, only shared instances are found, otherwise also exclusive * @return */ - public static Display getLastDisplayOf(String type, String name, int fromIndex) { - return getDisplayOfImpl(type, name, fromIndex, -1); + public static Display getLastDisplayOf(String type, String name, int fromIndex, boolean shared) { + return getDisplayOfImpl(type, name, fromIndex, -1, shared); } - private static Display getDisplayOfImpl(String type, String name, int fromIndex, int incr) { + private static Display getDisplayOfImpl(String type, String name, int fromIndex, int incr, boolean shared) { synchronized(displayList) { int i = fromIndex >= 0 ? fromIndex : displayList.size() - 1 ; while( ( incr > 0 ) ? i < displayList.size() : i >= 0 ) { Display display = (Display) displayList.get(i); if( display.getType().equals(type) && - display.getName().equals(name) ) { + display.getName().equals(name) && + ( !shared || shared && !display.isExclusive() ) + ) { return display; } i+=incr; diff --git a/src/newt/classes/com/jogamp/newt/NewtFactory.java b/src/newt/classes/com/jogamp/newt/NewtFactory.java index abae94ab6..1bf47f4aa 100644 --- a/src/newt/classes/com/jogamp/newt/NewtFactory.java +++ b/src/newt/classes/com/jogamp/newt/NewtFactory.java @@ -305,7 +305,7 @@ public class NewtFactory { * Instantiate a Display entity using the native handle. */ public static Display createDisplay(String type, long handle, boolean reuse) { - return DisplayImpl.create(type, null, handle, false); + return DisplayImpl.create(type, null, handle, reuse); } public static boolean isScreenCompatible(NativeWindow parent, Screen childScreen) { diff --git a/src/newt/classes/com/jogamp/newt/Screen.java b/src/newt/classes/com/jogamp/newt/Screen.java index 26f19ad6b..cfbcc988a 100644 --- a/src/newt/classes/com/jogamp/newt/Screen.java +++ b/src/newt/classes/com/jogamp/newt/Screen.java @@ -145,7 +145,7 @@ public abstract class Screen { public abstract Display getDisplay(); /** - * @return the screen fully qualified Screen name, + * @return The screen fully qualified Screen name, * which is a key of {@link com.jogamp.newt.Display#getFQName()} + {@link #getIndex()}. */ public abstract String getFQName(); diff --git a/src/newt/classes/jogamp/newt/DisplayImpl.java b/src/newt/classes/jogamp/newt/DisplayImpl.java index bca7f6e5b..daeb3e886 100644 --- a/src/newt/classes/jogamp/newt/DisplayImpl.java +++ b/src/newt/classes/jogamp/newt/DisplayImpl.java @@ -42,6 +42,7 @@ import com.jogamp.newt.event.NEWTEventConsumer; import jogamp.newt.event.NEWTEventTask; import com.jogamp.newt.util.EDTUtil; import java.util.ArrayList; + import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowException; @@ -66,7 +67,7 @@ public abstract class DisplayImpl extends Display { name = display.validateDisplayName(name, handle); synchronized(displayList) { if(reuse) { - Display display0 = Display.getLastDisplayOf(type, name, -1); + Display display0 = Display.getLastDisplayOf(type, name, -1, true /* shared only */); if(null != display0) { if(DEBUG) { System.err.println("Display.create() REUSE: "+display0+" "+getThreadName()); @@ -74,9 +75,9 @@ public abstract class DisplayImpl extends Display { return display0; } } + display.exclusive = !reuse; display.name = name; display.type=type; - display.destroyWhenUnused=false; display.refCount=0; display.id = serialno++; display.fqname = getFQName(display.type, display.name, display.id); @@ -94,7 +95,7 @@ public abstract class DisplayImpl extends Display { throw new RuntimeException(e); } } - + @Override public boolean equals(Object obj) { if (obj == null) { @@ -116,10 +117,12 @@ public abstract class DisplayImpl extends Display { return true; } + @Override public int hashCode() { return hashCode; } + @Override public synchronized final void createNative() throws NativeWindowException { @@ -148,10 +151,6 @@ public abstract class DisplayImpl extends Display { } } - protected boolean shallRunOnEDT() { - return true; - } - protected EDTUtil createEDTUtil() { final EDTUtil def; if(NewtFactory.useEDT()) { @@ -179,12 +178,7 @@ public abstract class DisplayImpl extends Display { if(DEBUG) { System.err.println("Display.setEDTUtil: "+oldEDTUtil+" -> "+newEDTUtil); } - if(null != oldEDTUtil) { - stopEDT( new Runnable() { public void run() {} } ); - // ready for restart .. - oldEDTUtil.waitUntilStopped(); - oldEDTUtil.reset(); - } + removeEDT( new Runnable() { public void run() {} } ); edtUtil = newEDTUtil; return oldEDTUtil; } @@ -194,16 +188,19 @@ public abstract class DisplayImpl extends Display { return edtUtil; } - private void stopEDT(final Runnable task) { - if( shallRunOnEDT() && null!=edtUtil ) { + private void removeEDT(final Runnable task) { + if(null!=edtUtil) { edtUtil.invokeStop(task); + // ready for restart .. + edtUtil.waitUntilStopped(); + edtUtil.reset(); } else { task.run(); } } public void runOnEDTIfAvail(boolean wait, final Runnable task) { - if( shallRunOnEDT() && null!=edtUtil && !edtUtil.isCurrentThreadEDT()) { + if( null!=edtUtil && !edtUtil.isCurrentThreadEDT()) { edtUtil.invoke(wait, task); } else { task.run(); @@ -212,18 +209,17 @@ public abstract class DisplayImpl extends Display { public boolean validateEDT() { if(0==refCount && null==aDevice && null != edtUtil && edtUtil.isRunning()) { - stopEDT( new Runnable() { + removeEDT( new Runnable() { public void run() { // nop } } ); - edtUtil.waitUntilStopped(); - edtUtil.reset(); return true; } return false; } + @Override public synchronized final void destroy() { if(DEBUG) { dumpDisplayList("Display.destroy("+getFQName()+") BEGIN"); @@ -239,17 +235,13 @@ public abstract class DisplayImpl extends Display { } final AbstractGraphicsDevice f_aDevice = aDevice; final DisplayImpl f_dpy = this; - stopEDT( new Runnable() { + removeEDT( new Runnable() { public void run() { if ( null != f_aDevice ) { f_dpy.closeNativeImpl(); } } } ); - if(null!=edtUtil) { - edtUtil.waitUntilStopped(); - edtUtil.reset(); - } aDevice = null; refCount=0; if(DEBUG) { @@ -290,21 +282,30 @@ public abstract class DisplayImpl extends Display { protected abstract void createNativeImpl(); protected abstract void closeNativeImpl(); + @Override public final int getId() { return id; } + @Override public final String getType() { return type; } + @Override public final String getName() { return name; } + @Override public final String getFQName() { return fqname; } + + @Override + public final boolean isExclusive() { + return exclusive; + } public static final String nilString = "nil" ; @@ -324,9 +325,10 @@ public abstract class DisplayImpl extends Display { sb.append(name); sb.append("-"); sb.append(id); - return sb.toString().intern(); + return sb.toString(); } + @Override public final long getHandle() { if(null!=aDevice) { return aDevice.getHandle(); @@ -334,14 +336,17 @@ public abstract class DisplayImpl extends Display { return 0; } + @Override public final AbstractGraphicsDevice getGraphicsDevice() { return aDevice; } + @Override public synchronized final boolean isNativeValid() { return null != aDevice; } + @Override public boolean isEDTRunning() { if(null!=edtUtil) { return edtUtil.isRunning(); @@ -351,7 +356,7 @@ public abstract class DisplayImpl extends Display { @Override public String toString() { - return "NEWT-Display["+getFQName()+", refCount "+refCount+", hasEDT "+(null!=edtUtil)+", edtRunning "+isEDTRunning()+", "+aDevice+"]"; + return "NEWT-Display["+getFQName()+", excl "+exclusive+", refCount "+refCount+", hasEDT "+(null!=edtUtil)+", edtRunning "+isEDTRunning()+", "+aDevice+"]"; } protected abstract void dispatchMessagesNative(); @@ -403,6 +408,7 @@ public abstract class DisplayImpl extends Display { eventTask.notifyCaller(); } + @Override public void dispatchMessages() { // System.err.println("Display.dispatchMessages() 0 "+this+" "+getThreadName()); if(0==refCount || // no screens @@ -475,20 +481,23 @@ public abstract class DisplayImpl extends Display { public interface DisplayRunnable { T run(long dpy); } - public final T runWithLockedDisplayHandle(DisplayRunnable action) { - final AbstractGraphicsDevice aDevice = getGraphicsDevice(); - if(null == aDevice) { - throw new RuntimeException("null device - not initialized: "+this); - } + public static final T runWithLockedDevice(AbstractGraphicsDevice device, DisplayRunnable action) { T res; - aDevice.lock(); + device.lock(); try { - res = action.run(aDevice.getHandle()); + res = action.run(device.getHandle()); } finally { - aDevice.unlock(); + device.unlock(); } return res; } + public final T runWithLockedDisplayDevice(DisplayRunnable action) { + final AbstractGraphicsDevice device = getGraphicsDevice(); + if(null == device) { + throw new RuntimeException("null device - not initialized: "+this); + } + return runWithLockedDevice(device, action); + } protected EDTUtil edtUtil = null; protected int id; @@ -497,7 +506,7 @@ public abstract class DisplayImpl extends Display { protected String fqname; protected int hashCode; protected int refCount; // number of Display references by Screen - protected boolean destroyWhenUnused; + protected boolean exclusive; // do not share this display, uses NullLock! protected AbstractGraphicsDevice aDevice; } diff --git a/src/newt/classes/jogamp/newt/ScreenImpl.java b/src/newt/classes/jogamp/newt/ScreenImpl.java index e2c0f746f..1cc53e80e 100644 --- a/src/newt/classes/jogamp/newt/ScreenImpl.java +++ b/src/newt/classes/jogamp/newt/ScreenImpl.java @@ -42,7 +42,6 @@ import java.util.List; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.util.Dimension; import javax.media.nativewindow.util.DimensionImmutable; import javax.media.nativewindow.util.Point; @@ -130,7 +129,7 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { } } screen.screen_idx = idx; - screen.fqname = (display.getFQName()+idx).intern(); + screen.fqname = display.getFQName()+"-s"+idx; screen.hashCode = screen.fqname.hashCode(); screenList.add(screen); if(DEBUG) { diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index c1ac87d38..79770189b 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -85,7 +85,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer private volatile long windowHandle = 0; // lifecycle critical private volatile boolean visible = false; // lifecycle critical private RecursiveLock windowLock = LockFactory.createRecursiveLock(); // Window instance wide lock - private RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); // Surface only lock + private int surfaceLockCount = 0; // surface lock recursion count private ScreenImpl screen; // never null after create - may change reference though (reparent) private boolean screenReferenceAdded = false; @@ -553,10 +553,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer @Override public final int lockSurface() throws NativeWindowException, RuntimeException { final RecursiveLock _wlock = windowLock; - final RecursiveLock _slock = surfaceLock; _wlock.lock(); - _slock.lock(); - int res = _slock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? + surfaceLockCount++; + int res = ( 1 == surfaceLockCount ) ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? if ( LOCK_SURFACE_NOT_READY == res ) { try { @@ -573,7 +572,6 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } finally { if (LOCK_SURFACE_NOT_READY >= res) { - _slock.unlock(); _wlock.unlock(); } } @@ -583,12 +581,10 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer @Override public final void unlockSurface() { - final RecursiveLock _slock = surfaceLock; final RecursiveLock _wlock = windowLock; - _slock.validateLocked(); _wlock.validateLocked(); - if (_slock.getHoldCount() == 1) { + if ( 1 == surfaceLockCount ) { final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); try { unlockSurfaceImpl(); @@ -596,42 +592,48 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer adevice.unlock(); } } - _slock.unlock(); + surfaceLockCount--; _wlock.unlock(); } @Override public final boolean isSurfaceLockedByOtherThread() { - return surfaceLock.isLockedByOtherThread(); + return windowLock.isLockedByOtherThread(); } @Override public final Thread getSurfaceLockOwner() { - return surfaceLock.getOwner(); + return windowLock.getOwner(); } public final RecursiveLock getLock() { return windowLock; } + @Override public long getSurfaceHandle() { return windowHandle; // default: return window handle } + @Override public boolean surfaceSwap() { return false; } + @Override public final AbstractGraphicsConfiguration getGraphicsConfiguration() { return config.getNativeGraphicsConfiguration(); } - public final long getDisplayHandle() { - return getScreen().getDisplay().getHandle(); + @Override + public long getDisplayHandle() { + // Actually: return getGraphicsConfiguration().getScreen().getDevice().getHandle(); + return screen.getDisplay().getHandle(); // shortcut } + @Override public final int getScreenIndex() { - return getScreen().getIndex(); + return screen.getIndex(); } //---------------------------------------------------------------------- @@ -1554,8 +1556,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer for (int i = 0; i < keyListeners.size(); i++ ) { sb.append(keyListeners.get(i)+", "); } - sb.append("], surfaceLock "+surfaceLock); - sb.append(", windowLock "+windowLock+"]"); + sb.append("], windowLock "+windowLock+"]"); return sb.toString(); } diff --git a/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java index 70e9ba570..ead567d82 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java @@ -66,7 +66,9 @@ public class DisplayDriver extends DisplayImpl { return def; } - protected void closeNativeImpl() { } + protected void closeNativeImpl() { + aDevice.close(); + } protected void dispatchMessagesNative() { /* nop */ } } diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java index 65ca63eec..cc55c336e 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java @@ -39,6 +39,7 @@ import javax.media.nativewindow.NativeWindowException; import jogamp.newt.NEWTJNILibLoader; import jogamp.opengl.egl.EGL; +import jogamp.opengl.egl.EGLDisplayUtil; import com.jogamp.nativewindow.egl.EGLGraphicsDevice; @@ -72,6 +73,7 @@ public class DisplayDriver extends jogamp.newt.DisplayImpl { if (aDevice.getHandle() != EGL.EGL_NO_DISPLAY) { DestroyDisplay(aDevice.getHandle()); } + aDevice.close(); } protected void dispatchMessagesNative() { diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java index 97c384d33..e370038d9 100644 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java @@ -84,6 +84,7 @@ public class DisplayDriver extends jogamp.newt.DisplayImpl { } } } + aDevice.close(); } protected void dispatchMessagesNative() { diff --git a/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java index 1a3f14859..b49c6b6e0 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java @@ -72,7 +72,9 @@ public class DisplayDriver extends DisplayImpl { aDevice = new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); } - protected void closeNativeImpl() { } + protected void closeNativeImpl() { + aDevice.close(); + } public static void runNSApplication() { runNSApplication0(); diff --git a/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java index 579ec5be8..615f9e63b 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java @@ -73,6 +73,7 @@ public class DisplayDriver extends DisplayImpl { protected void closeNativeImpl() { sharedClassFactory.releaseSharedClass(); + aDevice.close(); } protected void dispatchMessagesNative() { diff --git a/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java index 714324d63..bff050030 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java @@ -36,7 +36,6 @@ package jogamp.newt.driver.x11; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.NativeWindowFactory; import com.jogamp.nativewindow.x11.X11GraphicsDevice; @@ -74,71 +73,48 @@ public class DisplayDriver extends DisplayImpl { * {@inheritDoc} * * We use a private non-shared X11 Display instance for EDT window operations and one for exposed animation, eg. OpenGL. - *

      - * In case {@link X11Util#HAS_XLOCKDISPLAY_BUG} and {@link X11Util#XINITTHREADS_ALWAYS_ENABLED}, - * we use null locking. Even though this seems not to be rational, it gives most stable results on all platforms. - *

      - *

      - * Otherwise we use basic locking via the constructor {@link X11GraphicsDevice#X11GraphicsDevice(long, int, boolean)}, - * since it is possible to share this device via {@link com.jogamp.newt.NewtFactory#createDisplay(String, boolean)}. - *

      */ - @SuppressWarnings("unused") protected void createNativeImpl() { + X11Util.setX11ErrorHandler(true, DEBUG ? false : true); // make sure X11 error handler is set long handle = X11Util.openDisplay(name); if( 0 == handle ) { throw new RuntimeException("Error creating display(Win): "+name); } - if(USE_SEPARATE_DISPLAY_FOR_EDT) { - edtDisplayHandle = X11Util.openDisplay(name); - if( 0 == edtDisplayHandle ) { - X11Util.closeDisplay(handle); - throw new RuntimeException("Error creating display(EDT): "+name); - } - } else { - edtDisplayHandle = handle; - } + aDevice = new X11GraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_UNIT, true); try { - CompleteDisplay0(edtDisplayHandle); + CompleteDisplay0(aDevice.getHandle()); } catch(RuntimeException e) { closeNativeImpl(); throw e; - } - - // see API doc above! - if(X11Util.XINITTHREADS_ALWAYS_ENABLED && X11Util.HAS_XLOCKDISPLAY_BUG) { - aDevice = new X11GraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_UNIT, NativeWindowFactory.getNullToolkitLock(), false); - } else { - aDevice = new X11GraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_UNIT, false); - } + } } protected void closeNativeImpl() { - DisplayRelease0(edtDisplayHandle, javaObjectAtom, windowDeleteAtom); + DisplayRelease0(aDevice.getHandle(), javaObjectAtom, windowDeleteAtom); javaObjectAtom = 0; windowDeleteAtom = 0; - // closing using ATI driver bug 'same order' - final long handle = getHandle(); - X11Util.closeDisplay(handle); - if(handle != edtDisplayHandle) { - X11Util.closeDisplay(edtDisplayHandle); - } - edtDisplayHandle = 0; + aDevice.close(); // closes X11 display } protected void dispatchMessagesNative() { - if(0 != edtDisplayHandle) { - DispatchMessages0(edtDisplayHandle, javaObjectAtom, windowDeleteAtom); + aDevice.lock(); + try { + final long handle = aDevice.getHandle(); + if(0 != handle) { + DispatchMessages0(handle, javaObjectAtom, windowDeleteAtom); + } + } finally { + aDevice.unlock(); } } - protected long getEDTHandle() { return edtDisplayHandle; } protected long getJavaObjectAtom() { return javaObjectAtom; } protected long getWindowDeleteAtom() { return windowDeleteAtom; } //---------------------------------------------------------------------- // Internals only // + private static native boolean initIDs0(boolean debug); private native void CompleteDisplay0(long handle); @@ -151,17 +127,6 @@ public class DisplayDriver extends DisplayImpl { private native void DispatchMessages0(long display, long javaObjectAtom, long windowDeleteAtom); - /** - * 2011/06/14 libX11 1.4.2 and libxcb 1.7 bug 20708 - Multithreading Issues w/ OpenGL, .. - * https://bugs.freedesktop.org/show_bug.cgi?id=20708 - * https://jogamp.org/bugzilla/show_bug.cgi?id=502 - * Affects: Ubuntu 11.04, OpenSuSE 11, .. - * Workaround: Using a separate X11 Display connection for event dispatching (EDT) - */ - private final boolean USE_SEPARATE_DISPLAY_FOR_EDT = true; - - private long edtDisplayHandle; - /** X11 Window delete atom marker used on EDT */ private long windowDeleteAtom; diff --git a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java index 10f6b84da..b09d98e06 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java @@ -59,7 +59,7 @@ public class ScreenDriver extends ScreenImpl { protected void createNativeImpl() { // validate screen index - Long handle = display.runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + Long handle = runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public Long run(long dpy) { return new Long(GetScreen0(dpy, screen_idx)); } } ); @@ -81,7 +81,7 @@ public class ScreenDriver extends ScreenImpl { private int nmode_number; protected int[] getScreenModeFirstImpl() { - return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public int[] run(long dpy) { // initialize iterators and static data nrotations = getAvailableScreenModeRotations0(dpy, screen_idx); @@ -110,7 +110,7 @@ public class ScreenDriver extends ScreenImpl { protected int[] getScreenModeNextImpl() { // assemble: w x h x bpp x f x r - return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public int[] run(long dpy) { /** System.err.println("******** mode: "+nmode_number); @@ -176,7 +176,7 @@ public class ScreenDriver extends ScreenImpl { } protected ScreenMode getCurrentScreenModeImpl() { - return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public ScreenMode run(long dpy) { long screenConfigHandle = getScreenConfiguration0(dpy, screen_idx); if(0 == screenConfigHandle) { @@ -237,7 +237,7 @@ public class ScreenDriver extends ScreenImpl { throw new RuntimeException("ScreenMode not element of ScreenMode list: "+screenMode); } final long t0 = System.currentTimeMillis(); - boolean done = runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + boolean done = runWithTempDisplayHandle( new DisplayImpl.DisplayRunnable() { public Boolean run(long dpy) { boolean done = false; long screenConfigHandle = getScreenConfiguration0(dpy, screen_idx); @@ -276,23 +276,21 @@ public class ScreenDriver extends ScreenImpl { return done; } - private class XineramaEnabledQuery implements DisplayImpl.DisplayRunnable { + private DisplayImpl.DisplayRunnable xineramaEnabledQueryWithTemp = new DisplayImpl.DisplayRunnable() { public Boolean run(long dpy) { return new Boolean(X11Util.XineramaIsEnabled(dpy)); - } - } - private XineramaEnabledQuery xineramaEnabledQuery = new XineramaEnabledQuery(); + } }; protected int validateScreenIndex(final int idx) { if(getDisplay().isNativeValid()) { - return runWithLockedDisplayHandle( xineramaEnabledQuery ).booleanValue() ? 0 : idx; + return X11Util.XineramaIsEnabled((X11GraphicsDevice)getDisplay().getGraphicsDevice()) ? 0 : idx; } else { - return runWithTempDisplayHandle( xineramaEnabledQuery ).booleanValue() ? 0 : idx; + return runWithTempDisplayHandle( xineramaEnabledQueryWithTemp ).booleanValue() ? 0 : idx; } } protected void getVirtualScreenOriginAndSize(final Point virtualOrigin, final Dimension virtualSize) { - display.runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public Object run(long dpy) { virtualOrigin.setX(0); virtualOrigin.setY(0); @@ -305,10 +303,8 @@ public class ScreenDriver extends ScreenImpl { //---------------------------------------------------------------------- // Internals only // - private final T runWithLockedDisplayHandle(DisplayRunnable action) { - return display.runWithLockedDisplayHandle(action); - // return runWithTempDisplayHandle(action); - // return runWithoutLock(action); + private final T runWithLockedDisplayDevice(DisplayRunnable action) { + return display.runWithLockedDisplayDevice(action); } private final T runWithTempDisplayHandle(DisplayRunnable action) { @@ -324,9 +320,6 @@ public class ScreenDriver extends ScreenImpl { } return res; } - private final T runWithoutLock(DisplayRunnable action) { - return action.run(display.getHandle()); - } private static native long GetScreen0(long dpy, int scrn_idx); diff --git a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java index 97d1ae3db..aea86a420 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java @@ -35,6 +35,7 @@ package jogamp.newt.driver.x11; import jogamp.nativewindow.x11.X11Lib; +import jogamp.nativewindow.x11.X11Util; import jogamp.newt.DisplayImpl; import jogamp.newt.DisplayImpl.DisplayRunnable; import jogamp.newt.WindowImpl; @@ -44,6 +45,8 @@ import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.InsetsImmutable; import javax.media.nativewindow.util.Point; +import com.jogamp.nativewindow.x11.X11GraphicsDevice; +import com.jogamp.nativewindow.x11.X11GraphicsScreen; import com.jogamp.newt.event.MouseEvent; public class WindowDriver extends WindowImpl { @@ -63,9 +66,19 @@ public class WindowDriver extends WindowImpl { protected void createNativeImpl() { final ScreenDriver screen = (ScreenDriver) getScreen(); final DisplayDriver display = (DisplayDriver) screen.getDisplay(); + final AbstractGraphicsDevice edtDevice = display.getGraphicsDevice(); + + // Decoupled X11 Device/Screen allowing X11 display lock-free off-thread rendering + final long renderDeviceHandle = X11Util.openDisplay(edtDevice.getConnection()); + if( 0 == renderDeviceHandle ) { + throw new RuntimeException("Error creating display(EDT): "+edtDevice.getConnection()); + } + renderDevice = new X11GraphicsDevice(renderDeviceHandle, AbstractGraphicsDevice.DEFAULT_UNIT, true); + AbstractGraphicsScreen renderScreen = new X11GraphicsScreen((X11GraphicsDevice) renderDevice, screen.getIndex()); + final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice(), capsRequested); final AbstractGraphicsConfiguration cfg = factory.chooseGraphicsConfiguration( - capsRequested, capsRequested, capabilitiesChooser, screen.getGraphicsScreen(), VisualIDHolder.VID_UNDEFINED); + capsRequested, capsRequested, capabilitiesChooser, renderScreen, VisualIDHolder.VID_UNDEFINED); if(DEBUG_IMPLEMENTATION) { System.err.println("X11Window.createNativeImpl() factory: "+factory+", chosen config: "+cfg); } @@ -78,11 +91,16 @@ public class WindowDriver extends WindowImpl { } setGraphicsConfiguration(cfg); final int flags = getReconfigureFlags(0, true) & - ( FLAG_IS_ALWAYSONTOP | FLAG_IS_UNDECORATED ) ; - setWindowHandle(CreateWindow0(getParentWindowHandle(), - display.getEDTHandle(), screen.getIndex(), visualID, - display.getJavaObjectAtom(), display.getWindowDeleteAtom(), - getX(), getY(), getWidth(), getHeight(), autoPosition(), flags)); + ( FLAG_IS_ALWAYSONTOP | FLAG_IS_UNDECORATED ) ; + edtDevice.lock(); + try { + setWindowHandle(CreateWindow0(getParentWindowHandle(), + edtDevice.getHandle(), screen.getIndex(), visualID, + display.getJavaObjectAtom(), display.getWindowDeleteAtom(), + getX(), getY(), getWidth(), getHeight(), autoPosition(), flags)); + } finally { + edtDevice.unlock(); + } windowHandleClose = getWindowHandle(); if (0 == windowHandleClose) { throw new NativeWindowException("Error creating window"); @@ -92,8 +110,10 @@ public class WindowDriver extends WindowImpl { protected void closeNativeImpl() { if(0!=windowHandleClose && null!=getScreen() ) { DisplayDriver display = (DisplayDriver) getScreen().getDisplay(); + final AbstractGraphicsDevice edtDevice = display.getGraphicsDevice(); + edtDevice.lock(); try { - CloseWindow0(display.getEDTHandle(), windowHandleClose, + CloseWindow0(edtDevice.getHandle(), windowHandleClose, display.getJavaObjectAtom(), display.getWindowDeleteAtom()); } catch (Throwable t) { if(DEBUG_IMPLEMENTATION) { @@ -101,28 +121,47 @@ public class WindowDriver extends WindowImpl { e.printStackTrace(); } } finally { + edtDevice.unlock(); windowHandleClose = 0; } } + if(null != renderDevice) { + renderDevice.close(); // closes X11 display + renderDevice = null; + } } - protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + @Override + public long getDisplayHandle() { + // Actually: return getGraphicsConfiguration().getScreen().getDevice().getHandle(); + return renderDevice.getHandle(); // shortcut + } + + protected boolean reconfigureWindowImpl(final int x, final int y, final int width, final int height, final int flags) { if(DEBUG_IMPLEMENTATION) { System.err.println("X11Window reconfig: "+x+"/"+y+" "+width+"x"+height+", "+ getReconfigureFlagsAsString(null, flags)); } + final int _x, _y; if(0 == ( FLAG_IS_UNDECORATED & flags)) { final InsetsImmutable i = getInsets(); // client position -> top-level window position - x -= i.getLeftWidth() ; - y -= i.getTopHeight() ; + _x = x - i.getLeftWidth() ; + _y = y - i.getTopHeight() ; + } else { + _x = x; + _y = y; } final DisplayDriver display = (DisplayDriver) getScreen().getDisplay(); - reconfigureWindow0( getDisplayEDTHandle(), getScreenIndex(), - getParentWindowHandle(), getWindowHandle(), display.getWindowDeleteAtom(), - x, y, width, height, flags); - + runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + public Object run(long dpy) { + reconfigureWindow0( dpy, getScreenIndex(), + getParentWindowHandle(), getWindowHandle(), display.getWindowDeleteAtom(), + _x, _y, width, height, flags); + return null; + } + }); return true; } @@ -133,13 +172,18 @@ public class WindowDriver extends WindowImpl { } } - protected void requestFocusImpl(boolean force) { - requestFocus0(getDisplayEDTHandle(), getWindowHandle(), force); + protected void requestFocusImpl(final boolean force) { + runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + public Object run(long dpy) { + requestFocus0(dpy, getWindowHandle(), force); + return null; + } + }); } @Override protected void setTitleImpl(final String title) { - runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public Object run(long dpy) { setTitle0(dpy, getWindowHandle(), title); return null; @@ -149,35 +193,38 @@ public class WindowDriver extends WindowImpl { @Override protected boolean setPointerVisibleImpl(final boolean pointerVisible) { - return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public Boolean run(long dpy) { - return Boolean.valueOf(setPointerVisible0(getDisplayEDTHandle(), getWindowHandle(), pointerVisible)); + return Boolean.valueOf(setPointerVisible0(dpy, getWindowHandle(), pointerVisible)); } }).booleanValue(); } @Override protected boolean confinePointerImpl(final boolean confine) { - return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public Boolean run(long dpy) { - return Boolean.valueOf(confinePointer0(getDisplayEDTHandle(), getWindowHandle(), confine)); + return Boolean.valueOf(confinePointer0(dpy, getWindowHandle(), confine)); } }).booleanValue(); } @Override protected void warpPointerImpl(final int x, final int y) { - runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable() { + runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public Object run(long dpy) { - warpPointer0(getDisplayEDTHandle(), getWindowHandle(), x, y); + warpPointer0(dpy, getWindowHandle(), x, y); return null; } }); } protected Point getLocationOnScreenImpl(final int x, final int y) { - // X11Util.GetRelativeLocation: locks display already ! - return X11Lib.GetRelativeLocation( getScreen().getDisplay().getHandle(), getScreenIndex(), getWindowHandle(), 0 /*root win*/, x, y); + return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + public Point run(long dpy) { + return X11Lib.GetRelativeLocation(dpy, getScreenIndex(), getWindowHandle(), 0 /*root win*/, x, y); + } + } ); } protected void updateInsetsImpl(Insets insets) { @@ -229,16 +276,11 @@ public class WindowDriver extends WindowImpl { //---------------------------------------------------------------------- // Internals only // - private static final String getCurrentThreadName() { return Thread.currentThread().getName(); } // Callback for JNI private static final void dumpStack() { Thread.dumpStack(); } // Callback for JNI - private final long getDisplayEDTHandle() { - return ((DisplayDriver) getScreen().getDisplay()).getEDTHandle(); - } - private final T runWithLockedDisplayHandle(DisplayRunnable action) { - return ((DisplayImpl) getScreen().getDisplay()).runWithLockedDisplayHandle(action); - // return runWithTempDisplayHandle(action); + private final T runWithLockedDisplayDevice(DisplayRunnable action) { + return ((DisplayDriver) getScreen().getDisplay()).runWithLockedDisplayDevice(action); } protected static native boolean initIDs0(); @@ -258,4 +300,5 @@ public class WindowDriver extends WindowImpl { private static native void warpPointer0(long display, long windowHandle, int x, int y); private long windowHandleClose; + private AbstractGraphicsDevice renderDevice; } diff --git a/src/newt/native/X11Common.h b/src/newt/native/X11Common.h index 128b6b6f1..4d1a7b59e 100644 --- a/src/newt/native/X11Common.h +++ b/src/newt/native/X11Common.h @@ -70,7 +70,6 @@ extern jclass X11NewtWindowClazz; extern jmethodID insetsChangedID; extern jmethodID visibleChangedID; -void NewtDisplay_x11ErrorHandlerEnable(JNIEnv * env, Display *dpy, int onoff, int quiet, int sync); jobject getJavaWindowProperty(JNIEnv *env, Display *dpy, Window window, jlong javaObjectAtom, Bool showWarning); Status NewtWindows_getRootAndParent (Display *dpy, Window w, Window * root_return, Window * parent_return); diff --git a/src/newt/native/X11Display.c b/src/newt/native/X11Display.c index 84b3a7630..56c11fab4 100644 --- a/src/newt/native/X11Display.c +++ b/src/newt/native/X11Display.c @@ -52,90 +52,6 @@ static jmethodID enqueueKeyEventID = NULL; static jmethodID sendKeyEventID = NULL; static jmethodID requestFocusID = NULL; -static JavaVM *jvmHandle = NULL; -static int jvmVersion = 0; - -static void setupJVMVars(JNIEnv * env) { - if(0 != (*env)->GetJavaVM(env, &jvmHandle)) { - jvmHandle = NULL; - } - jvmVersion = (*env)->GetVersion(env); -} - -static XErrorHandler origErrorHandler = NULL ; -static int errorHandlerQuiet = 0 ; -static int errorHandlerDebug = 0 ; -static int errorHandlerThrowException = 0; - -static int x11ErrorHandler(Display *dpy, XErrorEvent *e) -{ - if(!errorHandlerQuiet) { - const char * errnoStr = strerror(errno); - char threadName[80]; - char errCodeStr[80]; - char reqCodeStr[80]; - - int shallBeDetached = 0; - JNIEnv *jniEnv = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); - - (void) NewtCommon_GetStaticStringMethod(jniEnv, X11NewtWindowClazz, getCurrentThreadNameID, threadName, sizeof(threadName), "n/a"); - snprintf(errCodeStr, sizeof(errCodeStr), "%d", e->request_code); - XGetErrorDatabaseText(dpy, "XRequest", errCodeStr, "Unknown", reqCodeStr, sizeof(reqCodeStr)); - XGetErrorText(dpy, e->error_code, errCodeStr, sizeof(errCodeStr)); - - fprintf(stderr, "Info: Newt X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", - threadName, e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, - (int)e->request_code, (int)e->minor_code, reqCodeStr); - - if( errorHandlerDebug ) { - (*jniEnv)->CallStaticVoidMethod(jniEnv, X11NewtWindowClazz, dumpStackID); - } - - if(errorHandlerThrowException) { - if(NULL != jniEnv) { - NewtCommon_throwNewRuntimeException(jniEnv, "Newt X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", - threadName, e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, - (int)e->request_code, (int)e->minor_code, reqCodeStr); - } else { - fprintf(stderr, "Nativewindow X11 Error: null JNIEnv"); - #if 0 - if(NULL!=origErrorHandler) { - origErrorHandler(dpy, e); - } - #endif - } - } - fflush(stderr); - - if (NULL != jniEnv && shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } - } - - return 0; -} - -void NewtDisplay_x11ErrorHandlerEnable(JNIEnv * env, Display *dpy, int onoff, int quiet, int sync) { - errorHandlerQuiet = quiet; - if(onoff) { - if(NULL==origErrorHandler) { - setupJVMVars(env); - origErrorHandler = XSetErrorHandler(x11ErrorHandler); - if(sync && NULL!=dpy) { - XSync(dpy, False); - } - } - } else { - if(NULL!=origErrorHandler) { - if(sync && NULL!=dpy) { - XSync(dpy, False); - } - XSetErrorHandler(origErrorHandler); - origErrorHandler = NULL; - } - } -} - /** * Keycode */ @@ -273,9 +189,6 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_initIDs0 { jclass c; - if(debug) { - errorHandlerDebug = 1 ; - } NewtCommon_init(env); if(NULL==X11NewtWindowClazz) { @@ -439,8 +352,6 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessage // DBG_PRINT( "X11: DispatchMessages dpy %p, win %p, Event %d\n", (void*)dpy, (void*)evt.xany.window, (int)evt.type); - NewtDisplay_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); - jwindow = getJavaWindowProperty(env, dpy, evt.xany.window, javaObjectAtom, #ifdef VERBOSE_ON True @@ -449,8 +360,6 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessage #endif ); - NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); - if(NULL==jwindow) { fprintf(stderr, "Warning: NEWT X11 DisplayDispatch %p, Couldn't handle event %d for X11 window %p\n", (void*)dpy, evt.type, (void*)evt.xany.window); diff --git a/src/newt/native/X11Window.c b/src/newt/native/X11Window.c index 59862f463..2e16e7cae 100644 --- a/src/newt/native/X11Window.c +++ b/src/newt/native/X11Window.c @@ -683,16 +683,12 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CloseWindow0 DBG_PRINT( "X11: CloseWindow START dpy %p, win %p\n", (void*)dpy, (void*)w); - NewtDisplay_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); - jwindow = getJavaWindowProperty(env, dpy, w, javaObjectAtom, True); if(NULL==jwindow) { - NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); NewtCommon_throwNewRuntimeException(env, "could not fetch Java Window object, bail out!"); return; } if ( JNI_FALSE == (*env)->IsSameObject(env, jwindow, obj) ) { - NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); NewtCommon_throwNewRuntimeException(env, "Internal Error .. Window global ref not the same!"); return; } @@ -700,7 +696,6 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CloseWindow0 XSync(dpy, False); XSelectInput(dpy, w, 0); XUnmapWindow(dpy, w); - NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); // Drain all events related to this window .. Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessages0(env, obj, display, javaObjectAtom, windowDeleteAtom); @@ -761,8 +756,6 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_reconfigureWindo fsEWMHFlags |= _NET_WM_ABOVE; // toggle above } - NewtDisplay_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); - DBG_PRINT( "X11: reconfigureWindow0 dpy %p, scrn %d, parent %p/%p, win %p, %d/%d %dx%d, parentChange %d, hasParent %d, decorationChange %d, undecorated %d, fullscreenChange %d, fullscreen %d, alwaysOnTopChange %d, alwaysOnTop %d, visibleChange %d, visible %d, tempInvisible %d, fsEWMHFlags %d\n", (void*)dpy, screen_index, (void*) jparent, (void*)parent, (void*)w, x, y, width, height, @@ -779,7 +772,6 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_reconfigureWindo ( TST_FLAG_CHANGE_FULLSCREEN(flags) || TST_FLAG_CHANGE_ALWAYSONTOP(flags) ) ) { Bool enable = TST_FLAG_CHANGE_FULLSCREEN(flags) ? TST_FLAG_IS_FULLSCREEN(flags) : TST_FLAG_IS_ALWAYSONTOP(flags) ; if( NewtWindows_setFullscreenEWMH(dpy, root, w, fsEWMHFlags, isVisible, enable) ) { - NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); #ifdef FS_GRAB_KEYBOARD if(TST_FLAG_CHANGE_FULLSCREEN(flags)) { if(TST_FLAG_IS_FULLSCREEN(flags)) { @@ -863,8 +855,6 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_reconfigureWindo #endif } - NewtDisplay_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); - DBG_PRINT( "X11: reconfigureWindow0 X\n"); } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/InitConcurrentBaseNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/InitConcurrentBaseNEWT.java new file mode 100644 index 000000000..11d1331ed --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/InitConcurrentBaseNEWT.java @@ -0,0 +1,219 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import javax.media.nativewindow.Capabilities; +import javax.media.nativewindow.util.InsetsImmutable; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLProfile; + +import org.junit.Assert; +import org.junit.BeforeClass; + +import com.jogamp.newt.Display; +import com.jogamp.newt.NewtFactory; +import com.jogamp.newt.Screen; +import com.jogamp.newt.Window; +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.util.Animator; + +/** + * Concurrent and lock-free initialization and rendering using exclusive NEWT Display EDT instances, or + * concurrent locked initialization and lock-free rendering using a shared NEWT Display EDT instances. + *

      + * Rendering is always lock-free and independent of the EDT. + *

      + */ +public class InitConcurrentBaseNEWT extends UITestCase { + + static final int demoSize = 128; + + static long duration = 300; // ms + + static InsetsImmutable insets = null; + static int scrnHeight, scrnWidth; + static int num_x, num_y; + + @BeforeClass + public static void initClass() { + Window dummyWindow = NewtFactory.createWindow(new Capabilities()); + dummyWindow.setSize(demoSize, demoSize); + dummyWindow.setVisible(true); + Assert.assertEquals(true, dummyWindow.isVisible()); + Assert.assertEquals(true, dummyWindow.isNativeValid()); + insets = dummyWindow.getInsets(); + scrnHeight = dummyWindow.getScreen().getHeight(); + scrnWidth = dummyWindow.getScreen().getWidth(); + num_x = scrnWidth / ( demoSize + insets.getTotalWidth() ) - 2; + num_y = scrnHeight / ( demoSize + insets.getTotalHeight() ) - 2; + dummyWindow.destroy(); + } + + public class JOGLTask implements Runnable { + private final int id; + private final Object postSync; + private final boolean reuse; + private boolean done = false; + + public JOGLTask(Object postSync, int id, boolean reuse) { + this.postSync = postSync; + this.id = id; + this.reuse = reuse; + } + public void run() { + int x = ( id % num_x ) * ( demoSize + insets.getTotalHeight() ); + int y = ( (id / num_x) % num_y ) * ( demoSize + insets.getTotalHeight() ); + + System.err.println("JOGLTask "+id+": START: "+x+"/"+y+", reuse "+reuse+" - "+Thread.currentThread().getName()); + final Display display = NewtFactory.createDisplay(null, reuse); + final Screen screen = NewtFactory.createScreen(display, 0); + final GLWindow glWindow = GLWindow.create(screen, new GLCapabilities(GLProfile.getDefault())); + Assert.assertNotNull(glWindow); + glWindow.setTitle("Task "+id); + glWindow.setPosition(x + insets.getLeftWidth(), y + insets.getTopHeight() ); + + glWindow.addGLEventListener(new GearsES2(0)); + + Animator animator = new Animator(glWindow); + + glWindow.setSize(demoSize, demoSize); + glWindow.setVisible(true); + animator.setUpdateFPSFrames(60, null); + + System.err.println("JOGLTask "+id+": INITIALIZED: "+", "+display+" - "+Thread.currentThread().getName()); + + animator.start(); + Assert.assertEquals(true, animator.isAnimating()); + Assert.assertEquals(true, glWindow.isVisible()); + Assert.assertEquals(true, glWindow.isNativeValid()); + Assert.assertEquals(true, glWindow.isRealized()); + System.err.println("JOGLTask "+id+": RUNNING: "+Thread.currentThread().getName()); + + while(animator.isAnimating() && animator.getTotalFPSDuration()=0; i--) { + if(!tasks[i].done()) { + return false; + } + } + return true; + } + protected static String doneDump(JOGLTask[] tasks) { + StringBuilder sb = new StringBuilder(); + sb.append("["); + for(int i=0; i0) { + sb.append(", "); + } + sb.append(i).append(": ").append(tasks[i].done()); + } + sb.append("]"); + return sb.toString(); + } + + protected static boolean isDead(Thread[] threads) { + for(int i=threads.length-1; i>=0; i--) { + if(threads[i].isAlive()) { + return false; + } + } + return true; + } + protected static String isAliveDump(Thread[] threads) { + StringBuilder sb = new StringBuilder(); + sb.append("["); + for(int i=0; i0) { + sb.append(", "); + } + sb.append(i).append(": ").append(threads[i].isAlive()); + } + sb.append("]"); + return sb.toString(); + } + + protected void runJOGLTasks(int num, boolean reuse) throws InterruptedException { + final String currentThreadName = Thread.currentThread().getName(); + final Object syncDone = new Object(); + final JOGLTask[] tasks = new JOGLTask[num]; + final Thread[] threads = new Thread[num]; + int i; + for(i=0; i + * Rendering is always lock-free and independent of the EDT, however shared NEWT Display instances + * perform lifecycle actions (window creation etc) with locking. + *

      + */ +public class TestInitConcurrent01NEWT extends InitConcurrentBaseNEWT { + + @Test + public void test02TwoThreads() throws InterruptedException { + runJOGLTasks(2, true); + } + + @Test + public void test02FourThreads() throws InterruptedException { + runJOGLTasks(4, true); + } + + @Test + public void test16SixteenThreads() throws InterruptedException { + if( Platform.getCPUFamily() != Platform.CPUFamily.ARM ) { + runJOGLTasks(16, true); + } else { + runJOGLTasks( 8, true); + } + } + + public static void main(String args[]) throws IOException { + for(int i=0; i + * Rendering is always lock-free and independent of the EDT, however exclusive NEWT Display instances + * perform lifecycle actions (window creation etc) w/o locking. + *

      + */ +public class TestInitConcurrent02NEWT extends InitConcurrentBaseNEWT { + + @Test + public void test02TwoThreads() throws InterruptedException { + runJOGLTasks(2, false); + } + + @Test + public void test02FourThreads() throws InterruptedException { + runJOGLTasks(4, false); + } + + @Test + public void test16SixteenThreads() throws InterruptedException { + if( Platform.getCPUFamily() != Platform.CPUFamily.ARM ) { + runJOGLTasks(16, false); + } else { + runJOGLTasks( 8, false); + } + } + + public static void main(String args[]) throws IOException { + for(int i=0; i=0; i--) { - if(!tasks[i].done()) { - return false; - } - } - return true; - } - protected static String doneDump(JOGLTask[] tasks) { - StringBuilder sb = new StringBuilder(); - sb.append("["); - for(int i=0; i0) { - sb.append(", "); - } - sb.append(i).append(": ").append(tasks[i].done()); - } - sb.append("]"); - return sb.toString(); - } - - protected static boolean isDead(Thread[] threads) { - for(int i=threads.length-1; i>=0; i--) { - if(threads[i].isAlive()) { - return false; - } - } - return true; - } - protected static String isAliveDump(Thread[] threads) { - StringBuilder sb = new StringBuilder(); - sb.append("["); - for(int i=0; i0) { - sb.append(", "); - } - sb.append(i).append(": ").append(threads[i].isAlive()); - } - sb.append("]"); - return sb.toString(); - } - - protected void runJOGLTasks(int num) throws InterruptedException { - final String currentThreadName = Thread.currentThread().getName(); - final Object sync = new Object(); - final JOGLTask[] tasks = new JOGLTask[num]; - final Thread[] threads = new Thread[num]; - int i; - for(i=0; i Date: Fri, 28 Sep 2012 18:52:31 +0200 Subject: NativeWindow/X11 + NEWT/X11: Cache 'isXineramaEnabled()' to reduce X11 server roundtrips. --- .../classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java | 9 +++++++++ .../classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java | 10 +--------- src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java | 9 ++++++--- src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java | 6 ++++-- src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java | 4 ++-- 5 files changed, 22 insertions(+), 16 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index 2e4099c1b..142bb99e3 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -46,6 +46,7 @@ import javax.media.nativewindow.ToolkitLock; public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneable { final boolean handleOwner; + final boolean isXineramaEnabled; /** Constructs a new X11GraphicsDevice corresponding to the given connection and default * {@link javax.media.nativewindow.ToolkitLock} via {@link NativeWindowFactory#getDefaultToolkitLock(String)}.
      @@ -56,6 +57,7 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl public X11GraphicsDevice(String connection, int unitID) { super(NativeWindowFactory.TYPE_X11, connection, unitID); handleOwner = false; + isXineramaEnabled = false; } /** Constructs a new X11GraphicsDevice corresponding to the given native display handle and default @@ -69,6 +71,7 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl throw new NativeWindowException("null display"); } handleOwner = owner; + isXineramaEnabled = X11Util.XineramaIsEnabled(this); } /** @@ -82,7 +85,9 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl throw new NativeWindowException("null display"); } handleOwner = owner; + isXineramaEnabled = X11Util.XineramaIsEnabled(this); } + private static int getDefaultScreenImpl(long dpy) { return X11Lib.DefaultScreen(dpy); @@ -114,6 +119,10 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl return X11Lib.DefaultVisualID(display, getDefaultScreenImpl(display)); } + public final boolean isXineramaEnabled() { + return isXineramaEnabled; + } + @Override public Object clone() { return super.clone(); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java index 7ab5bd6aa..fa57124fb 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java @@ -48,7 +48,7 @@ public class X11GraphicsScreen extends DefaultGraphicsScreen implements Cloneabl /** Constructs a new X11GraphicsScreen corresponding to the given native screen index. */ public X11GraphicsScreen(X11GraphicsDevice device, int screen) { - super(device, fetchScreen(device, screen)); + super(device, device.isXineramaEnabled() ? 0 : screen); } public static AbstractGraphicsScreen createScreenDevice(long display, int screenIdx, boolean owner) { @@ -61,14 +61,6 @@ public class X11GraphicsScreen extends DefaultGraphicsScreen implements Cloneabl return X11Lib.DefaultVisualID(getDevice().getHandle(), getIndex()); } - private static int fetchScreen(X11GraphicsDevice device, int screen) { - // It still could be an AWT hold handle .. - if(X11Util.XineramaIsEnabled(device)) { - screen = 0; // Xinerama -> 1 screen - } - return screen; - } - public Object clone() { return super.clone(); } diff --git a/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java index bff050030..6e80e966a 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java @@ -85,8 +85,8 @@ public class DisplayDriver extends DisplayImpl { CompleteDisplay0(aDevice.getHandle()); } catch(RuntimeException e) { closeNativeImpl(); - throw e; - } + throw e; + } } protected void closeNativeImpl() { @@ -111,6 +111,9 @@ public class DisplayDriver extends DisplayImpl { protected long getJavaObjectAtom() { return javaObjectAtom; } protected long getWindowDeleteAtom() { return windowDeleteAtom; } + /** Returns null if !{@link #isNativeValid()}, otherwise the Boolean value of {@link X11GraphicsDevice#isXineramaEnabled()}. */ + protected Boolean isXineramaEnabled() { return isNativeValid() ? Boolean.valueOf(((X11GraphicsDevice)aDevice).isXineramaEnabled()) : null; } + //---------------------------------------------------------------------- // Internals only // @@ -131,6 +134,6 @@ public class DisplayDriver extends DisplayImpl { private long windowDeleteAtom; /** X11 Window java object property used on EDT */ - private long javaObjectAtom; + private long javaObjectAtom; } diff --git a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java index b09d98e06..7a3c718c0 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java @@ -282,8 +282,10 @@ public class ScreenDriver extends ScreenImpl { } }; protected int validateScreenIndex(final int idx) { - if(getDisplay().isNativeValid()) { - return X11Util.XineramaIsEnabled((X11GraphicsDevice)getDisplay().getGraphicsDevice()) ? 0 : idx; + final DisplayDriver x11Display = (DisplayDriver) getDisplay(); + final Boolean r = x11Display.isXineramaEnabled(); + if( null != r ) { + return r.booleanValue() ? 0 : idx; } else { return runWithTempDisplayHandle( xineramaEnabledQueryWithTemp ).booleanValue() ? 0 : idx; } diff --git a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java index aea86a420..bde723634 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java @@ -74,7 +74,7 @@ public class WindowDriver extends WindowImpl { throw new RuntimeException("Error creating display(EDT): "+edtDevice.getConnection()); } renderDevice = new X11GraphicsDevice(renderDeviceHandle, AbstractGraphicsDevice.DEFAULT_UNIT, true); - AbstractGraphicsScreen renderScreen = new X11GraphicsScreen((X11GraphicsDevice) renderDevice, screen.getIndex()); + final AbstractGraphicsScreen renderScreen = new X11GraphicsScreen(renderDevice, screen.getIndex()); final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice(), capsRequested); final AbstractGraphicsConfiguration cfg = factory.chooseGraphicsConfiguration( @@ -300,5 +300,5 @@ public class WindowDriver extends WindowImpl { private static native void warpPointer0(long display, long windowHandle, int x, int y); private long windowHandleClose; - private AbstractGraphicsDevice renderDevice; + private X11GraphicsDevice renderDevice; } -- cgit v1.2.3 From 30d6d5e3c1ee7132c2b3cc722839528882e03053 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 28 Sep 2012 18:55:09 +0200 Subject: X11 NativeWindow: Fix Error and IOError handler, i.e. NPE checks and no JVM dependency (signal is async); X11Util: XSync w/ discard reusable Display when queue-in. --- .../classes/jogamp/nativewindow/x11/X11Util.java | 1 + src/nativewindow/native/x11/Xmisc.c | 73 ++++++++++------------ 2 files changed, 35 insertions(+), 39 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 60f54eb3c..67508bf87 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -425,6 +425,7 @@ public class X11Util { pendingDisplayList.remove(namedDpy); } else { // for reuse + X11Lib.XSync(namedDpy.getHandle(), true); // flush output buffer and discard all events reusableDisplayList.add(namedDpy); } diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index afdd413eb..9e2130668 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -160,10 +160,12 @@ static JavaVM *jvmHandle = NULL; static int jvmVersion = 0; static void setupJVMVars(JNIEnv * env) { - if(0 != (*env)->GetJavaVM(env, &jvmHandle)) { - jvmHandle = NULL; + if( NULL != env && NULL == jvmHandle ) { + if(0 != (*env)->GetJavaVM(env, &jvmHandle)) { + jvmHandle = NULL; + } + jvmVersion = (*env)->GetVersion(env); } - jvmVersion = (*env)->GetVersion(env); } static XErrorHandler origErrorHandler = NULL ; @@ -175,47 +177,42 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) { if(!errorHandlerQuiet) { const char * errnoStr = strerror(errno); - char threadName[80]; char errCodeStr[80]; char reqCodeStr[80]; int shallBeDetached = 0; JNIEnv *jniEnv = NULL; - if( errorHandlerDebug || errorHandlerThrowException ) { - jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); - } - (void) NativewindowCommon_GetStaticStringMethod(jniEnv, X11UtilClazz, getCurrentThreadNameID, threadName, sizeof(threadName), "n/a"); - snprintf(errCodeStr, sizeof(errCodeStr), "%d", e->request_code); XGetErrorDatabaseText(dpy, "XRequest", errCodeStr, "Unknown", reqCodeStr, sizeof(reqCodeStr)); XGetErrorText(dpy, e->error_code, errCodeStr, sizeof(errCodeStr)); - fprintf(stderr, "Info: Nativewindow X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", - threadName, e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, + fprintf(stderr, "Info: Nativewindow X11 Error: %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", + e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, (int)e->request_code, (int)e->minor_code, reqCodeStr); + fflush(stderr); - if( errorHandlerDebug && NULL != jniEnv ) { - (*jniEnv)->CallStaticVoidMethod(jniEnv, X11UtilClazz, dumpStackID); + if( NULL != jvmHandle && ( errorHandlerDebug || errorHandlerThrowException ) ) { + jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); + if(NULL == jniEnv) { + fprintf(stderr, "Nativewindow X11 Error: null JNIEnv"); + fflush(stderr); + } } - if(errorHandlerThrowException) { - if(NULL != jniEnv) { - NativewindowCommon_throwNewRuntimeException(jniEnv, "Nativewindow X11 Error (Thread: %s): %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", - threadName, e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, + if( NULL != jniEnv ) { + if( errorHandlerDebug ) { + (*jniEnv)->CallStaticVoidMethod(jniEnv, X11UtilClazz, dumpStackID); + } + + if(errorHandlerThrowException) { + NativewindowCommon_throwNewRuntimeException(jniEnv, "Nativewindow X11 Error: %d - %s, dpy %p, id %x, # %d: %d:%d %s\n", + e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, (int)e->request_code, (int)e->minor_code, reqCodeStr); - } else { - fprintf(stderr, "Nativewindow X11 Error: null JNIEnv"); - #if 0 - if(NULL!=origErrorHandler) { - origErrorHandler(dpy, e); - } - #endif } - } - fflush(stderr); - if (NULL != jniEnv && shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); + if (shallBeDetached) { + (*jvmHandle)->DetachCurrentThread(jvmHandle); + } } } @@ -253,17 +250,15 @@ static int x11IOErrorHandler(Display *dpy) JNIEnv *jniEnv = NULL; fprintf(stderr, "Nativewindow X11 IOError: Display %p (%s): %s\n", dpy, dpyName, errnoStr); - (*jniEnv)->CallStaticVoidMethod(jniEnv, X11UtilClazz, dumpStackID); - - jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); - if (NULL != jniEnv) { - char threadName[80]; - (void) NativewindowCommon_GetStaticStringMethod(jniEnv, X11UtilClazz, getCurrentThreadNameID, threadName, sizeof(threadName), "n/a"); - - NativewindowCommon_FatalError(jniEnv, "Nativewindow X11 IOError (Thread %s): Display %p (%s): %s", threadName, dpy, dpyName, errnoStr); - - if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); + fflush(stderr); + + if( NULL != jvmHandle ) { + jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); + if (NULL != jniEnv) { + NativewindowCommon_FatalError(jniEnv, "Nativewindow X11 IOError: Display %p (%s): %s", dpy, dpyName, errnoStr); + if (shallBeDetached) { + (*jvmHandle)->DetachCurrentThread(jvmHandle); + } } } if(NULL!=origIOErrorHandler) { -- cgit v1.2.3 From 43891be36e8485353ac74f329fd2f7438303a846 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 29 Sep 2012 04:41:47 +0200 Subject: Cache XineramaIsEnabled(dpy) per display-name in X11Util minimize triggering ATI driver bug of sporadic XCB errors and to reduce server roundtrips. Enhances commit: e4176f4e76f519b3599ad557210def3d35266e7b X11Util.XineramaIsEnabled(dpy) hash maps the Xinerama enable result to the dpy-name. Minimize triggering ATI driver bug of sporadic XCB errors: Our multithreading code somehow triggers an _XReply in XQueryExtension beside other functions, which fails the XCB assertion: ../../src/xcb_io.c:178: dequeue_pending_request: Assertion `!xcb_xlib_unknown_req_in_deq' failed. This only appears w/ ATI driver and is probably due to a race condition in the driver (?). This change also reduces server roundtrips / querying time for the cost of 1 hash-map. --- make/scripts/tests.sh | 1 - .../classes/jogamp/nativewindow/x11/X11Util.java | 31 +++++++++++++++++----- 2 files changed, 24 insertions(+), 8 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index f3a71d288..345e23ae7 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -137,7 +137,6 @@ function jrun() { #D_ARGS="-Dnativewindow.debug=all" #D_ARGS="-Djogl.debug.GLCanvas" #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.X11Util.XSync" - D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.X11Util.XSync" #D_ARGS="-Dnativewindow.debug.X11Util.XSync" #D_ARGS="-Dnativewindow.debug.ToolkitLock" #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLCode -Djogl.debug.TraceGL" diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 67508bf87..30792113d 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -34,6 +34,7 @@ package jogamp.nativewindow.x11; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import javax.media.nativewindow.AbstractGraphicsDevice; @@ -139,6 +140,7 @@ public class X11Util { private static List openDisplayList = new ArrayList(); // open, no close attempt private static List reusableDisplayList = new ArrayList(); // close attempt, marked uncloseable, for reuse private static List pendingDisplayList = new ArrayList(); // all open (close attempt or reusable) in creation order + private static final HashMap displayXineramaEnabledMap = new HashMap(); /** * Cleanup resources. @@ -178,6 +180,7 @@ public class X11Util { reusableDisplayList.clear(); pendingDisplayList.clear(); openDisplayMap.clear(); + displayXineramaEnabledMap.clear(); shutdown0(); } } @@ -503,10 +506,19 @@ public class X11Util { device.unlock(); } } + public static boolean XineramaIsEnabled(long displayHandle) { if( 0 == displayHandle ) { throw new IllegalArgumentException("X11 Display handle is NULL"); } + final String displayName = X11Lib.XDisplayString(displayHandle); + synchronized(displayXineramaEnabledMap) { + final Boolean b = displayXineramaEnabledMap.get(displayName); + if(null != b) { + return b.booleanValue(); + } + } + final boolean res; if(!XineramaFetched) { // volatile: ok synchronized(X11Util.class) { if( !XineramaFetched ) { @@ -519,16 +531,21 @@ public class X11Util { } } if(0!=XineramaQueryFunc) { - final boolean res = X11Lib.XineramaIsEnabled(XineramaQueryFunc, displayHandle); + res = X11Lib.XineramaIsEnabled(XineramaQueryFunc, displayHandle); + } else { if(DEBUG) { - System.err.println("XineramaIsEnabled: 0x"+Long.toHexString(displayHandle)+": "+res); + System.err.println("XineramaIsEnabled: Couldn't bind to Xinerama - lib 0x"+Long.toHexString(XineramaLibHandle)+ + "query 0x"+Long.toHexString(XineramaQueryFunc)); } - return res; - } else if(DEBUG) { - System.err.println("XineramaIsEnabled: Couldn't bind to Xinerama - lib 0x"+Long.toHexString(XineramaLibHandle)+ - "query 0x"+Long.toHexString(XineramaQueryFunc)); + res = false; } - return false; + synchronized(displayXineramaEnabledMap) { + if(DEBUG) { + System.err.println("XineramaIsEnabled Cache: Display "+displayName+" (0x"+Long.toHexString(displayHandle)+") -> "+res); + } + displayXineramaEnabledMap.put(displayName, Boolean.valueOf(res)); + } + return res; } private static final String getCurrentThreadName() { return Thread.currentThread().getName(); } // Callback for JNI -- cgit v1.2.3 From 8a1e50dc33e14e9423e2f4bc066b32a835bb33fb Mon Sep 17 00:00:00 2001 From: Xerxes RÃ¥nby Date: Sun, 30 Sep 2012 00:51:39 +0200 Subject: _getNativeWindowingType() TYPE_BCM_VC_IV autodetection. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Xerxes RÃ¥nby --- .../javax/media/nativewindow/NativeWindowFactory.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 4f4bb629b..d1ec3a4da 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -33,6 +33,7 @@ package javax.media.nativewindow; +import java.io.File; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; @@ -65,6 +66,9 @@ public abstract class NativeWindowFactory { /** X11 type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ public static final String TYPE_X11 = ".x11".intern(); + /** Broadcom VC IV/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ + public static final String TYPE_BCM_VC_IV = "jogamp.newt.driver.bcm.vc.iv".intern(); + /** Android/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}.*/ public static final String TYPE_ANDROID = ".android".intern(); @@ -102,6 +106,18 @@ public abstract class NativeWindowFactory { protected NativeWindowFactory() { } + private static final boolean guessBroadcomVCIV() { + return AccessController.doPrivileged(new PrivilegedAction() { + private final File vcliblocation = new File( + "/opt/vc/lib/libbcm_host.so"); + public Boolean run() { + if ( vcliblocation.isFile() ) { + return new Boolean(true); + } + return new Boolean(false); + } } ).booleanValue(); + } + private static String _getNativeWindowingType() { switch(Platform.OS_TYPE) { case ANDROID: @@ -118,6 +134,8 @@ public abstract class NativeWindowFactory { case SUNOS: case HPUX: default: + if(guessBroadcomVCIV()) + return TYPE_BCM_VC_IV; return TYPE_X11; } } -- cgit v1.2.3 From fa55b54822a256eb73147763829b946433c3d3f7 Mon Sep 17 00:00:00 2001 From: Xerxes RÃ¥nby Date: Sun, 30 Sep 2012 01:24:07 +0200 Subject: ".bcm.vc.iv" is enough now -> NEWT agnostic relative package path. --- .../classes/javax/media/nativewindow/NativeWindowFactory.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index d1ec3a4da..886c9af34 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -67,7 +67,7 @@ public abstract class NativeWindowFactory { public static final String TYPE_X11 = ".x11".intern(); /** Broadcom VC IV/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}. */ - public static final String TYPE_BCM_VC_IV = "jogamp.newt.driver.bcm.vc.iv".intern(); + public static final String TYPE_BCM_VC_IV = ".bcm.vc.iv".intern(); /** Android/EGL type, as retrieved with {@link #getNativeWindowType(boolean)}. String is canonical via {@link String#intern()}.*/ public static final String TYPE_ANDROID = ".android".intern(); -- cgit v1.2.3 From 8351d513730009316b81149414ea87f3c631f9a2 Mon Sep 17 00:00:00 2001 From: Xerxes RÃ¥nby Date: Sun, 30 Sep 2012 01:32:35 +0200 Subject: Add braces and fix indentation to conform with jogl coding standards. --- .../classes/javax/media/nativewindow/NativeWindowFactory.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 886c9af34..ddacc2859 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -115,7 +115,8 @@ public abstract class NativeWindowFactory { return new Boolean(true); } return new Boolean(false); - } } ).booleanValue(); + } + } ).booleanValue(); } private static String _getNativeWindowingType() { @@ -134,8 +135,9 @@ public abstract class NativeWindowFactory { case SUNOS: case HPUX: default: - if(guessBroadcomVCIV()) + if( guessBroadcomVCIV() ) { return TYPE_BCM_VC_IV; + } return TYPE_X11; } } -- cgit v1.2.3 From 92398025abdabb2fdef0d78edd41e730991a6f94 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 30 Sep 2012 19:47:46 +0200 Subject: Workaround for Bug 623: Sporadic XCB assertion failures w/ ATI proprietary driver and w/o native X11 locking The proprietary ATI X11 driver does not handle multi-threaded [GL] clients well, i.e. triggers an XCB assertion 'from time to time'. It almost seems like that the driver either: - aliases all display connections to it's connection name, i.e. server; or - utilizes a build-in display connection w/o locking, used for some reason +++ - X11Lib: Add QueryExtension(dpy, name) allowing early driver determination w/o GL - X11Util detects 'requiresGlobalToolkitLock' and 'markAllDisplaysUnclosable' via X11 extensions. In case certain ATI extensions are available, both are set to true. - X11GLXDrawableFactory: Dropped setting 'markAllDisplaysUnclosable', using X11Util's detection (see above). - New GlobalToolkitLock to satisfy certain driver restrictions (ATI's XCB multithreading bug) - NativeWindowFactory handles new property requiresGlobalToolkitLock, in which case the new GlobalToolkitLock is being used instead of ResourceToolkitLock. - JAWTUtil ToolkitLock locks GlobalToolkitLock 1st to match new 'requiresGlobalToolkitLock' property. - Document static method requirement of X11Util, GDIUtil and OSXUtil via marker interface ToolkitProperties - ToolkitLock: New method 'validateLocked()', allowing use to validate whether the device/toolkit is properly locked and hence to detect implementation bugs. See unit test class: ValidateLockListener --- make/config/nativewindow/x11-CustomJavaCode.java | 5 + make/scripts/tests.sh | 8 +- .../opengl/x11/glx/X11GLXDrawableFactory.java | 4 - .../jogamp/nativewindow/x11/X11GraphicsDevice.java | 2 +- .../media/nativewindow/AbstractGraphicsDevice.java | 11 ++- .../media/nativewindow/DefaultGraphicsDevice.java | 21 +++-- .../media/nativewindow/NativeWindowFactory.java | 101 +++++++++++++-------- .../javax/media/nativewindow/ToolkitLock.java | 22 ++++- .../jogamp/nativewindow/GlobalToolkitLock.java | 75 +++++++++++++++ .../nativewindow/NativeWindowFactoryImpl.java | 7 +- .../jogamp/nativewindow/NullToolkitLock.java | 19 +++- .../jogamp/nativewindow/ResourceToolkitLock.java | 15 ++- .../nativewindow/SharedResourceToolkitLock.java | 11 ++- .../jogamp/nativewindow/ToolkitProperties.java | 51 +++++++++++ .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 36 +++++++- .../jogamp/nativewindow/macosx/OSXUtil.java | 22 +++-- .../jogamp/nativewindow/windows/GDIUtil.java | 15 ++- .../classes/jogamp/nativewindow/x11/X11Util.java | 51 ++++++++--- src/nativewindow/native/x11/Xmisc.c | 35 +++++++ .../junit/jogl/acore/InitConcurrentBaseNEWT.java | 2 + .../test/junit/util/ValidateLockListener.java | 71 +++++++++++++++ 21 files changed, 496 insertions(+), 88 deletions(-) create mode 100644 src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java create mode 100644 src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java create mode 100644 src/test/com/jogamp/opengl/test/junit/util/ValidateLockListener.java (limited to 'src/nativewindow') diff --git a/make/config/nativewindow/x11-CustomJavaCode.java b/make/config/nativewindow/x11-CustomJavaCode.java index 56aec4725..8e5da3b2d 100644 --- a/make/config/nativewindow/x11-CustomJavaCode.java +++ b/make/config/nativewindow/x11-CustomJavaCode.java @@ -36,6 +36,11 @@ } private static native Object GetRelativeLocation0(long display, int screen_index, long src_win, long dest_win, int src_x, int src_y); + public static boolean QueryExtension(long display, String extensionName) { + return QueryExtension0(display, extensionName); + } + private static native boolean QueryExtension0(long display, String extensionName); + public static native int XCloseDisplay(long display); public static native void XUnlockDisplay(long display); public static native void XLockDisplay(long display); diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 345e23ae7..0908ef1fd 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -137,7 +137,8 @@ function jrun() { #D_ARGS="-Dnativewindow.debug=all" #D_ARGS="-Djogl.debug.GLCanvas" #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.X11Util.XSync" - #D_ARGS="-Dnativewindow.debug.X11Util.XSync" + #D_ARGS="-Dnativewindow.debug.X11Util.XSync -Dnativewindow.debug.ToolkitLock.TraceLock" + D_ARGS="-Dnativewindow.debug.X11Util -Dnativewindow.debug.X11Util.XSync -Dnativewindow.debug.NullToolkitLock.InvalidLocked -Dnativewindow.debug.NativeWindow" #D_ARGS="-Dnativewindow.debug.ToolkitLock" #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLCode -Djogl.debug.TraceGL" #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLState" @@ -245,7 +246,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent01NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent02NEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextSurfaceLockNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug00NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug01NEWT $* @@ -254,7 +255,8 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES1NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateNEWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestBug623ATIXCBAssertionFailureNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT $* diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index b867125ad..018f6a6ea 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -241,10 +241,6 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { final String glXServerVendorName = GLX.glXQueryServerString(sharedDevice.getHandle(), 0, GLX.GLX_VENDOR); final VersionNumber glXServerVersion = GLXUtil.getGLXServerVersionNumber(sharedDevice); final boolean glXServerMultisampleAvailable = GLXUtil.isMultisampleAvailable(GLX.glXQueryServerString(sharedDevice.getHandle(), 0, GLX.GLX_EXTENSIONS)); - if(X11Util.ATI_HAS_XCLOSEDISPLAY_BUG && GLXUtil.isVendorATI(glXServerVendorName)) { - X11Util.setMarkAllDisplaysUnclosable(true); - X11Util.markDisplayUncloseable(sharedDevice.getHandle()); - } final GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP, false); if (null == glp) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index 142bb99e3..0f28ca67c 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -61,7 +61,7 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl } /** Constructs a new X11GraphicsDevice corresponding to the given native display handle and default - * {@link javax.media.nativewindow.ToolkitLock} via {@link NativeWindowFactory#createDefaultToolkitLock(String, long)}. + * {@link javax.media.nativewindow.ToolkitLock} via {@link NativeWindowFactory#getDefaultToolkitLock(String, long)}. * @see DefaultGraphicsDevice#DefaultGraphicsDevice(String, String, int, long) */ public X11GraphicsDevice(long display, int unitID, boolean owner) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java index 5eaaa6613..8ecd5242d 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java @@ -102,17 +102,24 @@ public interface AbstractGraphicsDevice extends Cloneable { public long getHandle(); /** - * Optionally locking the device, utilizing eg {@link javax.media.nativewindow.ToolkitLock}. + * Optionally locking the device, utilizing eg {@link javax.media.nativewindow.ToolkitLock#lock()}. * The lock implementation must be recursive. */ public void lock(); /** - * Optionally unlocking the device, utilizing eg {@link javax.media.nativewindow.ToolkitLock}. + * Optionally unlocking the device, utilizing eg {@link javax.media.nativewindow.ToolkitLock#unlock()}. * The lock implementation must be recursive. + * + * @throws RuntimeException in case the lock is not acquired by this thread. */ public void unlock(); + /** + * @throws RuntimeException if current thread does not hold the lock + */ + public void validateLocked() throws RuntimeException; + /** * Optionally [re]opening the device if handle is null. *

      diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java index b16b0c75c..9288652d9 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java @@ -60,7 +60,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice /** * Create an instance with the system default {@link ToolkitLock}. - * gathered via {@link NativeWindowFactory#createDefaultToolkitLock(String, long)}. + * gathered via {@link NativeWindowFactory#getDefaultToolkitLock(String, long)}. * @param type * @param handle */ @@ -70,7 +70,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice this.unitID = unitID; this.uniqueID = getUniqueID(type, connection, unitID); this.handle = handle; - this.toolkitLock = NativeWindowFactory.createDefaultToolkitLock(type, handle); + this.toolkitLock = NativeWindowFactory.getDefaultToolkitLock(type, handle); } /** @@ -123,8 +123,10 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice } /** - * No lock is performed on the graphics device per default, - * instead the aggregated recursive {@link ToolkitLock#lock()} is invoked. + * {@inheritDoc} + *

      + * Locking is perfomed via delegation to {@link ToolkitLock#lock()}, {@link ToolkitLock#unlock()}. + *

      * * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long) * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long, javax.media.nativewindow.ToolkitLock) @@ -134,9 +136,16 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice toolkitLock.lock(); } + @Override + public final void validateLocked() throws RuntimeException { + toolkitLock.validateLocked(); + } + /** - * No lock is performed on the graphics device per default, - * instead the aggregated recursive {@link ToolkitLock#unlock()} is invoked. + * {@inheritDoc} + *

      + * Locking is perfomed via delegation to {@link ToolkitLock#lock()}, {@link ToolkitLock#unlock()}. + *

      * * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long) * @see DefaultGraphicsDevice#DefaultGraphicsDevice(java.lang.String, long, javax.media.nativewindow.ToolkitLock) diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 4f4bb629b..af8008f0f 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -42,6 +42,7 @@ import java.util.Map; import jogamp.nativewindow.Debug; import jogamp.nativewindow.NativeWindowFactoryImpl; +import jogamp.nativewindow.ToolkitProperties; import jogamp.nativewindow.ResourceToolkitLock; import com.jogamp.common.os.Platform; @@ -87,13 +88,17 @@ public abstract class NativeWindowFactory { private static boolean isAWTAvailable; private static final String JAWTUtilClassName = "jogamp.nativewindow.jawt.JAWTUtil" ; + /** {@link jogamp.nativewindow.x11.X11Util} implements {@link ToolkitProperties}. */ private static final String X11UtilClassName = "jogamp.nativewindow.x11.X11Util"; + /** {@link jogamp.nativewindow.macosx.OSXUtil} implements {@link ToolkitProperties}. */ private static final String OSXUtilClassName = "jogamp.nativewindow.macosx.OSXUtil"; + /** {@link jogamp.nativewindow.windows.GDIUtil} implements {@link ToolkitProperties}. */ private static final String GDIClassName = "jogamp.nativewindow.windows.GDIUtil"; private static ToolkitLock jawtUtilJAWTToolkitLock; private static boolean requiresToolkitLock; + private static boolean requiresGlobalToolkitLock; private static volatile boolean isJVMShuttingDown = false; @@ -156,11 +161,18 @@ public abstract class NativeWindowFactory { if( null != clazzName ) { ReflectionUtil.callStaticMethod(clazzName, "initSingleton", null, null, cl ); - final Boolean res = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "requiresToolkitLock", null, null, cl); - requiresToolkitLock = res.booleanValue(); + final Boolean res1 = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "requiresToolkitLock", null, null, cl); + requiresToolkitLock = res1.booleanValue(); + if(requiresToolkitLock) { + final Boolean res2 = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "requiresGlobalToolkitLock", null, null, cl); + requiresGlobalToolkitLock = res2.booleanValue(); + } else { + requiresGlobalToolkitLock = false; + } } else { requiresToolkitLock = false; - } + requiresGlobalToolkitLock = false; + } } private static void shutdownNativeImpl(final ClassLoader cl) { @@ -261,7 +273,7 @@ public abstract class NativeWindowFactory { } if(DEBUG) { - System.err.println("NativeWindowFactory requiresToolkitLock "+requiresToolkitLock); + System.err.println("NativeWindowFactory requiresToolkitLock "+requiresToolkitLock+", requiresGlobalToolkitLock "+requiresGlobalToolkitLock); System.err.println("NativeWindowFactory isAWTAvailable "+isAWTAvailable+", defaultFactory "+factory); } @@ -295,7 +307,12 @@ public abstract class NativeWindowFactory { /** @return true if the underlying toolkit requires locking, otherwise false. */ public static boolean requiresToolkitLock() { return requiresToolkitLock; - } + } + + /** @return true if the underlying toolkit requires global locking, otherwise false. */ + public static boolean requiresGlobalToolkitLock() { + return requiresGlobalToolkitLock; + } /** @return true if not headless, AWT Component and NativeWindow's AWT part available */ public static boolean isAWTAvailable() { return isAWTAvailable; } @@ -331,9 +348,28 @@ public abstract class NativeWindowFactory { return defaultFactory; } + /** + * Returns the AWT {@link ToolkitLock} (JAWT based) if {@link #isAWTAvailable}, otherwise null. + *

      + * The JAWT based {@link ToolkitLock} also locks the global lock, + * which matters if the latter is required. + *

      + */ + public static ToolkitLock getAWTToolkitLock() { + return jawtUtilJAWTToolkitLock; + } + + public static ToolkitLock getNullToolkitLock() { + return NativeWindowFactoryImpl.getNullToolkitLock(); + } + + public static ToolkitLock getGlobalToolkitLock() { + return NativeWindowFactoryImpl.getGlobalToolkitLock(); + } + /** - * Provides the system default {@link ToolkitLock}, a singleton instance. - *
      + * Provides the system default {@link ToolkitLock} for the default system windowing type. + * @see #getNativeWindowType(boolean) * @see #getDefaultToolkitLock(java.lang.String) */ public static ToolkitLock getDefaultToolkitLock() { @@ -341,57 +377,44 @@ public abstract class NativeWindowFactory { } /** - * Provides the default {@link ToolkitLock} for type, a singleton instance. + * Provides the default {@link ToolkitLock} for type. *
        - *
      • JAWT {@link ToolkitLock} if required and AWT available, otherwise
      • + *
      • JAWT {@link ToolkitLock} if required and type is of {@link #TYPE_AWT} and AWT available,
      • + *
      • {@link jogamp.nativewindow.GlobalToolkitLock} if required, otherwise
      • + *
      • {@link jogamp.nativewindow.ResourceToolkitLock} if required, otherwise
      • *
      • {@link jogamp.nativewindow.NullToolkitLock}
      • *
      */ public static ToolkitLock getDefaultToolkitLock(String type) { - if( requiresToolkitLock() ) { - if( TYPE_AWT == type && TYPE_X11 == getNativeWindowType(false) && isAWTAvailable() ) { + if( requiresToolkitLock ) { + if( TYPE_AWT == type && isAWTAvailable() ) { return getAWTToolkitLock(); } - } - return NativeWindowFactoryImpl.getNullToolkitLock(); - } - - /** Returns the AWT Toolkit (JAWT based) if {@link #isAWTAvailable}, otherwise null. */ - public static ToolkitLock getAWTToolkitLock() { - return jawtUtilJAWTToolkitLock; - } - - public static ToolkitLock getNullToolkitLock() { - return NativeWindowFactoryImpl.getNullToolkitLock(); - } - - /** - * Creates the default {@link ToolkitLock} for type and deviceHandle. - *
        - *
      • {@link jogamp.nativewindow.ResourceToolkitLock} if required, otherwise
      • - *
      • {@link jogamp.nativewindow.NullToolkitLock}
      • - *
      - */ - public static ToolkitLock createDefaultToolkitLock(String type, long deviceHandle) { - if( requiresToolkitLock() ) { + if( requiresGlobalToolkitLock ) { + return NativeWindowFactoryImpl.getGlobalToolkitLock(); + } return ResourceToolkitLock.create(); } return NativeWindowFactoryImpl.getNullToolkitLock(); } - + /** - * Creates the default {@link ToolkitLock} for type and deviceHandle. + * Provides the default {@link ToolkitLock} for type and deviceHandle. *
        - *
      • JAWT {@link ToolkitLock} if required and AWT available,
      • + *
      • JAWT {@link ToolkitLock} if required and type is of {@link #TYPE_AWT} and AWT available,
      • + *
      • {@link jogamp.nativewindow.GlobalToolkitLock} if required, otherwise
      • *
      • {@link jogamp.nativewindow.ResourceToolkitLock} if required, otherwise
      • *
      • {@link jogamp.nativewindow.NullToolkitLock}
      • *
      */ - public static ToolkitLock createDefaultToolkitLock(String type, String sharedType, long deviceHandle) { - if( requiresToolkitLock() ) { - if( TYPE_AWT == sharedType && isAWTAvailable() ) { + public static ToolkitLock getDefaultToolkitLock(String type, long deviceHandle) { + if( requiresToolkitLock ) { + if( TYPE_AWT == type && isAWTAvailable() ) { return getAWTToolkitLock(); } + if( requiresGlobalToolkitLock ) { + return NativeWindowFactoryImpl.getGlobalToolkitLock(); + } return ResourceToolkitLock.create(); } return NativeWindowFactoryImpl.getNullToolkitLock(); diff --git a/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java b/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java index 18b7cf5d9..eccfcfa4f 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java @@ -37,15 +37,35 @@ import jogamp.nativewindow.Debug; * Toolkit locks are created solely via {@link NativeWindowFactory}. *

      *

      - * One use case is the AWT locking on X11, see {@link NativeWindowFactory#createDefaultToolkitLock(String, long)}. + * One use case is the AWT locking on X11, see {@link NativeWindowFactory#getDefaultToolkitLock(String, long)}. *

      */ public interface ToolkitLock { + public static final boolean DEBUG = Debug.debug("ToolkitLock"); public static final boolean TRACE_LOCK = Debug.isPropertyDefined("nativewindow.debug.ToolkitLock.TraceLock", true); + /** + * Blocking until the lock is acquired by this Thread or a timeout is reached. + *

      + * Timeout is implementation specific, if used at all. + *

      + * + * @throws RuntimeException in case of a timeout + */ public void lock(); + + /** + * Release the lock. + * + * @throws RuntimeException in case the lock is not acquired by this thread. + */ public void unlock(); + /** + * @throws RuntimeException if current thread does not hold the lock + */ + public void validateLocked() throws RuntimeException; + /** * Dispose this instance. *

      diff --git a/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java new file mode 100644 index 000000000..0c2a1e43f --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java @@ -0,0 +1,75 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.nativewindow; + +import javax.media.nativewindow.ToolkitLock; + +import com.jogamp.common.util.locks.LockFactory; +import com.jogamp.common.util.locks.RecursiveLock; + +/** + * Implementing a global recursive {@link javax.media.nativewindow.ToolkitLock}. + *

      + * This is the last resort for unstable driver, e.g. proprietary ATI/X11 12.8 and 12.9, + * where multiple X11 display connections to the same connection name are not treated + * thread safe within the GL/X11 driver. + *

      + */ +public class GlobalToolkitLock implements ToolkitLock { + private static final RecursiveLock globalLock = LockFactory.createRecursiveLock(); + + /** Singleton via {@link NativeWindowFactoryImpl#getGlobalToolkitLock()} */ + protected GlobalToolkitLock() { } + + @Override + public final void lock() { + globalLock.lock(); + if(TRACE_LOCK) { System.err.println("GlobalToolkitLock.lock()"); } + } + + @Override + public final void unlock() { + if(TRACE_LOCK) { System.err.println("GlobalToolkitLock.unlock()"); } + globalLock.unlock(); // implicit lock validation + } + + @Override + public final void validateLocked() throws RuntimeException { + globalLock.validateLocked(); + } + + @Override + public final void dispose() { + // nop + } + + public String toString() { + return "GlobalToolkitLock[obj 0x"+Integer.toHexString(hashCode())+", isOwner "+globalLock.isOwner(Thread.currentThread())+", "+globalLock.toString()+"]"; + } +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java index 29564da3b..c35cede77 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java @@ -44,9 +44,14 @@ import com.jogamp.common.util.ReflectionUtil.AWTNames; public class NativeWindowFactoryImpl extends NativeWindowFactory { private static final ToolkitLock nullToolkitLock = new NullToolkitLock(); + private static final ToolkitLock globalToolkitLock = new GlobalToolkitLock(); public static ToolkitLock getNullToolkitLock() { - return nullToolkitLock; + return nullToolkitLock; + } + + public static ToolkitLock getGlobalToolkitLock() { + return globalToolkitLock; } // This subclass of NativeWindowFactory handles the case of diff --git a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java index e59910138..211e15955 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java @@ -31,15 +31,16 @@ package jogamp.nativewindow; import javax.media.nativewindow.ToolkitLock; /** - * Implementing a singleton global recursive {@link javax.media.nativewindow.ToolkitLock} - * without any locking. Since there is no locking it all, - * it is intrinsically recursive. + * Implementing a singleton global NOP {@link javax.media.nativewindow.ToolkitLock} + * without any locking. Since there is no locking it all, it is intrinsically recursive. */ public class NullToolkitLock implements ToolkitLock { - + public static final boolean INVALID_LOCKED = Debug.isPropertyDefined("nativewindow.debug.NullToolkitLock.InvalidLocked", true); + /** Singleton via {@link NativeWindowFactoryImpl#getNullToolkitLock()} */ protected NullToolkitLock() { } + @Override public final void lock() { if(TRACE_LOCK) { System.err.println("NullToolkitLock.lock()"); @@ -47,10 +48,20 @@ public class NullToolkitLock implements ToolkitLock { } } + @Override public final void unlock() { if(TRACE_LOCK) { System.err.println("NullToolkitLock.unlock()"); } } + @Override + public final void validateLocked() throws RuntimeException { + /* nop */ + if(INVALID_LOCKED) { + throw new RuntimeException("NullToolkitLock does not lock"); + } + } + + @Override public final void dispose() { // nop } diff --git a/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java index a3b0804fa..5b79de0b8 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java @@ -41,8 +41,6 @@ import com.jogamp.common.util.locks.RecursiveLock; *

      */ public class ResourceToolkitLock implements ToolkitLock { - public static final boolean DEBUG = Debug.debug("ToolkitLock"); - public static final ResourceToolkitLock create() { return new ResourceToolkitLock(); } @@ -53,17 +51,24 @@ public class ResourceToolkitLock implements ToolkitLock { this.lock = LockFactory.createRecursiveLock(); } - + @Override public final void lock() { - if(TRACE_LOCK) { System.err.println("ResourceToolkitLock.lock()"); } lock.lock(); + if(TRACE_LOCK) { System.err.println("ResourceToolkitLock.lock()"); } } + @Override public final void unlock() { if(TRACE_LOCK) { System.err.println("ResourceToolkitLock.unlock()"); } - lock.unlock(); + lock.unlock(); // implicit lock validation + } + + @Override + public final void validateLocked() throws RuntimeException { + lock.validateLocked(); } + @Override public final void dispose() { // nop } diff --git a/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java index 5d7ae8abb..94d12e6fc 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java @@ -49,7 +49,6 @@ import com.jogamp.common.util.locks.RecursiveLock; *

      */ public class SharedResourceToolkitLock implements ToolkitLock { - public static final boolean DEBUG = Debug.debug("ToolkitLock"); private static final LongObjectHashMap handle2Lock; static { handle2Lock = new LongObjectHashMap(); @@ -109,16 +108,24 @@ public class SharedResourceToolkitLock implements ToolkitLock { } + @Override public final void lock() { - if(TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.lock()"); } lock.lock(); + if(TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.lock()"); } } + @Override public final void unlock() { if(TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.unlock()"); } lock.unlock(); } + @Override + public final void validateLocked() throws RuntimeException { + lock.validateLocked(); + } + + @Override public final void dispose() { if(0 < refCount) { // volatile OK synchronized(handle2Lock) { diff --git a/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java b/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java new file mode 100644 index 000000000..2062d1f58 --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java @@ -0,0 +1,51 @@ +package jogamp.nativewindow; + +import javax.media.nativewindow.NativeWindowFactory; + +/** + * Marker interface. + *

      + * Implementation requires to provide static methods: + *

      +    public static void initSingleton() {}
      +    
      +    public static void shutdown() {}
      +    
      +    public static boolean requiresToolkitLock() {}
      +    
      +    public static boolean requiresGlobalToolkitLock() {}
      + * 
      + * Above static methods are invoked by {@link NativeWindowFactory#initSingleton()}, + * or {@link NativeWindowFactory#shutdown()} via reflection. + *

      + *

      + * If requiresGlobalToolkitLock() == true, then + * requiresToolkitLock() == true shall be valid as well. + *

      + */ +public interface ToolkitProperties { + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + */ + // void initSingleton(); + + /** + * Cleanup resources. + *

      + * Called by {@link NativeWindowFactory#shutdown()} + *

      + */ + // void shutdown(); + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + */ + // boolean requiresToolkitLock(); + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + */ + // boolean requiresGlobalToolkitLock(); + +} diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index 7c934b154..2dadfb16b 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -79,6 +79,8 @@ public class JAWTUtil { private static final Method sunToolkitAWTLockMethod; private static final Method sunToolkitAWTUnlockMethod; private static final boolean hasSunToolkitAWTLock; + + private static volatile Thread exclusiveOwnerThread; private static final ToolkitLock jawtToolkitLock; @@ -229,13 +231,23 @@ public class JAWTUtil { } hasSunToolkitAWTLock = _hasSunToolkitAWTLock; // hasSunToolkitAWTLock = false; + exclusiveOwnerThread = null; jawtToolkitLock = new ToolkitLock() { public final void lock() { + NativeWindowFactory.getGlobalToolkitLock().lock(); JAWTUtil.lockToolkit(); + if(TRACE_LOCK) { System.err.println("JAWTToolkitLock.lock()"); } } public final void unlock() { + if(TRACE_LOCK) { System.err.println("JAWTToolkitLock.unlock()"); } JAWTUtil.unlockToolkit(); + NativeWindowFactory.getGlobalToolkitLock().unlock(); + } + @Override + public final void validateLocked() throws RuntimeException { + NativeWindowFactory.getGlobalToolkitLock().validateLocked(); + JAWTUtil.validateLocked(); } public final void dispose() { // nop @@ -312,7 +324,7 @@ public class JAWTUtil { * JAWT's native Lock() function calls SunToolkit.awtLock(), * which just uses AWT's global ReentrantLock.
      */ - private static void awtLock() { + private static final void awtLock() { if(hasSunToolkitAWTLock) { try { sunToolkitAWTLockMethod.invoke(null, (Object[])null); @@ -322,6 +334,7 @@ public class JAWTUtil { } else { jawtLockObject.Lock(); } + exclusiveOwnerThread = Thread.currentThread(); } /** @@ -330,7 +343,9 @@ public class JAWTUtil { * JAWT's native Unlock() function calls SunToolkit.awtUnlock(), * which just uses AWT's global ReentrantLock.
      */ - private static void awtUnlock() { + private static final void awtUnlock() { + awtValidateLocked(); + exclusiveOwnerThread = null; if(hasSunToolkitAWTLock) { try { sunToolkitAWTUnlockMethod.invoke(null, (Object[])null); @@ -342,6 +357,16 @@ public class JAWTUtil { } } + private static final void awtValidateLocked() throws RuntimeException { + final Thread ct = Thread.currentThread(); + if( ct != exclusiveOwnerThread ) { + if ( null == exclusiveOwnerThread ) { + throw new RuntimeException(ct.getName()+": JAWT-ToolkitLock not locked"); + } + throw new RuntimeException(ct.getName()+": Not JAWT-ToolkitLock owner. Owner is "+exclusiveOwnerThread.getName()); + } + } + public static void lockToolkit() throws NativeWindowException { if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.lock()"); } if(!headlessMode && !isJava2DQueueFlusherThread()) { @@ -355,6 +380,13 @@ public class JAWTUtil { awtUnlock(); } } + + public static final void validateLocked() throws RuntimeException { + if(!headlessMode && !isJava2DQueueFlusherThread()) { + awtValidateLocked(); + } + } + public static ToolkitLock getJAWTToolkitLock() { return jawtToolkitLock; diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index b7a83e133..481cbbe39 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -34,13 +34,15 @@ import javax.media.nativewindow.util.Point; import jogamp.nativewindow.Debug; import jogamp.nativewindow.NWJNILibLoader; +import jogamp.nativewindow.ToolkitProperties; -public class OSXUtil { +public class OSXUtil implements ToolkitProperties { private static boolean isInit = false; private static final boolean DEBUG = Debug.debug("OSXUtil"); /** * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties */ public static synchronized void initSingleton() { if(!isInit) { @@ -60,13 +62,21 @@ public class OSXUtil { /** * Called by {@link NativeWindowFactory#shutdown()} + * @see ToolkitProperties */ - public static void shutdown() { - } + public static void shutdown() { } - public static boolean requiresToolkitLock() { - return false; - } + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static boolean requiresToolkitLock() { return false; } + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static final boolean requiresGlobalToolkitLock() { return false; } public static boolean isNSView(long object) { return isNSView0(object); diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index 613c76032..4408a0903 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -33,9 +33,10 @@ import javax.media.nativewindow.NativeWindowFactory; import jogamp.nativewindow.NWJNILibLoader; import jogamp.nativewindow.Debug; +import jogamp.nativewindow.ToolkitProperties; import jogamp.nativewindow.x11.X11Util; -public class GDIUtil { +public class GDIUtil implements ToolkitProperties { private static final boolean DEBUG = Debug.debug("GDIUtil"); private static final String dummyWindowClassNameBase = "_dummyWindow_clazz" ; @@ -44,6 +45,7 @@ public class GDIUtil { /** * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties */ public static synchronized void initSingleton() { if(!isInit) { @@ -67,12 +69,23 @@ public class GDIUtil { /** * Called by {@link NativeWindowFactory#shutdown()} + * @see ToolkitProperties */ public static void shutdown() { } + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ public static boolean requiresToolkitLock() { return false; } + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static final boolean requiresGlobalToolkitLock() { return false; } + private static RegisteredClass dummyWindowClass = null; private static Object dummyWindowSync = new Object(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 30792113d..a331fa940 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -43,13 +43,15 @@ import javax.media.nativewindow.NativeWindowFactory; import jogamp.nativewindow.Debug; import jogamp.nativewindow.NWJNILibLoader; +import jogamp.nativewindow.ToolkitProperties; + import com.jogamp.common.util.LongObjectHashMap; import com.jogamp.nativewindow.x11.X11GraphicsDevice; /** * Contains a thread safe X11 utility to retrieve display connections. */ -public class X11Util { +public class X11Util implements ToolkitProperties { /** * See Bug 515 - https://jogamp.org/bugzilla/show_bug.cgi?id=515 *

      @@ -88,11 +90,15 @@ public class X11Util { private static String nullDisplayName = null; private static volatile boolean isInit = false; private static boolean markAllDisplaysUnclosable = false; // ATI/AMD X11 driver issues + private static boolean requiresGlobalToolkitLock = false; // ATI/AMD X11 driver issues private static Object setX11ErrorHandlerLock = new Object(); + private static final String X11_EXTENSION_ATIFGLRXDRI = "ATIFGLRXDRI"; + private static final String X11_EXTENSION_ATIFGLEXTENSION = "ATIFGLEXTENSION"; /** * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties */ public static void initSingleton() { if(!isInit) { @@ -100,7 +106,7 @@ public class X11Util { if(!isInit) { isInit = true; if(DEBUG) { - System.out.println("X11UtilUtil.initSingleton()"); + System.out.println("X11Util.initSingleton()"); } if(!NWJNILibLoader.loadNativeWindow("x11")) { throw new NativeWindowException("NativeWindow X11 native library load error."); @@ -108,6 +114,7 @@ public class X11Util { final boolean isInitOK = initialize0( XERROR_STACKDUMP ); + final boolean hasX11_EXTENSION_ATIFGLRXDRI, hasX11_EXTENSION_ATIFGLEXTENSION; final long dpy = X11Lib.XOpenDisplay(null); if(0 != dpy) { if(XSYNC_ENABLED) { @@ -115,17 +122,29 @@ public class X11Util { } try { nullDisplayName = X11Lib.XDisplayString(dpy); + hasX11_EXTENSION_ATIFGLRXDRI = X11Lib.QueryExtension(dpy, X11_EXTENSION_ATIFGLRXDRI); + hasX11_EXTENSION_ATIFGLEXTENSION = X11Lib.QueryExtension(dpy, X11_EXTENSION_ATIFGLEXTENSION); } finally { X11Lib.XCloseDisplay(dpy); } } else { nullDisplayName = "nil"; + hasX11_EXTENSION_ATIFGLRXDRI = false; + hasX11_EXTENSION_ATIFGLEXTENSION = false; } + requiresGlobalToolkitLock = hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION; + markAllDisplaysUnclosable = ATI_HAS_XCLOSEDISPLAY_BUG && ( hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ); if(DEBUG) { - System.err.println("X11Util init OK "+isInitOK+"]"+ - ", X11 Display(NULL) <"+nullDisplayName+">"+ - ", XSynchronize Enabled: "+XSYNC_ENABLED); + System.err.println("X11Util.initSingleton(): OK "+isInitOK+"]"+ + ",\n\t X11 Display(NULL) <"+nullDisplayName+">"+ + ",\n\t XSynchronize Enabled: " + XSYNC_ENABLED+ + ",\n\t X11_EXTENSION_ATIFGLRXDRI " + hasX11_EXTENSION_ATIFGLRXDRI+ + ",\n\t X11_EXTENSION_ATIFGLEXTENSION " + hasX11_EXTENSION_ATIFGLEXTENSION+ + ",\n\t requiresToolkitLock "+requiresToolkitLock()+ + ",\n\t requiresGlobalToolkitLock "+requiresGlobalToolkitLock()+ + ",\n\t markAllDisplaysUnclosable "+getMarkAllDisplaysUnclosable() + ); // Thread.dumpStack(); } } @@ -147,6 +166,7 @@ public class X11Util { *

      * Called by {@link NativeWindowFactory#shutdown()} *

      + * @see ToolkitProperties */ public static void shutdown() { if(isInit) { @@ -189,8 +209,20 @@ public class X11Util { } } - public static boolean requiresToolkitLock() { - return true; // JAWT locking: yes, instead of native X11 locking w use a recursive lock. + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static final boolean requiresToolkitLock() { + return true; // JAWT locking: yes, instead of native X11 locking w use a recursive lock per display connection. + } + + /** + * Called by {@link NativeWindowFactory#initSingleton()} + * @see ToolkitProperties + */ + public static final boolean requiresGlobalToolkitLock() { + return requiresGlobalToolkitLock; // JAWT locking: yes, instead of native X11 locking w use a global lock. } public static void setX11ErrorHandler(boolean onoff, boolean quiet) { @@ -206,9 +238,6 @@ public class X11Util { public static boolean getMarkAllDisplaysUnclosable() { return markAllDisplaysUnclosable; } - public static void setMarkAllDisplaysUnclosable(boolean v) { - markAllDisplaysUnclosable = v; - } private X11Util() {} @@ -373,7 +402,7 @@ public class X11Util { name = validateDisplayName(name); boolean reused = false; - synchronized(globalLock) { + synchronized(globalLock) { for(int i=0; iNewObject(env, pointClz, pointCstr, (jint)dest_x, (jint)dest_y); } +/* + * Class: jogamp_nativewindow_x11_X11Lib + * Method: QueryExtension0 + * Signature: (JLjava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_x11_X11Lib_QueryExtension0 + (JNIEnv *env, jclass unused, jlong jdisplay, jstring jextensionName) +{ + int32_t major_opcode, first_event, first_error; + jboolean res = JNI_FALSE; + Display * display = (Display *) (intptr_t) jdisplay; + const char* extensionName = NULL; + + if(NULL==display) { + NativewindowCommon_throwNewRuntimeException(env, "NULL argument \"display\""); + return res; + } + if ( NULL == jextensionName ) { + NativewindowCommon_throwNewRuntimeException(env, "NULL argument \"extensionName\""); + return res; + } + extensionName = (*env)->GetStringUTFChars(env, jextensionName, (jboolean*)NULL); + if ( NULL == extensionName ) { + NativewindowCommon_throwNewRuntimeException(env, "Failed to get UTF-8 chars for argument \"extensionName\""); + return res; + } + + res = True == XQueryExtension(display, extensionName, &major_opcode, &first_event, &first_error) ? JNI_TRUE : JNI_FALSE; + + if ( NULL != jextensionName ) { + (*env)->ReleaseStringUTFChars(env, jextensionName, extensionName); + } + return res; +} + diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/InitConcurrentBaseNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/InitConcurrentBaseNEWT.java index 11d1331ed..6b2de8366 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/InitConcurrentBaseNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/InitConcurrentBaseNEWT.java @@ -43,6 +43,7 @@ import com.jogamp.newt.Window; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.test.junit.util.ValidateLockListener; import com.jogamp.opengl.util.Animator; /** @@ -100,6 +101,7 @@ public class InitConcurrentBaseNEWT extends UITestCase { glWindow.setTitle("Task "+id); glWindow.setPosition(x + insets.getLeftWidth(), y + insets.getTopHeight() ); + glWindow.addGLEventListener(new ValidateLockListener()); glWindow.addGLEventListener(new GearsES2(0)); Animator animator = new Animator(glWindow); diff --git a/src/test/com/jogamp/opengl/test/junit/util/ValidateLockListener.java b/src/test/com/jogamp/opengl/test/junit/util/ValidateLockListener.java new file mode 100644 index 000000000..73c1ad74c --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/util/ValidateLockListener.java @@ -0,0 +1,71 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.util; + + +import javax.media.nativewindow.NativeSurface; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLEventListener; + + +public class ValidateLockListener implements GLEventListener { + + private void validateLock(GLAutoDrawable drawable) { + final NativeSurface ns = drawable.getNativeSurface(); + ns.getGraphicsConfiguration().getScreen().getDevice().validateLocked(); + + final Thread current = Thread.currentThread(); + final Thread owner = ns.getSurfaceLockOwner(); + if( ns.isSurfaceLockedByOtherThread() ) { + throw new RuntimeException(current.getName()+": Locked by another thread(1), owner "+owner+", "+ns); + } + if( current != owner ) { + if( null == owner ) { + throw new RuntimeException(current.getName()+": Not locked: "+ns); + } + throw new RuntimeException(current.getName()+": Locked by another thread(2), owner "+owner+", "+ns); + } + } + + public void init(GLAutoDrawable drawable) { + validateLock(drawable); + } + + public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { + validateLock(drawable); + } + + public void display(GLAutoDrawable drawable) { + validateLock(drawable); + } + + public void dispose(GLAutoDrawable drawable) { + validateLock(drawable); + } +} -- cgit v1.2.3 From 2d35fc546097818aba5db51885f796cb0b442734 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 30 Sep 2012 19:52:20 +0200 Subject: Bug 623: X11Util adds property 'nativewindow.debug.X11Util.ATI_HAS_NO_MULTITHREADING_BUG' to disable GlobalToolkitLock workaround for testing. --- src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index a331fa940..221939cde 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -83,6 +83,11 @@ public class X11Util implements ToolkitProperties { */ public static final boolean ATI_HAS_XCLOSEDISPLAY_BUG = !Debug.isPropertyDefined("nativewindow.debug.X11Util.ATI_HAS_NO_XCLOSEDISPLAY_BUG", true); + /** + * See Bug 623 - https://jogamp.org/bugzilla/show_bug.cgi?id=623 + */ + public static final boolean ATI_HAS_MULTITHREADING_BUG = !Debug.isPropertyDefined("nativewindow.debug.X11Util.ATI_HAS_NO_MULTITHREADING_BUG", true); + public static final boolean DEBUG = Debug.debug("X11Util"); public static final boolean XSYNC_ENABLED = Debug.isPropertyDefined("nativewindow.debug.X11Util.XSync", true); public static final boolean XERROR_STACKDUMP = DEBUG || Debug.isPropertyDefined("nativewindow.debug.X11Util.XErrorStackDump", true); @@ -132,7 +137,7 @@ public class X11Util implements ToolkitProperties { hasX11_EXTENSION_ATIFGLRXDRI = false; hasX11_EXTENSION_ATIFGLEXTENSION = false; } - requiresGlobalToolkitLock = hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION; + requiresGlobalToolkitLock = ATI_HAS_MULTITHREADING_BUG && ( hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ); markAllDisplaysUnclosable = ATI_HAS_XCLOSEDISPLAY_BUG && ( hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ); if(DEBUG) { -- cgit v1.2.3 From e5c1e607d582d002256a07916aba71841744fb4d Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 30 Sep 2012 20:28:24 +0200 Subject: X11Util: Detailed closing information only in DEBUG mode, just print summary --- .../classes/jogamp/nativewindow/x11/X11Util.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 221939cde..103995a8d 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -190,8 +190,10 @@ public class X11Util implements ToolkitProperties { if( openDisplayList.size() > 0) { X11Util.dumpOpenDisplayConnections(); } - if( reusableDisplayList.size() > 0 || pendingDisplayList.size() > 0 ) { - X11Util.dumpPendingDisplayConnections(); + if(DEBUG) { + if( reusableDisplayList.size() > 0 || pendingDisplayList.size() > 0 ) { + X11Util.dumpPendingDisplayConnections(); + } } } @@ -317,11 +319,14 @@ public class X11Util implements ToolkitProperties { if( getMarkAllDisplaysUnclosable() ) { for(int i=0; i Date: Sun, 30 Sep 2012 20:29:06 +0200 Subject: NullToolkitLock.validateLocker(): Throw exception if locking is required (detecting impl. bugs) --- make/scripts/tests.sh | 2 +- src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 0908ef1fd..9e384d59f 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -138,7 +138,7 @@ function jrun() { #D_ARGS="-Djogl.debug.GLCanvas" #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.X11Util.XSync" #D_ARGS="-Dnativewindow.debug.X11Util.XSync -Dnativewindow.debug.ToolkitLock.TraceLock" - D_ARGS="-Dnativewindow.debug.X11Util -Dnativewindow.debug.X11Util.XSync -Dnativewindow.debug.NullToolkitLock.InvalidLocked -Dnativewindow.debug.NativeWindow" + D_ARGS="-Dnativewindow.debug.NativeWindow" #D_ARGS="-Dnativewindow.debug.ToolkitLock" #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLCode -Djogl.debug.TraceGL" #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLState" diff --git a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java index 211e15955..5fc5fe376 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java @@ -28,6 +28,7 @@ package jogamp.nativewindow; +import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ToolkitLock; /** @@ -35,8 +36,6 @@ import javax.media.nativewindow.ToolkitLock; * without any locking. Since there is no locking it all, it is intrinsically recursive. */ public class NullToolkitLock implements ToolkitLock { - public static final boolean INVALID_LOCKED = Debug.isPropertyDefined("nativewindow.debug.NullToolkitLock.InvalidLocked", true); - /** Singleton via {@link NativeWindowFactoryImpl#getNullToolkitLock()} */ protected NullToolkitLock() { } @@ -55,9 +54,8 @@ public class NullToolkitLock implements ToolkitLock { @Override public final void validateLocked() throws RuntimeException { - /* nop */ - if(INVALID_LOCKED) { - throw new RuntimeException("NullToolkitLock does not lock"); + if( NativeWindowFactory.requiresToolkitLock() ) { + throw new RuntimeException("NullToolkitLock does not lock, but locking is required."); } } -- cgit v1.2.3 From 0790108ca9c2a6a6d494e5017589fe083c518e23 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 30 Sep 2012 20:36:27 +0200 Subject: JAWTUtil ToolkitLock: Add lock counter to make lock validation recursive (Fix regression of commit 92398025abdabb2fdef0d78edd41e730991a6f94) --- .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index 2dadfb16b..67c64a95c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -81,6 +81,7 @@ public class JAWTUtil { private static final boolean hasSunToolkitAWTLock; private static volatile Thread exclusiveOwnerThread; + private static int lockCounter; private static final ToolkitLock jawtToolkitLock; @@ -232,6 +233,7 @@ public class JAWTUtil { hasSunToolkitAWTLock = _hasSunToolkitAWTLock; // hasSunToolkitAWTLock = false; exclusiveOwnerThread = null; + lockCounter = 0; jawtToolkitLock = new ToolkitLock() { public final void lock() { @@ -334,7 +336,10 @@ public class JAWTUtil { } else { jawtLockObject.Lock(); } - exclusiveOwnerThread = Thread.currentThread(); + if(0 == lockCounter) { + exclusiveOwnerThread = Thread.currentThread(); + } + lockCounter++; } /** @@ -345,7 +350,10 @@ public class JAWTUtil { */ private static final void awtUnlock() { awtValidateLocked(); - exclusiveOwnerThread = null; + lockCounter--; + if(0 == lockCounter) { + exclusiveOwnerThread = null; + } if(hasSunToolkitAWTLock) { try { sunToolkitAWTUnlockMethod.invoke(null, (Object[])null); -- cgit v1.2.3 From 7c333e3e2574879465719ed968112b27255368d4 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 2 Oct 2012 07:28:00 +0200 Subject: Relax Bug 613 workaround of commit 92398025abdabb2fdef0d78edd41e730991a6f94 Utilizing a GlobalToolkitLock in general to lock the display connection results in deadlock situations where locked surfaces signal other [offscreen] surfaces to render. We have to see whether we find a better solution, for now sporadic XCB assertion still happen. But it is preferrable to point to the root cause, then to jumping through hoops to complicate locking or even to deadlock. Locking: - X11GLXGraphicsConfigurationFactory add missing device locking in: - getAvailableCapabilities - chooseGraphicsConfigurationStatic - Newt/X11Window: Discard display events after window close. Relax ATI XCB/threading bug workaround: - ToolkitProperties: requiresGlobalToolkitLock() -> hasThreadingIssues() - NativeWindowFactory: Don't use GlobalToolkitLock in case of 'threadingIssues' the impact is too severe (see above) - NativeWindowFactory: Add getGlobalToolkitLockIfRequired(): To be used for small code blocks. If having 'threadingIssues' a GlobalToolkitLock is returned, otherwise NullToolkitLock. - X11GLXContext: [create/destroy]ContextARBImpl: Use 'NativeWindowFactory.getGlobalToolkitLockIfRequired()' for extra locking Misc Cleanup: - *DrawableFactory createMutableSurface: Also create new device if type is not suitable - *DrawableFactory createDummySurfaceImpl: Pass chosenCaps and use it (preserves orig. requested user caps) --- .../jogamp/opengl/GLDrawableFactoryImpl.java | 9 ++--- .../jogamp/opengl/egl/EGLDrawableFactory.java | 8 ++--- .../macosx/cgl/MacOSXCGLDrawableFactory.java | 9 ++--- .../windows/wgl/WindowsWGLDrawableFactory.java | 13 +++---- .../jogamp/opengl/x11/glx/X11GLXContext.java | 24 +++++++++---- .../opengl/x11/glx/X11GLXDrawableFactory.java | 22 ++++++------ .../glx/X11GLXGraphicsConfigurationFactory.java | 41 ++++++++++++++-------- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 2 +- .../media/nativewindow/NativeWindowFactory.java | 40 ++++++++------------- .../jogamp/nativewindow/GlobalToolkitLock.java | 13 ++++--- .../nativewindow/NativeWindowFactoryImpl.java | 5 --- .../jogamp/nativewindow/ToolkitProperties.java | 8 ++--- .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 3 -- .../jogamp/nativewindow/macosx/OSXUtil.java | 2 +- .../jogamp/nativewindow/windows/GDIUtil.java | 2 +- .../classes/jogamp/nativewindow/x11/X11Util.java | 10 +++--- .../jogamp/newt/driver/x11/DisplayDriver.java | 2 +- .../jogamp/newt/driver/x11/WindowDriver.java | 2 +- src/newt/native/X11Display.c | 4 +-- src/newt/native/X11Window.c | 2 +- 20 files changed, 113 insertions(+), 108 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index bd2db1b81..0ea565b89 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -188,7 +188,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { } if( chosenCaps.isFBO() && isFBOAvailable ) { // need to hook-up a native dummy surface since source may not have - final ProxySurface dummySurface = createDummySurfaceImpl(adevice, true, chosenCaps, null, 64, 64); + final ProxySurface dummySurface = createDummySurfaceImpl(adevice, false, chosenCaps, (GLCapabilitiesImmutable)config.getRequestedCapabilities(), null, 64, 64); dummySurface.setUpstreamSurfaceHook(new DelegatedUpstreamSurfaceHookWithSurfaceSize(dummySurface.getUpstreamSurfaceHook(), target)); result = createFBODrawableImpl(dummySurface, chosenCaps, 0); } else { @@ -299,7 +299,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { if( capsChosen.isFBO() ) { device.lock(); try { - final ProxySurface dummySurface = createDummySurfaceImpl(device, true, capsRequested, null, width, height); + final ProxySurface dummySurface = createDummySurfaceImpl(device, true, capsChosen, capsRequested, null, width, height); final GLDrawableImpl dummyDrawable = createOnscreenDrawableImpl(dummySurface); return new GLFBODrawableImpl.ResizeableImpl(this, dummyDrawable, dummySurface, capsChosen, 0); } finally { @@ -370,7 +370,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { } device.lock(); try { - return createDummySurfaceImpl(device, true, requestedCaps, chooser, width, height); + return createDummySurfaceImpl(device, true, requestedCaps, requestedCaps, chooser, width, height); } finally { device.unlock(); } @@ -386,6 +386,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { * @param device a valid platform dependent target device. * @param createNewDevice if true a new device instance is created using device details, * otherwise device 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. @@ -395,7 +396,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { * @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 requestedCaps, GLCapabilitiesChooser chooser, int width, int height); + GLCapabilitiesImmutable chosenCaps, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height); //--------------------------------------------------------------------------- // diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index a907c4aff..da3907193 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -367,7 +367,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { if( hasPBuffer[0] ) { // 2nd case create defaultDevice shared resource using pbuffer surface - surface = createDummySurfaceImpl(eglDevice, false, reqCapsPBuffer, null, 64, 64); // egl pbuffer offscreen + surface = createDummySurfaceImpl(eglDevice, false, reqCapsPBuffer, reqCapsPBuffer, null, 64, 64); // egl pbuffer offscreen upstreamSurface = (ProxySurface)surface; upstreamSurface.createNotify(); deviceFromUpstreamSurface = false; @@ -664,7 +664,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final boolean ownDevice; final EGLGraphicsDevice device; - if(createNewDevice || ! ( deviceReq instanceof EGLGraphicsDevice ) ) { + if( createNewDevice || ! (deviceReq instanceof EGLGraphicsDevice) ) { final long nativeDisplayID = ( deviceReq instanceof EGLGraphicsDevice) ? ( (EGLGraphicsDevice) deviceReq ).getNativeDisplayID() : deviceReq.getHandle() ; device = EGLDisplayUtil.eglCreateEGLGraphicsDevice(nativeDisplayID, deviceReq.getConnection(), deviceReq.getUnitID()); @@ -683,8 +683,8 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { @Override public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, - GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { - final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixOffscreenBitOnly(requestedCaps); // complete validation in EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(..) above + GLCapabilitiesImmutable chosenCaps, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { + chosenCaps = GLGraphicsConfigurationUtil.fixOffscreenBitOnly(chosenCaps); // complete validation in EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(..) above return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, new EGLDummyUpstreamSurfaceHook(width, height)); } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java index d59197e1d..ec3156f52 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java @@ -226,7 +226,8 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { if (null == glp) { throw new GLException("Couldn't get default GLProfile for device: "+sharedDevice); } - final GLDrawableImpl sharedDrawable = createOnscreenDrawableImpl(createDummySurfaceImpl(sharedDevice, false, new GLCapabilities(glp), null, 64, 64)); + final GLCapabilitiesImmutable caps = new GLCapabilities(glp); + final GLDrawableImpl sharedDrawable = createOnscreenDrawableImpl(createDummySurfaceImpl(sharedDevice, false, caps, caps, null, 64, 64)); sharedDrawable.setRealized(true); final MacOSXCGLContext sharedContext = (MacOSXCGLContext) sharedDrawable.createContext(null); @@ -358,7 +359,7 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final MacOSXGraphicsDevice device; - if(createNewDevice) { + if( createNewDevice || !(deviceReq instanceof MacOSXGraphicsDevice) ) { device = new MacOSXGraphicsDevice(deviceReq.getUnitID()); } else { device = (MacOSXGraphicsDevice)deviceReq; @@ -373,8 +374,8 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { @Override public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, - GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { - final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(requestedCaps); + GLCapabilitiesImmutable chosenCaps, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { + chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(chosenCaps); return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, new OSXDummyUpstreamSurfaceHook(width, height)); } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java index 91d5c225a..c6bc61a27 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java @@ -318,7 +318,8 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { if (null == glp) { throw new GLException("Couldn't get default GLProfile for device: "+sharedDevice); } - final GLDrawableImpl sharedDrawable = createOnscreenDrawableImpl(createDummySurfaceImpl(sharedDevice, false, new GLCapabilities(glp), null, 64, 64)); + final GLCapabilitiesImmutable caps = new GLCapabilities(glp); + final GLDrawableImpl sharedDrawable = createOnscreenDrawableImpl(createDummySurfaceImpl(sharedDevice, false, caps, caps, null, 64, 64)); sharedDrawable.setRealized(true); final GLContextImpl sharedContext = (GLContextImpl) sharedDrawable.createContext(null); @@ -543,7 +544,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final WindowsGraphicsDevice device; - if(createNewDevice) { + if(createNewDevice || !(deviceReq instanceof WindowsGraphicsDevice)) { device = new WindowsGraphicsDevice(deviceReq.getConnection(), deviceReq.getUnitID()); } else { device = (WindowsGraphicsDevice)deviceReq; @@ -558,18 +559,18 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { @Override public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, - GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { + GLCapabilitiesImmutable chosenCaps, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { final WindowsGraphicsDevice device; - if(createNewDevice) { + if( createNewDevice || !(deviceReq instanceof WindowsGraphicsDevice) ) { device = new WindowsGraphicsDevice(deviceReq.getConnection(), deviceReq.getUnitID()); } else { device = (WindowsGraphicsDevice)deviceReq; } final AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); - final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(requestedCaps); + chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(chosenCaps); final WindowsWGLGraphicsConfiguration config = WindowsWGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(chosenCaps, requestedCaps, chooser, screen); if(null == config) { - throw new GLException("Choosing GraphicsConfiguration failed w/ "+requestedCaps+" on "+screen); + throw new GLException("Choosing GraphicsConfiguration failed w/ "+chosenCaps+" on "+screen); } return new GDISurface(config, 0, new GDIDummyUpstreamSurfaceHook(width, height), createNewDevice); } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java index 72ddd2693..f7389d42e 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java @@ -48,6 +48,8 @@ import java.util.Map; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowFactory; +import javax.media.nativewindow.ToolkitLock; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLException; @@ -180,11 +182,16 @@ public abstract class X11GLXContext extends GLContextImpl { @Override protected void destroyContextARBImpl(long ctx) { - X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration)drawable.getNativeSurface().getGraphicsConfiguration(); - long display = config.getScreen().getDevice().getHandle(); - - glXMakeContextCurrent(display, 0, 0, 0); - GLX.glXDestroyContext(display, ctx); + final ToolkitLock tkLock = NativeWindowFactory.getGlobalToolkitLockIfRequired(); + tkLock.lock(); + try { + long display = drawable.getNativeSurface().getDisplayHandle(); + + glXMakeContextCurrent(display, 0, 0, 0); + GLX.glXDestroyContext(display, ctx); + } finally { + tkLock.unlock(); + } } private static final int ctx_arb_attribs_idx_major = 0; private static final int ctx_arb_attribs_idx_minor = 2; @@ -243,6 +250,8 @@ public abstract class X11GLXContext extends GLContextImpl { AbstractGraphicsDevice device = config.getScreen().getDevice(); final long display = device.getHandle(); + final ToolkitLock tkLock = NativeWindowFactory.getGlobalToolkitLockIfRequired(); + tkLock.lock(); try { // critical path, a remote display might not support this command, // hence we need to catch the X11 Error within this block. @@ -253,7 +262,10 @@ public abstract class X11GLXContext extends GLContextImpl { Throwable t = new Throwable(getThreadName()+": Info: X11GLXContext.createContextARBImpl glXCreateContextAttribsARB failed with "+getGLVersion(major, minor, ctp, "@creation"), re); t.printStackTrace(); } + } finally { + tkLock.unlock(); } + if(0!=ctx) { if (!glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), ctx)) { if(DEBUG) { @@ -420,7 +432,7 @@ public abstract class X11GLXContext extends GLContextImpl { @Override protected void destroyImpl() throws GLException { - GLX.glXDestroyContext(drawable.getNativeSurface().getDisplayHandle(), contextHandle); + destroyContextARBImpl(contextHandle); } @Override diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index 018f6a6ea..e38aabef8 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -229,7 +229,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { @Override public SharedResourceRunner.Resource createSharedResource(String connection) { - final X11GraphicsDevice sharedDevice = new X11GraphicsDevice(X11Util.openDisplay(connection), AbstractGraphicsDevice.DEFAULT_UNIT, true); + final X11GraphicsDevice sharedDevice = new X11GraphicsDevice(X11Util.openDisplay(connection), AbstractGraphicsDevice.DEFAULT_UNIT, true /* owner */); sharedDevice.lock(); try { final X11GraphicsScreen sharedScreen = new X11GraphicsScreen(sharedDevice, sharedDevice.getDefaultScreen()); @@ -246,8 +246,9 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { if (null == glp) { throw new GLException("Couldn't get default GLProfile for device: "+sharedDevice); } - - final GLDrawableImpl sharedDrawable = createOnscreenDrawableImpl(createDummySurfaceImpl(sharedDevice, false, new GLCapabilities(glp), null, 64, 64)); + + final GLCapabilitiesImmutable caps = new GLCapabilities(glp); + final GLDrawableImpl sharedDrawable = createOnscreenDrawableImpl(createDummySurfaceImpl(sharedDevice, false, caps, caps, null, 64, 64)); sharedDrawable.setRealized(true); final GLContextImpl sharedContext = (GLContextImpl) sharedDrawable.createContext(null); @@ -499,11 +500,10 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final X11GraphicsDevice device; - if(createNewDevice) { - // Null X11 resource locking, due to private non-shared Display handle - device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), true); + if( createNewDevice || !(deviceReq instanceof X11GraphicsDevice) ) { + device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), true /* owner */); } else { - device = (X11GraphicsDevice)deviceReq; + device = (X11GraphicsDevice) deviceReq; } final X11GraphicsScreen screen = new X11GraphicsScreen(device, device.getDefaultScreen()); final X11GLXGraphicsConfiguration config = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED); @@ -512,17 +512,17 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { } return new WrappedSurface(config, 0, upstreamHook, createNewDevice); } - + @Override public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, - GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { - final GLCapabilitiesImmutable chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(requestedCaps); + GLCapabilitiesImmutable chosenCaps, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { + chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(chosenCaps); return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, new X11DummyUpstreamSurfaceHook(width, height)); } @Override protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { - final X11GraphicsDevice device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), true); + final X11GraphicsDevice device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), true /* owner */); final X11GraphicsScreen screen = new X11GraphicsScreen(device, screenIdx); final int xvisualID = X11Lib.GetVisualIDFromWindow(device.getHandle(), windowHandle); if(VisualIDHolder.VID_UNDEFINED == xvisualID) { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java index ef2d3283d..8ac324205 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java @@ -127,16 +127,22 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF throw new GLException("Shared resource for device n/a: "+device); } final X11GraphicsScreen sharedScreen = (X11GraphicsScreen) sharedResource.getScreen(); - final boolean isMultisampleAvailable = factory.isGLXMultisampleAvailable(sharedScreen.getDevice()); + final X11GraphicsDevice sharedDevice = (X11GraphicsDevice) sharedScreen.getDevice(); + final boolean isMultisampleAvailable = sharedResource.isGLXMultisampleAvailable(); final GLProfile glp = GLProfile.getDefault(device); List availableCaps = null; - - if( sharedResource.isGLXVersionGreaterEqualOneThree() ) { - availableCaps = getAvailableGLCapabilitiesFBConfig(sharedScreen, glp, isMultisampleAvailable); - } - if( null == availableCaps || availableCaps.isEmpty() ) { - availableCaps = getAvailableGLCapabilitiesXVisual(sharedScreen, glp, isMultisampleAvailable); + + sharedDevice.lock(); + try { + if( sharedResource.isGLXVersionGreaterEqualOneThree() ) { + availableCaps = getAvailableGLCapabilitiesFBConfig(sharedScreen, glp, isMultisampleAvailable); + } + if( null == availableCaps || availableCaps.isEmpty() ) { + availableCaps = getAvailableGLCapabilitiesXVisual(sharedScreen, glp, isMultisampleAvailable); + } + } finally { + sharedDevice.unlock(); } if( null != availableCaps && availableCaps.size() > 1 ) { Collections.sort(availableCaps, XVisualIDComparator); @@ -215,16 +221,21 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, factory, x11Device); final boolean usePBuffer = !capsChosen.isOnscreen() && capsChosen.isPBuffer(); - + X11GLXGraphicsConfiguration res = null; - if( factory.isGLXVersionGreaterEqualOneThree(x11Device) ) { - res = chooseGraphicsConfigurationFBConfig(capsChosen, capsReq, chooser, x11Screen, xvisualID); - } - if(null==res) { - if(usePBuffer) { - throw new GLException("Error: Couldn't create X11GLXGraphicsConfiguration based on FBConfig for visualID "+toHexString(xvisualID)+", "+capsChosen); + x11Device.lock(); + try { + if( factory.isGLXVersionGreaterEqualOneThree(x11Device) ) { + res = chooseGraphicsConfigurationFBConfig(capsChosen, capsReq, chooser, x11Screen, xvisualID); + } + if(null==res) { + if(usePBuffer) { + throw new GLException("Error: Couldn't create X11GLXGraphicsConfiguration based on FBConfig for visualID "+toHexString(xvisualID)+", "+capsChosen); + } + res = chooseGraphicsConfigurationXVisual(capsChosen, capsReq, chooser, x11Screen, xvisualID); } - res = chooseGraphicsConfigurationXVisual(capsChosen, capsReq, chooser, x11Screen, xvisualID); + } finally { + x11Device.unlock(); } if(null==res) { throw new GLException("Error: Couldn't create X11GLXGraphicsConfiguration based on FBConfig and XVisual for visualID "+toHexString(xvisualID)+", "+x11Screen+", "+capsChosen); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index 1cc796086..7be747ff5 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -210,7 +210,7 @@ public class SWTAccessor { if( null != OS_gtk_class ) { long widgedHandle = callStaticMethodL2L(OS_GTK_WIDGET_WINDOW, handle); long displayHandle = callStaticMethodL2L(OS_gdk_x11_drawable_get_xdisplay, widgedHandle); - return new X11GraphicsDevice(displayHandle, AbstractGraphicsDevice.DEFAULT_UNIT, false); + return new X11GraphicsDevice(displayHandle, AbstractGraphicsDevice.DEFAULT_UNIT, false /* owner */); } final String nwt = NativeWindowFactory.getNativeWindowType(false); if( NativeWindowFactory.TYPE_WINDOWS == nwt ) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 1962bcd09..006ee4c97 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -42,6 +42,7 @@ import java.util.HashMap; import java.util.Map; import jogamp.nativewindow.Debug; +import jogamp.nativewindow.GlobalToolkitLock; import jogamp.nativewindow.NativeWindowFactoryImpl; import jogamp.nativewindow.ToolkitProperties; import jogamp.nativewindow.ResourceToolkitLock; @@ -102,7 +103,7 @@ public abstract class NativeWindowFactory { private static ToolkitLock jawtUtilJAWTToolkitLock; private static boolean requiresToolkitLock; - private static boolean requiresGlobalToolkitLock; + private static boolean desktopHasThreadingIssues; private static volatile boolean isJVMShuttingDown = false; @@ -183,15 +184,11 @@ public abstract class NativeWindowFactory { final Boolean res1 = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "requiresToolkitLock", null, null, cl); requiresToolkitLock = res1.booleanValue(); - if(requiresToolkitLock) { - final Boolean res2 = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "requiresGlobalToolkitLock", null, null, cl); - requiresGlobalToolkitLock = res2.booleanValue(); - } else { - requiresGlobalToolkitLock = false; - } + final Boolean res2 = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "hasThreadingIssues", null, null, cl); + desktopHasThreadingIssues = res2.booleanValue(); } else { requiresToolkitLock = false; - requiresGlobalToolkitLock = false; + desktopHasThreadingIssues = false; } } @@ -293,7 +290,7 @@ public abstract class NativeWindowFactory { } if(DEBUG) { - System.err.println("NativeWindowFactory requiresToolkitLock "+requiresToolkitLock+", requiresGlobalToolkitLock "+requiresGlobalToolkitLock); + System.err.println("NativeWindowFactory requiresToolkitLock "+requiresToolkitLock+", desktopHasThreadingIssues "+desktopHasThreadingIssues); System.err.println("NativeWindowFactory isAWTAvailable "+isAWTAvailable+", defaultFactory "+factory); } @@ -329,11 +326,6 @@ public abstract class NativeWindowFactory { return requiresToolkitLock; } - /** @return true if the underlying toolkit requires global locking, otherwise false. */ - public static boolean requiresGlobalToolkitLock() { - return requiresGlobalToolkitLock; - } - /** @return true if not headless, AWT Component and NativeWindow's AWT part available */ public static boolean isAWTAvailable() { return isAWTAvailable; } @@ -382,11 +374,15 @@ public abstract class NativeWindowFactory { public static ToolkitLock getNullToolkitLock() { return NativeWindowFactoryImpl.getNullToolkitLock(); } - - public static ToolkitLock getGlobalToolkitLock() { - return NativeWindowFactoryImpl.getGlobalToolkitLock(); - } + /** + * Ony call this for small code segments for desktop w/ threading issues. + * @return {@link GlobalToolkitLock} if desktop has threading issues, otherwise {@link #getNullToolkitLock()} + */ + public static ToolkitLock getGlobalToolkitLockIfRequired() { + return desktopHasThreadingIssues ? GlobalToolkitLock.getSingleton() : getNullToolkitLock(); + } + /** * Provides the system default {@link ToolkitLock} for the default system windowing type. * @see #getNativeWindowType(boolean) @@ -400,7 +396,6 @@ public abstract class NativeWindowFactory { * Provides the default {@link ToolkitLock} for type. *
        *
      • JAWT {@link ToolkitLock} if required and type is of {@link #TYPE_AWT} and AWT available,
      • - *
      • {@link jogamp.nativewindow.GlobalToolkitLock} if required, otherwise
      • *
      • {@link jogamp.nativewindow.ResourceToolkitLock} if required, otherwise
      • *
      • {@link jogamp.nativewindow.NullToolkitLock}
      • *
      @@ -410,9 +405,6 @@ public abstract class NativeWindowFactory { if( TYPE_AWT == type && isAWTAvailable() ) { return getAWTToolkitLock(); } - if( requiresGlobalToolkitLock ) { - return NativeWindowFactoryImpl.getGlobalToolkitLock(); - } return ResourceToolkitLock.create(); } return NativeWindowFactoryImpl.getNullToolkitLock(); @@ -422,7 +414,6 @@ public abstract class NativeWindowFactory { * Provides the default {@link ToolkitLock} for type and deviceHandle. *
        *
      • JAWT {@link ToolkitLock} if required and type is of {@link #TYPE_AWT} and AWT available,
      • - *
      • {@link jogamp.nativewindow.GlobalToolkitLock} if required, otherwise
      • *
      • {@link jogamp.nativewindow.ResourceToolkitLock} if required, otherwise
      • *
      • {@link jogamp.nativewindow.NullToolkitLock}
      • *
      @@ -432,9 +423,6 @@ public abstract class NativeWindowFactory { if( TYPE_AWT == type && isAWTAvailable() ) { return getAWTToolkitLock(); } - if( requiresGlobalToolkitLock ) { - return NativeWindowFactoryImpl.getGlobalToolkitLock(); - } return ResourceToolkitLock.create(); } return NativeWindowFactoryImpl.getNullToolkitLock(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java index 0c2a1e43f..c9f830811 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java @@ -36,16 +36,19 @@ import com.jogamp.common.util.locks.RecursiveLock; /** * Implementing a global recursive {@link javax.media.nativewindow.ToolkitLock}. *

      - * This is the last resort for unstable driver, e.g. proprietary ATI/X11 12.8 and 12.9, - * where multiple X11 display connections to the same connection name are not treated - * thread safe within the GL/X11 driver. + * This is the last resort for unstable driver where multiple X11 display connections + * to the same connection name are not treated thread safe within the GL/X11 driver. *

      */ public class GlobalToolkitLock implements ToolkitLock { private static final RecursiveLock globalLock = LockFactory.createRecursiveLock(); + private static GlobalToolkitLock singleton = new GlobalToolkitLock(); - /** Singleton via {@link NativeWindowFactoryImpl#getGlobalToolkitLock()} */ - protected GlobalToolkitLock() { } + public static final GlobalToolkitLock getSingleton() { + return singleton; + } + + private GlobalToolkitLock() { } @Override public final void lock() { diff --git a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java index c35cede77..a3a66b7f1 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java @@ -44,16 +44,11 @@ import com.jogamp.common.util.ReflectionUtil.AWTNames; public class NativeWindowFactoryImpl extends NativeWindowFactory { private static final ToolkitLock nullToolkitLock = new NullToolkitLock(); - private static final ToolkitLock globalToolkitLock = new GlobalToolkitLock(); public static ToolkitLock getNullToolkitLock() { return nullToolkitLock; } - public static ToolkitLock getGlobalToolkitLock() { - return globalToolkitLock; - } - // This subclass of NativeWindowFactory handles the case of // NativeWindows being passed in protected NativeWindow getNativeWindowImpl(Object winObj, AbstractGraphicsConfiguration config) throws IllegalArgumentException { diff --git a/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java b/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java index 2062d1f58..ed23def8f 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java +++ b/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java @@ -13,15 +13,11 @@ import javax.media.nativewindow.NativeWindowFactory; public static boolean requiresToolkitLock() {} - public static boolean requiresGlobalToolkitLock() {} + public static boolean hasThreadingIssues() {} * * Above static methods are invoked by {@link NativeWindowFactory#initSingleton()}, * or {@link NativeWindowFactory#shutdown()} via reflection. *

      - *

      - * If requiresGlobalToolkitLock() == true, then - * requiresToolkitLock() == true shall be valid as well. - *

      */ public interface ToolkitProperties { @@ -46,6 +42,6 @@ public interface ToolkitProperties { /** * Called by {@link NativeWindowFactory#initSingleton()} */ - // boolean requiresGlobalToolkitLock(); + // boolean hasThreadingIssues(); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index 67c64a95c..349da8ee6 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -237,18 +237,15 @@ public class JAWTUtil { jawtToolkitLock = new ToolkitLock() { public final void lock() { - NativeWindowFactory.getGlobalToolkitLock().lock(); JAWTUtil.lockToolkit(); if(TRACE_LOCK) { System.err.println("JAWTToolkitLock.lock()"); } } public final void unlock() { if(TRACE_LOCK) { System.err.println("JAWTToolkitLock.unlock()"); } JAWTUtil.unlockToolkit(); - NativeWindowFactory.getGlobalToolkitLock().unlock(); } @Override public final void validateLocked() throws RuntimeException { - NativeWindowFactory.getGlobalToolkitLock().validateLocked(); JAWTUtil.validateLocked(); } public final void dispose() { diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 481cbbe39..a195f137e 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -76,7 +76,7 @@ public class OSXUtil implements ToolkitProperties { * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties */ - public static final boolean requiresGlobalToolkitLock() { return false; } + public static final boolean hasThreadingIssues() { return false; } public static boolean isNSView(long object) { return isNSView0(object); diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index 4408a0903..2f4e18359 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -84,7 +84,7 @@ public class GDIUtil implements ToolkitProperties { * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties */ - public static final boolean requiresGlobalToolkitLock() { return false; } + public static final boolean hasThreadingIssues() { return false; } private static RegisteredClass dummyWindowClass = null; private static Object dummyWindowSync = new Object(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 103995a8d..c771cd67a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -95,7 +95,7 @@ public class X11Util implements ToolkitProperties { private static String nullDisplayName = null; private static volatile boolean isInit = false; private static boolean markAllDisplaysUnclosable = false; // ATI/AMD X11 driver issues - private static boolean requiresGlobalToolkitLock = false; // ATI/AMD X11 driver issues + private static boolean hasThreadingIssues = false; // ATI/AMD X11 driver issues private static Object setX11ErrorHandlerLock = new Object(); private static final String X11_EXTENSION_ATIFGLRXDRI = "ATIFGLRXDRI"; @@ -137,7 +137,7 @@ public class X11Util implements ToolkitProperties { hasX11_EXTENSION_ATIFGLRXDRI = false; hasX11_EXTENSION_ATIFGLEXTENSION = false; } - requiresGlobalToolkitLock = ATI_HAS_MULTITHREADING_BUG && ( hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ); + hasThreadingIssues = ATI_HAS_MULTITHREADING_BUG && ( hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ); markAllDisplaysUnclosable = ATI_HAS_XCLOSEDISPLAY_BUG && ( hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ); if(DEBUG) { @@ -147,7 +147,7 @@ public class X11Util implements ToolkitProperties { ",\n\t X11_EXTENSION_ATIFGLRXDRI " + hasX11_EXTENSION_ATIFGLRXDRI+ ",\n\t X11_EXTENSION_ATIFGLEXTENSION " + hasX11_EXTENSION_ATIFGLEXTENSION+ ",\n\t requiresToolkitLock "+requiresToolkitLock()+ - ",\n\t requiresGlobalToolkitLock "+requiresGlobalToolkitLock()+ + ",\n\t hasThreadingIssues "+hasThreadingIssues()+ ",\n\t markAllDisplaysUnclosable "+getMarkAllDisplaysUnclosable() ); // Thread.dumpStack(); @@ -228,8 +228,8 @@ public class X11Util implements ToolkitProperties { * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties */ - public static final boolean requiresGlobalToolkitLock() { - return requiresGlobalToolkitLock; // JAWT locking: yes, instead of native X11 locking w use a global lock. + public static final boolean hasThreadingIssues() { + return hasThreadingIssues; // JOGL impl. may utilize special locking "somewhere" } public static void setX11ErrorHandler(boolean onoff, boolean quiet) { diff --git a/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java index 6e80e966a..a3230fa62 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java @@ -80,7 +80,7 @@ public class DisplayDriver extends DisplayImpl { if( 0 == handle ) { throw new RuntimeException("Error creating display(Win): "+name); } - aDevice = new X11GraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_UNIT, true); + aDevice = new X11GraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_UNIT, true /* owner */); try { CompleteDisplay0(aDevice.getHandle()); } catch(RuntimeException e) { diff --git a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java index bde723634..92f174e39 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java @@ -73,7 +73,7 @@ public class WindowDriver extends WindowImpl { if( 0 == renderDeviceHandle ) { throw new RuntimeException("Error creating display(EDT): "+edtDevice.getConnection()); } - renderDevice = new X11GraphicsDevice(renderDeviceHandle, AbstractGraphicsDevice.DEFAULT_UNIT, true); + renderDevice = new X11GraphicsDevice(renderDeviceHandle, AbstractGraphicsDevice.DEFAULT_UNIT, true /* owner */); final AbstractGraphicsScreen renderScreen = new X11GraphicsScreen(renderDevice, screen.getIndex()); final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice(), capsRequested); diff --git a/src/newt/native/X11Display.c b/src/newt/native/X11Display.c index 56c11fab4..69a115ab1 100644 --- a/src/newt/native/X11Display.c +++ b/src/newt/native/X11Display.c @@ -329,10 +329,10 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessage char text[255]; // XEventsQueued(dpy, X): - // QueuedAlready : No I/O Flush or system call doesn't work on some cards (eg ATI) ?) + // QueuedAlready == XQLength(): No I/O Flush or system call doesn't work on some cards (eg ATI) ?) // QueuedAfterFlush == XPending(): I/O Flush only if no already queued events are available // QueuedAfterReading : QueuedAlready + if queue==0, attempt to read more .. - if ( 0 >= XPending(dpy) ) { + if ( 0 >= XEventsQueued(dpy, QueuedAfterFlush) ) { // DBG_PRINT( "X11: DispatchMessages 0x%X - Leave 1\n", dpy); return; } diff --git a/src/newt/native/X11Window.c b/src/newt/native/X11Window.c index 2e16e7cae..202ad6fff 100644 --- a/src/newt/native/X11Window.c +++ b/src/newt/native/X11Window.c @@ -701,7 +701,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CloseWindow0 Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessages0(env, obj, display, javaObjectAtom, windowDeleteAtom); XDestroyWindow(dpy, w); - XSync(dpy, False); + XSync(dpy, True); // discard all events now, no more handler (*env)->DeleteGlobalRef(env, jwindow); -- cgit v1.2.3 From 21b85e647f1e661c8e5e49caa91c564a3d041df2 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 2 Oct 2012 07:29:13 +0200 Subject: Fix commit fbe331f013608eb31ff0d8675f4e4c9881c9c48b (Bug 616 - Remove XInitThreads()) X11Util/Native: Fix X11Util_initialize0() arguments were wrong and code still invoked XInitThreads() .. woops; Added missing included "jogamp_nativewindow_x11_X11Util.h" incl. it's generation via javah, which was the culprit of not detecting it at compile time. This is a fix for commit fbe331f013608eb31ff0d8675f4e4c9881c9c48b --- make/build-nativewindow.xml | 1 + src/nativewindow/native/x11/Xmisc.c | 22 +++++----------------- 2 files changed, 6 insertions(+), 17 deletions(-) (limited to 'src/nativewindow') diff --git a/make/build-nativewindow.xml b/make/build-nativewindow.xml index 6a9dbdc2e..3c97d9d9b 100644 --- a/make/build-nativewindow.xml +++ b/make/build-nativewindow.xml @@ -759,6 +759,7 @@ + NewGlobalRef(env, clazz); - if( JNI_TRUE == firstUIActionOnProcess ) { - if( 0 == XInitThreads() ) { - fprintf(stderr, "Warning: XInitThreads() failed\n"); - } else { - _xinitThreadsOK=JNI_TRUE; - if(debug) { - fprintf(stderr, "X11: XInitThreads() called for concurrent Thread support\n"); - } - } - } else if(debug) { - fprintf(stderr, "X11: XInitThreads() _not_ called for concurrent Thread support\n"); - } _initClazzAccess(env); x11IOErrorHandlerEnable(1, env); @@ -310,7 +298,7 @@ Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass clazz, jboo fprintf(stderr, "Info: NativeWindow native init passed\n"); } } - return _xinitThreadsOK; + return JNI_TRUE; } JNIEXPORT void JNICALL -- cgit v1.2.3 From 9c96be7c0a1a19365ae983908260c6ff44f045c4 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 2 Oct 2012 17:13:56 +0200 Subject: NativeWindowFactory: Remove 'remedy' of Bug 613 Commit 92398025abdabb2fdef0d78edd41e730991a6f94 GlobalToolkitLock for create/destroy Turns out on it has no effect and ATI prop. driver still has XCB failures at this point. --- .../classes/jogamp/opengl/x11/glx/X11GLXContext.java | 20 ++++---------------- .../media/nativewindow/NativeWindowFactory.java | 9 --------- 2 files changed, 4 insertions(+), 25 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java index f7389d42e..89907ba15 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java @@ -48,8 +48,6 @@ import java.util.Map; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; -import javax.media.nativewindow.NativeWindowFactory; -import javax.media.nativewindow.ToolkitLock; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLException; @@ -182,16 +180,10 @@ public abstract class X11GLXContext extends GLContextImpl { @Override protected void destroyContextARBImpl(long ctx) { - final ToolkitLock tkLock = NativeWindowFactory.getGlobalToolkitLockIfRequired(); - tkLock.lock(); - try { - long display = drawable.getNativeSurface().getDisplayHandle(); - - glXMakeContextCurrent(display, 0, 0, 0); - GLX.glXDestroyContext(display, ctx); - } finally { - tkLock.unlock(); - } + final long display = drawable.getNativeSurface().getDisplayHandle(); + + glXMakeContextCurrent(display, 0, 0, 0); + GLX.glXDestroyContext(display, ctx); } private static final int ctx_arb_attribs_idx_major = 0; private static final int ctx_arb_attribs_idx_minor = 2; @@ -250,8 +242,6 @@ public abstract class X11GLXContext extends GLContextImpl { AbstractGraphicsDevice device = config.getScreen().getDevice(); final long display = device.getHandle(); - final ToolkitLock tkLock = NativeWindowFactory.getGlobalToolkitLockIfRequired(); - tkLock.lock(); try { // critical path, a remote display might not support this command, // hence we need to catch the X11 Error within this block. @@ -262,8 +252,6 @@ public abstract class X11GLXContext extends GLContextImpl { Throwable t = new Throwable(getThreadName()+": Info: X11GLXContext.createContextARBImpl glXCreateContextAttribsARB failed with "+getGLVersion(major, minor, ctp, "@creation"), re); t.printStackTrace(); } - } finally { - tkLock.unlock(); } if(0!=ctx) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 006ee4c97..37d408990 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -42,7 +42,6 @@ import java.util.HashMap; import java.util.Map; import jogamp.nativewindow.Debug; -import jogamp.nativewindow.GlobalToolkitLock; import jogamp.nativewindow.NativeWindowFactoryImpl; import jogamp.nativewindow.ToolkitProperties; import jogamp.nativewindow.ResourceToolkitLock; @@ -375,14 +374,6 @@ public abstract class NativeWindowFactory { return NativeWindowFactoryImpl.getNullToolkitLock(); } - /** - * Ony call this for small code segments for desktop w/ threading issues. - * @return {@link GlobalToolkitLock} if desktop has threading issues, otherwise {@link #getNullToolkitLock()} - */ - public static ToolkitLock getGlobalToolkitLockIfRequired() { - return desktopHasThreadingIssues ? GlobalToolkitLock.getSingleton() : getNullToolkitLock(); - } - /** * Provides the system default {@link ToolkitLock} for the default system windowing type. * @see #getNativeWindowType(boolean) -- cgit v1.2.3 From f7ca4df7b4e6b2acbdb941f67f6d7058db134d91 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 2 Oct 2012 17:56:20 +0200 Subject: Fix regression of fbe331f013608eb31ff0d8675f4e4c9881c9c48b [Remove XInitThreads()] NativeWindowFactory.getDefaultToolkitLock() is no more a global singleton, but an instance which has to track/lock a single resource. Hence the decoration w/ it in GLDrawableFactory is useless and applying lock/unlock on a new instance also a bug/regression. --- make/scripts/tests.sh | 4 ++-- src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java | 14 ++------------ .../com/jogamp/nativewindow/x11/X11GraphicsScreen.java | 6 ++++-- 3 files changed, 8 insertions(+), 16 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 5f24ae3cc..afc145460 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -247,7 +247,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent01NEWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent02NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextSurfaceLockNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug00NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug01NEWT $* @@ -351,7 +351,7 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent02NEWT $* # Per default (unit tests) all test are performed this way # with OSX: -XstartOnFirstThread # -#testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTEclipseGLCanvas01GLn $* +testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTEclipseGLCanvas01GLn $* #testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor03AWTGLn $* #testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* #testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTGLn $* diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index 0ea565b89..deb187372 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -441,24 +441,14 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { @Override public GLContext createExternalGLContext() { - NativeWindowFactory.getDefaultToolkitLock().lock(); - try { - return createExternalGLContextImpl(); - } finally { - NativeWindowFactory.getDefaultToolkitLock().unlock(); - } + return createExternalGLContextImpl(); } protected abstract GLDrawable createExternalGLDrawableImpl(); @Override public GLDrawable createExternalGLDrawable() { - NativeWindowFactory.getDefaultToolkitLock().lock(); - try { - return createExternalGLDrawableImpl(); - } finally { - NativeWindowFactory.getDefaultToolkitLock().unlock(); - } + return createExternalGLDrawableImpl(); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java index fa57124fb..2ec66290a 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java @@ -33,10 +33,12 @@ package com.jogamp.nativewindow.x11; -import javax.media.nativewindow.*; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.DefaultGraphicsScreen; +import javax.media.nativewindow.NativeWindowException; import jogamp.nativewindow.x11.X11Lib; -import jogamp.nativewindow.x11.X11Util; /** Encapsulates a screen index on X11 platforms. Objects of this type are passed to {@link -- cgit v1.2.3 From 67c2ab9bbc3522d85977151849c416f5aa320395 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 5 Oct 2012 18:46:56 +0200 Subject: EGL/X11 DummySurfaceHook: Lock display device at creation/destruction --- .../opengl/egl/EGLDummyUpstreamSurfaceHook.java | 32 +++++++++++------- .../x11/X11DummyUpstreamSurfaceHook.java | 38 ++++++++++++++-------- 2 files changed, 45 insertions(+), 25 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java b/src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java index b172d4f35..162e7166a 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java @@ -23,15 +23,20 @@ public class EGLDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize @Override public final void create(ProxySurface s) { final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) s.getGraphicsConfiguration().getScreen().getDevice(); - if(0 == eglDevice.getHandle()) { - eglDevice.open(); - s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); - } - if( EGL.EGL_NO_SURFACE == s.getSurfaceHandle() ) { - s.setSurfaceHandle( EGLDrawableFactory.createPBufferSurfaceImpl((EGLGraphicsConfiguration)s.getGraphicsConfiguration(), 64, 64, false) ); - s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + eglDevice.lock(); + try { + if(0 == eglDevice.getHandle()) { + eglDevice.open(); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + if( EGL.EGL_NO_SURFACE == s.getSurfaceHandle() ) { + s.setSurfaceHandle( EGLDrawableFactory.createPBufferSurfaceImpl((EGLGraphicsConfiguration)s.getGraphicsConfiguration(), 64, 64, false) ); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } + s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); + } finally { + eglDevice.unlock(); } - s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); } @Override @@ -41,9 +46,14 @@ public class EGLDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize if( EGL.EGL_NO_SURFACE == s.getSurfaceHandle() ) { throw new InternalError("Owns upstream surface, but no EGL surface: "+s); } - EGL.eglDestroySurface(eglDevice.getHandle(), s.getSurfaceHandle()); - s.setSurfaceHandle(EGL.EGL_NO_SURFACE); - s.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + eglDevice.lock(); + try { + EGL.eglDestroySurface(eglDevice.getHandle(), s.getSurfaceHandle()); + s.setSurfaceHandle(EGL.EGL_NO_SURFACE); + s.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } finally { + eglDevice.unlock(); + } } } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java index 55a29dd5e..67a33e55c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java @@ -30,19 +30,24 @@ public class X11DummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize final X11GraphicsConfiguration cfg = (X11GraphicsConfiguration) s.getGraphicsConfiguration(); final X11GraphicsScreen screen = (X11GraphicsScreen) cfg.getScreen(); final X11GraphicsDevice device = (X11GraphicsDevice) screen.getDevice(); - if(0 == device.getHandle()) { - device.open(); - s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); - } - if( 0 == s.getSurfaceHandle() ) { - final long windowHandle = X11Lib.CreateDummyWindow(device.getHandle(), screen.getIndex(), cfg.getXVisualID(), 64, 64); - if(0 == windowHandle) { - throw new NativeWindowException("Creating dummy window failed w/ "+cfg); + device.lock(); + try { + if(0 == device.getHandle()) { + device.open(); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + if( 0 == s.getSurfaceHandle() ) { + final long windowHandle = X11Lib.CreateDummyWindow(device.getHandle(), screen.getIndex(), cfg.getXVisualID(), 64, 64); + if(0 == windowHandle) { + throw new NativeWindowException("Creating dummy window failed w/ "+cfg); + } + s.setSurfaceHandle(windowHandle); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); } - s.setSurfaceHandle(windowHandle); - s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); + } finally { + device.unlock(); } - s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); } @Override @@ -52,9 +57,14 @@ public class X11DummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize if( 0 == s.getSurfaceHandle() ) { throw new InternalError("Owns upstream surface, but no X11 window: "+s); } - X11Lib.DestroyDummyWindow(device.getHandle(), s.getSurfaceHandle()); - s.setSurfaceHandle(0); - s.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + device.lock(); + try { + X11Lib.DestroyDummyWindow(device.getHandle(), s.getSurfaceHandle()); + s.setSurfaceHandle(0); + s.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + } finally { + device.unlock(); + } } } } -- cgit v1.2.3 From d73ee3ac8aac58914146c0c9949902452db83b56 Mon Sep 17 00:00:00 2001 From: Harvey Harrison Date: Tue, 16 Oct 2012 00:35:21 -0700 Subject: jogl: use Boolean TRUE/FALSE constants for values that will be immediately unboxed No reason for ever using new Boolean when the constants are available. Signed-off-by: Harvey Harrison --- .../classes/javax/media/nativewindow/NativeWindowFactory.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 37d408990..179610b25 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -117,9 +117,9 @@ public abstract class NativeWindowFactory { "/opt/vc/lib/libbcm_host.so"); public Boolean run() { if ( vcliblocation.isFile() ) { - return new Boolean(true); + return Boolean.TRUE; } - return new Boolean(false); + return Boolean.FALSE; } } ).booleanValue(); } -- cgit v1.2.3 From 808c8da0729b845d010d3f5e0babf1fc6129c3e9 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 4 Nov 2012 06:42:43 +0100 Subject: MacOSXCGLContext[NSOpenGLLayer/NSView]: Propagate drawable change Propagate drawable change to MacOSXCGLContext where either context/NSView or context/NSOpenGLLayer association needs to get updated. Fixes drawable/context switch. --- make/stub_includes/opengl/macosx-window-system.h | 1 + .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 75 ++++++++++++++++------ .../opengl/macosx/cgl/MacOSXCGLDrawable.java | 4 +- .../macosx/MacOSXWindowSystemInterface-calayer.m | 1 + .../native/macosx/MacOSXWindowSystemInterface.m | 13 +++- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 3 +- .../media/nativewindow/OffscreenLayerSurface.java | 3 + 7 files changed, 74 insertions(+), 26 deletions(-) (limited to 'src/nativewindow') diff --git a/make/stub_includes/opengl/macosx-window-system.h b/make/stub_includes/opengl/macosx-window-system.h index aaa0cc42e..a2da66878 100644 --- a/make/stub_includes/opengl/macosx-window-system.h +++ b/make/stub_includes/opengl/macosx-window-system.h @@ -36,6 +36,7 @@ NSOpenGLContext* createContext(NSOpenGLContext* shareContext, NSOpenGLPixelFormat* pixelFormat, Bool opaque, int* viewNotReady); +void setContextView(NSOpenGLContext* ctx, NSView* view); Bool makeCurrentContext(NSOpenGLContext* ctx); Bool clearCurrentContext(NSOpenGLContext *ctx); Bool deleteContext(NSOpenGLContext* ctx, Bool releaseOnMainThread); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 360b7457b..1c59b8d97 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -84,6 +84,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl // NSOpenGL-based or CGL-based) protected interface GLBackendImpl { boolean isNSContext(); + void drawableChangedNotify(); long create(long share, int ctp, int major, int minor); boolean destroy(long ctx); boolean contextRealized(boolean realized); @@ -336,7 +337,13 @@ public abstract class MacOSXCGLContext extends GLContextImpl super.contextRealized(false); // 2) free drawable stuff } } - + + /* pp */ void drawableChangedNotify() { + if( 0 != contextHandle) { + impl.drawableChangedNotify(); + } + } + /* pp */ void detachPBuffer() { impl.detachPBuffer(); } @@ -475,7 +482,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl class NSOpenGLImpl implements GLBackendImpl { private OffscreenLayerSurface backingLayerHost = null; private long nsOpenGLLayer = 0; - private long nsOpenGLLayerPFmt = 0; + private long nsOpenGLLayerPFmt = 0; // lifecycle: [create - contextRealized] private float screenVSyncTimeout; // microSec private int vsyncTimeout; // microSec - for nsOpenGLLayer mode private int lastWidth=0, lastHeight=0; // allowing to detect size change @@ -486,26 +493,31 @@ public abstract class MacOSXCGLContext extends GLContextImpl public boolean isNSContext() { return true; } @Override - public long create(long share, int ctp, int major, int minor) { - long ctx = 0; - final NativeSurface surface = drawable.getNativeSurface(); - final MacOSXCGLGraphicsConfiguration config = (MacOSXCGLGraphicsConfiguration) surface.getGraphicsConfiguration(); - final GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); + public void drawableChangedNotify() { + backingLayerHost = NativeWindowFactory.getOffscreenLayerSurface(drawable.getNativeSurface(), true); + if( null == backingLayerHost ) { + boolean[] isPBuffer = { false }; + boolean[] isFBO = { false }; + CGL.setContextView(contextHandle, getNSViewHandle(isPBuffer, isFBO)); + } else { + nsOpenGLLayer = backingLayerHost.getAttachedSurfaceLayer(); + } + } + + private long getNSViewHandle(boolean[] isPBuffer, boolean[] isFBO) { final long nsViewHandle; - final boolean isPBuffer; - final boolean isFBO; if(drawable instanceof GLFBODrawableImpl) { nsViewHandle = 0; - isPBuffer = false; - isFBO = true; + isPBuffer[0] = false; + isFBO[0] = true; if(DEBUG) { System.err.println("NS create GLFBODrawableImpl drawable: isFBO "+isFBO+", isPBuffer "+isPBuffer+", "+drawable.getClass().getName()+",\n\t"+drawable); } } else if(drawable instanceof MacOSXCGLDrawable) { // we allow null here! (special pbuffer case) nsViewHandle = ((MacOSXCGLDrawable)MacOSXCGLContext.this.drawable).getNSViewHandle(); - isPBuffer = CGL.isNSOpenGLPixelBuffer(drawable.getHandle()); - isFBO = false; + isPBuffer[0] = CGL.isNSOpenGLPixelBuffer(drawable.getHandle()); + isFBO[0] = false; if(DEBUG) { System.err.println("NS create MacOSXCGLDrawable drawable handle isFBO "+isFBO+", isPBuffer "+isPBuffer+", "+drawable.getClass().getName()+",\n\t"+drawable); } @@ -514,8 +526,8 @@ public abstract class MacOSXCGLContext extends GLContextImpl final long drawableHandle = drawable.getHandle(); final boolean isNSView = OSXUtil.isNSView(drawableHandle); final boolean isNSWindow = OSXUtil.isNSWindow(drawableHandle); - isPBuffer = CGL.isNSOpenGLPixelBuffer(drawableHandle); - isFBO = false; + isPBuffer[0] = CGL.isNSOpenGLPixelBuffer(drawableHandle); + isFBO[0] = false; if(DEBUG) { System.err.println("NS create Anonymous drawable handle "+toHexString(drawableHandle)+": isNSView "+isNSView+", isNSWindow "+isNSWindow+", isFBO "+isFBO+", isPBuffer "+isPBuffer+", "+drawable.getClass().getName()+",\n\t"+drawable); @@ -524,13 +536,32 @@ public abstract class MacOSXCGLContext extends GLContextImpl nsViewHandle = drawableHandle; } else if( isNSWindow ) { nsViewHandle = OSXUtil.GetNSView(drawableHandle); - } else if( isPBuffer ) { + } else if( isPBuffer[0] ) { nsViewHandle = 0; } else { throw new RuntimeException("Anonymous drawable instance's handle neither NSView, NSWindow nor PBuffer: "+toHexString(drawableHandle)+", "+drawable.getClass().getName()+",\n\t"+drawable); } } - needsSetContextPBuffer = isPBuffer; + needsSetContextPBuffer = isPBuffer[0]; + return nsViewHandle; + } + + @Override + public long create(long share, int ctp, int major, int minor) { + long ctx = 0; + final NativeSurface surface = drawable.getNativeSurface(); + final MacOSXCGLGraphicsConfiguration config = (MacOSXCGLGraphicsConfiguration) surface.getGraphicsConfiguration(); + final GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); + final long nsViewHandle; + final boolean isPBuffer; + final boolean isFBO; + { + boolean[] _isPBuffer = { false }; + boolean[] _isFBO = { false }; + nsViewHandle = getNSViewHandle(_isPBuffer, _isFBO); + isPBuffer = _isPBuffer[0]; + isFBO = _isFBO[0]; + } backingLayerHost = NativeWindowFactory.getOffscreenLayerSurface(surface, true); boolean incompleteView = null != backingLayerHost; @@ -661,6 +692,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl gl3ShaderProgramName = 0; } nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, gl3ShaderProgramName, nsOpenGLLayerPFmt, pbufferHandle, texID, chosenCaps.isBackgroundOpaque(), lastWidth, lastHeight); + nsOpenGLLayerPFmt = 0; // NSOpenGLLayer will release pfmt if (DEBUG) { System.err.println("NS create nsOpenGLLayer "+toHexString(nsOpenGLLayer)+" w/ pbuffer "+toHexString(pbufferHandle)+", texID "+texID+", texSize "+lastWidth+"x"+lastHeight+", "+drawable); } @@ -688,10 +720,6 @@ public abstract class MacOSXCGLContext extends GLContextImpl } nsOpenGLLayer = 0; } - if(0 != nsOpenGLLayerPFmt) { - CGL.deletePixelFormat(nsOpenGLLayerPFmt); - nsOpenGLLayerPFmt = 0; - } } backingLayerHost = null; return true; @@ -841,6 +869,11 @@ public abstract class MacOSXCGLContext extends GLContextImpl @Override public boolean isNSContext() { return false; } + @Override + public void drawableChangedNotify() { + // FIXME + } + @Override public long create(long share, int ctp, int major, int minor) { long ctx = 0; diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java index cc727c8e1..ff1772860 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java @@ -117,7 +117,9 @@ public abstract class MacOSXCGLDrawable extends GLDrawableImpl { // OpenGL window interface synchronized (createdContexts) { if(bound) { - createdContexts.add(new WeakReference((MacOSXCGLContext)ctx)); + final MacOSXCGLContext osxCtx = (MacOSXCGLContext)ctx; + createdContexts.add(new WeakReference(osxCtx)); + osxCtx.drawableChangedNotify(); } else { for(int i=0; i ref = createdContexts.get(i); diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index 6ebf400e2..b37930587 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -448,6 +448,7 @@ static const GLfloat gl_verts[] = { [self disableAnimation]; [self deallocPBuffer]; [[self openGLContext] release]; + [parentPixelFmt release]; [self release]; DBG_PRINT("MyNSOpenGLLayer::releaseLayer.X: %p (refcnt %d)\n", self, (int)[self retainCount]); pthread_mutex_unlock(&renderLock); diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m index 48807ee29..e8925f8e8 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m @@ -551,8 +551,7 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, NSOpenGLContext* ctx = [[NSOpenGLContext alloc] initWithFormat:fmt shareContext:share]; - if (ctx != nil) { - if (view != nil) { + if ( nil != ctx && nil != view ) { if(!opaque) { GLint zeroOpacity = 0; [ctx setValues:&zeroOpacity forParameter:NSOpenGLCPSurfaceOpacity]; @@ -563,7 +562,6 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, DBG_PRINT("createContext.3.X: setView\n"); [view unlockFocus]; } - } } DBG_PRINT("createContext.X: ctx: %p\n", ctx); @@ -571,6 +569,15 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, return ctx; } +void setContextView(NSOpenGLContext* ctx, NSView* view) { + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + if ( nil != ctx && nil != view ) { + [ctx setView:view]; + } + [pool release]; + return ctx; +} + Bool makeCurrentContext(NSOpenGLContext* ctx) { #if 0 // we issue the CGL Lock from Java upfront! diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index a62d08ccf..35c919f28 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -239,7 +239,8 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } protected abstract void detachSurfaceLayerImpl(final long layerHandle); - protected final long getAttachedSurfaceLayer() { + @Override + public final long getAttachedSurfaceLayer() { return offscreenSurfaceLayer; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index f9800109c..f6bc5822b 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -47,6 +47,9 @@ public interface OffscreenLayerSurface { */ public void detachSurfaceLayer() throws NativeWindowException; + /** Returns the attached surface layer or null if none is attached. */ + public long getAttachedSurfaceLayer(); + /** Returns true if a surface layer is attached, otherwise false. */ public boolean isSurfaceLayerAttached(); -- cgit v1.2.3 From d0f91a8ed17fbb1a7b56511c4e53a29e576f01af Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 8 Nov 2012 18:07:19 +0100 Subject: Fix GLAutoDrawable.dispose(): Dispose drawable even w/o context; JAWTWindow.lockSurface(): Check AWT component's native peer - Fix GLAutoDrawable.dispose(): Dispose drawable even w/o context - It is possible to have the GLContext not being created (not made current), so drawable shall be disposed independent. - Merge Runnable 'postDisposeOnEDTAction' to dispose Runnable for clarity - GLDrawableHelper: Split disposeGL from invokeGLImpl for clarity - JAWTWindow.lockSurface(): Check AWT component's native peer - W/o a native peer (!isDisplayable()), JAWT locking cannot succeed. - On OSX OpenJDK 1.7, attempting to JAWT lock a peer-less component crashes the VM - MacOSXJAWTWindow.lockSurfaceImpl(): Remove redundant null checks --- make/scripts/tests-osx-x64-custom.sh | 9 + make/scripts/tests.sh | 23 +-- .../classes/com/jogamp/opengl/swt/GLCanvas.java | 58 ++++--- .../classes/javax/media/opengl/awt/GLCanvas.java | 90 +++++----- .../classes/javax/media/opengl/awt/GLJPanel.java | 29 ++-- .../classes/jogamp/opengl/GLAutoDrawableBase.java | 33 ++-- .../classes/jogamp/opengl/GLDrawableHelper.java | 181 ++++++++++----------- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 47 +++--- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 40 ++--- .../awt/TestGLCanvasAWTActionDeadlock01AWT.java | 74 ++++++--- .../awt/TestGLCanvasAWTActionDeadlock02AWT.java | 51 ++++-- 11 files changed, 355 insertions(+), 280 deletions(-) create mode 100755 make/scripts/tests-osx-x64-custom.sh (limited to 'src/nativewindow') diff --git a/make/scripts/tests-osx-x64-custom.sh b/make/scripts/tests-osx-x64-custom.sh new file mode 100755 index 000000000..88587f086 --- /dev/null +++ b/make/scripts/tests-osx-x64-custom.sh @@ -0,0 +1,9 @@ +#! /bin/bash + +export DYLD_LIBRARY_PATH=/usr/local/lib:$DYLD_LIBRARY_PATH + +spath=`dirname $0` + +. $spath/tests.sh "`which java`" -d64 ../build-macosx $* + + diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index e746f5e4c..3add0371f 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -5,15 +5,15 @@ if [ -z "$1" -o -z "$2" -o -z "$3" ] ; then exit 0 fi -javaexe=$1 +javaexe="$1" shift javaxargs=$1 shift bdir=$1 shift -if [ ! -x $javaexe ] ; then - echo java-exe $javaexe is not an executable +if [ ! -x "$javaexe" ] ; then + echo java-exe "$javaexe" is not an executable exit 1 fi if [ ! -d $bdir ] ; then @@ -42,15 +42,15 @@ if [ $MOSX -eq 1 ] ; then MOSX_MT=1 fi -which $javaexe 2>&1 | tee -a java-run.log -$javaexe -version 2>&1 | tee -a java-run.log +which "$javaexe" 2>&1 | tee -a java-run.log +"$javaexe" -version 2>&1 | tee -a java-run.log echo LIBXCB_ALLOW_SLOPPY_LOCK: $LIBXCB_ALLOW_SLOPPY_LOCK 2>&1 | tee -a java-run.log echo LIBGL_DRIVERS_PATH: $LIBGL_DRIVERS_PATH 2>&1 | tee -a java-run.log echo LIBGL_DEBUG: $LIBGL_DEBUG 2>&1 | tee -a java-run.log echo LIBGL_ALWAYS_INDIRECT: $LIBGL_ALWAYS_INDIRECT 2>&1 | tee -a java-run.log echo LIBGL_ALWAYS_SOFTWARE: $LIBGL_ALWAYS_SOFTWARE 2>&1 | tee -a java-run.log echo SWT_CLASSPATH: $SWT_CLASSPATH 2>&1 | tee -a java-run.log -echo $javaexe $javaxargs $X_ARGS $D_ARGS $* 2>&1 | tee -a java-run.log +echo "$javaexe" $javaxargs $X_ARGS $D_ARGS $* 2>&1 | tee -a java-run.log echo MacOsX $MOSX function jrun() { @@ -209,13 +209,13 @@ function jrun() { echo echo LD_LIBRARY_PATH $LD_LIBRARY_PATH echo - echo $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $* + echo "$javaexe" $javaxargs $X_ARGS $D_ARGS $C_ARG $* #LIBGL_DRIVERS_PATH=/usr/lib/mesa:/usr/lib32/mesa \ #LIBGL_DEBUG=verbose INTEL_STRICT_CONFORMANCE=1 INTEL_DEBUG="buf bat" \ #LIBGL_DEBUG=verbose MESA_DEBUG=true INTEL_STRICT_CONFORMANCE=1 \ #export LIBGL_DEBUG=verbose MESA_DEBUG=true LIBGL_ALWAYS_SOFTWARE=true - #gdb --args $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $* - $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $* + #gdb --args "$javaexe" $javaxargs $X_ARGS $D_ARGS $C_ARG $* + "$javaexe" $javaxargs $X_ARGS $D_ARGS $C_ARG $* echo echo "Test End: $*" echo @@ -266,7 +266,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT2 $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES1NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestPointsNEWT $* @@ -285,6 +285,7 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOf #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOOnThreadSharedContext1DemoES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMix2DemosES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOMRTNEWT01 $* + #testawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableDeadlockAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461FBOSupersamplingSwingAWT #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* @@ -351,7 +352,7 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOf #testawt com.jogamp.opengl.test.junit.jogl.glu.TestBug463ScaleImageMemoryAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWTCardLayoutAnimatorStartStopBug532 $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAWTActionDeadlock00AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAWTActionDeadlock01AWT $* +testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAWTActionDeadlock01AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAWTActionDeadlock02AWT $* # diff --git a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java index 755a7c392..e80079c20 100644 --- a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java +++ b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java @@ -173,45 +173,49 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { /* * Disposes of OpenGL resources */ - private final Runnable postDisposeGLAction = new Runnable() { - @Override - public void run() { - context = null; - if (null != drawable) { - drawable.setRealized(false); - drawable = null; - } - } - }; - private final Runnable disposeOnEDTGLAction = new Runnable() { @Override public void run() { final RecursiveLock _lock = lock; _lock.lock(); try { - if (null != drawable && null != context) { - boolean animatorPaused = false; - final GLAnimatorControl animator = getAnimator(); - if (null != animator) { - animatorPaused = animator.pause(); - } - - if(context.isCreated()) { - helper.disposeGL(GLCanvas.this, drawable, context, postDisposeGLAction); - } - - if (animatorPaused) { - animator.resume(); - } + final GLAnimatorControl animator = getAnimator(); + final boolean animatorPaused; + if(null!=animator) { + // can't remove us from animator for recreational addNotify() + animatorPaused = animator.pause(); + } else { + animatorPaused = false; + } + + if ( null != context ) { + if( context.isCreated() ) { + // Catch dispose GLExceptions by GLEventListener, just 'print' them + // so we can continue with the destruction. + try { + helper.disposeGL(GLCanvas.this, context); + } catch (GLException gle) { + gle.printStackTrace(); + } + } + context = null; + } + if ( null != drawable ) { + drawable.setRealized(false); + drawable = null; } // SWT is owner of the device handle, not us. // Hence close() operation is a NOP. if (null != device) { - device.close(); - device = null; + device.close(); + device = null; } SWTAccessor.setRealized(GLCanvas.this, false); // unrealize .. + + if (animatorPaused) { + animator.resume(); + } + } finally { _lock.unlock(); } diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 1d8666e6a..a40cdcf88 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -888,33 +888,6 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing // private boolean disposeRegenerate; - private final Runnable postDisposeOnEDTAction = new Runnable() { - @Override - public void run() { - context=null; - if(null!=drawable) { - drawable.setRealized(false); - drawable=null; - if(null!=jawtWindow) { - jawtWindow.destroy(); - jawtWindow=null; - } - } - - if(disposeRegenerate) { - // Similar process as in addNotify()! - - // Recreate GLDrawable/GLContext to reflect it's new graphics configuration - createDrawableAndContext(); - - if(DEBUG) { - System.err.println(getThreadName()+": GLCanvas.dispose(true): new drawable: "+drawable); - } - validateGLDrawable(); // immediate attempt to recreate the drawable - } - } - }; - private final Runnable disposeOnEDTAction = new Runnable() { @Override public void run() { @@ -929,31 +902,64 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing Thread.dumpStack(); } - if(null!=drawable && null!=context) { - boolean animatorPaused = false; - if(null!=animator) { - // can't remove us from animator for recreational addNotify() - animatorPaused = animator.pause(); - } - - if(context.isCreated()) { - helper.disposeGL(GLCanvas.this, drawable, context, postDisposeOnEDTAction); + final boolean animatorPaused; + if(null!=animator) { + // can't remove us from animator for recreational addNotify() + animatorPaused = animator.pause(); + } else { + animatorPaused = false; + } + + if( null != context ) { + if( context.isCreated() ) { + // Catch dispose GLExceptions by GLEventListener, just 'print' them + // so we can continue with the destruction. + try { + helper.disposeGL(GLCanvas.this, context); + } catch (GLException gle) { + gle.printStackTrace(); + } + } + context=null; + } + if( null != drawable ) { + drawable.setRealized(false); + if(DEBUG) { + System.err.println(getThreadName()+": dispose("+disposeRegenerate+") - 1: "+drawable); } - - if(animatorPaused) { - animator.resume(); + drawable=null; + } + if( null != jawtWindow ) { + jawtWindow.destroy(); + if(DEBUG) { + System.err.println(getThreadName()+": dispose("+disposeRegenerate+") - 2: "+jawtWindow); } + jawtWindow=null; } - - if(!disposeRegenerate) { + + if(disposeRegenerate) { + // Similar process as in addNotify()! + + // Recreate GLDrawable/GLContext to reflect it's new graphics configuration + createDrawableAndContext(); + + if(DEBUG) { + System.err.println(getThreadName()+": GLCanvas.dispose(true): new drawable: "+drawable); + } + validateGLDrawable(); // immediate attempt to recreate the drawable + } else { if(null != awtConfig) { AWTEDTExecutor.singleton.invoke(getTreeLock(), true, disposeAbstractGraphicsDeviceActionOnEDT); } awtConfig=null; } + if(animatorPaused) { + animator.resume(); + } + if(DEBUG) { - System.err.println(getThreadName()+": dispose("+disposeRegenerate+") - END, "+animator); + System.err.println(getThreadName()+": dispose("+disposeRegenerate+") - END, animator "+animator); } } finally { diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java index 58b1baa65..dcfc1f0dd 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java @@ -757,21 +757,26 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing return "AWT-GLJPanel[ "+((null!=backend)?backend.getDrawable().getClass().getName():"null-drawable")+"]"; } - private final Runnable postDisposeAction = new Runnable() { - @Override - public void run() { - if (backend != null && !backend.isUsingOwnThreadManagment()) { - backend.destroy(); - backend = null; - isInitialized = false; - } - } - }; - private final Runnable disposeAction = new Runnable() { @Override public void run() { - helper.disposeGL(GLJPanel.this, backend.getDrawable(), backend.getContext(), postDisposeAction); + if ( null != backend ) { + final GLContext _context = backend.getContext(); + if( null != _context && _context.isCreated() ) { + // Catch dispose GLExceptions by GLEventListener, just 'print' them + // so we can continue with the destruction. + try { + helper.disposeGL(GLJPanel.this, _context); + } catch (GLException gle) { + gle.printStackTrace(); + } + } + if ( !backend.isUsingOwnThreadManagment() ) { + backend.destroy(); + backend = null; + isInitialized = false; + } + } } }; diff --git a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java index 7bcd37ecd..68fbe3dd5 100644 --- a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java +++ b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java @@ -223,27 +223,26 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { * In such case call super.destroyImplInLock first.

      */ protected void destroyImplInLock() { - final GLContext _context = context; - final GLDrawable _drawable = drawable; - if( null != _drawable ) { - if( _drawable.isRealized() ) { - if( null != _context && _context.isCreated() ) { - // Catch dispose GLExceptions by GLEventListener, just 'print' them - // so we can continue with the destruction. - try { - helper.disposeGL(this, _drawable, _context, null); - } catch (GLException gle) { - gle.printStackTrace(); - } + if( null != context ) { + if( context.isCreated() ) { + // Catch dispose GLExceptions by GLEventListener, just 'print' them + // so we can continue with the destruction. + try { + helper.disposeGL(this, context); + } catch (GLException gle) { + gle.printStackTrace(); } - _drawable.setRealized(false); } + context = null; + } + if( null != drawable ) { + final AbstractGraphicsDevice device = drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice(); + drawable.setRealized(false); + drawable = null; if( ownsDevice ) { - _drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice().close(); + device.close(); } - } - context = null; - drawable = null; + } } public final void defaultSwapBuffers() throws GLException { diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java index 36dc933ab..f7f846b05 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java @@ -397,8 +397,8 @@ public class GLDrawableHelper { * otherwise maked uninitialized. *

      *

      - * Please consider using {@link #disposeAllGLEventListener(GLAutoDrawable, GLDrawable, GLContext)} - * or {@link #disposeGL(GLAutoDrawable, GLDrawable, GLContext, Runnable)} + * Please consider using {@link #disposeAllGLEventListener(GLAutoDrawable, GLContext, boolean)} + * or {@link #disposeGL(GLAutoDrawable, GLContext)} * for correctness, i.e. encapsulating all calls w/ makeCurrent etc. *

      * @param autoDrawable @@ -483,8 +483,7 @@ public class GLDrawableHelper { * * @param autoDrawable * @param context - * @param listener - * @param initAction + * @param remove */ public final void disposeAllGLEventListener(final GLAutoDrawable autoDrawable, final GLDrawable drawable, @@ -505,29 +504,6 @@ public class GLDrawableHelper { } } - /** - * Principal helper method which runs - * {@link #disposeAllGLEventListener(GLAutoDrawable, boolean) disposeAllGLEventListener(autoDrawable, false)} - * with the context made current and destroys the context afterwards while holding the lock. - * @param autoDrawable - * @param drawable - * @param context - * @param postAction - */ - public final void disposeGL(final GLAutoDrawable autoDrawable, - final GLDrawable drawable, - final GLContext context, - final Runnable postAction) { - if(PERF_STATS) { - invokeGLImplStats(drawable, context, null, null, autoDrawable); - } else { - invokeGLImpl(drawable, context, null, null, autoDrawable); - } - if(null != postAction) { - postAction.run(); - } - } - private final void init(GLEventListener l, GLAutoDrawable drawable, boolean sendReshape) { l.init(drawable); if(sendReshape) { @@ -842,21 +818,66 @@ public class GLDrawableHelper { } if(PERF_STATS) { - invokeGLImplStats(drawable, context, runnable, initAction, null); + invokeGLImplStats(drawable, context, runnable, initAction); } else { - invokeGLImpl(drawable, context, runnable, initAction, null); + invokeGLImpl(drawable, context, runnable, initAction); } } + /** + * Principal helper method which runs + * {@link #disposeAllGLEventListener(GLAutoDrawable, boolean) disposeAllGLEventListener(autoDrawable, false)} + * with the context made current and destroys the context afterwards while holding the lock. + * @param autoDrawable + * @param context + */ + public final void disposeGL(final GLAutoDrawable autoDrawable, + final GLContext context) { + // Support for recursive makeCurrent() calls as well as calling + // other drawables' display() methods from within another one's + GLContext lastContext = GLContext.getCurrent(); + Runnable lastInitAction = null; + if (lastContext != null) { + if (lastContext == context) { + lastContext = null; // utilize recursive locking + } else { + lastInitAction = perThreadInitAction.get(); + lastContext.release(); + } + } + int res = GLContext.CONTEXT_NOT_CURRENT; + + try { + res = context.makeCurrent(); + if (GLContext.CONTEXT_NOT_CURRENT != res) { + if(GLContext.CONTEXT_CURRENT_NEW == res) { + throw new GLException(Thread.currentThread().getName()+" GLDrawableHelper " + this + ".invokeGL(): Dispose case (no init action given): Native context was not created (new ctx): "+context); + } + if( listeners.size() > 0 && null != autoDrawable ) { + disposeAllGLEventListener(autoDrawable, false); + } + } + } finally { + try { + context.destroy(); + flushGLRunnables(); + } catch (Exception e) { + System.err.println("Catched: "+e.getMessage()); + e.printStackTrace(); + } + if (lastContext != null) { + final int res2 = lastContext.makeCurrent(); + if (null != lastInitAction && res2 == GLContext.CONTEXT_CURRENT_NEW) { + lastInitAction.run(); + } + } + } + } + private final void invokeGLImpl(final GLDrawable drawable, final GLContext context, final Runnable runnable, - final Runnable initAction, - final GLAutoDrawable disposeAutoDrawable) { - final Thread currentThread = Thread.currentThread(); - - final boolean isDisposeAction = null==initAction ; - + final Runnable initAction) { // Support for recursive makeCurrent() calls as well as calling // other drawables' display() methods from within another one's GLContext lastContext = GLContext.getCurrent(); @@ -874,35 +895,21 @@ public class GLDrawableHelper { try { res = context.makeCurrent(); if (GLContext.CONTEXT_NOT_CURRENT != res) { - if(!isDisposeAction) { - perThreadInitAction.set(initAction); - if (GLContext.CONTEXT_CURRENT_NEW == res) { - if (DEBUG) { - System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running initAction"); - } - initAction.run(); - } - runnable.run(); - if (autoSwapBufferMode) { - drawable.swapBuffers(); - } - } else { - if(GLContext.CONTEXT_CURRENT_NEW == res) { - throw new GLException(currentThread.getName()+" GLDrawableHelper " + this + ".invokeGL(): Dispose case (no init action given): Native context was not created (new ctx): "+context); - } - if( listeners.size() > 0 && null != disposeAutoDrawable ) { - disposeAllGLEventListener(disposeAutoDrawable, false); - } + perThreadInitAction.set(initAction); + if (GLContext.CONTEXT_CURRENT_NEW == res) { + if (DEBUG) { + System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running initAction"); + } + initAction.run(); + } + runnable.run(); + if ( autoSwapBufferMode ) { + drawable.swapBuffers(); } } } finally { try { - if(isDisposeAction) { - context.destroy(); - flushGLRunnables(); - } else if( GLContext.CONTEXT_NOT_CURRENT != res ) { - context.release(); - } + context.release(); } catch (Exception e) { System.err.println("Catched: "+e.getMessage()); e.printStackTrace(); @@ -919,12 +926,9 @@ public class GLDrawableHelper { private final void invokeGLImplStats(final GLDrawable drawable, final GLContext context, final Runnable runnable, - final Runnable initAction, - final GLAutoDrawable disposeAutoDrawable) { + final Runnable initAction) { final Thread currentThread = Thread.currentThread(); - final boolean isDisposeAction = null==initAction ; - // Support for recursive makeCurrent() calls as well as calling // other drawables' display() methods from within another one's int res = GLContext.CONTEXT_NOT_CURRENT; @@ -956,41 +960,28 @@ public class GLDrawableHelper { ctxClaimed = true; } if (res != GLContext.CONTEXT_NOT_CURRENT) { - if(!isDisposeAction) { - perThreadInitAction.set(initAction); - if (res == GLContext.CONTEXT_CURRENT_NEW) { - if (DEBUG) { - System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running initAction"); - } - initAction.run(); - } - tdR = System.currentTimeMillis(); - tdA = tdR - t0; // makeCurrent - runnable.run(); - tdS = System.currentTimeMillis(); - tdR = tdS - tdR; // render time - if (autoSwapBufferMode) { - drawable.swapBuffers(); - tdX = System.currentTimeMillis(); - tdS = tdX - tdS; // swapBuffers - } - } else { - if(res == GLContext.CONTEXT_CURRENT_NEW) { - throw new GLException(currentThread.getName()+" GLDrawableHelper " + this + ".invokeGL(): Dispose case (no init action given): Native context was not created (new ctx): "+context); - } - if( listeners.size() > 0 && null != disposeAutoDrawable ) { - disposeAllGLEventListener(disposeAutoDrawable, false); - } + perThreadInitAction.set(initAction); + if (res == GLContext.CONTEXT_CURRENT_NEW) { + if (DEBUG) { + System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running initAction"); + } + initAction.run(); + } + tdR = System.currentTimeMillis(); + tdA = tdR - t0; // makeCurrent + runnable.run(); + tdS = System.currentTimeMillis(); + tdR = tdS - tdR; // render time + if (autoSwapBufferMode) { + drawable.swapBuffers(); + tdX = System.currentTimeMillis(); + tdS = tdX - tdS; // swapBuffers } } } finally { try { - if(isDisposeAction) { - context.destroy(); - flushGLRunnables(); - ctxDestroyed = true; - } else if( res != GLContext.CONTEXT_NOT_CURRENT && - (null == skipContextReleaseThread || currentThread != skipContextReleaseThread) ) { + if( res != GLContext.CONTEXT_NOT_CURRENT && + (null == skipContextReleaseThread || currentThread != skipContextReleaseThread) ) { context.release(); ctxReleased = true; } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 35c919f28..8527a0200 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -320,32 +320,41 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ? if ( LOCK_SURFACE_NOT_READY == res ) { - determineIfApplet(); - try { - final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); - adevice.lock(); + if( !component.isDisplayable() ) { + // W/o native peer, we cannot utilize JAWT for locking. + surfaceLock.unlock(); + if(DEBUG) { + System.err.println("JAWTWindow: Can't lock surface, component peer n/a. Component displayable "+component.isDisplayable()+", "+component); + Thread.dumpStack(); + } + } else { + determineIfApplet(); try { - if(null == jawt) { // no need to re-fetch for each frame - jawt = fetchJAWTImpl(); - isOffscreenLayerSurface = JAWTUtil.isJAWTUsingOffscreenLayer(jawt); - } - res = lockSurfaceImpl(); - if(LOCK_SUCCESS == res && drawable_old != drawable) { - res = LOCK_SURFACE_CHANGED; - if(DEBUG) { - System.err.println("JAWTWindow: surface change 0x"+Long.toHexString(drawable_old)+" -> 0x"+Long.toHexString(drawable)); - // Thread.dumpStack(); + final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice(); + adevice.lock(); + try { + if(null == jawt) { // no need to re-fetch for each frame + jawt = fetchJAWTImpl(); + isOffscreenLayerSurface = JAWTUtil.isJAWTUsingOffscreenLayer(jawt); + } + res = lockSurfaceImpl(); + if(LOCK_SUCCESS == res && drawable_old != drawable) { + res = LOCK_SURFACE_CHANGED; + if(DEBUG) { + System.err.println("JAWTWindow: surface change 0x"+Long.toHexString(drawable_old)+" -> 0x"+Long.toHexString(drawable)); + // Thread.dumpStack(); + } + } + } finally { + if (LOCK_SURFACE_NOT_READY >= res) { + adevice.unlock(); } } } finally { if (LOCK_SURFACE_NOT_READY >= res) { - adevice.unlock(); + surfaceLock.unlock(); } } - } finally { - if (LOCK_SURFACE_NOT_READY >= res) { - surfaceLock.unlock(); - } } } return res; diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 5fd242247..449121be1 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -119,13 +119,11 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } protected int lockSurfaceImpl() throws NativeWindowException { int ret = NativeWindow.LOCK_SURFACE_NOT_READY; - if(null == ds) { - ds = getJAWT().GetDrawingSurface(component); - if (ds == null) { - // Widget not yet realized - unlockSurfaceImpl(); - return NativeWindow.LOCK_SURFACE_NOT_READY; - } + ds = getJAWT().GetDrawingSurface(component); + if (ds == null) { + // Widget not yet realized + unlockSurfaceImpl(); + return NativeWindow.LOCK_SURFACE_NOT_READY; } int res = ds.Lock(); dsLocked = ( 0 == ( res & JAWTFactory.JAWT_LOCK_ERROR ) ) ; @@ -141,21 +139,19 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { if ((res & JAWTFactory.JAWT_LOCK_SURFACE_CHANGED) != 0) { ret = NativeWindow.LOCK_SURFACE_CHANGED; } - if(null == dsi) { - if (firstLock) { - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - dsi = ds.GetDrawingSurfaceInfo(); - return null; - } - }); - } else { - dsi = ds.GetDrawingSurfaceInfo(); - } - if (dsi == null) { - unlockSurfaceImpl(); - return NativeWindow.LOCK_SURFACE_NOT_READY; - } + if (firstLock) { + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + dsi = ds.GetDrawingSurfaceInfo(); + return null; + } + }); + } else { + dsi = ds.GetDrawingSurfaceInfo(); + } + if (dsi == null) { + unlockSurfaceImpl(); + return NativeWindow.LOCK_SURFACE_NOT_READY; } updateBounds(dsi.getBounds()); if (DEBUG && firstLock ) { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAWTActionDeadlock01AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAWTActionDeadlock01AWT.java index c2b6f1551..c51972c39 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAWTActionDeadlock01AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAWTActionDeadlock01AWT.java @@ -33,6 +33,9 @@ import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; + +import com.jogamp.common.os.Platform; +import com.jogamp.common.util.VersionNumber; import com.jogamp.opengl.util.Animator; import com.jogamp.opengl.util.AnimatorBase; import com.jogamp.opengl.util.FPSAnimator; @@ -53,7 +56,21 @@ import org.junit.Assert; import org.junit.Assume; import org.junit.Test; - +/** + * BUG on OSX/CALayer w/ Java6: + * If frame.setTitle() is issued right after initialization the call hangs in + *
       
      + * at apple.awt.CWindow._setTitle(Native Method)
      + *  at apple.awt.CWindow.setTitle(CWindow.java:765) [1.6.0_37, build 1.6.0_37-b06-434-11M3909]
      + * 
      + *

      + * OSX/CALayer is forced by using an Applet component in this unit test. + *

      + *

      + * Similar deadlock has been experienced w/ other mutable operation on an AWT Container owning a GLCanvas child, + * e.g. setResizable*(). + *

      + */ public class TestGLCanvasAWTActionDeadlock01AWT extends UITestCase { static long durationPerTest = 1000; // ms static final int width = 512; @@ -87,6 +104,14 @@ public class TestGLCanvasAWTActionDeadlock01AWT extends UITestCase { public void test02FPSAnimator_RestartOnCurrentThread() throws InterruptedException { testImpl(new FPSAnimator(30), 200, true); } */ + + private static void setFrameTitle(Frame frame, String msg) { + System.err.println("About to setTitle: <"+msg+"> CT "+Thread.currentThread().getName()+", "+ + frame+", displayable "+frame.isDisplayable()+ + ", valid "+frame.isValid()+", visible "+frame.isVisible()); + // Thread.dumpStack(); + frame.setTitle(msg); + } void testImpl(final AnimatorBase animator, int restartPeriod, boolean restartOnCurrentThread) throws InterruptedException { final Frame frame1 = new Frame("Frame 1"); @@ -94,6 +119,13 @@ public class TestGLCanvasAWTActionDeadlock01AWT extends UITestCase { private static final long serialVersionUID = 1L; }; + final VersionNumber version170 = new VersionNumber(1, 7, 0); + final boolean osxCALayerAWTModBug = Platform.OSType.MACOS == Platform.getOSType() && + 0 > Platform.getJavaVersionNumber().compareTo(version170); + System.err.println("OSX CALayer AWT-Mod Bug "+osxCALayerAWTModBug); + System.err.println("OSType "+Platform.getOSType()); + System.err.println("Java Version "+Platform.getJavaVersionNumber()); + Assert.assertNotNull(frame1); frame1.setLayout(null); frame1.pack(); @@ -109,7 +141,7 @@ public class TestGLCanvasAWTActionDeadlock01AWT extends UITestCase { frame1.setLocation(0, 0); frame1.setTitle("Generic Title"); frame1.add(applet1); - + frame1.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(frame1, applet1); @@ -122,34 +154,36 @@ public class TestGLCanvasAWTActionDeadlock01AWT extends UITestCase { @Override public void init(GLAutoDrawable drawable) { justInitialized = true; + if( !osxCALayerAWTModBug ) { + System.err.println("*Init*: CT "+Thread.currentThread().getName()); + setFrameTitle(frame1, "INIT"); + frame1.setResizable(false); + } } @Override public void dispose(GLAutoDrawable drawable) { + System.err.println("*Dispose*: CT "+Thread.currentThread().getName()); + setFrameTitle(frame1, "DISPOSE"); } @Override public void display(GLAutoDrawable drawable) { - if(!justInitialized) { - // BUG on OSX/CALayer: If frame.setTitle() is issued right after initialization - // the call hangs in - // at apple.awt.CWindow._setTitle(Native Method) - // at apple.awt.CWindow.setTitle(CWindow.java:765) [1.6.0_37, build 1.6.0_37-b06-434-11M3909] - // - final String msg = "f "+frameCount+", fps "+( null != animator ? animator.getLastFPS() : 0); - System.err.println("About to setTitle: CT "+Thread.currentThread().getName()+", "+msg+ - frame1+", displayable "+frame1.isDisplayable()+ - ", valid "+frame1.isValid()+", visible "+frame1.isVisible()); - // Thread.dumpStack(); - frame1.setTitle(msg); - + if( !osxCALayerAWTModBug || !justInitialized ) { + System.err.println("*Display*: CT "+Thread.currentThread().getName()); + setFrameTitle(frame1, "f "+frameCount+", fps "+( null != animator ? animator.getLastFPS() : 0)); + frame1.setResizable(false); } frameCount++; - justInitialized=false; + justInitialized = false; } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { + if( !osxCALayerAWTModBug || !justInitialized ) { + System.err.println("*Reshape*: CT "+Thread.currentThread().getName()); + setFrameTitle(frame1, "RESHAPE"); + } } }; gle2 = new GearsES2(); @@ -188,7 +222,7 @@ public class TestGLCanvasAWTActionDeadlock01AWT extends UITestCase { glCanvas.display(); } if(0 < restartPeriod) { - glCanvas = restart(frame1, applet1, glCanvas, restartOnCurrentThread); + glCanvas = restart(applet1, glCanvas, restartOnCurrentThread); } Thread.sleep(sleep); @@ -234,7 +268,7 @@ public class TestGLCanvasAWTActionDeadlock01AWT extends UITestCase { } } - GLCanvas restart(final Frame frame, final Applet applet, GLCanvas glCanvas, boolean restartOnCurrentThread) throws InterruptedException { + GLCanvas restart(final Applet applet, GLCanvas glCanvas, boolean restartOnCurrentThread) throws InterruptedException { glCanvas.disposeGLEventListener(gle1, true); glCanvas.disposeGLEventListener(gle2, true); detachGLCanvas(applet, glCanvas, restartOnCurrentThread); @@ -253,7 +287,7 @@ public class TestGLCanvasAWTActionDeadlock01AWT extends UITestCase { if( restartOnCurrentThread ) { applet.setLayout(new BorderLayout()); applet.add(glCanvas, BorderLayout.CENTER); - applet.validate(); + applet.validate(); } else { try { javax.swing.SwingUtilities.invokeAndWait(new Runnable() { @@ -274,7 +308,7 @@ public class TestGLCanvasAWTActionDeadlock01AWT extends UITestCase { System.err.println("*** detachGLCanvas.0 on-current-thread "+restartOnCurrentThread+", currentThread "+Thread.currentThread().getName()); if( restartOnCurrentThread ) { applet.remove(glCanvas); - applet.validate(); + applet.validate(); } else { try { javax.swing.SwingUtilities.invokeAndWait(new Runnable() { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAWTActionDeadlock02AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAWTActionDeadlock02AWT.java index a74286232..d8f25868b 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAWTActionDeadlock02AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAWTActionDeadlock02AWT.java @@ -53,12 +53,31 @@ import javax.media.opengl.awt.GLCanvas; import org.junit.Assume; import org.junit.Test; +import com.jogamp.common.os.Platform; +import com.jogamp.common.util.VersionNumber; import com.jogamp.opengl.util.AnimatorBase; import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; -// Sample program that relies on JOGL's mechanism to handle the OpenGL context -// and rendering loop when using an AWT canvas attached to an Applet. +/** + * Sample program that relies on JOGL's mechanism to handle the OpenGL context + * and rendering loop when using an AWT canvas attached to an Applet. + *

      + * BUG on OSX/CALayer w/ Java6: + * If frame.setTitle() is issued right after initialization the call hangs in + *

       
      + * at apple.awt.CWindow._setTitle(Native Method)
      + *  at apple.awt.CWindow.setTitle(CWindow.java:765) [1.6.0_37, build 1.6.0_37-b06-434-11M3909]
      + * 
      + *

      + *

      + * OSX/CALayer is forced by using an Applet component in this unit test. + *

      + *

      + * Similar deadlock has been experienced w/ other mutable operation on an AWT Container owning a GLCanvas child, + * e.g. setResizable*(). + *

      + */ public class TestGLCanvasAWTActionDeadlock02AWT extends UITestCase { static int framesPerTest = 240; // frames @@ -109,7 +128,9 @@ public class TestGLCanvasAWTActionDeadlock02AWT extends UITestCase { private long frameRatePeriod = 1000000000L / frameRate; private boolean initialized = false; - + private boolean osxCALayerAWTModBug = false; + boolean justInitialized = true; + private double theta = 0; private double s = 0; private double c = 0; @@ -161,6 +182,13 @@ public class TestGLCanvasAWTActionDeadlock02AWT extends UITestCase { millisOffset = System.currentTimeMillis(); + final VersionNumber version170 = new VersionNumber(1, 7, 0); + osxCALayerAWTModBug = Platform.OSType.MACOS == Platform.getOSType() && + 0 > Platform.getJavaVersionNumber().compareTo(version170); + System.err.println("OSX CALayer AWT-Mod Bug "+osxCALayerAWTModBug); + System.err.println("OSType "+Platform.getOSType()); + System.err.println("Java Version "+Platform.getJavaVersionNumber()); + // Frame setup ---------------------------------------------------------- width = 300; @@ -328,16 +356,9 @@ public class TestGLCanvasAWTActionDeadlock02AWT extends UITestCase { }}); } } - - boolean justInitialized = true; - + void draw(GL2 gl) { - if(!justInitialized) { - // BUG on OSX/CALayer: If frame.setTitle() is issued right after initialization - // the call hangs in - // at apple.awt.CWindow._setTitle(Native Method) - // at apple.awt.CWindow.setTitle(CWindow.java:765) [1.6.0_37, build 1.6.0_37-b06-434-11M3909] - // + if( !osxCALayerAWTModBug || !justInitialized ) { frame.setTitle("frame " + frameCount); } @@ -441,15 +462,15 @@ public class TestGLCanvasAWTActionDeadlock02AWT extends UITestCase { class SimpleListener implements GLEventListener { @Override public void display(GLAutoDrawable drawable) { - draw(drawable.getGL().getGL2()); - justInitialized = false; + draw(drawable.getGL().getGL2()); + justInitialized = false; } @Override public void dispose(GLAutoDrawable drawable) { } @Override - public void init(GLAutoDrawable drawable) { + public void init(GLAutoDrawable drawable) { justInitialized = true; } -- cgit v1.2.3 From 7e5371ca8eafce28c242fa7fbd8aec045fc81b71 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 21 Nov 2012 18:38:46 +0100 Subject: OSX CALayer Stencil/.. Fix: In case of FBO CALayer usage, use default caps/pixelformat w/ chosen GLProfile only Using a pixelformat w/ chosen stencil for CALayer does corrupt rendering for an unknown reason, probably due to incompatible pixelformat w/ CALayer composition. This patch simply discards any special chosen caps, while only recognizing the desired GLProfile for the FBO CALayer pixelformat. --- make/scripts/tests.sh | 11 +- .../jogamp/opengl/GLDrawableFactoryImpl.java | 4 +- .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 40 +++--- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 4 +- ...estGLAutoDrawableDelegateOnOffscrnCapsNEWT.java | 28 ++--- .../TestGLAutoDrawableFactoryOffscrnCapsNEWT.java | 53 +++++++- ...TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java | 51 +++++--- ...estGLAutoDrawableGLWindowOnOffscrnCapsNEWT.java | 136 +++++++++++++++++++-- ...LAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT.java | 53 +++++++- .../junit/jogl/demos/es2/awt/TestGearsES2AWT.java | 6 + 10 files changed, 315 insertions(+), 71 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 621b61c6f..fc9b47c69 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -76,6 +76,7 @@ function jrun() { #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.FBObject -Djogl.debug.GLContext -Djogl.debug.GLDrawable -Djogl.debug.GLCanvas -Dnewt.debug.Window" #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.FBObject" #D_ARGS="-Djogl.debug.GLContext.NoProfileAliasing" + #D_ARGS="-Djogamp.debug=all" #D_ARGS="-Djogamp.debug=all -Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" #D_ARGS="-Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" #D_ARGS="-Djogl.debug=all -Dnewt.debug=all" @@ -250,7 +251,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFloatUtil01MatrixMatrixMultNOUI $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestPMVMatrix01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestPMVMatrix01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestPMVMatrix02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestNEWTCloseX11DisplayBug565 $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT $* @@ -266,19 +267,19 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestPMVMatrix01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT2 $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES1NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestPointsNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryOffscrnCapsNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryOffscrnCapsNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer01GLCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer02NewtCanvasAWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* +testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableFactoryNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOOffThreadSharedContextMix2DemosES2NEWT $* diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index 2bb22f7b0..5c5db6d31 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -147,6 +147,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(target, true); if(null != ols) { final GLCapabilitiesImmutable chosenCapsMod = GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(chosenCaps, this, adevice); + // layered surface -> Offscreen/[FBO|PBuffer] if( !chosenCapsMod.isFBO() && !chosenCapsMod.isPBuffer() ) { throw new GLException("Neither FBO nor Pbuffer is available for "+chosenCapsMod+", "+target); @@ -155,7 +156,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { ols.setChosenCapabilities(chosenCapsMod); if(DEBUG) { System.err.println("GLDrawableFactoryImpl.createGLDrawable -> OnscreenDrawable -> Offscreen-Layer"); - System.err.println("chosenCaps: "+chosenCaps); + System.err.println("chosenCaps: "+chosenCaps); System.err.println("chosenCapsMod: "+chosenCapsMod); System.err.println("OffscreenLayerSurface: **** "+ols); System.err.println("Target: **** "+target); @@ -165,7 +166,6 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { throw new IllegalArgumentException("Passed NativeSurface must implement SurfaceChangeable for offscreen layered surface: "+target); } if( chosenCapsMod.isFBO() ) { - // target surface is already a native one result = createFBODrawableImpl(target, chosenCapsMod, 0); } else { result = createOffscreenDrawableImpl(target); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 1c59b8d97..cde9841b8 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -568,24 +568,38 @@ public abstract class MacOSXCGLContext extends GLContextImpl if( !incompleteView && surface instanceof ProxySurface ) { incompleteView = ((ProxySurface)surface).containsUpstreamOptionBits( ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE ); } - long pixelFormat = MacOSXCGLGraphicsConfiguration.GLCapabilities2NSPixelFormat(chosenCaps, ctp, major, minor); + long pixelFormat; + { + final GLCapabilitiesImmutable targetCaps; + if( isFBO ) { + // Use minimum GLCapabilities for the target surface w/ same profile + targetCaps = new GLCapabilities( chosenCaps.getGLProfile() ); + } else { + targetCaps = chosenCaps; + } + pixelFormat = MacOSXCGLGraphicsConfiguration.GLCapabilities2NSPixelFormat(targetCaps, ctp, major, minor); + } if (pixelFormat == 0) { if(DEBUG) { System.err.println("Unable to allocate pixel format with requested GLCapabilities: "+chosenCaps); } return 0; } - GLCapabilities fixedCaps = MacOSXCGLGraphicsConfiguration.NSPixelFormat2GLCapabilities(chosenCaps.getGLProfile(), pixelFormat); - if( !fixedCaps.isPBuffer() && isPBuffer ) { - throw new InternalError("handle is PBuffer, fixedCaps not: "+drawable); - } - { // determine on-/offscreen caps, since pformat is ambiguous - fixedCaps.setFBO( isFBO ); // exclusive - fixedCaps.setPBuffer( isPBuffer ); // exclusive - fixedCaps.setBitmap( false ); // n/a in our OSX impl. - fixedCaps.setOnscreen( !isFBO && !isPBuffer ); + final GLCapabilitiesImmutable fixedCaps; + if( isFBO ) { + // pixelformat of target doesn't affect caps w/ FBO + fixedCaps = chosenCaps; + } else { + final GLCapabilities _fixedCaps = MacOSXCGLGraphicsConfiguration.NSPixelFormat2GLCapabilities(chosenCaps.getGLProfile(), pixelFormat); + if( !_fixedCaps.isPBuffer() && isPBuffer ) { + throw new InternalError("handle is PBuffer, fixedCaps not: "+drawable); + } + // determine on-/offscreen caps, since pformat is ambiguous + _fixedCaps.setPBuffer( isPBuffer ); // exclusive + _fixedCaps.setBitmap( false ); // n/a in our OSX impl. + _fixedCaps.setOnscreen( !isFBO && !isPBuffer ); + fixedCaps = GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(_fixedCaps, chosenCaps.isBackgroundOpaque()); } - fixedCaps = GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(fixedCaps, chosenCaps.isBackgroundOpaque()); int sRefreshRate = OSXUtil.GetScreenRefreshRate(drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getIndex()); screenVSyncTimeout = 1000000f / sRefreshRate; if(DEBUG) { @@ -604,10 +618,6 @@ public abstract class MacOSXCGLContext extends GLContextImpl // Thread.dumpStack(); } config.setChosenCapabilities(fixedCaps); - /** - if(null != backingLayerHost) { - backingLayerHost.setChosenCapabilities(fixedCaps); - } */ try { final IntBuffer viewNotReady = Buffers.newDirectIntBuffer(1); diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 449121be1..9e270d403 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -193,8 +193,8 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } } if(null == errMsg) { - // fix caps reflecting offscreen! (no GL available here ..) - Capabilities caps = (Capabilities) getGraphicsConfiguration().getChosenCapabilities().cloneMutable(); + // Fix caps reflecting offscreen! (no GL available here ..) + final Capabilities caps = (Capabilities) getGraphicsConfiguration().getChosenCapabilities().cloneMutable(); caps.setOnscreen(false); setChosenCapabilities(caps); } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateOnOffscrnCapsNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateOnOffscrnCapsNEWT.java index d9e9b2bf3..c5b4227c2 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateOnOffscrnCapsNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateOnOffscrnCapsNEWT.java @@ -235,20 +235,20 @@ public class TestGLAutoDrawableDelegateOnOffscrnCapsNEWT extends UITestCase { } @Test - public void testGL2OnScreenDblBuf() throws InterruptedException { + public void testGL2OnScreenSglBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; + reqGLCaps.setDoubleBuffered(false); doTest(reqGLCaps, new GearsES2(1)); } - + @Test - public void testGL2OnScreenSglBuf() throws InterruptedException { + public void testGL2OnScreenDblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; - reqGLCaps.setDoubleBuffered(false); doTest(reqGLCaps, new GearsES2(1)); } - + @Test public void testGL2OffScreenAutoDblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); @@ -258,21 +258,21 @@ public class TestGLAutoDrawableDelegateOnOffscrnCapsNEWT extends UITestCase { } @Test - public void testGL2OffScreenFBODblBuf() throws InterruptedException { + public void testGL2OffScreenFBOSglBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); reqGLCaps.setFBO(true); + reqGLCaps.setDoubleBuffered(false); doTest(reqGLCaps, new GearsES2(1)); } @Test - public void testGL2OffScreenFBOSglBuf() throws InterruptedException { + public void testGL2OffScreenFBODblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); reqGLCaps.setFBO(true); - reqGLCaps.setDoubleBuffered(false); doTest(reqGLCaps, new GearsES2(1)); } @@ -306,17 +306,17 @@ public class TestGLAutoDrawableDelegateOnOffscrnCapsNEWT extends UITestCase { } @Test - public void testES2OnScreenDblBuf() throws InterruptedException { + public void testES2OnScreenSglBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); if(null == reqGLCaps) return; + reqGLCaps.setDoubleBuffered(false); doTest(reqGLCaps, new GearsES2(1)); } @Test - public void testES2OnScreenSglBuf() throws InterruptedException { + public void testES2OnScreenDblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); if(null == reqGLCaps) return; - reqGLCaps.setDoubleBuffered(false); doTest(reqGLCaps, new GearsES2(1)); } @@ -329,21 +329,21 @@ public class TestGLAutoDrawableDelegateOnOffscrnCapsNEWT extends UITestCase { } @Test - public void testES2OffScreenFBODblBuf() throws InterruptedException { + public void testES2OffScreenFBOSglBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); reqGLCaps.setFBO(true); + reqGLCaps.setDoubleBuffered(false); doTest(reqGLCaps, new GearsES2(1)); } @Test - public void testES2OffScreenFBOSglBuf() throws InterruptedException { + public void testES2OffScreenFBODblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); reqGLCaps.setFBO(true); - reqGLCaps.setDoubleBuffered(false); doTest(reqGLCaps, new GearsES2(1)); } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableFactoryOffscrnCapsNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableFactoryOffscrnCapsNEWT.java index 51f9cc411..f8092d064 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableFactoryOffscrnCapsNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableFactoryOffscrnCapsNEWT.java @@ -192,7 +192,7 @@ public class TestGLAutoDrawableFactoryOffscrnCapsNEWT extends UITestCase { } @Test - public void testGL2OffScreenFBOStencil() throws InterruptedException { + public void testGL2OffScreenFBODblBufStencil() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); @@ -202,13 +202,25 @@ public class TestGLAutoDrawableFactoryOffscrnCapsNEWT extends UITestCase { } @Test - public void testGL2OffScreenFBOStencilMSAA() throws InterruptedException { + public void testGL2OffScreenFBODblBufMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBODblBufStencilMSAA() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); reqGLCaps.setFBO(true); reqGLCaps.setStencilBits(1); reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); doTest(reqGLCaps, new GearsES2(1)); } @@ -249,6 +261,16 @@ public class TestGLAutoDrawableFactoryOffscrnCapsNEWT extends UITestCase { doTest(reqGLCaps, new GearsES2(1)); } + @Test + public void testES2OffScreenFBOSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + @Test public void testES2OffScreenFBODblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); @@ -259,12 +281,35 @@ public class TestGLAutoDrawableFactoryOffscrnCapsNEWT extends UITestCase { } @Test - public void testES2OffScreenFBOSglBuf() throws InterruptedException { + public void testES2OffScreenFBODblBufStencil() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); reqGLCaps.setFBO(true); - reqGLCaps.setDoubleBuffered(false); + reqGLCaps.setStencilBits(1); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBODblBufMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBODblBufStencilMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setStencilBits(1); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); doTest(reqGLCaps, new GearsES2(1)); } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java index a2ffa9069..0673e2f45 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java @@ -247,76 +247,89 @@ public class TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT extends UITestCase { } @Test - public void testGL2OnScreen() throws InterruptedException { + public void testGL2OnScreenDblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; doTest(reqGLCaps, new GearsES2(1)); } @Test - public void testGL2OffScreenAuto() throws InterruptedException { + public void testGL2OnScreenDblBufStencil() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; - reqGLCaps.setOnscreen(false); + reqGLCaps.setStencilBits(1); doTest(reqGLCaps, new GearsES2(1)); } - + @Test - public void testGL2OffScreenFBOMSAA() throws InterruptedException { + public void testGL2OnScreenDblBufMSAA() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; - reqGLCaps.setOnscreen(false); - reqGLCaps.setFBO(true); reqGLCaps.setSampleBuffers(true); reqGLCaps.setNumSamples(4); doTest(reqGLCaps, new GearsES2(1)); } @Test - public void testGL2OffScreenPbuffer() throws InterruptedException { + public void testGL2OnScreenDblBufStencilMSAA() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; - reqGLCaps.setOnscreen(false); - reqGLCaps.setPBuffer(true); + reqGLCaps.setStencilBits(1); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); doTest(reqGLCaps, new GearsES2(1)); } @Test - public void testES2OnScreen() throws InterruptedException { - final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + public void testGL2OffScreenAutoDblBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBODblBufStencil() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setStencilBits(1); doTest(reqGLCaps, new GearsES2(1)); } @Test - public void testES2OffScreenAuto() throws InterruptedException { - final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + public void testGL2OffScreenFBODblBufMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); doTest(reqGLCaps, new GearsES2(1)); } @Test - public void testES2OffScreenFBOMSAA() throws InterruptedException { - final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + public void testGL2OffScreenFBODblBufStencilMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); reqGLCaps.setFBO(true); + reqGLCaps.setStencilBits(1); reqGLCaps.setSampleBuffers(true); reqGLCaps.setNumSamples(4); doTest(reqGLCaps, new GearsES2(1)); } @Test - public void testES2OffScreenPbuffer() throws InterruptedException { - final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + public void testGL2OffScreenPbuffer() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); reqGLCaps.setPBuffer(true); doTest(reqGLCaps, new GearsES2(1)); } - public static void main(String args[]) throws IOException { org.junit.runner.JUnitCore.main(TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.class.getName()); } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT.java index da5456777..0a6056606 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT.java @@ -188,6 +188,14 @@ public class TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT extends UITestCase { } } + @Test + public void testGL2OnScreenSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + @Test public void testGL2OnScreenDblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); @@ -196,10 +204,29 @@ public class TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT extends UITestCase { } @Test - public void testGL2OnScreenSglBuf() throws InterruptedException { + public void testGL2OnScreenDblBufStencil() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; - reqGLCaps.setDoubleBuffered(false); + reqGLCaps.setStencilBits(1); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OnScreenDblBufMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OnScreenDblBufStencilMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setStencilBits(1); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); doTest(reqGLCaps, new GearsES2(1)); } @@ -211,6 +238,16 @@ public class TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT extends UITestCase { doTest(reqGLCaps, new GearsES2(1)); } + @Test + public void testGL2OffScreenFBOSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + @Test public void testGL2OffScreenFBODblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); @@ -221,12 +258,35 @@ public class TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT extends UITestCase { } @Test - public void testGL2OffScreenFBOSglBuf() throws InterruptedException { + public void testGL2OffScreenFBODblBufStencil() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); reqGLCaps.setFBO(true); - reqGLCaps.setDoubleBuffered(false); + reqGLCaps.setStencilBits(1); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBODblBufMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBODblBufStencilMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setStencilBits(1); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); doTest(reqGLCaps, new GearsES2(1)); } @@ -259,6 +319,14 @@ public class TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT extends UITestCase { doTest(reqGLCaps, new Gears(1)); } + @Test + public void testES2OnScreenSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + @Test public void testES2OnScreenDblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); @@ -267,10 +335,29 @@ public class TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT extends UITestCase { } @Test - public void testES2OnScreenSglBuf() throws InterruptedException { + public void testES2OnScreenDblBufStencil() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); if(null == reqGLCaps) return; - reqGLCaps.setDoubleBuffered(false); + reqGLCaps.setStencilBits(1); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OnScreenDblBufMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OnScreenDblBufStencilMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setStencilBits(1); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); doTest(reqGLCaps, new GearsES2(1)); } @@ -282,6 +369,16 @@ public class TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT extends UITestCase { doTest(reqGLCaps, new GearsES2(1)); } + @Test + public void testES2OffScreenFBOSglBuf() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setDoubleBuffered(false); + doTest(reqGLCaps, new GearsES2(1)); + } + @Test public void testES2OffScreenFBODblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); @@ -292,12 +389,35 @@ public class TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT extends UITestCase { } @Test - public void testES2OffScreenFBOSglBuf() throws InterruptedException { + public void testES2OffScreenFBODblBufStencil() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); if(null == reqGLCaps) return; reqGLCaps.setOnscreen(false); reqGLCaps.setFBO(true); - reqGLCaps.setDoubleBuffered(false); + reqGLCaps.setStencilBits(1); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBODblBufMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(reqGLCaps, new GearsES2(1)); + } + + @Test + public void testES2OffScreenFBODblBufStencilMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + reqGLCaps.setOnscreen(false); + reqGLCaps.setFBO(true); + reqGLCaps.setStencilBits(1); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); doTest(reqGLCaps, new GearsES2(1)); } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT.java index 37483f7e7..f4999c0fa 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT.java @@ -266,18 +266,67 @@ public class TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT extends UITestCase } @Test - public void testGL2OffScreenLayerAuto() throws InterruptedException { + public void testGL2OnScreenDblBufStencil() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setStencilBits(1); + doTest(false, reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OnScreenDblBufMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(false, reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OnScreenDblBufStencilMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setStencilBits(1); + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(false, reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenLayerAutoDblBuf() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; doTest(true, reqGLCaps, new GearsES2(1)); } @Test - public void testGL2OffScreenFBOMSAA() throws InterruptedException { + public void testGL2OffScreenFBODblBufStencil() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setFBO(true); + reqGLCaps.setOnscreen(true); // get native NEWT Window, not OffscreenWindow + reqGLCaps.setStencilBits(1); + doTest(true, reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBODblBufMSAA() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); + if(null == reqGLCaps) return; + reqGLCaps.setFBO(true); + reqGLCaps.setOnscreen(true); // get native NEWT Window, not OffscreenWindow + reqGLCaps.setSampleBuffers(true); + reqGLCaps.setNumSamples(4); + doTest(true, reqGLCaps, new GearsES2(1)); + } + + @Test + public void testGL2OffScreenFBODblBufStencilMSAA() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2); if(null == reqGLCaps) return; reqGLCaps.setFBO(true); reqGLCaps.setOnscreen(true); // get native NEWT Window, not OffscreenWindow + reqGLCaps.setStencilBits(1); reqGLCaps.setSampleBuffers(true); reqGLCaps.setNumSamples(4); doTest(true, reqGLCaps, new GearsES2(1)); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java index 07899b7d6..0a8063297 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java @@ -65,6 +65,7 @@ public class TestGearsES2AWT extends UITestCase { static boolean shallUseOffscreenLayer = false; static boolean shallUseOffscreenPBufferLayer = false; static boolean useMSAA = false; + static boolean useStencil = false; static boolean addComp = true; static boolean shutdownRemoveGLCanvas = true; static boolean shutdownDisposeFrame = true; @@ -159,6 +160,9 @@ public class TestGearsES2AWT extends UITestCase { caps.setNumSamples(4); caps.setSampleBuffers(true); } + if(useStencil) { + caps.setStencilBits(1); + } if(shallUseOffscreenLayer) { caps.setOnscreen(false); } @@ -192,6 +196,8 @@ public class TestGearsES2AWT extends UITestCase { shallUseOffscreenPBufferLayer = true; } else if(args[i].equals("-msaa")) { useMSAA = true; + } else if(args[i].equals("-stencil")) { + useStencil = true; } else if(args[i].equals("-wait")) { waitForKey = true; } else if(args[i].equals("-justGears")) { -- cgit v1.2.3 From 8cf694c1424277e6358039a964ecd75c54cf9af9 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Mon, 26 Nov 2012 18:15:59 +0100 Subject: SWTAccessor: OS_gtk_widget_unrealize optional (SWT 4.3) ; decorate PrivilegedAction for static initSingleton block (SWTAccessor, NewtFactory, NativeWindowFactory) --- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 18 +++++++++++++++--- .../javax/media/nativewindow/NativeWindowFactory.java | 19 ++++++++++++++----- src/newt/classes/com/jogamp/newt/NewtFactory.java | 13 +++++++++++-- 3 files changed, 40 insertions(+), 10 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index 7be747ff5..fca132f3f 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -30,6 +30,8 @@ package com.jogamp.nativewindow.swt; import com.jogamp.common.os.Platform; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedAction; import org.eclipse.swt.graphics.GCData; import org.eclipse.swt.widgets.Control; @@ -70,7 +72,7 @@ public class SWTAccessor { static final String str_OS_gtk_class = "org.eclipse.swt.internal.gtk.OS"; static final Class OS_gtk_class; static final Method OS_gtk_widget_realize; - static final Method OS_gtk_widget_unrealize; + static final Method OS_gtk_widget_unrealize; // optional (removed in SWT 4.3) static final Method OS_GTK_WIDGET_WINDOW; static final Method OS_gdk_x11_drawable_get_xdisplay; static final Method OS_gdk_x11_drawable_get_xid; @@ -83,6 +85,12 @@ public class SWTAccessor { static { Field f = null; + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + NativeWindowFactory.initSingleton(); // last resort .. + return null; + } } ); + final String nwt = NativeWindowFactory.getNativeWindowType(false); if(NativeWindowFactory.TYPE_MACOSX != nwt ) { @@ -127,14 +135,18 @@ public class SWTAccessor { Method m1=null, m2=null, m3=null, m4=null, m5=null; Class handleType = swt_uses_long_handles ? long.class : int.class ; if( NativeWindowFactory.TYPE_X11 == nwt ) { + // mandatory try { c = ReflectionUtil.getClass(str_OS_gtk_class, false, SWTAccessor.class.getClassLoader()); m1 = c.getDeclaredMethod(str_gtk_widget_realize, handleType); - m2 = c.getDeclaredMethod(str_gtk_widget_unrealize, handleType); m3 = c.getDeclaredMethod(str_GTK_WIDGET_WINDOW, handleType); m4 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xdisplay, handleType); m5 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xid, handleType); } catch (Exception ex) { throw new NativeWindowException(ex); } + // optional + try { + m2 = c.getDeclaredMethod(str_gtk_widget_unrealize, handleType); + } catch (Exception ex) { } } OS_gtk_class = c; OS_gtk_widget_realize = m1; @@ -197,7 +209,7 @@ public class SWTAccessor { public void run() { if(realize) { callStaticMethodL2V(OS_gtk_widget_realize, handle); - } else { + } else if(null != OS_gtk_widget_unrealize) { callStaticMethodL2V(OS_gtk_widget_unrealize, handle); } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 179610b25..d7f28a986 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -148,8 +148,18 @@ public abstract class NativeWindowFactory { } static { - Platform.initSingleton(); - DEBUG = Debug.debug("NativeWindow"); + final boolean[] _DEBUG = new boolean[] { false }; + final String[] _tmp = new String[] { null }; + + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + Platform.initSingleton(); // last resort .. + _DEBUG[0] = Debug.debug("NativeWindow"); + _tmp[0] = Debug.getProperty("nativewindow.ws.name", true); + return null; + } } ) ; + + DEBUG = _DEBUG[0]; if(DEBUG) { System.err.println(Thread.currentThread().getName()+" - Info: NativeWindowFactory."); // Thread.dumpStack(); @@ -157,11 +167,10 @@ public abstract class NativeWindowFactory { // Gather the windowing TK first nativeWindowingTypePure = _getNativeWindowingType(); - final String tmp = Debug.getProperty("nativewindow.ws.name", true); - if(null==tmp || tmp.length()==0) { + if(null==_tmp[0] || _tmp[0].length()==0) { nativeWindowingTypeCustom = nativeWindowingTypePure; } else { - nativeWindowingTypeCustom = tmp.intern(); // canonical representation + nativeWindowingTypeCustom = _tmp[0].intern(); // canonical representation } } diff --git a/src/newt/classes/com/jogamp/newt/NewtFactory.java b/src/newt/classes/com/jogamp/newt/NewtFactory.java index 1bf47f4aa..b3e904310 100644 --- a/src/newt/classes/com/jogamp/newt/NewtFactory.java +++ b/src/newt/classes/com/jogamp/newt/NewtFactory.java @@ -34,6 +34,9 @@ package com.jogamp.newt; +import java.security.AccessController; +import java.security.PrivilegedAction; + import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; @@ -41,6 +44,8 @@ import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowFactory; +import com.jogamp.common.os.Platform; + import jogamp.newt.Debug; import jogamp.newt.DisplayImpl; import jogamp.newt.ScreenImpl; @@ -54,8 +59,12 @@ public class NewtFactory { // Work-around for initialization order problems on Mac OS X // between native Newt and (apparently) Fmod static { - NativeWindowFactory.initSingleton(); // last resort .. - WindowImpl.init(NativeWindowFactory.getNativeWindowType(true)); + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + NativeWindowFactory.initSingleton(); // last resort .. + WindowImpl.init(NativeWindowFactory.getNativeWindowType(true)); + return null; + } } ); } public static Class getCustomClass(String packageName, String classBaseName) { -- cgit v1.2.3 From 337ae7842fc9a78196dab9a21eb052b3f4dfc5cd Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 27 Nov 2012 19:03:57 +0100 Subject: X11Util/Xmisc setX11ErrorHandler: Force setting X11 error handler if invoked from Java ensuring to overwrite other TKs handler SWT sets it's error handler, which exits application in case of an X11 error (e.g. n/a GL3 impl.). We need to allow overwriting it, hence allowing multiple calls (NEWT, GLContext). This patch also makes native NativewindowCommon_x11ErrorHandlerEnable(..) function static. --- src/nativewindow/native/x11/Xmisc.c | 46 ++++++++++++++++++++----------------- src/nativewindow/native/x11/Xmisc.h | 2 -- 2 files changed, 25 insertions(+), 23 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 129baac62..c73952693 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -220,12 +220,16 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) return 0; } -void NativewindowCommon_x11ErrorHandlerEnable(JNIEnv * env, Display *dpy, int onoff, int quiet, int sync) { +static void NativewindowCommon_x11ErrorHandlerEnable(JNIEnv * env, Display *dpy, int force, int onoff, int quiet, int sync) { errorHandlerQuiet = quiet; if(onoff) { - if(NULL==origErrorHandler) { + if(force || NULL==origErrorHandler) { + XErrorHandler prevErrorHandler; setupJVMVars(env); - origErrorHandler = XSetErrorHandler(x11ErrorHandler); + prevErrorHandler = XSetErrorHandler(x11ErrorHandler); + if(x11ErrorHandler != prevErrorHandler) { // if forced don't overwrite w/ orig w/ our handler + origErrorHandler = prevErrorHandler; + } if(sync && NULL!=dpy) { XSync(dpy, False); } @@ -292,7 +296,7 @@ Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass clazz, jboo _initClazzAccess(env); x11IOErrorHandlerEnable(1, env); - NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, 0, 0 /* no dpy, no sync */); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, 1, 0, 0 /* no dpy, force, no sync */); _initialized=1; if(JNI_TRUE == debug) { fprintf(stderr, "Info: NativeWindow native init passed\n"); @@ -303,13 +307,13 @@ Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass clazz, jboo JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Util_shutdown0(JNIEnv *env, jclass _unused) { - NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, 0 /* no dpy, no sync */); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, 0, 0 /* no dpy, no sync */); x11IOErrorHandlerEnable(0, env); } JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Util_setX11ErrorHandler0(JNIEnv *env, jclass _unused, jboolean onoff, jboolean quiet) { - NativewindowCommon_x11ErrorHandlerEnable(env, NULL, onoff ? 1 : 0, quiet ? 1 : 0, 0 /* no dpy, no sync */); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, onoff ? 1 : 0, quiet ? 1 : 0, 0 /* no dpy, force, no sync */); } /* Java->C glue code: @@ -334,9 +338,9 @@ Java_jogamp_nativewindow_x11_X11Lib_XGetVisualInfo1__JJLjava_nio_ByteBuffer_2Lja if (arg3 != NULL) { _ptr3 = (int *) (((char*) (*env)->GetPrimitiveArrayCritical(env, arg3, NULL)) + arg3_byte_offset); } - NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 1, 0, 0); _res = XGetVisualInfo((Display *) (intptr_t) arg0, (long) arg1, (XVisualInfo *) _ptr2, (int *) _ptr3); - // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 0, 0, 0); count = _ptr3[0]; if (arg3 != NULL) { (*env)->ReleasePrimitiveArrayCritical(env, arg3, _ptr3, 0); @@ -363,7 +367,7 @@ Java_jogamp_nativewindow_x11_X11Lib_GetVisualIDFromWindow(JNIEnv *env, jclass _u return; } - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 1, 0, 1); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, 0, 1); memset(&xwa, 0, sizeof(XWindowAttributes)); XGetWindowAttributes(dpy, w, &xwa); if(NULL != xwa.visual) { @@ -371,7 +375,7 @@ Java_jogamp_nativewindow_x11_X11Lib_GetVisualIDFromWindow(JNIEnv *env, jclass _u } else { r = 0; } - // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 1); return r; } @@ -383,9 +387,9 @@ Java_jogamp_nativewindow_x11_X11Lib_DefaultVisualID(JNIEnv *env, jclass _unused, if(0==display) { NativewindowCommon_FatalError(env, "invalid display connection.."); } - NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 1, 0, 0); r = (jint) XVisualIDFromVisual( DefaultVisual( (Display*) (intptr_t) display, screen ) ); - // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 0, 0, 0); return r; } @@ -426,9 +430,9 @@ Java_jogamp_nativewindow_x11_X11Lib_XCloseDisplay__J(JNIEnv *env, jclass _unused if(0==display) { NativewindowCommon_FatalError(env, "invalid display connection.."); } - NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 1, 0, 0); _res = XCloseDisplay((Display *) (intptr_t) display); - // NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, 0, 0); return _res; } @@ -466,7 +470,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow return 0; } - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, 0, 0); scrn = ScreenOfDisplay(dpy, scrn_idx); @@ -486,7 +490,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow if (visual==NULL) { - // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 1); NativewindowCommon_throwNewRuntimeException(env, "could not query Visual by given VisualID, bail out!"); return 0; } @@ -530,7 +534,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow XSelectInput(dpy, window, 0); // no events - // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 1); DBG_PRINT( "X11: [CreateWindow] created window %p on display %p\n", window, dpy); @@ -554,11 +558,11 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_DestroyDummyWindow return; } - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, 0, 0); XUnmapWindow(dpy, w); XSync(dpy, False); XDestroyWindow(dpy, w); - // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 1); } /* @@ -582,11 +586,11 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_x11_X11Lib_GetRelativeLocatio if( 0 == jdest_win ) { dest_win = root; } if( 0 == jsrc_win ) { src_win = root; } - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, 0, 0); res = XTranslateCoordinates(dpy, src_win, dest_win, src_x, src_y, &dest_x, &dest_y, &child); - // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 0); DBG_PRINT( "X11: GetRelativeLocation0: %p %d/%d -> %p %d/%d - ok: %d\n", (void*)src_win, src_x, src_y, (void*)dest_win, dest_x, dest_y, (int)res); diff --git a/src/nativewindow/native/x11/Xmisc.h b/src/nativewindow/native/x11/Xmisc.h index a44da950d..91f2ac5d9 100644 --- a/src/nativewindow/native/x11/Xmisc.h +++ b/src/nativewindow/native/x11/Xmisc.h @@ -39,6 +39,4 @@ #include #include -void NativewindowCommon_x11ErrorHandlerEnable(JNIEnv * env, Display *dpy, int onoff, int quiet, int sync); - #endif /* Xmisc_h */ -- cgit v1.2.3 From 6497cfa578b3ea5222678de930bb335e30794c7b Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 29 Nov 2012 00:01:20 +0100 Subject: SWTAccessor: Add SWT 4.3's X11-GTK version adaption (2.14, 2.24, 3.0) --- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 216 ++++++++++++++++----- 1 file changed, 170 insertions(+), 46 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index fca132f3f..e208cfb28 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -44,6 +44,7 @@ import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.VisualIDHolder; import com.jogamp.common.util.ReflectionUtil; +import com.jogamp.common.util.VersionNumber; import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsDevice; @@ -53,34 +54,58 @@ import jogamp.nativewindow.macosx.OSXUtil; import jogamp.nativewindow.x11.X11Lib; public class SWTAccessor { - static final Field swt_control_handle; - static final boolean swt_uses_long_handles; + private static final boolean DEBUG = true; + + private static final Field swt_control_handle; + private static final boolean swt_uses_long_handles; // X11/GTK, Windows/GDI, .. - static final String str_handle = "handle"; + private static final String str_handle = "handle"; // OSX/Cocoa - static final String str_view = "view"; // OSX - static final String str_id = "id"; // OSX + private static final String str_view = "view"; // OSX + private static final String str_id = "id"; // OSX // static final String str_NSView = "org.eclipse.swt.internal.cocoa.NSView"; - static final Method swt_control_internal_new_GC; - static final Method swt_control_internal_dispose_GC; - static final String str_internal_new_GC = "internal_new_GC"; - static final String str_internal_dispose_GC = "internal_dispose_GC"; + private static final Method swt_control_internal_new_GC; + private static final Method swt_control_internal_dispose_GC; + private static final String str_internal_new_GC = "internal_new_GC"; + private static final String str_internal_dispose_GC = "internal_dispose_GC"; - static final String str_OS_gtk_class = "org.eclipse.swt.internal.gtk.OS"; - static final Class OS_gtk_class; - static final Method OS_gtk_widget_realize; - static final Method OS_gtk_widget_unrealize; // optional (removed in SWT 4.3) - static final Method OS_GTK_WIDGET_WINDOW; - static final Method OS_gdk_x11_drawable_get_xdisplay; - static final Method OS_gdk_x11_drawable_get_xid; - static final String str_gtk_widget_realize = "gtk_widget_realize"; - static final String str_gtk_widget_unrealize = "gtk_widget_unrealize"; - static final String str_GTK_WIDGET_WINDOW = "GTK_WIDGET_WINDOW"; - static final String str_gdk_x11_drawable_get_xdisplay = "gdk_x11_drawable_get_xdisplay"; - static final String str_gdk_x11_drawable_get_xid = "gdk_x11_drawable_get_xid"; + private static final String str_OS_gtk_class = "org.eclipse.swt.internal.gtk.OS"; + private static final Class OS_gtk_class; + private static final String str_OS_gtk_version = "GTK_VERSION"; + private static final VersionNumber OS_gtk_version; + private static final Method OS_gtk_widget_realize; + private static final Method OS_gtk_widget_unrealize; // optional (removed in SWT 4.3) + private static final Method OS_GTK_WIDGET_WINDOW; + private static final Method OS_gtk_widget_get_window; + private static final Method OS_gdk_x11_drawable_get_xdisplay; + private static final Method OS_gdk_x11_display_get_xdisplay; + private static final Method OS_gdk_window_get_display; + private static final Method OS_gdk_x11_drawable_get_xid; + private static final Method OS_gdk_x11_window_get_xid; + private static final String str_gtk_widget_realize = "gtk_widget_realize"; + private static final String str_gtk_widget_unrealize = "gtk_widget_unrealize"; + private static final String str_GTK_WIDGET_WINDOW = "GTK_WIDGET_WINDOW"; + private static final String str_gtk_widget_get_window = "gtk_widget_get_window"; + private static final String str_gdk_x11_drawable_get_xdisplay = "gdk_x11_drawable_get_xdisplay"; + private static final String str_gdk_x11_display_get_xdisplay = "gdk_x11_display_get_xdisplay"; + private static final String str_gdk_window_get_display = "gdk_window_get_display"; + private static final String str_gdk_x11_drawable_get_xid = "gdk_x11_drawable_get_xid"; + private static final String str_gdk_x11_window_get_xid = "gdk_x11_window_get_xid"; + + private static final VersionNumber GTK_VERSION_2_14_0 = new VersionNumber(2, 14, 0); + private static final VersionNumber GTK_VERSION_2_24_0 = new VersionNumber(2, 24, 0); + private static final VersionNumber GTK_VERSION_3_0_0 = new VersionNumber(3, 0, 0); + + private static VersionNumber GTK_VERSION(int version) { + // return (major << 16) + (minor << 8) + micro; + final int micro = ( version ) & 0x0f; + final int minor = ( version >> 8 ) & 0x0f; + final int major = ( version >> 16 ) & 0x0f; + return new VersionNumber(major, minor, micro); + } static { Field f = null; @@ -131,17 +156,33 @@ public class SWTAccessor { } swt_control_internal_dispose_GC = m; - Class c=null; - Method m1=null, m2=null, m3=null, m4=null, m5=null; + Class c=null; + VersionNumber _gtk_version = new VersionNumber(0, 0, 0); + Method m1=null, m2=null, m3=null, m4=null, m5=null, m6=null, m7=null, m8=null, m9=null; Class handleType = swt_uses_long_handles ? long.class : int.class ; if( NativeWindowFactory.TYPE_X11 == nwt ) { // mandatory try { c = ReflectionUtil.getClass(str_OS_gtk_class, false, SWTAccessor.class.getClassLoader()); + Field field_OS_gtk_version = c.getField(str_OS_gtk_version); + _gtk_version = GTK_VERSION(field_OS_gtk_version.getInt(null)); m1 = c.getDeclaredMethod(str_gtk_widget_realize, handleType); - m3 = c.getDeclaredMethod(str_GTK_WIDGET_WINDOW, handleType); - m4 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xdisplay, handleType); - m5 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xid, handleType); + if( _gtk_version.compareTo(GTK_VERSION_2_14_0) < 0 ) { + m3 = c.getDeclaredMethod(str_GTK_WIDGET_WINDOW, handleType); + } else { + m4 = c.getDeclaredMethod(str_gtk_widget_get_window, handleType); + } + if( _gtk_version.compareTo(GTK_VERSION_2_24_0) < 0 ) { + m5 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xdisplay, handleType); + } else { + m6 = c.getDeclaredMethod(str_gdk_x11_display_get_xdisplay, handleType); + m7 = c.getDeclaredMethod(str_gdk_window_get_display, handleType); + } + if( _gtk_version.compareTo(GTK_VERSION_3_0_0) < 0 ) { + m8 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xid, handleType); + } else { + m9 = c.getDeclaredMethod(str_gdk_x11_window_get_xid, handleType); + } } catch (Exception ex) { throw new NativeWindowException(ex); } // optional try { @@ -149,13 +190,23 @@ public class SWTAccessor { } catch (Exception ex) { } } OS_gtk_class = c; + OS_gtk_version = _gtk_version; OS_gtk_widget_realize = m1; OS_gtk_widget_unrealize = m2; OS_GTK_WIDGET_WINDOW = m3; - OS_gdk_x11_drawable_get_xdisplay = m4; - OS_gdk_x11_drawable_get_xid = m5; + OS_gtk_widget_get_window = m4; + OS_gdk_x11_drawable_get_xdisplay = m5; + OS_gdk_x11_display_get_xdisplay = m6; + OS_gdk_window_get_display = m7; + OS_gdk_x11_drawable_get_xid = m8; + OS_gdk_x11_window_get_xid = m9; + + if(DEBUG) { + System.err.println("SWTAccessor.: GTK Version: "+OS_gtk_version); + } } - + + static Object getIntOrLong(long arg) { if(swt_uses_long_handles) { return new Long(arg); @@ -180,28 +231,43 @@ public class SWTAccessor { return swt_uses_long_handles; } - public static long getHandle(Control swtControl) { + public static VersionNumber GTK_VERSION() { return OS_gtk_version; } + + /** + * @param swtControl the SWT Control to retrieve the native widget-handle from + * @return the native widget-handle + * @throws NativeWindowException if the widget handle is null + */ + public static long getHandle(Control swtControl) throws NativeWindowException { long h = 0; if(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false) ) { try { Field fView = Control.class.getField(str_view); Object view = fView.get(swtControl); Field fId = view.getClass().getField(str_id); - return fId.getLong(view); + h = fId.getLong(view); } catch (Exception ex) { throw new NativeWindowException(ex); } + } else { + try { + h = swt_control_handle.getLong(swtControl); + } catch (Exception ex) { + throw new NativeWindowException(ex); + } } - - try { - h = swt_control_handle.getLong(swtControl); - } catch (Exception ex) { - throw new NativeWindowException(ex); + if(0 == h) { + throw new NativeWindowException("Null widget-handle of SWT "+swtControl.getClass().getName()+": "+swtControl.toString()); } return h; } - public static void setRealized(final Control swtControl, final boolean realize) { + public static void setRealized(final Control swtControl, final boolean realize) + throws NativeWindowException + { + if(!realize && swtControl.isDisposed()) { + return; + } final long handle = getHandle(swtControl); if(null != OS_gtk_class) { @@ -216,13 +282,64 @@ public class SWTAccessor { }); } } + + private static long gdk_x11_display_get_xdisplay(long window) { + final long xdisplay; + if ( OS_gtk_version.compareTo(GTK_VERSION_2_24_0) >= 0 ) { + final long display = callStaticMethodL2L(OS_gdk_window_get_display, window); + if(0 == display) { + throw new NativeWindowException("Null display-handle of gtk-window-handle 0x"+Long.toHexString(window)); + } + xdisplay = callStaticMethodL2L(OS_gdk_x11_display_get_xdisplay, display); + } else { + xdisplay = callStaticMethodL2L(OS_gdk_x11_drawable_get_xdisplay, window); + } + if(0 == xdisplay) { + throw new NativeWindowException("Null x11-display-handle of gtk-window-handle 0x"+Long.toHexString(window)); + } + return xdisplay; + } - public static AbstractGraphicsDevice getDevice(Control swtControl) { + private static long gdk_widget_get_window(long handle) { + final long window; + if ( OS_gtk_version.compareTo(GTK_VERSION_2_14_0) >= 0 ) { + window = callStaticMethodL2L(OS_gtk_widget_get_window, handle); + } else { + window = callStaticMethodL2L(OS_GTK_WIDGET_WINDOW, handle); + } + if(0 == window) { + throw new NativeWindowException("Null gtk-window-handle of SWT handle 0x"+Long.toHexString(handle)); + } + return window; + } + + private static long gdk_window_get_xwindow(long window) { + final long xwindow; + if ( OS_gtk_version.compareTo(GTK_VERSION_3_0_0) >= 0 ) { + xwindow = callStaticMethodL2L(OS_gdk_x11_window_get_xid, window); + } else { + xwindow = callStaticMethodL2L(OS_gdk_x11_drawable_get_xid, window); + } + if(0 == xwindow) { + throw new NativeWindowException("Null x11-window-handle of gtk-window-handle 0x"+Long.toHexString(window)); + } + return xwindow; + } + + /** + * @param swtControl the SWT Control to retrieve the native device handle from + * @return the AbstractGraphicsDevice w/ the native device handle + * @throws NativeWindowException if the widget handle is null + * @throws UnsupportedOperationException if the windowing system is not supported + */ + public static AbstractGraphicsDevice getDevice(Control swtControl) throws NativeWindowException, UnsupportedOperationException { long handle = getHandle(swtControl); if( null != OS_gtk_class ) { - long widgedHandle = callStaticMethodL2L(OS_GTK_WIDGET_WINDOW, handle); - long displayHandle = callStaticMethodL2L(OS_gdk_x11_drawable_get_xdisplay, widgedHandle); - return new X11GraphicsDevice(displayHandle, AbstractGraphicsDevice.DEFAULT_UNIT, false /* owner */); + final long xdisplay0 = gdk_x11_display_get_xdisplay( gdk_widget_get_window( handle ) ); + // final String displayName = X11Lib.XDisplayString(xdisplay0); + // final long xdisplay1 = X11Util.openDisplay(displayName); + // return new X11GraphicsDevice(xdisplay1, AbstractGraphicsDevice.DEFAULT_UNIT, true /* owner */); + return new X11GraphicsDevice(xdisplay0, AbstractGraphicsDevice.DEFAULT_UNIT, false /* owner */); } final String nwt = NativeWindowFactory.getNativeWindowType(false); if( NativeWindowFactory.TYPE_WINDOWS == nwt ) { @@ -233,7 +350,8 @@ public class SWTAccessor { } throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } - public static AbstractGraphicsScreen getScreen(AbstractGraphicsDevice device, int screen) { + + public static AbstractGraphicsScreen getScreen(AbstractGraphicsDevice device, int screen) throws UnsupportedOperationException { if( null != OS_gtk_class ) { return new X11GraphicsScreen((X11GraphicsDevice)device, screen); } @@ -244,6 +362,7 @@ public class SWTAccessor { } throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } + public static int getNativeVisualID(AbstractGraphicsDevice device, long windowHandle) { if( null != OS_gtk_class ) { return X11Lib.GetVisualIDFromWindow(device.getHandle(), windowHandle); @@ -256,11 +375,16 @@ public class SWTAccessor { throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } - public static long getWindowHandle(Control swtControl) { - long handle = getHandle(swtControl); + /** + * @param swtControl the SWT Control to retrieve the native window handle from + * @return the native window handle + * @throws NativeWindowException if the widget handle is null + * @throws UnsupportedOperationException if the windowing system is not supported + */ + public static long getWindowHandle(Control swtControl) throws NativeWindowException, UnsupportedOperationException { + final long handle = getHandle(swtControl); if( null != OS_gtk_class ) { - long widgedHandle = callStaticMethodL2L(OS_GTK_WIDGET_WINDOW, handle); - return callStaticMethodL2L(OS_gdk_x11_drawable_get_xid, widgedHandle); + return gdk_window_get_xwindow( gdk_widget_get_window( handle ) ); } final String nwt = NativeWindowFactory.getNativeWindowType(false); if( NativeWindowFactory.TYPE_WINDOWS == nwt || -- cgit v1.2.3 From 7cb6cf2a9708d3f4e06f2215eb0d06b00fa6cd15 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 4 Dec 2012 07:10:59 +0100 Subject: SWT GLCanvas: Fix sporadic drop of redraw on X11 _and_ allow using custom GLCapabilities on X11 (feature complete) To allow custom GLCapabilities, we had to use native parenting on X11 w/ a new child window. The desired visualID chosen by the users GLCapabilities is passed to the new child window. The redraw drops must be caused by the original GDK or the new child GDK window. Now we use a plain X11 child window similar to NEWT's X11 window and NewtCanvasSWT, which doesn't expose this bug. (Note: SWTAccessor/GLCanvas still contains the uncommented GDK code path for further inspection, if desired) Also added SWTNewtEventFactory to test event handling on the SWT GLCanvas w/ GearsES2. TestSWTJOGLGLCanvas01GLn tests custom GLCapabilities now. SWTEDTUtil has been moved to private: com.jogamp.newt.swt -> jogamp.newt.swt. --- make/build-common.xml | 1 + make/build-newt.xml | 2 +- make/config/nativewindow/x11-CustomJavaCode.java | 5 +- make/scripts/tests-x32.sh | 2 + make/scripts/tests-x64.bat | 4 +- make/scripts/tests.sh | 6 +- .../classes/com/jogamp/opengl/swt/GLCanvas.java | 350 ++++++++++++++------- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 345 +++++++++++++------- .../x11/X11DummyUpstreamSurfaceHook.java | 4 +- src/nativewindow/native/x11/Xmisc.c | 123 +++++++- .../classes/com/jogamp/newt/swt/NewtCanvasSWT.java | 82 +++-- .../classes/com/jogamp/newt/swt/SWTEDTUtil.java | 313 ------------------ src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java | 313 ++++++++++++++++++ .../jogamp/newt/swt/event/SWTNewtEventFactory.java | 249 +++++++++++++++ .../opengl/test/junit/jogl/demos/es2/GearsES2.java | 8 +- .../swt/TestNewtCanvasSWTBug628ResizeDeadlock.java | 5 +- .../junit/jogl/swt/TestSWTBug643AsyncExec.java | 26 +- .../junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java | 16 +- 18 files changed, 1236 insertions(+), 618 deletions(-) delete mode 100644 src/newt/classes/com/jogamp/newt/swt/SWTEDTUtil.java create mode 100644 src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java create mode 100644 src/newt/classes/jogamp/newt/swt/event/SWTNewtEventFactory.java (limited to 'src/nativewindow') diff --git a/make/build-common.xml b/make/build-common.xml index a718ae09a..414b0eba2 100644 --- a/make/build-common.xml +++ b/make/build-common.xml @@ -428,6 +428,7 @@ + diff --git a/make/build-newt.xml b/make/build-newt.xml index 7b9a51863..c3b51141f 100644 --- a/make/build-newt.xml +++ b/make/build-newt.xml @@ -112,7 +112,7 @@ value="com/jogamp/newt/awt/** com/jogamp/newt/event/awt/** jogamp/newt/awt/** ${java.part.driver.awt}"/> + value="com/jogamp/newt/swt/** jogamp/newt/swt/**"/> diff --git a/make/config/nativewindow/x11-CustomJavaCode.java b/make/config/nativewindow/x11-CustomJavaCode.java index 8e5da3b2d..4240c5e2f 100644 --- a/make/config/nativewindow/x11-CustomJavaCode.java +++ b/make/config/nativewindow/x11-CustomJavaCode.java @@ -28,8 +28,9 @@ public static native int DefaultVisualID(long display, int screen); - public static native long CreateDummyWindow(long display, int screen_index, int visualID, int width, int height); - public static native void DestroyDummyWindow(long display, long window); + public static native long CreateWindow(long parent, long display, int screen_index, int visualID, int width, int height, boolean input, boolean visible); + public static native void DestroyWindow(long display, long window); + public static native void SetWindowPosSize(long display, long window, int x, int y, int width, int height); public static Point GetRelativeLocation(long display, int screen_index, long src_win, long dest_win, int src_x, int src_y) { return (Point) GetRelativeLocation0(display, screen_index, src_win, dest_win, src_x, src_y); diff --git a/make/scripts/tests-x32.sh b/make/scripts/tests-x32.sh index a3aed84c3..858ed5fd8 100755 --- a/make/scripts/tests-x32.sh +++ b/make/scripts/tests-x32.sh @@ -6,6 +6,8 @@ if [ -e $SDIR/../../../gluegen/make/scripts/setenv-build-jogl-x86.sh ] ; then . $SDIR/../../../gluegen/make/scripts/setenv-build-jogl-x86.sh fi +export SWT_CLASSPATH=`pwd`/lib/swt/gtk-linux-x86/swt-debug.jar + . $SDIR/tests.sh `which java` -d32 ../build-x86 $* diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat index 7a2946d31..db7e27264 100755 --- a/make/scripts/tests-x64.bat +++ b/make/scripts/tests-x64.bat @@ -54,10 +54,10 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestP REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor03AWTGLn %* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn %* +scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTGLn %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTBug628ResizeDeadlock %* -scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTBug643AsyncExec %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTBug643AsyncExec %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestWindows01NEWT REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 0669efb37..628ab706b 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -113,7 +113,7 @@ function jrun() { #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile" #D_ARGS="-Djogl.debug.GLProfile" #D_ARGS="-Dnativewindow.debug.NativeWindow" - #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT" + D_ARGS="-Djogl.debug.GLCanvas -Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT -Djogl.debug.Animator" #D_ARGS="-Dnewt.debug.EDT -Dnewt.debug.Window -Djogl.debug.GLContext" #D_ARGS="-Dnativewindow.debug.X11Util.XErrorStackDump -Dnativewindow.debug.X11Util.TraceDisplayLifecycle -Dnativewindow.debug.X11Util" #D_ARGS="-Dnativewindow.debug.X11Util -Djogl.debug.GLContext -Djogl.debug.GLDrawable -Dnewt.debug=all" @@ -370,10 +370,10 @@ function testawtswt() { # #testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTEclipseGLCanvas01GLn $* #testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor03AWTGLn $* -#testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* +testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* #testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTGLn $* #testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTBug628ResizeDeadlock $* -testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTBug643AsyncExec $* +#testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTBug643AsyncExec $* # # newt.awt (testawt) diff --git a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java index a080a7045..0320c63ae 100644 --- a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java +++ b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java @@ -29,10 +29,16 @@ package com.jogamp.opengl.swt; import java.util.List; +import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.NativeSurface; +import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.ProxySurface; import javax.media.nativewindow.UpstreamSurfaceHook; +import javax.media.nativewindow.VisualIDHolder; +import javax.media.nativewindow.VisualIDHolder.VIDType; import javax.media.opengl.GL; import javax.media.opengl.GLAnimatorControl; import javax.media.opengl.GLAutoDrawable; @@ -48,23 +54,20 @@ import javax.media.opengl.GLProfile; import javax.media.opengl.GLRunnable; import javax.media.opengl.Threading; +import jogamp.nativewindow.x11.X11Util; import jogamp.opengl.Debug; import jogamp.opengl.GLContextImpl; import jogamp.opengl.GLDrawableHelper; import jogamp.opengl.GLDrawableImpl; import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ControlEvent; -import org.eclipse.swt.events.ControlListener; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import com.jogamp.common.GlueGenVersion; @@ -73,13 +76,14 @@ import com.jogamp.common.util.VersionUtil; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.nativewindow.swt.SWTAccessor; +import com.jogamp.nativewindow.x11.X11GraphicsDevice; import com.jogamp.opengl.JoglVersion; /** * Native SWT Canvas implementing GLAutoDrawable - * - *

      Note: To employ custom GLCapabilities, NewtCanvasSWT shall be used instead.

      - * + *

      + * Implementation allows use of custom {@link GLCapabilities}. + *

      */ public class GLCanvas extends Canvas implements GLAutoDrawable { private static final boolean DEBUG = Debug.debug("GLCanvas"); @@ -103,11 +107,15 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { private final GLCapabilitiesImmutable capsRequested; private final GLCapabilitiesChooser capsChooser; + private volatile Rectangle clientArea; private volatile GLDrawableImpl drawable; // volatile: avoid locking for read-only access - private GLContextImpl context; + private volatile GLContextImpl context; /* Native window surface */ - private AbstractGraphicsDevice device; + private final boolean useX11GTK; + private volatile long gdkWindow; // either GDK child window .. + private volatile long x11Window; // .. or X11 child window (for GL rendering) + private final AbstractGraphicsScreen screen; /* Construction parameters stored for GLAutoDrawable accessor methods */ private int additionalCtxCreationFlags = 0; @@ -135,7 +143,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { @Override public void run() { if (sendReshape) { - helper.reshape(GLCanvas.this, 0, 0, getWidth(), getHeight()); + helper.reshape(GLCanvas.this, 0, 0, clientArea.width, clientArea.height); sendReshape = false; } helper.display(GLCanvas.this); @@ -143,7 +151,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { }; /* Action to make specified context current prior to running displayAction */ - private final Runnable makeCurrentAndDisplayOnEDTAction = new Runnable() { + private final Runnable makeCurrentAndDisplayOnGLAction = new Runnable() { @Override public void run() { final RecursiveLock _lock = lock; @@ -159,13 +167,14 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { }; /* Swaps buffers, assuming the GLContext is current */ - private final Runnable swapBuffersOnEDTAction = new Runnable() { + private final Runnable swapBuffersOnGLAction = new Runnable() { @Override public void run() { final RecursiveLock _lock = lock; _lock.lock(); try { - if(null != drawable && !GLCanvas.this.isDisposed() ) { + final boolean drawableOK = null != drawable && drawable.isRealized(); + if( drawableOK && !GLCanvas.this.isDisposed() ) { drawable.swapBuffers(); } } finally { @@ -212,10 +221,14 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { drawable.setRealized(false); drawable = null; } - if (null != device) { - device.close(); - device = null; + if( 0 != x11Window) { + SWTAccessor.destroyX11Window(screen.getDevice(), x11Window); + x11Window = 0; + } else if( 0 != gdkWindow) { + SWTAccessor.destroyGDKWindow(gdkWindow); + gdkWindow = 0; } + screen.getDevice().close(); if (animatorPaused) { animator.resume(); @@ -249,11 +262,6 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { } }; - /** - * Storage for the client area rectangle so that it may be accessed from outside of the SWT thread. - */ - private volatile Rectangle clientArea; - /** * Creates an instance using {@link #GLCanvas(Composite, int, GLCapabilitiesImmutable, GLCapabilitiesChooser, GLContext)} * on the SWT thread. @@ -293,72 +301,80 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { * @param style * Optional SWT style bit-field. The {@link SWT#NO_BACKGROUND} bit is set before passing this up to the * Canvas constructor, so OpenGL handles the background. - * @param caps + * @param capsReqUser * Optional GLCapabilities. If not provided, the default capabilities for the default GLProfile for the * graphics device determined by the parent Composite are used. Note that the GLCapabilities that are * actually used may differ based on the capabilities of the graphics device. - * @param chooser + * @param capsChooser * Optional GLCapabilitiesChooser to customize the selection of the used GLCapabilities based on the * requested GLCapabilities, and the available capabilities of the graphics device. * @param shareWith * Optional GLContext to share state (textures, vbos, shaders, etc.) with. */ - public GLCanvas(final Composite parent, final int style, GLCapabilitiesImmutable caps, - final GLCapabilitiesChooser chooser, final GLContext shareWith) { + public GLCanvas(final Composite parent, final int style, GLCapabilitiesImmutable capsReqUser, + final GLCapabilitiesChooser capsChooser, final GLContext shareWith) { /* NO_BACKGROUND required to avoid clearing bg in native SWT widget (we do this in the GL display) */ super(parent, style | SWT.NO_BACKGROUND); GLProfile.initSingleton(); // ensure JOGL is completly initialized SWTAccessor.setRealized(this, true); - + clientArea = GLCanvas.this.getClientArea(); /* Get the nativewindow-Graphics Device associated with this control (which is determined by the parent Composite). * Note: SWT is owner of the native handle, hence closing operation will be a NOP. */ - device = SWTAccessor.getDevice(this); + final AbstractGraphicsDevice swtDevice = SWTAccessor.getDevice(this); + + useX11GTK = SWTAccessor.useX11GTK(); + if(useX11GTK) { + // Decoupled X11 Device/Screen allowing X11 display lock-free off-thread rendering + final long x11DeviceHandle = X11Util.openDisplay(swtDevice.getConnection()); + if( 0 == x11DeviceHandle ) { + throw new RuntimeException("Error creating display(EDT): "+swtDevice.getConnection()); + } + final AbstractGraphicsDevice x11Device = new X11GraphicsDevice(x11DeviceHandle, AbstractGraphicsDevice.DEFAULT_UNIT, true /* owner */); + screen = SWTAccessor.getScreen(x11Device, -1 /* default */); + } else { + screen = SWTAccessor.getScreen(swtDevice, -1 /* default */); + } /* Select default GLCapabilities if none was provided, otherwise clone provided caps to ensure safety */ - if(null == caps) { - caps = new GLCapabilities(GLProfile.getDefault(device)); + if(null == capsReqUser) { + capsReqUser = new GLCapabilities(GLProfile.getDefault(screen.getDevice())); } - this.capsRequested = caps; - this.capsChooser = chooser; + + this.capsRequested = capsReqUser; + this.capsChooser = capsChooser; this.shareWith = shareWith; // post create .. when ready + gdkWindow = 0; + x11Window = 0; drawable = null; context = null; - /* Register SWT listeners (e.g. PaintListener) to render/resize GL surface. */ - /* TODO: verify that these do not need to be manually de-registered when destroying the SWT component */ - addPaintListener(new PaintListener() { - @Override - public void paintControl(final PaintEvent arg0) { - if ( !helper.isAnimatorAnimatingOnOtherThread() ) { - display(); // checks: null != drawable - } - } - }); - - addControlListener(new ControlListener() { - @Override - public void controlMoved(ControlEvent e) { - } - - @Override - public void controlResized(final ControlEvent arg0) { - updateSizeCheck(); - } - }); - - addDisposeListener(new DisposeListener() { - @Override - public void widgetDisposed(DisposeEvent e) { - GLCanvas.this.dispose(); - } - }); + final Listener listener = new Listener () { + @Override + public void handleEvent (Event event) { + switch (event.type) { + case SWT.Paint: + displayIfNoAnimatorNoCheck(); + break; + case SWT.Resize: + updateSizeCheck(); + break; + case SWT.Dispose: + GLCanvas.this.dispose(); + break; + } + } + }; + addListener (SWT.Resize, listener); + addListener (SWT.Paint, listener); + addListener (SWT.Dispose, listener); } + private final UpstreamSurfaceHook swtCanvasUpStreamHook = new UpstreamSurfaceHook() { @Override public final void create(ProxySurface s) { /* nop */ } @@ -390,11 +406,13 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { ) { clientArea = nClientArea; // write back new value - GLDrawableImpl _drawable = drawable; - if( null != _drawable ) { - if(DEBUG) { - System.err.println("GLCanvas.sizeChanged: ("+Thread.currentThread().getName()+"): "+nClientArea.width+"x"+nClientArea.height+" - surfaceHandle 0x"+Long.toHexString(getNativeSurface().getSurfaceHandle())); - } + final GLDrawableImpl _drawable = drawable; + final boolean drawableOK = null != _drawable && _drawable.isRealized(); + if(DEBUG) { + final long dh = drawableOK ? _drawable.getHandle() : 0; + System.err.println("GLCanvas.sizeChanged: ("+Thread.currentThread().getName()+"): "+nClientArea.x+"/"+nClientArea.y+" "+nClientArea.width+"x"+nClientArea.height+" - drawableHandle 0x"+Long.toHexString(dh)); + } + if( drawableOK ) { if( ! _drawable.getChosenGLCapabilities().isOnscreen() ) { final RecursiveLock _lock = lock; _lock.lock(); @@ -407,66 +425,154 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { } finally { _lock.unlock(); } - } - sendReshape = true; // async if display() doesn't get called below, but avoiding deadlock - } + } + } + if(0 != x11Window) { + SWTAccessor.resizeX11Window(screen.getDevice(), clientArea, x11Window); + } else if(0 != gdkWindow) { + SWTAccessor.resizeGDKWindow(clientArea, gdkWindow); + } + sendReshape = true; // async if display() doesn't get called below, but avoiding deadlock } } - @Override - public void display() { - if( null != drawable || validateDrawableAndContext() ) { - runInGLThread(makeCurrentAndDisplayOnEDTAction); - } + private boolean isValidAndVisibleOnEDTActionResult; + private final Runnable isValidAndVisibleOnEDTAction = new Runnable() { + @Override + public void run() { + isValidAndVisibleOnEDTActionResult = !GLCanvas.this.isDisposed() && GLCanvas.this.isVisible(); + } }; + + private final boolean isValidAndVisibleOnEDT() { + synchronized(isValidAndVisibleOnEDTAction) { + runOnEDTIfAvail(true, isValidAndVisibleOnEDTAction); + return isValidAndVisibleOnEDTActionResult; + } } - - /** assumes drawable == null ! */ - protected final boolean validateDrawableAndContext() { - if( isDisposed() || !isVisible() ) { + /** assumes drawable == null || !drawable.isRealized() ! Checks of !isDispose() and isVisible() */ + protected final boolean validateDrawableAndContextWithCheck() { + if( !isValidAndVisibleOnEDT() ) { return false; } + return validateDrawableAndContextPostCheck(); + } + + /** assumes drawable == null || !drawable.isRealized() ! No check of !isDispose() and isVisible() */ + protected final boolean validateDrawableAndContextPostCheck() { final Rectangle nClientArea = clientArea; if(0 >= nClientArea.width || 0 >= nClientArea.height) { return false; } + final boolean res; final RecursiveLock _lock = lock; _lock.lock(); try { - final GLDrawableFactory glFactory = GLDrawableFactory.getFactory(capsRequested.getGLProfile()); - - /* Native handle for the control, used to associate with GLContext */ - final long nativeWindowHandle = SWTAccessor.getWindowHandle(this); - - /* Create a NativeWindow proxy for the SWT canvas */ - ProxySurface proxySurface = null; - try { - proxySurface = glFactory.createProxySurface(device, 0 /* screenIdx */, nativeWindowHandle, - capsRequested, capsChooser, swtCanvasUpStreamHook); - } catch (GLException gle) { - // not ready yet .. - if(DEBUG) { System.err.println(gle.getMessage()); } + if(null == drawable) { + createDrawableAndContext(); } - - if(null != proxySurface) { - /* Associate a GL surface with the proxy */ - drawable = (GLDrawableImpl) glFactory.createGLDrawable(proxySurface); + if(null != drawable) { drawable.setRealized(true); - - context = (GLContextImpl) drawable.createContext(shareWith); + res = drawable.isRealized(); + } else { + res = false; } } finally { _lock.unlock(); + } + + if(res) { + sendReshape = true; + if(DEBUG) { + System.err.println("SWT GLCanvas realized! "+this+", "+drawable); + // Thread.dumpStack(); + } } - final boolean res = null != drawable; - if(DEBUG && res) { - System.err.println("SWT GLCanvas realized! "+this+", "+drawable); - Thread.dumpStack(); - } - return res; + return res; + } + + private final void createDrawableAndContext() { + final AbstractGraphicsDevice device = screen.getDevice(); + device.open(); + + final long nativeWindowHandle; + if( useX11GTK ) { + final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(device, capsRequested); + final AbstractGraphicsConfiguration cfg = factory.chooseGraphicsConfiguration( + capsRequested, capsRequested, capsChooser, screen, VisualIDHolder.VID_UNDEFINED); + if(DEBUG) { + System.err.println("SWT.GLCanvas.X11 factory: "+factory+", chosen config: "+cfg); + } + if (null == cfg) { + throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); + } + final int visualID = cfg.getVisualID(VIDType.NATIVE); + if( VisualIDHolder.VID_UNDEFINED != visualID ) { + // gdkWindow = SWTAccessor.createCompatibleGDKChildWindow(this, visualID, clientArea.width, clientArea.height); + // nativeWindowHandle = SWTAccessor.gdk_window_get_xwindow(gdkWindow); + x11Window = SWTAccessor.createCompatibleX11ChildWindow(screen, this, visualID, clientArea.width, clientArea.height); + nativeWindowHandle = x11Window; + } else { + throw new GLException("Could not choose valid visualID: 0x"+Integer.toHexString(visualID)+", "+this); + } + } else { + nativeWindowHandle = SWTAccessor.getWindowHandle(this); + } + final GLDrawableFactory glFactory = GLDrawableFactory.getFactory(capsRequested.getGLProfile()); + + // Create a NativeWindow proxy for the SWT canvas + ProxySurface proxySurface = glFactory.createProxySurface(device, screen.getIndex(), nativeWindowHandle, + capsRequested, capsChooser, swtCanvasUpStreamHook); + // Associate a GL surface with the proxy + drawable = (GLDrawableImpl) glFactory.createGLDrawable(proxySurface); + context = (GLContextImpl) drawable.createContext(shareWith); + context.setContextCreationFlags(additionalCtxCreationFlags); + } + + @Override + public void update() { + // don't paint background etc .. nop avoids flickering + // super.update(); + } + + /** + @Override + public boolean forceFocus() { + final boolean r = super.forceFocus(); + if(r && 0 != gdkWindow) { + SWTGTKUtil.focusGDKWindow(gdkWindow); + } + return r; + } */ + + @Override + public void dispose() { + runInGLThread(disposeOnEDTGLAction); + super.dispose(); + } + + private final void displayIfNoAnimatorNoCheck() { + if ( !helper.isAnimatorAnimatingOnOtherThread() ) { + final boolean drawableOK = null != drawable && drawable.isRealized(); + if( drawableOK || validateDrawableAndContextPostCheck() ) { + runInGLThread(makeCurrentAndDisplayOnGLAction); + } + } } + // + // GL[Auto]Drawable + // + + @Override + public void display() { + final boolean drawableOK = null != drawable && drawable.isRealized(); + if( drawableOK || validateDrawableAndContextWithCheck() ) { + runInGLThread(makeCurrentAndDisplayOnGLAction); + } + } + @Override public final Object getUpstreamWidget() { return this; @@ -692,18 +798,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { @Override public void swapBuffers() throws GLException { - runInGLThread(swapBuffersOnEDTAction); - } - - @Override - public void update() { - // don't paint background etc .. nop avoids flickering - } - - @Override - public void dispose() { - runInGLThread(disposeOnEDTGLAction); - super.dispose(); + runInGLThread(swapBuffersOnGLAction); } /** @@ -746,7 +841,32 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { } */ action.run(); } + + private void runOnEDTIfAvail(boolean wait, final Runnable action) { + final Display d = isDisposed() ? null : getDisplay(); + if( null == d || d.isDisposed() || d.getThread() == Thread.currentThread() ) { + action.run(); + } else if(wait) { + d.syncExec(action); + } else { + d.asyncExec(action); + } + } + + @Override + public String toString() { + final GLDrawable _drawable = drawable; + final int dw = (null!=_drawable) ? _drawable.getWidth() : -1; + final int dh = (null!=_drawable) ? _drawable.getHeight() : -1; + return "SWT-GLCanvas[Realized "+isRealized()+ + ",\n\t"+((null!=_drawable)?_drawable.getClass().getName():"null-drawable")+ + ",\n\tFactory "+getFactory()+ + ",\n\thandle 0x"+Long.toHexString(getHandle())+ + ",\n\tDrawable size "+dw+"x"+dh+ + ",\n\tSWT size "+getWidth()+"x"+getHeight()+"]"; + } + public static void main(final String[] args) { System.err.println(VersionUtil.getPlatformInfo()); System.err.println(GlueGenVersion.getInstance()); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index e208cfb28..eba26c7d3 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -34,6 +34,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; import org.eclipse.swt.graphics.GCData; +import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import javax.media.nativewindow.AbstractGraphicsScreen; @@ -59,12 +60,22 @@ public class SWTAccessor { private static final Field swt_control_handle; private static final boolean swt_uses_long_handles; + private static Object swt_osx_init = new Object(); + private static Field swt_osx_control_view = null; + private static Field swt_osx_view_id = null; + + private static final String nwt; + private static final boolean isOSX; + private static final boolean isWindows; + private static final boolean isX11; + private static final boolean isX11GTK; + // X11/GTK, Windows/GDI, .. private static final String str_handle = "handle"; // OSX/Cocoa - private static final String str_view = "view"; // OSX - private static final String str_id = "id"; // OSX + private static final String str_osx_view = "view"; // OSX + private static final String str_osx_id = "id"; // OSX // static final String str_NSView = "org.eclipse.swt.internal.cocoa.NSView"; private static final Method swt_control_internal_new_GC; @@ -73,9 +84,10 @@ public class SWTAccessor { private static final String str_internal_dispose_GC = "internal_dispose_GC"; private static final String str_OS_gtk_class = "org.eclipse.swt.internal.gtk.OS"; - private static final Class OS_gtk_class; + public static final Class OS_gtk_class; private static final String str_OS_gtk_version = "GTK_VERSION"; - private static final VersionNumber OS_gtk_version; + public static final VersionNumber OS_gtk_version; + private static final Method OS_gtk_widget_realize; private static final Method OS_gtk_widget_unrealize; // optional (removed in SWT 4.3) private static final Method OS_GTK_WIDGET_WINDOW; @@ -85,6 +97,8 @@ public class SWTAccessor { private static final Method OS_gdk_window_get_display; private static final Method OS_gdk_x11_drawable_get_xid; private static final Method OS_gdk_x11_window_get_xid; + private static final Method OS_gdk_window_set_back_pixmap; + private static final String str_gtk_widget_realize = "gtk_widget_realize"; private static final String str_gtk_widget_unrealize = "gtk_widget_unrealize"; private static final String str_GTK_WIDGET_WINDOW = "GTK_WIDGET_WINDOW"; @@ -94,6 +108,7 @@ public class SWTAccessor { private static final String str_gdk_window_get_display = "gdk_window_get_display"; private static final String str_gdk_x11_drawable_get_xid = "gdk_x11_drawable_get_xid"; private static final String str_gdk_x11_window_get_xid = "gdk_x11_window_get_xid"; + private static final String str_gdk_window_set_back_pixmap = "gdk_window_set_back_pixmap"; private static final VersionNumber GTK_VERSION_2_14_0 = new VersionNumber(2, 14, 0); private static final VersionNumber GTK_VERSION_2_24_0 = new VersionNumber(2, 24, 0); @@ -108,23 +123,25 @@ public class SWTAccessor { } static { - Field f = null; - AccessController.doPrivileged(new PrivilegedAction() { public Object run() { NativeWindowFactory.initSingleton(); // last resort .. return null; } } ); - final String nwt = NativeWindowFactory.getNativeWindowType(false); - - if(NativeWindowFactory.TYPE_MACOSX != nwt ) { + nwt = NativeWindowFactory.getNativeWindowType(false); + isOSX = NativeWindowFactory.TYPE_MACOSX == nwt; + isWindows = NativeWindowFactory.TYPE_WINDOWS == nwt; + isX11 = NativeWindowFactory.TYPE_X11 == nwt; + + Field f = null; + if( !isOSX ) { try { f = Control.class.getField(str_handle); } catch (Exception ex) { throw new NativeWindowException(ex); } - } + } swt_control_handle = f; // maybe null ! boolean ulh; @@ -158,31 +175,32 @@ public class SWTAccessor { Class c=null; VersionNumber _gtk_version = new VersionNumber(0, 0, 0); - Method m1=null, m2=null, m3=null, m4=null, m5=null, m6=null, m7=null, m8=null, m9=null; - Class handleType = swt_uses_long_handles ? long.class : int.class ; - if( NativeWindowFactory.TYPE_X11 == nwt ) { + Method m1=null, m2=null, m3=null, m4=null, m5=null, m6=null, m7=null, m8=null, m9=null, ma=null; + final Class handleType = swt_uses_long_handles ? long.class : int.class ; + if( isX11 ) { // mandatory try { c = ReflectionUtil.getClass(str_OS_gtk_class, false, SWTAccessor.class.getClassLoader()); Field field_OS_gtk_version = c.getField(str_OS_gtk_version); _gtk_version = GTK_VERSION(field_OS_gtk_version.getInt(null)); m1 = c.getDeclaredMethod(str_gtk_widget_realize, handleType); - if( _gtk_version.compareTo(GTK_VERSION_2_14_0) < 0 ) { - m3 = c.getDeclaredMethod(str_GTK_WIDGET_WINDOW, handleType); - } else { + if (_gtk_version.compareTo(GTK_VERSION_2_14_0) >= 0) { m4 = c.getDeclaredMethod(str_gtk_widget_get_window, handleType); - } - if( _gtk_version.compareTo(GTK_VERSION_2_24_0) < 0 ) { - m5 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xdisplay, handleType); } else { + m3 = c.getDeclaredMethod(str_GTK_WIDGET_WINDOW, handleType); + } + if (_gtk_version.compareTo(GTK_VERSION_2_24_0) >= 0) { m6 = c.getDeclaredMethod(str_gdk_x11_display_get_xdisplay, handleType); - m7 = c.getDeclaredMethod(str_gdk_window_get_display, handleType); - } - if( _gtk_version.compareTo(GTK_VERSION_3_0_0) < 0 ) { - m8 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xid, handleType); + m7 = c.getDeclaredMethod(str_gdk_window_get_display, handleType); } else { + m5 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xdisplay, handleType); + } + if (_gtk_version.compareTo(GTK_VERSION_3_0_0) >= 0) { m9 = c.getDeclaredMethod(str_gdk_x11_window_get_xid, handleType); + } else { + m8 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xid, handleType); } + ma = c.getDeclaredMethod(str_gdk_window_set_back_pixmap, handleType, handleType, boolean.class); } catch (Exception ex) { throw new NativeWindowException(ex); } // optional try { @@ -200,25 +218,31 @@ public class SWTAccessor { OS_gdk_window_get_display = m7; OS_gdk_x11_drawable_get_xid = m8; OS_gdk_x11_window_get_xid = m9; + OS_gdk_window_set_back_pixmap = ma; + + isX11GTK = isX11 && null != OS_gtk_class; if(DEBUG) { System.err.println("SWTAccessor.: GTK Version: "+OS_gtk_version); } } - - - static Object getIntOrLong(long arg) { + + private static Number getIntOrLong(long arg) { if(swt_uses_long_handles) { return new Long(arg); } return new Integer((int) arg); } - static void callStaticMethodL2V(Method m, long arg) { + private static void callStaticMethodL2V(Method m, long arg) { ReflectionUtil.callMethod(null, m, new Object[] { getIntOrLong(arg) }); } - static long callStaticMethodL2L(Method m, long arg) { + private static void callStaticMethodLLZ2V(Method m, long arg0, long arg1, boolean arg3) { + ReflectionUtil.callMethod(null, m, new Object[] { getIntOrLong(arg0), getIntOrLong(arg1), Boolean.valueOf(arg3) }); + } + + private static long callStaticMethodL2L(Method m, long arg) { Object o = ReflectionUtil.callMethod(null, m, new Object[] { getIntOrLong(arg) }); if(o instanceof Number) { return ((Number)o).longValue(); @@ -226,13 +250,73 @@ public class SWTAccessor { throw new InternalError("SWT method "+m.getName()+" didn't return int or long but "+o.getClass()); } } - + + // + // Public properties + // + public static boolean isUsingLongHandles() { return swt_uses_long_handles; } + public static boolean useX11GTK() { return isX11GTK; } public static VersionNumber GTK_VERSION() { return OS_gtk_version; } + // + // Common GTK + // + + public static long gdk_widget_get_window(long handle) { + final long window; + if (OS_gtk_version.compareTo(GTK_VERSION_2_14_0) >= 0) { + window = callStaticMethodL2L(OS_gtk_widget_get_window, handle); + } else { + window = callStaticMethodL2L(OS_GTK_WIDGET_WINDOW, handle); + } + if(0 == window) { + throw new NativeWindowException("Null gtk-window-handle of SWT handle 0x"+Long.toHexString(handle)); + } + return window; + } + + public static long gdk_window_get_xdisplay(long window) { + final long xdisplay; + if (OS_gtk_version.compareTo(GTK_VERSION_2_24_0) >= 0) { + final long display = callStaticMethodL2L(OS_gdk_window_get_display, window); + if(0 == display) { + throw new NativeWindowException("Null display-handle of gtk-window-handle 0x"+Long.toHexString(window)); + } + xdisplay = callStaticMethodL2L(OS_gdk_x11_display_get_xdisplay, display); + } else { + xdisplay = callStaticMethodL2L(OS_gdk_x11_drawable_get_xdisplay, window); + } + if(0 == xdisplay) { + throw new NativeWindowException("Null x11-display-handle of gtk-window-handle 0x"+Long.toHexString(window)); + } + return xdisplay; + } + + public static long gdk_window_get_xwindow(long window) { + final long xWindow; + if (OS_gtk_version.compareTo(GTK_VERSION_3_0_0) >= 0) { + xWindow = callStaticMethodL2L(OS_gdk_x11_window_get_xid, window); + } else { + xWindow = callStaticMethodL2L(OS_gdk_x11_drawable_get_xid, window); + } + if(0 == xWindow) { + throw new NativeWindowException("Null x11-window-handle of gtk-window-handle 0x"+Long.toHexString(window)); + } + return xWindow; + } + + public static void gdk_window_set_back_pixmap(long window, long pixmap, boolean parent_relative) { + callStaticMethodLLZ2V(OS_gdk_window_set_back_pixmap, window, pixmap, parent_relative); + } + + // + // Common any toolkit + // + /** * @param swtControl the SWT Control to retrieve the native widget-handle from * @return the native widget-handle @@ -240,15 +324,21 @@ public class SWTAccessor { */ public static long getHandle(Control swtControl) throws NativeWindowException { long h = 0; - if(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false) ) { - try { - Field fView = Control.class.getField(str_view); - Object view = fView.get(swtControl); - Field fId = view.getClass().getField(str_id); - h = fId.getLong(view); - } catch (Exception ex) { - throw new NativeWindowException(ex); - } + if( isOSX ) { + synchronized(swt_osx_init) { + try { + if(null == swt_osx_view_id) { + swt_osx_control_view = Control.class.getField(str_osx_view); + Object view = swt_osx_control_view.get(swtControl); + swt_osx_view_id = view.getClass().getField(str_osx_id); + h = swt_osx_view_id.getLong(view); + } else { + h = swt_osx_view_id.getLong( swt_osx_control_view.get(swtControl) ); + } + } catch (Exception ex) { + throw new NativeWindowException(ex); + } + } } else { try { h = swt_control_handle.getLong(swtControl); @@ -283,49 +373,6 @@ public class SWTAccessor { } } - private static long gdk_x11_display_get_xdisplay(long window) { - final long xdisplay; - if ( OS_gtk_version.compareTo(GTK_VERSION_2_24_0) >= 0 ) { - final long display = callStaticMethodL2L(OS_gdk_window_get_display, window); - if(0 == display) { - throw new NativeWindowException("Null display-handle of gtk-window-handle 0x"+Long.toHexString(window)); - } - xdisplay = callStaticMethodL2L(OS_gdk_x11_display_get_xdisplay, display); - } else { - xdisplay = callStaticMethodL2L(OS_gdk_x11_drawable_get_xdisplay, window); - } - if(0 == xdisplay) { - throw new NativeWindowException("Null x11-display-handle of gtk-window-handle 0x"+Long.toHexString(window)); - } - return xdisplay; - } - - private static long gdk_widget_get_window(long handle) { - final long window; - if ( OS_gtk_version.compareTo(GTK_VERSION_2_14_0) >= 0 ) { - window = callStaticMethodL2L(OS_gtk_widget_get_window, handle); - } else { - window = callStaticMethodL2L(OS_GTK_WIDGET_WINDOW, handle); - } - if(0 == window) { - throw new NativeWindowException("Null gtk-window-handle of SWT handle 0x"+Long.toHexString(handle)); - } - return window; - } - - private static long gdk_window_get_xwindow(long window) { - final long xwindow; - if ( OS_gtk_version.compareTo(GTK_VERSION_3_0_0) >= 0 ) { - xwindow = callStaticMethodL2L(OS_gdk_x11_window_get_xid, window); - } else { - xwindow = callStaticMethodL2L(OS_gdk_x11_drawable_get_xid, window); - } - if(0 == xwindow) { - throw new NativeWindowException("Null x11-window-handle of gtk-window-handle 0x"+Long.toHexString(window)); - } - return xwindow; - } - /** * @param swtControl the SWT Control to retrieve the native device handle from * @return the AbstractGraphicsDevice w/ the native device handle @@ -333,43 +380,49 @@ public class SWTAccessor { * @throws UnsupportedOperationException if the windowing system is not supported */ public static AbstractGraphicsDevice getDevice(Control swtControl) throws NativeWindowException, UnsupportedOperationException { - long handle = getHandle(swtControl); - if( null != OS_gtk_class ) { - final long xdisplay0 = gdk_x11_display_get_xdisplay( gdk_widget_get_window( handle ) ); - // final String displayName = X11Lib.XDisplayString(xdisplay0); - // final long xdisplay1 = X11Util.openDisplay(displayName); - // return new X11GraphicsDevice(xdisplay1, AbstractGraphicsDevice.DEFAULT_UNIT, true /* owner */); + final long handle = getHandle(swtControl); + if( isX11GTK ) { + final long xdisplay0 = gdk_window_get_xdisplay( gdk_widget_get_window( handle ) ); return new X11GraphicsDevice(xdisplay0, AbstractGraphicsDevice.DEFAULT_UNIT, false /* owner */); } - final String nwt = NativeWindowFactory.getNativeWindowType(false); - if( NativeWindowFactory.TYPE_WINDOWS == nwt ) { + if( isWindows ) { return new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); } - if( NativeWindowFactory.TYPE_MACOSX == nwt ) { + if( isOSX ) { return new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); } throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } + /** + * + * @param device + * @param screen -1 is default screen of the given device, e.g. maybe 0 or determined by native API. >= 0 is specific screen + * @return + * @throws UnsupportedOperationException + */ public static AbstractGraphicsScreen getScreen(AbstractGraphicsDevice device, int screen) throws UnsupportedOperationException { - if( null != OS_gtk_class ) { - return new X11GraphicsScreen((X11GraphicsDevice)device, screen); + if( isX11 ) { + X11GraphicsDevice x11Device = (X11GraphicsDevice)device; + if(0 > screen) { + screen = x11Device.getDefaultScreen(); + } + return new X11GraphicsScreen(x11Device, screen); + } + if(0 > screen) { + screen = 0; // FIXME: Needs native API utilization } - final String nwt = NativeWindowFactory.getNativeWindowType(false); - if( NativeWindowFactory.TYPE_WINDOWS == nwt || - NativeWindowFactory.TYPE_MACOSX == nwt ) { + if( isWindows || isOSX ) { return new DefaultGraphicsScreen(device, screen); } throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } public static int getNativeVisualID(AbstractGraphicsDevice device, long windowHandle) { - if( null != OS_gtk_class ) { + if( isX11 ) { return X11Lib.GetVisualIDFromWindow(device.getHandle(), windowHandle); } - final String nwt = NativeWindowFactory.getNativeWindowType(false); - if( NativeWindowFactory.TYPE_WINDOWS == nwt || - NativeWindowFactory.TYPE_MACOSX == nwt ) { + if( isWindows || isOSX ) { return VisualIDHolder.VID_UNDEFINED; } throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); @@ -383,12 +436,13 @@ public class SWTAccessor { */ public static long getWindowHandle(Control swtControl) throws NativeWindowException, UnsupportedOperationException { final long handle = getHandle(swtControl); - if( null != OS_gtk_class ) { + if(0 == handle) { + throw new NativeWindowException("Null SWT handle of SWT control "+swtControl); + } + if( isX11GTK ) { return gdk_window_get_xwindow( gdk_widget_get_window( handle ) ); } - final String nwt = NativeWindowFactory.getNativeWindowType(false); - if( NativeWindowFactory.TYPE_WINDOWS == nwt || - NativeWindowFactory.TYPE_MACOSX == nwt ) { + if( isWindows || isOSX ) { return handle; } throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); @@ -407,7 +461,7 @@ public class SWTAccessor { throw new InternalError("SWT internal_new_GC did not return int or long but "+o[0].getClass()); } } - + public static void disposeGC(final Control swtControl, final long gc, final GCData gcData) { invoke(true, new Runnable() { public void run() { @@ -437,7 +491,7 @@ public class SWTAccessor { * @see Platform#getOSType() */ public static void invoke(boolean wait, Runnable runnable) { - if( Platform.OS_TYPE == Platform.OSType.MACOS ) { + if( isOSX ) { // Use SWT main thread! Only reliable config w/ -XStartOnMainThread !? OSXUtil.RunOnMainThread(wait, runnable); } else { @@ -445,4 +499,85 @@ public class SWTAccessor { } } + // + // Specific X11 GTK ChildWindow - Using plain X11 native parenting (works well) + // + + public static long createCompatibleX11ChildWindow(AbstractGraphicsScreen screen, Control swtControl, int visualID, int width, int height) { + final long handle = getHandle(swtControl); + final long parentWindow = gdk_widget_get_window( handle ); + gdk_window_set_back_pixmap (parentWindow, 0, false); + + final long x11ParentHandle = gdk_window_get_xwindow(parentWindow); + final long x11WindowHandle = X11Lib.CreateWindow(x11ParentHandle, screen.getDevice().getHandle(), screen.getIndex(), visualID, width, height, true, true); + + return x11WindowHandle; + } + + public static void resizeX11Window(AbstractGraphicsDevice device, Rectangle clientArea, long x11Window) { + X11Lib.SetWindowPosSize(device.getHandle(), x11Window, clientArea.x, clientArea.y, clientArea.width, clientArea.height); + } + public static void destroyX11Window(AbstractGraphicsDevice device, long x11Window) { + X11Lib.DestroyWindow(device.getHandle(), x11Window); + } + + // + // Specific X11 SWT/GTK ChildWindow - Using SWT/GTK native parenting (buggy - sporadic resize flickering, sporadic drop of rendering) + // + // FIXME: Need to use reflection for 32bit access as well ! + // + + // public static final int GDK_WA_TYPE_HINT = 1 << 9; + // public static final int GDK_WA_VISUAL = 1 << 6; + + public static long createCompatibleGDKChildWindow(Control swtControl, int visualID, int width, int height) { + return 0; + /** + final long handle = SWTAccessor.getHandle(swtControl); + final long parentWindow = gdk_widget_get_window( handle ); + + final long screen = OS.gdk_screen_get_default (); + final long gdkvisual = OS.gdk_x11_screen_lookup_visual (screen, visualID); + + final GdkWindowAttr attrs = new GdkWindowAttr(); + attrs.width = width > 0 ? width : 1; + attrs.height = height > 0 ? height : 1; + attrs.event_mask = OS.GDK_KEY_PRESS_MASK | OS.GDK_KEY_RELEASE_MASK | + OS.GDK_FOCUS_CHANGE_MASK | OS.GDK_POINTER_MOTION_MASK | + OS.GDK_BUTTON_PRESS_MASK | OS.GDK_BUTTON_RELEASE_MASK | + OS.GDK_ENTER_NOTIFY_MASK | OS.GDK_LEAVE_NOTIFY_MASK | + OS.GDK_EXPOSURE_MASK | OS.GDK_VISIBILITY_NOTIFY_MASK | + OS.GDK_POINTER_MOTION_HINT_MASK; + attrs.window_type = OS.GDK_WINDOW_CHILD; + attrs.visual = gdkvisual; + + final long childWindow = OS.gdk_window_new (parentWindow, attrs, OS.GDK_WA_VISUAL|GDK_WA_TYPE_HINT); + OS.gdk_window_set_user_data (childWindow, handle); + OS.gdk_window_set_back_pixmap (parentWindow, 0, false); + + OS.gdk_window_show (childWindow); + OS.gdk_flush(); + return childWindow; */ + } + + public static void showGDKWindow(long gdkWindow) { + /* OS.gdk_window_show (gdkWindow); + OS.gdk_flush(); */ + } + public static void focusGDKWindow(long gdkWindow) { + /* + OS.gdk_window_show (gdkWindow); + OS.gdk_window_focus(gdkWindow, 0); + OS.gdk_flush(); */ + } + public static void resizeGDKWindow(Rectangle clientArea, long gdkWindow) { + /** + OS.gdk_window_move (gdkWindow, clientArea.x, clientArea.y); + OS.gdk_window_resize (gdkWindow, clientArea.width, clientArea.height); + OS.gdk_flush(); */ + } + + public static void destroyGDKWindow(long gdkWindow) { + // OS.gdk_window_destroy (gdkWindow); + } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java index 67a33e55c..827862002 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java @@ -37,7 +37,7 @@ public class X11DummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); } if( 0 == s.getSurfaceHandle() ) { - final long windowHandle = X11Lib.CreateDummyWindow(device.getHandle(), screen.getIndex(), cfg.getXVisualID(), 64, 64); + final long windowHandle = X11Lib.CreateWindow(0, device.getHandle(), screen.getIndex(), cfg.getXVisualID(), 64, 64, false, false); if(0 == windowHandle) { throw new NativeWindowException("Creating dummy window failed w/ "+cfg); } @@ -59,7 +59,7 @@ public class X11DummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize } device.lock(); try { - X11Lib.DestroyDummyWindow(device.getHandle(), s.getSurfaceHandle()); + X11Lib.DestroyWindow(device.getHandle(), s.getSurfaceHandle()); s.setSurfaceHandle(0); s.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); } finally { diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index c73952693..a8d45f288 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -31,6 +31,8 @@ #include "jogamp_nativewindow_x11_X11Lib.h" #include "jogamp_nativewindow_x11_X11Util.h" +#include + // #define VERBOSE_ON 1 #ifdef VERBOSE_ON @@ -85,6 +87,8 @@ Bool XF86VidModeSetGammaRamp( #define RTLD_DEFAULT NULL #endif +#define X11_MOUSE_EVENT_MASK (ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask) + static const char * const ClazzNameBuffers = "com/jogamp/common/nio/Buffers"; static const char * const ClazzNameBuffersStaticCstrName = "copyByteBuffer"; static const char * const ClazzNameBuffersStaticCstrSignature = "(Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer;"; @@ -436,17 +440,62 @@ Java_jogamp_nativewindow_x11_X11Lib_XCloseDisplay__J(JNIEnv *env, jclass _unused return _res; } +static void NativewindowX11_setNormalWindowEWMH (Display *dpy, Window w) { + Atom _NET_WM_WINDOW_TYPE = XInternAtom( dpy, "_NET_WM_WINDOW_TYPE", False ); + Atom types[1]={0}; + types[0] = XInternAtom( dpy, "_NET_WM_WINDOW_TYPE_NORMAL", False ); + XChangeProperty( dpy, w, _NET_WM_WINDOW_TYPE, XA_ATOM, 32, PropModeReplace, (unsigned char *)&types, 1); + XSync(dpy, False); +} + +#define DECOR_USE_MWM 1 // works for known WMs +// #define DECOR_USE_EWMH 1 // haven't seen this to work (NORMAL->POPUP, never gets undecorated) + +/* see */ +#define MWM_HINTS_DECORATIONS (1L << 1) +#define PROP_MWM_HINTS_ELEMENTS 5 + +static void NativewindowX11_setDecorations (Display *dpy, Window w, Bool decorated) { + +#ifdef DECOR_USE_MWM + unsigned long mwmhints[PROP_MWM_HINTS_ELEMENTS] = { MWM_HINTS_DECORATIONS, 0, decorated, 0, 0 }; // flags, functions, decorations, input_mode, status + Atom _MOTIF_WM_HINTS = XInternAtom( dpy, "_MOTIF_WM_HINTS", False ); +#endif + +#ifdef DECOR_USE_EWMH + Atom _NET_WM_WINDOW_TYPE = XInternAtom( dpy, "_NET_WM_WINDOW_TYPE", False ); + Atom types[3]={0}; + int ntypes=0; + if(True==decorated) { + types[ntypes++] = XInternAtom( dpy, "_NET_WM_WINDOW_TYPE_NORMAL", False ); + } else { + types[ntypes++] = XInternAtom( dpy, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False ); + } +#endif + +#ifdef DECOR_USE_MWM + XChangeProperty( dpy, w, _MOTIF_WM_HINTS, _MOTIF_WM_HINTS, 32, PropModeReplace, (unsigned char *)&mwmhints, PROP_MWM_HINTS_ELEMENTS); +#endif + +#ifdef DECOR_USE_EWMH + XChangeProperty( dpy, w, _NET_WM_WINDOW_TYPE, XA_ATOM, 32, PropModeReplace, (unsigned char *)&types, ntypes); +#endif + + XSync(dpy, False); +} + /* * Class: jogamp_nativewindow_x11_X11Lib - * Method: CreateDummyWindow - * Signature: (JIIII)J + * Method: CreateWindow + * Signature: (JJIIIIZZ)J */ -JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow - (JNIEnv *env, jclass unused, jlong display, jint screen_index, jint visualID, jint width, jint height) +JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateWindow + (JNIEnv *env, jclass unused, jlong parent, jlong display, jint screen_index, jint visualID, jint width, jint height, jboolean input, jboolean visible) { Display * dpy = (Display *)(intptr_t)display; int scrn_idx = (int)screen_index; - Window windowParent = 0; + Window root = RootWindow(dpy, scrn_idx); + Window windowParent = (Window) parent; Window window = 0; XVisualInfo visualTemplate; @@ -473,6 +522,9 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, 0, 0); scrn = ScreenOfDisplay(dpy, scrn_idx); + if(0==windowParent) { + windowParent = root; + } // try given VisualID on screen memset(&visualTemplate, 0, sizeof(XVisualInfo)); @@ -500,9 +552,6 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow pVisualQuery=NULL; } - if(0==windowParent) { - windowParent = XRootWindowOfScreen(scrn); - } attrMask = ( CWBackingStore | CWBackingPlanes | CWBackingPixel | CWBackPixmap | CWBorderPixel | CWColormap | CWOverrideRedirect ) ; @@ -514,15 +563,22 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow xswa.backing_store=NotUseful; /* NotUseful, WhenMapped, Always */ xswa.backing_planes=0; /* planes to be preserved if possible */ xswa.backing_pixel=0; /* value to use in restoring planes */ + if( input ) { + xswa.event_mask = X11_MOUSE_EVENT_MASK; + xswa.event_mask |= KeyPressMask | KeyReleaseMask ; + } + if( visible ) { + xswa.event_mask |= FocusChangeMask | SubstructureNotifyMask | StructureNotifyMask | ExposureMask ; + } xswa.colormap = XCreateColormap(dpy, - XRootWindow(dpy, scrn_idx), + windowParent, visual, AllocNone); window = XCreateWindow(dpy, windowParent, - 0, 0, + 0, 0, // only a hint, WM most likely will override width, height, 0, // border width depth, @@ -530,9 +586,25 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow visual, attrMask, &xswa); + if(0==window) { + NativewindowCommon_throwNewRuntimeException(env, "could not create Window, bail out!"); + return 0; + } + + NativewindowX11_setNormalWindowEWMH(dpy, window); + NativewindowX11_setDecorations(dpy, window, False); + + if( visible ) { + XEvent event; + + XMapWindow(dpy, window); + } + XSync(dpy, False); - XSelectInput(dpy, window, 0); // no events + if( !input ) { + XSelectInput(dpy, window, 0); // no events + } // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 1); @@ -544,10 +616,10 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow /* * Class: jogamp_nativewindow_x11_X11Lib - * Method: DestroyDummyWindow + * Method: DestroyWindow * Signature: (JJ)V */ -JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_DestroyDummyWindow +JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_DestroyWindow (JNIEnv *env, jclass unused, jlong display, jlong window) { Display * dpy = (Display *)(intptr_t)display; @@ -559,12 +631,37 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_DestroyDummyWindow } NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, 0, 0); + XSelectInput(dpy, w, 0); XUnmapWindow(dpy, w); XSync(dpy, False); XDestroyWindow(dpy, w); // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 1); } +JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_SetWindowPosSize + (JNIEnv *env, jclass unused, jlong display, jlong window, jint x, jint y, jint width, jint height) { + Display * dpy = (Display *)(intptr_t)display; + Window w = (Window) window; + XWindowChanges xwc; + int flags = 0; + + memset(&xwc, 0, sizeof(XWindowChanges)); + + if(0<=x && 0<=y) { + flags |= CWX | CWY; + xwc.x=x; + xwc.y=y; + } + + if(0 + * Implementation allows use of custom {@link GLCapabilities}. + *

      */ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { private static final boolean DEBUG = Debug.debug("Window"); @@ -126,54 +126,44 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { clientArea = getClientArea(); final AbstractGraphicsDevice device = SWTAccessor.getDevice(this); - screen = SWTAccessor.getScreen(device, 0); + screen = SWTAccessor.getScreen(device, -1 /* default */); nativeWindow = null; if(null != child) { setNEWTChild(child); } - - /* Register SWT listeners (e.g. PaintListener) to render/resize GL surface. */ - /* TODO: verify that these do not need to be manually de-registered when destroying the SWT component */ - addPaintListener(new PaintListener() { + + final Listener listener = new Listener () { @Override - public void paintControl(final PaintEvent arg0) { - if( null != nativeWindow || validateNative() ) { - if( newtChildReady ) { - if( postSetSize ) { - newtChild.setSize(clientArea.width, clientArea.height); - postSetSize = false; + public void handleEvent (Event event) { + switch (event.type) { + case SWT.Paint: + if( null != nativeWindow || validateNative() ) { + if( newtChildReady ) { + if( postSetSize ) { + newtChild.setSize(clientArea.width, clientArea.height); + postSetSize = false; + } + newtChild.windowRepaint(0, 0, clientArea.width, clientArea.height); } - newtChild.windowRepaint(0, 0, clientArea.width, clientArea.height); } + break; + case SWT.Resize: + updateSizeCheck(); + break; + case SWT.Dispose: + NewtCanvasSWT.this.dispose(); + break; } } - }); - - addControlListener(new ControlListener() { - @Override - public void controlMoved(ControlEvent e) { - } - @Override - public void controlResized(final ControlEvent arg0) { - updateSizeCheck(); - } - }); - - addDisposeListener(new DisposeListener() { - @Override - public void widgetDisposed(DisposeEvent e) { - NewtCanvasSWT.this.dispose(); - } - }); - + }; + addListener (SWT.Resize, listener); + addListener (SWT.Paint, listener); + addListener (SWT.Dispose, listener); } /** assumes nativeWindow == null ! */ protected final boolean validateNative() { - if( isDisposed() || !isVisible() ) { - return false; - } updateSizeCheck(); final Rectangle nClientArea = clientArea; if(0 >= nClientArea.width || 0 >= nClientArea.height) { @@ -216,6 +206,10 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { ( nClientArea.width != oClientArea.width || nClientArea.height != oClientArea.height ) ) { clientArea = nClientArea; // write back new value + if(DEBUG) { + final long nsh = newtChildReady ? newtChild.getSurfaceHandle() : 0; + System.err.println("NewtCanvasSWT.sizeChanged: ("+Thread.currentThread().getName()+"): newtChildReady "+newtChildReady+", "+nClientArea.x+"/"+nClientArea.y+" "+nClientArea.width+"x"+nClientArea.height+" - surfaceHandle 0x"+Long.toHexString(nsh)); + } if( newtChildReady ) { newtChild.setSize(clientArea.width, clientArea.height); } else { @@ -223,7 +217,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { } } } - + @Override public void update() { // don't paint background etc .. nop avoids flickering @@ -261,11 +255,11 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { public NativeWindow getNativeWindow() { return nativeWindow; } public WindowClosingMode getDefaultCloseOperation() { - return newtChildCloseOp; // FIXME + return newtChildCloseOp; // TODO: implement ?! } public WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) { - return newtChildCloseOp = op; // FIXME + return newtChildCloseOp = op; // TODO: implement ?! } diff --git a/src/newt/classes/com/jogamp/newt/swt/SWTEDTUtil.java b/src/newt/classes/com/jogamp/newt/swt/SWTEDTUtil.java deleted file mode 100644 index 1c20fe524..000000000 --- a/src/newt/classes/com/jogamp/newt/swt/SWTEDTUtil.java +++ /dev/null @@ -1,313 +0,0 @@ -/** - * Copyright 2012 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ -package com.jogamp.newt.swt; - -import javax.media.nativewindow.NativeWindowException; - -import jogamp.newt.Debug; - -import com.jogamp.common.util.RunnableTask; -import com.jogamp.newt.util.EDTUtil; - -/** - * Simple {@link EDTUtil} implementation utilizing the SWT UI thread - * of the given {@link Display}. - */ -public class SWTEDTUtil implements EDTUtil { - public static final boolean DEBUG = Debug.debug("EDT"); - - private final Object edtLock = new Object(); // locking the EDT start/stop state - private final ThreadGroup threadGroup; - private final String name; - private final Runnable dispatchMessages; - private final org.eclipse.swt.widgets.Display swtDisplay; - private NewtEventDispatchThread nedt = null; - private int start_iter=0; - private static long pollPeriod = EDTUtil.defaultEDTPollPeriod; - - public SWTEDTUtil(final com.jogamp.newt.Display newtDisplay, org.eclipse.swt.widgets.Display swtDisplay) { - this.threadGroup = Thread.currentThread().getThreadGroup(); - this.name=Thread.currentThread().getName()+"-SWTDisplay-"+newtDisplay.getFQName()+"-EDT-"; - this.dispatchMessages = new Runnable() { - public void run() { - ((jogamp.newt.DisplayImpl) newtDisplay).dispatchMessages(); - } }; - this.swtDisplay = swtDisplay; - this.nedt = new NewtEventDispatchThread(threadGroup, name); - this.nedt.setDaemon(true); // don't stop JVM from shutdown .. - } - - public final org.eclipse.swt.widgets.Display getDisplay() { - return swtDisplay; - } - - @Override - public long getPollPeriod() { - return pollPeriod; - } - - @Override - public void setPollPeriod(long ms) { - pollPeriod = ms; - } - - @Override - public void reset() { - synchronized(edtLock) { - waitUntilStopped(); - if(DEBUG) { - System.err.println(Thread.currentThread()+": SWT-EDT reset - edt: "+nedt); - } - this.nedt = new NewtEventDispatchThread(threadGroup, name); - this.nedt.setDaemon(true); // don't stop JVM from shutdown .. - } - } - - private final void startImpl() { - if(nedt.isAlive()) { - throw new RuntimeException("SWT-EDT Thread.isAlive(): true, isRunning: "+nedt.isRunning()+", edt: "+nedt); - } - start_iter++; - nedt.setName(name+start_iter); - nedt.shouldStop = false; - if(DEBUG) { - System.err.println(Thread.currentThread()+": SWT-EDT START - edt: "+nedt); - // Thread.dumpStack(); - } - nedt.start(); - } - - @Override - public boolean isCurrentThreadEDT() { - return swtDisplay.getThread() == Thread.currentThread(); - } - - @Override - public final boolean isCurrentThreadNEDT() { - return nedt == Thread.currentThread(); - } - - @Override - public final boolean isCurrentThreadEDTorNEDT() { - final Thread ct = Thread.currentThread(); - return ct == swtDisplay.getThread() || ct == nedt ; - } - - @Override - public boolean isRunning() { - return nedt.isRunning() ; // SWT is always running - } - - @Override - public final void invokeStop(Runnable task) { - invokeImpl(true, task, true); - } - - @Override - public final void invoke(boolean wait, Runnable task) { - invokeImpl(wait, task, false); - } - - private void invokeImpl(boolean wait, Runnable task, boolean stop) { - Throwable throwable = null; - RunnableTask rTask = null; - Object rTaskLock = new Object(); - synchronized(rTaskLock) { // lock the optional task execution - synchronized(edtLock) { // lock the EDT status - if( nedt.shouldStop ) { - // drop task .. - if(DEBUG) { - System.err.println(Thread.currentThread()+": Warning: SWT-EDT about (1) to stop, won't enqueue new task: "+nedt); - Thread.dumpStack(); - } - return; - } - // System.err.println(Thread.currentThread()+" XXX stop: "+stop+", tasks: "+edt.tasks.size()+", task: "+task); - // Thread.dumpStack(); - if(stop) { - synchronized(nedt.sync) { - nedt.shouldStop = true; - nedt.sync.notifyAll(); // stop immediate if waiting (poll freq) - } - if(DEBUG) { - System.err.println(Thread.currentThread()+": SWT-EDT signal STOP (on edt: "+isCurrentThreadEDT()+") - "+nedt); - // Thread.dumpStack(); - } - } else if( !nedt.isRunning() ) { - // start if should not stop && not started yet - startImpl(); - } - if( null == task ) { - wait = false; - } else if( isCurrentThreadEDT() ) { - task.run(); - wait = false; // running in same thread (EDT) -> no wait - } else if( swtDisplay.isDisposed() ) { - wait = false; // drop task, SWT disposed - } else { - rTask = new RunnableTask(task, - wait ? rTaskLock : null, - true /* always catch and report Exceptions, don't disturb EDT */); - swtDisplay.asyncExec(rTask); - } - } - 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) { - if(throwable instanceof NativeWindowException) { - throw (NativeWindowException)throwable; - } - throw new RuntimeException(throwable); - } - } - } - } - - @Override - final public void waitUntilIdle() { - final NewtEventDispatchThread _nedt; - synchronized(edtLock) { - _nedt = nedt; - } - final Thread ct = Thread.currentThread(); - if(!_nedt.isRunning() || _nedt == ct || swtDisplay.getThread() == ct) { - return; - } - try { - swtDisplay.syncExec(new Runnable() { - public void run() { } - }); - } catch (Exception e) { } - } - - @Override - final public void waitUntilStopped() { - synchronized(edtLock) { - final Thread ct = Thread.currentThread(); - if(nedt.isRunning() && nedt != ct && swtDisplay.getThread() != ct) { - while(nedt.isRunning()) { - try { - edtLock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - } - - class NewtEventDispatchThread extends Thread { - volatile boolean shouldStop = false; - volatile boolean isRunning = false; - Object sync = new Object(); - - public NewtEventDispatchThread(ThreadGroup tg, String name) { - super(tg, name); - } - - final public boolean isRunning() { - return isRunning; - } - - @Override - final public void start() throws IllegalThreadStateException { - isRunning = true; - super.start(); - } - - /** - * Utilizing locking only on tasks and its execution, - * not for event dispatching. - */ - @Override - final public void run() { - if(DEBUG) { - System.err.println(getName()+": SWT-EDT run() START "+ getName()); - } - RuntimeException error = null; - try { - do { - // event dispatch - if(!shouldStop) { - // EDT invoke thread is SWT-EDT, - // hence dispatching is required to run on SWT-EDT as well. - // Otherwise a deadlock may happen due to dispatched event's - // triggering a locking action. - if ( !swtDisplay.isDisposed() ) { - swtDisplay.syncExec(dispatchMessages); - } else { - dispatchMessages.run(); - } - } - // wait - synchronized(sync) { - if(!shouldStop) { - try { - sync.wait(pollPeriod); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } while(!shouldStop) ; - } catch (Throwable t) { - // handle errors .. - shouldStop = true; - if(t instanceof RuntimeException) { - error = (RuntimeException) t; - } else { - error = new RuntimeException("Within SWT-EDT", t); - } - } finally { - if(DEBUG) { - System.err.println(getName()+": SWT-EDT run() END "+ getName()+", "+error); - } - synchronized(edtLock) { - isRunning = !shouldStop; - if(!isRunning) { - edtLock.notifyAll(); - } - } - if(DEBUG) { - System.err.println(getName()+": SWT-EDT run() EXIT "+ getName()+", exception: "+error); - } - if(null!=error) { - throw error; - } - } // finally - } // run() - } // EventDispatchThread - -} diff --git a/src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java b/src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java new file mode 100644 index 000000000..7297e5858 --- /dev/null +++ b/src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java @@ -0,0 +1,313 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package jogamp.newt.swt; + +import javax.media.nativewindow.NativeWindowException; + +import jogamp.newt.Debug; + +import com.jogamp.common.util.RunnableTask; +import com.jogamp.newt.util.EDTUtil; + +/** + * Simple {@link EDTUtil} implementation utilizing the SWT UI thread + * of the given {@link Display}. + */ +public class SWTEDTUtil implements EDTUtil { + public static final boolean DEBUG = Debug.debug("EDT"); + + private final Object edtLock = new Object(); // locking the EDT start/stop state + private final ThreadGroup threadGroup; + private final String name; + private final Runnable dispatchMessages; + private final org.eclipse.swt.widgets.Display swtDisplay; + private NewtEventDispatchThread nedt = null; + private int start_iter=0; + private static long pollPeriod = EDTUtil.defaultEDTPollPeriod; + + public SWTEDTUtil(final com.jogamp.newt.Display newtDisplay, org.eclipse.swt.widgets.Display swtDisplay) { + this.threadGroup = Thread.currentThread().getThreadGroup(); + this.name=Thread.currentThread().getName()+"-SWTDisplay-"+newtDisplay.getFQName()+"-EDT-"; + this.dispatchMessages = new Runnable() { + public void run() { + ((jogamp.newt.DisplayImpl) newtDisplay).dispatchMessages(); + } }; + this.swtDisplay = swtDisplay; + this.nedt = new NewtEventDispatchThread(threadGroup, name); + this.nedt.setDaemon(true); // don't stop JVM from shutdown .. + } + + public final org.eclipse.swt.widgets.Display getDisplay() { + return swtDisplay; + } + + @Override + public long getPollPeriod() { + return pollPeriod; + } + + @Override + public void setPollPeriod(long ms) { + pollPeriod = ms; + } + + @Override + public void reset() { + synchronized(edtLock) { + waitUntilStopped(); + if(DEBUG) { + System.err.println(Thread.currentThread()+": SWT-EDT reset - edt: "+nedt); + } + this.nedt = new NewtEventDispatchThread(threadGroup, name); + this.nedt.setDaemon(true); // don't stop JVM from shutdown .. + } + } + + private final void startImpl() { + if(nedt.isAlive()) { + throw new RuntimeException("SWT-EDT Thread.isAlive(): true, isRunning: "+nedt.isRunning()+", edt: "+nedt); + } + start_iter++; + nedt.setName(name+start_iter); + nedt.shouldStop = false; + if(DEBUG) { + System.err.println(Thread.currentThread()+": SWT-EDT START - edt: "+nedt); + // Thread.dumpStack(); + } + nedt.start(); + } + + @Override + public boolean isCurrentThreadEDT() { + return swtDisplay.getThread() == Thread.currentThread(); + } + + @Override + public final boolean isCurrentThreadNEDT() { + return nedt == Thread.currentThread(); + } + + @Override + public final boolean isCurrentThreadEDTorNEDT() { + final Thread ct = Thread.currentThread(); + return ct == swtDisplay.getThread() || ct == nedt ; + } + + @Override + public boolean isRunning() { + return nedt.isRunning() ; // SWT is always running + } + + @Override + public final void invokeStop(Runnable task) { + invokeImpl(true, task, true); + } + + @Override + public final void invoke(boolean wait, Runnable task) { + invokeImpl(wait, task, false); + } + + private void invokeImpl(boolean wait, Runnable task, boolean stop) { + Throwable throwable = null; + RunnableTask rTask = null; + Object rTaskLock = new Object(); + synchronized(rTaskLock) { // lock the optional task execution + synchronized(edtLock) { // lock the EDT status + if( nedt.shouldStop ) { + // drop task .. + if(DEBUG) { + System.err.println(Thread.currentThread()+": Warning: SWT-EDT about (1) to stop, won't enqueue new task: "+nedt); + Thread.dumpStack(); + } + return; + } + // System.err.println(Thread.currentThread()+" XXX stop: "+stop+", tasks: "+edt.tasks.size()+", task: "+task); + // Thread.dumpStack(); + if(stop) { + synchronized(nedt.sync) { + nedt.shouldStop = true; + nedt.sync.notifyAll(); // stop immediate if waiting (poll freq) + } + if(DEBUG) { + System.err.println(Thread.currentThread()+": SWT-EDT signal STOP (on edt: "+isCurrentThreadEDT()+") - "+nedt); + // Thread.dumpStack(); + } + } else if( !nedt.isRunning() ) { + // start if should not stop && not started yet + startImpl(); + } + if( null == task ) { + wait = false; + } else if( isCurrentThreadEDT() ) { + task.run(); + wait = false; // running in same thread (EDT) -> no wait + } else if( swtDisplay.isDisposed() ) { + wait = false; // drop task, SWT disposed + } else { + rTask = new RunnableTask(task, + wait ? rTaskLock : null, + true /* always catch and report Exceptions, don't disturb EDT */); + swtDisplay.asyncExec(rTask); + } + } + 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) { + if(throwable instanceof NativeWindowException) { + throw (NativeWindowException)throwable; + } + throw new RuntimeException(throwable); + } + } + } + } + + @Override + final public void waitUntilIdle() { + final NewtEventDispatchThread _nedt; + synchronized(edtLock) { + _nedt = nedt; + } + final Thread ct = Thread.currentThread(); + if(!_nedt.isRunning() || _nedt == ct || swtDisplay.getThread() == ct) { + return; + } + try { + swtDisplay.syncExec(new Runnable() { + public void run() { } + }); + } catch (Exception e) { } + } + + @Override + final public void waitUntilStopped() { + synchronized(edtLock) { + final Thread ct = Thread.currentThread(); + if(nedt.isRunning() && nedt != ct && swtDisplay.getThread() != ct) { + while(nedt.isRunning()) { + try { + edtLock.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + } + + class NewtEventDispatchThread extends Thread { + volatile boolean shouldStop = false; + volatile boolean isRunning = false; + Object sync = new Object(); + + public NewtEventDispatchThread(ThreadGroup tg, String name) { + super(tg, name); + } + + final public boolean isRunning() { + return isRunning; + } + + @Override + final public void start() throws IllegalThreadStateException { + isRunning = true; + super.start(); + } + + /** + * Utilizing locking only on tasks and its execution, + * not for event dispatching. + */ + @Override + final public void run() { + if(DEBUG) { + System.err.println(getName()+": SWT-EDT run() START "+ getName()); + } + RuntimeException error = null; + try { + do { + // event dispatch + if(!shouldStop) { + // EDT invoke thread is SWT-EDT, + // hence dispatching is required to run on SWT-EDT as well. + // Otherwise a deadlock may happen due to dispatched event's + // triggering a locking action. + if ( !swtDisplay.isDisposed() ) { + swtDisplay.syncExec(dispatchMessages); + } else { + dispatchMessages.run(); + } + } + // wait + synchronized(sync) { + if(!shouldStop) { + try { + sync.wait(pollPeriod); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } while(!shouldStop) ; + } catch (Throwable t) { + // handle errors .. + shouldStop = true; + if(t instanceof RuntimeException) { + error = (RuntimeException) t; + } else { + error = new RuntimeException("Within SWT-EDT", t); + } + } finally { + if(DEBUG) { + System.err.println(getName()+": SWT-EDT run() END "+ getName()+", "+error); + } + synchronized(edtLock) { + isRunning = !shouldStop; + if(!isRunning) { + edtLock.notifyAll(); + } + } + if(DEBUG) { + System.err.println(getName()+": SWT-EDT run() EXIT "+ getName()+", exception: "+error); + } + if(null!=error) { + throw error; + } + } // finally + } // run() + } // EventDispatchThread + +} diff --git a/src/newt/classes/jogamp/newt/swt/event/SWTNewtEventFactory.java b/src/newt/classes/jogamp/newt/swt/event/SWTNewtEventFactory.java new file mode 100644 index 000000000..e238f5d9e --- /dev/null +++ b/src/newt/classes/jogamp/newt/swt/event/SWTNewtEventFactory.java @@ -0,0 +1,249 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.newt.swt.event; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Listener; + +import com.jogamp.common.util.IntIntHashMap; +import com.jogamp.newt.event.InputEvent; + +/** + * SWT event translator to NEWT, inclusive dispatch listener. + *

      + * Disclaimer: This code is merely tested and subject to change. + *

      + */ +public class SWTNewtEventFactory { + + protected static final IntIntHashMap eventTypeSWT2NEWT; + + static { + IntIntHashMap map = new IntIntHashMap(); + map.setKeyNotFoundValue(0xFFFFFFFF); + + // map.put(SWT.MouseXXX, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_CLICKED); + map.put(SWT.MouseDown, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_PRESSED); + map.put(SWT.MouseUp, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED); + map.put(SWT.MouseMove, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_MOVED); + map.put(SWT.MouseEnter, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_ENTERED); + map.put(SWT.MouseExit, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_EXITED); + // map.put(SWT.MouseXXX, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_DRAGGED); + map.put(SWT.MouseVerticalWheel, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_WHEEL_MOVED); + + map.put(SWT.KeyDown, com.jogamp.newt.event.KeyEvent.EVENT_KEY_PRESSED); + map.put(SWT.KeyUp, com.jogamp.newt.event.KeyEvent.EVENT_KEY_RELEASED); + // map.put(SWT.KeyXXX, com.jogamp.newt.event.KeyEvent.EVENT_KEY_TYPED); + + eventTypeSWT2NEWT = map; + } + + public static final int swtModifiers2Newt(int awtMods, boolean mouseHint) { + int newtMods = 0; + if ((awtMods & SWT.SHIFT) != 0) newtMods |= com.jogamp.newt.event.InputEvent.SHIFT_MASK; + if ((awtMods & SWT.CTRL) != 0) newtMods |= com.jogamp.newt.event.InputEvent.CTRL_MASK; + if ((awtMods & SWT.ALT) != 0) newtMods |= com.jogamp.newt.event.InputEvent.ALT_MASK; + return newtMods; + } + + public static final com.jogamp.newt.event.InputEvent createInputEvent(org.eclipse.swt.widgets.Event event, Object source) { + com.jogamp.newt.event.InputEvent res = createMouseEvent(event, source); + if(null == res) { + res = createKeyEvent(event, source); + } + return res; + } + + public static final com.jogamp.newt.event.MouseEvent createMouseEvent(org.eclipse.swt.widgets.Event event, Object source) { + switch(event.type) { + case SWT.MouseDown: + case SWT.MouseUp: + case SWT.MouseMove: + case SWT.MouseEnter: + case SWT.MouseExit: + case SWT.MouseVerticalWheel: + break; + default: + return null; + } + int type = eventTypeSWT2NEWT.get(event.type); + if(0xFFFFFFFF != type) { + int rotation = 0; + if (SWT.MouseVerticalWheel == event.type) { + // SWT/NEWT rotation is reversed - AWT +1 is down, NEWT +1 is up. + // rotation = -1 * (int) event.rotation; + rotation = (int) event.rotation; + } + + int mods = swtModifiers2Newt(event.stateMask, true); + + if( source instanceof com.jogamp.newt.Window) { + final com.jogamp.newt.Window newtSource = (com.jogamp.newt.Window)source; + if(newtSource.isPointerConfined()) { + mods |= InputEvent.CONFINED_MASK; + } + if(!newtSource.isPointerVisible()) { + mods |= InputEvent.INVISIBLE_MASK; + } + } + + return new com.jogamp.newt.event.MouseEvent( + type, (null==source)?(Object)event.data:source, (0xFFFFFFFFL & (long)event.time), + mods, event.x, event.y, event.count, event.button, rotation); + } + return null; // no mapping .. + } + + public static final com.jogamp.newt.event.KeyEvent createKeyEvent(org.eclipse.swt.widgets.Event event, Object source) { + switch(event.type) { + case SWT.KeyDown: + case SWT.KeyUp: + break; + default: + return null; + } + int type = eventTypeSWT2NEWT.get(event.type); + if(0xFFFFFFFF != type) { + return new com.jogamp.newt.event.KeyEvent( + type, (null==source)?(Object)event.data:source, (0xFFFFFFFFL & (long)event.time), + swtModifiers2Newt(event.stateMask, false), + event.keyCode, event.character); + } + return null; // no mapping .. + } + + // + // + // + + int dragButtonDown = 0; + + public SWTNewtEventFactory() { + resetButtonsDown(); + } + + final void resetButtonsDown() { + dragButtonDown = 0; + } + + public final boolean dispatchMouseEvent(org.eclipse.swt.widgets.Event event, Object source, com.jogamp.newt.event.MouseListener l) { + com.jogamp.newt.event.MouseEvent res = createMouseEvent(event, source); + if(null != res) { + if(null != l) { + switch(event.type) { + case SWT.MouseDown: + dragButtonDown = event.button; + l.mousePressed(res); break; + case SWT.MouseUp: + dragButtonDown = 0; + l.mouseReleased(res); + { + final com.jogamp.newt.event.MouseEvent res2 = new com.jogamp.newt.event.MouseEvent( + com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_CLICKED, + res.getSource(), + res.getWhen(), res.getModifiers(), + res.getX(), res.getY(), res.getClickCount(), + res.getButton(), res.getWheelRotation() ); + l.mouseClicked(res2); + } + break; + case SWT.MouseMove: + if( 0 < dragButtonDown ) { + final com.jogamp.newt.event.MouseEvent res2 = new com.jogamp.newt.event.MouseEvent( + com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_DRAGGED, + res.getSource(), + res.getWhen(), res.getModifiers(), + res.getX(), res.getY(), res.getClickCount(), + dragButtonDown, res.getWheelRotation() ); + l.mouseDragged( res2 ); + } else { + l.mouseMoved(res); + } + break; + case SWT.MouseEnter: + l.mouseEntered(res); + break; + case SWT.MouseExit: + resetButtonsDown(); + l.mouseExited(res); + break; + case SWT.MouseVerticalWheel: + l.mouseWheelMoved(res); + break; + } + } + return true; + } + return false; + } + + public final boolean dispatchKeyEvent(org.eclipse.swt.widgets.Event event, Object source, com.jogamp.newt.event.KeyListener l) { + com.jogamp.newt.event.KeyEvent res = createKeyEvent(event, source); + if(null != res) { + if(null != l) { + switch(event.type) { + case SWT.KeyDown: + l.keyPressed(res); + break; + case SWT.KeyUp: + l.keyReleased(res); + l.keyTyped(res); + break; + } + } + return true; + } + return false; + } + + public final void attachDispatchListener(final org.eclipse.swt.widgets.Control ctrl, final Object source, + final com.jogamp.newt.event.MouseListener ml, + final com.jogamp.newt.event.KeyListener kl) { + final Listener listener = new Listener () { + @Override + public void handleEvent (Event event) { + if( dispatchMouseEvent( event, source, ml ) ) { + return; + } + if( dispatchKeyEvent( event, source, kl ) ) { + return; + } + } }; + ctrl.addListener(SWT.MouseDown, listener); + ctrl.addListener(SWT.MouseUp, listener); + ctrl.addListener(SWT.MouseMove, listener); + ctrl.addListener(SWT.MouseEnter, listener); + ctrl.addListener(SWT.MouseExit, listener); + ctrl.addListener(SWT.MouseVerticalWheel, listener); + ctrl.addListener(SWT.KeyDown, listener); + ctrl.addListener(SWT.KeyUp, listener); + } +} + diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java index e9fe9b401..a3023538f 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java @@ -60,8 +60,8 @@ public class GearsES2 implements GLEventListener { private int swapInterval = 0; private boolean pmvUseBackingArray = true; // the default for PMVMatrix now, since it's faster // private MouseListener gearsMouse = new TraceMouseAdapter(new GearsMouseAdapter()); - private MouseListener gearsMouse = new GearsMouseAdapter(); - private KeyListener gearsKeys = new GearsKeyAdapter(); + public MouseListener gearsMouse = new GearsMouseAdapter(); + public KeyListener gearsKeys = new GearsKeyAdapter(); private int prevMouseX, prevMouseY; private boolean doRotate = true; @@ -352,6 +352,10 @@ public class GearsES2 implements GLEventListener { window = (Window) source; width=window.getWidth(); height=window.getHeight(); + } else if (source instanceof GLAutoDrawable) { + GLAutoDrawable glad = (GLAutoDrawable) source; + width = glad.getWidth(); + height = glad.getHeight(); } else if (GLProfile.isAWTAvailable() && source instanceof java.awt.Component) { java.awt.Component comp = (java.awt.Component) source; width=comp.getWidth(); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestNewtCanvasSWTBug628ResizeDeadlock.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestNewtCanvasSWTBug628ResizeDeadlock.java index a0874e609..1f3bf3156 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestNewtCanvasSWTBug628ResizeDeadlock.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestNewtCanvasSWTBug628ResizeDeadlock.java @@ -366,8 +366,9 @@ public class TestNewtCanvasSWTBug628ResizeDeadlock extends UITestCase { try { while( !shallStop && !dsc.display.isDisposed() ) { - if( !dsc.display.readAndDispatch() ) { - dsc.display.sleep(); + if( !dsc.display.readAndDispatch() && !shallStop ) { + // blocks on linux .. dsc.display.sleep(); + Thread.sleep(10); } } } catch (Exception e0) { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTBug643AsyncExec.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTBug643AsyncExec.java index 0a47b96eb..97b3ab243 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTBug643AsyncExec.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTBug643AsyncExec.java @@ -45,12 +45,13 @@ import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities ; import javax.media.opengl.GLProfile; +import jogamp.newt.swt.SWTEDTUtil; +import jogamp.newt.swt.event.SWTNewtEventFactory; import junit.framework.Assert; import com.jogamp.nativewindow.swt.SWTAccessor; import com.jogamp.newt.opengl.GLWindow ; import com.jogamp.newt.swt.NewtCanvasSWT ; -import com.jogamp.newt.swt.SWTEDTUtil; import com.jogamp.opengl.swt.GLCanvas; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; import com.jogamp.opengl.test.junit.util.AWTRobotUtil; @@ -121,15 +122,15 @@ public class TestSWTBug643AsyncExec extends UITestCase { final Runnable swtAsyncAction = new Runnable() { public void run() { - ++swtN ; - System.err.println("[SWT A-i shallStop "+shallStop+"]: Counter[loc "+swtN+", glob: "+incrSWTCount()+"]"); + ++swtN ; incrSWTCount(); + System.err.println("[SWT A-i shallStop "+shallStop+"]: Counter[loc "+swtN+", glob: "+getSWTCount()+"]"); } }; final Runnable newtAsyncAction = new Runnable() { public void run() { - ++newtN ; - System.err.println("[NEWT A-i shallStop "+shallStop+"]: Counter[loc "+newtN+", glob: "+incrNEWTCount()+"]"); + ++newtN ; incrNEWTCount(); + System.err.println("[NEWT A-i shallStop "+shallStop+"]: Counter[loc "+newtN+", glob: "+getNEWTCount()+"]"); } }; public void run() @@ -219,9 +220,13 @@ public class TestSWTBug643AsyncExec extends UITestCase { final GLAutoDrawable glad; if( useJOGLGLCanvas ) { - glad = GLCanvas.create(dsc.composite, 0, caps, null, null); - glad.addGLEventListener( new GearsES2() ) ; - newtDisplay = null; + final GearsES2 demo = new GearsES2(); + final GLCanvas glc = GLCanvas.create(dsc.composite, 0, caps, null, null); + final SWTNewtEventFactory swtNewtEventFactory = new SWTNewtEventFactory(); + swtNewtEventFactory.attachDispatchListener(glc, glc, demo.gearsMouse, demo.gearsKeys); + glc.addGLEventListener( demo ) ; + glad = glc; + newtDisplay = null; } else if( useNewtCanvasSWT ) { final GLWindow glWindow = GLWindow.create( caps ) ; glWindow.addGLEventListener( new GearsES2() ) ; @@ -287,8 +292,9 @@ public class TestSWTBug643AsyncExec extends UITestCase { try { final Display d = dsc.display; while( !shallStop && !d.isDisposed() ) { - if( !d.readAndDispatch() ) { - dsc.display.sleep(); + if( !d.readAndDispatch() && !shallStop ) { + // blocks on linux .. dsc.display.sleep(); + Thread.sleep(10); } } } catch (Exception e0) { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java index a5d2c8012..1822d2eaf 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLn.java @@ -50,6 +50,7 @@ import org.junit.Test; import com.jogamp.nativewindow.swt.SWTAccessor; import com.jogamp.opengl.swt.GLCanvas; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.jogl.demos.es2.MultisampleDemoES2; import com.jogamp.opengl.test.junit.util.UITestCase; import com.jogamp.opengl.util.Animator; import com.jogamp.opengl.util.GLReadBufferUtil; @@ -58,10 +59,9 @@ import com.jogamp.opengl.util.texture.TextureIO; /** * Tests that a basic SWT app can open without crashing under different GL profiles. *

      - * Uses JOGL's new SWT GLCanvas. - *

      - *

      - * Note: To employ custom GLCapabilities, NewtCanvasSWT shall be used. + * Uses JOGL's new SWT GLCanvas, + * which allows utilizing custom GLCapability settings, + * independent from the already instantiated SWT visual. *

      *

      * Note that {@link SWTAccessor#invoke(boolean, Runnable)} is still used to comply w/ @@ -188,6 +188,14 @@ public class TestSWTJOGLGLCanvas01GLn extends UITestCase { runTestAGL( new GLCapabilities(GLProfile.getGL2ES2()), new GearsES2() ); } + @Test + public void test_MultisampleAndAlpha() throws InterruptedException { + GLCapabilities caps = new GLCapabilities(GLProfile.getGL2ES2()); + caps.setSampleBuffers(true); + caps.setNumSamples(2); + runTestAGL( caps, new MultisampleDemoES2(true) ); + } + static int atoi(String a) { int i=0; try { -- cgit v1.2.3 From b0be3d764fc6ff90457fcb96ea81d53ba04cd420 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 25 Dec 2012 03:50:40 +0100 Subject: Misc OSX/SWT: OSXUtil.RunOnMainThread(..) refinement; Fix Test*NewtEventModifiers for SWT (TestNewtEventModifiersNewtCanvasSWT) - Misc OSX/SWT: OSXUtil.RunOnMainThread(..) refinement - 'waitUntilDone' is implemented on Java site via lock/wait on RunnableTask to not freeze OSX main thread. - Fix Test*NewtEventModifiers for SWT (TestNewtEventModifiersNewtCanvasSWT) - Deal with SWT's requirement to run the SWT event dispatch on the TK thread, which must be the main thread on OSX. We spawn off the actual test-action into another thread, while dispatching the events until the test-action is completed. - AWTRobot: Add 'void requestFocus(Robot robot, Object obj, int x, int y)' - Use waitForIdle() only if programmed in Robot (Deadlock w/ OSX SWT) - Required for SWT usage (see above) --- make/scripts/tests.sh | 2 +- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 2 +- .../jogamp/nativewindow/macosx/OSXUtil.java | 39 ++++++- src/nativewindow/native/macosx/OSXmisc.m | 21 +++- .../junit/newt/event/BaseNewtEventModifiers.java | 112 +++++++++++++++++---- .../event/TestNewtEventModifiersNewtCanvasSWT.java | 103 ++++++++----------- .../opengl/test/junit/util/AWTRobotUtil.java | 19 +++- 7 files changed, 206 insertions(+), 92 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index b91e155a0..db061b4bc 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -405,7 +405,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNEWTWindowAWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersAWTCanvas $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNewtCanvasAWT $* -testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNewtCanvasSWT $* +testawtswt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNewtCanvasSWT $* #testawt com.jogamp.opengl.test.junit.newt.TestListenerCom01AWT #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aAWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01bAWT $* diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index eba26c7d3..d3e339586 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -480,7 +480,7 @@ public class SWTAccessor { *

    • Mac OSX *
        * - *
      • Main Thread: Run on OSX UI main thread.
      • + *
      • Main Thread: Run on OSX UI main thread. 'wait' is implemented on Java site via lock/wait on {@link RunnableTask} to not freeze OSX main thread.
      • *
    • *
    • Linux, Windows, .. *
        diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index a195f137e..f06f97064 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -32,6 +32,8 @@ import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.Point; +import com.jogamp.common.util.RunnableTask; + import jogamp.nativewindow.Debug; import jogamp.nativewindow.NWJNILibLoader; import jogamp.nativewindow.ToolkitProperties; @@ -154,11 +156,42 @@ public class OSXUtil implements ToolkitProperties { DestroyCALayer0(caLayer); } + /** + * Run on OSX UI main thread. + *

        + * 'waitUntilDone' is implemented on Java site via lock/wait on {@link RunnableTask} to not freeze OSX main thread. + *

        + * + * @param waitUntilDone + * @param runnable + */ public static void RunOnMainThread(boolean waitUntilDone, Runnable runnable) { - if(IsMainThread0()) { + if( IsMainThread0() ) { runnable.run(); // don't leave the JVM } else { - RunOnMainThread0(waitUntilDone, runnable); + if( waitUntilDone ) { + // Utilize Java side lock/wait and simply pass the Runnable async to OSX main thread, + // otherwise we may freeze the OSX main thread. + Throwable throwable = null; + final Object sync = new Object(); + final RunnableTask rt = new RunnableTask( runnable, sync, true ); + synchronized(sync) { + RunOnMainThread0(rt); + try { + sync.wait(); + } catch (InterruptedException ie) { + throwable = ie; + } + if(null==throwable) { + throwable = rt.getThrowable(); + } + if(null!=throwable) { + throw new RuntimeException(throwable); + } + } + } else { + RunOnMainThread0(runnable); + } } } @@ -205,7 +238,7 @@ public class OSXUtil implements ToolkitProperties { private static native void AddCASublayer0(long rootCALayer, long subCALayer); private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); - private static native void RunOnMainThread0(boolean waitUntilDone, Runnable runnable); + private static native void RunOnMainThread0(Runnable runnable); private static native boolean IsMainThread0(); private static native int GetScreenRefreshRate0(int scrn_idx); } diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 1cf41fc9d..72bb2338c 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -519,13 +519,18 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow { int shallBeDetached = 0; JNIEnv* env = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); + DBG_PRINT("MainRunnable.0 env: %d\n", (int)(NULL!=env)); if(NULL!=env) { + DBG_PRINT("MainRunnable.1.0\n"); (*env)->CallVoidMethod(env, runnableObj, runnableRunID); + DBG_PRINT("MainRunnable.1.1\n"); if (shallBeDetached) { + DBG_PRINT("MainRunnable.1.2\n"); (*jvmHandle)->DetachCurrentThread(jvmHandle); } } + DBG_PRINT("MainRunnable.X\n"); } @end @@ -537,14 +542,16 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow * Signature: (ZLjava/lang/Runnable;)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunOnMainThread0 - (JNIEnv *env, jclass unused, jboolean jwait, jobject runnable) + (JNIEnv *env, jclass unused, jobject runnable) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + DBG_PRINT( "RunOnMainThread0: isMainThread %d, NSApp %d, NSApp-isRunning %d\n", + (int)([NSThread isMainThread]), (int)(NULL!=NSApp), (int)([NSApp isRunning])); + if ( NO == [NSThread isMainThread] ) { jobject runnableGlob = (*env)->NewGlobalRef(env, runnable); - BOOL wait = (JNI_TRUE == jwait) ? YES : NO; JavaVM *jvmHandle = NULL; int jvmVersion = 0; @@ -554,14 +561,18 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunOnMainThread0 jvmVersion = (*env)->GetVersion(env); } + DBG_PRINT( "RunOnMainThread0.1.0\n"); MainRunnable * mr = [[MainRunnable alloc] initWithRunnable: runnableGlob jvmHandle: jvmHandle jvmVersion: jvmVersion]; - [mr performSelectorOnMainThread:@selector(jRun) withObject:nil waitUntilDone:wait]; + [mr performSelectorOnMainThread:@selector(jRun) withObject:nil waitUntilDone:NO]; [mr release]; + DBG_PRINT( "RunOnMainThread0.1.1\n"); (*env)->DeleteGlobalRef(env, runnableGlob); } else { + DBG_PRINT( "RunOnMainThread0.2\n"); (*env)->CallVoidMethod(env, runnable, runnableRunID); } + DBG_PRINT( "RunOnMainThread0.X\n"); [pool release]; } @@ -620,7 +631,7 @@ JNIEXPORT jint JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetScreenRefreshR DBG_PRINT("GetScreenRefreshRate.0: screen %p\n", (void *)screen); if(NULL != screen) { CGDirectDisplayID display = NewtScreen_getCGDirectDisplayIDByNSScreen(screen); - DBG_PRINT("GetScreenRefreshRate.1: display %p\n", (void *)display); + DBG_PRINT("GetScreenRefreshRate.1: display %p\n", (void *)(intptr_t)display); if(0 != display) { CFDictionaryRef mode = CGDisplayCurrentMode(display); DBG_PRINT("GetScreenRefreshRate.2: mode %p\n", (void *)mode); @@ -633,7 +644,7 @@ JNIEXPORT jint JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetScreenRefreshR if(0 == res) { res = 60; // default .. (experienced on OSX 10.6.8) } - DBG_PRINT(stderr, "GetScreenRefreshRate.X: %d\n", res); + DBG_PRINT(stderr, "GetScreenRefreshRate.X: %d\n", (int)res); // [pool release]; JNF_COCOA_EXIT(env); return res; diff --git a/src/test/com/jogamp/opengl/test/junit/newt/event/BaseNewtEventModifiers.java b/src/test/com/jogamp/opengl/test/junit/newt/event/BaseNewtEventModifiers.java index 85a5f24cb..6cbbc675f 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/event/BaseNewtEventModifiers.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/event/BaseNewtEventModifiers.java @@ -34,12 +34,12 @@ import java.util.ArrayList ; import javax.media.opengl.GLProfile ; import org.junit.After ; -import org.junit.AfterClass ; import org.junit.Assert ; import org.junit.Before ; import org.junit.BeforeClass ; import org.junit.Test ; +import com.jogamp.common.util.RunnableTask; import com.jogamp.newt.event.MouseEvent; import com.jogamp.opengl.test.junit.util.UITestCase ; @@ -59,18 +59,18 @@ public abstract class BaseNewtEventModifiers extends UITestCase { protected static final int TEST_FRAME_WIDTH = 400 ; protected static final int TEST_FRAME_HEIGHT = 400 ; - private static final int INITIAL_MOUSE_X = TEST_FRAME_X + ( TEST_FRAME_WIDTH / 2 ) ; - private static final int INITIAL_MOUSE_Y = TEST_FRAME_Y + ( TEST_FRAME_HEIGHT / 2 ) ; + protected static final int INITIAL_MOUSE_X = TEST_FRAME_X + ( TEST_FRAME_WIDTH / 2 ) ; + protected static final int INITIAL_MOUSE_Y = TEST_FRAME_Y + ( TEST_FRAME_HEIGHT / 2 ) ; - private static final int MS_ROBOT_KEY_PRESS_DELAY = 50 ; - private static final int MS_ROBOT_KEY_RELEASE_DELAY = 50 ; - private static final int MS_ROBOT_MOUSE_MOVE_DELAY = 100 ; + protected static final int MS_ROBOT_KEY_PRESS_DELAY = 50 ; + protected static final int MS_ROBOT_KEY_RELEASE_DELAY = 50 ; + protected static final int MS_ROBOT_MOUSE_MOVE_DELAY = 100 ; - private static final int MS_ROBOT_AUTO_DELAY = 50 ; - private static final int MS_ROBOT_POST_TEST_DELAY = 100; + protected static final int MS_ROBOT_AUTO_DELAY = 50 ; + protected static final int MS_ROBOT_POST_TEST_DELAY = 100; - private static final boolean _debug = true ; - private static PrintStream _debugPrintStream = System.err ; + protected static final boolean _debug = true ; + protected static PrintStream _debugPrintStream = System.err ; //////////////////////////////////////////////////////////////////////////// @@ -335,6 +335,35 @@ public abstract class BaseNewtEventModifiers extends UITestCase { _testMouseListener.setModifierCheckEnabled( true ) ; } + //////////////////////////////////////////////////////////////////////////// + // Following both methods are mandatory to deal with SWT's requirement + // to run the SWT event dispatch on the TK thread - which must be the main thread on OSX. + // We spawn off the actual test-action into another thread, + // while dispatching the events until the test-action is completed. + // YES: This is sort of ideal - NOT :) + + protected void eventDispatch() { + try { + Thread.sleep(100); + } catch (InterruptedException e) { } + } + + private void execOffThreadWithOnThreadEventDispatch(Runnable testAction) { + Throwable throwable = null; + final Object sync = new Object(); + final RunnableTask rt = new RunnableTask( testAction, sync, true ); + new Thread(rt, "Test-Thread").start(); + while( !rt.isExecuted() && null == throwable ) { + eventDispatch(); + } + if(null==throwable) { + throwable = rt.getThrowable(); + } + if(null!=throwable) { + throw new RuntimeException(throwable); + } + } + //////////////////////////////////////////////////////////////////////////// // The approach on all these tests is to tell the test mouse listener what @@ -357,17 +386,32 @@ public abstract class BaseNewtEventModifiers extends UITestCase { @Test public void testSingleButtonPressAndRelease() throws Exception { - _doSingleButtonPressAndRelease( 0, 0 ) ; + execOffThreadWithOnThreadEventDispatch(new Runnable() { + public void run() { + try { + _doSingleButtonPressAndRelease( 0, 0 ); + } catch (Exception e) { throw new RuntimeException(e); } + } } ); } @Test public void testSingleButtonPressAndReleaseWithShift() throws Exception { - _doSingleButtonPressAndRelease( java.awt.event.KeyEvent.VK_SHIFT, java.awt.event.InputEvent.SHIFT_DOWN_MASK ) ; + execOffThreadWithOnThreadEventDispatch(new Runnable() { + public void run() { + try { + _doSingleButtonPressAndRelease( java.awt.event.KeyEvent.VK_SHIFT, java.awt.event.InputEvent.SHIFT_DOWN_MASK ) ; + } catch (Exception e) { throw new RuntimeException(e); } + } } ); } @Test public void testSingleButtonPressAndReleaseWithCtrl() throws Exception { - _doSingleButtonPressAndRelease( java.awt.event.KeyEvent.VK_CONTROL, java.awt.event.InputEvent.CTRL_DOWN_MASK ) ; + execOffThreadWithOnThreadEventDispatch(new Runnable() { + public void run() { + try { + _doSingleButtonPressAndRelease( java.awt.event.KeyEvent.VK_CONTROL, java.awt.event.InputEvent.CTRL_DOWN_MASK ) ; + } catch (Exception e) { throw new RuntimeException(e); } + } } ); } /** @@ -375,12 +419,22 @@ public abstract class BaseNewtEventModifiers extends UITestCase { * so it's probably best to leave them commented out. @Test public void testSingleButtonPressAndReleaseWithMeta() throws Exception { - _doSingleButtonPressAndRelease( java.awt.event.KeyEvent.VK_META, java.awt.event.InputEvent.META_DOWN_MASK ) ; + execOffThreadWithOnThreadEventDispatch(new Runnable() { + public void run() { + try { + _doSingleButtonPressAndRelease( java.awt.event.KeyEvent.VK_META, java.awt.event.InputEvent.META_DOWN_MASK ) ; + } catch (Exception e) { throw new RuntimeException(e); } + } } ); } @Test public void testSingleButtonPressAndReleaseWithAlt() throws Exception { - _doSingleButtonPressAndRelease( java.awt.event.KeyEvent.VK_ALT, java.awt.event.InputEvent.ALT_DOWN_MASK ) ; + execOffThreadWithOnThreadEventDispatch(new Runnable() { + public void run() { + try { + _doSingleButtonPressAndRelease( java.awt.event.KeyEvent.VK_ALT, java.awt.event.InputEvent.ALT_DOWN_MASK ) ; + } catch (Exception e) { throw new RuntimeException(e); } + } } ); } */ @@ -392,7 +446,12 @@ public abstract class BaseNewtEventModifiers extends UITestCase { * enough to not let this modifier slip through (?). @Test public void testSingleButtonPressAndReleaseWithAltGraph() throws Exception { - _doSingleButtonPressAndRelease( java.awt.event.KeyEvent.VK_ALT_GRAPH, java.awt.event.InputEvent.ALT_GRAPH_DOWN_MASK ) ; + execOffThreadWithOnThreadEventDispatch(new Runnable() { + public void run() { + try { + _doSingleButtonPressAndRelease( java.awt.event.KeyEvent.VK_ALT_GRAPH, java.awt.event.InputEvent.ALT_GRAPH_DOWN_MASK ) ; + } catch (Exception e) { throw new RuntimeException(e); } + } } ); } */ @@ -400,17 +459,32 @@ public abstract class BaseNewtEventModifiers extends UITestCase { @Test public void testHoldOneButtonAndPressAnother() throws Exception { - _doHoldOneButtonAndPressAnother( 0, 0 ) ; + execOffThreadWithOnThreadEventDispatch(new Runnable() { + public void run() { + try { + _doHoldOneButtonAndPressAnother( 0, 0 ) ; + } catch (Exception e) { throw new RuntimeException(e); } + } } ); } @Test public void testPressAllButtonsInSequence() throws Exception { - _doPressAllButtonsInSequence( 0, 0 ) ; + execOffThreadWithOnThreadEventDispatch(new Runnable() { + public void run() { + try { + _doPressAllButtonsInSequence( 0, 0 ) ; + } catch (Exception e) { throw new RuntimeException(e); } + } } ); } @Test public void testSingleButtonClickAndDrag() throws Exception { - _doSingleButtonClickAndDrag( 0, 0 ) ; + execOffThreadWithOnThreadEventDispatch(new Runnable() { + public void run() { + try { + _doSingleButtonClickAndDrag( 0, 0 ) ; + } catch (Exception e) { throw new RuntimeException(e); } + } } ); } //////////////////////////////////////////////////////////////////////////// diff --git a/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtEventModifiersNewtCanvasSWT.java b/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtEventModifiersNewtCanvasSWT.java index 83b7ded7a..cafc3dd46 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtEventModifiersNewtCanvasSWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtEventModifiersNewtCanvasSWT.java @@ -59,69 +59,42 @@ public class TestNewtEventModifiersNewtCanvasSWT extends BaseNewtEventModifiers private static Shell _shell = null; private static Composite _composite = null; private static GLWindow _glWindow ; - private static DisplayThread _displayThread ; //////////////////////////////////////////////////////////////////////////// - - private static class DisplayThread extends Thread - { - public volatile boolean shallStop = false; - public volatile boolean isInit = false; - - public DisplayThread() - { - super( "SWT Display Thread" ) ; - } - - public void run() { - - synchronized(this) { - SWTAccessor.invoke(true, new Runnable() { - public void run() { - _display = new Display(); - Assert.assertNotNull( _display ); - }}); - - isInit = true; - this.notifyAll(); - } - - while( !_display.isDisposed() && !shallStop && isInterrupted() == false ) { - if( !_display.readAndDispatch() ) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { } - } - } - - synchronized(this) { + + protected static void eventDispatch2xImpl() { + eventDispatchImpl(); + try { + Thread.sleep(100); + } catch (InterruptedException e) { } + eventDispatchImpl(); + } + + protected static void eventDispatchImpl() { + if( !_display.isDisposed() ) { + if( !_display.readAndDispatch() ) { try { - if(!_display.isDisposed()) { - SWTAccessor.invoke(true, new Runnable() { - public void run() { - _display.dispose(); - }}); - } - } finally { - isInit = false; - this.notifyAll(); - } + Thread.sleep(10); + } catch (InterruptedException e) { } } - } + } } - + + @Override + protected void eventDispatch() { + eventDispatchImpl(); + } + //////////////////////////////////////////////////////////////////////////// @BeforeClass public static void beforeClass() throws Exception { - _displayThread = new DisplayThread() ; - synchronized(_displayThread) { - _displayThread.start() ; - while(!_displayThread.isInit) { - _displayThread.wait(); - } - } + SWTAccessor.invoke(true, new Runnable() { + public void run() { + _display = new Display(); + }}); + Assert.assertNotNull( _display ); _display.syncExec(new Runnable() { public void run() { @@ -149,10 +122,16 @@ public class TestNewtEventModifiersNewtCanvasSWT extends BaseNewtEventModifiers } }); - AWTRobotUtil.assertRequestFocusAndWait(null, _glWindow, _glWindow, null, null); // programmatic + // no AWT idling, may deadlock on OSX! Assert.assertNotNull(_robot); - AWTRobotUtil.requestFocus(_robot, _glWindow, false); // within unit framework, prev. tests (TestFocus02SwingAWTRobot) 'confuses' Windows keyboard input - + _robot.setAutoWaitForIdle( false ) ; + + // no waiting for results .. + AWTRobotUtil.requestFocus(null, _glWindow, false); // programmatic + eventDispatch2xImpl(); + AWTRobotUtil.requestFocus(_robot, _glWindow, INITIAL_MOUSE_X, INITIAL_MOUSE_Y); + eventDispatch2xImpl(); + _glWindow.addMouseListener( _testMouseListener ) ; } @@ -171,12 +150,12 @@ public class TestNewtEventModifiersNewtCanvasSWT extends BaseNewtEventModifiers _shell.dispose(); }}); - synchronized(_displayThread) { - _displayThread.shallStop = true; - while( _displayThread.isInit && _displayThread.isAlive() ) { - _displayThread.wait(); - } - } + if(!_display.isDisposed()) { + SWTAccessor.invoke(true, new Runnable() { + public void run() { + _display.dispose(); + }}); + } } catch( Throwable throwable ) { throwable.printStackTrace(); diff --git a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java index b5c96d10f..45648bedf 100644 --- a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java +++ b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java @@ -287,7 +287,24 @@ public class AWTRobotUtil { System.err.println("requestFocus: click, d: "+d+" ms"); } } - + + public static void requestFocus(Robot robot, Object obj, int x, int y) + throws AWTException, InterruptedException, InvocationTargetException { + + final boolean idling = robot.isAutoWaitForIdle(); + final int mouseButton = java.awt.event.InputEvent.BUTTON1_MASK; + robot.mouseMove( x, y ); + if( idling ) { + robot.waitForIdle(); + } else { + try { Thread.sleep(50); } catch (InterruptedException e) { } + } + robot.mousePress(mouseButton); + robot.mouseRelease(mouseButton); + final int d = getClickTimeout(obj) + 1; + robot.delay( d ); + } + public static boolean hasFocus(Object obj) { if(obj instanceof Component) { final Component comp = (Component) obj; -- cgit v1.2.3 From 35236f571a09e1ef21a57693bd2e4d715413f700 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 30 Dec 2012 19:40:17 +0100 Subject: Bug632: Test NEWT Child Window Translucency (X11/Windows) .. - Windows: Child window is not translucent at all - X11: Child window is translucent to parent's background, however - parents content is _not_ 'composed in'. - TODO: Find whether there is a solution or not. - Note: The child window does not change it's rel. position if parent moves! This is a feature, since we don't have impl. a layout. --- make/scripts/java-win64-dbg.bat | 2 +- make/scripts/tests-x64.bat | 13 +- make/scripts/tests.sh | 47 ++++---- make/stub_includes/win32/WindowsDWM.h | 5 +- .../wgl/WindowsWGLGraphicsConfiguration.java | 13 +- .../jogamp/nativewindow/windows/GDIUtil.java | 10 ++ src/nativewindow/native/win32/GDImisc.c | 26 ++++ src/nativewindow/native/win32/WindowsDWM.h | 2 + .../TestTranslucentChildWindowBug632NEWT.java | 132 +++++++++++++++++++++ .../parenting/TestTranslucentParentingAWT.java | 12 +- 10 files changed, 219 insertions(+), 43 deletions(-) create mode 100644 src/test/com/jogamp/opengl/test/junit/newt/parenting/TestTranslucentChildWindowBug632NEWT.java (limited to 'src/nativewindow') diff --git a/make/scripts/java-win64-dbg.bat b/make/scripts/java-win64-dbg.bat index f0a0e9ad7..239856c84 100755 --- a/make/scripts/java-win64-dbg.bat +++ b/make/scripts/java-win64-dbg.bat @@ -30,7 +30,7 @@ REM set D_ARGS="-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary REM set D_ARGS="-Djogl.debug.ExtensionAvailabilityCache" "-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.ProcAddressHelper=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.NativeLibrary=true" REM set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.ExtensionAvailabilityCache" "-Djogamp.debug.ProcAddressHelper=true" -REM set D_ARGS="-Djogl.debug.GraphicsConfiguration" +set D_ARGS="-Dnativewindow.debug.GraphicsConfiguration" REM set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.GLDrawable" "-Dnativewindow.debug.GraphicsConfiguration" REM set D_ARGS="-Djogamp.debug.JNILibLoader=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" "-Djogl.debug.GLProfile=true" REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.Lock" "-Djogamp.debug.Lock.TraceLock" diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat index 2429ede0b..63a8d57f7 100755 --- a/make/scripts/tests-x64.bat +++ b/make/scripts/tests-x64.bat @@ -48,7 +48,7 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.event.TestNewtK REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNEWTWindowAWT $* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersAWTCanvas %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNewtCanvasAWT %* -scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNewtCanvasSWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNewtCanvasSWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01bAWT %* @@ -60,6 +60,8 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestP REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aSWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestTranslucentParentingAWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestTranslucentChildWindowBug632NEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor03AWTGLn %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn %* @@ -87,8 +89,13 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.TexCu REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle01NEWT REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestCloseNewtAWT -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleAWT -time 10000 -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleNEWT -time 10000 +REM scripts\java-win64-dbg.bat testawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1AWT %* +REM scripts\java-win64-dbg.bat testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1NEWT %* +REM scripts\java-win64-dbg.bat testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES2NEWT %* +REM scripts\java-win64-dbg.bat testawt com.jogamp.opengl.test.junit.jogl.caps.TestTranslucencyAWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.caps.TestTranslucencyNEWT %* +scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestTranslucentChildWindowBug632NEWT %* + REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestBug461OffscreenSupersamplingSwingAWT REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestShaderCompilationBug459AWT diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 353cc873a..7cd1fdc5b 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -97,14 +97,15 @@ function jrun() { #D_ARGS="-Djogl.debug.TraceGL -Djogl.debug.DebugGL -Djogl.debug.GLSLCode" #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.FBObject -Djogl.debug.GLContext -Djogl.debug.GLDrawable -Djogl.debug.GLCanvas -Dnewt.debug.Window" #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.FBObject" - D_ARGS="-Djogl.debug.GLContext" + #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLDrawable -Dnativewindow.debug.GraphicsConfiguration" + D_ARGS="-Dnativewindow.debug.GraphicsConfiguration" + #D_ARGS="-Djogl.debug.GLContext" #D_ARGS="-Djogl.debug.GLContext.NoProfileAliasing" #D_ARGS="-Djogamp.debug=all" #D_ARGS="-Djogamp.debug=all -Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" #D_ARGS="-Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" #D_ARGS="-Djogl.debug=all -Dnewt.debug=all" #D_ARGS="-Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.GLCanvas" - #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLDrawable -Dnativewindow.debug.GraphicsConfiguration" #D_ARGS="-Djogl.debug.GLDrawable" #D_ARGS="-Djogl.fbo.force.none" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all -Djogamp.debug.Lock" @@ -281,7 +282,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLPointsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug651NEWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug658NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug658NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryOffscrnCapsNEWT $* @@ -291,7 +292,6 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug658NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer01GLCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer02NewtCanvasAWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableFactoryNEWT $* @@ -304,11 +304,6 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug658NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461FBOSupersamplingSwingAWT #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* -#testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT $* -#testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cSwingAWT $* - - #testnoawt com.jogamp.opengl.test.junit.jogl.glu.TestGluUnprojectFloatNOUI $* #testnoawt com.jogamp.opengl.test.junit.newt.TestRemoteWindow01NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestRemoteGLWindows01NEWT $* @@ -324,8 +319,6 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug658NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestGLWindows02NEWTAnimated $* #testnoawt com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle01NEWT #testnoawt com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle02NEWT -#testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT $* -#testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00bNEWT #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01NEWT @@ -409,23 +402,13 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug658NEWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNewtCanvasAWT $* #testawtswt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNewtCanvasSWT $* #testawt com.jogamp.opengl.test.junit.newt.TestListenerCom01AWT -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aAWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01bAWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cAWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cSwingAWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting02AWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting03AWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT $* -#testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aSWT $* -#testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* -#testawt com.jogamp.opengl.test.junit.newt.parenting.TestTranslucentParentingAWT $* #testawt com.jogamp.opengl.test.junit.newt.TestCloseNewtAWT #testawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1AWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES2NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.caps.TestTranslucencyAWT $* #testawt com.jogamp.opengl.test.junit.jogl.caps.TestTranslucencyNEWT $* +testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestTranslucentChildWindowBug632NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestBug605FlippedImageNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestBug605FlippedImageAWT $* #testawt com.jogamp.opengl.test.junit.jogl.glsl.TestShaderCompilationBug459AWT @@ -436,9 +419,27 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug658NEWT $* #testawt $* -#testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrent01NEWT $* +# +# NEWT Parenting (w/ NEWT, AWT or SWT) +# +#testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cSwingAWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aAWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01bAWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cAWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting02AWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting03AWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT $* +#testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aSWT $* +#testawtswt com.jogamp.opengl.test.junit.newt.parenting.TestParenting04SWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* +#testawt com.jogamp.opengl.test.junit.newt.parenting.TestTranslucentParentingAWT $* +#testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestTranslucentChildWindowBug632NEWT $* + # # Misc Utils # diff --git a/make/stub_includes/win32/WindowsDWM.h b/make/stub_includes/win32/WindowsDWM.h index 357602dae..2115a5908 100644 --- a/make/stub_includes/win32/WindowsDWM.h +++ b/make/stub_includes/win32/WindowsDWM.h @@ -1,8 +1,11 @@ #ifndef WGL_DWM_VERSION_1_X -#define DWM_BB_ENABLE 1 +#define DWM_BB_ENABLE 0x00000001 +#define DWM_BB_BLURREGION 0x00000002 +#define DWM_BB_TRANSITIONONMAXIMIZED 0x00000004 #define DWM_EC_DISABLECOMPOSITION 0 #define DWM_EC_ENABLECOMPOSITION 1 + typedef struct tagDWM_BLURBEHIND { DWORD dwFlags; diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java index 70da1137d..651d981ab 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java @@ -55,6 +55,7 @@ import com.jogamp.opengl.GLExtensions; import jogamp.nativewindow.windows.DWM_BLURBEHIND; import jogamp.nativewindow.windows.GDI; +import jogamp.nativewindow.windows.GDIUtil; import jogamp.nativewindow.windows.MARGINS; import jogamp.nativewindow.windows.PIXELFORMATDESCRIPTOR; import jogamp.opengl.GLContextImpl; @@ -170,13 +171,13 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio " for device context " + toHexString(hdc) + ": error code " + GDI.GetLastError()); } - if(!caps.isBackgroundOpaque()) { + if( !caps.isBackgroundOpaque() ) { final long hwnd = GDI.WindowFromDC(hdc); DWM_BLURBEHIND bb = DWM_BLURBEHIND.create(); - bb.setDwFlags(GDI.DWM_BB_ENABLE); - bb.setFEnable(1); + bb.setDwFlags(GDI.DWM_BB_ENABLE| GDI.DWM_BB_TRANSITIONONMAXIMIZED); + bb.setFEnable( 1 ); boolean ok = GDI.DwmEnableBlurBehindWindow(hwnd, bb); - if(ok) { + if( ok ) { MARGINS m = MARGINS.create(); m.setCxLeftWidth(-1); m.setCxRightWidth(-1); @@ -185,7 +186,9 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio ok = GDI.DwmExtendFrameIntoClientArea(hwnd, m); } if(DEBUG) { - System.err.println("translucency enabled on wnd: 0x"+Long.toHexString(hwnd)+" - ok: "+ok); + final boolean isUndecorated = GDIUtil.IsUndecorated(hwnd); + final boolean isChild = GDIUtil.IsChild(hwnd); + System.err.println("translucency enabled on wnd: 0x"+Long.toHexString(hwnd)+" - isUndecorated "+isUndecorated+", isChild "+isChild+", ok: "+ok); } } if (DEBUG) { diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index 2f4e18359..acb4c84da 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -112,12 +112,22 @@ public class GDIUtil implements ToolkitProperties { return (Point) GetRelativeLocation0(src_win, dest_win, src_x, src_y); } + public static boolean IsUndecorated(long win) { + return IsUndecorated0(win); + } + + public static boolean IsChild(long win) { + return IsChild0(win); + } + public static native boolean CreateWindowClass(long hInstance, String clazzName, long wndProc); public static native boolean DestroyWindowClass(long hInstance, String className); private static native boolean initIDs0(); private static native long getDummyWndProc0(); private static native Object GetRelativeLocation0(long src_win, long dest_win, int src_x, int src_y); + private static native boolean IsChild0(long win); + private static native boolean IsUndecorated0(long win); static native long CreateDummyWindow0(long hInstance, String className, String windowName, int x, int y, int width, int height); } diff --git a/src/nativewindow/native/win32/GDImisc.c b/src/nativewindow/native/win32/GDImisc.c index 3ab7f9859..23be47380 100644 --- a/src/nativewindow/native/win32/GDImisc.c +++ b/src/nativewindow/native/win32/GDImisc.c @@ -224,3 +224,29 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_windows_GDIUtil_GetRelativeLo return (*env)->NewObject(env, pointClz, pointCstr, (jint)dest.x, (jint)dest.y); } +/* + * Class: jogamp_nativewindow_windows_GDIUtil + * Method: IsChild0 + */ +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_IsChild0 + (JNIEnv *env, jclass unused, jlong jwin) +{ + HWND hwnd = (HWND) (intptr_t) jwin; + LONG style = GetWindowLong(hwnd, GWL_STYLE); + BOOL bIsChild = 0 != (style & WS_CHILD) ; + return bIsChild ? JNI_TRUE : JNI_FALSE; +} + +/* + * Class: jogamp_nativewindow_windows_GDIUtil + * Method: IsUndecorated0 + */ +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_IsUndecorated0 + (JNIEnv *env, jclass unused, jlong jwin) +{ + HWND hwnd = (HWND) (intptr_t) jwin; + LONG style = GetWindowLong(hwnd, GWL_STYLE); + BOOL bIsUndecorated = 0 != (style & (WS_CHILD|WS_POPUP)) ; + return bIsUndecorated ? JNI_TRUE : JNI_FALSE; +} + diff --git a/src/nativewindow/native/win32/WindowsDWM.h b/src/nativewindow/native/win32/WindowsDWM.h index 36f82fc94..6e5160fa4 100644 --- a/src/nativewindow/native/win32/WindowsDWM.h +++ b/src/nativewindow/native/win32/WindowsDWM.h @@ -4,6 +4,8 @@ #include #define DWM_BB_ENABLE 0x00000001 // fEnable has been specified + #define DWM_BB_BLURREGION 0x00000002 + #define DWM_BB_TRANSITIONONMAXIMIZED 0x00000004 #define DWM_EC_DISABLECOMPOSITION 0 #define DWM_EC_ENABLECOMPOSITION 1 diff --git a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestTranslucentChildWindowBug632NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestTranslucentChildWindowBug632NEWT.java new file mode 100644 index 000000000..1d186a490 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestTranslucentChildWindowBug632NEWT.java @@ -0,0 +1,132 @@ +package com.jogamp.opengl.test.junit.newt.parenting; + +import java.io.IOException; + +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeWindow; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLProfile; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.MiscUtils; +import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.util.Animator; + +public class TestTranslucentChildWindowBug632NEWT extends UITestCase { + static long durationPerTest = 2*300; + static GLProfile glp; + static boolean opaque; + + @BeforeClass + public static void initClass() { + glp = GLProfile.getDefault(); + opaque = false; + } + + static GLWindow createParentWindow(GLCapabilitiesImmutable caps, int width, int height) + throws InterruptedException + { + Assert.assertNotNull(caps); + // + // Create native windowing resources .. X11/Win/OSX + // + GLWindow glWindow; + glWindow = GLWindow.create(caps); + Assert.assertNotNull(glWindow); + + glWindow.setTitle("NEWT Parenting Window Test"); + + glWindow.addGLEventListener(new GearsES2(1)); + + glWindow.setSize(width, height); + glWindow.setVisible(true); + Assert.assertEquals(true,glWindow.isVisible()); + Assert.assertEquals(true,glWindow.isNativeValid()); + + return glWindow; + } + + static GLWindow createNestedWindow(NativeWindow nativeParentWindow, GLCapabilitiesImmutable caps, int x, int y, int width, int height) + throws InterruptedException { + + Assert.assertNotNull(nativeParentWindow); + Assert.assertNotNull(caps); + // + // Create native windowing resources .. X11/Win/OSX + // + GLWindow glWindow; + glWindow = GLWindow.create(nativeParentWindow, caps); + Assert.assertNotNull(glWindow); + + glWindow.setTitle("NEWT Parenting Window Test"); + + glWindow.addGLEventListener(new GearsES2(1)); + + glWindow.setPosition(x, y); + glWindow.setSize(width, height); + glWindow.setVisible(true); + Assert.assertEquals(true,glWindow.isVisible()); + Assert.assertEquals(true,glWindow.isNativeValid()); + + return glWindow; + } + + static void destroyWindow(GLWindow glWindow) { + if(null!=glWindow) { + glWindow.destroy(); + Assert.assertEquals(false,glWindow.isNativeValid()); + } + } + + @Test + public void testWindow00() throws InterruptedException { + final Animator animator = new Animator(); + + GLCapabilities caps = new GLCapabilities(glp); + Assert.assertNotNull(caps); + caps.setBackgroundOpaque(opaque); + GLWindow window1 = createParentWindow(caps, 400, 400); + Assert.assertEquals(true,window1.isNativeValid()); + Assert.assertEquals(true,window1.isVisible()); + animator.add(window1); + + GLWindow window2 = createNestedWindow(window1, caps, 400-300, 400-300, 300, 300); + Assert.assertEquals(true,window2.isNativeValid()); + Assert.assertEquals(true,window2.isVisible()); + animator.add(window2); + + animator.start(); + + AbstractGraphicsDevice device1 = window1.getScreen().getDisplay().getGraphicsDevice(); + + System.err.println("GLProfiles window1: "+device1.getConnection()+": "+GLProfile.glAvailabilityToString(device1)); + + Thread.sleep(durationPerTest/2); + + window1.setSize(512, 512); + window2.setPosition(512-300, 512-300); + + Thread.sleep(durationPerTest/2); + + animator.stop(); + + destroyWindow(window2); + destroyWindow(window1); + } + + public static void main(String[] args) throws IOException { + for(int i=0; i Date: Mon, 14 Jan 2013 05:58:21 +0100 Subject: NEWT-MouseEvent getWheelRotation() API Update - Fixes Bug 659: NEWT Horizontal Scrolling Behavior (OSX, X11, Win32); Bug 639: High-Res Mouse-Wheel - API update 'float getWheelRotation()': Usually a wheel rotation of > 0.0f is up, and < 0.0f is down. Usually a wheel rotations is considered a vertical scroll. If isShiftDown(), a wheel rotations is considered a horizontal scroll, where shift-up = left = > 0.0f, and shift-down = right = < 0.0f. However, on some OS this might be flipped due to the OS default behavior. The latter is true for OS X 10.7 (Lion) for example. The events will be send usually in steps of one, ie. -1.0f and 1.0f. Higher values may result due to fast scrolling. Fractional values may result due to slow scrolling with high resolution devices. The button number refers to the wheel number. - Fix Bug 659: NEWT Horizontal Scrolling Behavior (OSX, X11, Win32) - See new API doc above - X11/Horiz: Keep using button1 and set SHIFT modifier - OSX/Horiz: - PAD: Use highes absolute scrolling value (Axis1/Axis2) and set SHIFT modifier for horizontal scrolling (Axis2) - XXX: Use deltaX for horizontal scrolling, detected by SHIFT modifier. (traditional) - Windows/Horiz: - Add WM_MOUSEHWHEEL support (-> set SHIFT modifier), but it's rarely impl. for trackpads! - Add exp. WM_HSCROLL, but it will only be delivered if windows has WS_HSCROLL, hence dead code! - Android: - Add ACTION_SCROLL (API Level 12), only used if layout is a scroll layout - Using GestureDetector to detect scroll even w/ pointerCount > 2, while: - skipping 1st scroll event (value too high) - skipping other events while in-scroll mode - waiting until all pointers were released before cont. normally - using View config's 1/touchSlope as scale factor - Fix Bug 639: High-Res Mouse-Wheel - getWheelRotation() return value changed: int -> float allowing fractions, see API doc changes above. - Fractions are currently supported natively (API) on - Windows - OSX - Android - AndroidNewtEventFactory ir refactored (requires an instance now) and AndroidNewtEventTranslator (event listener) is pulled our of Android WindowDriver. --- make/resources/android/AndroidManifest-test.xml | 24 +- make/scripts/java-win32-dbg.bat | 1 + make/scripts/java-win64-dbg.bat | 3 +- make/scripts/tests-x32.bat | 6 +- make/scripts/tests-x64.bat | 8 +- make/scripts/tests.sh | 6 +- .../jogamp/nativewindow/windows/GDIUtil.java | 5 +- .../nativewindow/windows/RegisteredClass.java | 5 +- .../windows/RegisteredClassFactory.java | 26 +- src/newt/classes/com/jogamp/newt/NewtFactory.java | 8 +- .../classes/com/jogamp/newt/event/MouseEvent.java | 24 +- src/newt/classes/jogamp/newt/WindowImpl.java | 16 +- .../jogamp/newt/awt/event/AWTNewtEventFactory.java | 4 +- .../jogamp/newt/driver/android/WindowDriver.java | 100 +++--- .../android/event/AndroidNewtEventFactory.java | 355 ++++++++++++++++----- .../android/event/AndroidNewtEventTranslator.java | 55 ++++ .../jogamp/newt/driver/windows/DisplayDriver.java | 13 +- .../jogamp/newt/driver/windows/WindowDriver.java | 13 +- .../jogamp/newt/driver/x11/WindowDriver.java | 14 +- .../jogamp/newt/swt/event/SWTNewtEventFactory.java | 4 +- src/newt/native/KDWindow.c | 6 +- src/newt/native/NewtMacWindow.m | 58 ++-- src/newt/native/WindowsWindow.c | 181 +++++++++-- src/newt/native/X11Display.c | 24 +- src/newt/native/X11Event.c | 20 +- src/newt/native/XCBEvent.c | 12 +- src/newt/native/bcm_vc_iv.c | 2 +- .../opengl/test/junit/jogl/demos/es2/GearsES2.java | 29 +- 28 files changed, 750 insertions(+), 272 deletions(-) create mode 100644 src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventTranslator.java (limited to 'src/nativewindow') diff --git a/make/resources/android/AndroidManifest-test.xml b/make/resources/android/AndroidManifest-test.xml index 3c2046df1..0817b3450 100644 --- a/make/resources/android/AndroidManifest-test.xml +++ b/make/resources/android/AndroidManifest-test.xml @@ -18,9 +18,9 @@ android:persistent="false" > - @@ -28,9 +28,9 @@ - @@ -39,9 +39,9 @@ - @@ -49,9 +49,9 @@ - diff --git a/make/scripts/java-win32-dbg.bat b/make/scripts/java-win32-dbg.bat index a4a9e9a5b..1852d9b0c 100755 --- a/make/scripts/java-win32-dbg.bat +++ b/make/scripts/java-win32-dbg.bat @@ -36,6 +36,7 @@ REM set D_ARGS="-Djogl.debug=all" REM set D_ARGS="-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL" REM set D_ARGS="-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL" "-Djogl.debug=all" REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display" "-Dnewt.test.Window.reparent.incompatible=true" +REM set D_ARGS="-Dnewt.debug.Window.MouseEvent" REM set D_ARGS="-Xcheck:jni" "-Xint" "-verbose:jni" set X_ARGS="-Dsun.java2d.noddraw=true" "-Dsun.awt.noerasebackground=true" diff --git a/make/scripts/java-win64-dbg.bat b/make/scripts/java-win64-dbg.bat index 239856c84..63c46eee5 100755 --- a/make/scripts/java-win64-dbg.bat +++ b/make/scripts/java-win64-dbg.bat @@ -30,7 +30,7 @@ REM set D_ARGS="-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary REM set D_ARGS="-Djogl.debug.ExtensionAvailabilityCache" "-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.ProcAddressHelper=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.NativeLibrary=true" REM set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.ExtensionAvailabilityCache" "-Djogamp.debug.ProcAddressHelper=true" -set D_ARGS="-Dnativewindow.debug.GraphicsConfiguration" +REM set D_ARGS="-Dnativewindow.debug.GraphicsConfiguration" REM set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.GLDrawable" "-Dnativewindow.debug.GraphicsConfiguration" REM set D_ARGS="-Djogamp.debug.JNILibLoader=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" "-Djogl.debug.GLProfile=true" REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.Lock" "-Djogamp.debug.Lock.TraceLock" @@ -41,6 +41,7 @@ REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLC REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch" REM set D_ARGS="-Dnewt.debug.Window" REM set D_ARGS="-Dnewt.debug.Window.KeyEvent" +REM set D_ARGS="-Dnewt.debug.Window.MouseEvent" REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display" REM set D_ARGS="-Djogl.debug.GLDebugMessageHandler" "-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL" REM set D_ARGS="-Djogl.debug.DebugGL" "-Djogl.debug.GLDebugMessageHandler" "-Djogl.debug.GLSLCode" diff --git a/make/scripts/tests-x32.bat b/make/scripts/tests-x32.bat index ec6c41f37..adc4ece39 100755 --- a/make/scripts/tests-x32.bat +++ b/make/scripts/tests-x32.bat @@ -1,5 +1,5 @@ REM scripts\java-win32-dbg.bat jogamp.newt.awt.opengl.VersionApplet -scripts\java-win32-dbg.bat com.jogamp.newt.opengl.GLWindow +REM scripts\java-win32-dbg.bat com.jogamp.newt.opengl.GLWindow REM scripts\java-win32-dbg.bat javax.media.opengl.awt.GLCanvas REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT %* REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT %* @@ -16,12 +16,14 @@ REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt. REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT -time 30000 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT %* REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT %* -REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* +scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 4000 -x 10 -y 10 -width 100 -height 100 -screen 0 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT %* REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestAWTCardLayoutAnimatorStartStopBug532 %* REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT -time 5000 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT -time 5000 +REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %* +REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.demos.gl3.newt.TestGeomShader01TextureGL3NEWT %* REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestAWT03GLCanvasRecreate01 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.newt.TestSwingAWTRobotUsageBeforeJOGLInitBug411 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestTransformFeedbackVaryingsBug407NEWT diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat index 20cb54147..b66f8b8ab 100755 --- a/make/scripts/tests-x64.bat +++ b/make/scripts/tests-x64.bat @@ -22,7 +22,7 @@ REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclu REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext01VSyncAnimAWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext02FPSAnimNEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext02FPSAnimAWT %* -scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext11VSyncAnimNEWT %* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext11VSyncAnimNEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext12FPSAnimNEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* @@ -49,11 +49,13 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestIsReali REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT -time 30000 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT %* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* +scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 4000 -x 10 -y 10 -width 100 -height 100 -screen 0 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 40000 -width 100 -height 100 -screen 0 %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT -time 5000 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT -time 5000 +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.gl3.newt.TestGeomShader01TextureGL3NEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.newt.TestSwingAWTRobotUsageBeforeJOGLInitBug411 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestTransformFeedbackVaryingsBug407NEWT REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLSimple01NEWT -time 2000 @@ -146,5 +148,3 @@ REM scripts\java-win64.bat com.jogamp.opengl.test.junit.graph.demos.GPURegionNew REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.awt.TestBug461FBOSupersamplingSwingAWT REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01 -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %* - diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 130cf1570..bc379de63 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -165,7 +165,7 @@ function jrun() { #D_ARGS="-Dnewt.debug.Window -Djogl.debug.Animator -Dnewt.debug.Screen" #D_ARGS="-Dnewt.debug.Window" #D_ARGS="-Dnewt.debug.Window.KeyEvent" - #D_ARGS="-Dnewt.debug.Window.MouseEvent" + D_ARGS="-Dnewt.debug.Window.MouseEvent" #D_ARGS="-Dnewt.debug.Window -Dnativewindow.debug=all" #D_ARGS="-Dnewt.debug.Window -Dnativewindow.debug.JAWT -Djogl.debug.Animator" #D_ARGS="-Dnewt.debug.Window" @@ -261,7 +261,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.gl3.newt.TestGeomShader01TextureGL3NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFloatUtil01MatrixMatrixMultNOUI $* @@ -285,7 +285,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLPointsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug651NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug658NEWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext01VSyncAnimNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext01VSyncAnimNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext01VSyncAnimAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext02FPSAnimNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext02FPSAnimAWT $* diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index acb4c84da..00741a328 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -34,7 +34,6 @@ import javax.media.nativewindow.NativeWindowFactory; import jogamp.nativewindow.NWJNILibLoader; import jogamp.nativewindow.Debug; import jogamp.nativewindow.ToolkitProperties; -import jogamp.nativewindow.x11.X11Util; public class GDIUtil implements ToolkitProperties { private static final boolean DEBUG = Debug.debug("GDIUtil"); @@ -49,7 +48,7 @@ public class GDIUtil implements ToolkitProperties { */ public static synchronized void initSingleton() { if(!isInit) { - synchronized(X11Util.class) { + synchronized(GDIUtil.class) { if(!isInit) { if(DEBUG) { System.out.println("GDI.initSingleton()"); @@ -92,7 +91,7 @@ public class GDIUtil implements ToolkitProperties { public static long CreateDummyWindow(int x, int y, int width, int height) { synchronized(dummyWindowSync) { dummyWindowClass = dummyWindowClassFactory.getSharedClass(); - return CreateDummyWindow0(dummyWindowClass.getHandle(), dummyWindowClass.getName(), dummyWindowClass.getName(), x, y, width, height); + return CreateDummyWindow0(dummyWindowClass.getHInstance(), dummyWindowClass.getName(), dummyWindowClass.getName(), x, y, width, height); } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java index afb3daf7c..949f5d06d 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java @@ -37,7 +37,10 @@ public class RegisteredClass { className = name; } - public final long getHandle() { return hInstance; } + /** Application handle, same as {@link RegisteredClassFactory#getHInstance()}. */ + public final long getHInstance() { return hInstance; } + + /** Unique Window Class Name */ public final String getName() { return className; } @Override diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java index 00bedfc8e..0280b0df7 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java @@ -33,8 +33,17 @@ import java.util.ArrayList; import javax.media.nativewindow.NativeWindowException; public class RegisteredClassFactory { - static final boolean DEBUG = Debug.debug("RegisteredClass"); - private static ArrayList registeredFactories = new ArrayList(); + private static final boolean DEBUG = Debug.debug("RegisteredClass"); + private static final ArrayList registeredFactories; + private static final long hInstance; + + static { + hInstance = GDI.GetApplicationHandle(); + if( 0 == hInstance ) { + throw new NativeWindowException("Error: Null ModuleHandle for Application"); + } + registeredFactories = new ArrayList(); + } private String classBaseName; private long wndProc; @@ -43,7 +52,7 @@ public class RegisteredClassFactory { private int classIter = 0; private int sharedRefCount = 0; private final Object sync = new Object(); - + /** * Release the {@link RegisteredClass} of all {@link RegisteredClassFactory}. */ @@ -53,7 +62,7 @@ public class RegisteredClassFactory { final RegisteredClassFactory rcf = registeredFactories.get(j); synchronized(rcf.sync) { if(null != rcf.sharedClass) { - GDIUtil.DestroyWindowClass(rcf.sharedClass.getHandle(), rcf.sharedClass.getName()); + GDIUtil.DestroyWindowClass(rcf.sharedClass.getHInstance(), rcf.sharedClass.getName()); rcf.sharedClass = null; rcf.sharedRefCount = 0; rcf.classIter = 0; @@ -65,6 +74,9 @@ public class RegisteredClassFactory { } } } + + /** Application handle. */ + public static long getHInstance() { return hInstance; } public RegisteredClassFactory(String classBaseName, long wndProc) { this.classBaseName = classBaseName; @@ -80,10 +92,6 @@ public class RegisteredClassFactory { if( null != sharedClass ) { throw new InternalError("Error ("+sharedRefCount+"): SharedClass not null: "+sharedClass); } - long hInstance = GDI.GetApplicationHandle(); - if( 0 == hInstance ) { - throw new NativeWindowException("Error: Null ModuleHandle for Application"); - } String clazzName = null; boolean registered = false; final int classIterMark = classIter - 1; @@ -121,7 +129,7 @@ public class RegisteredClassFactory { throw new InternalError("Error ("+sharedRefCount+"): SharedClass is null"); } if( 0 == sharedRefCount ) { - GDIUtil.DestroyWindowClass(sharedClass.getHandle(), sharedClass.getName()); + GDIUtil.DestroyWindowClass(sharedClass.getHInstance(), sharedClass.getName()); if(DEBUG) { System.err.println("RegisteredClassFactory releaseSharedClass ("+sharedRefCount+") released: "+sharedClass); } diff --git a/src/newt/classes/com/jogamp/newt/NewtFactory.java b/src/newt/classes/com/jogamp/newt/NewtFactory.java index b3e904310..e66b2f624 100644 --- a/src/newt/classes/com/jogamp/newt/NewtFactory.java +++ b/src/newt/classes/com/jogamp/newt/NewtFactory.java @@ -44,8 +44,6 @@ import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowFactory; -import com.jogamp.common.os.Platform; - import jogamp.newt.Debug; import jogamp.newt.DisplayImpl; import jogamp.newt.ScreenImpl; @@ -56,13 +54,15 @@ public class NewtFactory { public static final String DRIVER_DEFAULT_ROOT_PACKAGE = "jogamp.newt.driver"; - // Work-around for initialization order problems on Mac OS X - // between native Newt and (apparently) Fmod static { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { NativeWindowFactory.initSingleton(); // last resort .. + + // Work-around for initialization order problems on Mac OS X + // between native Newt and (apparently) Fmod WindowImpl.init(NativeWindowFactory.getNativeWindowType(true)); + return null; } } ); } diff --git a/src/newt/classes/com/jogamp/newt/event/MouseEvent.java b/src/newt/classes/com/jogamp/newt/event/MouseEvent.java index 914aaa647..e6b3d8a24 100644 --- a/src/newt/classes/com/jogamp/newt/event/MouseEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/MouseEvent.java @@ -65,7 +65,7 @@ public class MouseEvent extends InputEvent public MouseEvent(int eventType, Object source, long when, int modifiers, int x, int y, int clickCount, int button, - int rotation) + float rotation) { super(eventType, source, when, modifiers); this.x = new int[]{x}; @@ -79,7 +79,7 @@ public class MouseEvent extends InputEvent public MouseEvent(int eventType, Object source, long when, int modifiers, int[] x, int[] y, float[] pressure, int[] pointerids, int clickCount, int button, - int rotation) + float rotation) { super(eventType, source, when, modifiers); this.x = x; @@ -154,20 +154,29 @@ public class MouseEvent extends InputEvent } /** - * Usually a wheel rotation of > 0 is up, - * and < 0 is down.
        + * Usually a wheel rotation of > 0.0f is up, + * and < 0.0f is down. + *

        + * Usually a wheel rotations is considered a vertical scroll.
        + * If {@link #isShiftDown()}, a wheel rotations is + * considered a horizontal scroll, where shift-up = left = > 0.0f, + * and shift-down = right = < 0.0f. + *

        + *

        * However, on some OS this might be flipped due to the OS default behavior. * The latter is true for OS X 10.7 (Lion) for example. + *

        *

        - * The events will be send usually in steps of one, ie. -1 and 1. + * The events will be send usually in steps of one, ie. -1.0f and 1.0f. * Higher values may result due to fast scrolling. + * Fractional values may result due to slow scrolling with high resolution devices. *

        *

        * The button number refers to the wheel number. *

        * @return */ - public int getWheelRotation() { + public float getWheelRotation() { return wheelRotation; } @@ -212,7 +221,8 @@ public class MouseEvent extends InputEvent default: return "unknown (" + type + ")"; } } - private final int x[], y[], clickCount, button, wheelRotation; + private final int x[], y[], clickCount, button; + private final float wheelRotation; private final float pressure[]; private final int pointerids[]; diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index 6e1059952..3c93de5b3 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -133,10 +133,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer private ArrayList windowListeners = new ArrayList(); private boolean repaintQueued = false; - // Workaround for initialization order problems on Mac OS X - // between native Newt and (apparently) Fmod -- if Fmod is - // initialized first then the connection to the window server - // breaks, leading to errors from deep within the AppKit + /** + * Workaround for initialization order problems on Mac OS X + * between native Newt and (apparently) Fmod -- if Fmod is + * initialized first then the connection to the window server + * breaks, leading to errors from deep within the AppKit + */ public static void init(String type) { if (NativeWindowFactory.TYPE_MACOSX.equals(type)) { try { @@ -1974,16 +1976,16 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // MouseListener/Event Support // public void sendMouseEvent(int eventType, int modifiers, - int x, int y, int button, int rotation) { + int x, int y, int button, float rotation) { doMouseEvent(false, false, eventType, modifiers, x, y, button, rotation); } public void enqueueMouseEvent(boolean wait, int eventType, int modifiers, - int x, int y, int button, int rotation) { + int x, int y, int button, float rotation) { doMouseEvent(true, wait, eventType, modifiers, x, y, button, rotation); } protected void doMouseEvent(boolean enqueue, boolean wait, int eventType, int modifiers, - int x, int y, int button, int rotation) { + int x, int y, int button, float rotation) { if( eventType == MouseEvent.EVENT_MOUSE_ENTERED || eventType == MouseEvent.EVENT_MOUSE_EXITED ) { if( eventType == MouseEvent.EVENT_MOUSE_EXITED && x==-1 && y==-1 ) { x = lastMousePosition.getX(); diff --git a/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java b/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java index 1a61d0528..e0f7af69c 100644 --- a/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java +++ b/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java @@ -262,10 +262,10 @@ public class AWTNewtEventFactory { public static final com.jogamp.newt.event.MouseEvent createMouseEvent(java.awt.event.MouseEvent event, com.jogamp.newt.Window newtSource) { int type = eventTypeAWT2NEWT.get(event.getID()); if(0xFFFFFFFF != type) { - int rotation = 0; + float rotation = 0; if (event instanceof java.awt.event.MouseWheelEvent) { // AWT/NEWT rotation is reversed - AWT +1 is down, NEWT +1 is up. - rotation = -1 * ((java.awt.event.MouseWheelEvent)event).getWheelRotation(); + rotation = -1f * ((java.awt.event.MouseWheelEvent)event).getWheelRotation(); } final int newtButton = awtButton2Newt(event.getButton()); diff --git a/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java index f18520630..281bd9e0f 100644 --- a/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java @@ -29,7 +29,7 @@ package jogamp.newt.driver.android; import jogamp.common.os.android.StaticContext; -import jogamp.newt.driver.android.event.AndroidNewtEventFactory; +import jogamp.newt.driver.android.event.AndroidNewtEventTranslator; import javax.media.nativewindow.Capabilities; import javax.media.nativewindow.CapabilitiesImmutable; @@ -41,6 +41,7 @@ import javax.media.opengl.GLCapabilitiesChooser; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLException; +import com.jogamp.common.os.AndroidVersion; import com.jogamp.nativewindow.egl.EGLGraphicsDevice; import jogamp.opengl.egl.EGL; @@ -58,7 +59,6 @@ import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback2; import android.view.inputmethod.InputMethodManager; import android.view.SurfaceView; -import android.view.View; public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { static { @@ -139,42 +139,6 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { return false; } - class AndroidEvents implements View.OnKeyListener, View.OnTouchListener, View.OnFocusChangeListener { - - @Override - public boolean onTouch(View v, android.view.MotionEvent event) { - final com.jogamp.newt.event.MouseEvent[] newtEvents = AndroidNewtEventFactory.createMouseEvents(event, WindowDriver.this); - if(null != newtEvents) { - focusChanged(false, true); - for(int i=0; i[] getCustomConstructorArgumentTypes() { return new Class[] { Context.class } ; } @@ -196,22 +160,33 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { setBrokenFocusChange(true); } + private void setupInputListener(boolean enable) { + Log.d(MD.TAG, "setupInputListener(enable "+enable+") - "+Thread.currentThread().getName()); + + final AndroidNewtEventTranslator eventTranslator = + enable ? new AndroidNewtEventTranslator(this, androidView.getContext(), androidView.getHandler()) : null; + androidView.setOnTouchListener(eventTranslator); + androidView.setOnKeyListener(eventTranslator); + androidView.setOnFocusChangeListener(eventTranslator); + if(AndroidVersion.SDK_INT >= 12) { // API Level 12 + Log.d(MD.TAG, "instantiationFinished() - enable GenericMotionListener - "+Thread.currentThread().getName()); + androidView.setOnGenericMotionListener(eventTranslator); + } + androidView.setClickable(false); + androidView.setFocusable(enable); + androidView.setFocusableInTouchMode(enable); + } + @Override protected void instantiationFinished() { + Log.d(MD.TAG, "instantiationFinished() - "+Thread.currentThread().getName()); + final Context ctx = StaticContext.getContext(); if(null == ctx) { throw new NativeWindowException("No static [Application] Context has been set. Call StaticContext.setContext(Context) first."); } androidView = new MSurfaceView(ctx); - - final AndroidEvents ae = new AndroidEvents(); - androidView.setOnTouchListener(ae); - androidView.setClickable(false); - androidView.setOnKeyListener(ae); - androidView.setOnFocusChangeListener(ae); - androidView.setFocusable(true); - androidView.setFocusableInTouchMode(true); - + final SurfaceHolder sh = androidView.getHolder(); sh.addCallback(WindowDriver.this); sh.setFormat(getFormat(getRequestedCapabilities())); @@ -220,7 +195,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { defineSize(0, 0); } - public SurfaceView getAndroidView() { return androidView; } + public final SurfaceView getAndroidView() { return androidView; } @Override protected boolean canCreateNativeImpl() { @@ -259,11 +234,14 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { if (EGL.EGL_NO_SURFACE==eglSurface) { throw new NativeWindowException("Creation of window surface failed: "+eglConfig+", surfaceHandle 0x"+Long.toHexString(surfaceHandle)+", error "+toHexString(EGL.eglGetError())); } - + // propagate data .. setGraphicsConfiguration(eglConfig); setWindowHandle(surfaceHandle); focusChanged(false, true); + + setupInputListener(true); + Log.d(MD.TAG, "createNativeImpl X: eglSurfaceHandle 0x"+Long.toHexString(eglSurface)); } @@ -272,6 +250,9 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { Log.d(MD.TAG, "closeNativeImpl 0 - surfaceHandle 0x"+Long.toHexString(surfaceHandle)+ ", eglSurfaceHandle 0x"+Long.toHexString(eglSurface)+ ", format [a "+androidFormat+", n "+nativeFormat+"], "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()+" - "+Thread.currentThread().getName()); + + setupInputListener(false); + if(0 != eglSurface) { final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) getScreen().getDisplay().getGraphicsDevice(); if (!EGL.eglDestroySurface(eglDevice.getHandle(), eglSurface)) { @@ -289,6 +270,19 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { return eglSurface; } + /** + *

        + * Accessible protected method! + *

        + * + * {@inheritDoc} + */ + @Override + public void focusChanged(boolean defer, boolean focusGained) { + super.focusChanged(defer, focusGained); + } + + @Override protected void requestFocusImpl(boolean reparented) { if(null != androidView) { Log.d(MD.TAG, "requestFocusImpl: reparented "+reparented); @@ -301,6 +295,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { } } + @Override protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { boolean res = true; @@ -330,10 +325,12 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { return res; } + @Override protected Point getLocationOnScreenImpl(int x, int y) { return new Point(x,y); } + @Override protected void updateInsetsImpl(Insets insets) { // nop .. } @@ -367,6 +364,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { } private KeyboardVisibleReceiver keyboardVisibleReceiver = new KeyboardVisibleReceiver(); + @Override protected final boolean setKeyboardVisibleImpl(boolean visible) { if(null != androidView) { final InputMethodManager imm = (InputMethodManager) getAndroidView().getContext().getSystemService(Context.INPUT_METHOD_SERVICE); @@ -388,10 +386,12 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { // Surface Callbacks // + @Override public void surfaceCreated(SurfaceHolder holder) { Log.d(MD.TAG, "surfaceCreated: "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()); } + @Override public void surfaceChanged(SurfaceHolder aHolder, int aFormat, int aWidth, int aHeight) { Log.d(MD.TAG, "surfaceChanged: f "+nativeFormat+" -> "+aFormat+", "+aWidth+"x"+aHeight+", current surfaceHandle: 0x"+Long.toHexString(surfaceHandle)); if(0!=surfaceHandle && androidFormat != aFormat ) { @@ -436,11 +436,13 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { Log.d(MD.TAG, "surfaceChanged: X"); } + @Override public void surfaceDestroyed(SurfaceHolder holder) { Log.d(MD.TAG, "surfaceDestroyed"); windowDestroyNotify(true); // actually too late .. however .. } + @Override public void surfaceRedrawNeeded(SurfaceHolder holder) { Log.d(MD.TAG, "surfaceRedrawNeeded"); windowRepaint(0, 0, getWidth(), getHeight()); diff --git a/src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventFactory.java b/src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventFactory.java index d23b5f576..dc1e8aeef 100644 --- a/src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventFactory.java +++ b/src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventFactory.java @@ -28,38 +28,81 @@ package jogamp.newt.driver.android.event; -import java.awt.event.MouseEvent; - -import com.jogamp.common.util.IntIntHashMap; +import com.jogamp.common.os.AndroidVersion; import com.jogamp.newt.Window; import com.jogamp.newt.event.InputEvent; public class AndroidNewtEventFactory { - protected static final IntIntHashMap eventTypeANDROID2NEWT; - - private static final String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" , - "POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" }; + private static final String names[] = { "DOWN" , "UP" , "MOVE", "CANCEL" , "OUTSIDE", // 0 - 4 + "POINTER_DOWN" , "POINTER_UP" , "HOVER_MOVE" , "SCROLL", // 5 - 8 + "HOVER_ENTER", "HOVER_EXIT" // 0 - 10 + }; - static { - IntIntHashMap map = new IntIntHashMap(); - map.setKeyNotFoundValue(0xFFFFFFFF); - - map.put(android.view.MotionEvent.ACTION_DOWN, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_PRESSED); - map.put(android.view.MotionEvent.ACTION_UP, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED); - map.put(android.view.MotionEvent.ACTION_CANCEL, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED); - map.put(android.view.MotionEvent.ACTION_MOVE, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_DRAGGED); - map.put(android.view.MotionEvent.ACTION_OUTSIDE, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_MOVED); - - map.put(android.view.MotionEvent.ACTION_POINTER_DOWN, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_PRESSED); - map.put(android.view.MotionEvent.ACTION_POINTER_UP, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED); - - map.put(android.view.accessibility.AccessibilityEvent.TYPE_VIEW_FOCUSED, com.jogamp.newt.event.WindowEvent.EVENT_WINDOW_GAINED_FOCUS); - - eventTypeANDROID2NEWT = map; + /** API Level 12: {@link android.view.MotionEvent#ACTION_SCROLL} = {@value} */ + private static final int ACTION_SCROLL = 8; + + private static final int aMotionEventType2Newt(int aType) { + final int nType; + switch( aType ) { + case android.view.MotionEvent.ACTION_DOWN: + nType = com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_PRESSED; + break; + case android.view.MotionEvent.ACTION_UP: + nType = com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED; + break; + case android.view.MotionEvent.ACTION_MOVE: + nType = com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_DRAGGED; + break; + case android.view.MotionEvent.ACTION_CANCEL: + nType = com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED; + break; + case android.view.MotionEvent.ACTION_OUTSIDE: + nType = com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_MOVED; + break; + // + case android.view.MotionEvent.ACTION_POINTER_DOWN: + nType = com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_PRESSED; + break; + case android.view.MotionEvent.ACTION_POINTER_UP: + nType = com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED; + break; + // case ACTION_HOVER_MOVE + case ACTION_SCROLL: // API Level 12 ! + nType = com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_WHEEL_MOVED; + break; + // case ACTION_HOVER_ENTER + // case ACTION_HOVER_EXIT + default: + nType = 0xFFFFFFFF; + } + return nType; + } + + private static final int aAccessibilityEventType2Newt(int aType) { + final int nType; + switch( aType ) { + case android.view.accessibility.AccessibilityEvent.TYPE_VIEW_FOCUSED: + nType = com.jogamp.newt.event.WindowEvent.EVENT_WINDOW_GAINED_FOCUS; break; + default: + nType = 0xFFFFFFFF; + } + return nType; } - static final int androidKeyCode2Newt(int androidKeyCode) { + private static final int aKeyEventType2NewtEventType(int androidKeyAction) { + switch(androidKeyAction) { + case android.view.KeyEvent.ACTION_DOWN: + case android.view.KeyEvent.ACTION_MULTIPLE: + return com.jogamp.newt.event.KeyEvent.EVENT_KEY_PRESSED; + case android.view.KeyEvent.ACTION_UP: + return com.jogamp.newt.event.KeyEvent.EVENT_KEY_RELEASED; + default: + return 0; + } + } + + private static final int aKeyCode2NewtKeyCode(int androidKeyCode) { if(android.view.KeyEvent.KEYCODE_0 <= androidKeyCode && androidKeyCode <= android.view.KeyEvent.KEYCODE_9) { return com.jogamp.newt.event.KeyEvent.VK_0 + ( androidKeyCode - android.view.KeyEvent.KEYCODE_0 ) ; } @@ -104,15 +147,7 @@ public class AndroidNewtEventFactory { return 0; } - public static final com.jogamp.newt.event.WindowEvent createWindowEvent(android.view.accessibility.AccessibilityEvent event, com.jogamp.newt.Window newtSource) { - int type = eventTypeANDROID2NEWT.get(event.getEventType()); - if(0xFFFFFFFF != type) { - return new com.jogamp.newt.event.WindowEvent(type, ((null==newtSource)?null:(Object)newtSource), event.getEventTime()); - } - return null; // no mapping .. - } - - static final int androidKeyModifiers2Newt(int androidMods) { + private static final int aKeyModifiers2Newt(int androidMods) { int newtMods = 0; if ((androidMods & android.view.KeyEvent.META_SYM_ON) != 0) newtMods |= com.jogamp.newt.event.InputEvent.META_MASK; if ((androidMods & android.view.KeyEvent.META_SHIFT_ON) != 0) newtMods |= com.jogamp.newt.event.InputEvent.SHIFT_MASK; @@ -121,29 +156,40 @@ public class AndroidNewtEventFactory { return newtMods; } - private static final int androidKeyAction2NewtEventType(int androidKeyAction) { - switch(androidKeyAction) { - case android.view.KeyEvent.ACTION_DOWN: - case android.view.KeyEvent.ACTION_MULTIPLE: - return com.jogamp.newt.event.KeyEvent.EVENT_KEY_PRESSED; - case android.view.KeyEvent.ACTION_UP: - return com.jogamp.newt.event.KeyEvent.EVENT_KEY_RELEASED; - default: - return 0; + private final NewtGestureListener gestureListener; + private final android.view.GestureDetector gestureDetector; + private final float touchSlop; + + public AndroidNewtEventFactory(android.content.Context context, android.os.Handler handler) { + gestureListener = new NewtGestureListener(); + gestureDetector = new android.view.GestureDetector(context, gestureListener, handler, false /* ignoreMultitouch */); + gestureDetector.setIsLongpressEnabled(false); // favor scroll event! + final android.view.ViewConfiguration configuration = android.view.ViewConfiguration.get(context); + touchSlop = configuration.getScaledTouchSlop(); + } + + public com.jogamp.newt.event.WindowEvent createWindowEvent(android.view.accessibility.AccessibilityEvent event, com.jogamp.newt.Window newtSource) { + final int aType = event.getEventType(); + final int nType = aAccessibilityEventType2Newt(aType); + + if(0xFFFFFFFF != nType) { + return new com.jogamp.newt.event.WindowEvent(nType, ((null==newtSource)?null:(Object)newtSource), event.getEventTime()); } + return null; // no mapping .. } + - public static final com.jogamp.newt.event.KeyEvent[] createKeyEvents(int keyCode, android.view.KeyEvent event, com.jogamp.newt.Window newtSource) { - final int type = androidKeyAction2NewtEventType(event.getAction()); + public com.jogamp.newt.event.KeyEvent[] createKeyEvents(int keyCode, android.view.KeyEvent event, com.jogamp.newt.Window newtSource) { + final int type = aKeyEventType2NewtEventType(event.getAction()); if(Window.DEBUG_MOUSE_EVENT) { System.err.println("createKeyEvent: type 0x"+Integer.toHexString(type)+", keyCode 0x"+Integer.toHexString(keyCode)+", "+event); } if(0xFFFFFFFF != type) { - final int newtKeyCode = androidKeyCode2Newt(keyCode); + final int newtKeyCode = aKeyCode2NewtKeyCode(keyCode); if(0 != newtKeyCode) { final Object src = (null==newtSource)?null:(Object)newtSource; final long unixTime = System.currentTimeMillis() + ( event.getEventTime() - android.os.SystemClock.uptimeMillis() ); - final int newtMods = androidKeyModifiers2Newt(event.getMetaState()); + final int newtMods = aKeyModifiers2Newt(event.getMetaState()); final com.jogamp.newt.event.KeyEvent ke1 = new com.jogamp.newt.event.KeyEvent( type, src, unixTime, newtMods, newtKeyCode, event.getDisplayLabel()); @@ -161,29 +207,145 @@ public class AndroidNewtEventFactory { return null; } - public static final com.jogamp.newt.event.MouseEvent[] createMouseEvents(android.view.MotionEvent event, com.jogamp.newt.Window newtSource) { + private int gestureScrollPointerDown = 0; + + public com.jogamp.newt.event.MouseEvent[] createMouseEvents(boolean isOnTouchEvent, + android.view.MotionEvent event, com.jogamp.newt.Window newtSource) { if(Window.DEBUG_MOUSE_EVENT) { - System.err.println("createMouseEvent: "+toString(event)); + System.err.println("createMouseEvent: "+toString(event)); } - int type = eventTypeANDROID2NEWT.get(event.getAction()); - if(0xFFFFFFFF != type) { - int rotation = 0; - int clickCount = 1; + + // + // Prefilter Android Event (Gesture, ..) and determine final type + // + final int aType, nType; + float[] rotationXY = null; + int rotationSource = 0; // 1 - Gesture, 2 - ACTION_SCROLL + { + final int pointerCount = event.getPointerCount(); + final boolean gestureEvent = isOnTouchEvent && pointerCount>1 && gestureDetector.onTouchEvent(event); + int _aType = 0xFFFFFFFF; + if( gestureEvent ) { + rotationXY = gestureListener.getScrollDistanceXY(); + if( null != rotationXY) { + final boolean skip = 0 == gestureScrollPointerDown; // skip 1st .. too bug distance + gestureScrollPointerDown = pointerCount; + if( skip ) { + if(Window.DEBUG_MOUSE_EVENT) { + System.err.println("createMouseEvent: GestureEvent Scroll Start - SKIP "+rotationXY[0]+"/"+rotationXY[1]+", gestureScrollPointerDown "+gestureScrollPointerDown); + } + return null; + } + _aType = ACTION_SCROLL; // 8 + rotationSource = 1; + } else { + throw new InternalError("Gesture Internal Error: consumed onTouchEvent, but no result (Scroll)"); + } + } + if( 0xFFFFFFFF == _aType ) { + _aType = event.getActionMasked(); + } + aType = _aType; + nType = aMotionEventType2Newt(aType); + + // + // Check whether events shall be skipped + // + if( !gestureEvent ) { + // Scroll Gesture: Wait for all pointers up - ACTION_UP, ACTION_POINTER_UP + if( 0 < gestureScrollPointerDown ) { + if( com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED == nType ) { + gestureScrollPointerDown--; + } + if(Window.DEBUG_MOUSE_EVENT) { + System.err.println("createMouseEvent: !GestureEvent SKIP gestureScrollPointerDown "+gestureScrollPointerDown); + } + return null; + } + } + } + + if(0xFFFFFFFF != nType) { + final int clickCount = 1; int modifiers = 0; - int[] x = new int[event.getPointerCount()]; - int[] y = new int[event.getPointerCount()]; - float[] pressure = new float[event.getPointerCount()]; - int[] pointers = new int[event.getPointerCount()]; - int index = 0; - while(index < event.getPointerCount()) { - x[index] = (int)event.getX(index); - y[index] = (int)event.getY(index); - pressure[index] = event.getPressure(index); - pointers[index] = event.getPointerId(index); - index++; + if( null == rotationXY && AndroidVersion.SDK_INT >= 12 && ACTION_SCROLL == aType ) { // API Level 12 + rotationXY = new float[] { event.getAxisValue(android.view.MotionEvent.AXIS_X), + event.getAxisValue(android.view.MotionEvent.AXIS_Y) }; + rotationSource = 2; } - + + final float rotation; + if( null != rotationXY ) { + final float _rotation; + if( rotationXY[0]*rotationXY[0] > rotationXY[1]*rotationXY[1] ) { + // Horizontal + modifiers |= com.jogamp.newt.event.InputEvent.SHIFT_MASK; + _rotation = rotationXY[0]; + } else { + // Vertical + _rotation = rotationXY[1]; + } + rotation = _rotation / touchSlop; + if(Window.DEBUG_MOUSE_EVENT) { + System.err.println("createMouseEvent: Scroll "+rotationXY[0]+"/"+rotationXY[1]+" -> "+_rotation+" / "+touchSlop+" -> "+rotation+" scaled -- mods "+modifiers+", source "+rotationSource); + } + } else { + rotation = 0.0f; + } + + // + // Determine newt-button and whether dedicated pointer is pressed + // + final int pCount; + final int pIndex; + final int button; + switch( aType ) { + case android.view.MotionEvent.ACTION_POINTER_DOWN: + case android.view.MotionEvent.ACTION_POINTER_UP: { + pIndex = event.getActionIndex(); + pCount = 1; + final int b = event.getPointerId(pIndex) + 1; // FIXME: Assumption that Pointer-ID starts w/ 0 ! + if( com.jogamp.newt.event.MouseEvent.BUTTON1 <= b && b <= com.jogamp.newt.event.MouseEvent.BUTTON_NUMBER ) { + button = b; + } else { + button = com.jogamp.newt.event.MouseEvent.BUTTON1; + } + } + break; + default: { + pIndex = 0; + pCount = event.getPointerCount(); // all + button = com.jogamp.newt.event.MouseEvent.BUTTON1; + } + } + + // + // Collect common data + // + final int[] x = new int[pCount]; + final int[] y = new int[pCount]; + final float[] pressure = new float[pCount]; + final int[] pointerIds = new int[pCount]; + { + if(Window.DEBUG_MOUSE_EVENT) { + System.err.println("createMouseEvent: collect ptr-data ["+pIndex+".."+(pIndex+pCount-1)+", "+pCount+"], aType "+aType+", button "+button+", gestureScrollPointerDown "+gestureScrollPointerDown); + } + int i = pIndex; + int j = 0; + while(j < pCount) { + x[j] = (int)event.getX(i); + y[j] = (int)event.getY(i); + pressure[j] = event.getPressure(i); + pointerIds[j] = event.getPointerId(i); + if(Window.DEBUG_MOUSE_EVENT) { + System.err.println("createMouseEvent: ptr-data["+i+" -> "+j+"] "+x[j]+"/"+y[j]+", pressure "+pressure[j]+", id "+pointerIds[j]); + } + i++; + j++; + } + } + if(null!=newtSource) { if(newtSource.isPointerConfined()) { modifiers |= InputEvent.CONFINED_MASK; @@ -195,21 +357,20 @@ public class AndroidNewtEventFactory { final Object src = (null==newtSource)?null:(Object)newtSource; final long unixTime = System.currentTimeMillis() + ( event.getEventTime() - android.os.SystemClock.uptimeMillis() ); - final int button = pointers.length==1 ? MouseEvent.BUTTON1 : 0; final com.jogamp.newt.event.MouseEvent me1 = new com.jogamp.newt.event.MouseEvent( - type, src, unixTime, - modifiers, x, y, pressure, pointers, clickCount, + nType, src, unixTime, + modifiers, x, y, pressure, pointerIds, clickCount, button, rotation); - if(type == com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED) { + if( com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED == nType ) { return new com.jogamp.newt.event.MouseEvent[] { me1, new com.jogamp.newt.event.MouseEvent( com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_CLICKED, - src, unixTime, modifiers, x, y, pressure, pointers, clickCount, + src, unixTime, modifiers, x, y, pressure, pointerIds, clickCount, button, rotation) }; } else { - return new com.jogamp.newt.event.MouseEvent[] { me1 }; + return new com.jogamp.newt.event.MouseEvent[] { me1 }; } } return null; // no mapping .. @@ -238,6 +399,58 @@ public class AndroidNewtEventFactory { } sb.append("]" ); return sb.toString(); - } + } + + class NewtGestureListener implements android.view.GestureDetector.OnGestureListener { + private float[] scrollDistance; + + NewtGestureListener() { + scrollDistance = null; + } + + /** Returns non null w/ 2 float values, XY, if storing onScroll's XY distance - otherwise null */ + public float[] getScrollDistanceXY() { + float[] sd = scrollDistance; + scrollDistance = null; + return sd; + } + + // + // Simple feedback + // + + @Override + public void onShowPress(android.view.MotionEvent e) { + } + + @Override + public void onLongPress(android.view.MotionEvent e) { + } + + @Override + public boolean onSingleTapUp(android.view.MotionEvent e) { + return false; + } + + // + // Consumed or not consumed ! + // + + @Override + public boolean onDown(android.view.MotionEvent e) { + return false; + } + + @Override + public boolean onScroll(android.view.MotionEvent e1, android.view.MotionEvent e2, float distanceX, float distanceY) { + scrollDistance = new float[] { distanceX, distanceY }; + return true; + } + + @Override + public boolean onFling(android.view.MotionEvent e1, android.view.MotionEvent e2, float velocityX, float velocityY) { + return false; + } + }; } diff --git a/src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventTranslator.java b/src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventTranslator.java new file mode 100644 index 000000000..ee0c8f8b1 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventTranslator.java @@ -0,0 +1,55 @@ +package jogamp.newt.driver.android.event; + +import jogamp.newt.driver.android.WindowDriver; +import android.view.View; + +public class AndroidNewtEventTranslator implements View.OnKeyListener, View.OnTouchListener, View.OnFocusChangeListener, View.OnGenericMotionListener { + private final WindowDriver newtWindow; + private final AndroidNewtEventFactory factory; + + public AndroidNewtEventTranslator(WindowDriver newtWindow, android.content.Context context, android.os.Handler handler) { + this.newtWindow = newtWindow; + this.factory = new AndroidNewtEventFactory(context, handler); + } + + private final boolean processTouchMotionEvents(View v, android.view.MotionEvent event, boolean isOnTouchEvent) { + final com.jogamp.newt.event.MouseEvent[] newtEvents = factory.createMouseEvents(isOnTouchEvent, event, newtWindow); + if(null != newtEvents) { + newtWindow.focusChanged(false, true); + for(int i=0; iCallVoidMethod(env, javaWindow, sendMouseEventID, (ptr->select==0) ? (jint) EVENT_MOUSE_RELEASED : (jint) EVENT_MOUSE_PRESSED, (jint) 0, - (jint) ptr->x, (jint) ptr->y, 1, 0); + (jint) ptr->x, (jint) ptr->y, 1, 0.0f); } else { DBG_PRINT( "event mouse: src: %d, s:%p, i:0x%X (%d,%d)\n", userData, ptr->select, ptr->index, ptr->x, ptr->y); (*env)->CallVoidMethod(env, javaWindow, sendMouseEventID, (jint) EVENT_MOUSE_MOVED, 0, - (jint) ptr->x, (jint) ptr->y, 0, 0); + (jint) ptr->x, (jint) ptr->y, 0, 0.0f); } } break; @@ -193,7 +193,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_kd_WindowDriver_initIDs sizeChangedID = (*env)->GetMethodID(env, clazz, "sizeChanged", "(ZIIZ)V"); visibleChangedID = (*env)->GetMethodID(env, clazz, "visibleChanged", "(ZZ)V"); windowDestroyNotifyID = (*env)->GetMethodID(env, clazz, "windowDestroyNotify", "(Z)Z"); - sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(IIIIII)V"); + sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(IIIIIF)V"); sendKeyEventID = (*env)->GetMethodID(env, clazz, "sendKeyEvent", "(IIIC)V"); if (windowCreatedID == NULL || sizeChangedID == NULL || diff --git a/src/newt/native/NewtMacWindow.m b/src/newt/native/NewtMacWindow.m index b89b5c21d..5b826566b 100644 --- a/src/newt/native/NewtMacWindow.m +++ b/src/newt/native/NewtMacWindow.m @@ -36,36 +36,49 @@ #import "KeyEvent.h" #import "MouseEvent.h" -jint GetDeltaY(NSEvent *event, jint javaMods) { - CGFloat deltaY = 0.0; +#include + +static jfloat GetDelta(NSEvent *event, jint javaMods[]) { CGEventRef cgEvent = [event CGEvent]; + CGFloat deltaY = 0.0; + CGFloat deltaX = 0.0; + CGFloat delta = 0.0; if (CGEventGetIntegerValueField(cgEvent, kCGScrollWheelEventIsContinuous)) { // mouse pad case - deltaY = - CGEventGetIntegerValueField(cgEvent, kCGScrollWheelEventPointDeltaAxis1); - // fprintf(stderr, "WHEEL/PAD: %lf\n", (double)deltaY); + deltaX = CGEventGetIntegerValueField(cgEvent, kCGScrollWheelEventPointDeltaAxis2); + deltaY = CGEventGetIntegerValueField(cgEvent, kCGScrollWheelEventPointDeltaAxis1); + // fprintf(stderr, "WHEEL/PAD: %lf/%lf - 0x%X\n", (double)deltaX, (double)deltaY, javaMods[0]); + if( fabsf(deltaX) > fabsf(deltaY) ) { + javaMods[0] |= EVENT_SHIFT_MASK; + delta = deltaX; + } else { + delta = deltaY; + } } else { // traditional mouse wheel case + deltaX = [event deltaX]; deltaY = [event deltaY]; - // fprintf(stderr, "WHEEL/TRAD: %lf\n", (double)deltaY); - if (deltaY == 0.0 && (javaMods & EVENT_SHIFT_MASK) != 0) { + // fprintf(stderr, "WHEEL/TRACK: %lf/%lf - 0x%X\n", (double)deltaX, (double)deltaY, javaMods[0]); + if (deltaY == 0.0 && (javaMods[0] & EVENT_SHIFT_MASK) != 0) { // shift+vertical wheel scroll produces horizontal scroll // we convert it to vertical - deltaY = [event deltaX]; + delta = deltaX; + } else { + delta = deltaY; } - if (-1.0 < deltaY && deltaY < 1.0) { - deltaY *= 10.0; + if (-1.0 < delta && delta < 1.0) { + delta *= 10.0; } else { - if (deltaY < 0.0) { - deltaY = deltaY - 0.5f; + if (delta < 0.0) { + delta = delta - 0.5f; } else { - deltaY = deltaY + 0.5f; + delta = delta + 0.5f; } } } - // fprintf(stderr, "WHEEL/res: %d\n", (int)deltaY); - return (jint) deltaY; + // fprintf(stderr, "WHEEL/RES: %lf - 0x%X\n", (double)delta, javaMods[0]); + return (jfloat) delta; } static jmethodID enqueueMouseEventID = NULL; @@ -328,8 +341,8 @@ static jmethodID windowRepaintID = NULL; + (BOOL) initNatives: (JNIEnv*) env forClass: (jclass) clazz { - enqueueMouseEventID = (*env)->GetMethodID(env, clazz, "enqueueMouseEvent", "(ZIIIIII)V"); - sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(IIIIII)V"); + enqueueMouseEventID = (*env)->GetMethodID(env, clazz, "enqueueMouseEvent", "(ZIIIIIF)V"); + sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(IIIIIF)V"); enqueueKeyEventID = (*env)->GetMethodID(env, clazz, "enqueueKeyEvent", "(ZIIIC)V"); sendKeyEventID = (*env)->GetMethodID(env, clazz, "sendKeyEvent", "(IIIC)V"); sizeChangedID = (*env)->GetMethodID(env, clazz, "sizeChanged", "(ZIIZ)V"); @@ -686,15 +699,16 @@ static jint mods2JavaMods(NSUInteger mods) DBG_PRINT("sendMouseEvent: null JNIEnv\n"); return; } - jint javaMods = mods2JavaMods([event modifierFlags]); + jint javaMods[] = { 0 } ; + javaMods[0] = mods2JavaMods([event modifierFlags]); // convert to 1-based button number (or use zero if no button is involved) // TODO: detect mouse button when mouse wheel scrolled jint javaButtonNum = 0; - jint scrollDeltaY = 0; + jfloat scrollDeltaY = 0.0f; switch ([event type]) { case NSScrollWheel: { - scrollDeltaY = GetDeltaY(event, javaMods); + scrollDeltaY = GetDelta(event, javaMods); javaButtonNum = 1; break; } @@ -727,12 +741,12 @@ static jint mods2JavaMods(NSUInteger mods) #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, javaWindowObject, sendMouseEventID, - evType, javaMods, + evType, javaMods[0], (jint) location.x, (jint) location.y, javaButtonNum, scrollDeltaY); #else (*env)->CallVoidMethod(env, javaWindowObject, enqueueMouseEventID, JNI_FALSE, - evType, javaMods, + evType, javaMods[0], (jint) location.x, (jint) location.y, javaButtonNum, scrollDeltaY); #endif diff --git a/src/newt/native/WindowsWindow.c b/src/newt/native/WindowsWindow.c index b20717acc..17b93cfce 100644 --- a/src/newt/native/WindowsWindow.c +++ b/src/newt/native/WindowsWindow.c @@ -53,9 +53,13 @@ #define WM_MOUSEWHEEL 0x020A #endif //WM_MOUSEWHEEL -#ifndef WHEEL_DELTA -#define WHEEL_DELTA 120 -#endif //WHEEL_DELTA +#ifndef WM_MOUSEHWHEEL +#define WM_MOUSEHWHEEL 0x020E +#endif //WM_MOUSEHWHEEL + +#ifndef WHEEL_DELTAf +#define WHEEL_DELTAf (120.0f) +#endif //WHEEL_DELTAf #ifndef WHEEL_PAGESCROLL #define WHEEL_PAGESCROLL (UINT_MAX) @@ -64,6 +68,23 @@ #ifndef GET_WHEEL_DELTA_WPARAM // defined for (_WIN32_WINNT >= 0x0500) #define GET_WHEEL_DELTA_WPARAM(wParam) ((short)HIWORD(wParam)) #endif +#ifndef GET_KEYSTATE_WPARAM +#define GET_KEYSTATE_WPARAM(wParam) ((short)LOWORD(wParam)) +#endif + +#ifndef WM_HSCROLL +#define WM_HSCROLL 0x0114 +#endif +#ifndef WM_VSCROLL +#define WM_VSCROLL 0x0115 +#endif + +#ifndef WH_MOUSE +#define WH_MOUSE 7 +#endif +#ifndef WH_MOUSE_LL +#define WH_MOUSE_LL 14 +#endif #ifndef MONITOR_DEFAULTTONULL #define MONITOR_DEFAULTTONULL 0 @@ -796,6 +817,72 @@ static void WmSize(JNIEnv *env, jobject window, HWND wnd, UINT type) (*env)->CallVoidMethod(env, window, sizeChangedID, JNI_FALSE, w, h, JNI_FALSE); } +#ifdef TEST_MOUSE_HOOKS + +static HHOOK hookLLMP; +static HHOOK hookMP; + +static LRESULT CALLBACK HookLowLevelMouseProc (int code, WPARAM wParam, LPARAM lParam) +{ + // if (code == HC_ACTION) + { + const char *msg; + char msg_buff[128]; + switch (wParam) + { + case WM_LBUTTONDOWN: msg = "WM_LBUTTONDOWN"; break; + case WM_LBUTTONUP: msg = "WM_LBUTTONUP"; break; + case WM_MOUSEMOVE: msg = "WM_MOUSEMOVE"; break; + case WM_MOUSEWHEEL: msg = "WM_MOUSEWHEEL"; break; + case WM_MOUSEHWHEEL: msg = "WM_MOUSEHWHEEL"; break; + case WM_RBUTTONDOWN: msg = "WM_RBUTTONDOWN"; break; + case WM_RBUTTONUP: msg = "WM_RBUTTONUP"; break; + default: + sprintf(msg_buff, "Unknown msg: %u", wParam); + msg = msg_buff; + break; + }//switch + + const MSLLHOOKSTRUCT *p = (MSLLHOOKSTRUCT*)lParam; + DBG_PRINT("**** LLMP: Code: 0x%X: %s - %d/%d\n", code, msg, (int)p->pt.x, (int)p->pt.y); + //} else { + // DBG_PRINT("**** LLMP: CODE: 0x%X\n", code); + } + return CallNextHookEx(hookLLMP, code, wParam, lParam); +} + +static LRESULT CALLBACK HookMouseProc (int code, WPARAM wParam, LPARAM lParam) +{ + // if (code == HC_ACTION) + { + const char *msg; + char msg_buff[128]; + switch (wParam) + { + case WM_LBUTTONDOWN: msg = "WM_LBUTTONDOWN"; break; + case WM_LBUTTONUP: msg = "WM_LBUTTONUP"; break; + case WM_MOUSEMOVE: msg = "WM_MOUSEMOVE"; break; + case WM_MOUSEWHEEL: msg = "WM_MOUSEWHEEL"; break; + case WM_MOUSEHWHEEL: msg = "WM_MOUSEHWHEEL"; break; + case WM_RBUTTONDOWN: msg = "WM_RBUTTONDOWN"; break; + case WM_RBUTTONUP: msg = "WM_RBUTTONUP"; break; + default: + sprintf(msg_buff, "Unknown msg: %u", wParam); + msg = msg_buff; + break; + }//switch + + const MOUSEHOOKSTRUCT *p = (MOUSEHOOKSTRUCT*)lParam; + DBG_PRINT("**** MP: Code: 0x%X: %s - hwnd %p, %d/%d\n", code, msg, p->hwnd, (int)p->pt.x, (int)p->pt.y); + //} else { + // DBG_PRINT("**** MP: CODE: 0x%X\n", code); + } + return CallNextHookEx(hookMP, code, wParam, lParam); +} + +#endif + + static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam) { LRESULT res = 0; int useDefWindowProc = 0; @@ -817,7 +904,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP env = wud->jenv; window = wud->jinstance; - // DBG_PRINT("*** WindowsWindow: thread 0x%X - window %p -> %p, 0x%X %d/%d\n", (int)GetCurrentThreadId(), wnd, window, message, (int)LOWORD(lParam), (int)HIWORD(lParam)); + // DBG_PRINT("*** WindowsWindow: thread 0x%X - window %p -> %p, msg 0x%X, %d/%d\n", (int)GetCurrentThreadId(), wnd, window, message, (int)LOWORD(lParam), (int)HIWORD(lParam)); if (NULL==window || NULL==env) { return DefWindowProc(wnd, message, wParam, lParam); @@ -921,7 +1008,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP (jint) EVENT_MOUSE_PRESSED, GetModifiers( FALSE, 0 ), (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam), - (jint) 1, (jint) 0); + (jint) 1, (jfloat) 0.0f); useDefWindowProc = 1; break; @@ -930,7 +1017,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP (jint) EVENT_MOUSE_RELEASED, GetModifiers( FALSE, 0 ), (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam), - (jint) 1, (jint) 0); + (jint) 1, (jfloat) 0.0f); useDefWindowProc = 1; break; @@ -941,7 +1028,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP (jint) EVENT_MOUSE_PRESSED, GetModifiers( FALSE, 0 ), (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam), - (jint) 2, (jint) 0); + (jint) 2, (jfloat) 0.0f); useDefWindowProc = 1; break; @@ -950,7 +1037,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP (jint) EVENT_MOUSE_RELEASED, GetModifiers( FALSE, 0 ), (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam), - (jint) 2, (jint) 0); + (jint) 2, (jfloat) 0.0f); useDefWindowProc = 1; break; @@ -961,7 +1048,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP (jint) EVENT_MOUSE_PRESSED, GetModifiers( FALSE, 0 ), (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam), - (jint) 3, (jint) 0); + (jint) 3, (jfloat) 0.0f); useDefWindowProc = 1; break; @@ -970,7 +1057,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP (jint) EVENT_MOUSE_RELEASED, GetModifiers( FALSE, 0 ), (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam), - (jint) 3, (jint) 0); + (jint) 3, (jfloat) 0.0f); useDefWindowProc = 1; break; @@ -979,7 +1066,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP (jint) EVENT_MOUSE_MOVED, GetModifiers( FALSE, 0 ), (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam), - (jint) 0, (jint) 0); + (jint) 0, (jfloat) 0.0f); useDefWindowProc = 1; break; case WM_MOUSELEAVE: @@ -987,24 +1074,64 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP (jint) EVENT_MOUSE_EXITED, 0, (jint) -1, (jint) -1, // fake - (jint) 0, (jint) 0); + (jint) 0, (jfloat) 0.0f); useDefWindowProc = 1; break; // Java synthesizes EVENT_MOUSE_ENTERED - case WM_MOUSEWHEEL: { + case WM_HSCROLL: { // Only delivered if windows has WS_HSCROLL, hence dead code! + int sb = LOWORD(wParam); + int modifiers = GetModifiers( FALSE, 0 ) | EVENT_SHIFT_MASK; + float rotation; + switch(sb) { + case SB_LINELEFT: + rotation = 1.0f; + break; + case SB_PAGELEFT: + rotation = 2.0f; + break; + case SB_LINERIGHT: + rotation = -1.0f; + break; + case SB_PAGERIGHT: + rotation = -1.0f; + break; + } + DBG_PRINT("*** WindowsWindow: WM_HSCROLL 0x%X, rotation %f, mods 0x%X\n", sb, rotation, modifiers); + (*env)->CallVoidMethod(env, window, sendMouseEventID, + (jint) EVENT_MOUSE_WHEEL_MOVED, + modifiers, + (jint) 0, (jint) 0, + (jint) 1, (jfloat) rotation); + useDefWindowProc = 1; + break; + } + case WM_MOUSEHWHEEL: /* tilt */ + case WM_MOUSEWHEEL: /* rotation */ { // need to convert the coordinates to component-relative int x = GET_X_LPARAM(lParam); int y = GET_Y_LPARAM(lParam); + int modifiers = GetModifiers( FALSE, 0 ); + float rotationOrTilt = (float)(GET_WHEEL_DELTA_WPARAM(wParam))/WHEEL_DELTAf; + int vKeys = GET_KEYSTATE_WPARAM(wParam); POINT eventPt; eventPt.x = x; eventPt.y = y; ScreenToClient(wnd, &eventPt); + + if( WM_MOUSEHWHEEL == message ) { + modifiers |= EVENT_SHIFT_MASK; + DBG_PRINT("*** WindowsWindow: WM_MOUSEHWHEEL %d/%d, tilt %f, vKeys 0x%X, mods 0x%X\n", + (int)eventPt.x, (int)eventPt.y, rotationOrTilt, vKeys, modifiers); + } else { + DBG_PRINT("*** WindowsWindow: WM_MOUSEWHEEL %d/%d, rotation %f, vKeys 0x%X, mods 0x%X\n", + (int)eventPt.x, (int)eventPt.y, rotationOrTilt, vKeys, modifiers); + } (*env)->CallVoidMethod(env, window, sendMouseEventID, (jint) EVENT_MOUSE_WHEEL_MOVED, - GetModifiers( FALSE, 0 ), + modifiers, (jint) eventPt.x, (jint) eventPt.y, - (jint) 1, (jint) (GET_WHEEL_DELTA_WPARAM(wParam)/120.0f)); + (jint) 1, (jfloat) rotationOrTilt); useDefWindowProc = 1; break; } @@ -1057,8 +1184,9 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP useDefWindowProc = 1; } - if (useDefWindowProc) + if (useDefWindowProc) { return DefWindowProc(wnd, message, wParam, lParam); + } return res; } @@ -1195,7 +1323,7 @@ static void NewtScreen_scanDisplayDevices() { int i = 0; LPCTSTR name; while(NULL != (name = NewtScreen_getDisplayDeviceName(&device, i))) { - fprintf(stderr, "*** [%d]: <%s> active %d\n", i, name, ( 0 != ( device.StateFlags & DISPLAY_DEVICE_ACTIVE ) ) ); + DBG_PRINT("*** [%d]: <%s> active %d\n", i, name, ( 0 != ( device.StateFlags & DISPLAY_DEVICE_ACTIVE ) ) ); i++; } }*/ @@ -1335,7 +1463,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_setScree * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowDriver_initIDs0 - (JNIEnv *env, jclass clazz) + (JNIEnv *env, jclass clazz, jlong hInstance) { NewtCommon_init(env); @@ -1346,8 +1474,8 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowDriver_initIDs0 visibleChangedID = (*env)->GetMethodID(env, clazz, "visibleChanged", "(ZZ)V"); windowDestroyNotifyID = (*env)->GetMethodID(env, clazz, "windowDestroyNotify", "(Z)Z"); windowRepaintID = (*env)->GetMethodID(env, clazz, "windowRepaint", "(ZIIII)V"); - enqueueMouseEventID = (*env)->GetMethodID(env, clazz, "enqueueMouseEvent", "(ZIIIIII)V"); - sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(IIIIII)V"); + enqueueMouseEventID = (*env)->GetMethodID(env, clazz, "enqueueMouseEvent", "(ZIIIIIF)V"); + sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(IIIIIF)V"); enqueueKeyEventID = (*env)->GetMethodID(env, clazz, "enqueueKeyEvent", "(ZIIIC)V"); sendKeyEventID = (*env)->GetMethodID(env, clazz, "sendKeyEvent", "(IIIC)V"); requestFocusID = (*env)->GetMethodID(env, clazz, "requestFocus", "(Z)V"); @@ -1367,6 +1495,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowDriver_initIDs0 return JNI_FALSE; } BuildDynamicKeyMapTable(); + return JNI_TRUE; } @@ -1412,6 +1541,8 @@ static void NewtWindow_setVisiblePosSize(HWND hwnd, BOOL atop, BOOL visible, UpdateWindow(hwnd); } +#define WS_DEFAULT_STYLES (WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_TABSTOP) + /* * Class: jogamp_newt_driver_windows_WindowDriver * Method: CreateWindow @@ -1425,7 +1556,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowDriver_CreateWindo HWND parentWindow = (HWND) (intptr_t) parent; const TCHAR* wndClassName = NULL; const TCHAR* wndName = NULL; - DWORD windowStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE | WS_TABSTOP; + DWORD windowStyle = WS_DEFAULT_STYLES | WS_VISIBLE; int x=(int)jx, y=(int)jy; int width=(int)defaultWidth, height=(int)defaultHeight; HWND window = NULL; @@ -1516,6 +1647,12 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowDriver_CreateWindo (*env)->ReleaseStringUTFChars(env, jWndName, wndName); #endif +#ifdef TEST_MOUSE_HOOKS + hookLLMP = SetWindowsHookEx(WH_MOUSE_LL, &HookLowLevelMouseProc, (HINSTANCE) (intptr_t) hInstance, 0); + hookMP = SetWindowsHookEx(WH_MOUSE_LL, &HookMouseProc, (HINSTANCE) (intptr_t) hInstance, 0); + DBG_PRINT("**** LLMP Hook %p, MP Hook %p\n", hookLLMP, hookMP); +#endif + return (jlong) (intptr_t) window; } @@ -1563,7 +1700,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowDriver_reconfigureW { HWND hwndP = (HWND) (intptr_t) parent; HWND hwnd = (HWND) (intptr_t) window; - DWORD windowStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN ; + DWORD windowStyle = WS_DEFAULT_STYLES; BOOL styleChange = TST_FLAG_CHANGE_DECORATION(flags) || TST_FLAG_CHANGE_FULLSCREEN(flags) || TST_FLAG_CHANGE_PARENTING(flags) ; DBG_PRINT( "*** WindowsWindow: reconfigureWindow0 parent %p, window %p, %d/%d %dx%d, parentChange %d, hasParent %d, decorationChange %d, undecorated %d, fullscreenChange %d, fullscreen %d, alwaysOnTopChange %d, alwaysOnTop %d, visibleChange %d, visible %d -> styleChange %d\n", diff --git a/src/newt/native/X11Display.c b/src/newt/native/X11Display.c index 3f34a16b6..85b3a14c7 100644 --- a/src/newt/native/X11Display.c +++ b/src/newt/native/X11Display.c @@ -218,8 +218,8 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_initIDs0 reparentNotifyID = (*env)->GetMethodID(env, X11NewtWindowClazz, "reparentNotify", "(J)V"); windowDestroyNotifyID = (*env)->GetMethodID(env, X11NewtWindowClazz, "windowDestroyNotify", "(Z)Z"); windowRepaintID = (*env)->GetMethodID(env, X11NewtWindowClazz, "windowRepaint", "(ZIIII)V"); - enqueueMouseEventID = (*env)->GetMethodID(env, X11NewtWindowClazz, "enqueueMouseEvent", "(ZIIIIII)V"); - sendMouseEventID = (*env)->GetMethodID(env, X11NewtWindowClazz, "sendMouseEvent", "(IIIIII)V"); + enqueueMouseEventID = (*env)->GetMethodID(env, X11NewtWindowClazz, "enqueueMouseEvent", "(ZIIIIIF)V"); + sendMouseEventID = (*env)->GetMethodID(env, X11NewtWindowClazz, "sendMouseEvent", "(IIIIIF)V"); enqueueKeyEventID = (*env)->GetMethodID(env, X11NewtWindowClazz, "enqueueKeyEvent", "(ZIIIC)V"); sendKeyEventID = (*env)->GetMethodID(env, X11NewtWindowClazz, "sendKeyEvent", "(IIIC)V"); requestFocusID = (*env)->GetMethodID(env, X11NewtWindowClazz, "requestFocus", "(Z)V"); @@ -416,33 +416,33 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessage #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_PRESSED, modifiers, - (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/); + (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_PRESSED, modifiers, - (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/); + (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0.0f /*rotation*/); #endif break; case ButtonRelease: #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_RELEASED, modifiers, - (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/); + (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_RELEASED, modifiers, - (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/); + (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0.0f /*rotation*/); #endif break; case MotionNotify: #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_MOVED, modifiers, - (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_MOVED, modifiers, - (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0.0f /*rotation*/); #endif break; case EnterNotify: @@ -450,11 +450,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessage #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_ENTERED, modifiers, - (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_ENTERED, modifiers, - (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0.0f /*rotation*/); #endif break; case LeaveNotify: @@ -462,11 +462,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessage #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_EXITED, modifiers, - (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_EXITED, modifiers, - (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0.0f /*rotation*/); #endif break; case KeyPress: diff --git a/src/newt/native/X11Event.c b/src/newt/native/X11Event.c index 079203400..770f60e8f 100644 --- a/src/newt/native/X11Event.c +++ b/src/newt/native/X11Event.c @@ -103,33 +103,33 @@ void X11EventPoll(JNIEnv *env, jobject obj, Display *dpy, jlong javaObjectAtom, #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_PRESSED, modifiers, - (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/); + (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_PRESSED, modifiers, - (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/); + (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0.0f /*rotation*/); #endif break; case ButtonRelease: #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_RELEASED, modifiers, - (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/); + (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_RELEASED, modifiers, - (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/); + (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0.0f /*rotation*/); #endif break; case MotionNotify: #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_MOVED, modifiers, - (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_MOVED, modifiers, - (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0.0f /*rotation*/); #endif break; case EnterNotify: @@ -137,11 +137,11 @@ void X11EventPoll(JNIEnv *env, jobject obj, Display *dpy, jlong javaObjectAtom, #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_ENTERED, modifiers, - (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_ENTERED, modifiers, - (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0.0f /*rotation*/); #endif break; case LeaveNotify: @@ -149,11 +149,11 @@ void X11EventPoll(JNIEnv *env, jobject obj, Display *dpy, jlong javaObjectAtom, #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_EXITED, modifiers, - (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_EXITED, modifiers, - (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); + (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0.0f /*rotation*/); #endif break; case KeyPress: diff --git a/src/newt/native/XCBEvent.c b/src/newt/native/XCBEvent.c index 77a3380db..f067f4b7a 100644 --- a/src/newt/native/XCBEvent.c +++ b/src/newt/native/XCBEvent.c @@ -129,11 +129,11 @@ void XCBEventPoll(JNIEnv *env, jobject obj, Display *dpy, jlong javaObjectAtom, #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_PRESSED, modifiers, - (jint) _evt->event_x, (jint) _evt->event_y, (jint) _evt->state, 0 /*rotation*/); + (jint) _evt->event_x, (jint) _evt->event_y, (jint) _evt->state, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_PRESSED, modifiers, - (jint) _evt->event_x, (jint) _evt->event_y, (jint) _evt->state, 0 /*rotation*/); + (jint) _evt->event_x, (jint) _evt->event_y, (jint) _evt->state, 0.0f /*rotation*/); #endif } break; case XCB_BUTTON_RELEASE: { @@ -141,11 +141,11 @@ void XCBEventPoll(JNIEnv *env, jobject obj, Display *dpy, jlong javaObjectAtom, #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_RELEASED, modifiers, - (jint) _evt->event_x, (jint) _evt->event_y, (jint) _evt->state, 0 /*rotation*/); + (jint) _evt->event_x, (jint) _evt->event_y, (jint) _evt->state, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_RELEASED, modifiers, - (jint) _evt->event_x, (jint) _evt->event_y, (jint) _evt->state, 0 /*rotation*/); + (jint) _evt->event_x, (jint) _evt->event_y, (jint) _evt->state, 0.0f /*rotation*/); #endif } break; case XCB_MOTION_NOTIFY: { @@ -153,11 +153,11 @@ void XCBEventPoll(JNIEnv *env, jobject obj, Display *dpy, jlong javaObjectAtom, #ifdef USE_SENDIO_DIRECT (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_MOVED, modifiers, - (jint) _evt->event_x, (jint) _evt->event_y, (jint)0, 0 /*rotation*/); + (jint) _evt->event_x, (jint) _evt->event_y, (jint)0, 0.0f /*rotation*/); #else (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_MOVED, modifiers, - (jint) _evt->event_x, (jint) _evt->event_y, (jint)0, 0 /*rotation*/); + (jint) _evt->event_x, (jint) _evt->event_y, (jint)0, 0.0f /*rotation*/); #endif } break; case XCB_KEY_PRESS: { diff --git a/src/newt/native/bcm_vc_iv.c b/src/newt/native/bcm_vc_iv.c index 0093da437..bbddf764b 100644 --- a/src/newt/native/bcm_vc_iv.c +++ b/src/newt/native/bcm_vc_iv.c @@ -117,7 +117,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_bcm_vc_iv_WindowDriver_initID sizeChangedID = (*env)->GetMethodID(env, clazz, "sizeChanged", "(ZIIZ)V"); visibleChangedID = (*env)->GetMethodID(env, clazz, "visibleChanged", "(ZZ)V"); windowDestroyNotifyID = (*env)->GetMethodID(env, clazz, "windowDestroyNotify", "(Z)Z"); - sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(IIIIII)V"); + sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(IIIIIF)V"); sendKeyEventID = (*env)->GetMethodID(env, clazz, "sendKeyEvent", "(IIIC)V"); if (windowCreatedID == NULL || sizeChangedID == NULL || diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java index cc5aae99e..43a393495 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java @@ -55,6 +55,7 @@ public class GearsES2 implements GLEventListener { private GLUniformData pmvMatrixUniform = null; private GLUniformData colorU = null; private float view_rotx = 20.0f, view_roty = 30.0f, view_rotz = 0.0f; + private float panX = 0.0f, panY = 0.0f; private GearsObjectES2 gear1=null, gear2=null, gear3=null; private float angle = 0.0f; private int swapInterval = 0; @@ -302,6 +303,7 @@ public class GearsES2 implements GLEventListener { st.useProgram(gl, true); pmvMatrix.glPushMatrix(); + pmvMatrix.glTranslatef(panX, panY, 0.0f); pmvMatrix.glRotatef(view_rotx, 1.0f, 0.0f, 0.0f); pmvMatrix.glRotatef(view_roty, 0.0f, 1.0f, 0.0f); pmvMatrix.glRotatef(view_rotz, 0.0f, 0.0f, 1.0f); @@ -336,7 +338,32 @@ public class GearsES2 implements GLEventListener { } } - class GearsMouseAdapter extends MouseAdapter { + class GearsMouseAdapter implements MouseListener{ + + @Override + public void mouseClicked(MouseEvent e) { + } + + @Override + public void mouseEntered(MouseEvent e) { + } + + @Override + public void mouseExited(MouseEvent e) { + } + + @Override + public void mouseWheelMoved(MouseEvent e) { + float r = e.getWheelRotation() * 1.0f; + if( e.isShiftDown() ) { + // horizontal + panX -= r; // positive -> left + } else { + // vertical + panY += r; // positive -> up + } + } + public void mousePressed(MouseEvent e) { prevMouseX = e.getX(); prevMouseY = e.getY(); -- cgit v1.2.3 From 85d70b7d38885fa8ba6374aa790d5a296acc8ec1 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 20 Jan 2013 15:05:02 +0100 Subject: Android: Allow selection of native window formats RGBA8888, RGBX8888 and RGB565; Fix HiSilicon/Vivante/Immersion.16 EGLConfig selection (zero depth buffer @ visualID) - NEWT/Android Fix PixelFormat/NativeWindowFormat/VisualID Selection - Fix allows proper selection of native window formats: RGBA8888, RGBX8888 and RGB565 - Selection is performed in 3 steps: 1) @ Construction (non native): SurfaceHolder.setFormat( getSurfaceHolderFormat( caps ) ) 2) @ Native Surface Creation: getANativeWindowFormat( androidFormat) -> ANativeWindow_setBuffersGeometry(..) Note: The set native format is revalidated, i.e. read out via ANativeWindow_getFormat(..). 3) @ EGL Creation: ANativeWindow_getFormat(..) -> fixCaps(..) - simply fixing the chosen caps. - NEWT GLWindow.GLLifecycleHook.resetCounter: - Also reset GLAnimatorControl's counter, if attached. - NEWT WindowImpl -> GLLifecycleHook.resetCounter() calls issued _after_ operation before unlock(). - JOGL/EGLGraphicsConfigurationFactory - Validate whether the visualID matching EGLConfig depth buffer is suitable. On HiSilicon/Vivante/Immersion.16: Depth buffer w/ matching visualID is zero! - NativeWindow/Capabilities.compareTo: Fix alpha comparison --- make/resources/android/AndroidManifest-test.xml | 20 ++++ make/resources/android/res-test/values/strings.xml | 4 + .../opengl/egl/EGLGraphicsConfiguration.java | 11 +- .../egl/EGLGraphicsConfigurationFactory.java | 12 +- .../javax/media/nativewindow/Capabilities.java | 8 +- .../classes/com/jogamp/newt/opengl/GLWindow.java | 4 + src/newt/classes/jogamp/newt/WindowImpl.java | 14 +-- .../jogamp/newt/driver/android/WindowDriver.java | 128 ++++++++++++++------- .../opengl/test/android/NEWTGearsES2Activity.java | 15 ++- .../android/NEWTGearsES2ECTActivityLauncher.java | 75 ++++++++++++ .../NEWTGearsES2RGB565ActivityLauncher.java | 75 ++++++++++++ 11 files changed, 308 insertions(+), 58 deletions(-) create mode 100644 src/test/com/jogamp/opengl/test/android/NEWTGearsES2ECTActivityLauncher.java create mode 100644 src/test/com/jogamp/opengl/test/android/NEWTGearsES2RGB565ActivityLauncher.java (limited to 'src/nativewindow') diff --git a/make/resources/android/AndroidManifest-test.xml b/make/resources/android/AndroidManifest-test.xml index 0817b3450..5357d0a18 100644 --- a/make/resources/android/AndroidManifest-test.xml +++ b/make/resources/android/AndroidManifest-test.xml @@ -28,6 +28,26 @@ + + + + + + + + + + + + GearsES1 GearsES2 GearsES2 + Gears565 + Gears565 + GearsECT + GearsECT GearsES2T GearsES2T GraphUI1p diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java index 71dfe1d0f..b1ffe608e 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java @@ -72,7 +72,14 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple this.chooser = chooser; } - public static EGLGraphicsConfiguration create(GLCapabilitiesImmutable capsRequested, AbstractGraphicsScreen absScreen, int cfgID) { + /** + * @param capsRequested + * @param absScreen + * @param eglConfigID {@link EGL#EGL_CONFIG_ID} for which the config is being created for. + * @return + * @throws GLException if invalid EGL display. + */ + public static EGLGraphicsConfiguration create(GLCapabilitiesImmutable capsRequested, AbstractGraphicsScreen absScreen, int eglConfigID) { final AbstractGraphicsDevice absDevice = absScreen.getDevice(); if(null==absDevice || !(absDevice instanceof EGLGraphicsDevice)) { throw new GLException("GraphicsDevice must be a valid EGLGraphicsDevice"); @@ -81,7 +88,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple if (dpy == EGL.EGL_NO_DISPLAY) { throw new GLException("Invalid EGL display: "+absDevice); } - final long cfg = EGLConfigId2EGLConfig(dpy, cfgID); + final long cfg = EGLConfigId2EGLConfig(dpy, eglConfigID); if(0 < cfg) { final int winattrmask = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsRequested); final EGLGLCapabilities caps = EGLConfig2Capabilities((EGLGraphicsDevice)absDevice, capsRequested.getGLProfile(), cfg, winattrmask, false); diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java index f638ef82b..7e1f8a5a2 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java @@ -411,8 +411,13 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if( VisualIDHolder.VID_UNDEFINED != nativeVisualID ) { List removedCaps = new ArrayList(); for(int i=0; i 0 ) ? alphaBits : 1; - final int rgba = redBits * greenBits * blueBits * a; - - final int xa = ( caps.getAlphaBits() ) > 0 ? caps.getAlphaBits() : 1; - final int xrgba = caps.getRedBits() * caps.getGreenBits() * caps.getBlueBits() * xa; + final int rgba = redBits * greenBits * blueBits * ( alphaBits + 1 ); + + final int xrgba = caps.getRedBits() * caps.getGreenBits() * caps.getBlueBits() * ( caps.getAlphaBits() + 1 ); if(rgba > xrgba) { return 1; diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index 73a4134bd..96d0f6e3b 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -443,6 +443,10 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind System.err.println("GLWindow.resetCounter() "+WindowImpl.getThreadName()); } GLWindow.this.resetFPSCounter(); + final GLAnimatorControl animator = GLWindow.this.getAnimator(); + if( null != animator ) { + animator.resetFPSCounter(); + } } @Override diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index 89c3bada6..88fbfc951 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -707,10 +707,6 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer final RecursiveLock _lock = windowLock; _lock.lock(); try { - if(null!=lifecycleHook) { - lifecycleHook.resetCounter(); - } - if(!visible && null!=childWindows && childWindows.size()>0) { synchronized(childWindowsLock) { for(int i = 0; i < childWindows.size(); i++ ) { @@ -756,6 +752,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer System.err.println("Window setVisible: END ("+getThreadName()+") "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle)+", visible: "+WindowImpl.this.visible+", nativeWindowCreated: "+nativeWindowCreated+", madeVisible: "+madeVisible); } } finally { + if(null!=lifecycleHook) { + lifecycleHook.resetCounter(); + } _lock.unlock(); } if( nativeWindowCreated || madeVisible ) { @@ -1014,10 +1013,6 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer System.err.println("Window.reparent: START ("+getThreadName()+") valid "+isNativeValid()+", windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle)+", visible "+wasVisible+", old parentWindow: "+Display.hashCodeNullSafe(parentWindow)+", new parentWindow: "+Display.hashCodeNullSafe(newParentWindow)+", forceDestroyCreate "+forceDestroyCreate+", "+x+"/"+y+" "+width+"x"+height); } - if(null!=lifecycleHook) { - lifecycleHook.resetCounter(); - } - if(null!=newParentWindow) { // reset position to 0/0 within parent space x = 0; @@ -1211,6 +1206,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer System.err.println("Window.reparentWindow: END-1 ("+getThreadName()+") windowHandle "+toHexString(windowHandle)+", visible: "+visible+", parentWindowHandle "+toHexString(parentWindowHandle)+", parentWindow "+ Display.hashCodeNullSafe(parentWindow)+" "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()); } } finally { + if(null!=lifecycleHook) { + lifecycleHook.resetCounter(); + } _lock.unlock(); } if(wasVisible) { diff --git a/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java index ba5d09759..a85febca0 100644 --- a/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java @@ -71,6 +71,82 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { DisplayDriver.initSingleton(); } + /** + * First stage of selecting an Android PixelFormat, + * at construction via {@link SurfaceHolder#setFormat(int)} + * before native realization! + * + * @param rCaps requested Capabilities + * @return An Android PixelFormat number suitable for {@link SurfaceHolder#setFormat(int)}. + */ + public static final int getSurfaceHolderFormat(CapabilitiesImmutable rCaps) { + int fmt = PixelFormat.UNKNOWN; + + if( !rCaps.isBackgroundOpaque() ) { + fmt = PixelFormat.TRANSLUCENT; + } else if( rCaps.getRedBits()<=5 && + rCaps.getGreenBits()<=6 && + rCaps.getBlueBits()<=5 && + rCaps.getAlphaBits()==0 ) { + fmt = PixelFormat.RGB_565; + } else if( rCaps.getAlphaBits()==0 ) { + fmt = PixelFormat.RGB_888; + } else { + fmt = PixelFormat.RGBA_8888; + } + Log.d(MD.TAG, "getSurfaceHolderFormat: requested: "+rCaps); + Log.d(MD.TAG, "getSurfaceHolderFormat: returned: "+fmt); + + return fmt; + } + + + public static final int NATIVE_WINDOW_FORMAT_RGBA_8888 = 1; + public static final int NATIVE_WINDOW_FORMAT_RGBX_8888 = 2; + public static final int NATIVE_WINDOW_FORMAT_RGB_565 = 4; + + /** + * Second stage of selecting an Android PixelFormat, + * at right after native (surface) realization at {@link Callback2#surfaceChanged(SurfaceHolder, int, int, int)}. + * Selection happens via {@link #setSurfaceVisualID0(long, int)} before native EGL creation. + * + * @param androidPixelFormat An Android PixelFormat delivered via {@link Callback2#surfaceChanged(SurfaceHolder, int, int, int)} params. + * @return A native Android PixelFormat number suitable for {@link #setSurfaceVisualID0(long, int)}. + */ + public static final int getANativeWindowFormat(int androidPixelFormat) { + final int nativePixelFormat; + switch(androidPixelFormat) { + case PixelFormat.RGBA_8888: + case PixelFormat.RGBA_5551: + case PixelFormat.RGBA_4444: + nativePixelFormat = NATIVE_WINDOW_FORMAT_RGBA_8888; + break; + + case PixelFormat.RGBX_8888: + case PixelFormat.RGB_888: + nativePixelFormat = NATIVE_WINDOW_FORMAT_RGBX_8888; + break; + + case PixelFormat.RGB_565: + case PixelFormat.RGB_332: + nativePixelFormat = NATIVE_WINDOW_FORMAT_RGB_565; + break; + default: nativePixelFormat = NATIVE_WINDOW_FORMAT_RGBA_8888; + } + Log.d(MD.TAG, "getANativeWindowFormat: android: "+androidPixelFormat+" -> native "+nativePixelFormat); + return nativePixelFormat; + } + + /** + * Final stage of Android PixelFormat operation, + * match the requested Capabilities w/ Android PixelFormat number. + * This is done at native realization @ {@link Callback2#surfaceChanged(SurfaceHolder, int, int, int)}. + * + * @param matchFormatPrecise + * @param format + * @param rCaps requested Capabilities + * @return The fixed Capabilities + */ public static final CapabilitiesImmutable fixCaps(boolean matchFormatPrecise, int format, CapabilitiesImmutable rCaps) { PixelFormat pf = new PixelFormat(); PixelFormat.getPixelFormatInfo(format, pf); @@ -78,10 +154,10 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { int r, g, b, a; switch(format) { - case PixelFormat.RGBA_8888: r=8; g=8; b=8; a=8; break; - case PixelFormat.RGBX_8888: r=8; g=8; b=8; a=0; break; + case PixelFormat.RGBA_8888: r=8; g=8; b=8; a=8; break; // NATIVE_WINDOW_FORMAT_RGBA_8888 + case PixelFormat.RGBX_8888: r=8; g=8; b=8; a=0; break; // NATIVE_WINDOW_FORMAT_RGBX_8888 case PixelFormat.RGB_888: r=8; g=8; b=8; a=0; break; - case PixelFormat.RGB_565: r=5; g=6; b=5; a=0; break; + case PixelFormat.RGB_565: r=5; g=6; b=5; a=0; break; // NATIVE_WINDOW_FORMAT_RGB_565 case PixelFormat.RGBA_5551: r=5; g=5; b=5; a=1; break; case PixelFormat.RGBA_4444: r=4; g=4; b=4; a=4; break; case PixelFormat.RGB_332: r=3; g=3; b=2; a=0; break; @@ -110,32 +186,6 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { return res; } - public static final int getFormat(CapabilitiesImmutable rCaps) { - int fmt = PixelFormat.UNKNOWN; - - if(!rCaps.isBackgroundOpaque()) { - fmt = PixelFormat.TRANSLUCENT; - } else if(rCaps.getRedBits()<=5 && - rCaps.getGreenBits()<=6 && - rCaps.getBlueBits()<=5 && - rCaps.getAlphaBits()==0) { - fmt = PixelFormat.RGB_565; - } - /* else if(rCaps.getRedBits()<=5 && - rCaps.getGreenBits()<=5 && - rCaps.getBlueBits()<=5 && - rCaps.getAlphaBits()==1) { - fmt = PixelFormat.RGBA_5551; // FIXME: Supported ? - } */ - else { - fmt = PixelFormat.RGBA_8888; - } - Log.d(MD.TAG, "getFormat: requested: "+rCaps); - Log.d(MD.TAG, "getFormat: returned: "+fmt); - - return fmt; - } - public static final boolean isAndroidFormatTransparent(int aFormat) { switch (aFormat) { case PixelFormat.TRANSLUCENT: @@ -195,12 +245,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { final SurfaceHolder sh = androidView.getHolder(); sh.addCallback(WindowDriver.this); - sh.setFormat(getFormat(getRequestedCapabilities())); - } - private final void removeAndroidView() { - final SurfaceHolder sh = androidView.getHolder(); - sh.removeCallback(WindowDriver.this); - androidView = null; + sh.setFormat(getSurfaceHolderFormat(getRequestedCapabilities())); } public final SurfaceView getAndroidView() { return androidView; } @@ -287,6 +332,8 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { } final int nativeVisualID = eglConfig.getVisualID(VisualIDHolder.VIDType.NATIVE); Log.d(MD.TAG, "nativeVisualID 0x"+Integer.toHexString(nativeVisualID)); + Log.d(MD.TAG, "requestedCaps: "+eglConfig.getRequestedCapabilities()); + Log.d(MD.TAG, "chosenCaps : "+eglConfig.getChosenCapabilities()); if(VisualIDHolder.VID_UNDEFINED != nativeVisualID) { setSurfaceVisualID0(surfaceHandle, nativeVisualID); } @@ -334,16 +381,11 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { if( null != viewGroup) { viewGroup.post(new Runnable() { public void run() { - if(null == androidView) { - final Context ctx = StaticContext.getContext(); - setupAndroidView(ctx); - } viewGroup.removeView(androidView); Log.d(MD.TAG, "closeNativeImpl: removed from static ViewGroup - on thread "+Thread.currentThread().getName()); } }); } } - removeAndroidView(); } surface = null; @@ -504,7 +546,11 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { surface = aHolder.getSurface(); surfaceHandle = getSurfaceHandle0(surface); acquire0(surfaceHandle); + final int aNativeWindowFormat = getANativeWindowFormat(androidFormat); + setSurfaceVisualID0(surfaceHandle, aNativeWindowFormat); nativeFormat = getSurfaceVisualID0(surfaceHandle); + Log.d(MD.TAG, "surfaceChanged: androidFormat "+androidFormat+" -- (set-native "+aNativeWindowFormat+") --> nativeFormat "+nativeFormat); + final int nWidth = getWidth0(surfaceHandle); final int nHeight = getHeight0(surfaceHandle); capsByFormat = (GLCapabilitiesImmutable) fixCaps(true /* matchFormatPrecise */, nativeFormat, getRequestedCapabilities()); @@ -560,7 +606,9 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { // protected static native boolean initIDs0(); protected static native long getSurfaceHandle0(Surface surface); + /** Return the native window format via ANativeWindow_getFormat(..). */ protected static native int getSurfaceVisualID0(long surfaceHandle); + /** Set the native window format via ANativeWindow_setBuffersGeometry(..). */ protected static native void setSurfaceVisualID0(long surfaceHandle, int nativeVisualID); protected static native int getWidth0(long surfaceHandle); protected static native int getHeight0(long surfaceHandle); diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java index 4468868f6..e782ac75f 100644 --- a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java +++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java @@ -47,6 +47,9 @@ import android.util.Log; public class NEWTGearsES2Activity extends NewtBaseActivity { static String TAG = "NEWTGearsES2Activity"; + static final String forceRGBA5650 = "demo.force.rgba5650"; + static final String forceECT = "demo.force.ect"; + @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate - 0"); @@ -54,6 +57,11 @@ public class NEWTGearsES2Activity extends NewtBaseActivity { // create GLWindow (-> incl. underlying NEWT Display, Screen & Window) GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GLES2)); + if( null != System.getProperty(forceRGBA5650) ) { + Log.d(TAG, "forceRGBA5650"); + caps.setRedBits(5); caps.setGreenBits(6); caps.setBlueBits(5); + } + Log.d(TAG, "req caps: "+caps); GLWindow glWindow = GLWindow.create(caps); glWindow.setFullscreen(true); @@ -81,6 +89,11 @@ public class NEWTGearsES2Activity extends NewtBaseActivity { setAnimator(animator); // glWindow.setSkipContextReleaseThread(animator.getThread()); + if( null != System.getProperty(forceECT) ) { + Log.d(TAG, "forceECT"); + animator.setExclusiveContext(true); + } + glWindow.setVisible(true); animator.setUpdateFPSFrames(60, System.err); @@ -88,5 +101,5 @@ public class NEWTGearsES2Activity extends NewtBaseActivity { glWindow.resetFPSCounter(); Log.d(TAG, "onCreate - X"); - } + } } diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2ECTActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2ECTActivityLauncher.java new file mode 100644 index 000000000..c54aa0fa6 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2ECTActivityLauncher.java @@ -0,0 +1,75 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.test.android; + +import java.util.Arrays; +import java.util.List; + +import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties; + +public class NEWTGearsES2ECTActivityLauncher extends LauncherUtil.BaseActivityLauncher { + + static String demo = "com.jogamp.opengl.test.android.NEWTGearsES2Activity"; + // static String[] pkgs = new String[] { "com.jogamp.common", "javax.media.opengl", "com.jogamp.opengl.test" }; + static String[] pkgs = new String[] { "com.jogamp.opengl.test" }; + + @Override + public void init() { + final OrderedProperties props = getProperties(); + // props.setProperty("jogamp.debug.JNILibLoader", "true"); + // props.setProperty("jogamp.debug.NativeLibrary", "true"); + // props.setProperty("jogamp.debug.IOUtil", "true"); + // properties.setProperty("jogamp.debug.NativeLibrary.Lookup", "true"); + // props.setProperty("nativewindow.debug", "all"); + props.setProperty("nativewindow.debug.GraphicsConfiguration", "true"); + // props.setProperty("jogl.debug", "all"); + // properties.setProperty("jogl.debug.GLProfile", "true"); + // props.setProperty("jogl.debug.GLDrawable", "true"); + props.setProperty("jogl.debug.GLContext", "true"); + props.setProperty("jogl.debug.GLSLCode", "true"); + // props.setProperty("jogl.debug.CapabilitiesChooser", "true"); + // props.setProperty("jogl.debug.GLSLState", "true"); + // props.setProperty("jogl.debug.DebugGL", "true"); + // props.setProperty("jogl.debug.TraceGL", "true"); + // props.setProperty("newt.debug", "all"); + props.setProperty("newt.debug.Window", "true"); + props.setProperty("newt.debug.Window.MouseEvent", "true"); + props.setProperty("newt.debug.Window.KeyEvent", "true"); + + props.setProperty("demo.force.ect", "true"); + } + + @Override + public String getActivityName() { + return demo; + } + @Override + public List getPackages() { + return Arrays.asList(pkgs); + } +} diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2RGB565ActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2RGB565ActivityLauncher.java new file mode 100644 index 000000000..fbd9b0a9c --- /dev/null +++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2RGB565ActivityLauncher.java @@ -0,0 +1,75 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.test.android; + +import java.util.Arrays; +import java.util.List; + +import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties; + +public class NEWTGearsES2RGB565ActivityLauncher extends LauncherUtil.BaseActivityLauncher { + + static String demo = "com.jogamp.opengl.test.android.NEWTGearsES2Activity"; + // static String[] pkgs = new String[] { "com.jogamp.common", "javax.media.opengl", "com.jogamp.opengl.test" }; + static String[] pkgs = new String[] { "com.jogamp.opengl.test" }; + + @Override + public void init() { + final OrderedProperties props = getProperties(); + // props.setProperty("jogamp.debug.JNILibLoader", "true"); + // props.setProperty("jogamp.debug.NativeLibrary", "true"); + // props.setProperty("jogamp.debug.IOUtil", "true"); + // properties.setProperty("jogamp.debug.NativeLibrary.Lookup", "true"); + // props.setProperty("nativewindow.debug", "all"); + props.setProperty("nativewindow.debug.GraphicsConfiguration", "true"); + // props.setProperty("jogl.debug", "all"); + // properties.setProperty("jogl.debug.GLProfile", "true"); + // props.setProperty("jogl.debug.GLDrawable", "true"); + props.setProperty("jogl.debug.GLContext", "true"); + props.setProperty("jogl.debug.GLSLCode", "true"); + // props.setProperty("jogl.debug.CapabilitiesChooser", "true"); + // props.setProperty("jogl.debug.GLSLState", "true"); + // props.setProperty("jogl.debug.DebugGL", "true"); + // props.setProperty("jogl.debug.TraceGL", "true"); + // props.setProperty("newt.debug", "all"); + props.setProperty("newt.debug.Window", "true"); + props.setProperty("newt.debug.Window.MouseEvent", "true"); + props.setProperty("newt.debug.Window.KeyEvent", "true"); + + props.setProperty("demo.force.rgba5650", "true"); + } + + @Override + public String getActivityName() { + return demo; + } + @Override + public List getPackages() { + return Arrays.asList(pkgs); + } +} -- cgit v1.2.3 From b738983638703bb721ee4c9820c8ef43e2252e73 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 24 Jan 2013 17:24:22 +0100 Subject: Bug 665 (part 1) - Allow dis-association of GLContext's GLDrawable .. Changes allowing re-association (incl. null) of GLContext/GLDrawable: - GLAutoDrawable: Refine API doc 'setContext(..)' - GLContext: Refine API doc: 'setGLDrawable(..)' 'getGLDrawable()' - GLContextImpl.setGLDrawable(): Handle null drawable - GLAutoDrawableDelegate/GLAutoDrawableBase: Allow null GLContext - GLDrawableHelper.switchContext(..)/recreateGLDrawable(): Balance GLContext.setGLDrawable(..) calls - New GLEventListenerState, holding state vector [GLEventListener, GLContext, .. ] impl. relocation of all components from/to GLAutoDrawable. - GLDrawableUtil - Using GLEventListenerState for swapGLContextAndAllGLEventListener(..) +++ NEWT Window*: - getDisplayHandle() is 'final', no more 'shortcut' code allowed due to re-association incl. display handle. - close*: - close config's device (was missing) - null config +++ Changes allowing reconfig of Display handle as required to re-associate pre-existing GLContext to a 'window': - AbstractGraphicsDevice: Add isHandleOwner() / clearHandleOwner() - Impl. in X11GraphicsDevice and EGLGraphicsDevice, NOP in DefaultGraphicsDevice - DefaultGraphicsConfiguration add 'setScreen(..)' - MutableGraphicsConfiguration - Make DefaultGraphicsConfiguration.setScreen(..) public - NativeWindowFactory add 'createScreen(String type, AbstractGraphicsDevice device, int screen)' - Refactored from SWTAccessor - NativeWindow x11ErrorHandler: Dump Stack Trace in DEBUG mode, always. --- make/scripts/tests-x64.bat | 3 +- make/scripts/tests.sh | 10 +- .../com/jogamp/opengl/GLAutoDrawableDelegate.java | 8 +- .../com/jogamp/opengl/util/GLDrawableUtil.java | 116 +------ .../classes/javax/media/opengl/GLAutoDrawable.java | 32 +- src/jogl/classes/javax/media/opengl/GLContext.java | 23 +- .../classes/jogamp/opengl/GLAutoDrawableBase.java | 13 +- src/jogl/classes/jogamp/opengl/GLContextImpl.java | 24 +- .../classes/jogamp/opengl/GLDrawableHelper.java | 31 +- .../jogamp/opengl/GLEventListenerState.java | 267 ++++++++++++++++ .../nativewindow/MutableGraphicsConfiguration.java | 7 + .../jogamp/nativewindow/egl/EGLGraphicsDevice.java | 11 +- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 19 +- .../jogamp/nativewindow/x11/X11GraphicsDevice.java | 12 +- .../AbstractGraphicsConfiguration.java | 3 +- .../media/nativewindow/AbstractGraphicsDevice.java | 12 +- .../media/nativewindow/AbstractGraphicsScreen.java | 2 + .../nativewindow/DefaultGraphicsConfiguration.java | 17 +- .../media/nativewindow/DefaultGraphicsDevice.java | 19 +- .../media/nativewindow/DefaultGraphicsScreen.java | 6 +- .../media/nativewindow/NativeWindowFactory.java | 27 ++ src/nativewindow/native/x11/Xmisc.c | 2 +- .../classes/com/jogamp/newt/opengl/GLWindow.java | 18 +- src/newt/classes/jogamp/newt/WindowImpl.java | 9 +- .../jogamp/newt/driver/x11/WindowDriver.java | 10 +- .../acore/TestGLContextDrawableSwitch01NEWT.java | 330 +++++++++++++++++++ .../acore/TestGLContextDrawableSwitch11NEWT.java | 352 +++++++++++++++++++++ .../acore/TestGLContextDrawableSwitchNEWT.java | 310 ------------------ .../test/junit/util/GLEventListenerCounter.java | 65 ++++ 29 files changed, 1222 insertions(+), 536 deletions(-) create mode 100644 src/jogl/classes/jogamp/opengl/GLEventListenerState.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitch01NEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitch11NEWT.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitchNEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/util/GLEventListenerCounter.java (limited to 'src/nativewindow') diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat index b66f8b8ab..8bee4c6dd 100755 --- a/make/scripts/tests-x64.bat +++ b/make/scripts/tests-x64.bat @@ -12,7 +12,8 @@ REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedCon REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile02NEWT %* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT %* +scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitch01NEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitch11NEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug00NEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug01NEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT %* diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 80e418056..9625519b9 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -89,6 +89,7 @@ function jrun() { #D_ARGS="-Djogl.debug.FBObject" #D_ARGS="-Djogl.debug.GLSLCode" #D_ARGS="-Djogl.debug.GLSLCode -Djogl.debug.DebugGL -Djogl.debug.TraceGL" + #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogl.debug.FixedFuncPipeline -Djogl.debug.GLSLCode" #D_ARGS="-Djogl.debug.FixedFuncPipeline -Djogl.debug.GLSLState" @@ -105,6 +106,7 @@ function jrun() { #D_ARGS="-Djogamp.debug=all" #D_ARGS="-Djogamp.debug=all -Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" #D_ARGS="-Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" + #D_ARGS="-Dnativewindow.debug.X11Util" #D_ARGS="-Djogl.debug.Animator" #D_ARGS="-Djogl.debug=all -Dnewt.debug=all" #D_ARGS="-Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.GLCanvas" @@ -284,7 +286,8 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT2 $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES1NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitchNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitch01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitch02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLPointsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug651NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLMesaBug658NEWT $* @@ -303,6 +306,9 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableNewtCanvasAWTOnOffscrnCapsAWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitch01NEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLContextDrawableSwitch11NEWT $* + #testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer01GLCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer02NewtCanvasAWT $* @@ -399,7 +405,7 @@ function testawtswt() { # # newt.awt (testawt) # -testawt com.jogamp.opengl.test.junit.jogl.newt.TestSwingAWTRobotUsageBeforeJOGLInitBug411 $* +#testawt com.jogamp.opengl.test.junit.jogl.newt.TestSwingAWTRobotUsageBeforeJOGLInitBug411 $* #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper $* #testawt com.jogamp.opengl.test.junit.newt.TestEventSourceNotAWTBug #testawt com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot $* diff --git a/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java index 38a8deef8..38315dc72 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java +++ b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java @@ -65,7 +65,10 @@ import jogamp.opengl.GLDrawableImpl; public class GLAutoDrawableDelegate extends GLAutoDrawableBase implements GLAutoDrawable { /** * @param drawable a valid and already realized {@link GLDrawable} - * @param context a valid {@link GLContext}, may not be made current (created) yet. + * @param context a valid {@link GLContext}, + * may not have been made current (created) yet, + * may not be associated w/ drawable yet, + * may be null for lazy initialization * @param upstreamWidget optional UI element holding this instance, see {@link #getUpstreamWidget()}. * @param ownDevice pass true if {@link AbstractGraphicsDevice#close()} shall be issued, * otherwise pass false. Closing the device is required in case @@ -78,9 +81,6 @@ public class GLAutoDrawableDelegate extends GLAutoDrawableBase implements GLAuto if(null == drawable) { throw new IllegalArgumentException("null drawable"); } - if(null == context) { - throw new IllegalArgumentException("null context"); - } if(!drawable.isRealized()) { throw new IllegalArgumentException("drawable not realized"); } diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLDrawableUtil.java b/src/jogl/classes/com/jogamp/opengl/util/GLDrawableUtil.java index cc81e4820..c03e4bfa4 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLDrawableUtil.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLDrawableUtil.java @@ -27,17 +27,14 @@ */ package com.jogamp.opengl.util; -import java.util.ArrayList; -import java.util.List; - import javax.media.opengl.GLAnimatorControl; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawable; import javax.media.opengl.GLEventListener; -import javax.media.opengl.GLRunnable; import jogamp.opengl.Debug; +import jogamp.opengl.GLEventListenerState; /** * Providing utility functions dealing w/ {@link GLDrawable}s, {@link GLAutoDrawable} and their {@link GLEventListener}. @@ -83,7 +80,7 @@ public class GLDrawableUtil { dest.addGLEventListener(listener); if(preserveInitState && initialized) { dest.setGLEventListenerInitState(listener, true); - dest.invoke(false, new ReshapeGLEventListener(listener)); + dest.invoke(false, new GLEventListenerState.ReshapeGLEventListener(listener)); } // else .. !init state is default } @@ -121,108 +118,13 @@ public class GLDrawableUtil { * @param b */ public static final void swapGLContextAndAllGLEventListener(GLAutoDrawable a, GLAutoDrawable b) { - final List aGLCmds = new ArrayList(); - final List bGLCmds = new ArrayList(); - final GLAnimatorControl aAnim = a.getAnimator(); - final GLAnimatorControl bAnim = b.getAnimator(); - final boolean aIsPaused = isAnimatorAnimatingOnOtherThread(aAnim) && aAnim.pause(); - final boolean bIsPaused = isAnimatorAnimatingOnOtherThread(bAnim) && bAnim.pause(); - - // - // remove and cache all GLEventListener and their init-state - // - final int aSz = a.getGLEventListenerCount(); - final GLEventListener[] aGLE = new GLEventListener[aSz]; - final boolean[] aInit = new boolean[aSz]; - for(int i=0; idrawable might be an inner GLDrawable instance if using a delegation pattern, - * or this GLAutoDrawable instance. + * Associate the new context, newtCtx, to this auto-drawable. *

        - * If the old or new context was current on this thread, it is being released before switching the drawable. + * The current context will be dis-associated from this auto-drawable + * via {@link GLContext#setGLDrawable(GLDrawable, boolean) setGLDrawable(null, true);} first. + *

        + *

        + * The new context will be associated with this auto-drawable + * via {@link GLContext#setGLDrawable(GLDrawable, boolean) newCtx.setGLDrawable(drawable, true);}. + *

        + *

        + * If the old or new context was current on this thread, it is being released before switching the association. * The new context will be made current afterwards, if it was current before. * However the user shall take extra care that no other thread * attempts to make this context current. *

        *

        - * Be aware that the old context is still bound to the drawable, - * and that one context can only be bound to one drawable at one time! - *

        - *

        * In case you do not intend to use the old context anymore, i.e. - * not assigning it to another drawable, it shall be - * destroyed before setting the new context, i.e.: + * not assigning it to another drawable, it shall be + * destroyed, i.e.: *

        -            GLContext oldCtx = glad.getContext();
        +            GLContext oldCtx = glad.setContext(newCtx);
                     if(null != oldCtx) {
                         oldCtx.destroy();
                     }
        -            glad.setContext(newCtx);            
            * 
        - * This is required, since a context must have a valid drawable at all times - * and this API shall not restrict the user in any way. *

        * - * @param newCtx the new context - * @return the replaced GLContext, maybe null + * @param newCtx the new context, maybe null for dis-association. + * @return the previous GLContext, maybe null * * @see GLContext#setGLDrawable(GLDrawable, boolean) * @see GLContext#setGLReadDrawable(GLDrawable) diff --git a/src/jogl/classes/javax/media/opengl/GLContext.java b/src/jogl/classes/javax/media/opengl/GLContext.java index 455f2d70d..4817add4d 100644 --- a/src/jogl/classes/javax/media/opengl/GLContext.java +++ b/src/jogl/classes/javax/media/opengl/GLContext.java @@ -217,15 +217,20 @@ public abstract class GLContext { /** * Sets the read/write drawable for framebuffer operations. *

        + * If the arguments reflect the current state of this context + * this method is a no-operation and returns the old and current {@link GLDrawable}. + *

        + *

        * If the context was current on this thread, it is being released before switching the drawable * and made current afterwards. However the user shall take extra care that not other thread * attempts to make this context current. Otherwise a race condition may happen. *

        - * @param readWrite the read/write drawable for framebuffer operations. - * @param setWriteOnly if true and if the current read-drawable differs - * from the write-drawable ({@link #setGLReadDrawable(GLDrawable)}), - * only change the write-drawable. Otherwise set both drawables. - * @return the replaced read/write drawable + * @param readWrite The read/write drawable for framebuffer operations, maybe null to remove association. + * @param setWriteOnly Only change the write-drawable, if setWriteOnly is true and + * if the {@link #getGLReadDrawable() read-drawable} differs + * from the {@link #getGLDrawable() write-drawable}. + * Otherwise set both drawables, read and write. + * @return The previous read/write drawable * * @throws GLException in case null is being passed or * this context is made current on another thread. @@ -239,6 +244,12 @@ public abstract class GLContext { /** * Returns the write-drawable this context uses for framebuffer operations. + *

        + * If the read-drawable has not been changed manually via {@link #setGLReadDrawable(GLDrawable)}, + * it equals to the write-drawable (default). + *

        + * @see #setGLDrawable(GLDrawable, boolean) + * @see #setGLReadDrawable(GLDrawable) */ public abstract GLDrawable getGLDrawable(); @@ -259,7 +270,7 @@ public abstract class GLContext { * * @param read the read-drawable for read framebuffer operations. * If null is passed, the default write drawable will be set. - * @return the replaced read-drawable + * @return the previous read-drawable * * @throws GLException in case a read drawable is not supported or * this context is made current on another thread. diff --git a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java index eadd59559..c20197e72 100644 --- a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java +++ b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java @@ -74,8 +74,12 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { protected volatile boolean sendDestroy = false; // volatile: maybe written by WindowManager thread w/o locking /** - * @param drawable upstream {@link GLDrawableImpl} instance, may be null for lazy initialization - * @param context upstream {@link GLContextImpl} instance, may be null for lazy initialization + * @param drawable upstream {@link GLDrawableImpl} instance, + * may be null for lazy initialization + * @param context upstream {@link GLContextImpl} instance, + * may not have been made current (created) yet, + * may not be associated w/ drawable yet, + * may be null for lazy initialization * @param ownsDevice pass true if {@link AbstractGraphicsDevice#close()} shall be issued, * otherwise pass false. Closing the device is required in case * the drawable is created w/ it's own new instance, e.g. offscreen drawables, @@ -85,6 +89,9 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { this.drawable = drawable; this.context = context; this.ownsDevice = ownsDevice; + if(null != context && null != drawable) { + context.setGLDrawable(drawable, false); + } resetFPSCounter(); } @@ -326,7 +333,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, FPSCounter { final GLContext oldCtx = context; final boolean newCtxCurrent = GLDrawableHelper.switchContext(drawable, oldCtx, newCtx, additionalCtxCreationFlags); context=(GLContextImpl)newCtx; - if(newCtxCurrent) { + if(newCtxCurrent) { // implies null != newCtx context.makeCurrent(); } return oldCtx; diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index f2c2cfada..2a2b6a8fd 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -203,8 +203,8 @@ public abstract class GLContextImpl extends GLContext { @Override public final GLDrawable setGLDrawable(GLDrawable readWrite, boolean setWriteOnly) { - if(null==readWrite) { - throw new GLException("Null read/write drawable not allowed"); + if( drawable == readWrite && ( setWriteOnly || drawableRead == readWrite ) ) { + return drawable; // no change. } final boolean lockHeld = lock.isOwner(Thread.currentThread()); if(lockHeld) { @@ -212,16 +212,20 @@ public abstract class GLContextImpl extends GLContext { } else if(lock.isLockedByOtherThread()) { // still could glitch .. throw new GLException("GLContext current by other thread ("+lock.getOwner()+"), operation not allowed."); } - if(!setWriteOnly || drawableRead==drawable) { // if !setWriteOnly || !explicitReadDrawable + if( !setWriteOnly || drawableRead == drawable ) { // if !setWriteOnly || !explicitReadDrawable drawableRead = (GLDrawableImpl) readWrite; } final GLDrawableImpl old = drawable; - old.associateContext(this, false); - drawableRetargeted = null != drawable; + if( null != old ) { + old.associateContext(this, false); + } + drawableRetargeted |= null != drawable && readWrite != drawable; drawable = (GLDrawableImpl) readWrite ; - drawable.associateContext(this, true); - if(lockHeld) { - makeCurrent(); + if( null != drawable ) { + drawable.associateContext(this, true); + if( lockHeld ) { + makeCurrent(); + } } return old; } @@ -334,7 +338,7 @@ public abstract class GLContextImpl extends GLContext { ", surf "+toHexString(drawable.getHandle())+", isShared "+GLContextShareSet.isShared(this)+" - "+lock); } if (contextHandle != 0) { - int lockRes = drawable.lockSurface(); + final int lockRes = drawable.lockSurface(); if (NativeSurface.LOCK_SURFACE_NOT_READY == lockRes) { // this would be odd .. throw new GLException("Surface not ready to lock: "+drawable); @@ -408,7 +412,7 @@ public abstract class GLContextImpl extends GLContext { throw new GLException("Destination OpenGL context has not been created"); } - int lockRes = drawable.lockSurface(); + final int lockRes = drawable.lockSurface(); if (NativeSurface.LOCK_SURFACE_NOT_READY == lockRes) { // this would be odd .. throw new GLException("Surface not ready to lock"); diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java index f8c58ee34..5d113ff83 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java @@ -131,30 +131,36 @@ public class GLDrawableHelper { } /** - * Associate a new context to the drawable and also propagates the context/drawable switch by - * calling {@link GLContext#setGLDrawable(GLDrawable, boolean) newCtx.setGLDrawable(drawable, true);}. - *

        - * If the old or new context was current on this thread, it is being released before switching the drawable. + * Switch {@link GLContext} / {@link GLDrawable} association. + *

        + * Dis-associate oldCtx from drawable + * via {@link GLContext#setGLDrawable(GLDrawable, boolean) oldCtx.setGLDrawable(null, true);}. *

        *

        - * Be aware that the old context is still bound to the drawable, - * and that one context can only bound to one drawable at one time! + * Re-associate newCtx with drawable + * via {@link GLContext#setGLDrawable(GLDrawable, boolean) newCtx.setGLDrawable(drawable, true);}. + *

        + *

        + * If the old or new context was current on this thread, it is being released before switching the drawable. *

        *

        * No locking is being performed on the drawable, caller is required to take care of it. *

        * * @param drawable the drawable which context is changed - * @param oldCtx the old context - * @param newCtx the new context + * @param oldCtx the old context, maybe null. + * @param newCtx the new context, maybe null for dis-association. * @param newCtxCreationFlags additional creation flags if newCtx is not null and not been created yet, see {@link GLContext#setContextCreationFlags(int)} * @return true if the new context was current, otherwise false * * @see GLAutoDrawable#setContext(GLContext) */ public static final boolean switchContext(GLDrawable drawable, GLContext oldCtx, GLContext newCtx, int newCtxCreationFlags) { - if( null != oldCtx && oldCtx.isCurrent() ) { - oldCtx.release(); + if( null != oldCtx ) { + if( oldCtx.isCurrent() ) { + oldCtx.release(); + } + oldCtx.setGLDrawable(null, true); // dis-associate old pair } final boolean newCtxCurrent; if(null!=newCtx) { @@ -163,8 +169,8 @@ public class GLDrawableHelper { newCtx.release(); } newCtx.setContextCreationFlags(newCtxCreationFlags); - newCtx.setGLDrawable(drawable, true); // propagate context/drawable switch - } else { + newCtx.setGLDrawable(drawable, true); // re-associate new pair + } else { newCtxCurrent = false; } return newCtxCurrent; @@ -203,6 +209,7 @@ public class GLDrawableHelper { } context.getGL().glFinish(); context.release(); + context.setGLDrawable(null, true); // dis-associate } if(null != proxySurface) { diff --git a/src/jogl/classes/jogamp/opengl/GLEventListenerState.java b/src/jogl/classes/jogamp/opengl/GLEventListenerState.java new file mode 100644 index 000000000..dea2bc85b --- /dev/null +++ b/src/jogl/classes/jogamp/opengl/GLEventListenerState.java @@ -0,0 +1,267 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package jogamp.opengl; + +import java.util.ArrayList; +import java.util.List; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.NativeWindowFactory; +import javax.media.nativewindow.VisualIDHolder; +import javax.media.opengl.GLAnimatorControl; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLException; +import javax.media.opengl.GLRunnable; + +import com.jogamp.nativewindow.MutableGraphicsConfiguration; + +/** + * GLEventListenerState is holding {@link GLAutoDrawable} components crucial + * to relocating all its {@link GLEventListener} w/ their operating {@link GLContext}, etc. + * The components are: + *
          + *
        • {@link AbstractGraphicsScreen}
        • + *
        • {@link GLCapabilitiesImmutable}
        • + *
        • {@link GLContext} operating all {@link GLEventListener}
        • + *
        • All {@link GLEventListener}
        • + *
        • All {@link GLEventListener}'s init state
        • + *
        • {@link GLAnimatorControl}
        • + *
        + *

        + * A GLEventListenerState instance can be created while components are {@link #moveFrom(GLAutoDrawable) moved from} a {@link GLAutoDrawable} + * to the new instance, which gains {@link #isOwner() ownership} of the moved components. + *

        + *

        + * A GLEventListenerState instance's components can be {@link #moveTo(GLAutoDrawable) moved to} a {@link GLAutoDrawable}, + * while loosing {@link #isOwner() ownership} of the moved components. + *

        + *

        + */ +public class GLEventListenerState { + private GLEventListenerState(AbstractGraphicsScreen screen, GLCapabilitiesImmutable caps, GLContext context, int count, GLAnimatorControl anim) { + this.screen = screen; + this.caps = caps; + this.context = context; + this.listeners = new GLEventListener[count]; + this.listenersInit = new boolean[count]; + this.anim = anim; + this.owner = true; + } + /** + * Returns true, if this instance is the current owner of the components, + * otherwise false. + *

        + * Ownership is lost if {@link #moveTo(GLAutoDrawable)} is being called successfully + * and all components are transferred to the new {@link GLAutoDrawable}. + *

        + */ + public final boolean isOwner() { return owner; } + + public final int listenerCount() { return listeners.length; } + + public final AbstractGraphicsScreen screen; + public final GLCapabilitiesImmutable caps; + public final GLContext context; + public final GLEventListener[] listeners; + public final boolean[] listenersInit; + public final GLAnimatorControl anim; + + private boolean owner; + + /** + * Last resort to destroy and loose ownership + */ + public void destroy() { + if( owner ) { + final int aSz = listenerCount(); + for(int i=0; i + * Note that all components are removed from the {@link GLAutoDrawable}, + * i.e. the {@link GLContext}, all {@link GLEventListener}. + *

        + *

        + * If the {@link GLAutoDrawable} was added to a {@link GLAnimatorControl}, it is removed + * and the {@link GLAnimatorControl} added to the GLEventListenerState. + *

        + *

        + * The returned GLEventListenerState instance is the {@link #isOwner() owner of the components}. + *

        + * + * @param a {@link GLAutoDrawable} source to move components from + * @return new GLEventListenerState instance {@link #isOwner() owning} moved components. + * + * @see #moveTo(GLAutoDrawable) + */ + public static GLEventListenerState moveFrom(GLAutoDrawable a) { + final int aSz = a.getGLEventListenerCount(); + + // Create new AbstractGraphicsScreen w/ cloned AbstractGraphicsDevice for future GLAutoDrawable + // allowing this AbstractGraphicsDevice to loose ownership -> not closing display/device! + final AbstractGraphicsConfiguration aCfg1 = a.getNativeSurface().getGraphicsConfiguration(); + final GLCapabilitiesImmutable caps1 = (GLCapabilitiesImmutable) aCfg1.getChosenCapabilities(); + final AbstractGraphicsScreen aScreen1 = aCfg1.getScreen(); + final AbstractGraphicsDevice aDevice1 = aScreen1.getDevice(); + final AbstractGraphicsDevice aDevice2 = (AbstractGraphicsDevice) aDevice1.clone(); + final AbstractGraphicsScreen aScreen2 = NativeWindowFactory.createScreen( NativeWindowFactory.getNativeWindowType(false), aDevice2, aScreen1.getIndex() ); + + final GLAnimatorControl aAnim = a.getAnimator(); + if( null != aAnim ) { + aAnim.remove(a); // also handles ECT + } + + final GLEventListenerState glls = new GLEventListenerState(aScreen2, caps1, a.getContext(), aSz, aAnim); + + // + // remove and cache all GLEventListener and their init-state + // + for(int i=0; i + * If the previous {@link GLAutoDrawable} was removed from a {@link GLAnimatorControl} by previous {@link #moveFrom(GLAutoDrawable)}, + * the given {@link GLAutoDrawable} is added to the cached {@link GLAnimatorControl}. + * This operation is skipped, if the given {@link GLAutoDrawable} is already added to a {@link GLAnimatorControl} instance. + *

        + *

        + * Note: After this operation, the GLEventListenerState reference should be released. + *

        + * + * @param a {@link GLAutoDrawable} destination to move GLEventListenerState components to + * + * @throws GLException if the {@link GLAutoDrawable}'s configuration is incompatible, i.e. different {@link GLCapabilitiesImmutable}. + * + * @see #moveFrom(GLAutoDrawable) + * @see #isOwner() + */ + public final void moveTo(GLAutoDrawable a) { + final List aGLCmds = new ArrayList(); + final int aSz = listenerCount(); + + final MutableGraphicsConfiguration aCfg = (MutableGraphicsConfiguration) a.getNativeSurface().getGraphicsConfiguration(); + final GLCapabilitiesImmutable aCaps = (GLCapabilitiesImmutable) aCfg.getChosenCapabilities(); + if( caps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) != aCaps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) ) { + throw new GLException("XXX: Incompatible - Prev Holder: "+caps+", New Holder "+caps); + } + final GLContext prevContext = a.getContext(); + if( null != prevContext) { + prevContext.destroy(); + } + final AbstractGraphicsScreen preScreen = aCfg.getScreen(); + aCfg.setScreen( screen ); + preScreen.getDevice().close(); + a.setContext( context ); + owner = false; + + // + // Trigger GL-Viewport reset and reshape of all initialized GLEventListeners + // + aGLCmds.add(setViewport); + for(int i=0; i= 0 is specific screen * @return - * @throws UnsupportedOperationException */ - public static AbstractGraphicsScreen getScreen(AbstractGraphicsDevice device, int screen) throws UnsupportedOperationException { - if( isX11 ) { - X11GraphicsDevice x11Device = (X11GraphicsDevice)device; - if(0 > screen) { - screen = x11Device.getDefaultScreen(); - } - return new X11GraphicsScreen(x11Device, screen); - } - if(0 > screen) { - screen = 0; // FIXME: Needs native API utilization - } - if( isWindows || isOSX ) { - return new DefaultGraphicsScreen(device, screen); - } - throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); + public static AbstractGraphicsScreen getScreen(AbstractGraphicsDevice device, int screen) { + return NativeWindowFactory.createScreen(nwt, device, screen); } public static int getNativeVisualID(AbstractGraphicsDevice device, long windowHandle) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index 0f28ca67c..da3b31de4 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -45,7 +45,7 @@ import javax.media.nativewindow.ToolkitLock; */ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneable { - final boolean handleOwner; + /* final */ boolean handleOwner; final boolean isXineramaEnabled; /** Constructs a new X11GraphicsDevice corresponding to the given connection and default @@ -153,5 +153,13 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl } return super.close(); } + + @Override + public boolean isHandleOwner() { + return handleOwner; + } + @Override + public void clearHandleOwner() { + handleOwner = false; + } } - diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java index ebdaf2fbb..4e45113d4 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java @@ -42,8 +42,9 @@ package javax.media.nativewindow; /** A marker interface describing a graphics configuration, visual, or pixel format in a toolkit-independent manner. */ - public interface AbstractGraphicsConfiguration extends VisualIDHolder, Cloneable { + public Object clone(); + /** * Return the screen this graphics configuration is valid for */ diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java index 8ecd5242d..585cd1f09 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java @@ -45,7 +45,6 @@ import jogamp.nativewindow.Debug; /** A interface describing a graphics device in a toolkit-independent manner. */ - public interface AbstractGraphicsDevice extends Cloneable { public static final boolean DEBUG = Debug.debug("GraphicsDevice"); @@ -58,6 +57,8 @@ public interface AbstractGraphicsDevice extends Cloneable { /** Default unit id for the 1st device: 0 */ public static int DEFAULT_UNIT = 0; + public Object clone(); + /** * Returns the type of the underlying subsystem, ie * NativeWindowFactory.TYPE_KD, NativeWindowFactory.TYPE_X11, .. @@ -143,10 +144,17 @@ public interface AbstractGraphicsDevice extends Cloneable { *

        * Example implementations like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice} * or {@link com.jogamp.nativewindow.egl.EGLGraphicsDevice} - * issue the native close operation or skip it depending on the handles's ownership. + * issue the native close operation or skip it depending on the {@link #isHandleOwner() handles's ownership}. *

        * * @return true if the handle was not null and closing was successful, otherwise false. */ public boolean close(); + + /** + * @return true if instance owns the handle to issue {@link #close()}, otherwise false. + */ + public boolean isHandleOwner(); + + public void clearHandleOwner(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java index eb2cc9120..acb98073b 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java @@ -44,6 +44,8 @@ package javax.media.nativewindow; */ public interface AbstractGraphicsScreen extends Cloneable { + public Object clone(); + /** * Return the device this graphics configuration is valid for */ diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java index a33c3792a..6b23172e1 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java @@ -93,25 +93,26 @@ public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphics /** * Set the capabilities to a new value. * + *

        * The use case for setting the Capabilities at a later time is - * a change of the graphics device in a multi-screen environment.
        - * + * a change or re-validation of capabilities. + *

        * @see javax.media.nativewindow.GraphicsConfigurationFactory#chooseGraphicsConfiguration(Capabilities, CapabilitiesChooser, AbstractGraphicsScreen) */ protected void setChosenCapabilities(CapabilitiesImmutable capsChosen) { - capabilitiesChosen = capsChosen; + this.capabilitiesChosen = capsChosen; } /** * Set a new screen. * + *

        * the use case for setting a new screen at a later time is - * a change of the graphics device in a multi-screen environment.
        - * - * A copy of the passed object is being used. + * a change of the graphics device in a multi-screen environment. + *

        */ - final protected void setScreen(DefaultGraphicsScreen screen) { - this.screen = (AbstractGraphicsScreen) screen.clone(); + protected void setScreen(AbstractGraphicsScreen screen) { + this.screen = screen; } @Override diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java index 9288652d9..b3ae4628c 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java @@ -37,10 +37,10 @@ import jogamp.nativewindow.NativeWindowFactoryImpl; public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice { private static final String separator = "_"; - private String type; - protected String connection; - protected int unitID; - protected String uniqueID; + private final String type; + protected final String connection; + protected final int unitID; + protected final String uniqueID; protected long handle; protected ToolkitLock toolkitLock; @@ -170,9 +170,18 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice return false; } + @Override + public boolean isHandleOwner() { + return false; + } + + @Override + public void clearHandleOwner() { + } + @Override public String toString() { - return getClass().getSimpleName()+"[type "+getType()+", connection "+getConnection()+", unitID "+getUnitID()+", handle 0x"+Long.toHexString(getHandle())+", "+toolkitLock+"]"; + return getClass().getSimpleName()+"[type "+getType()+", connection "+getConnection()+", unitID "+getUnitID()+", handle 0x"+Long.toHexString(getHandle())+", owner "+isHandleOwner()+", "+toolkitLock+"]"; } /** diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java index f50bd0e14..9fa58c7a3 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java @@ -33,8 +33,8 @@ package javax.media.nativewindow; public class DefaultGraphicsScreen implements Cloneable, AbstractGraphicsScreen { - AbstractGraphicsDevice device; - private int idx; + private final AbstractGraphicsDevice device; + private final int idx; public DefaultGraphicsScreen(AbstractGraphicsDevice device, int idx) { this.device = device; @@ -57,7 +57,7 @@ public class DefaultGraphicsScreen implements Cloneable, AbstractGraphicsScreen public AbstractGraphicsDevice getDevice() { return device; } - + public int getIndex() { return idx; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index d7f28a986..07702c762 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -48,6 +48,10 @@ import jogamp.nativewindow.ResourceToolkitLock; import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; +import com.jogamp.nativewindow.awt.AWTGraphicsDevice; +import com.jogamp.nativewindow.awt.AWTGraphicsScreen; +import com.jogamp.nativewindow.x11.X11GraphicsDevice; +import com.jogamp.nativewindow.x11.X11GraphicsScreen; /** Provides a pluggable mechanism for arbitrary window toolkits to adapt their components to the {@link NativeWindow} interface, @@ -428,6 +432,29 @@ public abstract class NativeWindowFactory { return NativeWindowFactoryImpl.getNullToolkitLock(); } + /** + * @param device + * @param screen -1 is default screen of the given device, e.g. maybe 0 or determined by native API. >= 0 is specific screen + * @return newly created AbstractGraphicsScreen of given native type + */ + public static AbstractGraphicsScreen createScreen(String type, AbstractGraphicsDevice device, int screen) { + if( TYPE_X11 == type ) { + final X11GraphicsDevice x11Device = (X11GraphicsDevice)device; + if(0 > screen) { + screen = x11Device.getDefaultScreen(); + } + return new X11GraphicsScreen(x11Device, screen); + } + if(0 > screen) { + screen = 0; // FIXME: Needs native API utilization + } + if( TYPE_AWT == type ) { + final AWTGraphicsDevice awtDevice = (AWTGraphicsDevice) device; + return new AWTGraphicsScreen(awtDevice); + } + return new DefaultGraphicsScreen(device, screen); + } + /** Returns the appropriate NativeWindowFactory to handle window objects of the given type. The windowClass might be {@link NativeWindow NativeWindow}, in which case the client has diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index a8d45f288..017c52df2 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -180,7 +180,7 @@ static int errorHandlerThrowException = 0; static int x11ErrorHandler(Display *dpy, XErrorEvent *e) { - if(!errorHandlerQuiet) { + if( !errorHandlerQuiet || errorHandlerDebug ) { const char * errnoStr = strerror(errno); char errCodeStr[80]; char reqCodeStr[80]; diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index 96d0f6e3b..7fccb6622 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -458,24 +458,22 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind } else { t0 = 0; } - - /* if (nativeWindowCreated && null != context) { - throw new GLException("InternalError: Native Windows has been just created, but context wasn't destroyed (is not null)"); - } */ - if (null == context && visible && 0 != window.getWindowHandle() && 0 ctx1/draw2, ctx2/draw1. + */ +public class TestGLContextDrawableSwitch01NEWT extends UITestCase { + static GLProfile glp; + static GLCapabilities caps; + static int width, height; + + @BeforeClass + public static void initClass() { + glp = GLProfile.getGL2ES2(); + caps = new GLCapabilities(glp); + width = 256; + height = 256; + } + + private GLAutoDrawable createGLAutoDrawable(GLCapabilities caps, int x, int y, int width, int height, WindowListener wl) throws InterruptedException { + final Window window = NewtFactory.createWindow(caps); + Assert.assertNotNull(window); + window.setPosition(x, y); + window.setSize(width, height); + window.setVisible(true); + Assert.assertTrue(AWTRobotUtil.waitForVisible(window, true)); + Assert.assertTrue(AWTRobotUtil.waitForRealized(window, true)); + + final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); + final GLDrawable drawable = factory.createGLDrawable(window); + Assert.assertNotNull(drawable); + + drawable.setRealized(true); + Assert.assertTrue(drawable.isRealized()); + + final GLContext context = drawable.createContext(null); + Assert.assertNotNull(context); + + final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(drawable, context, window, false, null) { + @Override + protected void destroyImplInLock() { + super.destroyImplInLock(); + window.destroy(); // destroys the actual window + } + }; + + // add basic window interaction + window.addWindowListener(new WindowAdapter() { + @Override + public void windowRepaint(WindowUpdateEvent e) { + glad.windowRepaintOp(); + } + @Override + public void windowResized(WindowEvent e) { + glad.windowResizedOp(window.getWidth(), window.getHeight()); + } + @Override + public void windowDestroyNotify(WindowEvent e) { + glad.windowDestroyNotifyOp(); + } + }); + window.addWindowListener(wl); + + return glad; + } + + @Test(timeout=30000) + public void testSwitch2WindowSingleContext() throws InterruptedException { + final QuitAdapter quitAdapter = new QuitAdapter(); + + GLAutoDrawable glad1 = createGLAutoDrawable(caps, 64, 64, width, height, quitAdapter); + GLAutoDrawable glad2 = createGLAutoDrawable(caps, 2*64+width, 64, width+100, height+100, quitAdapter); + + // create single context using glad1 and assign it to glad1, + // destroy the prev. context afterwards. + { + final GLContext newCtx = glad1.createContext(null); + Assert.assertNotNull(newCtx); + final GLContext oldCtx = glad1.setContext(newCtx); + Assert.assertNotNull(oldCtx); + oldCtx.destroy(); + final int res = newCtx.makeCurrent(); + Assert.assertTrue(GLContext.CONTEXT_CURRENT_NEW==res || GLContext.CONTEXT_CURRENT==res); + newCtx.release(); + } + + final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); + GearsES2 gears = new GearsES2(1); + glad1.addGLEventListener(gears); + glad1.addGLEventListener(snapshotGLEventListener); + snapshotGLEventListener.setMakeSnapshot(); + + Animator animator = new Animator(); + animator.add(glad1); + animator.add(glad2); + animator.start(); + + int s = 0; + long t0 = System.currentTimeMillis(); + long t1 = t0; + + while( !quitAdapter.shouldQuit() && ( t1 - t0 ) < duration ) { + if( ( t1 - t0 ) / period > s) { + s++; + System.err.println(s+" - switch - START "+ ( t1 - t0 )); + + // switch context _and_ the demo synchronously + GLDrawableUtil.swapGLContextAndAllGLEventListener(glad1, glad2); + + System.err.println(s+" - switch - END "+ ( t1 - t0 )); + } + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + animator.stop(); + glad1.destroy(); + glad2.destroy(); + } + + @Test(timeout=30000) + public void testSwitch2GLWindowOneDemo() throws InterruptedException { + final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); + final GearsES2 gears = new GearsES2(1); + final QuitAdapter quitAdapter = new QuitAdapter(); + + GLWindow glWindow1 = GLWindow.create(caps); + glWindow1.setTitle("win1"); + glWindow1.setSize(width, height); + glWindow1.setPosition(64, 64); + glWindow1.addGLEventListener(0, gears); + glWindow1.addGLEventListener(snapshotGLEventListener); + glWindow1.addWindowListener(quitAdapter); + + GLWindow glWindow2 = GLWindow.create(caps); + glWindow2.setTitle("win2"); + glWindow2.setSize(width+100, height+100); + glWindow2.setPosition(2*64+width, 64); + glWindow2.addWindowListener(quitAdapter); + + Animator animator = new Animator(); + animator.add(glWindow1); + animator.add(glWindow2); + animator.start(); + + glWindow1.setVisible(true); + glWindow2.setVisible(true); + + snapshotGLEventListener.setMakeSnapshot(); + + int s = 0; + long t0 = System.currentTimeMillis(); + long t1 = t0; + + while( !quitAdapter.shouldQuit() && ( t1 - t0 ) < duration ) { + if( ( t1 - t0 ) / period > s) { + s++; + System.err.println(s+" - switch - START "+ ( t1 - t0 )); + System.err.println(s+" - A w1-h 0x"+Long.toHexString(glWindow1.getHandle())+",-ctx 0x"+Long.toHexString(glWindow1.getContext().getHandle())); + System.err.println(s+" - A w2-h 0x"+Long.toHexString(glWindow2.getHandle())+",-ctx 0x"+Long.toHexString(glWindow2.getContext().getHandle())); + + // switch context _and_ the demo synchronously + GLDrawableUtil.swapGLContextAndAllGLEventListener(glWindow1, glWindow2); + + System.err.println(s+" - B w1-h 0x"+Long.toHexString(glWindow1.getHandle())+",-ctx 0x"+Long.toHexString(glWindow1.getContext().getHandle())); + System.err.println(s+" - B w2-h 0x"+Long.toHexString(glWindow2.getHandle())+",-ctx 0x"+Long.toHexString(glWindow2.getContext().getHandle())); + System.err.println(s+" - switch - END "+ ( t1 - t0 )); + + snapshotGLEventListener.setMakeSnapshot(); + } + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + animator.stop(); + glWindow1.destroy(); + glWindow2.destroy(); + + } + + @Test(timeout=30000) + public void testSwitch2GLWindowEachWithOwnDemo() throws InterruptedException { + final GearsES2 gears = new GearsES2(1); + final RedSquareES2 rsquare = new RedSquareES2(1); + final QuitAdapter quitAdapter = new QuitAdapter(); + final SnapshotGLEventListener snapshotGLEventListener1 = new SnapshotGLEventListener(); + final SnapshotGLEventListener snapshotGLEventListener2 = new SnapshotGLEventListener(); + + GLWindow glWindow1 = GLWindow.create(caps); + glWindow1.setTitle("win1"); + glWindow1.setSize(width, height); + glWindow1.setPosition(64, 64); + glWindow1.addGLEventListener(0, gears); + glWindow1.addGLEventListener(snapshotGLEventListener1); + glWindow1.addWindowListener(quitAdapter); + + GLWindow glWindow2 = GLWindow.create(caps); + glWindow2.setTitle("win2"); + glWindow2.setSize(width+100, height+100); + glWindow2.setPosition(2*64+width, 64); + glWindow2.addGLEventListener(0, rsquare); + glWindow2.addGLEventListener(snapshotGLEventListener2); + glWindow2.addWindowListener(quitAdapter); + + Animator animator = new Animator(); + animator.add(glWindow1); + animator.add(glWindow2); + animator.start(); + + glWindow1.setVisible(true); + glWindow2.setVisible(true); + + snapshotGLEventListener1.setMakeSnapshot(); + snapshotGLEventListener2.setMakeSnapshot(); + + int s = 0; + long t0 = System.currentTimeMillis(); + long t1 = t0; + + while( !quitAdapter.shouldQuit() && ( t1 - t0 ) < duration ) { + if( ( t1 - t0 ) / period > s) { + s++; + System.err.println(s+" - switch - START "+ ( t1 - t0 )); + System.err.println(s+" - A w1-h 0x"+Long.toHexString(glWindow1.getHandle())+",-ctx 0x"+Long.toHexString(glWindow1.getContext().getHandle())); + System.err.println(s+" - A w2-h 0x"+Long.toHexString(glWindow2.getHandle())+",-ctx 0x"+Long.toHexString(glWindow2.getContext().getHandle())); + GLDrawableUtil.swapGLContextAndAllGLEventListener(glWindow1, glWindow2); + System.err.println(s+" - B w1-h 0x"+Long.toHexString(glWindow1.getHandle())+",-ctx 0x"+Long.toHexString(glWindow1.getContext().getHandle())); + System.err.println(s+" - B w2-h 0x"+Long.toHexString(glWindow2.getHandle())+",-ctx 0x"+Long.toHexString(glWindow2.getContext().getHandle())); + System.err.println(s+" - switch - END "+ ( t1 - t0 )); + snapshotGLEventListener1.setMakeSnapshot(); + snapshotGLEventListener2.setMakeSnapshot(); + } + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + animator.stop(); + // System.err.println("pre -del-w1: w1: "+glWindow1); + // System.err.println("pre -del-w1: w2: "+glWindow2); + glWindow1.destroy(); + // System.err.println("post-del-w1: w1: "+glWindow1); + // System.err.println("post-del-w1: w2: "+glWindow2); + glWindow2.destroy(); + + } + + // default timing for 2 switches + static long duration = 2200; // ms + static long period = 1000; // ms + + public static void main(String args[]) throws IOException { + for(int i=0; i + * See Bug 665 - https://jogamp.org/bugzilla/show_bug.cgi?id=665. + *

        + */ +public class TestGLContextDrawableSwitch11NEWT extends UITestCase { + static GLProfile glp; + static GLCapabilities caps; + static int width, height; + + @BeforeClass + public static void initClass() { + glp = GLProfile.getGL2ES2(); + caps = new GLCapabilities(glp); + width = 256; + height = 256; + } + + private GLAutoDrawable createGLAutoDrawable(GLCapabilities caps, int x, int y, int width, int height, WindowListener wl) throws InterruptedException { + final Window window = NewtFactory.createWindow(caps); + Assert.assertNotNull(window); + window.setPosition(x, y); + window.setSize(width, height); + window.setVisible(true); + Assert.assertTrue(AWTRobotUtil.waitForVisible(window, true)); + Assert.assertTrue(AWTRobotUtil.waitForRealized(window, true)); + + final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); + final GLDrawable drawable = factory.createGLDrawable(window); + Assert.assertNotNull(drawable); + + drawable.setRealized(true); + Assert.assertTrue(drawable.isRealized()); + + final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(drawable, null, window, false, null) { + @Override + protected void destroyImplInLock() { + super.destroyImplInLock(); + window.destroy(); // destroys the actual window + } + }; + + // add basic window interaction + window.addWindowListener(new WindowAdapter() { + @Override + public void windowRepaint(WindowUpdateEvent e) { + glad.windowRepaintOp(); + } + @Override + public void windowResized(WindowEvent e) { + glad.windowResizedOp(window.getWidth(), window.getHeight()); + } + @Override + public void windowDestroyNotify(WindowEvent e) { + glad.windowDestroyNotifyOp(); + } + }); + window.addWindowListener(wl); + + return glad; + } + + @Test(timeout=30000) + public void test01() throws InterruptedException { + final QuitAdapter quitAdapter = new QuitAdapter(); + + final GLEventListenerCounter glelCounter = new GLEventListenerCounter(); + final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); + final Animator animator = new Animator(); + animator.start(); + + final long t0 = System.currentTimeMillis(); + final GLEventListenerState glls1; + + // - create glad1 w/o context + // - create context using glad1 and assign it to glad1 + { + final GLAutoDrawable glad1 = createGLAutoDrawable(caps, 64, 64, width, height, quitAdapter); + final GLContext context1 = glad1.createContext(null); + glad1.setContext(context1); + animator.add(glad1); + + glad1.addGLEventListener(glelCounter); + glad1.addGLEventListener(new GearsES2(1)); + glad1.addGLEventListener(snapshotGLEventListener); + snapshotGLEventListener.setMakeSnapshot(); + + long t1 = System.currentTimeMillis(); + + while( !quitAdapter.shouldQuit() && ( t1 - t0 ) < duration/2 ) { + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + // - dis-associate context from glad1 + // - destroy glad1 + Assert.assertEquals(1, glelCounter.initCount); + Assert.assertTrue(1 <= glelCounter.reshapeCount); + Assert.assertTrue(1 <= glelCounter.displayCount); + Assert.assertEquals(0, glelCounter.disposeCount); + Assert.assertEquals(context1, glad1.getContext()); + Assert.assertEquals(3, glad1.getGLEventListenerCount()); + Assert.assertEquals(context1.getGLReadDrawable(), glad1.getDelegatedDrawable()); + Assert.assertEquals(context1.getGLDrawable(), glad1.getDelegatedDrawable()); + + glls1 = GLEventListenerState.moveFrom(glad1); + + Assert.assertEquals(1, glelCounter.initCount); + Assert.assertTrue(1 <= glelCounter.reshapeCount); + Assert.assertTrue(1 <= glelCounter.displayCount); + Assert.assertEquals(0, glelCounter.disposeCount); + Assert.assertEquals(context1, glls1.context); + Assert.assertNull(context1.getGLReadDrawable()); + Assert.assertNull(context1.getGLDrawable()); + Assert.assertEquals(3, glls1.listenerCount()); + Assert.assertEquals(true, glls1.isOwner()); + Assert.assertEquals(null, glad1.getContext()); + Assert.assertEquals(0, glad1.getGLEventListenerCount()); + + glad1.destroy(); + Assert.assertEquals(1, glelCounter.initCount); + Assert.assertTrue(1 <= glelCounter.reshapeCount); + Assert.assertTrue(1 <= glelCounter.displayCount); + Assert.assertEquals(0, glelCounter.disposeCount); + } + + // - create glad2 w/ survived context + { + final GLAutoDrawable glad2 = createGLAutoDrawable(caps, 2*64+width, 64, width+100, height+100, quitAdapter); + snapshotGLEventListener.setMakeSnapshot(); + + Assert.assertEquals(null, glad2.getContext()); + Assert.assertEquals(0, glad2.getGLEventListenerCount()); + + glls1.moveTo(glad2); + + Assert.assertEquals(1, glelCounter.initCount); + Assert.assertTrue(1 <= glelCounter.reshapeCount); + Assert.assertTrue(1 <= glelCounter.displayCount); + Assert.assertEquals(0, glelCounter.disposeCount); + Assert.assertEquals(glls1.context, glad2.getContext()); + Assert.assertEquals(3, glad2.getGLEventListenerCount()); + Assert.assertEquals(glls1.context.getGLReadDrawable(), glad2.getDelegatedDrawable()); + Assert.assertEquals(glls1.context.getGLDrawable(), glad2.getDelegatedDrawable()); + Assert.assertEquals(false, glls1.isOwner()); + + long t1 = System.currentTimeMillis(); + + while( !quitAdapter.shouldQuit() && ( t1 - t0 ) < duration/1 ) { + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + glad2.destroy(); + Assert.assertEquals(1, glelCounter.initCount); + Assert.assertTrue(1 <= glelCounter.reshapeCount); + Assert.assertTrue(1 <= glelCounter.displayCount); + Assert.assertEquals(1, glelCounter.disposeCount); + } + animator.stop(); + } + + @Test(timeout=30000) + public void test02() throws InterruptedException { + final QuitAdapter quitAdapter = new QuitAdapter(); + + final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); + final GLEventListenerCounter glelTracker = new GLEventListenerCounter(); + final Animator animator = new Animator(); + animator.start(); + + final long t0 = System.currentTimeMillis(); + final GLEventListenerState glls1; + + // - create glad1 w/o context + // - create context using glad1 and assign it to glad1 + { + final GLWindow glad1 = GLWindow.create(caps); + glad1.setSize(width, height); + glad1.setPosition(64, 64); + glad1.addWindowListener(quitAdapter); + glad1.setVisible(true); + animator.add(glad1); + + glad1.addGLEventListener(glelTracker); + glad1.addGLEventListener(new GearsES2(1)); + glad1.addGLEventListener(snapshotGLEventListener); + snapshotGLEventListener.setMakeSnapshot(); + + long t1 = System.currentTimeMillis(); + + while( !quitAdapter.shouldQuit() && ( t1 - t0 ) < duration/2 ) { + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + // - dis-associate context from glad1 + // - destroy glad1 + Assert.assertEquals(1, glelTracker.initCount); + Assert.assertTrue(1 <= glelTracker.reshapeCount); + Assert.assertTrue(1 <= glelTracker.displayCount); + Assert.assertEquals(0, glelTracker.disposeCount); + Assert.assertEquals(3, glad1.getGLEventListenerCount()); + Assert.assertEquals(glad1.getContext().getGLReadDrawable(), glad1.getDelegatedDrawable()); + Assert.assertEquals(glad1.getContext().getGLDrawable(), glad1.getDelegatedDrawable()); + + final GLContext context1 = glad1.getContext(); + glls1 = GLEventListenerState.moveFrom(glad1); + + Assert.assertEquals(1, glelTracker.initCount); + Assert.assertTrue(1 <= glelTracker.reshapeCount); + Assert.assertTrue(1 <= glelTracker.displayCount); + Assert.assertEquals(0, glelTracker.disposeCount); + Assert.assertEquals(context1, glls1.context); + Assert.assertNull(context1.getGLReadDrawable()); + Assert.assertNull(context1.getGLDrawable()); + Assert.assertEquals(3, glls1.listenerCount()); + Assert.assertEquals(true, glls1.isOwner()); + Assert.assertEquals(null, glad1.getContext()); + Assert.assertEquals(0, glad1.getGLEventListenerCount()); + + glad1.destroy(); + Assert.assertEquals(1, glelTracker.initCount); + Assert.assertTrue(1 <= glelTracker.reshapeCount); + Assert.assertTrue(1 <= glelTracker.displayCount); + Assert.assertEquals(0, glelTracker.disposeCount); + } + + // - create glad2 w/ survived context + { + final GLWindow glad2 = GLWindow.create(caps); + glad2.setSize(width+100, height+100); + glad2.setPosition(2*64+width, 64); + glad2.addWindowListener(quitAdapter); + glad2.setVisible(true); + snapshotGLEventListener.setMakeSnapshot(); + + Assert.assertNotNull(glad2.getContext()); + Assert.assertEquals(0, glad2.getGLEventListenerCount()); + + glls1.moveTo(glad2); + + Assert.assertEquals(1, glelTracker.initCount); + Assert.assertTrue(1 <= glelTracker.reshapeCount); + Assert.assertTrue(1 <= glelTracker.displayCount); + Assert.assertEquals(0, glelTracker.disposeCount); + Assert.assertEquals(glls1.context, glad2.getContext()); + Assert.assertEquals(3, glad2.getGLEventListenerCount()); + Assert.assertEquals(glls1.context.getGLReadDrawable(), glad2.getDelegatedDrawable()); + Assert.assertEquals(glls1.context.getGLDrawable(), glad2.getDelegatedDrawable()); + Assert.assertEquals(false, glls1.isOwner()); + + long t1 = System.currentTimeMillis(); + + while( !quitAdapter.shouldQuit() && ( t1 - t0 ) < duration/1 ) { + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + glad2.destroy(); + Assert.assertEquals(1, glelTracker.initCount); + Assert.assertTrue(1 <= glelTracker.reshapeCount); + Assert.assertTrue(1 <= glelTracker.displayCount); + Assert.assertEquals(1, glelTracker.disposeCount); + } + animator.stop(); + } + + // default timing for 2 switches + static long duration = 2200; // ms + + public static void main(String args[]) throws IOException { + for(int i=0; i s) { - s++; - System.err.println(s+" - switch - START "+ ( t1 - t0 )); - - // switch context _and_ the demo synchronously - GLDrawableUtil.swapGLContextAndAllGLEventListener(glad1, glad2); - - System.err.println(s+" - switch - END "+ ( t1 - t0 )); - } - Thread.sleep(100); - t1 = System.currentTimeMillis(); - } - - animator.stop(); - glad1.destroy(); - glad2.destroy(); - } - - @Test(timeout=30000) - public void testSwitch2GLWindowOneDemo() throws InterruptedException { - GearsES2 gears = new GearsES2(1); - final QuitAdapter quitAdapter = new QuitAdapter(); - - GLWindow glWindow1 = GLWindow.create(caps); - glWindow1.setTitle("win1"); - glWindow1.setSize(width, height); - glWindow1.setPosition(64, 64); - glWindow1.addGLEventListener(0, gears); - glWindow1.addWindowListener(quitAdapter); - - GLWindow glWindow2 = GLWindow.create(caps); - glWindow2.setTitle("win2"); - glWindow2.setSize(width+100, height+100); - glWindow2.setPosition(2*64+width, 64); - glWindow2.addWindowListener(quitAdapter); - - Animator animator = new Animator(); - animator.add(glWindow1); - animator.add(glWindow2); - animator.start(); - - glWindow1.setVisible(true); - glWindow2.setVisible(true); - - int s = 0; - long t0 = System.currentTimeMillis(); - long t1 = t0; - - while( !quitAdapter.shouldQuit() && ( t1 - t0 ) < duration ) { - if( ( t1 - t0 ) / period > s) { - s++; - System.err.println(s+" - switch - START "+ ( t1 - t0 )); - System.err.println(s+" - A w1-h 0x"+Long.toHexString(glWindow1.getHandle())+",-ctx 0x"+Long.toHexString(glWindow1.getContext().getHandle())); - System.err.println(s+" - A w2-h 0x"+Long.toHexString(glWindow2.getHandle())+",-ctx 0x"+Long.toHexString(glWindow2.getContext().getHandle())); - - // switch context _and_ the demo synchronously - GLDrawableUtil.swapGLContextAndAllGLEventListener(glWindow1, glWindow2); - - System.err.println(s+" - B w1-h 0x"+Long.toHexString(glWindow1.getHandle())+",-ctx 0x"+Long.toHexString(glWindow1.getContext().getHandle())); - System.err.println(s+" - B w2-h 0x"+Long.toHexString(glWindow2.getHandle())+",-ctx 0x"+Long.toHexString(glWindow2.getContext().getHandle())); - System.err.println(s+" - switch - END "+ ( t1 - t0 )); - } - Thread.sleep(100); - t1 = System.currentTimeMillis(); - } - - animator.stop(); - glWindow1.destroy(); - glWindow2.destroy(); - - } - - @Test(timeout=30000) - public void testSwitch2GLWindowEachWithOwnDemo() throws InterruptedException { - GearsES2 gears = new GearsES2(1); - RedSquareES2 rsquare = new RedSquareES2(1); - final QuitAdapter quitAdapter = new QuitAdapter(); - - GLWindow glWindow1 = GLWindow.create(caps); - glWindow1.setTitle("win1"); - glWindow1.setSize(width, height); - glWindow1.setPosition(64, 64); - glWindow1.addGLEventListener(0, gears); - glWindow1.addWindowListener(quitAdapter); - - GLWindow glWindow2 = GLWindow.create(caps); - glWindow2.setTitle("win2"); - glWindow2.setSize(width+100, height+100); - glWindow2.setPosition(2*64+width, 64); - glWindow2.addGLEventListener(0, rsquare); - glWindow2.addWindowListener(quitAdapter); - - Animator animator = new Animator(); - animator.add(glWindow1); - animator.add(glWindow2); - animator.start(); - - glWindow1.setVisible(true); - glWindow2.setVisible(true); - - int s = 0; - long t0 = System.currentTimeMillis(); - long t1 = t0; - - while( !quitAdapter.shouldQuit() && ( t1 - t0 ) < duration ) { - if( ( t1 - t0 ) / period > s) { - s++; - System.err.println(s+" - switch - START "+ ( t1 - t0 )); - System.err.println(s+" - A w1-h 0x"+Long.toHexString(glWindow1.getHandle())+",-ctx 0x"+Long.toHexString(glWindow1.getContext().getHandle())); - System.err.println(s+" - A w2-h 0x"+Long.toHexString(glWindow2.getHandle())+",-ctx 0x"+Long.toHexString(glWindow2.getContext().getHandle())); - GLDrawableUtil.swapGLContextAndAllGLEventListener(glWindow1, glWindow2); - System.err.println(s+" - B w1-h 0x"+Long.toHexString(glWindow1.getHandle())+",-ctx 0x"+Long.toHexString(glWindow1.getContext().getHandle())); - System.err.println(s+" - B w2-h 0x"+Long.toHexString(glWindow2.getHandle())+",-ctx 0x"+Long.toHexString(glWindow2.getContext().getHandle())); - System.err.println(s+" - switch - END "+ ( t1 - t0 )); - } - Thread.sleep(100); - t1 = System.currentTimeMillis(); - } - - animator.stop(); - // System.err.println("pre -del-w1: w1: "+glWindow1); - // System.err.println("pre -del-w1: w2: "+glWindow2); - glWindow1.destroy(); - // System.err.println("post-del-w1: w1: "+glWindow1); - // System.err.println("post-del-w1: w2: "+glWindow2); - glWindow2.destroy(); - - } - - // default timing for 2 switches - static long duration = 2200; // ms - static long period = 1000; // ms - - public static void main(String args[]) throws IOException { - for(int i=0; i Date: Sat, 26 Jan 2013 05:58:10 +0100 Subject: ProxySurface: Add 'NativeSurface getUpstreamSurface()' ; ProxySurfaceImpl: Don't cache 'displayHandle' - ProxySurface: Add 'NativeSurface getUpstreamSurface()' allowing querying direct access of a backing surface representing this instance. - Use case: EGLWrappedSurface - Default impl. returns null - ProxySurfaceImpl: Don't cache 'displayHandle' - getDisplayHandle() is 'final', no more 'shortcut' code allowed due to re-association incl. display handle. - See commit b738983638703bb721ee4c9820c8ef43e2252e73 --- .../jogamp/opengl/egl/EGLWrappedSurface.java | 1 + .../javax/media/nativewindow/ProxySurface.java | 15 +++++++++- .../jogamp/nativewindow/ProxySurfaceImpl.java | 32 ++++++++++++---------- 3 files changed, 32 insertions(+), 16 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java b/src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java index b36303392..2c2c6cc4b 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java @@ -20,6 +20,7 @@ public class EGLWrappedSurface extends WrappedSurface { } } + @Override public final NativeSurface getUpstreamSurface() { return ((EGLUpstreamSurfaceHook)super.getUpstreamSurfaceHook()).getUpstreamSurface(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java index 395fdc818..a83739a1d 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java @@ -65,7 +65,20 @@ public interface ProxySurface extends MutableSurface { /** Allow redefining the AbstractGraphicsConfiguration */ public void setGraphicsConfiguration(AbstractGraphicsConfiguration cfg); - /** Returns the set {@link UpstreamSurfaceHook}, or null if not set. */ + /** + * Return the upstream {@link NativeSurface} if used, otherwise null. + *

        + * An upstream {@link NativeSurface} may backup this {@link ProxySurface} instance's representation, + * e.g. via a {@link #setUpstreamSurfaceHook(UpstreamSurfaceHook) set} {@link UpstreamSurfaceHook}. + *

        + *

        + * One example is the JOGL EGLWrappedSurface, which might be backed up by a + * native platform NativeSurface (X11, WGL, CGL, ..). + *

        + */ + public NativeSurface getUpstreamSurface(); + + /** Returns the {@link UpstreamSurfaceHook} if {@link #setUpstreamSurfaceHook(UpstreamSurfaceHook) set}, otherwise null. */ public UpstreamSurfaceHook getUpstreamSurfaceHook(); /** diff --git a/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java index 63f56cbae..56e342793 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java @@ -42,7 +42,6 @@ import com.jogamp.common.util.locks.RecursiveLock; public abstract class ProxySurfaceImpl implements ProxySurface { private final SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); - protected long displayHandle; // convenient ref of config.screen.device.handle private AbstractGraphicsConfiguration config; // control access due to delegation private UpstreamSurfaceHook upstream; private long surfaceHandle_old; @@ -65,7 +64,6 @@ public abstract class ProxySurfaceImpl implements ProxySurface { throw new IllegalArgumentException("null UpstreamSurfaceHook"); } this.config = cfg; - this.displayHandle=config.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); this.upstream = upstream; this.surfaceHandle_old = 0; this.implBitfield = 0; @@ -76,8 +74,11 @@ public abstract class ProxySurfaceImpl implements ProxySurface { } @Override - public final UpstreamSurfaceHook getUpstreamSurfaceHook() { return upstream; } + public NativeSurface getUpstreamSurface() { return null; } + @Override + public final UpstreamSurfaceHook getUpstreamSurfaceHook() { return upstream; } + @Override public void setUpstreamSurfaceHook(UpstreamSurfaceHook hook) { if(null == hook) { @@ -96,7 +97,6 @@ public abstract class ProxySurfaceImpl implements ProxySurface { if(upstreamSurfaceHookLifecycleEnabled) { upstream.create(this); } - this.displayHandle=config.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); this.surfaceHandle_old = 0; } @@ -111,7 +111,6 @@ public abstract class ProxySurfaceImpl implements ProxySurface { } invalidateImpl(); } - this.displayHandle = 0; this.surfaceHandle_old = 0; } @@ -123,11 +122,6 @@ public abstract class ProxySurfaceImpl implements ProxySurface { throw new InternalError("UpstreamSurfaceHook given, but required method not implemented."); } - @Override - public final long getDisplayHandle() { - return displayHandle; - } - protected final AbstractGraphicsConfiguration getPrivateGraphicsConfiguration() { return config; } @@ -137,6 +131,11 @@ public abstract class ProxySurfaceImpl implements ProxySurface { return config.getNativeGraphicsConfiguration(); } + @Override + public final long getDisplayHandle() { + return config.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); + } + @Override public final void setGraphicsConfiguration(AbstractGraphicsConfiguration cfg) { config = cfg; @@ -305,12 +304,15 @@ public abstract class ProxySurfaceImpl implements ProxySurface { if(null == sink) { sink = new StringBuilder(); } - sink.append(getUpstreamSurfaceHook()). - append(", displayHandle 0x" + Long.toHexString(getDisplayHandle())). - append(", surfaceHandle 0x" + Long.toHexString(getSurfaceHandle())). - append(", size " + getWidth() + "x" + getHeight()).append(", "); + sink.append("displayHandle 0x" + Long.toHexString(getDisplayHandle())). + append("\n, surfaceHandle 0x" + Long.toHexString(getSurfaceHandle())). + append("\n, size " + getWidth() + "x" + getHeight()).append("\n, "); getUpstreamOptionBits(sink); - sink.append(", surfaceLock "+surfaceLock); + sink.append("\n, "+config). + append("\n, surfaceLock "+surfaceLock+"\n, "). + append(getUpstreamSurfaceHook()). + append("\n, upstreamSurface "+(null != getUpstreamSurface())); + // append("\n, upstreamSurface "+getUpstreamSurface()); return sink; } -- cgit v1.2.3 From 4e9054d996870467182b0e963fa80aa6740968b6 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 27 Jan 2013 04:36:53 +0100 Subject: Fix misc API docs .. --- src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java | 2 +- src/jogl/classes/javax/media/opengl/GLAutoDrawable.java | 4 ++-- src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java | 3 +++ 3 files changed, 6 insertions(+), 3 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java index 24116f199..206331ac0 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java +++ b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java @@ -48,7 +48,7 @@ import jogamp.opengl.GLDrawableImpl; /** * Fully functional {@link GLAutoDrawable} implementation - * utilizing already created created {@link GLDrawable} and {@link GLContext} instances. + * utilizing already created {@link GLDrawable} and {@link GLContext} instances. *

        * Since no native windowing system events are being processed, it is recommended * to handle at least: diff --git a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java index 612ff6bdb..6abe4308b 100644 --- a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java +++ b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java @@ -382,7 +382,7 @@ public interface GLAutoDrawable extends GLDrawable { * which will be executed within the next {@link #display()} call * after all registered {@link GLEventListener}s * {@link GLEventListener#display(GLAutoDrawable) display(GLAutoDrawable)} - * methods has been called. + * methods have been called. *

        * If no {@link GLAnimatorControl} is animating (default),
        * or if the current thread is the animator thread,
        @@ -391,7 +391,7 @@ public interface GLAutoDrawable extends GLDrawable { *

        *

        * If an {@link GLAnimatorControl animator} is running,
        - * no explicit {@link #display()} call is issued, allowing the {@link GLAnimatorControl animator} to perform it when it's due.
        + * no explicit {@link #display()} call is issued, allowing the {@link GLAnimatorControl animator} to perform at due time.
        *

        *

        * If wait is true the call blocks until the glRunnable diff --git a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java index a83739a1d..15a8738c5 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java @@ -44,6 +44,7 @@ public interface ProxySurface extends MutableSurface { /** * Implementation specific bit-value stating this {@link ProxySurface} owns the upstream's surface handle * @see #addUpstreamOptionBits(int) + * @see #clearUpstreamOptionBits(int) * @see #getUpstreamOptionBits() */ public static final int OPT_PROXY_OWNS_UPSTREAM_SURFACE = 1 << 6; @@ -51,6 +52,7 @@ public interface ProxySurface extends MutableSurface { /** * Implementation specific bit-value stating this {@link ProxySurface} owns the upstream's {@link AbstractGraphicsDevice}. * @see #addUpstreamOptionBits(int) + * @see #clearUpstreamOptionBits(int) * @see #getUpstreamOptionBits() */ public static final int OPT_PROXY_OWNS_UPSTREAM_DEVICE = 1 << 7; @@ -58,6 +60,7 @@ public interface ProxySurface extends MutableSurface { /** * Implementation specific bitvalue stating the upstream's {@link NativeSurface} is an invisible window, i.e. maybe incomplete. * @see #addUpstreamOptionBits(int) + * @see #clearUpstreamOptionBits(int) * @see #getUpstreamOptionBits() */ public static final int OPT_UPSTREAM_WINDOW_INVISIBLE = 1 << 8; -- cgit v1.2.3 From 2fe180fbee15b82e2ae14fe3c95887db246c874d Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 27 Jan 2013 14:08:07 +0100 Subject: Bug 665 (part 3) - Allow dis-association of GLContext's GLDrawable .. - Add EGL/ES2 tests, attempt to fix wrapped EGL case - Bug 665 (part 2) was commit 7fd5f76e1eb4bbf93fe9b1171744bd755d8f96e4 - Add EGL/ES2 tests in - TestGLContextDrawableSwitch01NEWT - TestGLContextDrawableSwitch11NEWT - Attempt to fix wrapped EGL case (incomplete) - Using EGL/ES w/ non native EGL device/surface, but natively wrapped instances (most of the cases), a 'complicated' delegation of Native-Upstream -> EGL-Proxy -> EGL-Instance is being used heavily relying on the objects lifecycle. GLEventListenerState tries to roll back the realized state and even sets the upstream device handle, but this doesn't seem to be sufficient on X11. Discussion: It might turn out that we only can implement the survival of GLContext and it's display device reliable w/ EGL within the GLAutoDrawable implementation, which can hold the previous not destructed instances. --- src/jogl/classes/jogamp/opengl/GLContextImpl.java | 9 +- .../jogamp/opengl/GLEventListenerState.java | 134 +++++++++++++++++---- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 2 +- .../javax/media/nativewindow/NativeSurface.java | 2 +- .../media/nativewindow/NativeWindowFactory.java | 5 +- .../acore/TestGLContextDrawableSwitch01NEWT.java | 57 +++++++-- .../acore/TestGLContextDrawableSwitch11NEWT.java | 63 +++++++--- 7 files changed, 219 insertions(+), 53 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index 2a2b6a8fd..b17fce569 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -206,11 +206,12 @@ public abstract class GLContextImpl extends GLContext { if( drawable == readWrite && ( setWriteOnly || drawableRead == readWrite ) ) { return drawable; // no change. } - final boolean lockHeld = lock.isOwner(Thread.currentThread()); + final Thread currentThread = Thread.currentThread(); + final boolean lockHeld = lock.isOwner(currentThread); if(lockHeld) { release(); } else if(lock.isLockedByOtherThread()) { // still could glitch .. - throw new GLException("GLContext current by other thread ("+lock.getOwner()+"), operation not allowed."); + throw new GLException("GLContext current by other thread "+lock.getOwner().getName()+", operation not allowed on this thread "+currentThread.getName()); } if( !setWriteOnly || drawableRead == drawable ) { // if !setWriteOnly || !explicitReadDrawable drawableRead = (GLDrawableImpl) readWrite; @@ -339,7 +340,7 @@ public abstract class GLContextImpl extends GLContext { } if (contextHandle != 0) { final int lockRes = drawable.lockSurface(); - if (NativeSurface.LOCK_SURFACE_NOT_READY == lockRes) { + if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { // this would be odd .. throw new GLException("Surface not ready to lock: "+drawable); } @@ -413,7 +414,7 @@ public abstract class GLContextImpl extends GLContext { } final int lockRes = drawable.lockSurface(); - if (NativeSurface.LOCK_SURFACE_NOT_READY == lockRes) { + if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { // this would be odd .. throw new GLException("Surface not ready to lock"); } diff --git a/src/jogl/classes/jogamp/opengl/GLEventListenerState.java b/src/jogl/classes/jogamp/opengl/GLEventListenerState.java index dea2bc85b..7a2569850 100644 --- a/src/jogl/classes/jogamp/opengl/GLEventListenerState.java +++ b/src/jogl/classes/jogamp/opengl/GLEventListenerState.java @@ -33,7 +33,9 @@ import java.util.List; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.NativeSurface; import javax.media.nativewindow.NativeWindowFactory; +import javax.media.nativewindow.ProxySurface; import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.GLAnimatorControl; import javax.media.opengl.GLAutoDrawable; @@ -43,6 +45,7 @@ import javax.media.opengl.GLEventListener; import javax.media.opengl.GLException; import javax.media.opengl.GLRunnable; +import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.nativewindow.MutableGraphicsConfiguration; /** @@ -68,7 +71,11 @@ import com.jogamp.nativewindow.MutableGraphicsConfiguration; *

        */ public class GLEventListenerState { - private GLEventListenerState(AbstractGraphicsScreen screen, GLCapabilitiesImmutable caps, GLContext context, int count, GLAnimatorControl anim) { + private static final boolean DEBUG = true; + + private GLEventListenerState(AbstractGraphicsScreen upstreamScreen, AbstractGraphicsScreen screen, GLCapabilitiesImmutable caps, + GLContext context, int count, GLAnimatorControl anim) { + this.upstreamScreen = upstreamScreen; this.screen = screen; this.caps = caps; this.context = context; @@ -89,6 +96,7 @@ public class GLEventListenerState { public final int listenerCount() { return listeners.length; } + public final AbstractGraphicsScreen upstreamScreen; public final AbstractGraphicsScreen screen; public final GLCapabilitiesImmutable caps; public final GLContext context; @@ -112,6 +120,11 @@ public class GLEventListenerState { owner = false; } } + + private static AbstractGraphicsScreen cloneScreen(AbstractGraphicsScreen aScreen) { + final AbstractGraphicsDevice aDevice2 = (AbstractGraphicsDevice) aScreen.getDevice().clone(); + return NativeWindowFactory.createScreen( aDevice2, aScreen.getIndex() ); + } /** * Moves all GLEventListenerState components from the given {@link GLAutoDrawable} @@ -138,19 +151,45 @@ public class GLEventListenerState { // Create new AbstractGraphicsScreen w/ cloned AbstractGraphicsDevice for future GLAutoDrawable // allowing this AbstractGraphicsDevice to loose ownership -> not closing display/device! - final AbstractGraphicsConfiguration aCfg1 = a.getNativeSurface().getGraphicsConfiguration(); - final GLCapabilitiesImmutable caps1 = (GLCapabilitiesImmutable) aCfg1.getChosenCapabilities(); - final AbstractGraphicsScreen aScreen1 = aCfg1.getScreen(); - final AbstractGraphicsDevice aDevice1 = aScreen1.getDevice(); - final AbstractGraphicsDevice aDevice2 = (AbstractGraphicsDevice) aDevice1.clone(); - final AbstractGraphicsScreen aScreen2 = NativeWindowFactory.createScreen( NativeWindowFactory.getNativeWindowType(false), aDevice2, aScreen1.getIndex() ); + final NativeSurface aSurface = a.getNativeSurface(); + final AbstractGraphicsConfiguration aCfg = aSurface.getGraphicsConfiguration(); + final AbstractGraphicsScreen aScreen1 = aCfg.getScreen(); + final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) aCfg.getChosenCapabilities(); + final AbstractGraphicsScreen aScreen2 = cloneScreen(aScreen1); + if( DEBUG ) { + System.err.println("X00 NativeSurface: "+aSurface.getClass().getName()+", "+aSurface); + } + aScreen1.getDevice().clearHandleOwner(); // don't close device handle + + final AbstractGraphicsScreen aUpScreen2; + { + AbstractGraphicsScreen _aUpScreen2=null; + if(aSurface instanceof ProxySurface) { + final ProxySurface aProxy = (ProxySurface)aSurface; + final NativeSurface aUpSurface = aProxy.getUpstreamSurface(); + if(null != aUpSurface) { + System.err.println("X00 UpstreamSurface: "+aUpSurface.getClass().getName()+", "+aUpSurface); + } + aProxy.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); // don't close device handle + if(null != aUpSurface) { + final AbstractGraphicsScreen aUpScreen1 = aUpSurface.getGraphicsConfiguration().getScreen(); + _aUpScreen2 = cloneScreen(aUpScreen1); + if(null != aUpScreen1) { + aUpScreen1.getDevice().clearHandleOwner(); // don't close device handle + } + System.err.println("X0X NativeSurface: "+aSurface.getClass().getName()+", "+aSurface); + System.err.println("X0X UpstreamSurface: "+aUpSurface.getClass().getName()+", "+aUpSurface); + } + } + aUpScreen2=_aUpScreen2; + } final GLAnimatorControl aAnim = a.getAnimator(); if( null != aAnim ) { aAnim.remove(a); // also handles ECT } - final GLEventListenerState glls = new GLEventListenerState(aScreen2, caps1, a.getContext(), aSz, aAnim); + final GLEventListenerState glls = new GLEventListenerState(aUpScreen2, aScreen2, caps, a.getContext(), aSz, aAnim); // // remove and cache all GLEventListener and their init-state @@ -167,7 +206,6 @@ public class GLEventListenerState { a.invoke(true, glFinish); a.setContext( null ); - aDevice1.clearHandleOwner(); // don't close handle return glls; } @@ -195,19 +233,71 @@ public class GLEventListenerState { final List aGLCmds = new ArrayList(); final int aSz = listenerCount(); - final MutableGraphicsConfiguration aCfg = (MutableGraphicsConfiguration) a.getNativeSurface().getGraphicsConfiguration(); + final NativeSurface aSurface = a.getNativeSurface(); + final MutableGraphicsConfiguration aCfg = (MutableGraphicsConfiguration) aSurface.getGraphicsConfiguration(); final GLCapabilitiesImmutable aCaps = (GLCapabilitiesImmutable) aCfg.getChosenCapabilities(); - if( caps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) != aCaps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) ) { - throw new GLException("XXX: Incompatible - Prev Holder: "+caps+", New Holder "+caps); + if( caps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) != aCaps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) || + caps.getVisualID(VisualIDHolder.VIDType.NATIVE) != aCaps.getVisualID(VisualIDHolder.VIDType.NATIVE) ) { + throw new GLException("Incompatible Capabilities - Prev-Holder: "+caps+", New-Holder "+caps); } - final GLContext prevContext = a.getContext(); - if( null != prevContext) { - prevContext.destroy(); + // Destroy and remove currently associated GLContext, if any (will be replaced) + { + final GLContext ctx = a.getContext(); + if( null != ctx) { + ctx.destroy(); + } + a.setContext( null ); + } + final boolean aRealized = a.isRealized(); + if( aRealized ) { + a.setRealized(false); + } + // Set new Screen and close previous one + { + if( DEBUG ) { + System.err.println("XX0 NativeSurface: "+aSurface.getClass().getName()+", "+aSurface); + } + final AbstractGraphicsScreen aScreen1 = aCfg.getScreen(); + aCfg.setScreen( screen ); + aScreen1.getDevice().close(); + System.err.println("XXX NativeSurface: "+aSurface.getClass().getName()+", "+aSurface); + } + // If using a ProxySurface w/ an upstream surface, set new Screen and close previous one on it + { + boolean upstreamSet = false; + if(aSurface instanceof ProxySurface) { + final ProxySurface aProxy = (ProxySurface)aSurface; + final NativeSurface aUpSurface = aProxy.getUpstreamSurface(); + if(null != aUpSurface) { + final MutableGraphicsConfiguration aUpCfg = (MutableGraphicsConfiguration) aUpSurface.getGraphicsConfiguration(); + final AbstractGraphicsScreen aUpScreen1 = aUpCfg.getScreen(); + if( null != upstreamScreen ) { + System.err.println("XX0 UpstreamSurface: "+aUpSurface.getClass().getName()+", "+aUpSurface); + aUpCfg.setScreen( upstreamScreen ); + aUpScreen1.getDevice().close(); + upstreamSet = true; + System.err.println("XXX UpstreamSurface: "+aUpSurface.getClass().getName()+", "+aUpSurface); + } else { + throw new GLException("Incompatible Surface config - Has Upstream-Surface: Prev-Holder = false, New-Holder = true"); + } + } + } + if( !upstreamSet && null != upstreamScreen ) { + throw new GLException("Incompatible Surface config - Has Upstream-Surface: Prev-Holder = true, New-Holder = false"); + } + } + + if( aRealized ) { + a.setRealized(true); + } + final boolean surfaceLocked = false; // NativeSurface.LOCK_SURFACE_NOT_READY < aSurface.lockSurface(); + try { + a.setContext( context ); + } finally { + if( surfaceLocked ) { + aSurface.unlockSurface(); + } } - final AbstractGraphicsScreen preScreen = aCfg.getScreen(); - aCfg.setScreen( screen ); - preScreen.getDevice().close(); - a.setContext( context ); owner = false; // @@ -220,15 +310,13 @@ public class GLEventListenerState { } } aGLCmds.add(glFinish); - a.invoke(true, aGLCmds); + a.invoke(aRealized, aGLCmds); // only wait if already realized // add all cached GLEventListener to their destination and fix their init-state for(int i=0; i - * boolean ok = lockSurface() > LOCK_SURFACE_NOT_READY; + * boolean ok = LOCK_SURFACE_NOT_READY < lockSurface(); * *

        *

        diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 07702c762..b6a052253 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -435,9 +435,10 @@ public abstract class NativeWindowFactory { /** * @param device * @param screen -1 is default screen of the given device, e.g. maybe 0 or determined by native API. >= 0 is specific screen - * @return newly created AbstractGraphicsScreen of given native type + * @return newly created AbstractGraphicsScreen matching device's native type */ - public static AbstractGraphicsScreen createScreen(String type, AbstractGraphicsDevice device, int screen) { + public static AbstractGraphicsScreen createScreen(AbstractGraphicsDevice device, int screen) { + final String type = device.getType(); if( TYPE_X11 == type ) { final X11GraphicsDevice x11Device = (X11GraphicsDevice)device; if(0 > screen) { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitch01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitch01NEWT.java index 08a0857a9..8b1449493 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitch01NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitch01NEWT.java @@ -64,14 +64,18 @@ import org.junit.Test; * i.e. ctx1/draw1, ctx2/draw2 -> ctx1/draw2, ctx2/draw1. */ public class TestGLContextDrawableSwitch01NEWT extends UITestCase { - static GLProfile glp; - static GLCapabilities caps; static int width, height; + static GLCapabilities getCaps(String profile) { + if( !GLProfile.isAvailable(profile) ) { + System.err.println("Profile "+profile+" n/a"); + return null; + } + return new GLCapabilities(GLProfile.get(profile)); + } + @BeforeClass public static void initClass() { - glp = GLProfile.getGL2ES2(); - caps = new GLCapabilities(glp); width = 256; height = 256; } @@ -124,7 +128,20 @@ public class TestGLContextDrawableSwitch01NEWT extends UITestCase { } @Test(timeout=30000) - public void testSwitch2WindowSingleContext() throws InterruptedException { + public void testSwitch2WindowSingleContextGL2ES2() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2ES2); + if(null == reqGLCaps) return; + testSwitch2WindowSingleContextImpl(reqGLCaps); + } + + @Test(timeout=30000) + public void testSwitch2WindowSingleContextGLES2() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + testSwitch2WindowSingleContextImpl(reqGLCaps); + } + + private void testSwitch2WindowSingleContextImpl(GLCapabilities caps) throws InterruptedException { final QuitAdapter quitAdapter = new QuitAdapter(); GLAutoDrawable glad1 = createGLAutoDrawable(caps, 64, 64, width, height, quitAdapter); @@ -178,7 +195,20 @@ public class TestGLContextDrawableSwitch01NEWT extends UITestCase { } @Test(timeout=30000) - public void testSwitch2GLWindowOneDemo() throws InterruptedException { + public void testSwitch2GLWindowOneDemoGL2ES2() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2ES2); + if(null == reqGLCaps) return; + testSwitch2GLWindowOneDemoImpl(reqGLCaps); + } + + @Test(timeout=30000) + public void testSwitch2GLWindowOneDemoGLES2() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + testSwitch2GLWindowOneDemoImpl(reqGLCaps); + } + + private void testSwitch2GLWindowOneDemoImpl(GLCapabilities caps) throws InterruptedException { final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); final GearsES2 gears = new GearsES2(1); final QuitAdapter quitAdapter = new QuitAdapter(); @@ -238,7 +268,20 @@ public class TestGLContextDrawableSwitch01NEWT extends UITestCase { } @Test(timeout=30000) - public void testSwitch2GLWindowEachWithOwnDemo() throws InterruptedException { + public void testSwitch2GLWindowEachWithOwnDemoGL2ES2() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2ES2); + if(null == reqGLCaps) return; + testSwitch2GLWindowEachWithOwnDemoImpl(reqGLCaps); + } + + @Test(timeout=30000) + public void testSwitch2GLWindowEachWithOwnDemoGLES2() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + testSwitch2GLWindowEachWithOwnDemoImpl(reqGLCaps); + } + + public void testSwitch2GLWindowEachWithOwnDemoImpl(GLCapabilities caps) throws InterruptedException { final GearsES2 gears = new GearsES2(1); final RedSquareES2 rsquare = new RedSquareES2(1); final QuitAdapter quitAdapter = new QuitAdapter(); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitch11NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitch11NEWT.java index cd308e165..4af9a3932 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitch11NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLContextDrawableSwitch11NEWT.java @@ -69,19 +69,23 @@ import org.junit.Test; *

        */ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { - static GLProfile glp; - static GLCapabilities caps; static int width, height; + static GLCapabilities getCaps(String profile) { + if( !GLProfile.isAvailable(profile) ) { + System.err.println("Profile "+profile+" n/a"); + return null; + } + return new GLCapabilities(GLProfile.get(profile)); + } + @BeforeClass public static void initClass() { - glp = GLProfile.getGL2ES2(); - caps = new GLCapabilities(glp); width = 256; height = 256; } - private GLAutoDrawable createGLAutoDrawable(GLCapabilities caps, int x, int y, int width, int height, WindowListener wl) throws InterruptedException { + private GLAutoDrawable createGLAutoDrawableWithoutContext(GLCapabilities caps, int x, int y, int width, int height, WindowListener wl) throws InterruptedException { final Window window = NewtFactory.createWindow(caps); Assert.assertNotNull(window); window.setPosition(x, y); @@ -126,7 +130,20 @@ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { } @Test(timeout=30000) - public void test01() throws InterruptedException { + public void test01GLADDelegateGL2ES2() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2ES2); + if(null == reqGLCaps) return; + test01GLADDelegateImpl(reqGLCaps); + } + + @Test(timeout=30000) + public void test01GLADDelegateGLES2() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + test01GLADDelegateImpl(reqGLCaps); + } + + private void test01GLADDelegateImpl(GLCapabilities caps) throws InterruptedException { final QuitAdapter quitAdapter = new QuitAdapter(); final GLEventListenerCounter glelCounter = new GLEventListenerCounter(); @@ -140,7 +157,7 @@ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { // - create glad1 w/o context // - create context using glad1 and assign it to glad1 { - final GLAutoDrawable glad1 = createGLAutoDrawable(caps, 64, 64, width, height, quitAdapter); + final GLAutoDrawable glad1 = createGLAutoDrawableWithoutContext(caps, 64, 64, width, height, quitAdapter); final GLContext context1 = glad1.createContext(null); glad1.setContext(context1); animator.add(glad1); @@ -149,7 +166,7 @@ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { glad1.addGLEventListener(new GearsES2(1)); glad1.addGLEventListener(snapshotGLEventListener); snapshotGLEventListener.setMakeSnapshot(); - + long t1 = System.currentTimeMillis(); while( !quitAdapter.shouldQuit() && ( t1 - t0 ) < duration/2 ) { @@ -157,8 +174,6 @@ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { t1 = System.currentTimeMillis(); } - // - dis-associate context from glad1 - // - destroy glad1 Assert.assertEquals(1, glelCounter.initCount); Assert.assertTrue(1 <= glelCounter.reshapeCount); Assert.assertTrue(1 <= glelCounter.displayCount); @@ -168,6 +183,8 @@ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { Assert.assertEquals(context1.getGLReadDrawable(), glad1.getDelegatedDrawable()); Assert.assertEquals(context1.getGLDrawable(), glad1.getDelegatedDrawable()); + // - dis-associate context from glad1 + // - destroy glad1 glls1 = GLEventListenerState.moveFrom(glad1); Assert.assertEquals(1, glelCounter.initCount); @@ -191,7 +208,7 @@ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { // - create glad2 w/ survived context { - final GLAutoDrawable glad2 = createGLAutoDrawable(caps, 2*64+width, 64, width+100, height+100, quitAdapter); + final GLAutoDrawable glad2 = createGLAutoDrawableWithoutContext(caps, 2*64+width, 64, width+100, height+100, quitAdapter); snapshotGLEventListener.setMakeSnapshot(); Assert.assertEquals(null, glad2.getContext()); @@ -199,6 +216,8 @@ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { glls1.moveTo(glad2); + Assert.assertTrue(glad2.isRealized()); + Assert.assertEquals(1, glelCounter.initCount); Assert.assertTrue(1 <= glelCounter.reshapeCount); Assert.assertTrue(1 <= glelCounter.displayCount); @@ -226,7 +245,20 @@ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { } @Test(timeout=30000) - public void test02() throws InterruptedException { + public void test02GLWindowGL2ES2() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2ES2); + if(null == reqGLCaps) return; + test02GLWindowImpl(reqGLCaps); + } + + @Test(timeout=30000) + public void test02GLWindowGLES2() throws InterruptedException { + final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); + if(null == reqGLCaps) return; + test02GLWindowImpl(reqGLCaps); + } + + private void test02GLWindowImpl(GLCapabilities caps) throws InterruptedException { final QuitAdapter quitAdapter = new QuitAdapter(); final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); @@ -244,7 +276,6 @@ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { glad1.setSize(width, height); glad1.setPosition(64, 64); glad1.addWindowListener(quitAdapter); - glad1.setVisible(true); animator.add(glad1); glad1.addGLEventListener(glelTracker); @@ -252,6 +283,8 @@ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { glad1.addGLEventListener(snapshotGLEventListener); snapshotGLEventListener.setMakeSnapshot(); + glad1.setVisible(true); + long t1 = System.currentTimeMillis(); while( !quitAdapter.shouldQuit() && ( t1 - t0 ) < duration/2 ) { @@ -297,13 +330,13 @@ public class TestGLContextDrawableSwitch11NEWT extends UITestCase { glad2.setSize(width+100, height+100); glad2.setPosition(2*64+width, 64); glad2.addWindowListener(quitAdapter); - glad2.setVisible(true); snapshotGLEventListener.setMakeSnapshot(); + glad2.setVisible(true); Assert.assertNotNull(glad2.getContext()); Assert.assertEquals(0, glad2.getGLEventListenerCount()); - glls1.moveTo(glad2); + glls1.moveTo(glad2); Assert.assertEquals(1, glelTracker.initCount); Assert.assertTrue(1 <= glelTracker.reshapeCount); -- cgit v1.2.3 From f6e6fab2a7ddfb5c9b614cb072c27ff697629161 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 14 Feb 2013 15:12:18 +0100 Subject: Fix OSX CALayer Bug 690 and Bug 691: Occasional Freeze on CVDisplayLinkStop; Layers and native GL-Context are _not_ Released ; Java Side wait for Main-Thread - Fix Bug 690: Occasional Freeze on CVDisplayLinkStop - NSOpenGLLayer.disableAnimation() shall not claim the renderLock mutex, since the CVDisplayLink callback could be waiting for the lock. This waiting callback could freeze the call to CVDisplayLinkStop. - Fix Bug 691: Layers and native GL-Context are _not_ Released - Following proper release cycle: Context unrealized: - JAWTWindow.detachSurfaceLayer() -> OSXUtil.RemoveCASublayer(..) - CGL.releaseNSOpenGLLayer(..) JAWTWindow.destroy() - MacOSXJAWTWindow.UnsetJAWTRootSurfaceLayer(..) - OSXUtil.DestroyCALayer(..) - 'Magic' CALayer release calls (w/o manual retain beforehand) at: - OSXUtil.RemoveCASublayer(..): [subLayer release] - MacOSXJAWTWindow.UnsetJAWTRootSurfaceLayer(..): [rootLayer release] - OSXUtil.DestroyCALayer(..): [rootLayer release] - 'Magic' NSOpenGLLayer's NSOpenGLContext dealloc: - [NSOpenGLContext clearDrawable] - CGLDestroyContext( [NSOpenGLContext CGLContextObj] ) - Java Side wait for Main-Thread - Waiting for the delegated Main-Thread on the Java side eases debugging and won't block the Main-Thread in native code. - Utilizing this for all CALayer calls Test case: TestGLCanvasAddRemove01SwingAWT --- make/scripts/tests-osx-x64-java7.sh | 2 +- make/scripts/tests-osx-x64.sh | 4 + make/scripts/tests.sh | 14 +- .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 5 +- .../macosx/MacOSXWindowSystemInterface-calayer.m | 116 +++++++--- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 14 +- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 2 - .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 57 ++++- .../jogamp/nativewindow/macosx/OSXUtil.java | 83 +++++-- src/nativewindow/native/macosx/OSXmisc.m | 170 ++++++++------ .../jogl/awt/TestGLCanvasAddRemove01SwingAWT.java | 257 +++++++++++++++++++++ .../junit/jogl/demos/es2/awt/TestGearsES2AWT.java | 11 +- 12 files changed, 596 insertions(+), 139 deletions(-) create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAddRemove01SwingAWT.java (limited to 'src/nativewindow') diff --git a/make/scripts/tests-osx-x64-java7.sh b/make/scripts/tests-osx-x64-java7.sh index 36eee3255..378938167 100755 --- a/make/scripts/tests-osx-x64-java7.sh +++ b/make/scripts/tests-osx-x64-java7.sh @@ -8,6 +8,6 @@ export JAVA_HOME PATH spath=`dirname $0` -. $spath/tests.sh $JAVA_HOME/bin/java -d64 ../build-macosx-java7 $* +. $spath/tests.sh $JAVA_HOME/bin/java -d64 ../build-macosx $* diff --git a/make/scripts/tests-osx-x64.sh b/make/scripts/tests-osx-x64.sh index 748cf39a9..01f3e1bb2 100755 --- a/make/scripts/tests-osx-x64.sh +++ b/make/scripts/tests-osx-x64.sh @@ -2,6 +2,10 @@ export DYLD_LIBRARY_PATH=/usr/local/lib:$DYLD_LIBRARY_PATH +JAVA_HOME=`/usr/libexec/java_home -version 1.6` +PATH=$JAVA_HOME/bin:$PATH +export JAVA_HOME PATH + spath=`dirname $0` . $spath/tests.sh /usr/bin/java -d64 ../build-macosx $* diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index d00e3c133..198a8f2e6 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -33,7 +33,7 @@ MOSX_MT=0 uname -a | grep -i Darwin && MOSX=1 if [ $MOSX -eq 1 ] ; then echo setup OSX environment vars - export NSZombieEnabled=YES + #export NSZombieEnabled=YES export NSTraceEvents=YES #export OBJC_PRINT_EXCEPTIONS=YES echo NSZombieEnabled $NSZombieEnabled 2>&1 | tee -a java-run.log @@ -89,7 +89,7 @@ function jrun() { #D_ARGS="-Djogl.debug.FBObject" #D_ARGS="-Djogl.debug.GLSLCode" #D_ARGS="-Djogl.debug.GLSLCode -Djogl.debug.DebugGL -Djogl.debug.TraceGL" - #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch" + #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch -Dnativewindow.debug.JAWT" #D_ARGS="-Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogl.debug.FixedFuncPipeline -Djogl.debug.GLSLCode" #D_ARGS="-Djogl.debug.FixedFuncPipeline -Djogl.debug.GLSLState" @@ -175,7 +175,7 @@ function jrun() { #D_ARGS="-Dnewt.debug.Window" #D_ARGS="-Xprof" #D_ARGS="-Dnativewindow.debug=all" - #D_ARGS="-Djogl.debug.GLCanvas" + #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Java2D -Djogl.debug.GLJPanel" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Animator" #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.X11Util.XSync" #D_ARGS="-Dnativewindow.debug.X11Util.XSync -Dnativewindow.debug.ToolkitLock.TraceLock" @@ -415,6 +415,12 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyPressReleaseUnmaskRepeatAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyCodesAWT $* + +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT $* +testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAddRemove01SwingAWT $* + #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyCodeModifiersAWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNEWTWindowAWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersAWTCanvas $* @@ -538,7 +544,7 @@ function testawtswt() { # ATI/Linux: XCB Unknown request in queue while dequeuing # Most likely this is a multi-threaded client and XInitThreads has not been called # ../../src/xcb_io.c:178: dequeue_pending_request: Assertion `!xcb_xlib_unknown_req_in_deq' failed -testnoawt com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext01VSyncAnimNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext01VSyncAnimNEWT $* # this one works - though ! #testnoawt com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext02FPSAnimNEWT $* diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 838a0387d..0deaa2987 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -709,7 +709,10 @@ public abstract class MacOSXCGLContext extends GLContextImpl // still having a valid OLS attached to surface (parent OLS could have been removed) ols.detachSurfaceLayer(); } - CGL.releaseNSOpenGLLayer(nsOpenGLLayer); + OSXUtil.RunOnMainThread(true, new Runnable() { + public void run() { + CGL.releaseNSOpenGLLayer(nsOpenGLLayer); + } } ); if( null != gl3ShaderProgram ) { gl3ShaderProgram.destroy(MacOSXCGLContext.this.gl.getGL3()); gl3ShaderProgram = null; diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index b37930587..4334fc676 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -41,6 +41,8 @@ extern GLboolean glIsVertexArray (GLuint array); // // #define DBG_PERF 1 +// #define DBG_LIFECYCLE 1 + /** * Capture setView(NULL), which produces a 'invalid drawable' message * @@ -52,6 +54,10 @@ extern GLboolean glIsVertexArray (GLuint array); - (id)initWithFormat:(NSOpenGLPixelFormat *)format shareContext:(NSOpenGLContext *)share; - (void)setView:(NSView *)view; - (void)update; +#ifdef DBG_LIFECYCLE +- (id)retain; +- (oneway void)release; +#endif - (void)dealloc; @end @@ -82,11 +88,36 @@ extern GLboolean glIsVertexArray (GLuint array); DBG_PRINT("MyNSOpenGLContext.update.X\n"); } +#ifdef DBG_LIFECYCLE + +- (id)retain +{ + DBG_PRINT("MyNSOpenGLContext::retain.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + // NSLog(@"MyNSOpenGLContext::retain: %@",[NSThread callStackSymbols]); + id o = [super retain]; + DBG_PRINT("MyNSOpenGLContext::retain.X: %p (refcnt %d)\n", o, (int)[o retainCount]); + return o; +} + +- (oneway void)release +{ + DBG_PRINT("MyNSOpenGLContext::release.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + [super release]; + // DBG_PRINT("MyNSOpenGLContext::release.X: %p (refcnt %d)\n", self, (int)[self retainCount]); +} + +#endif + - (void)dealloc { - DBG_PRINT("MyNSOpenGLContext.dealloc: this.0 %p\n", self); + CGLContextObj cglCtx = [self CGLContextObj]; + DBG_PRINT("MyNSOpenGLContext::dealloc.0 %p (refcnt %d) - CGL-Ctx %p\n", self, (int)[self retainCount], cglCtx); + [self clearDrawable]; + if( NULL != cglCtx ) { + CGLDestroyContext( cglCtx ); + } [super dealloc]; - DBG_PRINT("MyNSOpenGLContext.dealloc.X: %p\n", self); + // DBG_PRINT("MyNSOpenGLContext.dealloc.X: %p\n", self); } @end @@ -95,6 +126,7 @@ extern GLboolean glIsVertexArray (GLuint array); { @private GLfloat gl_texCoords[8]; + NSOpenGLContext* myCtx; @protected NSOpenGLContext* parentCtx; @@ -150,6 +182,10 @@ extern GLboolean glIsVertexArray (GLuint array); - (void)pauseAnimation:(Bool)pause; - (void)deallocPBuffer; - (void)releaseLayer; +#ifdef DBG_LIFECYCLE +- (id)retain; +- (oneway void)release; +#endif - (void)dealloc; - (void)setSwapInterval:(int)interval; - (void)tick; @@ -209,6 +245,7 @@ static const GLfloat gl_verts[] = { pthread_mutex_init(&renderLock, &renderLockAttr); // recursive pthread_cond_init(&renderSignal, NULL); // no attribute + myCtx = NULL; { int i; for(i=0; i<8; i++) { @@ -418,15 +455,15 @@ static const GLfloat gl_verts[] = { { DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.0: %p (refcnt %d) - pfmt %p, parent %p\n", self, (int)[self retainCount], pixelFormat, parentCtx); - NSOpenGLContext * nctx = [[MyNSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:parentCtx]; - DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.X: new-ctx %p\n", nctx); - return nctx; + // NSLog(@"MyNSOpenGLLayer::openGLContextForPixelFormat: %@",[NSThread callStackSymbols]); + myCtx = [[MyNSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:parentCtx]; + DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.X: new-ctx %p\n", myCtx); + return myCtx; } - (void)disableAnimation { - DBG_PRINT("MyNSOpenGLLayer::disableAnimation: %p (refcnt %d) - displayLink %p\n", self, (int)[self retainCount], displayLink); - pthread_mutex_lock(&renderLock); + DBG_PRINT("MyNSOpenGLLayer::disableAnimation.0: %p (refcnt %d) - displayLink %p\n", self, (int)[self retainCount], displayLink); [self setAsynchronous: NO]; if(NULL != displayLink) { #ifdef HAS_CADisplayLink @@ -438,35 +475,63 @@ static const GLfloat gl_verts[] = { #endif displayLink = NULL; } - pthread_mutex_unlock(&renderLock); + DBG_PRINT("MyNSOpenGLLayer::disableAnimation.X: %p (refcnt %d) - displayLink %p\n", self, (int)[self retainCount], displayLink); } - (void)releaseLayer { DBG_PRINT("MyNSOpenGLLayer::releaseLayer.0: %p (refcnt %d)\n", self, (int)[self retainCount]); - pthread_mutex_lock(&renderLock); [self disableAnimation]; + pthread_mutex_lock(&renderLock); [self deallocPBuffer]; - [[self openGLContext] release]; + // [[self openGLContext] release]; + if( NULL != myCtx ) { + [myCtx release]; + // [myCtx dealloc]; + myCtx = NULL; + } + parentCtx = NULL; [parentPixelFmt release]; - [self release]; - DBG_PRINT("MyNSOpenGLLayer::releaseLayer.X: %p (refcnt %d)\n", self, (int)[self retainCount]); pthread_mutex_unlock(&renderLock); + [self release]; + DBG_PRINT("MyNSOpenGLLayer::releaseLayer.X: %p\n", self); } +#ifdef DBG_LIFECYCLE + +- (id)retain +{ + DBG_PRINT("MyNSOpenGLLayer::retain.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + // NSLog(@"MyNSOpenGLLayer::retain: %@",[NSThread callStackSymbols]); + id o = [super retain]; + DBG_PRINT("MyNSOpenGLLayer::retain.X: %p (refcnt %d)\n", o, (int)[o retainCount]); + return o; +} + +- (oneway void)release +{ + DBG_PRINT("MyNSOpenGLLayer::release.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + // NSLog(@"MyNSOpenGLLayer::release: %@",[NSThread callStackSymbols]); + [super release]; + // DBG_PRINT("MyNSOpenGLLayer::release.X: %p (refcnt %d)\n", self, (int)[self retainCount]); +} + +#endif + - (void)dealloc { DBG_PRINT("MyNSOpenGLLayer::dealloc.0 %p (refcnt %d)\n", self, (int)[self retainCount]); // NSLog(@"MyNSOpenGLLayer::dealloc: %@",[NSThread callStackSymbols]); - pthread_mutex_lock(&renderLock); [self disableAnimation]; + pthread_mutex_lock(&renderLock); [self deallocPBuffer]; + // [[self openGLContext] dealloc]; pthread_mutex_unlock(&renderLock); pthread_cond_destroy(&renderSignal); pthread_mutex_destroy(&renderLock); [super dealloc]; - DBG_PRINT("MyNSOpenGLLayer::dealloc.X %p\n", self); + // DBG_PRINT("MyNSOpenGLLayer::dealloc.X %p\n", self); } - (Bool)isGLSourceValid @@ -752,32 +817,27 @@ static const GLfloat gl_verts[] = { @end NSOpenGLLayer* createNSOpenGLLayer(NSOpenGLContext* ctx, int gl3ShaderProgramName, NSOpenGLPixelFormat* fmt, NSOpenGLPixelBuffer* p, uint32_t texID, Bool opaque, int texWidth, int texHeight) { - // This simply crashes after dealloc() has been called .. ie. ref-count -> 0 too early ? - // However using alloc/init, actual dealloc happens at JAWT destruction, hence too later IMHO. - // return [[MyNSOpenGLLayer layer] setupWithContext:ctx pixelFormat: fmt pbuffer: p texIDArg: (GLuint)texID - // opaque: opaque texWidth: texWidth texHeight: texHeight]; - return [[[MyNSOpenGLLayer alloc] init] setupWithContext:ctx gl3ShaderProgramName: (GLuint)gl3ShaderProgramName pixelFormat: fmt pbuffer: p texIDArg: (GLuint)texID opaque: opaque texWidth: texWidth texHeight: texHeight]; } void setNSOpenGLLayerSwapInterval(NSOpenGLLayer* layer, int interval) { - MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; [l setSwapInterval: interval]; [pool release]; } void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_micros) { - MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; [l waitUntilRenderSignal: to_micros]; [pool release]; } void setNSOpenGLLayerNeedsDisplayFBO(NSOpenGLLayer* layer, uint32_t texID) { - MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; Bool shallDraw; // volatile OK @@ -799,8 +859,8 @@ void setNSOpenGLLayerNeedsDisplayFBO(NSOpenGLLayer* layer, uint32_t texID) { } void setNSOpenGLLayerNeedsDisplayPBuffer(NSOpenGLLayer* layer, NSOpenGLPixelBuffer* p) { - MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; Bool shallDraw; if( NO == [l isSamePBuffer: p] ) { @@ -825,16 +885,10 @@ void setNSOpenGLLayerNeedsDisplayPBuffer(NSOpenGLLayer* layer, NSOpenGLPixelBuff } void releaseNSOpenGLLayer(NSOpenGLLayer* layer) { - MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; DBG_PRINT("MyNSOpenGLLayer::releaseNSOpenGLLayer.0: %p\n", l); - - if ( [NSThread isMainThread] == YES ) { - [l releaseLayer]; - } else { - [l performSelectorOnMainThread:@selector(releaseLayer) withObject:nil waitUntilDone:NO]; - } - + [l releaseLayer]; DBG_PRINT("MyNSOpenGLLayer::releaseNSOpenGLLayer.X: %p\n", l); [pool release]; } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 8527a0200..007a917a6 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -205,7 +205,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } try { if(DEBUG) { - System.err.println("JAWTWindow.attachSurfaceHandle(): 0x"+Long.toHexString(layerHandle) + ", bounds "+bounds); + System.err.println("JAWTWindow.attachSurfaceHandle(): "+toHexString(layerHandle) + ", bounds "+bounds); } attachSurfaceLayerImpl(layerHandle); offscreenSurfaceLayer = layerHandle; @@ -229,7 +229,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } try { if(DEBUG) { - System.err.println("JAWTWindow.detachSurfaceHandle(): 0x"+Long.toHexString(offscreenSurfaceLayer)); + System.err.println("JAWTWindow.detachSurfaceHandle(): osh "+toHexString(offscreenSurfaceLayer)); } detachSurfaceLayerImpl(offscreenSurfaceLayer); offscreenSurfaceLayer = 0; @@ -341,7 +341,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if(LOCK_SUCCESS == res && drawable_old != drawable) { res = LOCK_SURFACE_CHANGED; if(DEBUG) { - System.err.println("JAWTWindow: surface change 0x"+Long.toHexString(drawable_old)+" -> 0x"+Long.toHexString(drawable)); + System.err.println("JAWTWindow: surface change "+toHexString(drawable_old)+" -> "+toHexString(drawable)); // Thread.dumpStack(); } } @@ -549,8 +549,8 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, StringBuilder sb = new StringBuilder(); sb.append("JAWT-Window["+ - "windowHandle 0x"+Long.toHexString(getWindowHandle())+ - ", surfaceHandle 0x"+Long.toHexString(getSurfaceHandle())+ + "windowHandle "+toHexString(getWindowHandle())+ + ", surfaceHandle "+toHexString(getSurfaceHandle())+ ", bounds "+bounds+", insets "+insets+ ", shallUseOffscreenLayer "+shallUseOffscreenLayer+", isOffscreenLayerSurface "+isOffscreenLayerSurface); if(null!=component) { @@ -566,4 +566,8 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return sb.toString(); } + + protected final String toHexString(long l) { + return "0x"+Long.toHexString(l); + } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index 2b49f6745..5479f2495 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -38,7 +38,6 @@ import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import javax.media.nativewindow.AbstractGraphicsScreen; -import javax.media.nativewindow.DefaultGraphicsScreen; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowFactory; @@ -49,7 +48,6 @@ import com.jogamp.common.util.VersionNumber; import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsDevice; -import com.jogamp.nativewindow.x11.X11GraphicsScreen; import jogamp.nativewindow.macosx.OSXUtil; import jogamp.nativewindow.x11.X11Lib; diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 9e270d403..9b06cce1a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -51,6 +51,7 @@ import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.MutableSurface; import javax.media.nativewindow.util.Point; +import com.jogamp.common.util.Function; import com.jogamp.nativewindow.awt.JAWTWindow; import jogamp.nativewindow.jawt.JAWT; @@ -70,11 +71,40 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } protected void invalidateNative() { + if(DEBUG) { + System.err.println("MacOSXJAWTWindow.invalidateNative(): osh-enabled "+isOffscreenLayerSurfaceEnabled()+ + ", osh-set "+offscreenSurfaceHandleSet+ + ", osh "+toHexString(offscreenSurfaceHandle)+ + ", rsh "+toHexString(rootSurfaceLayerHandle)+ + ", wh "+toHexString(windowHandle)); + } offscreenSurfaceHandle=0; offscreenSurfaceHandleSet=false; - if(isOffscreenLayerSurfaceEnabled()) { + if( isOffscreenLayerSurfaceEnabled() ) { if(0 != rootSurfaceLayerHandle) { + final JAWT jawt = getJAWT(); + if( null != jawt ) { + final JAWT_DrawingSurface ds = jawt.GetDrawingSurface(component); + if (ds != null) { + if ( 0 == ( ds.Lock() & JAWTFactory.JAWT_LOCK_ERROR ) ) { + JAWT_DrawingSurfaceInfo dsi = null; + try { + dsi = ds.GetDrawingSurfaceInfo(); + if(! UnsetJAWTRootSurfaceLayer(dsi.getBuffer(), rootSurfaceLayerHandle)) { + System.err.println("Error clearing JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayerHandle)); + } + } finally { + if ( null != dsi ) { + ds.FreeDrawingSurfaceInfo(dsi); + } + ds.Unlock(); + } + } + jawt.FreeDrawingSurface(ds); + } + } OSXUtil.DestroyCALayer(rootSurfaceLayerHandle); + rootSurfaceLayerHandle = 0; } if(0 != windowHandle) { @@ -107,7 +137,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { throw new java.lang.UnsupportedOperationException("Not using CALAYER"); } if(DEBUG) { - System.err.println("MacOSXJAWTWindow.setSurfaceHandle(): 0x"+Long.toHexString(surfaceHandle)); + System.err.println("MacOSXJAWTWindow.setSurfaceHandle(): "+toHexString(surfaceHandle)); } this.offscreenSurfaceHandle = surfaceHandle; this.offscreenSurfaceHandleSet = true; @@ -117,6 +147,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { // use offscreen if supported and [ applet or requested ] return JAWTUtil.getJAWT(getShallUseOffscreenLayer() || isApplet()); } + protected int lockSurfaceImpl() throws NativeWindowException { int ret = NativeWindow.LOCK_SURFACE_NOT_READY; ds = getJAWT().GetDrawingSurface(component); @@ -189,7 +220,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } else { drawable = OSXUtil.GetNSView(windowHandle); if(0 == drawable) { - errMsg = "Null NSView of NSWindow 0x"+Long.toHexString(windowHandle); + errMsg = "Null NSView of NSWindow "+toHexString(windowHandle); } } if(null == errMsg) { @@ -204,8 +235,8 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { rootSurfaceLayerHandle = OSXUtil.CreateCALayer(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); if(0 == rootSurfaceLayerHandle) { errMsg = "Could not create root CALayer"; - } else if(!SetJAWTRootSurfaceLayer0(dsi.getBuffer(), rootSurfaceLayerHandle)) { - errMsg = "Could not set JAWT rootSurfaceLayerHandle 0x"+Long.toHexString(rootSurfaceLayerHandle); + } else if(!SetJAWTRootSurfaceLayer(dsi.getBuffer(), rootSurfaceLayerHandle)) { + errMsg = "Could not set JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayerHandle); } } } @@ -265,9 +296,23 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { return getLocationOnScreenNonBlocking(storage, component); } protected Point getLocationOnScreenNativeImpl(final int x0, final int y0) { return null; } + + private static boolean SetJAWTRootSurfaceLayer(final Buffer jawtDrawingSurfaceInfoBuffer, final long caLayer) { + return OSXUtil.RunOnMainThread(true, new Function() { + public Boolean eval(Object... args) { + return Boolean.valueOf( SetJAWTRootSurfaceLayer0(jawtDrawingSurfaceInfoBuffer, caLayer) ); + } } ).booleanValue(); + } + + private static boolean UnsetJAWTRootSurfaceLayer(final Buffer jawtDrawingSurfaceInfoBuffer, final long caLayer) { + return OSXUtil.RunOnMainThread(true, new Function() { + public Boolean eval(Object... args) { + return Boolean.valueOf( UnsetJAWTRootSurfaceLayer0(jawtDrawingSurfaceInfoBuffer, caLayer) ); + } } ).booleanValue(); + } private static native boolean SetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); - // private static native boolean UnsetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); + private static native boolean UnsetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); // Variables for lockSurface/unlockSurface private JAWT_DrawingSurface ds; diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index f06f97064..2e133c22f 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -32,6 +32,8 @@ import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.Point; +import com.jogamp.common.util.Function; +import com.jogamp.common.util.FunctionTask; import com.jogamp.common.util.RunnableTask; import jogamp.nativewindow.Debug; @@ -137,23 +139,33 @@ public class OSXUtil implements ToolkitProperties { public static long CreateCALayer(int x, int y, int width, int height) { return CreateCALayer0(x, y, width, height); } - public static void AddCASublayer(long rootCALayer, long subCALayer) { + public static void AddCASublayer(final long rootCALayer, final long subCALayer) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } - AddCASublayer0(rootCALayer, subCALayer); + RunOnMainThread(true, new Runnable() { + public void run() { + AddCASublayer0(rootCALayer, subCALayer); + } + }); } - public static void RemoveCASublayer(long rootCALayer, long subCALayer) { + public static void RemoveCASublayer(final long rootCALayer, final long subCALayer) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } - RemoveCASublayer0(rootCALayer, subCALayer); + RunOnMainThread(true, new Runnable() { + public void run() { + RemoveCASublayer0(rootCALayer, subCALayer); + } } ); } - public static void DestroyCALayer(long caLayer) { + public static void DestroyCALayer(final long caLayer) { if(0==caLayer) { throw new IllegalArgumentException("caLayer 0x"+Long.toHexString(caLayer)); } - DestroyCALayer0(caLayer); + RunOnMainThread(true, new Runnable() { + public void run() { + DestroyCALayer0(caLayer); + } } ); } /** @@ -169,14 +181,14 @@ public class OSXUtil implements ToolkitProperties { if( IsMainThread0() ) { runnable.run(); // don't leave the JVM } else { - if( waitUntilDone ) { - // Utilize Java side lock/wait and simply pass the Runnable async to OSX main thread, - // otherwise we may freeze the OSX main thread. - Throwable throwable = null; - final Object sync = new Object(); - final RunnableTask rt = new RunnableTask( runnable, sync, true ); - synchronized(sync) { - RunOnMainThread0(rt); + // Utilize Java side lock/wait and simply pass the Runnable async to OSX main thread, + // otherwise we may freeze the OSX main thread. + Throwable throwable = null; + final Object sync = new Object(); + final RunnableTask rt = new RunnableTask( runnable, waitUntilDone ? sync : null, true ); + synchronized(sync) { + RunOnMainThread0(rt); + if( waitUntilDone ) { try { sync.wait(); } catch (InterruptedException ie) { @@ -188,10 +200,47 @@ public class OSXUtil implements ToolkitProperties { if(null!=throwable) { throw new RuntimeException(throwable); } - } - } else { - RunOnMainThread0(runnable); + } + } + } + } + + /** + * Run on OSX UI main thread. + *

        + * 'waitUntilDone' is implemented on Java site via lock/wait on {@link FunctionTask} to not freeze OSX main thread. + *

        + * + * @param waitUntilDone + * @param func + */ + public static R RunOnMainThread(boolean waitUntilDone, Function func, A... args) { + if( IsMainThread0() ) { + return func.eval(args); // don't leave the JVM + } else { + // Utilize Java side lock/wait and simply pass the Runnable async to OSX main thread, + // otherwise we may freeze the OSX main thread. + Throwable throwable = null; + final Object sync = new Object(); + final FunctionTask rt = new FunctionTask( func, waitUntilDone ? sync : null, true ); + synchronized(sync) { + rt.setArgs(args); + RunOnMainThread0(rt); + if( waitUntilDone ) { + try { + sync.wait(); + } catch (InterruptedException ie) { + throwable = ie; + } + if(null==throwable) { + throwable = rt.getThrowable(); + } + if(null!=throwable) { + throw new RuntimeException(throwable); + } + } } + return rt.getResult(); } } diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 72bb2338c..3fa320042 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -49,6 +49,16 @@ #define DBG_PRINT(...) #endif +// #define VERBOSE2 1 +// +#ifdef VERBOSE2 + #define DBG_PRINT2(...) fprintf(stderr, __VA_ARGS__); fflush(stderr) +#else + #define DBG_PRINT2(...) +#endif + +// #define DBG_LIFECYCLE 1 + static const char * const ClazzNameRunnable = "java/lang/Runnable"; static jmethodID runnableRunID = NULL; @@ -324,7 +334,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; CALayer* layer = [[CALayer alloc] init]; - DBG_PRINT("CALayer::CreateCALayer.0: %p %d/%d %dx%d (refcnt %d)\n", layer, (int)x, (int)y, (int)width, (int)height, (int)[layer retainCount]); + DBG_PRINT("CALayer::CreateCALayer.0: root %p %d/%d %dx%d (refcnt %d)\n", layer, (int)x, (int)y, (int)width, (int)height, (int)[layer retainCount]); // avoid zero size if(0 == width) { width = 32; } if(0 == height) { height = 32; } @@ -341,8 +351,8 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 [layer removeAllAnimations]; [layer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; [layer setNeedsDisplayOnBoundsChange: YES]; - DBG_PRINT("CALayer::CreateCALayer.1: %p %lf/%lf %lfx%lf\n", layer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); - DBG_PRINT("CALayer::CreateCALayer.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]); + DBG_PRINT("CALayer::CreateCALayer.1: root %p %lf/%lf %lfx%lf\n", layer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + DBG_PRINT("CALayer::CreateCALayer.X: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); [pool release]; @@ -367,30 +377,28 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 if(lRectRoot.origin.x!=0 || lRectRoot.origin.y!=0) { lRectRoot.origin.x = 0; lRectRoot.origin.y = 0; - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - [rootLayer setFrame: lRectRoot]; - }]; + [rootLayer setFrame: lRectRoot]; DBG_PRINT("CALayer::AddCASublayer0.1: Origin %p frame*: %lf/%lf %lfx%lf\n", rootLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height); } - DBG_PRINT("CALayer::AddCASublayer0.2: %p . %p %lf/%lf %lfx%lf (refcnt %d)\n", - rootLayer, subLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height, (int)[subLayer retainCount]); - - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - // simple 1:1 layout ! - [subLayer setFrame:lRectRoot]; - [rootLayer addSublayer:subLayer]; - - // no animations for add/remove/swap sublayers etc - // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] - [rootLayer removeAllAnimations]; - [rootLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; - [rootLayer setNeedsDisplayOnBoundsChange: YES]; - [subLayer removeAllAnimations]; - [subLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; - [subLayer setNeedsDisplayOnBoundsChange: YES]; - }]; - DBG_PRINT("CALayer::AddCASublayer0.X: %p . %p (refcnt %d)\n", rootLayer, subLayer, (int)[subLayer retainCount]); + DBG_PRINT("CALayer::AddCASublayer0.2: root %p (refcnt %d) .sub %p %lf/%lf %lfx%lf (refcnt %d)\n", + rootLayer, (int)[rootLayer retainCount], + subLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height, (int)[subLayer retainCount]); + + // simple 1:1 layout ! + [subLayer setFrame:lRectRoot]; + [rootLayer addSublayer:subLayer]; + + // no animations for add/remove/swap sublayers etc + // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] + [rootLayer removeAllAnimations]; + [rootLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; + [rootLayer setNeedsDisplayOnBoundsChange: YES]; + [subLayer removeAllAnimations]; + [subLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; + [subLayer setNeedsDisplayOnBoundsChange: YES]; + DBG_PRINT("CALayer::AddCASublayer0.X: root %p (refcnt %d) .sub %p (refcnt %d)\n", + rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); JNF_COCOA_EXIT(env); } @@ -408,11 +416,12 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RemoveCASublayer0 (void)rootLayer; // no warnings - DBG_PRINT("CALayer::RemoveCASublayer0.0: %p . %p (refcnt %d)\n", rootLayer, subLayer, (int)[subLayer retainCount]); - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - [subLayer removeFromSuperlayer]; - }]; - DBG_PRINT("CALayer::RemoveCASublayer0.X: %p . %p\n", rootLayer, subLayer); + DBG_PRINT("CALayer::RemoveCASublayer0.0: root %p (refcnt %d) .sub %p (refcnt %d)\n", + rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); + [subLayer removeFromSuperlayer]; + [subLayer release]; + DBG_PRINT("CALayer::RemoveCASublayer0.X: root %p (refcnt %d) .sub %p (refcnt %d)\n", + rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); JNF_COCOA_EXIT(env); } @@ -427,11 +436,10 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyCALayer0 JNF_COCOA_ENTER(env); CALayer* layer = (CALayer*) ((intptr_t) caLayer); - DBG_PRINT("CALayer::DestroyCALayer0.0: %p (refcnt %d)\n", layer, (int)[layer retainCount]); - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - [layer release]; // performs release! - }]; - DBG_PRINT("CALayer::DestroyCALayer0.X: %p\n", layer); + DBG_PRINT("CALayer::DestroyCALayer0.0: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); + [layer release]; // Var.A + // [layer dealloc]; // Var.B -> SIGSEGV + DBG_PRINT("CALayer::DestroyCALayer0.X: root %p\n", layer); JNF_COCOA_EXIT(env); } @@ -450,12 +458,10 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow return JNI_FALSE; } CALayer* layer = (CALayer*) (intptr_t) caLayer; - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - id surfaceLayers = (id )dsi->platformInfo; - DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.0: %p -> %p (refcnt %d)\n", surfaceLayers.layer, layer, (int)[layer retainCount]); - surfaceLayers.layer = layer; // already incr. retain count - DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]); - }]; + id surfaceLayers = (id )dsi->platformInfo; + DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.0: pre %p -> root %p (refcnt %d)\n", surfaceLayers.layer, layer, (int)[layer retainCount]); + surfaceLayers.layer = layer; // already incr. retain count + DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.X: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); JNF_COCOA_EXIT(env); return JNI_TRUE; } @@ -464,6 +470,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow * Method: UnsetJAWTRootSurfaceLayer0 * Signature: (JJ)Z + */ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_UnsetJAWTRootSurfaceLayer0 (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) { @@ -474,23 +481,18 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow return JNI_FALSE; } CALayer* layer = (CALayer*) (intptr_t) caLayer; - { - id surfaceLayers = (id )dsi->platformInfo; - if(layer != surfaceLayers.layer) { - NativewindowCommon_throwNewRuntimeException(env, "Attached layer %p doesn't match given layer %p\n", surfaceLayers.layer, layer); - return JNI_FALSE; - } + id surfaceLayers = (id )dsi->platformInfo; + if(layer != surfaceLayers.layer) { + NativewindowCommon_throwNewRuntimeException(env, "Attached layer %p doesn't match given layer %p\n", surfaceLayers.layer, layer); + return JNI_FALSE; } - // [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ - id surfaceLayers = (id )dsi->platformInfo; - DBG_PRINT("CALayer::detachJAWTSurfaceLayer: (%p) %p -> NULL\n", layer, surfaceLayers.layer); - surfaceLayers.layer = NULL; - [layer release]; - // }]; + DBG_PRINT("CALayer::UnsetJAWTRootSurfaceLayer.0: root %p (refcnt %d) -> nil\n", layer, (int)[layer retainCount]); + surfaceLayers.layer = NULL; + [layer release]; // Var.A + DBG_PRINT("CALayer::UnsetJAWTRootSurfaceLayer.X: root %p (refcnt %d) -> nil\n", layer, (int)[layer retainCount]); JNF_COCOA_EXIT(env); return JNI_TRUE; } - */ @interface MainRunnable : NSObject @@ -503,6 +505,13 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow - (id) initWithRunnable: (jobject)runnable jvmHandle: (JavaVM*)jvm jvmVersion: (int)jvmVers; - (void) jRun; +#ifdef DBG_LIFECYCLE +- (id)retain; +- (oneway void)release; +- (void)dealloc; +#endif + + @end @implementation MainRunnable @@ -519,20 +528,47 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow { int shallBeDetached = 0; JNIEnv* env = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); - DBG_PRINT("MainRunnable.0 env: %d\n", (int)(NULL!=env)); + DBG_PRINT2("MainRunnable.1 env: %d\n", (int)(NULL!=env)); if(NULL!=env) { - DBG_PRINT("MainRunnable.1.0\n"); + DBG_PRINT2("MainRunnable.1.0\n"); (*env)->CallVoidMethod(env, runnableObj, runnableRunID); - DBG_PRINT("MainRunnable.1.1\n"); + DBG_PRINT2("MainRunnable.1.1\n"); + (*env)->DeleteGlobalRef(env, runnableObj); if (shallBeDetached) { - DBG_PRINT("MainRunnable.1.2\n"); + DBG_PRINT2("MainRunnable.1.3\n"); (*jvmHandle)->DetachCurrentThread(jvmHandle); } } - DBG_PRINT("MainRunnable.X\n"); + DBG_PRINT2("MainRunnable.X\n"); +} + +#ifdef DBG_LIFECYCLE + +- (id)retain +{ + DBG_PRINT2("MainRunnable::retain.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + id o = [super retain]; + DBG_PRINT2("MainRunnable::retain.X: %p (refcnt %d)\n", o, (int)[o retainCount]); + return o; +} + +- (oneway void)release +{ + DBG_PRINT2("MainRunnable::release.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + [super release]; + // DBG_PRINT2("MainRunnable::release.X: %p (refcnt %d)\n", self, (int)[self retainCount]); } +- (void)dealloc +{ + DBG_PRINT2("MainRunnable::dealloc.0 %p (refcnt %d)\n", self, (int)[self retainCount]); + [super dealloc]; + // DBG_PRINT2("MainRunnable.dealloc.X: %p\n", self); +} + +#endif + @end @@ -546,11 +582,11 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunOnMainThread0 { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - DBG_PRINT( "RunOnMainThread0: isMainThread %d, NSApp %d, NSApp-isRunning %d\n", + DBG_PRINT2( "RunOnMainThread0: isMainThread %d, NSApp %d, NSApp-isRunning %d\n", (int)([NSThread isMainThread]), (int)(NULL!=NSApp), (int)([NSApp isRunning])); if ( NO == [NSThread isMainThread] ) { - jobject runnableGlob = (*env)->NewGlobalRef(env, runnable); + jobject runnableObj = (*env)->NewGlobalRef(env, runnable); JavaVM *jvmHandle = NULL; int jvmVersion = 0; @@ -561,18 +597,18 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunOnMainThread0 jvmVersion = (*env)->GetVersion(env); } - DBG_PRINT( "RunOnMainThread0.1.0\n"); - MainRunnable * mr = [[MainRunnable alloc] initWithRunnable: runnableGlob jvmHandle: jvmHandle jvmVersion: jvmVersion]; + DBG_PRINT2( "RunOnMainThread0.1.0\n"); + MainRunnable * mr = [[MainRunnable alloc] initWithRunnable: runnableObj jvmHandle: jvmHandle jvmVersion: jvmVersion]; [mr performSelectorOnMainThread:@selector(jRun) withObject:nil waitUntilDone:NO]; + DBG_PRINT2( "RunOnMainThread0.1.1\n"); [mr release]; - DBG_PRINT( "RunOnMainThread0.1.1\n"); + DBG_PRINT2( "RunOnMainThread0.1.2\n"); - (*env)->DeleteGlobalRef(env, runnableGlob); } else { - DBG_PRINT( "RunOnMainThread0.2\n"); + DBG_PRINT2( "RunOnMainThread0.2\n"); (*env)->CallVoidMethod(env, runnable, runnableRunID); } - DBG_PRINT( "RunOnMainThread0.X\n"); + DBG_PRINT2( "RunOnMainThread0.X\n"); [pool release]; } @@ -644,7 +680,7 @@ JNIEXPORT jint JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetScreenRefreshR if(0 == res) { res = 60; // default .. (experienced on OSX 10.6.8) } - DBG_PRINT(stderr, "GetScreenRefreshRate.X: %d\n", (int)res); + DBG_PRINT("GetScreenRefreshRate.X: %d\n", (int)res); // [pool release]; JNF_COCOA_EXIT(env); return res; diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAddRemove01SwingAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAddRemove01SwingAWT.java new file mode 100644 index 000000000..76bb6362f --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAddRemove01SwingAWT.java @@ -0,0 +1,257 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.awt; + +import java.awt.AWTException; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.InvocationTargetException; + +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLProfile; +import javax.media.opengl.awt.GLCanvas; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears; +import com.jogamp.opengl.test.junit.util.UITestCase; + +public class TestGLCanvasAddRemove01SwingAWT extends UITestCase { + static long durationPerTest = 50; + static int addRemoveCount = 15; + static boolean shallUseOffscreenFBOLayer = false; + static boolean shallUseOffscreenPBufferLayer = false; + static GLProfile glp; + static int width, height; + static boolean waitForKey = false; + + @BeforeClass + public static void initClass() { + if(GLProfile.isAvailable(GLProfile.GL2)) { + glp = GLProfile.get(GLProfile.GL2); + Assert.assertNotNull(glp); + width = 640; + height = 480; + } else { + setTestSupported(false); + } + } + + @AfterClass + public static void releaseClass() { + } + + protected JPanel createParkingSlot(final JFrame[] top, final int width, final int height) + throws InterruptedException, InvocationTargetException + { + final JPanel[] jPanel = new JPanel[] { null }; + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + jPanel[0] = new JPanel(); + jPanel[0].setLayout(new BorderLayout()); + + final JFrame jFrame1 = new JFrame("Parking Slot"); + // jFrame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + jFrame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // equivalent to Frame, use windowClosing event! + jFrame1.getContentPane().add(jPanel[0]); + jFrame1.setSize(width, height); + + top[0] = jFrame1; + } } ); + return jPanel[0]; + } + + protected JPanel create(final JFrame[] top, final int width, final int height, final int num) + throws InterruptedException, InvocationTargetException + { + final JPanel[] jPanel = new JPanel[] { null }; + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + jPanel[0] = new JPanel(); + jPanel[0].setLayout(new BorderLayout()); + // jPanel[0].add(glcContainer[0], BorderLayout.CENTER); + + // final Container container2 = new Container(); + // container2.setLayout(new BorderLayout()); + // container2.add(jPanel1, BorderLayout.CENTER); + + final JPanel jPanel2 = new JPanel(); + jPanel2.setLayout(new BorderLayout()); + // jPanel2.add(container2, BorderLayout.CENTER); + jPanel2.add(jPanel[0], BorderLayout.CENTER); + + final JFrame jFrame1 = new JFrame("JFrame #"+num); + // jFrame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + jFrame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // equivalent to Frame, use windowClosing event! + jFrame1.getContentPane().add(jPanel2); + jFrame1.setSize(width, height); + + top[0] = jFrame1; + } } ); + return jPanel[0]; + } + + protected void add(final Container cont, final Component comp) + throws InterruptedException, InvocationTargetException + { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + cont.add(comp, BorderLayout.CENTER); + } } ); + } + + protected void remove(final Container cont, final Component comp) + throws InterruptedException, InvocationTargetException + { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + cont.remove(comp); + } } ); + } + protected void dispose(final GLCanvas glc) + throws InterruptedException, InvocationTargetException + { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + glc.destroy(); + } } ); + } + + protected void setVisible(final JFrame jFrame, final boolean visible) throws InterruptedException, InvocationTargetException { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + if( visible ) { + jFrame.validate(); + jFrame.pack(); + } + jFrame.setVisible(visible); + } } ) ; + } + + protected void dispose(final JFrame jFrame) throws InterruptedException, InvocationTargetException { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + jFrame.dispose(); + } } ) ; + } + + protected void runTestGL(GLCapabilities caps, int addRemoveOpCount) + throws AWTException, InterruptedException, InvocationTargetException + { + + // final JFrame[] parkingFrame = new JFrame[] { null }; + // final JPanel parkingPanel = createParkingSlot(parkingFrame, 2, 2); + + for(int i=0; i Date: Fri, 15 Feb 2013 17:15:49 +0100 Subject: Fix Bug 691 (part-2): Extra '[subLayer release]' is wrong, since 'CGL.releaseNSOpenGLLayer' triggers release - but very late w/ AWT usage. OSXUtil_RemoveCASublayer0's added '[subLayer release]' in commit f6e6fab2a7ddfb5c9b614cb072c27ff697629161 is wrong, since 'CGL.releaseNSOpenGLLayer' actually does trigger it's release. This was not seen w/ AWT tests, since it happens very later. A NewtCanvasAWT test disclosed this error -> removed that extra release call. The culprit for the late release w/ AWT usage was CGL.createNSOpenGLLayer's call in the current thread. Moving it to the Main-Thread fixed the problem. All CALayer lifecycle calls are issued on the Main-Thread now. NSOpenGLLayer's CVDisplayLink OpenGL fitting via 'CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext' is now performed at it's context creation in 'NSOpenGLLayer::openGLContextForPixelFormat'. The 'extra' release of the NSOpenGLLayer's NSOpenGLContext as introduced in commit f6e6fab2a7ddfb5c9b614cb072c27ff697629161 is still valid. --- make/config/jogl/cgl-macosx-CustomJavaCode.java | 22 ++ make/config/jogl/cgl-macosx.cfg | 9 + make/scripts/tests.sh | 11 +- .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 5 +- .../macosx/MacOSXWindowSystemInterface-calayer.m | 25 ++- .../jogamp/nativewindow/macosx/OSXUtil.java | 16 +- src/nativewindow/native/macosx/OSXmisc.m | 119 +++++++++-- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 5 +- .../acore/TestOffscreenLayer01GLCanvasAWT.java | 15 +- .../acore/TestOffscreenLayer02NewtCanvasAWT.java | 16 +- .../jogl/awt/TestGLCanvasAddRemove01SwingAWT.java | 53 ++--- .../awt/TestGLCanvasAddRemove02NewtCanvasAWT.java | 238 +++++++++++++++++++++ .../jogamp/opengl/test/junit/util/UITestCase.java | 11 + 13 files changed, 438 insertions(+), 107 deletions(-) create mode 100644 make/config/jogl/cgl-macosx-CustomJavaCode.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestGLCanvasAddRemove02NewtCanvasAWT.java (limited to 'src/nativewindow') diff --git a/make/config/jogl/cgl-macosx-CustomJavaCode.java b/make/config/jogl/cgl-macosx-CustomJavaCode.java new file mode 100644 index 000000000..b9a37d0c6 --- /dev/null +++ b/make/config/jogl/cgl-macosx-CustomJavaCode.java @@ -0,0 +1,22 @@ + +/** + * Creates the NSOpenGLLayer for FBO/PBuffer w/ optional GL3 shader program on Main-Thread + */ +public static long createNSOpenGLLayer(final long ctx, final int gl3ShaderProgramName, final long fmt, final long p, + final int texID, final boolean opaque, final int texWidth, final int texHeight) { + return OSXUtil.RunOnMainThread(true, new Function() { + public Long eval(Object... args) { + return Long.valueOf( createNSOpenGLLayerImpl(ctx, gl3ShaderProgramName, fmt, p, texID, opaque, texWidth, texHeight) ); + } } ).longValue(); +} + +/** + * Releases the NSOpenGLLayer on Main-Thread + */ +public static void releaseNSOpenGLLayer(final long nsOpenGLLayer) { + OSXUtil.RunOnMainThread(true, new Runnable() { + public void run() { + releaseNSOpenGLLayerImpl(nsOpenGLLayer); + } } ); +} + diff --git a/make/config/jogl/cgl-macosx.cfg b/make/config/jogl/cgl-macosx.cfg index 203802d29..98123f605 100644 --- a/make/config/jogl/cgl-macosx.cfg +++ b/make/config/jogl/cgl-macosx.cfg @@ -34,6 +34,13 @@ Opaque long NSOpenGLLayer * CustomCCode #include CustomCCode #include "macosx-window-system.h" +AccessControl createNSOpenGLLayerImpl PRIVATE +AccessControl releaseNSOpenGLLayerImpl PRIVATE +RenameJavaMethod createNSOpenGLLayer createNSOpenGLLayerImpl +RenameJavaMethod releaseNSOpenGLLayer releaseNSOpenGLLayerImpl + +IncludeAs CustomJavaCode CGL cgl-macosx-CustomJavaCode.java + # Implement the first argument to getProcAddress as String instead # of byte[] ArgumentIsString getProcAddress 0 @@ -53,3 +60,5 @@ DropUniqVendorExtensions SGIX DropUniqVendorExtensions SUN DropUniqVendorExtensions WIN +Import com.jogamp.common.util.Function +Import jogamp.nativewindow.macosx.OSXUtil diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 198a8f2e6..5f5248156 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -34,7 +34,7 @@ uname -a | grep -i Darwin && MOSX=1 if [ $MOSX -eq 1 ] ; then echo setup OSX environment vars #export NSZombieEnabled=YES - export NSTraceEvents=YES + #export NSTraceEvents=YES #export OBJC_PRINT_EXCEPTIONS=YES echo NSZombieEnabled $NSZombieEnabled 2>&1 | tee -a java-run.log echo NSTraceEvents $NSTraceEvents 2>&1 | tee -a java-run.log @@ -89,7 +89,7 @@ function jrun() { #D_ARGS="-Djogl.debug.FBObject" #D_ARGS="-Djogl.debug.GLSLCode" #D_ARGS="-Djogl.debug.GLSLCode -Djogl.debug.DebugGL -Djogl.debug.TraceGL" - #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch -Dnativewindow.debug.JAWT" + #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.JAWT -Dnewt.debug.Window" #D_ARGS="-Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogl.debug.FixedFuncPipeline -Djogl.debug.GLSLCode" #D_ARGS="-Djogl.debug.FixedFuncPipeline -Djogl.debug.GLSLState" @@ -311,6 +311,8 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer01GLCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer02NewtCanvasAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAddRemove01SwingAWT $* +testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAddRemove02NewtCanvasAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableFactoryNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOOffThreadSharedContextMix2DemosES2NEWT $* @@ -416,11 +418,6 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyCodesAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT $* -testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAddRemove01SwingAWT $* - #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyCodeModifiersAWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNEWTWindowAWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersAWTCanvas $* diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 0deaa2987..838a0387d 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -709,10 +709,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl // still having a valid OLS attached to surface (parent OLS could have been removed) ols.detachSurfaceLayer(); } - OSXUtil.RunOnMainThread(true, new Runnable() { - public void run() { - CGL.releaseNSOpenGLLayer(nsOpenGLLayer); - } } ); + CGL.releaseNSOpenGLLayer(nsOpenGLLayer); if( null != gl3ShaderProgram ) { gl3ShaderProgram.destroy(MacOSXCGLContext.this.gl.getGL3()); gl3ShaderProgram = null; diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index 4334fc676..8d1286169 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -75,8 +75,11 @@ extern GLboolean glIsVertexArray (GLuint array); - (void)setView:(NSView *)view { DBG_PRINT("MyNSOpenGLContext.setView: this.0 %p, view %p\n", self, view); + // NSLog(@"MyNSOpenGLContext::setView: %@",[NSThread callStackSymbols]); if(NULL != view) { [super setView:view]; + } else { + [self clearDrawable]; } DBG_PRINT("MyNSOpenGLContext.setView.X\n"); } @@ -301,13 +304,6 @@ static const GLfloat gl_verts[] = { displayLink = NULL; } } - if(NULL != displayLink) { - cvres = CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, [parentCtx CGLContextObj], [parentPixelFmt CGLPixelFormatObj]); - if(kCVReturnSuccess != cvres) { - DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext failed: %d\n", self, cvres); - displayLink = NULL; - } - } if(NULL != displayLink) { cvres = CVDisplayLinkSetOutputCallback(displayLink, renderMyNSOpenGLLayer, self); if(kCVReturnSuccess != cvres) { @@ -453,10 +449,20 @@ static const GLfloat gl_verts[] = { - (NSOpenGLContext *)openGLContextForPixelFormat:(NSOpenGLPixelFormat *)pixelFormat { - DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.0: %p (refcnt %d) - pfmt %p, parent %p\n", - self, (int)[self retainCount], pixelFormat, parentCtx); + DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.0: %p (refcnt %d) - pfmt %p, parent %p, DisplayLink %p\n", + self, (int)[self retainCount], pixelFormat, parentCtx, displayLink); // NSLog(@"MyNSOpenGLLayer::openGLContextForPixelFormat: %@",[NSThread callStackSymbols]); myCtx = [[MyNSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:parentCtx]; +#ifndef HAS_CADisplayLink + if(NULL != displayLink) { + CVReturn cvres; + DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.1: setup DisplayLink %p\n", displayLink); + cvres = CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, [myCtx CGLContextObj], [pixelFormat CGLPixelFormatObj]); + if(kCVReturnSuccess != cvres) { + DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext failed: %d\n", self, cvres); + } + } +#endif DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.X: new-ctx %p\n", myCtx); return myCtx; } @@ -487,7 +493,6 @@ static const GLfloat gl_verts[] = { // [[self openGLContext] release]; if( NULL != myCtx ) { [myCtx release]; - // [myCtx dealloc]; myCtx = NULL; } parentCtx = NULL; diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 2e133c22f..b765a68c3 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -136,8 +136,11 @@ public class OSXUtil implements ToolkitProperties { return GetNSWindow0(nsView); } - public static long CreateCALayer(int x, int y, int width, int height) { - return CreateCALayer0(x, y, width, height); + public static long CreateCALayer(final int x, final int y, final int width, final int height) { + return OSXUtil.RunOnMainThread(true, new Function() { + public Long eval(Object... args) { + return Long.valueOf( CreateCALayer0(x, y, width, height) ); + } } ).longValue(); } public static void AddCASublayer(final long rootCALayer, final long subCALayer) { if(0==rootCALayer || 0==subCALayer) { @@ -145,7 +148,7 @@ public class OSXUtil implements ToolkitProperties { } RunOnMainThread(true, new Runnable() { public void run() { - AddCASublayer0(rootCALayer, subCALayer); + AddCASublayer0(rootCALayer, subCALayer); } }); } @@ -205,6 +208,13 @@ public class OSXUtil implements ToolkitProperties { } } + private static Runnable _nop = new Runnable() { public void run() {}; }; + + /** Issues a {@link #RunOnMainThread(boolean, Runnable)} w/ an NOP runnable, while waiting until done. */ + public static void WaitUntilFinish() { + RunOnMainThread(true, _nop); + } + /** * Run on OSX UI main thread. *

        diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 3fa320042..83f3c821f 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -32,6 +32,7 @@ #include #include #include +#import #include "NativewindowCommon.h" #include "jogamp_nativewindow_macosx_OSXUtil.h" @@ -323,6 +324,64 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 return res; } +/** + * Track lifecycle via DBG_PRINT messages, if VERBOSE is enabled! + */ +@interface MyCALayer: CALayer +{ +} +- (id)init; +#ifdef DBG_LIFECYCLE +- (id)retain; +- (oneway void)release; +- (void)dealloc; +#endif + +@end + +@implementation MyCALayer + +- (id)init +{ + DBG_PRINT("MyCALayer.0\n"); + MyCALayer * o = [super init]; + DBG_PRINT("MyNSOpenGLContext.init.X: new %p\n", o); + DBG_PRINT("MyCALayer.0\n"); + return o; +} + +#ifdef DBG_LIFECYCLE + +- (id)retain +{ + DBG_PRINT("MyCALayer::retain.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + // NSLog(@"MyCALayer::retain: %@",[NSThread callStackSymbols]); + id o = [super retain]; + DBG_PRINT("MyCALayer::retain.X: %p (refcnt %d)\n", o, (int)[o retainCount]); + return o; +} + +- (oneway void)release +{ + DBG_PRINT("MyCALayer::release.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + // NSLog(@"MyCALayer::release: %@",[NSThread callStackSymbols]); + [super release]; + // DBG_PRINT("MyCALayer::release.X: %p (refcnt %d)\n", self, (int)[self retainCount]); +} + +- (void)dealloc +{ + DBG_PRINT("MyCALayer::dealloc.0 %p (refcnt %d)\n", self, (int)[self retainCount]); + // NSLog(@"MyCALayer::dealloc: %@",[NSThread callStackSymbols]); + [super dealloc]; + // DBG_PRINT("MyCALayer.dealloc.X: %p\n", self); +} + +#endif + + +@end + /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: CreateCALayer0 @@ -333,7 +392,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - CALayer* layer = [[CALayer alloc] init]; + MyCALayer* layer = [[MyCALayer alloc] init]; DBG_PRINT("CALayer::CreateCALayer.0: root %p %d/%d %dx%d (refcnt %d)\n", layer, (int)x, (int)y, (int)width, (int)height, (int)[layer retainCount]); // avoid zero size if(0 == width) { width = 32; } @@ -349,12 +408,12 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 // no animations for add/remove/swap sublayers etc // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] [layer removeAllAnimations]; + // [layer addAnimation:nil forKey:kCATransition]; [layer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; [layer setNeedsDisplayOnBoundsChange: YES]; DBG_PRINT("CALayer::CreateCALayer.1: root %p %lf/%lf %lfx%lf\n", layer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); - DBG_PRINT("CALayer::CreateCALayer.X: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); - [pool release]; + DBG_PRINT("CALayer::CreateCALayer.X: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); return (jlong) ((intptr_t) layer); } @@ -367,8 +426,8 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer) { - JNF_COCOA_ENTER(env); - CALayer* rootLayer = (CALayer*) ((intptr_t) rootCALayer); + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); CGRect lRectRoot = [rootLayer frame]; @@ -385,6 +444,9 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 rootLayer, (int)[rootLayer retainCount], subLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height, (int)[subLayer retainCount]); + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + // simple 1:1 layout ! [subLayer setFrame:lRectRoot]; [rootLayer addSublayer:subLayer]; @@ -392,14 +454,19 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 // no animations for add/remove/swap sublayers etc // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] [rootLayer removeAllAnimations]; + // [rootLayer addAnimation:nil forKey:kCATransition]; [rootLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; [rootLayer setNeedsDisplayOnBoundsChange: YES]; [subLayer removeAllAnimations]; + // [sublayer addAnimation:nil forKey:kCATransition]; [subLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; [subLayer setNeedsDisplayOnBoundsChange: YES]; + + [CATransaction commit]; + + [pool release]; DBG_PRINT("CALayer::AddCASublayer0.X: root %p (refcnt %d) .sub %p (refcnt %d)\n", rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); - JNF_COCOA_EXIT(env); } /* @@ -410,19 +477,26 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RemoveCASublayer0 (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer) { - JNF_COCOA_ENTER(env); - CALayer* rootLayer = (CALayer*) ((intptr_t) rootCALayer); + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); (void)rootLayer; // no warnings DBG_PRINT("CALayer::RemoveCASublayer0.0: root %p (refcnt %d) .sub %p (refcnt %d)\n", rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + [subLayer removeFromSuperlayer]; - [subLayer release]; + // [subLayer release] is called explicitly, e.g. via CGL.releaseNSOpenGLLayer(..) (MyNSOpenGLLayer::releaseLayer) + + [CATransaction commit]; + + [pool release]; DBG_PRINT("CALayer::RemoveCASublayer0.X: root %p (refcnt %d) .sub %p (refcnt %d)\n", rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); - JNF_COCOA_EXIT(env); } /* @@ -433,14 +507,13 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RemoveCASublayer0 JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyCALayer0 (JNIEnv *env, jclass unused, jlong caLayer) { - JNF_COCOA_ENTER(env); - CALayer* layer = (CALayer*) ((intptr_t) caLayer); + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyCALayer* layer = (MyCALayer*) ((intptr_t) caLayer); DBG_PRINT("CALayer::DestroyCALayer0.0: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); - [layer release]; // Var.A - // [layer dealloc]; // Var.B -> SIGSEGV + [layer release]; // Trigger release of root CALayer + [pool release]; DBG_PRINT("CALayer::DestroyCALayer0.X: root %p\n", layer); - JNF_COCOA_EXIT(env); } /* @@ -451,18 +524,18 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyCALayer0 JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_SetJAWTRootSurfaceLayer0 (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) { - JNF_COCOA_ENTER(env); + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); if (NULL == dsi) { NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); return JNI_FALSE; } - CALayer* layer = (CALayer*) (intptr_t) caLayer; + MyCALayer* layer = (MyCALayer*) (intptr_t) caLayer; id surfaceLayers = (id )dsi->platformInfo; DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.0: pre %p -> root %p (refcnt %d)\n", surfaceLayers.layer, layer, (int)[layer retainCount]); - surfaceLayers.layer = layer; // already incr. retain count + surfaceLayers.layer = [layer retain]; // Pairs w/ Unset + [pool release]; DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.X: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); - JNF_COCOA_EXIT(env); return JNI_TRUE; } @@ -474,23 +547,23 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_UnsetJAWTRootSurfaceLayer0 (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) { - JNF_COCOA_ENTER(env); + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); if (NULL == dsi) { NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); return JNI_FALSE; } - CALayer* layer = (CALayer*) (intptr_t) caLayer; + MyCALayer* layer = (MyCALayer*) (intptr_t) caLayer; id surfaceLayers = (id )dsi->platformInfo; if(layer != surfaceLayers.layer) { NativewindowCommon_throwNewRuntimeException(env, "Attached layer %p doesn't match given layer %p\n", surfaceLayers.layer, layer); return JNI_FALSE; } DBG_PRINT("CALayer::UnsetJAWTRootSurfaceLayer.0: root %p (refcnt %d) -> nil\n", layer, (int)[layer retainCount]); + [layer release]; // Pairs w/ Set surfaceLayers.layer = NULL; - [layer release]; // Var.A + [pool release]; DBG_PRINT("CALayer::UnsetJAWTRootSurfaceLayer.X: root %p (refcnt %d) -> nil\n", layer, (int)[layer retainCount]); - JNF_COCOA_EXIT(env); return JNI_TRUE; } diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 89a749c51..6fc5a46ce 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -397,11 +397,12 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto if(DEBUG) { System.err.println("NewtCanvasAWT.removeNotify: "+newtChild+", from "+cont); } + // Detach OLS early.. final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(newtChild, true); if(null != ols && ols.isSurfaceLayerAttached()) { ols.detachSurfaceLayer(); - } - reparentWindow(false, cont); + } + reparentWindow(false, cont); // will destroy context (offscreen -> onscreen) and implicit detachSurfaceLayer (if still attached) if(null != jawtWindow) { NewtFactoryAWT.destroyNativeWindow(jawtWindow); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java index 90407166f..8cc094276 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestOffscreenLayer01GLCanvasAWT.java @@ -33,9 +33,7 @@ import java.awt.Button; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import javax.media.opengl.GLAnimatorControl; @@ -70,6 +68,7 @@ public class TestOffscreenLayer01GLCanvasAWT extends UITestCase { static Dimension frameSize1; static Dimension preferredGLSize; static long durationPerTest = 1000; + static boolean waitForKey = false; @BeforeClass public static void initClass() { @@ -189,7 +188,10 @@ public class TestOffscreenLayer01GLCanvasAWT extends UITestCase { Thread.sleep(durationPerTest/2); - end(animator1, frame1, null); + end(animator1, frame1, null); + if( waitForKey ) { + UITestCase.waitForKey("Continue"); + } } public static void setDemoFields(GLEventListener demo, GLWindow glWindow, boolean debug) { @@ -214,7 +216,6 @@ public class TestOffscreenLayer01GLCanvasAWT extends UITestCase { } public static void main(String args[]) throws IOException { - boolean waitForKey = false; for(int i=0; i Press enter to continue"); + try { + System.err.println(stdin.readLine()); + } catch (IOException e) { } + } + static final String unsupportedTestMsg = "Test not supported on this platform."; public String getSnapshotFilename(int sn, String postSNDetail, GLCapabilitiesImmutable caps, int width, int height, boolean sinkHasAlpha, String fileSuffix, String destPath) { -- cgit v1.2.3 From a94ff9252df66c303f48489c3e8926104941465c Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 16 Feb 2013 03:55:22 +0100 Subject: Fix Bug 691 (part-3): NSOpenGLLayer::openGLContextForPixelFormat(..) on main-thread deadlock'ed due to locked shared context NSOpenGLLayer::openGLContextForPixelFormat(..) is performed on main-thread at 1st NSOpenGLLayer display method. This happened irregulary, i.e. sometimes (T0) right after NSOpenGLLayer creation and attachSurfaceLayer()/AddCASublayer(..), sometimes later (T1). NSOpenGLLayer::openGLContextForPixelFormat(..) uses the passed shared user context. The shared user context is locked at NSOpenGLLayer's creation (T0) and if performed at this early time the call deadlocks due to pthread_mutex wait for the shared user context. This fix performs NSOpenGLLayer creation and layer attachment while the shared user context is kept unlocked and enforces NSOpenGLLayer display and hence NSOpenGLLayer::openGLContextForPixelFormat(..). Added CGL.setNSOpenGLLayerEnabled(..) to enable/disable NSOpenGLLayer - currently not used. - Passed AddRemove tests for GLCanvas/Swing and GLWindow/NewtCanvasAWT w/ 100 loops on Java6 and Java7 on OSX. - Passed Instruments Leaks test w/ 10 loops on Java6 and Java7 --- make/config/jogl/cgl-macosx-CustomJavaCode.java | 22 +++++++++++++++ make/config/jogl/cgl-macosx.cfg | 2 ++ make/scripts/tests.sh | 4 +-- make/stub_includes/opengl/macosx-window-system.h | 1 + .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 31 +++++++++++++++++----- .../macosx/MacOSXWindowSystemInterface-calayer.m | 28 ++++++++++++++----- .../media/nativewindow/OffscreenLayerSurface.java | 8 ++++++ .../jogamp/nativewindow/macosx/OSXUtil.java | 28 +++++++++++++++++++ src/nativewindow/native/macosx/OSXmisc.m | 16 +++++++---- .../acore/TestAddRemove01GLCanvasSwingAWT.java | 2 +- .../TestAddRemove02GLWindowNewtCanvasAWT.java | 2 +- 11 files changed, 123 insertions(+), 21 deletions(-) (limited to 'src/nativewindow') diff --git a/make/config/jogl/cgl-macosx-CustomJavaCode.java b/make/config/jogl/cgl-macosx-CustomJavaCode.java index b9a37d0c6..d32e0ae8f 100644 --- a/make/config/jogl/cgl-macosx-CustomJavaCode.java +++ b/make/config/jogl/cgl-macosx-CustomJavaCode.java @@ -1,6 +1,14 @@ /** * Creates the NSOpenGLLayer for FBO/PBuffer w/ optional GL3 shader program on Main-Thread + *

        + * It is mandatory that the shared context handle ctx + * is not locked while calling this method. + *

        + *

        + * The NSOpenGLLayer starts in enabled mode, + * you may enable/disable it via {@link #setNSOpenGLLayerEnabled(long, boolean)}. + *

        */ public static long createNSOpenGLLayer(final long ctx, final int gl3ShaderProgramName, final long fmt, final long p, final int texID, final boolean opaque, final int texWidth, final int texHeight) { @@ -10,6 +18,20 @@ public static long createNSOpenGLLayer(final long ctx, final int gl3ShaderProgra } } ).longValue(); } +/** + * Enable or disable NSOpenGLLayer. + * + *

        + * If disabled, the NSOpenGLLayer will not be displayed, i.e. rendered. + *

        + */ +public static void setNSOpenGLLayerEnabled(final long nsOpenGLLayer, final boolean enable) { + OSXUtil.RunOnMainThread(true, new Runnable() { + public void run() { + setNSOpenGLLayerEnabledImpl(nsOpenGLLayer, enable); + } } ); +} + /** * Releases the NSOpenGLLayer on Main-Thread */ diff --git a/make/config/jogl/cgl-macosx.cfg b/make/config/jogl/cgl-macosx.cfg index 98123f605..edb5bfbbf 100644 --- a/make/config/jogl/cgl-macosx.cfg +++ b/make/config/jogl/cgl-macosx.cfg @@ -35,8 +35,10 @@ CustomCCode #include CustomCCode #include "macosx-window-system.h" AccessControl createNSOpenGLLayerImpl PRIVATE +AccessControl setNSOpenGLLayerEnabledImpl PRIVATE AccessControl releaseNSOpenGLLayerImpl PRIVATE RenameJavaMethod createNSOpenGLLayer createNSOpenGLLayerImpl +RenameJavaMethod setNSOpenGLLayerEnabled setNSOpenGLLayerEnabledImpl RenameJavaMethod releaseNSOpenGLLayer releaseNSOpenGLLayerImpl IncludeAs CustomJavaCode CGL cgl-macosx-CustomJavaCode.java diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 559c2aa6a..a20ec507c 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -301,8 +301,8 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.ect.TestExclusiveContext12FPSAnimNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer01GLCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestOffscreenLayer02NewtCanvasAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.acore.TestAddRemove01GLCanvasSwingAWT $* -testawt com.jogamp.opengl.test.junit.jogl.acore.TestAddRemove02GLWindowNewtCanvasAWT $* +testawt com.jogamp.opengl.test.junit.jogl.acore.TestAddRemove01GLCanvasSwingAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.acore.TestAddRemove02GLWindowNewtCanvasAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryOffscrnCapsNEWT $* diff --git a/make/stub_includes/opengl/macosx-window-system.h b/make/stub_includes/opengl/macosx-window-system.h index a2da66878..402a16efc 100644 --- a/make/stub_includes/opengl/macosx-window-system.h +++ b/make/stub_includes/opengl/macosx-window-system.h @@ -56,6 +56,7 @@ void setContextTextureImageToPBuffer(NSOpenGLContext* ctx, NSOpenGLPixelBuffer* Bool isNSOpenGLPixelBuffer(uint64_t object); NSOpenGLLayer* createNSOpenGLLayer(NSOpenGLContext* ctx, int gl3ShaderProgramName, NSOpenGLPixelFormat* fmt, NSOpenGLPixelBuffer* p, uint32_t texID, Bool opaque, int texWidth, int texHeight); +void setNSOpenGLLayerEnabled(NSOpenGLLayer* layer, Bool enable); void setNSOpenGLLayerSwapInterval(NSOpenGLLayer* layer, int interval); void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_micros); void setNSOpenGLLayerNeedsDisplayFBO(NSOpenGLLayer* layer, uint32_t texID); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 838a0387d..37aca0cd7 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -687,13 +687,32 @@ public abstract class MacOSXCGLContext extends GLContextImpl } else { gl3ShaderProgramName = 0; } - nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, gl3ShaderProgramName, nsOpenGLLayerPFmt, pbufferHandle, texID, chosenCaps.isBackgroundOpaque(), lastWidth, lastHeight); - nsOpenGLLayerPFmt = 0; // NSOpenGLLayer will release pfmt - if (DEBUG) { - System.err.println("NS create nsOpenGLLayer "+toHexString(nsOpenGLLayer)+" w/ pbuffer "+toHexString(pbufferHandle)+", texID "+texID+", texSize "+lastWidth+"x"+lastHeight+", "+drawable); + + /** + * Perform NSOpenGLLayer creation and attaching on main-thread, + * hence release the lock on our context - which will be used to + * create a shared context within NSOpenGLLayer. + */ + final long cglCtx = CGL.getCGLContext(ctx); + if(0 == cglCtx) { + throw new InternalError("Null CGLContext for: "+this); + } + final boolean ctxUnlocked = CGL.kCGLNoError == CGL.CGLUnlockContext(cglCtx); + try { + nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, gl3ShaderProgramName, nsOpenGLLayerPFmt, pbufferHandle, texID, chosenCaps.isBackgroundOpaque(), lastWidth, lastHeight); + nsOpenGLLayerPFmt = 0; // NSOpenGLLayer will release pfmt + if (DEBUG) { + System.err.println("NS create nsOpenGLLayer "+toHexString(nsOpenGLLayer)+" w/ pbuffer "+toHexString(pbufferHandle)+", texID "+texID+", texSize "+lastWidth+"x"+lastHeight+", "+drawable); + } + backingLayerHost.attachSurfaceLayer(nsOpenGLLayer); + setSwapInterval(1); // enabled per default in layered surface + } finally { + if( ctxUnlocked ) { + if( CGL.kCGLNoError != CGL.CGLLockContext(cglCtx) ) { + throw new InternalError("Could not re-lock CGLContext for: "+this); + } + } } - backingLayerHost.attachSurfaceLayer(nsOpenGLLayer); - setSwapInterval(1); // enabled per default in layered surface } else { lastWidth = drawable.getWidth(); lastHeight = drawable.getHeight(); diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index 8d1286169..55c4ad053 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -130,6 +130,7 @@ extern GLboolean glIsVertexArray (GLuint array); @private GLfloat gl_texCoords[8]; NSOpenGLContext* myCtx; + Bool isGLEnabled; @protected NSOpenGLContext* parentCtx; @@ -171,6 +172,7 @@ extern GLboolean glIsVertexArray (GLuint array); texWidth: (int) texWidth texHeight: (int) texHeight; +- (void) setGLEnabled: (Bool) enable; - (Bool) validateTexSizeWithNewSize; - (Bool) validateTexSize: (int) _texWidth texHeight: (int) _texHeight; - (void) setTextureID: (int) _texID; @@ -266,6 +268,7 @@ static const GLfloat gl_verts[] = { swapIntervalCounter = 0; timespec_now(&lastWaitTime); shallDraw = NO; + isGLEnabled = YES; newTexWidth = _texWidth; newTexHeight = _texHeight; [self validateTexSizeWithNewSize]; @@ -335,6 +338,12 @@ static const GLfloat gl_verts[] = { return self; } +- (void) setGLEnabled: (Bool) enable +{ + DBG_PRINT("MyNSOpenGLLayer::setGLEnabled: %p, %d -> %d\n", self, (int)isGLEnabled, (int)enable); + isGLEnabled = enable; +} + - (Bool) validateTexSizeWithNewSize { return [self validateTexSize: newTexWidth texHeight: newTexHeight]; @@ -444,6 +453,7 @@ static const GLfloat gl_verts[] = { { DBG_PRINT("MyNSOpenGLLayer::openGLPixelFormatForDisplayMask: %p (refcnt %d) - parent-pfmt %p -> new-pfmt %p\n", self, (int)[self retainCount], parentPixelFmt, parentPixelFmt); + // We simply take over ownership of parent PixelFormat .. return parentPixelFmt; } @@ -531,7 +541,6 @@ static const GLfloat gl_verts[] = { [self disableAnimation]; pthread_mutex_lock(&renderLock); [self deallocPBuffer]; - // [[self openGLContext] dealloc]; pthread_mutex_unlock(&renderLock); pthread_cond_destroy(&renderSignal); pthread_mutex_destroy(&renderLock); @@ -548,8 +557,8 @@ static const GLfloat gl_verts[] = { { CGRect lRectS = [[self superlayer] bounds]; - DBG_PRINT("MyNSOpenGLLayer::resizeWithOldSuperlayerSize: %p, texSize %dx%d, bounds: %lfx%lf -> %lfx%lf (refcnt %d)\n", - self, texWidth, texHeight, size.width, size.height, lRectS.size.width, lRectS.size.height, (int)[self retainCount]); + DBG_PRINT("MyNSOpenGLLayer::resizeWithOldSuperlayerSize: %p, texSize %dx%d, bounds: %lfx%lf -> %lf/%lf %lfx%lf (refcnt %d)\n", + self, texWidth, texHeight, size.width, size.height, lRectS.origin.x, lRectS.origin.y, lRectS.size.width, lRectS.size.height, (int)[self retainCount]); newTexWidth = lRectS.size.width; newTexHeight = lRectS.size.height; @@ -562,8 +571,8 @@ static const GLfloat gl_verts[] = { - (BOOL)canDrawInOpenGLContext:(NSOpenGLContext *)context pixelFormat:(NSOpenGLPixelFormat *)pixelFormat forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp { - SYNC_PRINT("", (int)shallDraw); - return shallDraw; + SYNC_PRINT("", (int)shallDraw, (int)isGLEnabled); + return shallDraw && isGLEnabled; } - (void)drawInOpenGLContext:(NSOpenGLContext *)context pixelFormat:(NSOpenGLPixelFormat *)pixelFormat @@ -573,7 +582,7 @@ static const GLfloat gl_verts[] = { SYNC_PRINT("<* "); // NSLog(@"MyNSOpenGLLayer::DRAW: %@",[NSThread callStackSymbols]); - if( shallDraw && ( NULL != pbuffer || NULL != newPBuffer || 0 != textureID ) ) { + if( isGLEnabled && shallDraw && ( NULL != pbuffer || NULL != newPBuffer || 0 != textureID ) ) { [context makeCurrentContext]; if( NULL != newPBuffer ) { // volatile OK @@ -825,6 +834,13 @@ NSOpenGLLayer* createNSOpenGLLayer(NSOpenGLContext* ctx, int gl3ShaderProgramNam return [[[MyNSOpenGLLayer alloc] init] setupWithContext:ctx gl3ShaderProgramName: (GLuint)gl3ShaderProgramName pixelFormat: fmt pbuffer: p texIDArg: (GLuint)texID opaque: opaque texWidth: texWidth texHeight: texHeight]; } + +void setNSOpenGLLayerEnabled(NSOpenGLLayer* layer, Bool enable) { + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; + [l setGLEnabled: enable]; + [pool release]; +} void setNSOpenGLLayerSwapInterval(NSOpenGLLayer* layer, int interval) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index f6bc5822b..ba60a7f38 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -33,6 +33,14 @@ package javax.media.nativewindow; public interface OffscreenLayerSurface { /** * Attach the offscreen layer to this offscreen layer surface. + *

        + * Implementation may realize all required resources at this point. + *

        + *

        + * It is mandatory that any related resources, e.g. a shared context, + * are not locked while calling this method. + *

        + * * @see #isOffscreenLayerSurfaceEnabled() * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false */ diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index b765a68c3..d85d1a84b 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -136,12 +136,31 @@ public class OSXUtil implements ToolkitProperties { return GetNSWindow0(nsView); } + /** + * Create a CALayer suitable to act as a root CALayer on the main-thread. + * @see #DestroyCALayer(long) + * @see #AddCASublayer(long, long) + */ public static long CreateCALayer(final int x, final int y, final int width, final int height) { return OSXUtil.RunOnMainThread(true, new Function() { public Long eval(Object... args) { return Long.valueOf( CreateCALayer0(x, y, width, height) ); } } ).longValue(); } + + /** + * Attach a sub CALayer to the root CALayer on the main-thread. + *

        + * Method will trigger a display + * call to the CALayer hierarchy to enforce resource creation if required, e.g. an NSOpenGLContext. + *

        + *

        + * It is mandatory that any related resources, e.g. a shared NSOpenGLContext, + * are not locked while calling this method. + *

        + * @see #CreateCALayer(int, int, int, int) + * @see #RemoveCASublayer(long, long) + */ public static void AddCASublayer(final long rootCALayer, final long subCALayer) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); @@ -152,6 +171,10 @@ public class OSXUtil implements ToolkitProperties { } }); } + + /** + * Detach a sub CALayer from the root CALayer on the main-thread. + */ public static void RemoveCASublayer(final long rootCALayer, final long subCALayer) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); @@ -161,6 +184,11 @@ public class OSXUtil implements ToolkitProperties { RemoveCASublayer0(rootCALayer, subCALayer); } } ); } + + /** + * Destroy a CALayer on the main-thread. + * @see #CreateCALayer(int, int, int, int) + */ public static void DestroyCALayer(final long caLayer) { if(0==caLayer) { throw new IllegalArgumentException("caLayer 0x"+Long.toHexString(caLayer)); diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 83f3c821f..8d876c175 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -430,6 +430,9 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + CGRect lRectRoot = [rootLayer frame]; DBG_PRINT("CALayer::AddCASublayer0.0: Origin %p frame0: %lf/%lf %lfx%lf\n", rootLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height); @@ -444,9 +447,6 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 rootLayer, (int)[rootLayer retainCount], subLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height, (int)[subLayer retainCount]); - [CATransaction begin]; - [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; - // simple 1:1 layout ! [subLayer setFrame:lRectRoot]; [rootLayer addSublayer:subLayer]; @@ -454,14 +454,20 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 // no animations for add/remove/swap sublayers etc // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] [rootLayer removeAllAnimations]; - // [rootLayer addAnimation:nil forKey:kCATransition]; + // [rootLayer addAnimation:nil forKey:kCATransition]; // JAU [rootLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; [rootLayer setNeedsDisplayOnBoundsChange: YES]; [subLayer removeAllAnimations]; - // [sublayer addAnimation:nil forKey:kCATransition]; + // [subLayer addAnimation:nil forKey:kCATransition]; // JAU [subLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; [subLayer setNeedsDisplayOnBoundsChange: YES]; + // Trigger display and hence ctx creation. + // The latter is essential since since the parent-context lock is cleared + // only for this window of time (method call). + [rootLayer setNeedsDisplay]; + [rootLayer displayIfNeeded]; + [CATransaction commit]; [pool release]; diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java index 2038124b5..61652371b 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java @@ -140,8 +140,8 @@ public class TestAddRemove01GLCanvasSwingAWT extends UITestCase { SwingUtilities.invokeAndWait(new Runnable() { public void run() { if( visible ) { - jFrame.validate(); jFrame.pack(); + jFrame.validate(); } jFrame.setVisible(visible); } } ) ; diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove02GLWindowNewtCanvasAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove02GLWindowNewtCanvasAWT.java index 0f12f967a..b4272a9c0 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove02GLWindowNewtCanvasAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove02GLWindowNewtCanvasAWT.java @@ -142,8 +142,8 @@ public class TestAddRemove02GLWindowNewtCanvasAWT extends UITestCase { SwingUtilities.invokeAndWait(new Runnable() { public void run() { if( visible ) { - jFrame.validate(); jFrame.pack(); + jFrame.validate(); } jFrame.setVisible(visible); } } ) ; -- cgit v1.2.3 From fdc20a0205bb01747055910eb2bb33202edee277 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 17 Feb 2013 18:55:18 +0100 Subject: OSX/Java7 Cleanup: Remove JavaNativeFoundation dependency; NativeWindow-JAWT: Remove c.fixup.jawt.version.macosx (redundant, libjawt.dylib is rpath'ed always) --- make/build-nativewindow.xml | 19 ---------------- make/scripts/make.jogl.all.macosx-java7.sh | 2 +- make/scripts/make.jogl.all.macosx-java7u12ea.sh | 25 ++++++++++++++++++++++ make/scripts/tests-osx-x64-java7.sh | 2 +- make/scripts/tests-osx-x64-java7OnJava6build.sh | 12 +++++++++++ make/scripts/tests-osx-x64-java7u12ea.sh | 12 +++++++++++ .../tests-osx-x64-java7u12eaOnJava6Build.sh | 12 +++++++++++ src/nativewindow/native/macosx/OSXmisc.m | 7 ++---- 8 files changed, 65 insertions(+), 26 deletions(-) create mode 100755 make/scripts/make.jogl.all.macosx-java7u12ea.sh create mode 100755 make/scripts/tests-osx-x64-java7OnJava6build.sh create mode 100755 make/scripts/tests-osx-x64-java7u12ea.sh create mode 100755 make/scripts/tests-osx-x64-java7u12eaOnJava6Build.sh (limited to 'src/nativewindow') diff --git a/make/build-nativewindow.xml b/make/build-nativewindow.xml index 3c97d9d9b..a8408eaa7 100644 --- a/make/build-nativewindow.xml +++ b/make/build-nativewindow.xml @@ -361,7 +361,6 @@ - @@ -446,9 +445,6 @@ - - - @@ -735,20 +731,6 @@ - - - - - - - - - - - - diff --git a/make/scripts/make.jogl.all.macosx-java7.sh b/make/scripts/make.jogl.all.macosx-java7.sh index afb72bf8c..fc7ace9d0 100755 --- a/make/scripts/make.jogl.all.macosx-java7.sh +++ b/make/scripts/make.jogl.all.macosx-java7.sh @@ -22,4 +22,4 @@ ant \ -Dtarget.targetlevel=1.6 \ -Dtarget.rt.jar=/opt-share/jre1.6.0_30/lib/rt.jar \ -Drootrel.build=build-macosx-java7 \ - $* 2>&1 | tee make.jogl.all.macosx.log + $* 2>&1 | tee make.jogl.all.macosx-java7.log diff --git a/make/scripts/make.jogl.all.macosx-java7u12ea.sh b/make/scripts/make.jogl.all.macosx-java7u12ea.sh new file mode 100755 index 000000000..88f23b8ee --- /dev/null +++ b/make/scripts/make.jogl.all.macosx-java7u12ea.sh @@ -0,0 +1,25 @@ +#! /bin/sh + +if [ -e /opt-share/etc/profile.ant ] ; then + . /opt-share/etc/profile.ant +fi + + +# -Dc.compiler.debug=true \ +# -Djavacdebug="true" \ +# -Djavacdebuglevel="source,lines,vars" \ +# +# -Dtarget.sourcelevel=1.6 \ +# -Dtarget.targetlevel=1.6 \ +# -Dtarget.rt.jar=/opt-share/jre1.6.0_30/lib/rt.jar \ + +JAVA_HOME=`/usr/libexec/java_home -version 1.7.0_12` +PATH=$JAVA_HOME/bin:$PATH +export JAVA_HOME PATH + +ant \ + -Dtarget.sourcelevel=1.6 \ + -Dtarget.targetlevel=1.6 \ + -Dtarget.rt.jar=/opt-share/jre1.6.0_30/lib/rt.jar \ + -Drootrel.build=build-macosx-java7 \ + $* 2>&1 | tee make.jogl.all.macosx-java7u12ea.log diff --git a/make/scripts/tests-osx-x64-java7.sh b/make/scripts/tests-osx-x64-java7.sh index e1b07202b..e870d0752 100755 --- a/make/scripts/tests-osx-x64-java7.sh +++ b/make/scripts/tests-osx-x64-java7.sh @@ -8,5 +8,5 @@ export JAVA_HOME PATH spath=`dirname $0` -. $spath/tests.sh $JAVA_HOME/bin/java -d64 ../build-macosx $* +. $spath/tests.sh $JAVA_HOME/bin/java -d64 ../build-macosx-java7 $* diff --git a/make/scripts/tests-osx-x64-java7OnJava6build.sh b/make/scripts/tests-osx-x64-java7OnJava6build.sh new file mode 100755 index 000000000..e1b07202b --- /dev/null +++ b/make/scripts/tests-osx-x64-java7OnJava6build.sh @@ -0,0 +1,12 @@ +#! /bin/bash + +export DYLD_LIBRARY_PATH=/usr/local/lib:$DYLD_LIBRARY_PATH + +JAVA_HOME=`/usr/libexec/java_home -version 1.7` +PATH=$JAVA_HOME/bin:$PATH +export JAVA_HOME PATH + +spath=`dirname $0` + +. $spath/tests.sh $JAVA_HOME/bin/java -d64 ../build-macosx $* + diff --git a/make/scripts/tests-osx-x64-java7u12ea.sh b/make/scripts/tests-osx-x64-java7u12ea.sh new file mode 100755 index 000000000..a8c9bed77 --- /dev/null +++ b/make/scripts/tests-osx-x64-java7u12ea.sh @@ -0,0 +1,12 @@ +#! /bin/bash + +export DYLD_LIBRARY_PATH=/usr/local/lib:$DYLD_LIBRARY_PATH + +JAVA_HOME=`/usr/libexec/java_home -version 1.7.0_12` +PATH=$JAVA_HOME/bin:$PATH +export JAVA_HOME PATH + +spath=`dirname $0` + +. $spath/tests.sh $JAVA_HOME/bin/java -d64 ../build-macosx-java7 $* + diff --git a/make/scripts/tests-osx-x64-java7u12eaOnJava6Build.sh b/make/scripts/tests-osx-x64-java7u12eaOnJava6Build.sh new file mode 100755 index 000000000..dad9c430e --- /dev/null +++ b/make/scripts/tests-osx-x64-java7u12eaOnJava6Build.sh @@ -0,0 +1,12 @@ +#! /bin/bash + +export DYLD_LIBRARY_PATH=/usr/local/lib:$DYLD_LIBRARY_PATH + +JAVA_HOME=`/usr/libexec/java_home -version 1.7.0_12` +PATH=$JAVA_HOME/bin:$PATH +export JAVA_HOME PATH + +spath=`dirname $0` + +. $spath/tests.sh $JAVA_HOME/bin/java -d64 ../build-macosx $* + diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 8d876c175..4c07b4df7 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -39,7 +39,6 @@ #include "jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow.h" #include -#import // #define VERBOSE 1 // @@ -740,8 +739,7 @@ JNIEXPORT jint JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetScreenRefreshR (JNIEnv *env, jclass unused, jint scrn_idx) { int res = 0; - JNF_COCOA_ENTER(env); - // NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; NSScreen *screen = NewtScreen_getNSScreenByIndex((int)scrn_idx); DBG_PRINT("GetScreenRefreshRate.0: screen %p\n", (void *)screen); if(NULL != screen) { @@ -760,8 +758,7 @@ JNIEXPORT jint JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetScreenRefreshR res = 60; // default .. (experienced on OSX 10.6.8) } DBG_PRINT("GetScreenRefreshRate.X: %d\n", (int)res); - // [pool release]; - JNF_COCOA_EXIT(env); + [pool release]; return res; } -- cgit v1.2.3 From 14b278536e6f8de2ee6254796b89bd27d5419b72 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 20 Feb 2013 21:51:40 +0100 Subject: OSX/Java7/CALayer + JAWT: Partially Fix AWT/NEWT CALayer 'out of sight' bug, where our CALayer is moved out of the visible area - same erroneous behavior for GLCanvas and NewtCanvasAWT - sized-frame: Set framesize and validate() it - sized-component: Set component preferred size and call frame.pack() - added workaround 'OffscreenLayerSurface.layoutSurfaceLayer()' to fix CALayer size, which snaps for: - OK initial size before setVisible: sized-frame and sized-component - OK resize w/ sized-frame - OK manual frame resize - Invisible: w/ sized-component after setVisible() ++ - CALayer-Sublayer (GL) has additional retain/release when added/removed to be on safe side. --- make/scripts/tests.sh | 73 ++++++++++++---------- .../classes/javax/media/opengl/awt/GLCanvas.java | 3 + .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 1 + .../macosx/MacOSXWindowSystemInterface-calayer.m | 24 ++++--- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 15 ++++- .../media/nativewindow/OffscreenLayerSurface.java | 15 +++++ .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 12 +++- .../jogamp/nativewindow/macosx/OSXUtil.java | 30 ++++++++- src/nativewindow/native/macosx/OSXmisc.m | 57 ++++++++++++++++- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 14 ++++- .../jogamp/newt/driver/macosx/WindowDriver.java | 2 +- .../junit/jogl/demos/es2/awt/TestGearsES2AWT.java | 3 +- .../jogl/demos/es2/newt/TestGearsES2NEWT.java | 3 +- .../demos/es2/newt/TestGearsES2NewtCanvasAWT.java | 3 +- .../demos/es2/newt/TestGearsES2NewtCanvasSWT.java | 9 +-- .../junit/jogl/demos/es2/swt/TestGearsES2SWT.java | 3 +- 16 files changed, 205 insertions(+), 62 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 7a65c736a..b3aa39dfc 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -35,7 +35,7 @@ if [ $MOSX -eq 1 ] ; then echo setup OSX environment vars #export NSZombieEnabled=YES export NSTraceEvents=YES - export OBJC_PRINT_EXCEPTIONS=YES + #export OBJC_PRINT_EXCEPTIONS=YES echo NSZombieEnabled $NSZombieEnabled 2>&1 | tee -a java-run.log echo NSTraceEvents $NSTraceEvents 2>&1 | tee -a java-run.log echo OBJC_PRINT_EXCEPTIONS $OBJC_PRINT_EXCEPTIONS 2>&1 | tee -a java-run.log @@ -135,7 +135,6 @@ function jrun() { #D_ARGS="-Dnewt.debug.Screen -Djogl.debug.Animator" #D_ARGS="-Djogl.debug.ExtensionAvailabilityCache -Djogl.debug=all -Dnativewindow.debug=all -Djogamp.debug.ProcAddressHelper=true -Djogamp.debug.NativeLibrary=true -Djogamp.debug.NativeLibrary.Lookup=true" #D_ARGS="-Dnewt.debug.MainThread" - #D_ARGS="-Dnewt.debug.Window" #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Dnativewindow.debug.NativeWindow" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Animator -Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.ExtensionAvailabilityCache" @@ -167,8 +166,8 @@ function jrun() { #D_ARGS="-Dnewt.debug.EDT" #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT -Djogl.debug.GLContext" #D_ARGS="-Dnewt.debug.Window -Djogl.debug.Animator -Dnewt.debug.Screen" - #D_ARGS="-Dnewt.debug.Window" - D_ARGS="-Dnewt.debug.Window.KeyEvent" + #D_ARGS="-Dnativewindow.debug.JAWT -Dnewt.debug.Window" + #D_ARGS="-Dnewt.debug.Window.KeyEvent" #D_ARGS="-Dnewt.debug.Window.MouseEvent" #D_ARGS="-Dnewt.debug.Window -Dnativewindow.debug=all" #D_ARGS="-Dnewt.debug.Window -Dnativewindow.debug.JAWT -Djogl.debug.Animator" @@ -222,9 +221,13 @@ function jrun() { #X_ARGS="-Dnativewindow.ws.name=jogamp.newt.driver.broadcom.egl $X_ARGS" echo CLASSPATH $CLASSPATH if [ $MOSX_MT -eq 1 ] ; then - X_ARGS="-XstartOnFirstThread $X_ARGS" - if [ $swton -eq 0 ] ; then + if [ $awton -eq 0 -a $swton -eq 0 ] ; then + # No AWT, No SWT -> Preserve Main-Thread + X_ARGS="-XstartOnFirstThread $X_ARGS" C_ARG="com.jogamp.newt.util.MainThread" + elif [ $swton -eq 1 ] ; then + # SWT: Only Launch on Main-Thread + X_ARGS="-XstartOnFirstThread $X_ARGS" fi fi echo @@ -255,6 +258,31 @@ function testawtswt() { jrun 1 1 $* 2>&1 | tee -a java-run.log } +# +# demos (any TK, more user driven tests) +# +#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* +testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWTAnalyzeBug455 $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWTBug450 $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper $* +#testawtswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT $* +#testawtswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2SWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestOlympicES1NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestRedSquareES1NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.gl3.newt.TestGeomShader01TextureGL3NEWT $* +#testswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT $* + # # core/newt (testnoawt and testawt) # @@ -262,13 +290,6 @@ function testawtswt() { #testnoawt com.jogamp.opengl.JoglVersion $* #testnoawt com.jogamp.newt.NewtVersion $* #testnoawt com.jogamp.newt.opengl.GLWindow $* -#testnoawt com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.gl3.newt.TestGeomShader01TextureGL3NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFloatUtil01MatrixMatrixMultNOUI $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestPMVMatrix01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestPMVMatrix02NEWT $* @@ -305,6 +326,9 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.acore.TestAddRemove02GLWindowNewtCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestAddRemove03GLWindowNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT $* + #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryOffscrnCapsNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT $* @@ -326,13 +350,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.glu.TestGluUnprojectFloatNOUI $* #testnoawt com.jogamp.opengl.test.junit.newt.TestRemoteWindow01NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestRemoteGLWindows01NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestOlympicES1NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestRedSquareES1NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT $* + #testnoawt com.jogamp.opengl.test.junit.newt.TestWindows01NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol02NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT $* @@ -373,11 +391,6 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug664GLCanvasSetVisibleSwingAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestIsRealizedConcurrency01AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.text.TestAWTTextRendererUseVertexArrayBug464 -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWTAnalyzeBug455 $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWTBug450 $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461FBOSupersamplingSwingAWT #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461PBufferSupersamplingSwingAWT #testawt com.jogamp.opengl.test.junit.jogl.glu.TestBug463ScaleImageMemoryAWT $* @@ -409,21 +422,19 @@ function testawtswt() { # newt.awt (testawt) # #testawt com.jogamp.opengl.test.junit.jogl.newt.TestSwingAWTRobotUsageBeforeJOGLInitBug411 $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper $* #testawt com.jogamp.opengl.test.junit.newt.TestEventSourceNotAWTBug #testawt com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot $* #testawt com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyEventOrderAWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyEventAutoRepeatAWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyPressReleaseUnmaskRepeatAWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* -testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyCodesAWT $* +#testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyCodesAWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyCodeModifiersAWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNEWTWindowAWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersAWTCanvas $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNewtCanvasAWT $* #testawtswt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNewtCanvasSWT $* + #testawt com.jogamp.opengl.test.junit.newt.TestListenerCom01AWT #testawt com.jogamp.opengl.test.junit.newt.TestCloseNewtAWT #testawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1AWT $* @@ -469,8 +480,6 @@ testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyCodesAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.TestImmModeSinkES1NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.TestImmModeSinkES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.TestES1FixedFunctionPipelineNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestRedSquareES1NEWT $* # # Texture / TextureUtils @@ -486,8 +495,6 @@ testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyCodesAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestTextureSequence01NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestTextureSequence01AWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube $* # # GLSL diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index c9069f9ce..dc4fe955c 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -702,6 +702,9 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } } sendReshape = true; // async if display() doesn't get called below, but avoiding deadlock + if(null != jawtWindow && jawtWindow.isOffscreenLayerSurfaceEnabled() ) { + jawtWindow.layoutSurfaceLayer(); + } } } } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 37aca0cd7..9e0174595 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -713,6 +713,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl } } } + backingLayerHost.layoutSurfaceLayer(); } else { lastWidth = drawable.getWidth(); lastHeight = drawable.getHeight(); diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index 55c4ad053..b965accab 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -114,6 +114,7 @@ extern GLboolean glIsVertexArray (GLuint array); - (void)dealloc { CGLContextObj cglCtx = [self CGLContextObj]; + DBG_PRINT("MyNSOpenGLContext::dealloc.0 %p (refcnt %d) - CGL-Ctx %p\n", self, (int)[self retainCount], cglCtx); [self clearDrawable]; if( NULL != cglCtx ) { @@ -537,7 +538,6 @@ static const GLfloat gl_verts[] = { { DBG_PRINT("MyNSOpenGLLayer::dealloc.0 %p (refcnt %d)\n", self, (int)[self retainCount]); // NSLog(@"MyNSOpenGLLayer::dealloc: %@",[NSThread callStackSymbols]); - [self disableAnimation]; pthread_mutex_lock(&renderLock); [self deallocPBuffer]; @@ -555,13 +555,23 @@ static const GLfloat gl_verts[] = { - (void)resizeWithOldSuperlayerSize:(CGSize)size { - CGRect lRectS = [[self superlayer] bounds]; - - DBG_PRINT("MyNSOpenGLLayer::resizeWithOldSuperlayerSize: %p, texSize %dx%d, bounds: %lfx%lf -> %lf/%lf %lfx%lf (refcnt %d)\n", - self, texWidth, texHeight, size.width, size.height, lRectS.origin.x, lRectS.origin.y, lRectS.size.width, lRectS.size.height, (int)[self retainCount]); + CALayer * superL = [self superlayer]; + CGRect lRectSFrame = [superL frame]; + + DBG_PRINT("MyNSOpenGLLayer::resizeWithOldSuperlayerSize: %p, texSize %dx%d -> size: %lfx%lf ; Super Frame[%lf/%lf %lfx%lf] (refcnt %d)\n", + self, texWidth, texHeight, size.width, size.height, + lRectSFrame.origin.x, lRectSFrame.origin.y, lRectSFrame.size.width, lRectSFrame.size.height, + (int)[self retainCount]); + + // With Java7 our root CALayer's frame gets off-limit -> force 0/0 origin! + if( lRectSFrame.origin.x!=0 || lRectSFrame.origin.y!=0 ) { + lRectSFrame.origin.x = 0; + lRectSFrame.origin.y = 0; + [superL setPosition: lRectSFrame.origin]; + } - newTexWidth = lRectS.size.width; - newTexHeight = lRectS.size.height; + newTexWidth = lRectSFrame.size.width; + newTexHeight = lRectSFrame.size.height; shallDraw = [self isGLSourceValid]; SYNC_PRINT("", newTexWidth, newTexHeight); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 007a917a6..d65f8c231 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -130,7 +130,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if(changed) { if(DEBUG) { System.err.println("JAWTWindow.updateBounds: "+bounds+" -> "+jb); - Thread.dumpStack(); + // Thread.dumpStack(); } bounds.setX(jawtBounds.getX()); bounds.setY(jawtBounds.getY()); @@ -205,7 +205,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } try { if(DEBUG) { - System.err.println("JAWTWindow.attachSurfaceHandle(): "+toHexString(layerHandle) + ", bounds "+bounds); + System.err.println("JAWTWindow.attachSurfaceHandle: "+toHexString(layerHandle) + ", bounds "+bounds); } attachSurfaceLayerImpl(layerHandle); offscreenSurfaceLayer = layerHandle; @@ -215,6 +215,17 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } protected abstract void attachSurfaceLayerImpl(final long layerHandle); + @Override + public void layoutSurfaceLayer() throws NativeWindowException { + if( !isOffscreenLayerSurfaceEnabled() ) { + throw new NativeWindowException("Not an offscreen layer surface"); + } + if( 0 != offscreenSurfaceLayer) { + layoutSurfaceLayerImpl(); + } + } + protected void layoutSurfaceLayerImpl() {} + @Override public final void detachSurfaceLayer() throws NativeWindowException { if( !isOffscreenLayerSurfaceEnabled() ) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index ba60a7f38..4885d5a4c 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -46,6 +46,21 @@ public interface OffscreenLayerSurface { */ public void attachSurfaceLayer(final long layerHandle) throws NativeWindowException; + /** + * Layout the offscreen layer according to the implementing class's constraints. + *

        + * This method allows triggering a re-layout of the offscreen surface + * in case the implementation requires it. + *

        + *

        + * Call this method if any parent or ancestor's layout has been changed, + * which could affects the layout of this surface. + *

        + * @see #isOffscreenLayerSurfaceEnabled() + * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false + */ + public void layoutSurfaceLayer() throws NativeWindowException; + /** * Detaches a previously attached offscreen layer from this offscreen layer surface. * @see #attachSurfaceLayer(long) diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 9b06cce1a..b25836d3c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -118,10 +118,20 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { OSXUtil.AddCASublayer(rootSurfaceLayerHandle, layerHandle); } + protected void layoutSurfaceLayerImpl() { + final long osl = getAttachedSurfaceLayer(); + final int w = getWidth(); + final int h = getHeight(); + if(DEBUG) { + System.err.println("JAWTWindow.fixSurfaceLayerLayout: "+toHexString(osl) + ", bounds "+bounds+", "+w+"x"+h); + } + OSXUtil.FixCALayerPosition(rootSurfaceLayerHandle, osl, w, h); + } + protected void detachSurfaceLayerImpl(final long layerHandle) { OSXUtil.RemoveCASublayer(rootSurfaceLayerHandle, layerHandle); } - + @Override public final long getWindowHandle() { return windowHandle; diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index d85d1a84b..5ff451cc0 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -149,7 +149,7 @@ public class OSXUtil implements ToolkitProperties { } /** - * Attach a sub CALayer to the root CALayer on the main-thread. + * Attach a sub CALayer to the root CALayer on the main-thread w/ blocking. *

        * Method will trigger a display * call to the CALayer hierarchy to enforce resource creation if required, e.g. an NSOpenGLContext. @@ -173,7 +173,30 @@ public class OSXUtil implements ToolkitProperties { } /** - * Detach a sub CALayer from the root CALayer on the main-thread. + * Fix root and sub CALayer position to 0/0 on the main-thread w/o blocking. + *

        + * For an unknown reason, on OSX/Java7 our root CALayer's frame position gets corrupted + * and is moved out of 'sight' .. or oddly half way to the upper right corner. + *

        + * + * @param rootCALayer the root surface layer, maybe null. + * @param subCALayer the client surface layer, maybe null. + * @param width the expected width + * @param height the expected height + */ + public static void FixCALayerPosition(final long rootCALayer, final long subCALayer, final int width, final int height) { + if( 0==rootCALayer && 0==subCALayer ) { + return; + } + RunOnMainThread(false, new Runnable() { + public void run() { + FixCALayerPosition0(rootCALayer, subCALayer, width, height); + } + }); + } + + /** + * Detach a sub CALayer from the root CALayer on the main-thread w/ blocking. */ public static void RemoveCASublayer(final long rootCALayer, final long subCALayer) { if(0==rootCALayer || 0==subCALayer) { @@ -186,7 +209,7 @@ public class OSXUtil implements ToolkitProperties { } /** - * Destroy a CALayer on the main-thread. + * Destroy a CALayer on the main-thread w/ blocking. * @see #CreateCALayer(int, int, int, int) */ public static void DestroyCALayer(final long caLayer) { @@ -323,6 +346,7 @@ public class OSXUtil implements ToolkitProperties { private static native long GetNSWindow0(long nsView); private static native long CreateCALayer0(int x, int y, int width, int height); private static native void AddCASublayer0(long rootCALayer, long subCALayer); + private static native void FixCALayerPosition0(long rootCALayer, long subCALayer, int width, int height); private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); private static native void RunOnMainThread0(Runnable runnable); diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 4c07b4df7..28e63e875 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -429,11 +429,13 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); + [subLayer retain]; // Pairs w/ RemoveCASublayer + [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; CGRect lRectRoot = [rootLayer frame]; - DBG_PRINT("CALayer::AddCASublayer0.0: Origin %p frame0: %lf/%lf %lfx%lf\n", + DBG_PRINT("CALayer::AddCASublayer0.0: Origin %p frame0: %lf/%lf %lfx%lf\n", rootLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height); if(lRectRoot.origin.x!=0 || lRectRoot.origin.y!=0) { lRectRoot.origin.x = 0; @@ -474,6 +476,57 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); } +/* + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: FixCALayerPosition0 + * Signature: (JJII)V + */ +JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_FixCALayerPosition0 + (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint width, jint height) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); + CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + + if( NULL != rootLayer ) { + CGRect lRect = [rootLayer frame]; + DBG_PRINT("CALayer::FixCALayerPosition0.0: Root Origin %p exp 0/0 %dx%d frame0: %lf/%lf %lfx%lf\n", + rootLayer, width, height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { + lRect.origin.x = 0; + lRect.origin.y = 0; + lRect.size.width = width; + lRect.size.height = height; + [rootLayer setFrame: lRect]; + DBG_PRINT("CALayer::FixCALayerPosition0.1: Root Origin %p frame*: %lf/%lf %lfx%lf\n", + rootLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + } + } + if( NULL != subLayer ) { + CGRect lRect = [subLayer frame]; + DBG_PRINT("CALayer::FixCALayerPosition0.0: SubL %p exp 0/0 %dx%d frame0: %lf/%lf %lfx%lf\n", + subLayer, width, height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { + lRect.origin.x = 0; + lRect.origin.y = 0; + lRect.size.width = width; + lRect.size.height = height; + [subLayer setFrame: lRect]; + DBG_PRINT("CALayer::FixCALayerPosition0.1: SubL Origin %p frame*: %lf/%lf %lfx%lf\n", + subLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + } + } + + [CATransaction commit]; + + [pool release]; + DBG_PRINT("CALayer::FixCALayerPosition0.X: root %p (refcnt %d) .sub %p (refcnt %d)\n", + rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); +} + /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: RemoveCASublayer0 @@ -495,7 +548,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RemoveCASublayer0 [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; [subLayer removeFromSuperlayer]; - // [subLayer release] is called explicitly, e.g. via CGL.releaseNSOpenGLLayer(..) (MyNSOpenGLLayer::releaseLayer) + [subLayer release]; // Pairs w/ AddCASublayer [CATransaction commit]; diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 195f8af8c..524917780 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -391,6 +391,18 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto reparentWindow(true, cont); } + @SuppressWarnings("deprecation") + @Override + public void reshape(int x, int y, int width, int height) { + super.reshape(x, y, width, height); + if(DEBUG) { + System.err.println("NewtCanvasAWT.reshape: "+x+"/"+y+" "+width+"x"+height); + } + if(null != jawtWindow && jawtWindow.isOffscreenLayerSurfaceEnabled() ) { + jawtWindow.layoutSurfaceLayer(); + } + } + @Override public void removeNotify() { java.awt.Container cont = AWTMisc.getContainer(this); @@ -459,7 +471,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto // force this AWT Canvas to be focus-able, // since this it is completely covered by the newtChild (z-order). - setFocusable(true); + setFocusable(true); } else { configureNewtChild(false); newtChild.setVisible(false); diff --git a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java index 08c7a14c2..f47ca327d 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java @@ -227,7 +227,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl } // else offscreen size is realized via recreation // no native event (fullscreen, some reparenting) positionChanged(true, x, y); - sizeChanged(true, width, height, false); // incl. validation (incl. repositioning) + sizeChanged(true, width, height, false); } if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && 0 != ( FLAG_IS_VISIBLE & flags) ) { if( !isOffscreenInstance ) { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java index 8d1ad57b4..447c6b94c 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java @@ -77,13 +77,12 @@ public class TestGearsES2AWT extends UITestCase { static int swapInterval = 1; static boolean exclusiveContext = false; static Thread awtEDT; - static Dimension rwsize; + static Dimension rwsize = null; @BeforeClass public static void initClass() { width = 640; height = 480; - rwsize = null; try { EventQueue.invokeAndWait(new Runnable() { public void run() { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java index 52ce425a8..47891a8df 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java @@ -71,7 +71,7 @@ import org.junit.Test; public class TestGearsES2NEWT extends UITestCase { static int screenIdx = 0; static PointImmutable wpos; - static DimensionImmutable wsize, rwsize; + static DimensionImmutable wsize, rwsize=null; static long duration = 500; // ms static boolean opaque = true; @@ -96,7 +96,6 @@ public class TestGearsES2NEWT extends UITestCase { public static void initClass() { if(null == wsize) { wsize = new Dimension(640, 480); - rwsize = null; } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NewtCanvasAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NewtCanvasAWT.java index 035ed624a..f98cb240b 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NewtCanvasAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NewtCanvasAWT.java @@ -78,7 +78,7 @@ public class TestGearsES2NewtCanvasAWT extends UITestCase { static int screenIdx = 0; static PointImmutable wpos; - static DimensionImmutable wsize, rwsize; + static DimensionImmutable wsize, rwsize = null; static long duration = 500; // ms static boolean opaque = true; @@ -99,7 +99,6 @@ public class TestGearsES2NewtCanvasAWT extends UITestCase { public static void initClass() { if(null == wsize) { wsize = new Dimension(640, 480); - rwsize = null; } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NewtCanvasSWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NewtCanvasSWT.java index 112a1282d..cb2cf064f 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NewtCanvasSWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NewtCanvasSWT.java @@ -73,7 +73,7 @@ import org.junit.Test; public class TestGearsES2NewtCanvasSWT extends UITestCase { static int screenIdx = 0; static PointImmutable wpos; - static DimensionImmutable wsize, rwsize; + static DimensionImmutable wsize, rwsize = null; static long duration = 500; // ms static boolean opaque = true; @@ -93,7 +93,6 @@ public class TestGearsES2NewtCanvasSWT extends UITestCase { public static void initClass() { if(null == wsize) { wsize = new Dimension(640, 480); - rwsize = new Dimension(-1, -1); } } @@ -219,7 +218,7 @@ public class TestGearsES2NewtCanvasSWT extends UITestCase { System.err.println("GL chosen: "+glWindow.getChosenCapabilities()); System.err.println("window pos/siz: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", "+glWindow.getInsets()); - if( 0 < rwsize.getWidth() && 0 < rwsize.getHeight() ) { + if( null != rwsize ) { for(int i=0; i<50; i++) { // 500 ms dispatched delay if( !display.readAndDispatch() ) { // blocks on linux .. display.sleep(); @@ -349,7 +348,9 @@ public class TestGearsES2NewtCanvasSWT extends UITestCase { } } wsize = new Dimension(w, h); - rwsize = new Dimension(rw, rh); + if( 0 < rw && 0 < rh ) { + rwsize = new Dimension(rw, rh); + } if(usePos) { wpos = new Point(x, y); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/swt/TestGearsES2SWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/swt/TestGearsES2SWT.java index 45bd3bb39..08e4ac26a 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/swt/TestGearsES2SWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/swt/TestGearsES2SWT.java @@ -65,7 +65,7 @@ import org.junit.Test; public class TestGearsES2SWT extends UITestCase { static int screenIdx = 0; static PointImmutable wpos; - static DimensionImmutable wsize, rwsize; + static DimensionImmutable wsize, rwsize=null; static long duration = 500; // ms static boolean opaque = true; @@ -85,7 +85,6 @@ public class TestGearsES2SWT extends UITestCase { public static void initClass() { if(null == wsize) { wsize = new Dimension(640, 480); - rwsize = null; } } -- cgit v1.2.3 From 405bc071d5d13e00d0561a485d31e3a7d61bf167 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 21 Feb 2013 14:22:10 +0100 Subject: TestNewtEventModifiers*: Robostness (uhh) Unify wait-clear result code - fix SWT event dispatching. --- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 17 ++++++ .../junit/newt/event/BaseNewtEventModifiers.java | 65 +++++++++++----------- .../event/TestNewtEventModifiersNewtCanvasSWT.java | 53 +++++++++--------- 3 files changed, 73 insertions(+), 62 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index 5479f2495..5c4fd82d2 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -482,6 +482,23 @@ public class SWTAccessor { } } + /** + * Runs the specified action on the SWT UI thread. + *

        + * If display is disposed or the current thread is the SWT UI thread + * {@link #invoke(boolean, Runnable)} is being used. + * @see #invoke(boolean, Runnable) + */ + public static void invoke(org.eclipse.swt.widgets.Display display, boolean wait, Runnable runnable) { + if( display.isDisposed() || Thread.currentThread() == display.getThread() ) { + invoke(wait, runnable); + } else if( wait ) { + display.syncExec(runnable); + } else { + display.asyncExec(runnable); + } + } + // // Specific X11 GTK ChildWindow - Using plain X11 native parenting (works well) // diff --git a/src/test/com/jogamp/opengl/test/junit/newt/event/BaseNewtEventModifiers.java b/src/test/com/jogamp/opengl/test/junit/newt/event/BaseNewtEventModifiers.java index 138d30823..4dd3bb98a 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/event/BaseNewtEventModifiers.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/event/BaseNewtEventModifiers.java @@ -318,11 +318,6 @@ public abstract class BaseNewtEventModifiers extends UITestCase { _testMouseListener = new TestMouseListener() ; } - @After - public void afterTest() throws Exception { - clearKeyboadAndMouse(); - } - //////////////////////////////////////////////////////////////////////////// // Following both methods are mandatory to deal with SWT's requirement // to run the SWT event dispatch on the TK thread - which must be the main thread on OSX. @@ -341,34 +336,32 @@ public abstract class BaseNewtEventModifiers extends UITestCase { _robot.setAutoDelay( MS_ROBOT_AUTO_DELAY ) ; { // Make sure all the buttons and modifier keys are released. - _releaseModifiers() ; - _escape() ; - eventDispatch(); eventDispatch(); eventDispatch(); - Thread.sleep( MS_ROBOT_POST_TEST_DELAY ) ; - eventDispatch(); eventDispatch(); eventDispatch(); - _testMouseListener.clear(); + clearKeyboadAndMouse(); } _testMouseListener.setModifierCheckEnabled( true ) ; Throwable throwable = null; - final Object sync = new Object(); - final RunnableTask rt = new RunnableTask( testAction, sync, true ); + // final Object sync = new Object(); + final RunnableTask rt = new RunnableTask( testAction, null, true ); try { - new Thread(rt, "Test-Thread").start(); - while( !rt.isExecuted() && null == throwable ) { - eventDispatch(); - } - if(null==throwable) { - throwable = rt.getThrowable(); - } - if(null!=throwable) { - throw new RuntimeException(throwable); - } + // synchronized(sync) { + new Thread(rt, "Test-Thread").start(); + int i=0; + while( !rt.isExecuted() && null == throwable ) { + System.err.println("WAIT-till-done: eventDispatch() #"+i++); + eventDispatch(); + } + if(null==throwable) { + throwable = rt.getThrowable(); + } + if(null!=throwable) { + throw new RuntimeException(throwable); + } + // } } finally { - _testMouseListener.setModifierCheckEnabled( false ) ; - eventDispatch(); eventDispatch(); eventDispatch(); - Thread.sleep( MS_ROBOT_POST_TEST_DELAY ) ; - eventDispatch(); eventDispatch(); eventDispatch(); + System.err.println("WAIT-till-done: DONE"); + _testMouseListener.setModifierCheckEnabled( false ) ; + clearKeyboadAndMouse(); } } @@ -684,20 +677,24 @@ public abstract class BaseNewtEventModifiers extends UITestCase { //////////////////////////////////////////////////////////////////////////// - public static void clearKeyboadAndMouse() throws Exception { - + public void eventDispatchedPostTestDelay() throws Exception { + eventDispatch(); eventDispatch(); eventDispatch(); + Thread.sleep( MS_ROBOT_POST_TEST_DELAY ) ; + eventDispatch(); eventDispatch(); eventDispatch(); + _testMouseListener.clear(); + } + + public void clearKeyboadAndMouse() throws Exception { // Make sure all modifiers are released, otherwise the user's // desktop can get locked up (ask me how I know this). - _releaseModifiers() ; _escape() ; - Thread.sleep( MS_ROBOT_POST_TEST_DELAY ) ; - _testMouseListener.clear(); + eventDispatchedPostTestDelay(); } //////////////////////////////////////////////////////////////////////////// - private static void _releaseModifiers() { + private void _releaseModifiers() { if (_robot != null) { @@ -722,7 +719,7 @@ public abstract class BaseNewtEventModifiers extends UITestCase { } } - private static void _escape() { + private void _escape() { if (_robot != null) { _robot.keyPress( java.awt.event.KeyEvent.VK_ESCAPE ) ; _robot.keyRelease( java.awt.event.KeyEvent.VK_ESCAPE ) ; diff --git a/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtEventModifiersNewtCanvasSWT.java b/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtEventModifiersNewtCanvasSWT.java index 002134216..6279b70dc 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtEventModifiersNewtCanvasSWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/event/TestNewtEventModifiersNewtCanvasSWT.java @@ -62,22 +62,23 @@ public class TestNewtEventModifiersNewtCanvasSWT extends BaseNewtEventModifiers //////////////////////////////////////////////////////////////////////////// - protected static void eventDispatch2xImpl() { - eventDispatchImpl(); + protected static void eventDispatchImpl() { + final int maxEvents = 10; try { Thread.sleep(100); } catch (InterruptedException e) { } - eventDispatchImpl(); - } - - protected static void eventDispatchImpl() { - if( !_display.isDisposed() ) { - if( !_display.readAndDispatch() ) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { } - } - } + final boolean[] res = { false }; + int i=0; + do { + SWTAccessor.invoke(_display, true, new Runnable() { + public void run() { + if( !_display.isDisposed() ) { + res[0] = _display.readAndDispatch(); + } else { + res[0] = false; + } + } } ); + } while( i Date: Fri, 22 Feb 2013 04:01:44 +0100 Subject: Fix CALayer pos/size and animation. - Fix CALayer animation: - All CALayer animations are set to nil via overriding 'actionForKey' - Fix CALayer pos/size bug: - Fix root and sub CALayer position to 0/0 and size on the main-thread w/o blocking. - If the sub CALayer implements the Objective-C NativeWindow protocol NWDedicatedSize (e.g. JOGL's MyNSOpenGLLayer), the dedicated size is passed to the layer, which propagates it appropriately. - On OSX/Java7 our root CALayer's frame position and size gets corrupted by its NSView, hence we have created the NWDedicatedSize protocol. --- make/build-jogl.xml | 14 +- make/build-nativewindow.xml | 3 +- make/scripts/tests.sh | 21 +-- .../macosx/MacOSXWindowSystemInterface-calayer.m | 197 ++++++++++++++------- .../native/macosx/MacOSXWindowSystemInterface.m | 1 - .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 2 +- .../jogamp/nativewindow/macosx/OSXUtil.java | 16 +- .../native/macosx/NativeWindowProtocols.h | 34 ++++ src/nativewindow/native/macosx/OSXmisc.m | 33 ++-- 9 files changed, 219 insertions(+), 102 deletions(-) create mode 100644 src/nativewindow/native/macosx/NativeWindowProtocols.h (limited to 'src/nativewindow') diff --git a/make/build-jogl.xml b/make/build-jogl.xml index 379758392..c481eb0f5 100644 --- a/make/build-jogl.xml +++ b/make/build-jogl.xml @@ -224,8 +224,9 @@ - - + + + @@ -1439,12 +1440,13 @@ + - - - + + + - + diff --git a/make/build-nativewindow.xml b/make/build-nativewindow.xml index a8408eaa7..d7ef73a46 100644 --- a/make/build-nativewindow.xml +++ b/make/build-nativewindow.xml @@ -691,8 +691,9 @@ - + + diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index b3aa39dfc..7a71932ca 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -171,7 +171,8 @@ function jrun() { #D_ARGS="-Dnewt.debug.Window.MouseEvent" #D_ARGS="-Dnewt.debug.Window -Dnativewindow.debug=all" #D_ARGS="-Dnewt.debug.Window -Dnativewindow.debug.JAWT -Djogl.debug.Animator" - #D_ARGS="-Dnewt.debug.Window" + #D_ARGS="-Dnewt.debug.Window -Djogl.debug.GLDrawable" + D_ARGS="-Dnewt.debug.Window" #D_ARGS="-Xprof" #D_ARGS="-Dnativewindow.debug=all" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Java2D -Djogl.debug.GLJPanel" @@ -261,27 +262,27 @@ function testawtswt() { # # demos (any TK, more user driven tests) # +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestOlympicES1NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestRedSquareES1NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWTAnalyzeBug455 $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWTBug450 $* -#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper $* #testawtswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT $* -#testawtswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2SWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestOlympicES1NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestRedSquareES1NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWTAnalyzeBug455 $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWTBug450 $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.gl3.newt.TestGeomShader01TextureGL3NEWT $* #testswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT $* +#testawtswt com.jogamp.opengl.test.junit.jogl.demos.es2.swt.TestGearsES2SWT $* # # core/newt (testnoawt and testawt) diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index b965accab..2cf74380c 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -1,6 +1,7 @@ #import "MacOSXWindowSystemInterface.h" #import #import +#import "NativeWindowProtocols.h" #include "timespec.h" #import @@ -126,7 +127,7 @@ extern GLboolean glIsVertexArray (GLuint array); @end -@interface MyNSOpenGLLayer: NSOpenGLLayer +@interface MyNSOpenGLLayer: NSOpenGLLayer { @private GLfloat gl_texCoords[8]; @@ -143,8 +144,8 @@ extern GLboolean glIsVertexArray (GLuint array); NSOpenGLPixelFormat* parentPixelFmt; int texWidth; int texHeight; - int newTexWidth; - int newTexHeight; + int dedicatedWidth; + int dedicatedHeight; volatile NSOpenGLPixelBuffer* pbuffer; volatile GLuint textureID; volatile NSOpenGLPixelBuffer* newPBuffer; @@ -173,8 +174,17 @@ extern GLboolean glIsVertexArray (GLuint array); texWidth: (int) texWidth texHeight: (int) texHeight; +- (void)releaseLayer; +- (void)deallocPBuffer; +- (void)disableAnimation; +- (void)pauseAnimation:(Bool)pause; +- (void)setSwapInterval:(int)interval; +- (void)tick; +- (void)waitUntilRenderSignal: (long) to_micros; +- (Bool)isGLSourceValid; + - (void) setGLEnabled: (Bool) enable; -- (Bool) validateTexSizeWithNewSize; +- (Bool) validateTexSizeWithDedicatedSize; - (Bool) validateTexSize: (int) _texWidth texHeight: (int) _texHeight; - (void) setTextureID: (int) _texID; @@ -182,21 +192,22 @@ extern GLboolean glIsVertexArray (GLuint array); - (void) setNewPBuffer: (NSOpenGLPixelBuffer*)p; - (void) applyNewPBuffer; +- (void)setDedicatedSize:(CGSize)size; // @NWDedicatedSize +- (CGRect)fixMyFrame; +- (CGRect)fixSuperPosition; +- (id)actionForKey:(NSString *)key ; - (NSOpenGLPixelFormat *)openGLPixelFormatForDisplayMask:(uint32_t)mask; - (NSOpenGLContext *)openGLContextForPixelFormat:(NSOpenGLPixelFormat *)pixelFormat; -- (void)disableAnimation; -- (void)pauseAnimation:(Bool)pause; -- (void)deallocPBuffer; -- (void)releaseLayer; +- (BOOL)canDrawInOpenGLContext:(NSOpenGLContext *)context pixelFormat:(NSOpenGLPixelFormat *)pixelFormat + forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp; +- (void)drawInOpenGLContext:(NSOpenGLContext *)context pixelFormat:(NSOpenGLPixelFormat *)pixelFormat + forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp; + #ifdef DBG_LIFECYCLE - (id)retain; - (oneway void)release; #endif - (void)dealloc; -- (void)setSwapInterval:(int)interval; -- (void)tick; -- (void)waitUntilRenderSignal: (long) to_micros; -- (Bool)isGLSourceValid; @end @@ -270,9 +281,9 @@ static const GLfloat gl_verts[] = { timespec_now(&lastWaitTime); shallDraw = NO; isGLEnabled = YES; - newTexWidth = _texWidth; - newTexHeight = _texHeight; - [self validateTexSizeWithNewSize]; + dedicatedWidth = _texWidth; + dedicatedHeight = _texHeight; + [self validateTexSizeWithDedicatedSize]; [self setTextureID: texID]; newPBuffer = NULL; @@ -345,9 +356,9 @@ static const GLfloat gl_verts[] = { isGLEnabled = enable; } -- (Bool) validateTexSizeWithNewSize +- (Bool) validateTexSizeWithDedicatedSize { - return [self validateTexSize: newTexWidth texHeight: newTexHeight]; + return [self validateTexSize: dedicatedWidth texHeight: dedicatedHeight]; } - (Bool) validateTexSize: (int) _texWidth texHeight: (int) _texHeight @@ -355,12 +366,14 @@ static const GLfloat gl_verts[] = { if(_texHeight != texHeight || _texWidth != texWidth) { texWidth = _texWidth; texHeight = _texHeight; + /** CGRect lRect = [self bounds]; lRect.origin.x = 0; lRect.origin.y = 0; lRect.size.width = texWidth; lRect.size.height = texHeight; - [self setFrame: lRect]; + [self setFrame: lRect]; */ + CGRect lRect = [self fixMyFrame]; GLfloat texCoordWidth, texCoordHeight; if(NULL != pbuffer) { @@ -382,8 +395,14 @@ static const GLfloat gl_verts[] = { gl_texCoords[5] = texCoordHeight; gl_texCoords[4] = texCoordWidth; gl_texCoords[6] = texCoordWidth; +#ifdef VERBOSE_ON + DBG_PRINT("MyNSOpenGLLayer::validateTexSize %p -> tex %dx%d, bounds: %lf/%lf %lfx%lf\n", + self, texWidth, texHeight, + lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); +#endif return YES; } else { + [self fixMyFrame]; return NO; } } @@ -450,34 +469,6 @@ static const GLfloat gl_verts[] = { } } -- (NSOpenGLPixelFormat *)openGLPixelFormatForDisplayMask:(uint32_t)mask -{ - DBG_PRINT("MyNSOpenGLLayer::openGLPixelFormatForDisplayMask: %p (refcnt %d) - parent-pfmt %p -> new-pfmt %p\n", - self, (int)[self retainCount], parentPixelFmt, parentPixelFmt); - // We simply take over ownership of parent PixelFormat .. - return parentPixelFmt; -} - -- (NSOpenGLContext *)openGLContextForPixelFormat:(NSOpenGLPixelFormat *)pixelFormat -{ - DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.0: %p (refcnt %d) - pfmt %p, parent %p, DisplayLink %p\n", - self, (int)[self retainCount], pixelFormat, parentCtx, displayLink); - // NSLog(@"MyNSOpenGLLayer::openGLContextForPixelFormat: %@",[NSThread callStackSymbols]); - myCtx = [[MyNSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:parentCtx]; -#ifndef HAS_CADisplayLink - if(NULL != displayLink) { - CVReturn cvres; - DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.1: setup DisplayLink %p\n", displayLink); - cvres = CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, [myCtx CGLContextObj], [pixelFormat CGLPixelFormatObj]); - if(kCVReturnSuccess != cvres) { - DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext failed: %d\n", self, cvres); - } - } -#endif - DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.X: new-ctx %p\n", myCtx); - return myCtx; -} - - (void)disableAnimation { DBG_PRINT("MyNSOpenGLLayer::disableAnimation.0: %p (refcnt %d) - displayLink %p\n", self, (int)[self retainCount], displayLink); @@ -553,29 +544,107 @@ static const GLfloat gl_verts[] = { return NULL != pbuffer || NULL != newPBuffer || 0 != textureID ; } -- (void)resizeWithOldSuperlayerSize:(CGSize)size - { - CALayer * superL = [self superlayer]; - CGRect lRectSFrame = [superL frame]; +// @NWDedicatedSize +- (void)setDedicatedSize:(CGSize)size { + DBG_PRINT("MyNSOpenGLLayer::setDedicatedSize: %p, texSize %dx%d <- %lfx%lf\n", + self, texWidth, texHeight, size.width, size.height); + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + + dedicatedWidth = size.width; + dedicatedHeight = size.height; + + CGRect rect = CGRectMake(0, 0, dedicatedWidth, dedicatedHeight); + [self setFrame: rect]; - DBG_PRINT("MyNSOpenGLLayer::resizeWithOldSuperlayerSize: %p, texSize %dx%d -> size: %lfx%lf ; Super Frame[%lf/%lf %lfx%lf] (refcnt %d)\n", - self, texWidth, texHeight, size.width, size.height, - lRectSFrame.origin.x, lRectSFrame.origin.y, lRectSFrame.size.width, lRectSFrame.size.height, - (int)[self retainCount]); + [CATransaction commit]; +} + +- (void) setFrame:(CGRect) frame { + CGRect rect = CGRectMake(0, 0, dedicatedWidth, dedicatedHeight); + [super setFrame: rect]; +} + +- (CGRect)fixMyFrame +{ + CGRect lRect = [self frame]; + + // With Java7 our root CALayer's frame gets off-limit -> force 0/0 origin! + if( lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=texWidth || lRect.size.height!=texHeight) { + DBG_PRINT("MyNSOpenGLLayer::fixMyFrame: %p, 0/0 texSize %dx%d -> Frame[%lf/%lf %lfx%lf]\n", + self, texWidth, texHeight, + lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + + lRect.origin.x = 0; + lRect.origin.y = 0; + lRect.size.width=texWidth; + lRect.size.height=texHeight; + [self setFrame: lRect]; + + [CATransaction commit]; + } + return lRect; +} + +- (CGRect)fixSuperPosition +{ + CALayer * superL = [self superlayer]; + CGRect lRect = [superL frame]; // With Java7 our root CALayer's frame gets off-limit -> force 0/0 origin! - if( lRectSFrame.origin.x!=0 || lRectSFrame.origin.y!=0 ) { - lRectSFrame.origin.x = 0; - lRectSFrame.origin.y = 0; - [superL setPosition: lRectSFrame.origin]; + if( lRect.origin.x!=0 || lRect.origin.y!=0 ) { + DBG_PRINT("MyNSOpenGLLayer::fixSuperPosition: %p, 0/0 -> Super Frame[%lf/%lf %lfx%lf]\n", + self, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + + lRect.origin.x = 0; + lRect.origin.y = 0; + [superL setPosition: lRect.origin]; + + [CATransaction commit]; } + return lRect; +} + +- (id)actionForKey:(NSString *)key +{ + DBG_PRINT("MyNSOpenGLLayer::actionForKey.0 %p key %s -> NIL\n", self, [key UTF8String]); + return nil; + // return [super actionForKey: key]; +} - newTexWidth = lRectSFrame.size.width; - newTexHeight = lRectSFrame.size.height; - shallDraw = [self isGLSourceValid]; - SYNC_PRINT("", newTexWidth, newTexHeight); +- (NSOpenGLPixelFormat *)openGLPixelFormatForDisplayMask:(uint32_t)mask +{ + DBG_PRINT("MyNSOpenGLLayer::openGLPixelFormatForDisplayMask: %p (refcnt %d) - parent-pfmt %p -> new-pfmt %p\n", + self, (int)[self retainCount], parentPixelFmt, parentPixelFmt); + // We simply take over ownership of parent PixelFormat .. + return parentPixelFmt; +} - [super resizeWithOldSuperlayerSize: size]; +- (NSOpenGLContext *)openGLContextForPixelFormat:(NSOpenGLPixelFormat *)pixelFormat +{ + DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.0: %p (refcnt %d) - pfmt %p, parent %p, DisplayLink %p\n", + self, (int)[self retainCount], pixelFormat, parentCtx, displayLink); + // NSLog(@"MyNSOpenGLLayer::openGLContextForPixelFormat: %@",[NSThread callStackSymbols]); + myCtx = [[MyNSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:parentCtx]; +#ifndef HAS_CADisplayLink + if(NULL != displayLink) { + CVReturn cvres; + DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.1: setup DisplayLink %p\n", displayLink); + cvres = CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, [myCtx CGLContextObj], [pixelFormat CGLPixelFormatObj]); + if(kCVReturnSuccess != cvres) { + DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext failed: %d\n", self, cvres); + } + } +#endif + DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.X: new-ctx %p\n", myCtx); + return myCtx; } - (BOOL)canDrawInOpenGLContext:(NSOpenGLContext *)context pixelFormat:(NSOpenGLPixelFormat *)pixelFormat @@ -601,7 +670,7 @@ static const GLfloat gl_verts[] = { GLenum textureTarget; - Bool texSizeChanged = [self validateTexSizeWithNewSize]; + Bool texSizeChanged = [self validateTexSizeWithDedicatedSize]; if( NULL != pbuffer ) { if( texSizeChanged && 0 != textureID ) { diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m index e8925f8e8..f8faeb8d0 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m @@ -575,7 +575,6 @@ void setContextView(NSOpenGLContext* ctx, NSView* view) { [ctx setView:view]; } [pool release]; - return ctx; } Bool makeCurrentContext(NSOpenGLContext* ctx) { diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index b25836d3c..3ec54ca78 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -125,7 +125,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { if(DEBUG) { System.err.println("JAWTWindow.fixSurfaceLayerLayout: "+toHexString(osl) + ", bounds "+bounds+", "+w+"x"+h); } - OSXUtil.FixCALayerPosition(rootSurfaceLayerHandle, osl, w, h); + OSXUtil.FixCALayerLayout(rootSurfaceLayerHandle, osl, w, h); } protected void detachSurfaceLayerImpl(final long layerHandle) { diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 5ff451cc0..aa44e2d64 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -173,10 +173,14 @@ public class OSXUtil implements ToolkitProperties { } /** - * Fix root and sub CALayer position to 0/0 on the main-thread w/o blocking. + * Fix root and sub CALayer position to 0/0 and size on the main-thread w/o blocking. *

        - * For an unknown reason, on OSX/Java7 our root CALayer's frame position gets corrupted - * and is moved out of 'sight' .. or oddly half way to the upper right corner. + * If the sub CALayer implements the Objective-C NativeWindow protocol NWDedicatedSize (e.g. JOGL's MyNSOpenGLLayer), + * the dedicated size is passed to the layer, which propagates it appropriately. + *

        + *

        + * On OSX/Java7 our root CALayer's frame position and size gets corrupted by its NSView, + * hence we have created the NWDedicatedSize protocol. *

        * * @param rootCALayer the root surface layer, maybe null. @@ -184,13 +188,13 @@ public class OSXUtil implements ToolkitProperties { * @param width the expected width * @param height the expected height */ - public static void FixCALayerPosition(final long rootCALayer, final long subCALayer, final int width, final int height) { + public static void FixCALayerLayout(final long rootCALayer, final long subCALayer, final int width, final int height) { if( 0==rootCALayer && 0==subCALayer ) { return; } RunOnMainThread(false, new Runnable() { public void run() { - FixCALayerPosition0(rootCALayer, subCALayer, width, height); + FixCALayerLayout0(rootCALayer, subCALayer, width, height); } }); } @@ -346,7 +350,7 @@ public class OSXUtil implements ToolkitProperties { private static native long GetNSWindow0(long nsView); private static native long CreateCALayer0(int x, int y, int width, int height); private static native void AddCASublayer0(long rootCALayer, long subCALayer); - private static native void FixCALayerPosition0(long rootCALayer, long subCALayer, int width, int height); + private static native void FixCALayerLayout0(long rootCALayer, long subCALayer, int width, int height); private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); private static native void RunOnMainThread0(Runnable runnable); diff --git a/src/nativewindow/native/macosx/NativeWindowProtocols.h b/src/nativewindow/native/macosx/NativeWindowProtocols.h new file mode 100644 index 000000000..b91a50dfd --- /dev/null +++ b/src/nativewindow/native/macosx/NativeWindowProtocols.h @@ -0,0 +1,34 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +#import + +@protocol NWDedicatedSize +- (void)setDedicatedSize:(CGSize)size; +@end + diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 28e63e875..c74d6cc58 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -33,6 +33,7 @@ #include #include #import +#import "NativeWindowProtocols.h" #include "NativewindowCommon.h" #include "jogamp_nativewindow_macosx_OSXUtil.h" @@ -335,6 +336,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 - (oneway void)release; - (void)dealloc; #endif +- (id)actionForKey:(NSString *)key ; @end @@ -378,6 +380,12 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 #endif +- (id)actionForKey:(NSString *)key +{ + DBG_PRINT("MyCALayer::actionForKey.0 %p key %s -> NIL\n", self, [key UTF8String]); + return nil; + // return [super actionForKey: key]; +} @end @@ -478,10 +486,10 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil - * Method: FixCALayerPosition0 + * Method: FixCALayerLayout0 * Signature: (JJII)V */ -JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_FixCALayerPosition0 +JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_FixCALayerLayout0 (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint width, jint height) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -493,38 +501,37 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_FixCALayerPositio if( NULL != rootLayer ) { CGRect lRect = [rootLayer frame]; - DBG_PRINT("CALayer::FixCALayerPosition0.0: Root Origin %p exp 0/0 %dx%d frame0: %lf/%lf %lfx%lf\n", - rootLayer, width, height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { + DBG_PRINT("CALayer::FixCALayerLayout0.0: Root %p exp 0/0 %dx%d -> frame0: %lf/%lf %lfx%lf\n", + rootLayer, (int)width, (int)height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); lRect.origin.x = 0; lRect.origin.y = 0; lRect.size.width = width; lRect.size.height = height; [rootLayer setFrame: lRect]; - DBG_PRINT("CALayer::FixCALayerPosition0.1: Root Origin %p frame*: %lf/%lf %lfx%lf\n", - rootLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); } } if( NULL != subLayer ) { CGRect lRect = [subLayer frame]; - DBG_PRINT("CALayer::FixCALayerPosition0.0: SubL %p exp 0/0 %dx%d frame0: %lf/%lf %lfx%lf\n", - subLayer, width, height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { + DBG_PRINT("CALayer::FixCALayerLayout0.0: SubL %p exp 0/0 %dx%d -> frame0: %lf/%lf %lfx%lf\n", + subLayer, (int)width, (int)height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); lRect.origin.x = 0; lRect.origin.y = 0; lRect.size.width = width; lRect.size.height = height; - [subLayer setFrame: lRect]; - DBG_PRINT("CALayer::FixCALayerPosition0.1: SubL Origin %p frame*: %lf/%lf %lfx%lf\n", - subLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + if( [subLayer conformsToProtocol:@protocol(NWDedicatedSize)] ) { + CALayer * subLayerDS = (CALayer *) subLayer; + [subLayerDS setDedicatedSize: lRect.size]; + } else { + [subLayer setFrame: lRect]; + } } } [CATransaction commit]; [pool release]; - DBG_PRINT("CALayer::FixCALayerPosition0.X: root %p (refcnt %d) .sub %p (refcnt %d)\n", - rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount]); } /* -- cgit v1.2.3 From 808a9a27a8c1c9e0a6701a8dd81d51f8daa8129d Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 28 Feb 2013 00:39:28 +0100 Subject: Fix NEWT/AWT WindowClosing Unit Tests ; Review/Cleanup NEWT WindowClosing mechanism Due to a NEWT WindowClosing event regression cause by NewtCanvasAWT changes a review of our WindowClosing event mechanism was required. Important cleanups are marked w/ '(*)' below. I would have preferred to change the 'WindowListener.windowDestroyNotify(WindowEvent)' method to pass a WindowCloseEvent object exposing more information like toolkit or programmatic destruction and passing whether a 'closing' or 'nop' action will be performed based on the WindowClosingMode. For now I postponed this idea .. since it would change the API again, but may reconsider it after merging the Android 'closing' patch. - InputEvent.consumedTag -> NEWTEvent.consumedTag - Window - (*) Promote setWindowDestroyNotifyAction(Runnable) to public, former WindowImpl.setHandleDestroyNotify(boolean). Using a Runnable action for WindowImpl.windowDestroyNotify(boolean) allows a setting defined alternative for destroy() and gets rid of [ab]using WindowListener.windowDestroyNotify(WindowEvent) for lifecycle actions. Used in: - GLWindow - GLAutoDrawableDelegate impl. - WindowImpl - Respect NEWTEvent.consumedTag for WindowEvents as well - (*) Impl. setHandleDestroyNotify(boolean) (see above) - (*) destroy() simply sends out pre- and post- destruction Window events, where windowDestroyNotify(boolean) sends out the pre-destruction event if NOP. - (*) windowDestroyNotify(boolean) is public now, allowing other impl. details to follow proper destruction using handleDestroyNotify Runnable (-> NewtCanvasAWT). - AWTWindowClosingProtocol: - addClosingListenerOneShot() -> addClosingListener() - calling addClosingListener() at addNotify() - calling removeClosingListener() at removeNotify() - AWTWindowClosingProtocol ctor taking NOP runnable, allowing to send WindowEvent.EVENT_WINDOW_DESTROY_NOTIFY at WindowClosingMode.DO_NOTHING_ON_CLOSE - add/remove listener on AWT-EDT - AWTWindowAdapter - Add 'removeWindowClosingFrom(..)', allowing to remove window closing event fwd. - Also fwd windowClosed in window closing fwd'ing. - NewtCanvasAWT - (*) Utilize AWTWindowClosingProtocol NOP runnable (see above) to fwd closing-NOP event to NEWT - (*) Unify remove/destroy code in destroyImpl(..) - !removeNotify -> destroy NEWT child programatic or as toolkit event - removeNotify || windowClosing -> destroy jawtWindow - (*) Remove AWTWindowAdapter/AWTParentWindowAdapter's windowClosingListener, since we utilize AWTWindowClosingProtocol - DisplayImpl - Adding 'final void dispatchMessage(final NEWTEvent event)' allowing to remove the NEWTEventTask wrapping for no reason in enqueueEvent(..) if on EDT and waiting. --- make/scripts/tests.sh | 5 +- .../com/jogamp/opengl/GLAutoDrawableDelegate.java | 6 +- .../classes/javax/media/opengl/awt/GLCanvas.java | 6 +- .../classes/javax/media/opengl/awt/GLJPanel.java | 5 +- .../nativewindow/awt/AWTWindowClosingProtocol.java | 85 ++++++----- .../javax/media/nativewindow/NativeWindow.java | 3 +- .../media/nativewindow/WindowClosingProtocol.java | 4 + src/newt/classes/com/jogamp/newt/Window.java | 36 ++++- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 83 ++++++----- .../jogamp/newt/awt/applet/JOGLNewtAppletBase.java | 4 +- .../classes/com/jogamp/newt/event/InputEvent.java | 5 - .../classes/com/jogamp/newt/event/NEWTEvent.java | 6 + .../com/jogamp/newt/event/WindowListener.java | 5 +- .../com/jogamp/newt/event/awt/AWTAdapter.java | 7 +- .../jogamp/newt/event/awt/AWTWindowAdapter.java | 20 ++- .../classes/com/jogamp/newt/opengl/GLWindow.java | 14 +- src/newt/classes/jogamp/newt/DisplayImpl.java | 26 ++-- src/newt/classes/jogamp/newt/WindowImpl.java | 72 ++++++---- .../newt/awt/event/AWTParentWindowAdapter.java | 4 +- .../jogamp/newt/driver/awt/WindowDriver.java | 5 +- .../jogl/acore/TestGLAutoDrawableDelegateNEWT.java | 160 +++++++++++++++++++++ ...estGLAutoDrawableDelegateOnOffscrnCapsNEWT.java | 11 +- .../acore/TestGLContextDrawableSwitch01NEWT.java | 9 +- .../acore/TestGLContextDrawableSwitch11NEWT.java | 9 +- .../jogl/acore/TestSharedContextNewtAWTBug523.java | 5 +- .../opengl/test/junit/newt/TestCloseNewtAWT.java | 7 +- .../junit/newt/TestWindowClosingProtocol01AWT.java | 24 ++-- .../newt/TestWindowClosingProtocol02NEWT.java | 12 +- .../newt/TestWindowClosingProtocol03NewtAWT.java | 41 ++++-- .../opengl/test/junit/util/AWTRobotUtil.java | 83 +++++++---- 30 files changed, 539 insertions(+), 223 deletions(-) create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateNEWT.java (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 7a71932ca..7a43fd3da 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -266,7 +266,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestOlympicES1NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestRedSquareES1NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* -testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testawtswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube $* @@ -330,6 +330,7 @@ testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasA #testnoawt com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateOnOffscrnCapsNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryOffscrnCapsNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT $* @@ -437,7 +438,6 @@ testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasA #testawtswt com.jogamp.opengl.test.junit.newt.event.TestNewtEventModifiersNewtCanvasSWT $* #testawt com.jogamp.opengl.test.junit.newt.TestListenerCom01AWT -#testawt com.jogamp.opengl.test.junit.newt.TestCloseNewtAWT #testawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1AWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES2NEWT $* @@ -448,6 +448,7 @@ testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasA #testnoawt com.jogamp.opengl.test.junit.jogl.caps.TestBug605FlippedImageAWT $* #testawt com.jogamp.opengl.test.junit.jogl.glsl.TestShaderCompilationBug459AWT +#testawt com.jogamp.opengl.test.junit.newt.TestCloseNewtAWT #testawt com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol01AWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol02NEWT $* #testawt com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol03NewtAWT $* diff --git a/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java index 206331ac0..0f0f03ac4 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java +++ b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java @@ -51,12 +51,12 @@ import jogamp.opengl.GLDrawableImpl; * utilizing already created {@link GLDrawable} and {@link GLContext} instances. *

        * Since no native windowing system events are being processed, it is recommended - * to handle at least: + * to handle at least the {@link com.jogamp.newt.event.WindowEvent window events}: *

          *
        • {@link com.jogamp.newt.event.WindowListener#windowRepaint(com.jogamp.newt.event.WindowUpdateEvent) repaint} using {@link #windowRepaintOp()}
        • *
        • {@link com.jogamp.newt.event.WindowListener#windowResized(com.jogamp.newt.event.WindowEvent) resize} using {@link #windowResizedOp()}
        • - *
        • {@link com.jogamp.newt.event.WindowListener#windowDestroyNotify(com.jogamp.newt.event.WindowEvent) destroy-notify} using {@link #windowDestroyNotifyOp()}
        • - *
        + * + * and setup a {@link com.jogamp.newt.Window#setWindowDestroyNotifyAction(Runnable) custom toolkit destruction} issuing {@link #windowDestroyNotifyOp()}. *

        *

        * See example {@link com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateNEWT TestGLAutoDrawableDelegateNEWT}. diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index dc4fe955c..94e123b3e 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -176,7 +176,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing public void run() { GLCanvas.this.destroyImpl( true ); } - }); + }, null); /** Creates a new GLCanvas component with a default set of OpenGL capabilities, using the default OpenGL capabilities selection @@ -460,7 +460,6 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing if( isVisible() ) { Threading.invoke(true, displayOnEDTAction, getTreeLock()); } - awtWindowClosingProtocol.addClosingListenerOneShot(); } /** @@ -568,7 +567,8 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing // for all launch flavors (applet/javaws/..) // validateGLDrawable(); } - + awtWindowClosingProtocol.addClosingListener(); + if(DEBUG) { System.err.println(getThreadName()+": Info: addNotify - end: peer: "+getPeer()); } diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java index 2b99bb570..6c28c75ab 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java @@ -174,7 +174,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing public void run() { GLJPanel.this.destroy(); } - }); + }, null); static { // Force eager initialization of part of the Java2D class since @@ -369,6 +369,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing @Override public void addNotify() { super.addNotify(); + awtWindowClosingProtocol.addClosingListener(); if (DEBUG) { System.err.println(getThreadName()+": GLJPanel.addNotify()"); } @@ -677,8 +678,6 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing if (!isInitialized) { backend.initialize(); } - - awtWindowClosingProtocol.addClosingListenerOneShot(); } @Override diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java index d78b4ac15..e3f85b948 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java @@ -33,22 +33,31 @@ import java.awt.Window; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; + import javax.media.nativewindow.WindowClosingProtocol; +import jogamp.common.awt.AWTEDTExecutor; import jogamp.nativewindow.awt.AWTMisc; public class AWTWindowClosingProtocol implements WindowClosingProtocol { private Component comp; - private Runnable closingOperation; - private volatile boolean closingListenerSet = false; + private Runnable closingOperationClose; + private Runnable closingOperationNOP; + private boolean closingListenerSet = false; private Object closingListenerLock = new Object(); private WindowClosingMode defaultCloseOperation = WindowClosingMode.DISPOSE_ON_CLOSE; private boolean defaultCloseOperationSetByUser = false; - public AWTWindowClosingProtocol(Component comp, Runnable closingOperation) { + /** + * @param comp mandatory AWT component which AWT Window is being queried by parent traversal + * @param closingOperationClose mandatory closing operation, triggered if windowClosing and {@link WindowClosingMode#DISPOSE_ON_CLOSE} + * @param closingOperationNOP optional closing operation, triggered if windowClosing and {@link WindowClosingMode#DO_NOTHING_ON_CLOSE} + */ + public AWTWindowClosingProtocol(Component comp, Runnable closingOperationClose, Runnable closingOperationNOP) { this.comp = comp; - this.closingOperation = closingOperation; + this.closingOperationClose = closingOperationClose; + this.closingOperationNOP = closingOperationNOP; } class WindowClosingAdapter extends WindowAdapter { @@ -59,54 +68,56 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { if( WindowClosingMode.DISPOSE_ON_CLOSE == op ) { // we have to issue this call right away, // otherwise the window gets destroyed - closingOperation.run(); + closingOperationClose.run(); + } else if( null != closingOperationNOP ){ + closingOperationNOP.run(); } } } WindowListener windowClosingAdapter = new WindowClosingAdapter(); - final boolean addClosingListenerImpl() { - Window w = AWTMisc.getWindow(comp); - if(null!=w) { - w.addWindowListener(windowClosingAdapter); - return true; - } - return false; - } - /** - * Adds this closing listener to the components Window if exist and only one time.
        - * Hence you may call this method every time to ensure it has been set, - * ie in case the Window parent is not available yet. + * Adds this closing listener to the components Window if exist and only one time. + *

        + * If the closing listener is already added, and {@link IllegalStateException} is thrown. + *

        * - * @return + * @return true if added, otherwise false. + * @throws IllegalStateException */ - public final boolean addClosingListenerOneShot() { - if(!closingListenerSet) { // volatile: ok + public final boolean addClosingListener() throws IllegalStateException { synchronized(closingListenerLock) { - if(!closingListenerSet) { - closingListenerSet=addClosingListenerImpl(); - return closingListenerSet; - } + if(closingListenerSet) { + throw new IllegalStateException("WindowClosingListener already set"); + } + final Window w = AWTMisc.getWindow(comp); + if(null!=w) { + AWTEDTExecutor.singleton.invoke(true, new Runnable() { + public void run() { + w.addWindowListener(windowClosingAdapter); + } } ); + closingListenerSet = true; + return true; + } } - } - return false; + return false; } public final boolean removeClosingListener() { - if(closingListenerSet) { // volatile: ok synchronized(closingListenerLock) { - if(closingListenerSet) { - Window w = AWTMisc.getWindow(comp); - if(null!=w) { - w.removeWindowListener(windowClosingAdapter); - closingListenerSet = false; - return true; - } - } + if(closingListenerSet) { + final Window w = AWTMisc.getWindow(comp); + if(null!=w) { + AWTEDTExecutor.singleton.invoke(true, new Runnable() { + public void run() { + w.removeWindowListener(windowClosingAdapter); + } } ); + closingListenerSet = false; + return true; + } + } } - } - return false; + return false; } /** diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java index 12e202975..a740ebbe0 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindow.java @@ -54,8 +54,7 @@ import javax.media.nativewindow.util.Point; public interface NativeWindow extends NativeSurface { /** - * destroys the window and releases - * windowing related resources. + * Destroys this window incl. releasing all related resources. */ public void destroy(); diff --git a/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java b/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java index 884c916e4..02f68f442 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java +++ b/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java @@ -37,6 +37,10 @@ package javax.media.nativewindow; * this protocol default behavior {@link WindowClosingMode#DISPOSE_ON_CLOSE DISPOSE_ON_CLOSE} shall be used.

        */ public interface WindowClosingProtocol { + + /** + * Window closing mode if triggered by toolkit close operation. + */ public enum WindowClosingMode { /** * Do nothing on native window close operation.
        diff --git a/src/newt/classes/com/jogamp/newt/Window.java b/src/newt/classes/com/jogamp/newt/Window.java index cc42465f1..ab1eef308 100644 --- a/src/newt/classes/com/jogamp/newt/Window.java +++ b/src/newt/classes/com/jogamp/newt/Window.java @@ -28,12 +28,15 @@ package com.jogamp.newt; +import com.jogamp.newt.event.WindowEvent; import com.jogamp.newt.event.WindowListener; import com.jogamp.newt.event.KeyListener; import com.jogamp.newt.event.KeyEvent; import com.jogamp.newt.event.InputEvent; import com.jogamp.newt.event.MouseListener; import jogamp.newt.Debug; +import jogamp.newt.WindowImpl; + import javax.media.nativewindow.CapabilitiesChooser; import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.NativeWindow; @@ -104,20 +107,42 @@ public interface Window extends NativeWindow, WindowClosingProtocol { CapabilitiesImmutable getChosenCapabilities(); /** - * Destroy the Window and it's children, incl. native destruction.
        - * The Window can be recreate via {@link #setVisible(boolean) setVisible(true)}. - *

        Visibility is set to false.

        + * {@inheritDoc} + *

        + * Also iterates through this window's children and destroys them. + *

        + *

        + * Visibility is set to false. + *

        + *

        + * Method sends out {@link WindowEvent#EVENT_WINDOW_DESTROY_NOTIFY pre-} and + * {@link WindowEvent#EVENT_WINDOW_DESTROYED post-} destruction events + * to all of it's {@link WindowListener}. + *

        *

        * This method invokes {@link Screen#removeReference()} after it's own destruction,
        * which will issue {@link Screen#destroy()} if the reference count becomes 0.
        * This destruction sequence shall end up in {@link Display#destroy()}, if all reference counts become 0. *

        + *

        + * The Window can be recreate via {@link #setVisible(boolean) setVisible(true)}. + *

        * @see #destroy() * @see #setVisible(boolean) */ @Override void destroy(); + /** + * Set a custom action handling destruction issued by a {@link WindowImpl#windowDestroyNotify(boolean) toolkit triggered window destroy} + * replacing the default {@link #destroy()} action. + *

        + * The custom action shall call {@link #destroy()} + * but may perform further tasks before and after. + *

        + */ + void setWindowDestroyNotifyAction(Runnable r); + /** * setVisible makes the window and children visible if visible is true, * otherwise the window and children becomes invisible. @@ -383,10 +408,13 @@ public interface Window extends NativeWindow, WindowClosingProtocol { // WindowListener // + /** + * Send a {@link WindowEvent} to all {@link WindowListener}. + * @param eventType a {@link WindowEvent} type, e.g. {@link WindowEvent#EVENT_WINDOW_REPAINT}. + */ public void sendWindowEvent(int eventType); /** - * * Appends the given {@link com.jogamp.newt.event.WindowListener} to the end of * the list. */ diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 3503dabd5..3c10859bf 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -51,6 +51,7 @@ import javax.swing.MenuSelectionManager; import jogamp.nativewindow.awt.AWTMisc; import jogamp.newt.Debug; +import jogamp.newt.WindowImpl; import jogamp.newt.awt.NewtFactoryAWT; import jogamp.newt.awt.event.AWTParentWindowAdapter; import jogamp.newt.driver.DriverClearFocus; @@ -59,9 +60,9 @@ import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol; import com.jogamp.nativewindow.awt.JAWTWindow; import com.jogamp.newt.Display; import com.jogamp.newt.Window; -import com.jogamp.newt.event.InputEvent; import com.jogamp.newt.event.KeyEvent; import com.jogamp.newt.event.KeyListener; +import com.jogamp.newt.event.NEWTEvent; import com.jogamp.newt.event.WindowAdapter; import com.jogamp.newt.event.WindowEvent; import com.jogamp.newt.event.WindowListener; @@ -88,16 +89,22 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto private boolean newtChildAttached = false; private boolean isOnscreen = true; private WindowClosingMode newtChildCloseOp; - private AWTAdapter awtAdapter = null; + private AWTParentWindowAdapter awtAdapter = null; private AWTAdapter awtMouseAdapter = null; private AWTAdapter awtKeyAdapter = null; private AWTWindowClosingProtocol awtWindowClosingProtocol = new AWTWindowClosingProtocol(this, new Runnable() { public void run() { - NewtCanvasAWT.this.destroy(); + NewtCanvasAWT.this.destroyImpl(false /* removeNotify */, true /* windowClosing */); } - }); + }, new Runnable() { + public void run() { + if( newtChild != null ) { + newtChild.sendWindowEvent(WindowEvent.EVENT_WINDOW_DESTROY_NOTIFY); + } + } + } ); /** * Instantiates a NewtCanvas without a NEWT child.
        @@ -209,7 +216,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } public void keyTyped(KeyEvent e) { if(suppress) { - e.setAttachment(InputEvent.consumedTag); + e.setAttachment(NEWTEvent.consumedTag); suppress = false; // reset } } @@ -239,7 +246,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } } if(suppress) { - evt.setAttachment(InputEvent.consumedTag); + evt.setAttachment(NEWTEvent.consumedTag); } if(DEBUG) { System.err.println("NewtCanvasAWT.focusKey: XXX: "+ks); @@ -361,27 +368,17 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto ", displayable "+isDisplayable()+", cont "+AWTMisc.getContainer(this)); } } + awtWindowClosingProtocol.addClosingListener(); } @Override public void removeNotify() { + awtWindowClosingProtocol.removeClosingListener(); + if( Beans.isDesignTime() ) { super.removeNotify(); } else { - java.awt.Container cont = AWTMisc.getContainer(this); - if(DEBUG) { - System.err.println("NewtCanvasAWT.removeNotify: "+newtChild+", from "+cont); - } - // Detach OLS early.. - final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(newtChild, true); - if(null != ols && ols.isSurfaceLayerAttached()) { - ols.detachSurfaceLayer(); - } - detachNewtChild(cont); // will destroy context (offscreen -> onscreen) and implicit detachSurfaceLayer (if still attached) - - NewtFactoryAWT.destroyNativeWindow(jawtWindow); - jawtWindow=null; - + destroyImpl(true /* removeNotify */, false /* windowClosing */); super.removeNotify(); } } @@ -397,20 +394,32 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto * @see Window#destroy() */ public final void destroy() { + destroyImpl(false /* removeNotify */, false /* windowClosing */); + } + + private final void destroyImpl(boolean removeNotify, boolean windowClosing) { if( null !=newtChild ) { java.awt.Container cont = AWTMisc.getContainer(this); if(DEBUG) { - System.err.println("NewtCanvasAWT.destroy(): "+newtChild+", from "+cont); + System.err.println("NewtCanvasAWT.destroy(removeNotify "+removeNotify+", windowClosing "+windowClosing+"): nw "+newtWinHandleToHexString(newtChild)+", from "+cont); } - // Detach OLS early.. - final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(newtChild, true); - if(null != ols && ols.isSurfaceLayerAttached()) { - ols.detachSurfaceLayer(); - } - detachNewtChild(cont); // will destroy context (offscreen -> onscreen) and implicit detachSurfaceLayer (if still attached) - newtChild.destroy(); - newtChild=null; + detachNewtChild(cont); + + if( !removeNotify ) { + final Window cWin = newtChild; + final Window dWin = cWin.getDelegatedWindow(); + newtChild=null; + if( windowClosing && dWin instanceof WindowImpl ) { + ((WindowImpl)dWin).windowDestroyNotify(true); + } else { + cWin.destroy(); + } + } } + if( ( removeNotify || windowClosing ) && null!=jawtWindow) { + NewtFactoryAWT.destroyNativeWindow(jawtWindow); + jawtWindow=null; + } } @Override @@ -501,8 +510,6 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto return false; } - awtWindowClosingProtocol.addClosingListenerOneShot(); - if( attachNewtChild && !newtChildAttached && null != newtChild ) { attachNewtChild(cont); } @@ -535,11 +542,11 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto throw new InternalError("XXX"); } isOnscreen = jawtWindow.getGraphicsConfiguration().getChosenCapabilities().isOnscreen(); - awtAdapter = new AWTParentWindowAdapter(jawtWindow, newtChild).addTo(this); + awtAdapter = (AWTParentWindowAdapter) new AWTParentWindowAdapter(jawtWindow, newtChild).addTo(this); + awtAdapter.removeWindowClosingFrom(this); // we utilize AWTWindowClosingProtocol triggered destruction! newtChild.addWindowListener(clearAWTMenusOnNewtFocus); newtChild.setFocusAction(focusAction); // enable AWT focus traversal newtChildCloseOp = newtChild.setDefaultCloseOperation(WindowClosingMode.DO_NOTHING_ON_CLOSE); - awtWindowClosingProtocol.addClosingListenerOneShot(); keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); keyboardFocusManager.addPropertyChangeListener("focusOwner", focusPropertyChangeListener); if(isOnscreen) { @@ -554,7 +561,6 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto newtChild.removeWindowListener(clearAWTMenusOnNewtFocus); newtChild.setFocusAction(null); newtChild.setDefaultCloseOperation(newtChildCloseOp); - awtWindowClosingProtocol.removeClosingListener(); } } } @@ -611,7 +617,14 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto newtChild.setFocusAction(null); // no AWT focus traversal .. configureNewtChild(false); newtChild.setVisible(false); - newtChild.reparentWindow(null); + + // Detach OLS early.. + final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(newtChild, true); + if(null != ols && ols.isSurfaceLayerAttached()) { + ols.detachSurfaceLayer(); + } + newtChild.reparentWindow(null); // will destroy context (offscreen -> onscreen) and implicit detachSurfaceLayer (if still attached) + if(DEBUG) { System.err.println("NewtCanvasAWT.detachNewtChild.X: win "+newtWinHandleToHexString(newtChild)+", EDTUtil: cur "+newtChild.getScreen().getDisplay().getEDTUtil()+", comp "+this); } diff --git a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java index 07004503e..c3ad51c96 100755 --- a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java +++ b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java @@ -300,9 +300,7 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener { glWindow.reparentWindow(awtParent); } else { glWindow.reparentWindow(null); - if(glClosable) { - glWindow.setDefaultCloseOperation(WindowClosingMode.DISPOSE_ON_CLOSE); - } + glWindow.setDefaultCloseOperation( glClosable ? WindowClosingMode.DISPOSE_ON_CLOSE : WindowClosingMode.DO_NOTHING_ON_CLOSE ); } } } diff --git a/src/newt/classes/com/jogamp/newt/event/InputEvent.java b/src/newt/classes/com/jogamp/newt/event/InputEvent.java index 9ef4de2b6..4920b59ea 100644 --- a/src/newt/classes/com/jogamp/newt/event/InputEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/InputEvent.java @@ -81,11 +81,6 @@ public abstract class InputEvent extends NEWTEvent return 0; } - /** Object when attached via {@link #setAttachment(Object)} marks the event consumed, - * ie. stops propagating the event any further to the event listener. - */ - public static final Object consumedTag = new Object(); - protected InputEvent(short eventType, Object source, long when, int modifiers) { super(eventType, source, when); this.modifiers=modifiers; diff --git a/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java b/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java index b8de6eb18..6f4561ce6 100644 --- a/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java @@ -48,6 +48,12 @@ package com.jogamp.newt.event; */ @SuppressWarnings("serial") public class NEWTEvent extends java.util.EventObject { + /** + * Object when attached via {@link #setAttachment(Object)} marks the event consumed, + * ie. stops propagating the event any further to the other event listener. + */ + public static final Object consumedTag = new Object(); + private final short eventType; private final long when; private Object attachment; diff --git a/src/newt/classes/com/jogamp/newt/event/WindowListener.java b/src/newt/classes/com/jogamp/newt/event/WindowListener.java index 011e1f654..dde182510 100644 --- a/src/newt/classes/com/jogamp/newt/event/WindowListener.java +++ b/src/newt/classes/com/jogamp/newt/event/WindowListener.java @@ -36,6 +36,7 @@ package com.jogamp.newt.event; import javax.media.nativewindow.WindowClosingProtocol; +/** NEWT {@link WindowEvent} listener. */ public interface WindowListener extends NEWTEventListener { /** Window is resized, your application shall respect the new window dimension. A repaint is recommended. */ public void windowResized(WindowEvent e); @@ -53,7 +54,9 @@ public interface WindowListener extends NEWTEventListener { **/ public void windowDestroyNotify(WindowEvent e); - /** Window has been destroyed.*/ + /** + * Window has been destroyed. + */ public void windowDestroyed(WindowEvent e); /** Window gained focus. */ diff --git a/src/newt/classes/com/jogamp/newt/event/awt/AWTAdapter.java b/src/newt/classes/com/jogamp/newt/event/awt/AWTAdapter.java index 8991203d5..6de2eee45 100644 --- a/src/newt/classes/com/jogamp/newt/event/awt/AWTAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/awt/AWTAdapter.java @@ -181,8 +181,13 @@ public abstract class AWTAdapter implements java.util.EventListener /** @see #addTo(java.awt.Component) */ public abstract AWTAdapter removeFrom(java.awt.Component awtComponent); + /** + * Enqueues the event to the {@link #getNewtWindow()} is not null. + */ void enqueueEvent(boolean wait, com.jogamp.newt.event.NEWTEvent event) { - newtWindow.enqueueEvent(wait, event); + if( null != newtWindow ) { + newtWindow.enqueueEvent(wait, event); + } } } diff --git a/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java b/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java index 2d63ca455..e91bb2f82 100644 --- a/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java @@ -66,13 +66,18 @@ public class AWTWindowAdapter return this; } - public AWTAdapter removeFrom(java.awt.Component awtComponent) { - awtComponent.removeFocusListener(this); - awtComponent.removeComponentListener(this); + public AWTAdapter removeWindowClosingFrom(java.awt.Component awtComponent) { java.awt.Window win = getWindow(awtComponent); if( null != win && null != windowClosingListener ) { win.removeWindowListener(windowClosingListener); } + return this; + } + + public AWTAdapter removeFrom(java.awt.Component awtComponent) { + awtComponent.removeFocusListener(this); + awtComponent.removeComponentListener(this); + removeWindowClosingFrom(awtComponent); if(awtComponent instanceof java.awt.Window) { ((java.awt.Window)awtComponent).removeWindowListener(this); } @@ -220,9 +225,16 @@ public class AWTWindowAdapter enqueueEvent(true, event); } } + public void windowClosed(java.awt.event.WindowEvent e) { + com.jogamp.newt.event.WindowEvent event = AWTNewtEventFactory.createWindowEvent(e, newtWindow); + if(null!=newtListener) { + ((com.jogamp.newt.event.WindowListener)newtListener).windowDestroyed(event); + } else { + enqueueEvent(true, event); + } + } public void windowActivated(java.awt.event.WindowEvent e) { } - public void windowClosed(java.awt.event.WindowEvent e) { } public void windowDeactivated(java.awt.event.WindowEvent e) { } public void windowDeiconified(java.awt.event.WindowEvent e) { } public void windowIconified(java.awt.event.WindowEvent e) { } diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index 7fccb6622..ce50d95dd 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -100,7 +100,10 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind protected GLWindow(Window window) { super(null, null, false /* always handle device lifecycle ourselves */); this.window = (WindowImpl) window; - this.window.setHandleDestroyNotify(false); + this.window.setWindowDestroyNotifyAction( new Runnable() { + public void run() { + defaultWindowDestroyNotifyOp(); + } } ); window.addWindowListener(new WindowAdapter() { @Override public void windowRepaint(WindowUpdateEvent e) { @@ -112,10 +115,6 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind defaultWindowResizedOp(getWidth(), getHeight()); } - @Override - public void windowDestroyNotify(WindowEvent e) { - defaultWindowDestroyNotifyOp(); - } }); this.window.setLifecycleHook(new GLLifecycleHook()); } @@ -389,6 +388,11 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind window.destroy(); } + @Override + public void setWindowDestroyNotifyAction(Runnable r) { + window.setWindowDestroyNotifyAction(r); + } + @Override public final void setVisible(boolean visible) { window.setVisible(visible); diff --git a/src/newt/classes/jogamp/newt/DisplayImpl.java b/src/newt/classes/jogamp/newt/DisplayImpl.java index 20b915cae..d4842ba2f 100644 --- a/src/newt/classes/jogamp/newt/DisplayImpl.java +++ b/src/newt/classes/jogamp/newt/DisplayImpl.java @@ -370,15 +370,8 @@ public abstract class DisplayImpl extends Display { DisplayImpl.this.dispatchMessages(); } }; - final void dispatchMessage(final NEWTEventTask eventTask) { - final NEWTEvent event = eventTask.get(); + final void dispatchMessage(final NEWTEvent event) { try { - if(null == event) { - // Ooops ? - System.err.println("Warning: event of eventTask is NULL"); - Thread.dumpStack(); - return; - } final Object source = event.getSource(); if(source instanceof NEWTEventConsumer) { final NEWTEventConsumer consumer = (NEWTEventConsumer) source ; @@ -396,6 +389,21 @@ public abstract class DisplayImpl extends Display { } else { re = new RuntimeException(t); } + throw re; + } + } + + final void dispatchMessage(final NEWTEventTask eventTask) { + final NEWTEvent event = eventTask.get(); + try { + if(null == event) { + // Ooops ? + System.err.println("Warning: event of eventTask is NULL"); + Thread.dumpStack(); + return; + } + dispatchMessage(event); + } catch (RuntimeException re) { if( eventTask.isCallerWaiting() ) { // propagate exception to caller eventTask.setException(re); @@ -451,7 +459,7 @@ public abstract class DisplayImpl extends Display { // can't wait if we are on EDT or NEDT -> consume right away if(wait && edtUtil.isCurrentThreadEDTorNEDT() ) { - dispatchMessage(new NEWTEventTask(e, null)); + dispatchMessage(e); return; } diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index 222a1173c..66ca3e07d 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -110,7 +110,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer private boolean pointerConfined = false; private LifecycleHook lifecycleHook = null; - private boolean handleDestroyNotify = true; + private Runnable windowDestroyNotifyAction = null; private FocusRunnable focusAction = null; private KeyListener keyboardFocusHandler = null; @@ -864,8 +864,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer _lock.lock(); try { if(DEBUG_IMPLEMENTATION) { - System.err.println("Window DestroyAction() "+getThreadName()); + System.err.println("Window DestroyAction() hasScreen "+(null != screen)+", isNativeValid "+isNativeValid()+" - "+getThreadName()); } + + // send synced destroy-notify notification + sendWindowEvent(WindowEvent.EVENT_WINDOW_DESTROY_NOTIFY); + // Childs first .. synchronized(childWindowsLock) { if(childWindows.size()>0) { @@ -875,8 +879,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer while( clonedChildWindows.size() > 0 ) { NativeWindow nw = clonedChildWindows.remove(0); if(nw instanceof WindowImpl) { - ((WindowImpl)nw).sendWindowEvent(WindowEvent.EVENT_WINDOW_DESTROY_NOTIFY); - ((WindowImpl)nw).destroy(); + ((WindowImpl)nw).windowDestroyNotify(true); } else { nw.destroy(); } @@ -1549,14 +1552,10 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public Object getWrappedWindow() { return null; } - - /** - * If set to true, the default value, this NEWT Window implementation will - * handle the destruction (ie {@link #destroy()} call) within {@link #windowDestroyNotify(boolean)} implementation.
        - * If set to false, it's up to the caller/owner to handle destruction within {@link #windowDestroyNotify(boolean)}. - */ - public void setHandleDestroyNotify(boolean b) { - handleDestroyNotify = b; + + @Override + public void setWindowDestroyNotifyAction(Runnable r) { + windowDestroyNotifyAction = r; } /** @@ -2211,7 +2210,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer default: throw new NativeWindowException("Unexpected mouse event type " + e.getEventType()); } - consumed = InputEvent.consumedTag == e.getAttachment(); + consumed = NEWTEvent.consumedTag == e.getAttachment(); } } @@ -2340,7 +2339,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer default: throw new NativeWindowException("Unexpected key event type " + e.getEventType()); } - return InputEvent.consumedTag == e.getAttachment(); + return NEWTEvent.consumedTag == e.getAttachment(); } @SuppressWarnings("deprecation") @@ -2446,7 +2445,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if(DEBUG_IMPLEMENTATION) { System.err.println("consumeWindowEvent: "+e+", visible "+isVisible()+" "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()); } - for(int i = 0; i < windowListeners.size(); i++ ) { + boolean consumed = false; + for(int i = 0; !consumed && i < windowListeners.size(); i++ ) { WindowListener l = windowListeners.get(i); switch(e.getEventType()) { case WindowEvent.EVENT_WINDOW_RESIZED: @@ -2475,6 +2475,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer new NativeWindowException("Unexpected window event type " + e.getEventType()); } + consumed = NEWTEvent.consumedTag == e.getAttachment(); } } @@ -2615,32 +2616,45 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } /** - * Triggered by implementation's WM events or programmatically + * Triggered by implementation's WM events or programmatic while respecting {@link #getDefaultCloseOperation()}. * * @param force if true, overrides {@link #setDefaultCloseOperation(WindowClosingMode)} with {@link WindowClosingProtocol#DISPOSE_ON_CLOSE} * and hence force destruction. Otherwise is follows the user settings. * @return true if this window is no more valid and hence has been destroyed, otherwise false. */ - protected boolean windowDestroyNotify(boolean force) { + public boolean windowDestroyNotify(boolean force) { + final WindowClosingMode defMode = getDefaultCloseOperation(); + final WindowClosingMode mode = force ? WindowClosingMode.DISPOSE_ON_CLOSE : defMode; if(DEBUG_IMPLEMENTATION) { - System.err.println("Window.windowDestroyNotify(force: "+force+") START "+getThreadName()+": "+this); - } - if(force) { - setDefaultCloseOperation(WindowClosingMode.DISPOSE_ON_CLOSE); + System.err.println("Window.windowDestroyNotify(force: "+force+", mode "+defMode+" -> "+mode+") "+getThreadName()+": "+this); } - - // send synced destroy notifications - enqueueWindowEvent(true, WindowEvent.EVENT_WINDOW_DESTROY_NOTIFY); - - if(handleDestroyNotify && WindowClosingMode.DISPOSE_ON_CLOSE == getDefaultCloseOperation()) { - destroy(); + + if( WindowClosingMode.DISPOSE_ON_CLOSE == mode ) { + if(force) { + setDefaultCloseOperation(mode); + } + try { + if( null == windowDestroyNotifyAction ) { + destroy(); + } else { + windowDestroyNotifyAction.run(); + } + } finally { + if(force) { + setDefaultCloseOperation(defMode); + } + } + } else { + // send synced destroy notifications + sendWindowEvent(WindowEvent.EVENT_WINDOW_DESTROY_NOTIFY); } final boolean destroyed = !isNativeValid(); if(DEBUG_IMPLEMENTATION) { - System.err.println("Window.windowDestroyNotify(force: "+force+") END "+getThreadName()+": destroyed "+destroyed+", "+this); - } + System.err.println("Window.windowDestroyNotify(force: "+force+", mode "+mode+") END "+getThreadName()+": destroyed "+destroyed+", "+this); + } + return destroyed; } diff --git a/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java b/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java index 701d9d60a..b348220d6 100644 --- a/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java +++ b/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java @@ -42,9 +42,7 @@ import com.jogamp.newt.event.awt.AWTWindowAdapter; * Specialized parent/client adapter, * where the NEWT child window really gets resized, * and the parent move window event gets discarded. */ -public class AWTParentWindowAdapter - extends AWTWindowAdapter - implements java.awt.event.HierarchyListener +public class AWTParentWindowAdapter extends AWTWindowAdapter implements java.awt.event.HierarchyListener { NativeWindow downstreamParent; diff --git a/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java index bee43a95e..0172309fb 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java @@ -256,10 +256,7 @@ public class WindowDriver extends WindowImpl { } @Override public void windowDestroyed(WindowEvent e) { - if(isNativeValid()) { - WindowDriver.this.windowDestroyNotify(true); - } - + // Not fwd by AWTWindowAdapter, synthesized by NEWT } @Override public void windowGainedFocus(WindowEvent e) { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateNEWT.java new file mode 100644 index 000000000..2729d6a5d --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableDelegateNEWT.java @@ -0,0 +1,160 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore; + +import java.io.IOException; + +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLContext; +import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLDrawableFactory; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLProfile; + +import org.junit.Assert; +import org.junit.Test; + +import com.jogamp.newt.NewtFactory; +import com.jogamp.newt.Window; +import com.jogamp.newt.event.WindowAdapter; +import com.jogamp.newt.event.WindowEvent; +import com.jogamp.newt.event.WindowUpdateEvent; +import com.jogamp.opengl.GLAutoDrawableDelegate; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.MiscUtils; +import com.jogamp.opengl.test.junit.util.QuitAdapter; +import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.util.Animator; + +/** + * Test using a NEWT {@link Window} for onscreen case. + *

        + * Creates a {@link GLDrawable} using the + * {@link GLDrawableFactory#createGLDrawable(javax.media.nativewindow.NativeSurface) factory model}. + * The {@link GLContext} is derived {@link GLDrawable#createContext(GLContext) from the drawable}. + *

        + *

        + * Finally a {@link GLAutoDrawableDelegate} is created with the just created {@link GLDrawable} and {@link GLContext}. + * It is being used to run the {@link GLEventListener}. + *

        + */ +public class TestGLAutoDrawableDelegateNEWT extends UITestCase { + static long duration = 500; // ms + + void doTest(GLCapabilitiesImmutable reqGLCaps, GLEventListener demo) throws InterruptedException { + final GLDrawableFactory factory = GLDrawableFactory.getFactory(reqGLCaps.getGLProfile()); + + // + // Create native windowing resources .. X11/Win/OSX + // + final Window window = NewtFactory.createWindow(reqGLCaps); + Assert.assertNotNull(window); + window.setSize(640, 400); + window.setVisible(true); + Assert.assertTrue(AWTRobotUtil.waitForVisible(window, true)); + Assert.assertTrue(AWTRobotUtil.waitForRealized(window, true)); + System.out.println("Window: "+window.getClass().getName()); + + final GLDrawable drawable = factory.createGLDrawable(window); + Assert.assertNotNull(drawable); + drawable.setRealized(true); + + final GLAutoDrawableDelegate glad = new GLAutoDrawableDelegate(drawable, drawable.createContext(null), window, false, null) { + @Override + protected void destroyImplInLock() { + super.destroyImplInLock(); // destroys drawable/context + window.destroy(); // destroys the actual window, incl. the device + } + }; + + window.setWindowDestroyNotifyAction( new Runnable() { + public void run() { + glad.windowDestroyNotifyOp(); + } } ); + + window.addWindowListener(new WindowAdapter() { + @Override + public void windowRepaint(WindowUpdateEvent e) { + glad.windowRepaintOp(); + } + + @Override + public void windowResized(WindowEvent e) { + glad.windowResizedOp(window.getWidth(), window.getHeight()); + } + }); + + glad.addGLEventListener(demo); + + QuitAdapter quitAdapter = new QuitAdapter(); + //glWindow.addKeyListener(new TraceKeyAdapter(quitAdapter)); + //glWindow.addWindowListener(new TraceWindowAdapter(quitAdapter)); + window.addKeyListener(quitAdapter); + window.addWindowListener(quitAdapter); + + Animator animator = new Animator(); + animator.setUpdateFPSFrames(60, System.err); + animator.setModeBits(false, Animator.MODE_EXPECT_AWT_RENDERING_THREAD); + animator.add(glad); + animator.start(); + Assert.assertTrue(animator.isStarted()); + Assert.assertTrue(animator.isAnimating()); + + while(!quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration() dispose @@ -90,10 +93,12 @@ public class TestWindowClosingProtocol01AWT extends UITestCase { Thread.sleep(300); - Assert.assertEquals(true, AWTRobotUtil.closeWindow(frame, false)); // no frame close, but GLCanvas's GL resources will be destroyed + Assert.assertEquals(true, AWTRobotUtil.closeWindow(frame, false, closingListener)); // no frame close, but GLCanvas's GL resources will be destroyed Thread.sleep(100); Assert.assertEquals(true, frame.isDisplayable()); Assert.assertEquals(true, frame.isVisible()); + Assert.assertEquals(true, closingListener.isWindowClosing()); + Assert.assertEquals(false, closingListener.isWindowClosed()); for (int wait=0; wait dispose @@ -84,9 +84,9 @@ public class TestWindowClosingProtocol02NEWT extends UITestCase { op = glWindow.getDefaultCloseOperation(); Assert.assertEquals(WindowClosingMode.DISPOSE_ON_CLOSE, op); - Assert.assertEquals(true, AWTRobotUtil.closeWindow(glWindow, true)); + Assert.assertEquals(true, AWTRobotUtil.closeWindow(glWindow, true, closingListener)); Assert.assertEquals(false, glWindow.isNativeValid()); - Assert.assertEquals(true, windowClosingListener.isWindowClosing()); + Assert.assertEquals(true, closingListener.isWindowClosing()); } public static void main(String[] args) { diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol03NewtAWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol03NewtAWT.java index be3c48fb6..b0a222a5a 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol03NewtAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol03NewtAWT.java @@ -46,17 +46,19 @@ import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; import com.jogamp.opengl.test.junit.util.AWTRobotUtil; import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil.WindowClosingListener; public class TestWindowClosingProtocol03NewtAWT extends UITestCase { @Test public void testCloseJFrameNewtCanvasAWT() throws InterruptedException, InvocationTargetException { final JFrame frame = new JFrame("testCloseJFrameNewtCanvasAWT"); - + final WindowClosingListener awtClosingListener = AWTRobotUtil.addClosingListener(frame); + GLProfile glp = GLProfile.getGL2ES2(); GLCapabilities caps = new GLCapabilities(glp); final GLWindow glWindow = GLWindow.create(caps); - final AWTRobotUtil.WindowClosingListener windowClosingListener = AWTRobotUtil.addClosingListener(glWindow); + final AWTRobotUtil.WindowClosingListener newtClosingListener = AWTRobotUtil.addClosingListener(glWindow); glWindow.addGLEventListener(new GearsES2()); @@ -81,20 +83,26 @@ public class TestWindowClosingProtocol03NewtAWT extends UITestCase { // // close with op: DO_NOTHING_ON_CLOSE -> NOP / HIDE (default) // - Assert.assertEquals(JFrame.HIDE_ON_CLOSE, frame.getDefaultCloseOperation()); - WindowClosingMode op = newtCanvas.getDefaultCloseOperation(); - Assert.assertEquals(WindowClosingMode.DO_NOTHING_ON_CLOSE, op); + { + Assert.assertEquals(JFrame.HIDE_ON_CLOSE, frame.getDefaultCloseOperation()); + WindowClosingMode op = newtCanvas.getDefaultCloseOperation(); + Assert.assertEquals(WindowClosingMode.DO_NOTHING_ON_CLOSE, op); + } Thread.sleep(300); - Assert.assertEquals(true, AWTRobotUtil.closeWindow(frame, false)); + Assert.assertEquals(true, AWTRobotUtil.closeWindow(frame, false, awtClosingListener)); Assert.assertEquals(true, frame.isDisplayable()); Assert.assertEquals(false, frame.isVisible()); Assert.assertEquals(true, newtCanvas.isValid()); Assert.assertEquals(true, newtCanvas.isDisplayable()); Assert.assertEquals(true, glWindow.isNativeValid()); - Assert.assertEquals(true, windowClosingListener.isWindowClosing()); - windowClosingListener.reset(); + Assert.assertEquals(true, awtClosingListener.isWindowClosing()); + Assert.assertEquals(false, awtClosingListener.isWindowClosed()); + Assert.assertEquals(true, newtClosingListener.isWindowClosing()); + Assert.assertEquals(false, newtClosingListener.isWindowClosed()); + awtClosingListener.reset(); + newtClosingListener.reset(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { @@ -107,20 +115,25 @@ public class TestWindowClosingProtocol03NewtAWT extends UITestCase { // // close with op (JFrame): DISPOSE_ON_CLOSE -- newtCanvas -- glWindow --> dispose // - frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - Assert.assertEquals(JFrame.DISPOSE_ON_CLOSE, frame.getDefaultCloseOperation()); - op = newtCanvas.getDefaultCloseOperation(); - Assert.assertEquals(WindowClosingMode.DISPOSE_ON_CLOSE, op); + { + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + Assert.assertEquals(JFrame.DISPOSE_ON_CLOSE, frame.getDefaultCloseOperation()); + WindowClosingMode op = newtCanvas.getDefaultCloseOperation(); + Assert.assertEquals(WindowClosingMode.DISPOSE_ON_CLOSE, op); + } Thread.sleep(300); - Assert.assertEquals(true, AWTRobotUtil.closeWindow(frame, true)); + Assert.assertEquals(true, AWTRobotUtil.closeWindow(frame, true, awtClosingListener)); Assert.assertEquals(false, frame.isDisplayable()); Assert.assertEquals(false, frame.isVisible()); Assert.assertEquals(false, newtCanvas.isValid()); Assert.assertEquals(false, newtCanvas.isDisplayable()); Assert.assertEquals(false, glWindow.isNativeValid()); - Assert.assertEquals(true, windowClosingListener.isWindowClosing()); + Assert.assertEquals(true, awtClosingListener.isWindowClosing()); + Assert.assertEquals(true, awtClosingListener.isWindowClosed()); + Assert.assertEquals(true, newtClosingListener.isWindowClosing()); + Assert.assertEquals(true, newtClosingListener.isWindowClosed()); } public static void main(String[] args) { diff --git a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java index ffc42e318..8b46760e1 100644 --- a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java +++ b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java @@ -28,6 +28,7 @@ package com.jogamp.opengl.test.junit.util; +import jogamp.common.awt.AWTEDTExecutor; import jogamp.newt.WindowImplAccess; import java.lang.reflect.InvocationTargetException; @@ -41,6 +42,8 @@ import javax.media.opengl.awt.GLCanvas; import org.junit.Assert; +import com.jogamp.newt.event.WindowEvent; + public class AWTRobotUtil { static final boolean DEBUG = false; @@ -646,16 +649,19 @@ public class AWTRobotUtil { * * @param obj either an AWT Window (Frame, JFrame) or NEWT Window * @param willClose indicating that the window will close, hence this method waits for the window to be closed + * @param wcl the WindowClosingListener to determine whether the AWT or NEWT widget has been closed. It should be attached + * to the widget ASAP before any other listener, e.g. via {@link #addClosingListener(Object)}. + * The WindowClosingListener will be reset before attempting to close the widget. * @return True if the Window is closing and closed (if willClose is true), each within TIME_OUT * @throws InterruptedException */ - public static boolean closeWindow(Object obj, boolean willClose) throws InterruptedException, InvocationTargetException { - WindowClosingListener closingListener = addClosingListener(obj); + public static boolean closeWindow(Object obj, boolean willClose, WindowClosingListener closingListener) throws InterruptedException { + closingListener.reset(); if(obj instanceof java.awt.Window) { final java.awt.Window win = (java.awt.Window) obj; java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit(); final java.awt.EventQueue evtQ = tk.getSystemEventQueue(); - java.awt.EventQueue.invokeAndWait(new Runnable() { + AWTEDTExecutor.singleton.invoke(true, new Runnable() { public void run() { evtQ.postEvent(new java.awt.event.WindowEvent(win, java.awt.event.WindowEvent.WINDOW_CLOSING)); } }); @@ -675,12 +681,15 @@ public class AWTRobotUtil { return wait Date: Thu, 28 Feb 2013 18:38:45 +0100 Subject: Fix AWT EDT Deadlock in AWTWindowClosingProtocol, regression of commit 808a9a27a8c1c9e0a6701a8dd81d51f8daa8129d --- .../com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java index e3f85b948..e499ff705 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java @@ -36,7 +36,6 @@ import java.awt.event.WindowListener; import javax.media.nativewindow.WindowClosingProtocol; -import jogamp.common.awt.AWTEDTExecutor; import jogamp.nativewindow.awt.AWTMisc; public class AWTWindowClosingProtocol implements WindowClosingProtocol { @@ -92,10 +91,7 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { } final Window w = AWTMisc.getWindow(comp); if(null!=w) { - AWTEDTExecutor.singleton.invoke(true, new Runnable() { - public void run() { - w.addWindowListener(windowClosingAdapter); - } } ); + w.addWindowListener(windowClosingAdapter); closingListenerSet = true; return true; } @@ -108,10 +104,7 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { if(closingListenerSet) { final Window w = AWTMisc.getWindow(comp); if(null!=w) { - AWTEDTExecutor.singleton.invoke(true, new Runnable() { - public void run() { - w.removeWindowListener(windowClosingAdapter); - } } ); + w.removeWindowListener(windowClosingAdapter); closingListenerSet = false; return true; } -- cgit v1.2.3 From 74019520e8d82d03f5cf95729456717b34060f5d Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 13 Mar 2013 07:15:41 +0100 Subject: Minor Changes: EGLDisplayUtil: Add stack trace in DEBUG mode for opened DPYs; JAWTWindow: Add JAWT info in toString() --- src/jogl/classes/javax/media/opengl/GLContext.java | 4 +- .../classes/jogamp/opengl/egl/EGLDisplayUtil.java | 76 +++++++++++++++++----- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 33 ++++++---- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 2 +- 4 files changed, 85 insertions(+), 30 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/GLContext.java b/src/jogl/classes/javax/media/opengl/GLContext.java index c31b76401..05200324d 100644 --- a/src/jogl/classes/javax/media/opengl/GLContext.java +++ b/src/jogl/classes/javax/media/opengl/GLContext.java @@ -477,12 +477,12 @@ public abstract class GLContext { public abstract GL setGL(GL gl); /** - * Returns the native GL context handle + * Returns the underlying native OpenGL context handle */ public final long getHandle() { return contextHandle; } /** - * Indicates whether the underlying OpenGL context has been created. + * Indicates whether the underlying native OpenGL context has been created. */ public final boolean isCreated() { return 0 != contextHandle; diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java index 1f6f49f88..f2efb0479 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java @@ -38,7 +38,7 @@ import javax.media.opengl.GLException; import jogamp.opengl.Debug; -import com.jogamp.common.util.LongIntHashMap; +import com.jogamp.common.util.LongObjectHashMap; import com.jogamp.nativewindow.egl.EGLGraphicsDevice; /** @@ -54,11 +54,26 @@ import com.jogamp.nativewindow.egl.EGLGraphicsDevice; public class EGLDisplayUtil { protected static final boolean DEBUG = Debug.debug("EGLDisplayUtil"); - static LongIntHashMap eglDisplayCounter; + private static class DpyCounter { + final long eglDisplay; + final Throwable createdStack; + int refCount; + + private DpyCounter(long eglDisplay) { + this.eglDisplay = eglDisplay; + this.refCount = 0; + this.createdStack = DEBUG ? new Throwable() : null; + } + + public String toString() { + return "EGLDisplay[0x"+Long.toHexString(eglDisplay)+": refCnt "+refCount+"]"; + } + } + static final LongObjectHashMap eglDisplayCounter; static { - eglDisplayCounter = new LongIntHashMap(); - eglDisplayCounter.setKeyNotFoundValue(0); + eglDisplayCounter = new LongObjectHashMap(); + eglDisplayCounter.setKeyNotFoundValue(null); } /** @@ -80,9 +95,13 @@ public class EGLDisplayUtil { public static void dumpOpenDisplayConnections() { System.err.println("EGLDisplayUtil: Open EGL Display Connections: "+eglDisplayCounter.size()); int i=0; - for(Iterator iter = eglDisplayCounter.iterator(); iter.hasNext(); i++) { - final LongIntHashMap.Entry e = iter.next(); - System.err.println("EGLDisplayUtil: Open["+i+"]: 0x"+Long.toHexString(e.key)+": refCnt "+e.value); + for(Iterator iter = eglDisplayCounter.iterator(); iter.hasNext(); i++) { + final LongObjectHashMap.Entry e = iter.next(); + final DpyCounter v = (DpyCounter) e.value; + System.err.println("EGLDisplayUtil: Open["+i+"]: 0x"+Long.toHexString(e.key)+": "+v); + if(null != v.createdStack) { + v.createdStack.printStackTrace(); + } } } @@ -108,18 +127,32 @@ public class EGLDisplayUtil { if( EGL.EGL_NO_DISPLAY == eglDisplay) { return false; } - final boolean res; - final int refCnt = eglDisplayCounter.get(eglDisplay) + 1; // 0 + 1 = 1 -> 1st init + final int refCnt; + final DpyCounter d; + { + DpyCounter _d = (DpyCounter) eglDisplayCounter.get(eglDisplay); + if(null == _d) { + _d = new DpyCounter(eglDisplay); + refCnt = 1; // 1st init + } else { + refCnt = _d.refCount + 1; + } + d = _d; + } + final boolean res; if(1==refCnt) { // only initialize once res = EGL.eglInitialize(eglDisplay, major, minor); } else { res = true; - } - if(res) { // map if successfully initialized, only - eglDisplayCounter.put(eglDisplay, refCnt); + } + if(res) { // update refCount and map if successfully initialized, only + d.refCount = refCnt; + if(1 == refCnt) { + eglDisplayCounter.put(eglDisplay, d); + } } if(DEBUG) { - System.err.println("EGLDisplayUtil.eglInitialize2("+EGLContext.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res); + System.err.println("EGLDisplayUtil.eglInitialize("+EGLContext.toHexString(eglDisplay)+" ...): #"+refCnt+", "+d+" = "+res); // Thread.dumpStack(); } return res; @@ -186,13 +219,24 @@ public class EGLDisplayUtil { return false; } final boolean res; - final int refCnt = eglDisplayCounter.get(eglDisplay) - 1; // 1 - 1 = 0 -> final terminate - if(0==refCnt) { // no terminate if still in use or already terminated + final int refCnt; + final DpyCounter d; + { + DpyCounter _d = (DpyCounter) eglDisplayCounter.get(eglDisplay); + if(null == _d) { + _d = null; + refCnt = -1; // n/a + } else { + refCnt = _d.refCount - 1; // 1 - 1 = 0 -> final terminate + } + d = _d; + } + if( 0 == refCnt ) { // no terminate if still in use or already terminated res = EGL.eglTerminate(eglDisplay); eglDisplayCounter.remove(eglDisplay); } else { if(0 < refCnt) { // no negative refCount - eglDisplayCounter.put(eglDisplay, refCnt); + d.refCount = refCnt; } res = true; } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index d65f8c231..99b629d1a 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -315,13 +315,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected abstract int lockSurfaceImpl() throws NativeWindowException; protected void dumpJAWTInfo() { - if(null != jawt) { - System.err.println("JAWT version: 0x"+Integer.toHexString(jawt.getCachedVersion())+ - ", CA_LAYER: "+ JAWTUtil.isJAWTUsingOffscreenLayer(jawt)+ - ", isLayeredSurface "+isOffscreenLayerSurfaceEnabled()+", bounds "+bounds+", insets "+insets); - } else { - System.err.println("JAWT n/a, bounds "+bounds+", insets "+insets); - } + System.err.println(jawt2String(null).toString()); // Thread.dumpStack(); } @@ -555,15 +549,32 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return component.hasFocus(); } + protected StringBuilder jawt2String(StringBuilder sb) { + if( null == sb ) { + sb = new StringBuilder(); + } + if(null != jawt) { + sb.append("JAWT version: 0x").append(Integer.toHexString(jawt.getCachedVersion())). + append(", CA_LAYER: ").append(JAWTUtil.isJAWTUsingOffscreenLayer(jawt)). + append(", isLayeredSurface ").append(isOffscreenLayerSurfaceEnabled()).append(", bounds ").append(bounds).append(", insets ").append(insets); + } else { + sb.append("JAWT n/a, bounds ").append(bounds).append(", insets ").append(insets); + } + return sb; + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("JAWT-Window["+ - "windowHandle "+toHexString(getWindowHandle())+ + sb.append("JAWT-Window["); + jawt2String(sb); + sb.append( ", shallUseOffscreenLayer "+shallUseOffscreenLayer+", isOffscreenLayerSurface "+isOffscreenLayerSurface+ + ", attachedSurfaceLayer "+toHexString(getAttachedSurfaceLayer())+ + ", windowHandle "+toHexString(getWindowHandle())+ ", surfaceHandle "+toHexString(getSurfaceHandle())+ - ", bounds "+bounds+", insets "+insets+ - ", shallUseOffscreenLayer "+shallUseOffscreenLayer+", isOffscreenLayerSurface "+isOffscreenLayerSurface); + ", bounds "+bounds+", insets "+insets + ); if(null!=component) { sb.append(", pos "+getX()+"/"+getY()+", size "+getWidth()+"x"+getHeight()+ ", visible "+component.isVisible()); diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 3c10859bf..9d5a878c6 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -416,7 +416,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } } } - if( ( removeNotify || windowClosing ) && null!=jawtWindow) { + if( ( removeNotify || windowClosing ) && null!=jawtWindow ) { NewtFactoryAWT.destroyNativeWindow(jawtWindow); jawtWindow=null; } -- cgit v1.2.3 From 896e8b021b39e9415040a57a1d540d7d24b02db1 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 14 Mar 2013 10:48:44 +0100 Subject: OSX/CALayer: Revise CALayer 'RunOnMainThread' utilization, avoiding deadlocks RunOnMainThread(waitUntilDone:=true,..) can deadlock the main-thread if called from AWT-EDT, since the main-thread may call back to AWT-EDT while injecting a new main-thread task. This patch revises all RunOnMainThread CALayer usage, resulting in only one required left: - OSXUtil.AddCASublayer() w/ waitUntilDone:=false Hence the CALayer code has no more potential to deadlock main-thread/AWT-EDT. OSXUtil.AddCASublayer() must be performed on main-thread, otherwise the CALayer attachment will fail - no visible rendering result. +++ Note: A good trigger to test this deadlock is to magnify/zoom the OSX desktop (click background + ctrl-mouse_wheel) before running some unit tests. TestGLCanvasAWTActionDeadlock01AWT and TestAddRemove02GLWindowNewtCanvasAWT also have the potential to trigger the mentioned deadlock. --- make/config/jogl/cgl-macosx-CustomJavaCode.java | 23 ++++-------- .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 30 +++++++--------- .../macosx/MacOSXWindowSystemInterface-calayer.m | 36 ++++++++----------- .../media/nativewindow/OffscreenLayerSurface.java | 4 --- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 38 +++++++++++--------- .../jogamp/nativewindow/macosx/OSXUtil.java | 37 +++++++------------ src/nativewindow/native/macosx/OSXmisc.m | 16 ++++----- .../junit/jogl/demos/es2/awt/TestGearsES2AWT.java | 41 ++++++++++++++-------- 8 files changed, 102 insertions(+), 123 deletions(-) (limited to 'src/nativewindow') diff --git a/make/config/jogl/cgl-macosx-CustomJavaCode.java b/make/config/jogl/cgl-macosx-CustomJavaCode.java index d32e0ae8f..ab1d44b64 100644 --- a/make/config/jogl/cgl-macosx-CustomJavaCode.java +++ b/make/config/jogl/cgl-macosx-CustomJavaCode.java @@ -1,9 +1,9 @@ /** - * Creates the NSOpenGLLayer for FBO/PBuffer w/ optional GL3 shader program on Main-Thread + * Creates the NSOpenGLLayer for FBO/PBuffer w/ optional GL3 shader program *

        - * It is mandatory that the shared context handle ctx - * is not locked while calling this method. + * The NSOpenGLLayer will immediatly create a OpenGL context sharing the given ctx, + * which will be used to render the texture offthread. *

        *

        * The NSOpenGLLayer starts in enabled mode, @@ -12,10 +12,7 @@ */ public static long createNSOpenGLLayer(final long ctx, final int gl3ShaderProgramName, final long fmt, final long p, final int texID, final boolean opaque, final int texWidth, final int texHeight) { - return OSXUtil.RunOnMainThread(true, new Function() { - public Long eval(Object... args) { - return Long.valueOf( createNSOpenGLLayerImpl(ctx, gl3ShaderProgramName, fmt, p, texID, opaque, texWidth, texHeight) ); - } } ).longValue(); + return createNSOpenGLLayerImpl(ctx, gl3ShaderProgramName, fmt, p, texID, opaque, texWidth, texHeight); } /** @@ -26,19 +23,13 @@ public static long createNSOpenGLLayer(final long ctx, final int gl3ShaderProgra *

        */ public static void setNSOpenGLLayerEnabled(final long nsOpenGLLayer, final boolean enable) { - OSXUtil.RunOnMainThread(true, new Runnable() { - public void run() { - setNSOpenGLLayerEnabledImpl(nsOpenGLLayer, enable); - } } ); + setNSOpenGLLayerEnabledImpl(nsOpenGLLayer, enable); } /** - * Releases the NSOpenGLLayer on Main-Thread + * Releases the NSOpenGLLayer */ public static void releaseNSOpenGLLayer(final long nsOpenGLLayer) { - OSXUtil.RunOnMainThread(true, new Runnable() { - public void run() { - releaseNSOpenGLLayerImpl(nsOpenGLLayer); - } } ); + releaseNSOpenGLLayerImpl(nsOpenGLLayer); } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index a03850043..9e6085030 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -676,30 +676,24 @@ public abstract class MacOSXCGLContext extends GLContextImpl } /** - * Perform NSOpenGLLayer creation and attaching on main-thread, - * hence release the lock on our context - which will be used to - * create a shared context within NSOpenGLLayer. + * NSOpenGLLayer creation is performed on the current thread, + * which immediately creates it's own GL ctx sharing this ctx + * not causing any locking issues. + * + * Subsequent attaching is performed on main-thread w/o blocking. + * + * This is a lock free operation. */ final long cglCtx = CGL.getCGLContext(ctx); if(0 == cglCtx) { throw new InternalError("Null CGLContext for: "+this); } - final boolean ctxUnlocked = CGL.kCGLNoError == CGL.CGLUnlockContext(cglCtx); - try { - nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, gl3ShaderProgramName, pixelFormat, pbufferHandle, texID, chosenCaps.isBackgroundOpaque(), lastWidth, lastHeight); - if (DEBUG) { - System.err.println("NS create nsOpenGLLayer "+toHexString(nsOpenGLLayer)+" w/ pbuffer "+toHexString(pbufferHandle)+", texID "+texID+", texSize "+lastWidth+"x"+lastHeight+", "+drawable); - } - backingLayerHost.attachSurfaceLayer(nsOpenGLLayer); - setSwapInterval(1); // enabled per default in layered surface - } finally { - if( ctxUnlocked ) { - if( CGL.kCGLNoError != CGL.CGLLockContext(cglCtx) ) { - throw new InternalError("Could not re-lock CGLContext for: "+this); - } - } + nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, gl3ShaderProgramName, pixelFormat, pbufferHandle, texID, chosenCaps.isBackgroundOpaque(), lastWidth, lastHeight); + if (DEBUG) { + System.err.println("NS create nsOpenGLLayer "+toHexString(nsOpenGLLayer)+" w/ pbuffer "+toHexString(pbufferHandle)+", texID "+texID+", texSize "+lastWidth+"x"+lastHeight+", "+drawable); } - backingLayerHost.layoutSurfaceLayer(); + backingLayerHost.attachSurfaceLayer(nsOpenGLLayer); + setSwapInterval(1); // enabled per default in layered surface } else { lastWidth = drawable.getWidth(); lastHeight = drawable.getHeight(); diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index abc9d7958..f93f15241 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -131,11 +131,10 @@ extern GLboolean glIsVertexArray (GLuint array); { @private GLfloat gl_texCoords[8]; - NSOpenGLContext* myCtx; + NSOpenGLContext* glContext; Bool isGLEnabled; @protected - NSOpenGLContext* parentCtx; GLuint gl3ShaderProgramName; GLuint vboBufVert; GLuint vboBufTexCoord; @@ -247,7 +246,7 @@ static const GLfloat gl_verts[] = { @implementation MyNSOpenGLLayer -- (id) setupWithContext: (NSOpenGLContext*) _parentCtx +- (id) setupWithContext: (NSOpenGLContext*) parentCtx gl3ShaderProgramName: (GLuint) _gl3ShaderProgramName pixelFormat: (NSOpenGLPixelFormat*) _parentPixelFmt pbuffer: (NSOpenGLPixelBuffer*) p @@ -262,20 +261,19 @@ static const GLfloat gl_verts[] = { pthread_mutex_init(&renderLock, &renderLockAttr); // recursive pthread_cond_init(&renderSignal, NULL); // no attribute - myCtx = NULL; { int i; for(i=0; i<8; i++) { gl_texCoords[i] = 0.0f; } } - parentCtx = _parentCtx; + parentPixelFmt = [_parentPixelFmt retain]; // until destruction + glContext = [[MyNSOpenGLContext alloc] initWithFormat:parentPixelFmt shareContext:parentCtx]; gl3ShaderProgramName = _gl3ShaderProgramName; vboBufVert = 0; vboBufTexCoord = 0; vertAttrLoc = 0; texCoordAttrLoc = 0; - parentPixelFmt = [_parentPixelFmt retain]; // until destruction swapInterval = 1; // defaults to on (as w/ new GL profiles) swapIntervalCounter = 0; timespec_now(&lastWaitTime); @@ -338,12 +336,12 @@ static const GLfloat gl_verts[] = { #ifdef VERBOSE_ON CGRect lRect = [self bounds]; if(NULL != pbuffer) { - DBG_PRINT("MyNSOpenGLLayer::init (pbuffer) %p, ctx %p, pfmt %p, pbuffer %p, opaque %d, pbuffer %dx%d -> tex %dx%d, bounds: %lf/%lf %lfx%lf, displayLink %p (refcnt %d)\n", - self, parentCtx, parentPixelFmt, pbuffer, opaque, [pbuffer pixelsWide], [pbuffer pixelsHigh], texWidth, texHeight, + DBG_PRINT("MyNSOpenGLLayer::init (pbuffer) %p, pctx %p, pfmt %p, pbuffer %p, ctx %p, opaque %d, pbuffer %dx%d -> tex %dx%d, bounds: %lf/%lf %lfx%lf, displayLink %p (refcnt %d)\n", + self, parentCtx, parentPixelFmt, pbuffer, glContext, opaque, [pbuffer pixelsWide], [pbuffer pixelsHigh], texWidth, texHeight, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, displayLink, (int)[self retainCount]); } else { - DBG_PRINT("MyNSOpenGLLayer::init (texture) %p, ctx %p, pfmt %p, opaque %d, tex[id %d, %dx%d], bounds: %lf/%lf %lfx%lf, displayLink %p (refcnt %d)\n", - self, parentCtx, parentPixelFmt, opaque, (int)textureID, texWidth, texHeight, + DBG_PRINT("MyNSOpenGLLayer::init (texture) %p, pctx %p, pfmt %p, ctx %p, opaque %d, tex[id %d, %dx%d], bounds: %lf/%lf %lfx%lf, displayLink %p (refcnt %d)\n", + self, parentCtx, parentPixelFmt, glContext, opaque, (int)textureID, texWidth, texHeight, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, displayLink, (int)[self retainCount]); } #endif @@ -493,11 +491,10 @@ static const GLfloat gl_verts[] = { pthread_mutex_lock(&renderLock); [self deallocPBuffer]; // [[self openGLContext] release]; - if( NULL != myCtx ) { - [myCtx release]; - myCtx = NULL; + if( NULL != glContext ) { + [glContext release]; + glContext = NULL; } - parentCtx = NULL; if( NULL != parentPixelFmt ) { [parentPixelFmt release]; parentPixelFmt = NULL; @@ -632,22 +629,19 @@ static const GLfloat gl_verts[] = { - (NSOpenGLContext *)openGLContextForPixelFormat:(NSOpenGLPixelFormat *)pixelFormat { - DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.0: %p (refcnt %d) - pfmt %p, parent %p, DisplayLink %p\n", - self, (int)[self retainCount], pixelFormat, parentCtx, displayLink); - // NSLog(@"MyNSOpenGLLayer::openGLContextForPixelFormat: %@",[NSThread callStackSymbols]); - myCtx = [[MyNSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:parentCtx]; + DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.0: %p (refcnt %d) - pfmt %p, ctx %p, DisplayLink %p\n", + self, (int)[self retainCount], pixelFormat, glContext, displayLink); #ifndef HAS_CADisplayLink if(NULL != displayLink) { CVReturn cvres; DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.1: setup DisplayLink %p\n", displayLink); - cvres = CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, [myCtx CGLContextObj], [pixelFormat CGLPixelFormatObj]); + cvres = CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, [glContext CGLContextObj], [pixelFormat CGLPixelFormatObj]); if(kCVReturnSuccess != cvres) { DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext failed: %d\n", self, cvres); } } #endif - DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.X: new-ctx %p\n", myCtx); - return myCtx; + return glContext; } - (BOOL)canDrawInOpenGLContext:(NSOpenGLContext *)context pixelFormat:(NSOpenGLPixelFormat *)pixelFormat diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index 4885d5a4c..df3f04f7f 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -36,10 +36,6 @@ public interface OffscreenLayerSurface { *

        * Implementation may realize all required resources at this point. *

        - *

        - * It is mandatory that any related resources, e.g. a shared context, - * are not locked while calling this method. - *

        * * @see #isOffscreenLayerSurfaceEnabled() * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 3ec54ca78..c8f758165 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -51,7 +51,6 @@ import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.MutableSurface; import javax.media.nativewindow.util.Point; -import com.jogamp.common.util.Function; import com.jogamp.nativewindow.awt.JAWTWindow; import jogamp.nativewindow.jawt.JAWT; @@ -90,8 +89,11 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { JAWT_DrawingSurfaceInfo dsi = null; try { dsi = ds.GetDrawingSurfaceInfo(); - if(! UnsetJAWTRootSurfaceLayer(dsi.getBuffer(), rootSurfaceLayerHandle)) { + try { + UnsetJAWTRootSurfaceLayer(dsi.getBuffer(), rootSurfaceLayerHandle); + } catch (Exception e) { System.err.println("Error clearing JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayerHandle)); + e.printStackTrace(); } } finally { if ( null != dsi ) { @@ -245,8 +247,12 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { rootSurfaceLayerHandle = OSXUtil.CreateCALayer(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); if(0 == rootSurfaceLayerHandle) { errMsg = "Could not create root CALayer"; - } else if(!SetJAWTRootSurfaceLayer(dsi.getBuffer(), rootSurfaceLayerHandle)) { - errMsg = "Could not set JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayerHandle); + } else { + try { + SetJAWTRootSurfaceLayer(dsi.getBuffer(), rootSurfaceLayerHandle); + } catch(Exception e) { + errMsg = "Could not set JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayerHandle)+", cause: "+e.getMessage(); + } } } } @@ -307,22 +313,22 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } protected Point getLocationOnScreenNativeImpl(final int x0, final int y0) { return null; } - private static boolean SetJAWTRootSurfaceLayer(final Buffer jawtDrawingSurfaceInfoBuffer, final long caLayer) { - return OSXUtil.RunOnMainThread(true, new Function() { - public Boolean eval(Object... args) { - return Boolean.valueOf( SetJAWTRootSurfaceLayer0(jawtDrawingSurfaceInfoBuffer, caLayer) ); - } } ).booleanValue(); + /** + * Set the given root CALayer in the JAWT surface + */ + private static void SetJAWTRootSurfaceLayer(final Buffer jawtDrawingSurfaceInfoBuffer, final long caLayer) { + SetJAWTRootSurfaceLayer0(jawtDrawingSurfaceInfoBuffer, caLayer); } - private static boolean UnsetJAWTRootSurfaceLayer(final Buffer jawtDrawingSurfaceInfoBuffer, final long caLayer) { - return OSXUtil.RunOnMainThread(true, new Function() { - public Boolean eval(Object... args) { - return Boolean.valueOf( UnsetJAWTRootSurfaceLayer0(jawtDrawingSurfaceInfoBuffer, caLayer) ); - } } ).booleanValue(); + /** + * Unset the given root CALayer in the JAWT surface + */ + private static void UnsetJAWTRootSurfaceLayer(final Buffer jawtDrawingSurfaceInfoBuffer, final long caLayer) { + UnsetJAWTRootSurfaceLayer0(jawtDrawingSurfaceInfoBuffer, caLayer); } - private static native boolean SetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); - private static native boolean UnsetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); + private static native void SetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); + private static native void UnsetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); // Variables for lockSurface/unlockSurface private JAWT_DrawingSurface ds; diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index aa44e2d64..59b42c249 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -137,26 +137,23 @@ public class OSXUtil implements ToolkitProperties { } /** - * Create a CALayer suitable to act as a root CALayer on the main-thread. + * Create a CALayer suitable to act as a root CALayer. * @see #DestroyCALayer(long) * @see #AddCASublayer(long, long) */ public static long CreateCALayer(final int x, final int y, final int width, final int height) { - return OSXUtil.RunOnMainThread(true, new Function() { - public Long eval(Object... args) { - return Long.valueOf( CreateCALayer0(x, y, width, height) ); - } } ).longValue(); + return CreateCALayer0(x, y, width, height); } /** - * Attach a sub CALayer to the root CALayer on the main-thread w/ blocking. + * Attach a sub CALayer to the root CALayer on the main-thread w/o blocking. *

        * Method will trigger a display * call to the CALayer hierarchy to enforce resource creation if required, e.g. an NSOpenGLContext. *

        *

        - * It is mandatory that any related resources, e.g. a shared NSOpenGLContext, - * are not locked while calling this method. + * Hence it is important that related resources are not locked if + * they will be used for creation. *

        * @see #CreateCALayer(int, int, int, int) * @see #RemoveCASublayer(long, long) @@ -165,7 +162,7 @@ public class OSXUtil implements ToolkitProperties { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } - RunOnMainThread(true, new Runnable() { + RunOnMainThread(false, new Runnable() { public void run() { AddCASublayer0(rootCALayer, subCALayer); } @@ -173,7 +170,7 @@ public class OSXUtil implements ToolkitProperties { } /** - * Fix root and sub CALayer position to 0/0 and size on the main-thread w/o blocking. + * Fix root and sub CALayer position to 0/0 and size *

        * If the sub CALayer implements the Objective-C NativeWindow protocol NWDedicatedSize (e.g. JOGL's MyNSOpenGLLayer), * the dedicated size is passed to the layer, which propagates it appropriately. @@ -192,38 +189,28 @@ public class OSXUtil implements ToolkitProperties { if( 0==rootCALayer && 0==subCALayer ) { return; } - RunOnMainThread(false, new Runnable() { - public void run() { - FixCALayerLayout0(rootCALayer, subCALayer, width, height); - } - }); + FixCALayerLayout0(rootCALayer, subCALayer, width, height); } /** - * Detach a sub CALayer from the root CALayer on the main-thread w/ blocking. + * Detach a sub CALayer from the root CALayer */ public static void RemoveCASublayer(final long rootCALayer, final long subCALayer) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } - RunOnMainThread(true, new Runnable() { - public void run() { - RemoveCASublayer0(rootCALayer, subCALayer); - } } ); + RemoveCASublayer0(rootCALayer, subCALayer); } /** - * Destroy a CALayer on the main-thread w/ blocking. + * Destroy a CALayer * @see #CreateCALayer(int, int, int, int) */ public static void DestroyCALayer(final long caLayer) { if(0==caLayer) { throw new IllegalArgumentException("caLayer 0x"+Long.toHexString(caLayer)); } - RunOnMainThread(true, new Runnable() { - public void run() { - DestroyCALayer0(caLayer); - } } ); + DestroyCALayer0(caLayer); } /** diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index c74d6cc58..14a9781f7 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -584,16 +584,16 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyCALayer0 /* * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow * Method: SetJAWTRootSurfaceLayer0 - * Signature: (JJ)Z + * Signature: (JJ)V */ -JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_SetJAWTRootSurfaceLayer0 +JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_SetJAWTRootSurfaceLayer0 (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); if (NULL == dsi) { NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); - return JNI_FALSE; + return; } MyCALayer* layer = (MyCALayer*) (intptr_t) caLayer; id surfaceLayers = (id )dsi->platformInfo; @@ -601,35 +601,33 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow surfaceLayers.layer = [layer retain]; // Pairs w/ Unset [pool release]; DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.X: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); - return JNI_TRUE; } /* * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow * Method: UnsetJAWTRootSurfaceLayer0 - * Signature: (JJ)Z + * Signature: (JJ)V */ -JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_UnsetJAWTRootSurfaceLayer0 +JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_UnsetJAWTRootSurfaceLayer0 (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); if (NULL == dsi) { NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); - return JNI_FALSE; + return; } MyCALayer* layer = (MyCALayer*) (intptr_t) caLayer; id surfaceLayers = (id )dsi->platformInfo; if(layer != surfaceLayers.layer) { NativewindowCommon_throwNewRuntimeException(env, "Attached layer %p doesn't match given layer %p\n", surfaceLayers.layer, layer); - return JNI_FALSE; + return; } DBG_PRINT("CALayer::UnsetJAWTRootSurfaceLayer.0: root %p (refcnt %d) -> nil\n", layer, (int)[layer retainCount]); [layer release]; // Pairs w/ Set surfaceLayers.layer = NULL; [pool release]; DBG_PRINT("CALayer::UnsetJAWTRootSurfaceLayer.X: root %p (refcnt %d) -> nil\n", layer, (int)[layer retainCount]); - return JNI_TRUE; } @interface MainRunnable : NSObject diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java index d59b81ff1..64151362b 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java @@ -77,6 +77,7 @@ public class TestGearsES2AWT extends UITestCase { static boolean shutdownSystemExit = false; static int swapInterval = 1; static boolean exclusiveContext = false; + static boolean useAnimator = true; static Thread awtEDT; static Dimension rwsize = null; @@ -167,8 +168,8 @@ public class TestGearsES2AWT extends UITestCase { glCanvas.addGLEventListener(new GearsES2(swapInterval)); - Animator animator = new Animator(glCanvas); - if( exclusiveContext ) { + final Animator animator = useAnimator ? new Animator(glCanvas) : null; + if( useAnimator && exclusiveContext ) { animator.setExclusiveContext(awtEDT); } QuitAdapter quitAdapter = new QuitAdapter(); @@ -184,11 +185,13 @@ public class TestGearsES2AWT extends UITestCase { Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame, true)); Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glCanvas, true)); - animator.start(); - Assert.assertTrue(animator.isStarted()); - Assert.assertTrue(animator.isAnimating()); - Assert.assertEquals(exclusiveContext ? awtEDT : null, glCanvas.getExclusiveContextThread()); - animator.setUpdateFPSFrames(60, System.err); + if( useAnimator ) { + animator.start(); + Assert.assertTrue(animator.isStarted()); + Assert.assertTrue(animator.isAnimating()); + Assert.assertEquals(exclusiveContext ? awtEDT : null, glCanvas.getExclusiveContextThread()); + animator.setUpdateFPSFrames(60, System.err); + } System.err.println("canvas pos/siz: "+glCanvas.getX()+"/"+glCanvas.getY()+" "+glCanvas.getWidth()+"x"+glCanvas.getHeight()); @@ -198,19 +201,25 @@ public class TestGearsES2AWT extends UITestCase { System.err.println("window resize pos/siz: "+glCanvas.getX()+"/"+glCanvas.getY()+" "+glCanvas.getWidth()+"x"+glCanvas.getHeight()); } - while(!quitAdapter.shouldQuit() /* && animator.isAnimating() */ && animator.getTotalFPSDuration() Date: Thu, 14 Mar 2013 11:26:10 +0100 Subject: OSX/CALayer: Simplify FixCALayerLayout()/layoutSurfaceLayer() call, no more need for explicit call - OffscreenLayerSurface.layoutSurfaceLayer() removed, no more required - JAWTWindow adds a ComponentListener, which issues FixCALayerLayout() at resized, moved and shown. - MyNSOpenGLLayer no more requires fix*Size() methods - MyNSOpenGLLayer::setDedicatedSize() need no explicit CATransaction, performed by caller. --- .../classes/javax/media/opengl/awt/GLCanvas.java | 8 ++- .../macosx/MacOSXWindowSystemInterface-calayer.m | 63 +--------------------- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 46 +++++++++++++--- .../media/nativewindow/OffscreenLayerSurface.java | 15 ------ .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 2 +- .../jogamp/nativewindow/macosx/OSXUtil.java | 3 +- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 3 -- 7 files changed, 46 insertions(+), 94 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 63c18db5d..278e2dc37 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -434,8 +434,9 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing _lock.lock(); try { final GLDrawable _drawable = drawable; - if( null == _drawable || realized && ( 0 >= _drawable.getWidth() || 0 >= _drawable.getHeight() ) ) { - return; + if( null == _drawable || realized == _drawable.isRealized() || + realized && ( 0 >= _drawable.getWidth() || 0 >= _drawable.getHeight() ) ) { + return; } _drawable.setRealized(realized); if( realized && _drawable.isRealized() ) { @@ -705,9 +706,6 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } } sendReshape = true; // async if display() doesn't get called below, but avoiding deadlock - if(null != jawtWindow && jawtWindow.isOffscreenLayerSurfaceEnabled() ) { - jawtWindow.layoutSurfaceLayer(); - } } } } diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index f93f15241..125ca8af8 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -192,8 +192,6 @@ extern GLboolean glIsVertexArray (GLuint array); - (void) applyNewPBuffer; - (void)setDedicatedSize:(CGSize)size; // @NWDedicatedSize -- (CGRect)fixMyFrame; -- (CGRect)fixSuperPosition; - (id)actionForKey:(NSString *)key ; - (NSOpenGLPixelFormat *)openGLPixelFormatForDisplayMask:(uint32_t)mask; - (NSOpenGLContext *)openGLContextForPixelFormat:(NSOpenGLPixelFormat *)pixelFormat; @@ -364,14 +362,6 @@ static const GLfloat gl_verts[] = { if(_texHeight != texHeight || _texWidth != texWidth) { texWidth = _texWidth; texHeight = _texHeight; - /** - CGRect lRect = [self bounds]; - lRect.origin.x = 0; - lRect.origin.y = 0; - lRect.size.width = texWidth; - lRect.size.height = texHeight; - [self setFrame: lRect]; */ - CGRect lRect = [self fixMyFrame]; GLfloat texCoordWidth, texCoordHeight; if(NULL != pbuffer) { @@ -394,13 +384,13 @@ static const GLfloat gl_verts[] = { gl_texCoords[4] = texCoordWidth; gl_texCoords[6] = texCoordWidth; #ifdef VERBOSE_ON + CGRect lRect = [self bounds]; DBG_PRINT("MyNSOpenGLLayer::validateTexSize %p -> tex %dx%d, bounds: %lf/%lf %lfx%lf\n", self, texWidth, texHeight, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); #endif return YES; } else { - [self fixMyFrame]; return NO; } } @@ -549,16 +539,11 @@ static const GLfloat gl_verts[] = { DBG_PRINT("MyNSOpenGLLayer::setDedicatedSize: %p, texSize %dx%d <- %lfx%lf\n", self, texWidth, texHeight, size.width, size.height); - [CATransaction begin]; - [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; - dedicatedWidth = size.width; dedicatedHeight = size.height; CGRect rect = CGRectMake(0, 0, dedicatedWidth, dedicatedHeight); [self setFrame: rect]; - - [CATransaction commit]; } - (void) setFrame:(CGRect) frame { @@ -566,52 +551,6 @@ static const GLfloat gl_verts[] = { [super setFrame: rect]; } -- (CGRect)fixMyFrame -{ - CGRect lRect = [self frame]; - - // With Java7 our root CALayer's frame gets off-limit -> force 0/0 origin! - if( lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=texWidth || lRect.size.height!=texHeight) { - DBG_PRINT("MyNSOpenGLLayer::fixMyFrame: %p, 0/0 texSize %dx%d -> Frame[%lf/%lf %lfx%lf]\n", - self, texWidth, texHeight, - lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); - - [CATransaction begin]; - [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; - - lRect.origin.x = 0; - lRect.origin.y = 0; - lRect.size.width=texWidth; - lRect.size.height=texHeight; - [self setFrame: lRect]; - - [CATransaction commit]; - } - return lRect; -} - -- (CGRect)fixSuperPosition -{ - CALayer * superL = [self superlayer]; - CGRect lRect = [superL frame]; - - // With Java7 our root CALayer's frame gets off-limit -> force 0/0 origin! - if( lRect.origin.x!=0 || lRect.origin.y!=0 ) { - DBG_PRINT("MyNSOpenGLLayer::fixSuperPosition: %p, 0/0 -> Super Frame[%lf/%lf %lfx%lf]\n", - self, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); - - [CATransaction begin]; - [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; - - lRect.origin.x = 0; - lRect.origin.y = 0; - [superL setPosition: lRect.origin]; - - [CATransaction commit]; - } - return lRect; -} - - (id)actionForKey:(NSString *)key { DBG_PRINT("MyNSOpenGLLayer::actionForKey.0 %p key %s -> NIL\n", self, [key UTF8String]); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 99b629d1a..3e5e629b6 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -43,6 +43,8 @@ import com.jogamp.nativewindow.MutableGraphicsConfiguration; import java.awt.Component; import java.awt.Container; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; import java.applet.Applet; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; @@ -110,6 +112,25 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, this.component = windowObject; this.isApplet = false; this.offscreenSurfaceLayer = 0; + this.component.addComponentListener(new ComponentListener() { + @Override + public void componentResized(ComponentEvent e) { + layoutSurfaceLayerIfEnabled(); + } + + @Override + public void componentMoved(ComponentEvent e) { + layoutSurfaceLayerIfEnabled(); + } + + @Override + public void componentShown(ComponentEvent e) { + layoutSurfaceLayerIfEnabled(); + } + + @Override + public void componentHidden(ComponentEvent e) { } + }); } protected synchronized void invalidate() { @@ -215,16 +236,27 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } protected abstract void attachSurfaceLayerImpl(final long layerHandle); - @Override - public void layoutSurfaceLayer() throws NativeWindowException { - if( !isOffscreenLayerSurfaceEnabled() ) { - throw new NativeWindowException("Not an offscreen layer surface"); - } - if( 0 != offscreenSurfaceLayer) { + /** + * Layout the offscreen layer according to the implementing class's constraints. + *

        + * This method allows triggering a re-layout of the offscreen surface + * in case the implementation requires it. + *

        + *

        + * Call this method if any parent or ancestor's layout has been changed, + * which could affects the layout of this surface. + *

        + * @see #isOffscreenLayerSurfaceEnabled() + * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false + */ + protected void layoutSurfaceLayerImpl() {} + + private final void layoutSurfaceLayerIfEnabled() throws NativeWindowException { + if( isOffscreenLayerSurfaceEnabled() && 0 != offscreenSurfaceLayer ) { layoutSurfaceLayerImpl(); } } - protected void layoutSurfaceLayerImpl() {} + @Override public final void detachSurfaceLayer() throws NativeWindowException { diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index df3f04f7f..8c02a68bb 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -42,21 +42,6 @@ public interface OffscreenLayerSurface { */ public void attachSurfaceLayer(final long layerHandle) throws NativeWindowException; - /** - * Layout the offscreen layer according to the implementing class's constraints. - *

        - * This method allows triggering a re-layout of the offscreen surface - * in case the implementation requires it. - *

        - *

        - * Call this method if any parent or ancestor's layout has been changed, - * which could affects the layout of this surface. - *

        - * @see #isOffscreenLayerSurfaceEnabled() - * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false - */ - public void layoutSurfaceLayer() throws NativeWindowException; - /** * Detaches a previously attached offscreen layer from this offscreen layer surface. * @see #attachSurfaceLayer(long) diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index c8f758165..758105713 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -117,7 +117,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } protected void attachSurfaceLayerImpl(final long layerHandle) { - OSXUtil.AddCASublayer(rootSurfaceLayerHandle, layerHandle); + OSXUtil.AddCASublayer(rootSurfaceLayerHandle, layerHandle, getWidth(), getHeight()); } protected void layoutSurfaceLayerImpl() { diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 59b42c249..1563a5a8b 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -158,13 +158,14 @@ public class OSXUtil implements ToolkitProperties { * @see #CreateCALayer(int, int, int, int) * @see #RemoveCASublayer(long, long) */ - public static void AddCASublayer(final long rootCALayer, final long subCALayer) { + public static void AddCASublayer(final long rootCALayer, final long subCALayer, final int width, final int height) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } RunOnMainThread(false, new Runnable() { public void run() { AddCASublayer0(rootCALayer, subCALayer); + FixCALayerLayout0(rootCALayer, subCALayer, width, height); } }); } diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 9d5a878c6..d902b0f09 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -445,9 +445,6 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } if( validateComponent(true, null) ) { // newtChild.setSize(width, height); - if(null != jawtWindow && jawtWindow.isOffscreenLayerSurfaceEnabled() ) { - jawtWindow.layoutSurfaceLayer(); - } } } } -- cgit v1.2.3 From 28c6472335b924080d638b33a28f8f4eedb459b1 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 15 Mar 2013 19:08:22 +0100 Subject: Remodel OSX/CALayer Threading (commit 896e8b021b39e9415040a57a1d540d7d24b02db1): Run on main-thread w/o blocking ; Misc Changes Commit 896e8b021b39e9415040a57a1d540d7d24b02db1 moved all native CALayer calls to the current thread to avoid deadlocks. Even though this seemed to be fine at least resource GC (release/dealloc calls) were issued very late in time, probably due to multithreading synchronization of JAWT and/or OSX API. Example: Our 'TestAddRemove01GLCanvasSwingAWT' test didn't freed CALayer resources incl. GL ctx when destroying the objects (AWT Frame, GLCanvas, ..), leading to resource starvation .. eventually. Remedy is a compromise of behavior before commit 896e8b021b39e9415040a57a1d540d7d24b02db1 and that commit, i.e. to run CALayer lifecycle methods on main-thread, but do not block! The careful part within MacOSXCGLContext.associateDrawable(..) performs the following block on main-thread: - lock the context - create NSOpenGLLayer (incl. it's own shared GL context and the DisplayLink) - attach NSOpenGLLayer to root CALayer - unlock the context Due to the GL ctx locking, this async offthread operation is safe within our course of operations. Details: - NSOpenGLContext - Context and CVDisplayLink creation at init - Call [ctx update] if texture/frame size changed - 'waitUntilRenderSignal' uses default TO value if given TO is 0 to avoid deadlocks +++ Misc Changes: - Fix object type detection: isMemberOfClass -> isKindOfClass - OSXUtil_isNSView0 OSXUtil_isNSWindow0, CGL_isNSOpenGLPixelBuffer - MacOSXCGLDrawable/MacOSXPbufferCGLDrawable: remove getNSViewHandle() method. MacOSXCGLContext uses common code to detect nature of the drawable handle. - MacOSXCGLContext/CALayer: Use safe screenVSyncTimeout values, never 0 to avoid deadlock! - JAWTWindow.invalidate: Call detachSurfaceLayer() if not done yet --- .../classes/javax/media/opengl/awt/GLCanvas.java | 1 + .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 127 +++++++++++++-------- .../opengl/macosx/cgl/MacOSXCGLDrawable.java | 4 - .../macosx/cgl/MacOSXPbufferCGLDrawable.java | 6 - .../macosx/MacOSXWindowSystemInterface-calayer.m | 85 +++++++------- .../native/macosx/MacOSXWindowSystemInterface.m | 83 ++++++++------ .../com/jogamp/nativewindow/awt/JAWTWindow.java | 7 ++ .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 60 +++++----- .../jogamp/nativewindow/macosx/OSXUtil.java | 25 ++-- src/nativewindow/native/macosx/OSXmisc.m | 114 +++++++++++------- .../acore/TestAddRemove01GLCanvasSwingAWT.java | 32 +++++- .../TestAddRemove02GLWindowNewtCanvasAWT.java | 20 +++- .../jogl/acore/TestAddRemove03GLWindowNEWT.java | 20 +++- ...TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java | 9 ++ .../jogl/demos/es2/newt/TestGearsES2NEWT.java | 14 +-- 15 files changed, 358 insertions(+), 249 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 278e2dc37..2fdf18404 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -946,6 +946,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing animatorPaused = false; } + // OLS will be detached by disposeGL's context destruction below if( null != context ) { if( context.isCreated() ) { // Catch dispose GLExceptions by GLEventListener, just 'print' them diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 9e6085030..f01e03a2f 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -462,9 +462,9 @@ public abstract class MacOSXCGLContext extends GLContextImpl // NSOpenGLContext-based implementation class NSOpenGLImpl implements GLBackendImpl { private long pixelFormat = 0; // lifecycle: [create - destroy] - private long nsOpenGLLayer = 0; // lifecycle: [associateDrawable_true - associateDrawable_false] - private float screenVSyncTimeout; // microSec - private int vsyncTimeout; // microSec - for nsOpenGLLayer mode + private volatile long nsOpenGLLayer = 0; // lifecycle: [associateDrawable_true - associateDrawable_false] + private float screenVSyncTimeout = 16666; // microSec - defaults to 1/60s + private volatile int vsyncTimeout = 16666 + 1000; // microSec - for nsOpenGLLayer mode - defaults to 1/60s + 1ms private int lastWidth=0, lastHeight=0; // allowing to detect size change private boolean needsSetContextPBuffer = false; private ShaderProgram gl3ShaderProgram = null; @@ -472,6 +472,8 @@ public abstract class MacOSXCGLContext extends GLContextImpl @Override public boolean isNSContext() { return true; } + + /** Only returns a valid NSView. If !NSView, return null and mark either pbuffer and FBO. */ private long getNSViewHandle(boolean[] isPBuffer, boolean[] isFBO) { final long nsViewHandle; if(drawable instanceof GLFBODrawableImpl) { @@ -479,27 +481,15 @@ public abstract class MacOSXCGLContext extends GLContextImpl isPBuffer[0] = false; isFBO[0] = true; if(DEBUG) { - System.err.println("NS create GLFBODrawableImpl drawable: isFBO "+isFBO+", isPBuffer "+isPBuffer+", "+drawable.getClass().getName()+",\n\t"+drawable); - } - } else if(drawable instanceof MacOSXCGLDrawable) { - // we allow null here! (special pbuffer case) - nsViewHandle = ((MacOSXCGLDrawable)MacOSXCGLContext.this.drawable).getNSViewHandle(); - isPBuffer[0] = CGL.isNSOpenGLPixelBuffer(drawable.getHandle()); - isFBO[0] = false; - if(DEBUG) { - System.err.println("NS create MacOSXCGLDrawable drawable handle isFBO "+isFBO+", isPBuffer "+isPBuffer+", "+drawable.getClass().getName()+",\n\t"+drawable); + System.err.println("NS viewHandle.1: GLFBODrawableImpl drawable: isFBO "+isFBO+", isPBuffer "+isPBuffer+", "+drawable.getClass().getName()+",\n\t"+drawable); } } else { - // we only allow a valid NSView here final long drawableHandle = drawable.getHandle(); final boolean isNSView = OSXUtil.isNSView(drawableHandle); final boolean isNSWindow = OSXUtil.isNSWindow(drawableHandle); isPBuffer[0] = CGL.isNSOpenGLPixelBuffer(drawableHandle); isFBO[0] = false; - if(DEBUG) { - System.err.println("NS create Anonymous drawable handle "+toHexString(drawableHandle)+": isNSView "+isNSView+", isNSWindow "+isNSWindow+", isFBO "+isFBO+", isPBuffer "+isPBuffer+", "+drawable.getClass().getName()+",\n\t"+drawable); - } if( isNSView ) { nsViewHandle = drawableHandle; } else if( isNSWindow ) { @@ -507,7 +497,10 @@ public abstract class MacOSXCGLContext extends GLContextImpl } else if( isPBuffer[0] ) { nsViewHandle = 0; } else { - throw new RuntimeException("Anonymous drawable instance's handle neither NSView, NSWindow nor PBuffer: "+toHexString(drawableHandle)+", "+drawable.getClass().getName()+",\n\t"+drawable); + throw new RuntimeException("Drawable's handle neither NSView, NSWindow nor PBuffer: drawableHandle "+toHexString(drawableHandle)+", isNSView "+isNSView+", isNSWindow "+isNSWindow+", isFBO "+isFBO[0]+", isPBuffer "+isPBuffer[0]+", "+drawable.getClass().getName()+",\n\t"+drawable); + } + if(DEBUG) { + System.err.println("NS viewHandle.2: drawableHandle "+toHexString(drawableHandle)+" -> nsViewHandle "+toHexString(nsViewHandle)+": isNSView "+isNSView+", isNSWindow "+isNSWindow+", isFBO "+isFBO[0]+", isPBuffer "+isPBuffer[0]+", "+drawable.getClass().getName()+",\n\t"+drawable); } } needsSetContextPBuffer = isPBuffer[0]; @@ -567,8 +560,10 @@ public abstract class MacOSXCGLContext extends GLContextImpl _fixedCaps.setOnscreen( !isFBO && !isPBuffer ); fixedCaps = GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(_fixedCaps, chosenCaps.isBackgroundOpaque()); } - int sRefreshRate = OSXUtil.GetScreenRefreshRate(drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getIndex()); - screenVSyncTimeout = 1000000f / sRefreshRate; + final int sRefreshRate = OSXUtil.GetScreenRefreshRate(drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getIndex()); + if( 0 < sRefreshRate ) { + screenVSyncTimeout = 1000000f / sRefreshRate; + } if(DEBUG) { System.err.println("NS create OSX>=lion "+isLionOrLater); System.err.println("NS create incompleteView: "+incompleteView); @@ -611,7 +606,6 @@ public abstract class MacOSXCGLContext extends GLContextImpl pixelFormat = 0; } return CGL.deleteContext(ctx, true); - } @Override @@ -622,10 +616,8 @@ public abstract class MacOSXCGLContext extends GLContextImpl System.err.println("MaxOSXCGLContext.NSOpenGLImpl.associateDrawable: "+bound+", ctx "+toHexString(contextHandle)+", hasBackingLayerHost "+(null!=backingLayerHost)); } - if( bound ) { - - if( null != backingLayerHost ) { - + if( bound ) { + if( null != backingLayerHost ) { if( 0 != nsOpenGLLayer ) { // FIXME: redundant throw new InternalError("Lifecycle: bound=true, hasBackingLayerHost=true, but 'nsOpenGLLayer' is already/still set local: "+nsOpenGLLayer+", "+this); } @@ -676,32 +668,59 @@ public abstract class MacOSXCGLContext extends GLContextImpl } /** - * NSOpenGLLayer creation is performed on the current thread, - * which immediately creates it's own GL ctx sharing this ctx - * not causing any locking issues. + * NSOpenGLLayer creation and it's attachment is performed on the main w/o blocking, + * due to OSX main-thread requirements. + * Note: It somewhat works from another thread, however, + * GC-dealloc of the 'released' resources would happen very late! * - * Subsequent attaching is performed on main-thread w/o blocking. + * NSOpenGLLayer initialization creates it's own GL ctx sharing + * this ctx, hence we have to lock this ctx in the main-thread. * - * This is a lock free operation. - */ - final long cglCtx = CGL.getCGLContext(ctx); - if(0 == cglCtx) { - throw new InternalError("Null CGLContext for: "+this); - } - nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, gl3ShaderProgramName, pixelFormat, pbufferHandle, texID, chosenCaps.isBackgroundOpaque(), lastWidth, lastHeight); - if (DEBUG) { - System.err.println("NS create nsOpenGLLayer "+toHexString(nsOpenGLLayer)+" w/ pbuffer "+toHexString(pbufferHandle)+", texID "+texID+", texSize "+lastWidth+"x"+lastHeight+", "+drawable); - } - backingLayerHost.attachSurfaceLayer(nsOpenGLLayer); - setSwapInterval(1); // enabled per default in layered surface - } else { + * Locking of this ctx while creation and attachment + * also gives us good means of synchronization, i.e. it will be + * performed after this thread ends it's associateDrawable() [makeCurrent(), setDrawable(..)] + * and before the next display cycle involving makeCurrent(). + */ + OSXUtil.RunOnMainThread(false, new Runnable() { + public void run() { + if (DEBUG) { + System.err.println("NS create nsOpenGLLayer.0 "+Thread.currentThread().getName()); + } + final long cglCtx = CGL.getCGLContext(ctx); + if(0 == cglCtx) { + throw new GLException("Null CGLContext for: "+MacOSXCGLContext.this); + } + if( CGL.kCGLNoError != CGL.CGLLockContext(cglCtx) ) { + throw new GLException("Could not lock CGLContext for: "+MacOSXCGLContext.this); + } + try { + nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, gl3ShaderProgramName, pixelFormat, pbufferHandle, texID, chosenCaps.isBackgroundOpaque(), lastWidth, lastHeight); + if (DEBUG) { + System.err.println("NS create nsOpenGLLayer.2 "+Thread.currentThread().getName()+": "+toHexString(nsOpenGLLayer)+" w/ pbuffer "+toHexString(pbufferHandle)+", texID "+texID+", texSize "+lastWidth+"x"+lastHeight+", "+drawable); + } + backingLayerHost.attachSurfaceLayer(nsOpenGLLayer); + setSwapInterval(1); // enabled per default in layered surface + } catch (Throwable t) { + throw new GLException("createNSOpenGLLayer failed for: "+MacOSXCGLContext.this, t); + } finally { + if(CGL.kCGLNoError != CGL.CGLUnlockContext(cglCtx)) { + throw new GLException("Could not unlock CGLContext for: "+MacOSXCGLContext.this); + } + } + if (DEBUG) { + System.err.println("NS create nsOpenGLLayer.X "+Thread.currentThread().getName()); + } + } + }); + CGL.setContextView(contextHandle, 0); // [ctx clearDrawable] + } else { // -> null == backingLayerHost lastWidth = drawable.getWidth(); lastHeight = drawable.getHeight(); boolean[] isPBuffer = { false }; boolean[] isFBO = { false }; - CGL.setContextView(contextHandle, getNSViewHandle(isPBuffer, isFBO)); + CGL.setContextView(contextHandle, getNSViewHandle(isPBuffer, isFBO)); // will call [ctx clearDrawable] if view == 0, otherwise [ctx setView: view] if valid } - } else { + } else { // -> !bound if( 0 != nsOpenGLLayer ) { if( null == backingLayerHost ) { // FIXME: redundant throw new InternalError("Lifecycle: bound=false, hasNSOpneGLLayer=true, but 'backingLayerHost' is null local: "+nsOpenGLLayer+", "+this); @@ -714,13 +733,20 @@ public abstract class MacOSXCGLContext extends GLContextImpl // still having a valid OLS attached to surface (parent OLS could have been removed) backingLayerHost.detachSurfaceLayer(); } - CGL.releaseNSOpenGLLayer(nsOpenGLLayer); + // All CALayer lifecycle calls are deferred on main-thread, so is this. + final long _nsOpenGLLayer = nsOpenGLLayer; + nsOpenGLLayer = 0; + OSXUtil.RunOnMainThread(false, new Runnable() { + public void run() { + CGL.releaseNSOpenGLLayer(_nsOpenGLLayer); + } + }); if( null != gl3ShaderProgram ) { gl3ShaderProgram.destroy(MacOSXCGLContext.this.gl.getGL3()); gl3ShaderProgram = null; } - nsOpenGLLayer = 0; } + CGL.setContextView(contextHandle, 0); // [ctx clearDrawable] } } @@ -808,8 +834,10 @@ public abstract class MacOSXCGLContext extends GLContextImpl public boolean setSwapInterval(int interval) { if(0 != nsOpenGLLayer) { CGL.setNSOpenGLLayerSwapInterval(nsOpenGLLayer, interval); - vsyncTimeout = interval * (int)screenVSyncTimeout + 1000; // +1ms - if(DEBUG) { System.err.println("NS setSwapInterval: "+vsyncTimeout+" micros"); } + if( 0 < interval ) { + vsyncTimeout = interval * (int)screenVSyncTimeout + 1000; // +1ms + } + if(DEBUG) { System.err.println("NS setSwapInterval: "+interval+" -> "+vsyncTimeout+" micros"); } } CGL.setSwapInterval(contextHandle, interval); return true; @@ -839,8 +867,9 @@ public abstract class MacOSXCGLContext extends GLContextImpl } if(valid) { if(0 == skipSync) { - // If v-sync is disabled, frames will be drawn as quickly as possible - // w/o delay but in sync w/ CALayer. Otherwise wait until next swap interval (v-sync). + // If v-sync is disabled, frames will be drawn as quickly as possible w/o delay, + // while still synchronizing w/ CALayer. + // If v-sync is enabled wait until next swap interval (v-sync). CGL.waitUntilNSOpenGLLayerIsReady(nsOpenGLLayer, vsyncTimeout); } else { skipSync--; diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java index 0f282d33f..1daa892ba 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java @@ -106,10 +106,6 @@ public abstract class MacOSXCGLDrawable extends GLDrawableImpl { protected void setRealizedImpl() { } - protected long getNSViewHandle() { - return GLBackendType.NSOPENGL == openGLMode ? getHandle() : 0; - } - @Override protected void associateContext(GLContext ctx, boolean bound) { // NOTE: we need to keep track of the created contexts in order to diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java index ddff43031..1e845d179 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java @@ -92,12 +92,6 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { return new MacOSXPbufferCGLContext(this, shareWith); } - @Override - protected long getNSViewHandle() { - // pbuffer handle is NSOpenGLPixelBuffer - return 0; - } - protected int getTextureTarget() { return pBufferTexTarget; } protected int getTextureWidth() { return pBufferTexWidth; } protected int getTextureHeight() { return pBufferTexHeight; } diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index 125ca8af8..96783c75d 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -117,6 +117,7 @@ extern GLboolean glIsVertexArray (GLuint array); CGLContextObj cglCtx = [self CGLContextObj]; DBG_PRINT("MyNSOpenGLContext::dealloc.0 %p (refcnt %d) - CGL-Ctx %p\n", self, (int)[self retainCount], cglCtx); + // NSLog(@"MyNSOpenGLContext::dealloc: %@",[NSThread callStackSymbols]); [self clearDrawable]; if( NULL != cglCtx ) { CGLDestroyContext( cglCtx ); @@ -143,8 +144,8 @@ extern GLboolean glIsVertexArray (GLuint array); NSOpenGLPixelFormat* parentPixelFmt; int texWidth; int texHeight; - int dedicatedWidth; - int dedicatedHeight; + volatile int dedicatedWidth; + volatile int dedicatedHeight; volatile NSOpenGLPixelBuffer* pbuffer; volatile GLuint textureID; volatile NSOpenGLPixelBuffer* newPBuffer; @@ -184,7 +185,6 @@ extern GLboolean glIsVertexArray (GLuint array); - (void) setGLEnabled: (Bool) enable; - (Bool) validateTexSizeWithDedicatedSize; -- (Bool) validateTexSize: (int) _texWidth texHeight: (int) _texHeight; - (void) setTextureID: (int) _texID; - (Bool) isSamePBuffer: (NSOpenGLPixelBuffer*) p; @@ -315,6 +315,14 @@ static const GLfloat gl_verts[] = { displayLink = NULL; } } + if(NULL != displayLink) { + CVReturn cvres; + DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.1: setup DisplayLink %p\n", displayLink); + cvres = CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, [glContext CGLContextObj], [parentPixelFmt CGLPixelFormatObj]); + if(kCVReturnSuccess != cvres) { + DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext failed: %d\n", self, cvres); + } + } if(NULL != displayLink) { cvres = CVDisplayLinkSetOutputCallback(displayLink, renderMyNSOpenGLLayer, self); if(kCVReturnSuccess != cvres) { @@ -354,14 +362,9 @@ static const GLfloat gl_verts[] = { - (Bool) validateTexSizeWithDedicatedSize { - return [self validateTexSize: dedicatedWidth texHeight: dedicatedHeight]; -} - -- (Bool) validateTexSize: (int) _texWidth texHeight: (int) _texHeight -{ - if(_texHeight != texHeight || _texWidth != texWidth) { - texWidth = _texWidth; - texHeight = _texHeight; + if( dedicatedHeight != texHeight || dedicatedWidth != texWidth ) { + texWidth = dedicatedWidth; + texHeight = dedicatedHeight; GLfloat texCoordWidth, texCoordHeight; if(NULL != pbuffer) { @@ -477,10 +480,10 @@ static const GLfloat gl_verts[] = { - (void)releaseLayer { DBG_PRINT("MyNSOpenGLLayer::releaseLayer.0: %p (refcnt %d)\n", self, (int)[self retainCount]); + [self setGLEnabled: NO]; [self disableAnimation]; pthread_mutex_lock(&renderLock); [self deallocPBuffer]; - // [[self openGLContext] release]; if( NULL != glContext ) { [glContext release]; glContext = NULL; @@ -570,16 +573,6 @@ static const GLfloat gl_verts[] = { { DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.0: %p (refcnt %d) - pfmt %p, ctx %p, DisplayLink %p\n", self, (int)[self retainCount], pixelFormat, glContext, displayLink); -#ifndef HAS_CADisplayLink - if(NULL != displayLink) { - CVReturn cvres; - DBG_PRINT("MyNSOpenGLLayer::openGLContextForPixelFormat.1: setup DisplayLink %p\n", displayLink); - cvres = CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, [glContext CGLContextObj], [pixelFormat CGLPixelFormatObj]); - if(kCVReturnSuccess != cvres) { - DBG_PRINT("MyNSOpenGLLayer::init %p, CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext failed: %d\n", self, cvres); - } - } -#endif return glContext; } @@ -607,6 +600,9 @@ static const GLfloat gl_verts[] = { GLenum textureTarget; Bool texSizeChanged = [self validateTexSizeWithDedicatedSize]; + if( texSizeChanged ) { + [context update]; + } if( NULL != pbuffer ) { if( texSizeChanged && 0 != textureID ) { @@ -812,29 +808,23 @@ static const GLfloat gl_verts[] = { struct timespec t0, t1, td, td2; timespec_now(&t0); #endif - if(0 < to_micros) { - struct timespec to_abs = lastWaitTime; - timespec_addmicros(&to_abs, to_micros); - #ifdef DBG_SYNC - timespec_subtract(&td, &to_abs, &t0); - fprintf(stderr, ", (%ld) / ", timespec_milliseconds(&td)); - #endif - wr = pthread_cond_timedwait(&renderSignal, &renderLock, &to_abs); - #ifdef DBG_SYNC - timespec_now(&t1); - timespec_subtract(&td, &t1, &t0); - timespec_subtract(&td2, &t1, &lastWaitTime); - fprintf(stderr, "(%ld) / (%ld) ms", timespec_milliseconds(&td), timespec_milliseconds(&td2)); - #endif - } else { - pthread_cond_wait (&renderSignal, &renderLock); - #ifdef DBG_SYNC - timespec_now(&t1); - timespec_subtract(&td, &t1, &t0); - timespec_subtract(&td2, &t1, &lastWaitTime); - fprintf(stderr, "(%ld) / (%ld) ms", timespec_milliseconds(&td), timespec_milliseconds(&td2)); - #endif + if( 0 >= to_micros ) { + to_micros = 16666 + 1000; // defaults to 1/60s + 1ms + NSLog(@"MyNSOpenGLContext::waitUntilRenderSignal: to_micros was zero, using defaults"); } + struct timespec to_abs = lastWaitTime; + timespec_addmicros(&to_abs, to_micros); + #ifdef DBG_SYNC + timespec_subtract(&td, &to_abs, &t0); + fprintf(stderr, ", (%ld) / ", timespec_milliseconds(&td)); + #endif + wr = pthread_cond_timedwait(&renderSignal, &renderLock, &to_abs); + #ifdef DBG_SYNC + timespec_now(&t1); + timespec_subtract(&td, &t1, &t0); + timespec_subtract(&td2, &t1, &lastWaitTime); + fprintf(stderr, "(%ld) / (%ld) ms", timespec_milliseconds(&td), timespec_milliseconds(&td2)); + #endif ready = YES; } } while (NO == ready && 0 == wr) ; @@ -923,9 +913,16 @@ void setNSOpenGLLayerNeedsDisplayPBuffer(NSOpenGLLayer* layer, NSOpenGLPixelBuff void releaseNSOpenGLLayer(NSOpenGLLayer* layer) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer; + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + DBG_PRINT("MyNSOpenGLLayer::releaseNSOpenGLLayer.0: %p\n", l); [l releaseLayer]; DBG_PRINT("MyNSOpenGLLayer::releaseNSOpenGLLayer.X: %p\n", l); + + [CATransaction commit]; + [pool release]; } diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m index f8faeb8d0..38f1789e3 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m @@ -501,6 +501,28 @@ NSView* getNSView(NSOpenGLContext* ctx) { return view; } +static Bool lockViewIfReady(NSView *view) { + Bool viewReady = false; + + if (view != nil) { + if ([view lockFocusIfCanDraw] == NO) { + DBG_PRINT("lockViewIfReady.1 [view lockFocusIfCanDraw] failed\n"); + } else { + NSRect frame = [view frame]; + if ((frame.size.width == 0) || (frame.size.height == 0)) { + [view unlockFocus]; + DBG_PRINT("lockViewIfReady.2 view.frame size %dx%d\n", (int)frame.size.width, (int)frame.size.height); + } else { + DBG_PRINT("lockViewIfReady.X ready and locked\n"); + viewReady = true; + } + } + } else { + DBG_PRINT("lockViewIfReady.3 nil view\n"); + } + return viewReady; +} + NSOpenGLContext* createContext(NSOpenGLContext* share, NSView* view, Bool incompleteView, @@ -515,40 +537,18 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, DBG_PRINT("createContext.0: share %p, view %p, incompleteView %d, pixfmt %p, opaque %d\n", share, view, (int)incompleteView, fmt, opaque); - if (view != nil) { - Bool viewReady = true; - - if(!incompleteView) { - if ([view lockFocusIfCanDraw] == NO) { - DBG_PRINT("createContext.1 [view lockFocusIfCanDraw] failed\n"); - viewReady = false; - } - } - if(viewReady) { - NSRect frame = [view frame]; - if ((frame.size.width == 0) || (frame.size.height == 0)) { - if(!incompleteView) { - [view unlockFocus]; - } - DBG_PRINT("createContext.2 view.frame size %dx%d\n", (int)frame.size.width, (int)frame.size.height); - viewReady = false; - } - } + Bool viewReadyAndLocked = incompleteView ? false : lockViewIfReady(view); - if (!viewReady) - { - if (viewNotReady != NULL) - { - *viewNotReady = 1; - } + if (nil != viewNotReady) { + *viewNotReady = 1; + } - // the view is not ready yet - DBG_PRINT("createContext.X: view not ready yet\n"); - [pool release]; - return NULL; - } + if (nil != view && !incompleteView && !viewReadyAndLocked) { + DBG_PRINT("createContext.X: Assumed complete view not ready yet\n"); + [pool release]; + return NULL; } - + NSOpenGLContext* ctx = [[NSOpenGLContext alloc] initWithFormat:fmt shareContext:share]; if ( nil != ctx && nil != view ) { @@ -556,10 +556,8 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, GLint zeroOpacity = 0; [ctx setValues:&zeroOpacity forParameter:NSOpenGLCPSurfaceOpacity]; } - if(!incompleteView) { - DBG_PRINT("createContext.3.0: setView\n"); + if( viewReadyAndLocked ) { [ctx setView:view]; - DBG_PRINT("createContext.3.X: setView\n"); [view unlockFocus]; } } @@ -571,8 +569,19 @@ NSOpenGLContext* createContext(NSOpenGLContext* share, void setContextView(NSOpenGLContext* ctx, NSView* view) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - if ( nil != ctx && nil != view ) { - [ctx setView:view]; + if ( nil != ctx ) { + if ( nil != view ) { + Bool viewReadyAndLocked = lockViewIfReady(view); + DBG_PRINT("setContextView.0: ctx %p, view %p: setView: %d\n", ctx, view, viewReadyAndLocked); + if( viewReadyAndLocked ) { + [ctx setView:view]; + [view unlockFocus]; + } + } else { + DBG_PRINT("setContextView.1: ctx %p, view nil: clearDrawable\n", ctx); + [ctx clearDrawable]; + } + DBG_PRINT("setContextView.X\n"); } [pool release]; } @@ -725,7 +734,7 @@ void setContextTextureImageToPBuffer(NSOpenGLContext* ctx, NSOpenGLPixelBuffer* Bool isNSOpenGLPixelBuffer(uint64_t object) { NSObject *nsObj = (NSObject*) (intptr_t) object; DBG_PRINT("isNSOpenGLPixelBuffer.0: obj %p\n", object); - Bool res = [nsObj isMemberOfClass:[NSOpenGLPixelBuffer class]]; + Bool res = [nsObj isKindOfClass:[NSOpenGLPixelBuffer class]]; DBG_PRINT("isNSOpenGLPixelBuffer.X: res %d\n", (int)res); return res; } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 3e5e629b6..15a0f550f 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -134,6 +134,13 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } protected synchronized void invalidate() { + if(DEBUG) { + System.err.println("JAWTWindow.invalidate()"); + // Thread.dumpStack(); + } + if( isSurfaceLayerAttached() ) { + detachSurfaceLayer(); + } invalidateNative(); jawt = null; isOffscreenLayerSurface = false; diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 758105713..d11d24664 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -74,13 +74,16 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { System.err.println("MacOSXJAWTWindow.invalidateNative(): osh-enabled "+isOffscreenLayerSurfaceEnabled()+ ", osh-set "+offscreenSurfaceHandleSet+ ", osh "+toHexString(offscreenSurfaceHandle)+ - ", rsh "+toHexString(rootSurfaceLayerHandle)+ - ", wh "+toHexString(windowHandle)); + ", rsh "+toHexString(rootSurfaceLayer)+ + ", wh "+toHexString(windowHandle)+" - "+Thread.currentThread().getName()); } offscreenSurfaceHandle=0; offscreenSurfaceHandleSet=false; if( isOffscreenLayerSurfaceEnabled() ) { - if(0 != rootSurfaceLayerHandle) { + if(0 != windowHandle) { + OSXUtil.DestroyNSWindow(windowHandle); + } + if(0 != rootSurfaceLayer) { final JAWT jawt = getJAWT(); if( null != jawt ) { final JAWT_DrawingSurface ds = jawt.GetDrawingSurface(component); @@ -90,9 +93,9 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { try { dsi = ds.GetDrawingSurfaceInfo(); try { - UnsetJAWTRootSurfaceLayer(dsi.getBuffer(), rootSurfaceLayerHandle); + UnsetJAWTRootSurfaceLayer0(dsi.getBuffer(), rootSurfaceLayer); } catch (Exception e) { - System.err.println("Error clearing JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayerHandle)); + System.err.println("Error clearing JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayer)); e.printStackTrace(); } } finally { @@ -105,19 +108,15 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { jawt.FreeDrawingSurface(ds); } } - OSXUtil.DestroyCALayer(rootSurfaceLayerHandle); - - rootSurfaceLayerHandle = 0; - } - if(0 != windowHandle) { - OSXUtil.DestroyNSWindow(windowHandle); + OSXUtil.DestroyCALayer(rootSurfaceLayer); + rootSurfaceLayer = 0; } } windowHandle=0; } - + protected void attachSurfaceLayerImpl(final long layerHandle) { - OSXUtil.AddCASublayer(rootSurfaceLayerHandle, layerHandle, getWidth(), getHeight()); + OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, getWidth(), getHeight()); } protected void layoutSurfaceLayerImpl() { @@ -127,11 +126,11 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { if(DEBUG) { System.err.println("JAWTWindow.fixSurfaceLayerLayout: "+toHexString(osl) + ", bounds "+bounds+", "+w+"x"+h); } - OSXUtil.FixCALayerLayout(rootSurfaceLayerHandle, osl, w, h); + OSXUtil.FixCALayerLayout(rootSurfaceLayer, osl, w, h); } protected void detachSurfaceLayerImpl(final long layerHandle) { - OSXUtil.RemoveCASublayer(rootSurfaceLayerHandle, layerHandle); + OSXUtil.RemoveCASublayer(rootSurfaceLayer, layerHandle); } @Override @@ -243,23 +242,23 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } } if(null == errMsg) { - if(0 == rootSurfaceLayerHandle) { - rootSurfaceLayerHandle = OSXUtil.CreateCALayer(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); - if(0 == rootSurfaceLayerHandle) { + if(0 == rootSurfaceLayer) { + rootSurfaceLayer = OSXUtil.CreateCALayer(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); + if(0 == rootSurfaceLayer) { errMsg = "Could not create root CALayer"; } else { try { - SetJAWTRootSurfaceLayer(dsi.getBuffer(), rootSurfaceLayerHandle); + SetJAWTRootSurfaceLayer0(dsi.getBuffer(), rootSurfaceLayer); } catch(Exception e) { - errMsg = "Could not set JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayerHandle)+", cause: "+e.getMessage(); + errMsg = "Could not set JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayer)+", cause: "+e.getMessage(); } } } } if(null != errMsg) { - if(0 != rootSurfaceLayerHandle) { - OSXUtil.DestroyCALayer(rootSurfaceLayerHandle); - rootSurfaceLayerHandle = 0; + if(0 != rootSurfaceLayer) { + OSXUtil.DestroyCALayer(rootSurfaceLayer); + rootSurfaceLayer = 0; } if(0 != windowHandle) { OSXUtil.DestroyNSWindow(windowHandle); @@ -316,18 +315,11 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { /** * Set the given root CALayer in the JAWT surface */ - private static void SetJAWTRootSurfaceLayer(final Buffer jawtDrawingSurfaceInfoBuffer, final long caLayer) { - SetJAWTRootSurfaceLayer0(jawtDrawingSurfaceInfoBuffer, caLayer); - } - + private static native void SetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); + /** - * Unset the given root CALayer in the JAWT surface + * Unset the given root CALayer in the JAWT surface, passing the NIO DrawingSurfaceInfo buffer */ - private static void UnsetJAWTRootSurfaceLayer(final Buffer jawtDrawingSurfaceInfoBuffer, final long caLayer) { - UnsetJAWTRootSurfaceLayer0(jawtDrawingSurfaceInfoBuffer, caLayer); - } - - private static native void SetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); private static native void UnsetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); // Variables for lockSurface/unlockSurface @@ -337,7 +329,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { private JAWT_MacOSXDrawingSurfaceInfo macosxdsi; - private long rootSurfaceLayerHandle = 0; // attached to the JAWT_SurfaceLayer + private long rootSurfaceLayer = 0; // attached to the JAWT_SurfaceLayer private long windowHandle = 0; private long offscreenSurfaceHandle = 0; diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 1563a5a8b..703c3d972 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -83,11 +83,11 @@ public class OSXUtil implements ToolkitProperties { public static final boolean hasThreadingIssues() { return false; } public static boolean isNSView(long object) { - return isNSView0(object); + return 0 != object ? isNSView0(object) : false; } public static boolean isNSWindow(long object) { - return isNSWindow0(object); + return 0 != object ? isNSWindow0(object) : false; } /** @@ -164,8 +164,7 @@ public class OSXUtil implements ToolkitProperties { } RunOnMainThread(false, new Runnable() { public void run() { - AddCASublayer0(rootCALayer, subCALayer); - FixCALayerLayout0(rootCALayer, subCALayer, width, height); + AddCASublayer0(rootCALayer, subCALayer, width, height); } }); } @@ -194,24 +193,32 @@ public class OSXUtil implements ToolkitProperties { } /** - * Detach a sub CALayer from the root CALayer + * Detach a sub CALayer from the root CALayer on the main-thread w/o blocking. */ public static void RemoveCASublayer(final long rootCALayer, final long subCALayer) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } - RemoveCASublayer0(rootCALayer, subCALayer); + RunOnMainThread(false, new Runnable() { + public void run() { + RemoveCASublayer0(rootCALayer, subCALayer); + } + }); } /** - * Destroy a CALayer + * Destroy a CALayer on main-thread w/o blocking. * @see #CreateCALayer(int, int, int, int) */ public static void DestroyCALayer(final long caLayer) { if(0==caLayer) { throw new IllegalArgumentException("caLayer 0x"+Long.toHexString(caLayer)); } - DestroyCALayer0(caLayer); + RunOnMainThread(false, new Runnable() { + public void run() { + DestroyCALayer0(caLayer); + } + }); } /** @@ -337,7 +344,7 @@ public class OSXUtil implements ToolkitProperties { private static native long GetNSView0(long nsWindow); private static native long GetNSWindow0(long nsView); private static native long CreateCALayer0(int x, int y, int width, int height); - private static native void AddCASublayer0(long rootCALayer, long subCALayer); + private static native void AddCASublayer0(long rootCALayer, long subCALayer, int width, int height); private static native void FixCALayerLayout0(long rootCALayer, long subCALayer, int width, int height); private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 14a9781f7..81dcfa959 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -127,13 +127,17 @@ Java_jogamp_nativewindow_macosx_OSXUtil_initIDs0(JNIEnv *env, jclass _unused) { JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_isNSView0(JNIEnv *env, jclass _unused, jlong object) { NSObject *nsObj = (NSObject*) (intptr_t) object; - return [nsObj isMemberOfClass:[NSView class]]; + jboolean u = [nsObj isKindOfClass:[NSView class]]; + DBG_PRINT( "isNSView(obj: %p): %s -> %d\n", nsObj, [[nsObj description] UTF8String], u); + return u; } JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_isNSWindow0(JNIEnv *env, jclass _unused, jlong object) { NSObject *nsObj = (NSObject*) (intptr_t) object; - return [nsObj isMemberOfClass:[NSWindow class]]; + jboolean u = [nsObj isKindOfClass:[NSWindow class]]; + DBG_PRINT( "isNSWindow(obj: %p): %s -> %d\n", nsObj, [[nsObj description] UTF8String], u); + return u; } /* @@ -425,23 +429,56 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 return (jlong) ((intptr_t) layer); } +static void FixCALayerLayout0(MyCALayer* rootLayer, CALayer* subLayer, jint width, jint height) { + if( NULL != rootLayer ) { + CGRect lRect = [rootLayer frame]; + if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { + DBG_PRINT("CALayer::FixCALayerLayout0.0: Root %p exp 0/0 %dx%d -> frame0: %lf/%lf %lfx%lf\n", + rootLayer, (int)width, (int)height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + lRect.origin.x = 0; + lRect.origin.y = 0; + lRect.size.width = width; + lRect.size.height = height; + [rootLayer setFrame: lRect]; + } + } + if( NULL != subLayer ) { + CGRect lRect = [subLayer frame]; + if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { + DBG_PRINT("CALayer::FixCALayerLayout0.0: SubL %p exp 0/0 %dx%d -> frame0: %lf/%lf %lfx%lf\n", + subLayer, (int)width, (int)height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + lRect.origin.x = 0; + lRect.origin.y = 0; + lRect.size.width = width; + lRect.size.height = height; + if( [subLayer conformsToProtocol:@protocol(NWDedicatedSize)] ) { + CALayer * subLayerDS = (CALayer *) subLayer; + [subLayerDS setDedicatedSize: lRect.size]; + } else { + [subLayer setFrame: lRect]; + } + } + } +} + /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: AddCASublayer0 - * Signature: (JJ)V + * Signature: (JJII)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 - (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer) + (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint width, jint height) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); - [subLayer retain]; // Pairs w/ RemoveCASublayer - [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + [rootLayer retain]; // Pairs w/ RemoveCASublayer + [subLayer retain]; // Pairs w/ RemoveCASublayer + CGRect lRectRoot = [rootLayer frame]; DBG_PRINT("CALayer::AddCASublayer0.0: Origin %p frame0: %lf/%lf %lfx%lf\n", rootLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height); @@ -471,11 +508,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 [subLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; [subLayer setNeedsDisplayOnBoundsChange: YES]; - // Trigger display and hence ctx creation. - // The latter is essential since since the parent-context lock is cleared - // only for this window of time (method call). - [rootLayer setNeedsDisplay]; - [rootLayer displayIfNeeded]; + FixCALayerLayout0(rootLayer, subLayer, width, height); [CATransaction commit]; @@ -499,35 +532,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_FixCALayerLayout0 [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; - if( NULL != rootLayer ) { - CGRect lRect = [rootLayer frame]; - if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { - DBG_PRINT("CALayer::FixCALayerLayout0.0: Root %p exp 0/0 %dx%d -> frame0: %lf/%lf %lfx%lf\n", - rootLayer, (int)width, (int)height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); - lRect.origin.x = 0; - lRect.origin.y = 0; - lRect.size.width = width; - lRect.size.height = height; - [rootLayer setFrame: lRect]; - } - } - if( NULL != subLayer ) { - CGRect lRect = [subLayer frame]; - if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { - DBG_PRINT("CALayer::FixCALayerLayout0.0: SubL %p exp 0/0 %dx%d -> frame0: %lf/%lf %lfx%lf\n", - subLayer, (int)width, (int)height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); - lRect.origin.x = 0; - lRect.origin.y = 0; - lRect.size.width = width; - lRect.size.height = height; - if( [subLayer conformsToProtocol:@protocol(NWDedicatedSize)] ) { - CALayer * subLayerDS = (CALayer *) subLayer; - [subLayerDS setDedicatedSize: lRect.size]; - } else { - [subLayer setFrame: lRect]; - } - } - } + FixCALayerLayout0(rootLayer, subLayer, width, height); [CATransaction commit]; @@ -556,6 +561,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RemoveCASublayer0 [subLayer removeFromSuperlayer]; [subLayer release]; // Pairs w/ AddCASublayer + [rootLayer release]; // Pairs w/ AddCASublayer [CATransaction commit]; @@ -575,8 +581,14 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyCALayer0 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; MyCALayer* layer = (MyCALayer*) ((intptr_t) caLayer); + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + DBG_PRINT("CALayer::DestroyCALayer0.0: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); - [layer release]; // Trigger release of root CALayer + [layer release]; // Trigger release and dealloc of root CALayer, it's child etc .. + + [CATransaction commit]; + [pool release]; DBG_PRINT("CALayer::DestroyCALayer0.X: root %p\n", layer); } @@ -590,6 +602,10 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Set (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); if (NULL == dsi) { NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); @@ -598,7 +614,10 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Set MyCALayer* layer = (MyCALayer*) (intptr_t) caLayer; id surfaceLayers = (id )dsi->platformInfo; DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.0: pre %p -> root %p (refcnt %d)\n", surfaceLayers.layer, layer, (int)[layer retainCount]); - surfaceLayers.layer = [layer retain]; // Pairs w/ Unset + [surfaceLayers setLayer: [layer retain]]; // Pairs w/ Unset + + [CATransaction commit]; + [pool release]; DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.X: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); } @@ -612,6 +631,10 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Uns (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); if (NULL == dsi) { NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); @@ -625,7 +648,10 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Uns } DBG_PRINT("CALayer::UnsetJAWTRootSurfaceLayer.0: root %p (refcnt %d) -> nil\n", layer, (int)[layer retainCount]); [layer release]; // Pairs w/ Set - surfaceLayers.layer = NULL; + [surfaceLayers setLayer: NULL]; + + [CATransaction commit]; + [pool release]; DBG_PRINT("CALayer::UnsetJAWTRootSurfaceLayer.X: root %p (refcnt %d) -> nil\n", layer, (int)[layer retainCount]); } @@ -735,8 +761,10 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunOnMainThread0 DBG_PRINT2( "RunOnMainThread0.1.0\n"); MainRunnable * mr = [[MainRunnable alloc] initWithRunnable: runnableObj jvmHandle: jvmHandle jvmVersion: jvmVersion]; + [mr performSelectorOnMainThread:@selector(jRun) withObject:nil waitUntilDone:NO]; DBG_PRINT2( "RunOnMainThread0.1.1\n"); + [mr release]; DBG_PRINT2( "RunOnMainThread0.1.2\n"); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java index ce8f9adc8..48c3c89b3 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java @@ -51,17 +51,21 @@ import org.junit.BeforeClass; import org.junit.Test; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; public class TestAddRemove01GLCanvasSwingAWT extends UITestCase { static long durationPerTest = 50; static int addRemoveCount = 15; + static int pauseEach = 0; + static int pauseDuration = 500; static boolean noOnscreenTest = false; static boolean noOffscreenTest = false; static boolean shallUseOffscreenPBufferLayer = false; static GLProfile glp; static int width, height; static boolean waitForKey = false; + static boolean waitForKeyPost = false; @BeforeClass public static void initClass() { @@ -167,9 +171,19 @@ public class TestAddRemove01GLCanvasSwingAWT extends UITestCase { } while ( ( System.currentTimeMillis() - t0 ) < durationPerTest ) ; System.err.println("GLCanvas isOffscreenLayerSurfaceEnabled: "+glc.isOffscreenLayerSurfaceEnabled()+": "+glc.getChosenGLCapabilities()); + + dispose(top[0]); - dispose(top[0]); + if( 0 < pauseEach && 0 == i % pauseEach ) { + System.err.println("******* P A U S E - Start ********"); + // OSXUtil.WaitUntilFinish(); + Thread.sleep(pauseDuration); + System.err.println("******* P A U S E - End ********"); + } } + if(waitForKeyPost) { + UITestCase.waitForKey("End"); + } } @Test @@ -213,9 +227,13 @@ public class TestAddRemove01GLCanvasSwingAWT extends UITestCase { } catch (Exception ex) { ex.printStackTrace(); } } else if(args[i].equals("-loops")) { i++; - try { - addRemoveCount = Integer.parseInt(args[i]); - } catch (Exception ex) { ex.printStackTrace(); } + addRemoveCount = MiscUtils.atoi(args[i], addRemoveCount); + } else if(args[i].equals("-pauseEach")) { + i++; + pauseEach = MiscUtils.atoi(args[i], pauseEach); + } else if(args[i].equals("-pauseDuration")) { + i++; + pauseDuration = MiscUtils.atoi(args[i], pauseDuration); } else if(args[i].equals("-noOnscreen")) { noOnscreenTest = true; } else if(args[i].equals("-noOffscreen")) { @@ -224,11 +242,15 @@ public class TestAddRemove01GLCanvasSwingAWT extends UITestCase { shallUseOffscreenPBufferLayer = true; } else if(args[i].equals("-wait")) { waitForKey = true; - } + } else if(args[i].equals("-waitPost")) { + waitForKeyPost = true; + } } System.err.println("waitForKey "+waitForKey); System.err.println("addRemoveCount "+addRemoveCount); + System.err.println("pauseEach "+pauseEach); + System.err.println("pauseDuration "+pauseDuration); System.err.println("noOnscreenTest "+noOnscreenTest); System.err.println("noOffscreenTest "+noOffscreenTest); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove02GLWindowNewtCanvasAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove02GLWindowNewtCanvasAWT.java index 3d78943f9..ce88abfba 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove02GLWindowNewtCanvasAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove02GLWindowNewtCanvasAWT.java @@ -53,11 +53,14 @@ import org.junit.Test; import com.jogamp.newt.awt.NewtCanvasAWT; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; public class TestAddRemove02GLWindowNewtCanvasAWT extends UITestCase { static long durationPerTest = 50; static int addRemoveCount = 15; + static int pauseEach = 0; + static int pauseDuration = 500; static boolean noOnscreenTest = false; static boolean noOffscreenTest = false; static boolean shallUseOffscreenPBufferLayer = false; @@ -174,6 +177,11 @@ public class TestAddRemove02GLWindowNewtCanvasAWT extends UITestCase { dispose(top[0]); glw.destroy(); + + if( 0 < pauseEach && 0 == i % pauseEach ) { + System.err.println("******* P A U S E ********"); + Thread.sleep(pauseDuration); + } } } @@ -218,9 +226,13 @@ public class TestAddRemove02GLWindowNewtCanvasAWT extends UITestCase { } catch (Exception ex) { ex.printStackTrace(); } } else if(args[i].equals("-loops")) { i++; - try { - addRemoveCount = Integer.parseInt(args[i]); - } catch (Exception ex) { ex.printStackTrace(); } + addRemoveCount = MiscUtils.atoi(args[i], addRemoveCount); + } else if(args[i].equals("-pauseEach")) { + i++; + pauseEach = MiscUtils.atoi(args[i], pauseEach); + } else if(args[i].equals("-pauseDuration")) { + i++; + pauseDuration = MiscUtils.atoi(args[i], pauseDuration); } else if(args[i].equals("-noOnscreen")) { noOnscreenTest = true; } else if(args[i].equals("-noOffscreen")) { @@ -234,6 +246,8 @@ public class TestAddRemove02GLWindowNewtCanvasAWT extends UITestCase { System.err.println("waitForKey "+waitForKey); System.err.println("addRemoveCount "+addRemoveCount); + System.err.println("pauseEach "+pauseEach); + System.err.println("pauseDuration "+pauseDuration); System.err.println("noOnscreenTest "+noOnscreenTest); System.err.println("noOffscreenTest "+noOffscreenTest); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove03GLWindowNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove03GLWindowNEWT.java index 9d7a4026b..981b14af3 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove03GLWindowNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove03GLWindowNEWT.java @@ -41,11 +41,14 @@ import org.junit.Test; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; public class TestAddRemove03GLWindowNEWT extends UITestCase { static long durationPerTest = 50; static int addRemoveCount = 15; + static int pauseEach = 0; + static int pauseDuration = 500; static GLProfile glp; static int width, height; static boolean waitForKey = false; @@ -91,6 +94,11 @@ public class TestAddRemove03GLWindowNEWT extends UITestCase { System.err.println("GLWindow: "+glw.getChosenGLCapabilities()); glw.destroy(); + + if( 0 < pauseEach && 0 == i % pauseEach ) { + System.err.println("******* P A U S E ********"); + Thread.sleep(pauseDuration); + } } } @@ -111,9 +119,13 @@ public class TestAddRemove03GLWindowNEWT extends UITestCase { } catch (Exception ex) { ex.printStackTrace(); } } else if(args[i].equals("-loops")) { i++; - try { - addRemoveCount = Integer.parseInt(args[i]); - } catch (Exception ex) { ex.printStackTrace(); } + addRemoveCount = MiscUtils.atoi(args[i], addRemoveCount); + } else if(args[i].equals("-pauseEach")) { + i++; + pauseEach = MiscUtils.atoi(args[i], pauseEach); + } else if(args[i].equals("-pauseDuration")) { + i++; + pauseDuration = MiscUtils.atoi(args[i], pauseDuration); } else if(args[i].equals("-wait")) { waitForKey = true; } @@ -121,6 +133,8 @@ public class TestAddRemove03GLWindowNEWT extends UITestCase { System.err.println("waitForKey "+waitForKey); System.err.println("addRemoveCount "+addRemoveCount); + System.err.println("pauseEach "+pauseEach); + System.err.println("pauseDuration "+pauseDuration); if(waitForKey) { UITestCase.waitForKey("Start"); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java index 0673e2f45..0b70cf151 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT.java @@ -64,6 +64,7 @@ import com.jogamp.opengl.test.junit.util.UITestCase; public class TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT extends UITestCase { static final int widthStep = 800/4; static final int heightStep = 600/4; + static boolean waitForKey = false; volatile int szStep = 2; static GLCapabilities getCaps(String profile) { @@ -331,6 +332,14 @@ public class TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT extends UITestCase { } public static void main(String args[]) throws IOException { + for(int i=0; i Date: Mon, 18 Mar 2013 08:16:25 +0100 Subject: NativeWindow OSXUtil RunOnMainThread: Use daemon attachment and do not detach; Add RunLater0(..) --- src/nativewindow/native/NativewindowCommon.c | 9 +++- src/nativewindow/native/NativewindowCommon.h | 2 +- src/nativewindow/native/macosx/OSXmisc.m | 65 ++++++++++++++++++---------- src/nativewindow/native/x11/Xmisc.c | 4 +- 4 files changed, 53 insertions(+), 27 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/native/NativewindowCommon.c b/src/nativewindow/native/NativewindowCommon.c index d2fdd5d69..e909c0494 100644 --- a/src/nativewindow/native/NativewindowCommon.c +++ b/src/nativewindow/native/NativewindowCommon.c @@ -74,7 +74,7 @@ jchar* NativewindowCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str) return strChars; } -JNIEnv* NativewindowCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int * shallBeDetached) { +JNIEnv* NativewindowCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int asDaemon, int * shallBeDetached) { JNIEnv* curEnv = NULL; JNIEnv* newEnv = NULL; int envRes; @@ -83,7 +83,12 @@ JNIEnv* NativewindowCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int * envRes = (*jvmHandle)->GetEnv(jvmHandle, (void **) &curEnv, jvmVersion) ; if( JNI_EDETACHED == envRes ) { // detached thread - attach to JVM - if( JNI_OK != ( envRes = (*jvmHandle)->AttachCurrentThread(jvmHandle, (void**) &newEnv, NULL) ) ) { + if( asDaemon ) { + envRes = (*jvmHandle)->AttachCurrentThreadAsDaemon(jvmHandle, (void**) &newEnv, NULL); + } else { + envRes = (*jvmHandle)->AttachCurrentThread(jvmHandle, (void**) &newEnv, NULL); + } + if( JNI_OK != envRes ) { fprintf(stderr, "JNIEnv: can't attach thread: %d\n", envRes); return NULL; } diff --git a/src/nativewindow/native/NativewindowCommon.h b/src/nativewindow/native/NativewindowCommon.h index 73b890c4f..a2975f3fd 100644 --- a/src/nativewindow/native/NativewindowCommon.h +++ b/src/nativewindow/native/NativewindowCommon.h @@ -13,6 +13,6 @@ jchar* NativewindowCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str) void NativewindowCommon_FatalError(JNIEnv *env, const char* msg, ...); void NativewindowCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...); -JNIEnv* NativewindowCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int * shallBeDetached); +JNIEnv* NativewindowCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int asDaemon, int * shallBeDetached); #endif diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 81dcfa959..5d292d76e 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -689,7 +689,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Uns - (void) jRun { int shallBeDetached = 0; - JNIEnv* env = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); + JNIEnv* env = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, 1 /* asDaemon */, &shallBeDetached); DBG_PRINT2("MainRunnable.1 env: %d\n", (int)(NULL!=env)); if(NULL!=env) { DBG_PRINT2("MainRunnable.1.0\n"); @@ -699,7 +699,8 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Uns if (shallBeDetached) { DBG_PRINT2("MainRunnable.1.3\n"); - (*jvmHandle)->DetachCurrentThread(jvmHandle); + // Keep attached on main thread ! + // (*jvmHandle)->DetachCurrentThread(jvmHandle); } } DBG_PRINT2("MainRunnable.X\n"); @@ -733,21 +734,12 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Uns @end - -/* - * Class: Java_jogamp_nativewindow_macosx_OSXUtil - * Method: RunOnMainThread0 - * Signature: (ZLjava/lang/Runnable;)V - */ -JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunOnMainThread0 - (JNIEnv *env, jclass unused, jobject runnable) +static void RunOnThread (JNIEnv *env, jobject runnable, BOOL onMain, jint delayInMS) { - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - - DBG_PRINT2( "RunOnMainThread0: isMainThread %d, NSApp %d, NSApp-isRunning %d\n", - (int)([NSThread isMainThread]), (int)(NULL!=NSApp), (int)([NSApp isRunning])); + DBG_PRINT2( "RunOnThread0: isMainThread %d, NSApp %d, NSApp-isRunning %d, onMain %d, delay %dms\n", + (int)([NSThread isMainThread]), (int)(NULL!=NSApp), (int)([NSApp isRunning]), (int)onMain, (int)delayInMS); - if ( NO == [NSThread isMainThread] ) { + if ( !onMain || NO == [NSThread isMainThread] ) { jobject runnableObj = (*env)->NewGlobalRef(env, runnable); JavaVM *jvmHandle = NULL; @@ -759,27 +751,56 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunOnMainThread0 jvmVersion = (*env)->GetVersion(env); } - DBG_PRINT2( "RunOnMainThread0.1.0\n"); + DBG_PRINT2( "RunOnThread.1.0\n"); MainRunnable * mr = [[MainRunnable alloc] initWithRunnable: runnableObj jvmHandle: jvmHandle jvmVersion: jvmVersion]; - [mr performSelectorOnMainThread:@selector(jRun) withObject:nil waitUntilDone:NO]; - DBG_PRINT2( "RunOnMainThread0.1.1\n"); + if( onMain ) { + [mr performSelectorOnMainThread:@selector(jRun) withObject:nil waitUntilDone:NO]; + } else { + NSTimeInterval delay = (double)delayInMS/1000.0; + [mr performSelector:@selector(jRun) withObject:nil afterDelay:delay]; + } + DBG_PRINT2( "RunOnThread.1.1\n"); [mr release]; - DBG_PRINT2( "RunOnMainThread0.1.2\n"); + DBG_PRINT2( "RunOnThread.1.2\n"); } else { - DBG_PRINT2( "RunOnMainThread0.2\n"); + DBG_PRINT2( "RunOnThread.2\n"); (*env)->CallVoidMethod(env, runnable, runnableRunID); } - DBG_PRINT2( "RunOnMainThread0.X\n"); + DBG_PRINT2( "RunOnThread.X\n"); +} +/* + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: RunOnMainThread0 + * Signature: (ZLjava/lang/Runnable;)V + */ +JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunOnMainThread0 + (JNIEnv *env, jclass unused, jobject runnable) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + RunOnThread (env, runnable, YES, 0); [pool release]; } /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil - * Method: RunOnMainThread0 + * Method: RunLater0 + * Signature: (ZLjava/lang/Runnable;I)V + */ +JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunLater0 + (JNIEnv *env, jclass unused, jobject runnable, jint delay) +{ + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + RunOnThread (env, runnable, NO, delay); + [pool release]; +} + +/* + * Class: Java_jogamp_nativewindow_macosx_OSXUtil + * Method: IsMainThread0 * Signature: (V)V */ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_IsMainThread0 diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 017c52df2..77e6ea978 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -197,7 +197,7 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) fflush(stderr); if( NULL != jvmHandle && ( errorHandlerDebug || errorHandlerThrowException ) ) { - jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); + jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, 0 /* asDaemon */, &shallBeDetached); if(NULL == jniEnv) { fprintf(stderr, "Nativewindow X11 Error: null JNIEnv"); fflush(stderr); @@ -262,7 +262,7 @@ static int x11IOErrorHandler(Display *dpy) fflush(stderr); if( NULL != jvmHandle ) { - jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); + jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, 0 /* asDaemon */, &shallBeDetached); if (NULL != jniEnv) { NativewindowCommon_FatalError(jniEnv, "Nativewindow X11 IOError: Display %p (%s): %s", dpy, dpyName, errnoStr); if (shallBeDetached) { -- cgit v1.2.3 From 12e868f79938f44eba6f50313f977be76d8ea2bb Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 19 Mar 2013 00:00:18 +0100 Subject: MyNSOpenGLContext::dealloc: Avoid 'invalid context' --- .../macosx/MacOSXWindowSystemInterface-calayer.m | 28 +++++++++++++++++++--- src/nativewindow/native/macosx/OSXmisc.m | 8 +++---- 2 files changed, 29 insertions(+), 7 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index 96783c75d..0f1073c9d 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -112,18 +112,40 @@ extern GLboolean glIsVertexArray (GLuint array); #endif +#ifdef VERBOSE_ON + #define CGLRETAINCOUNT(c) (NULL!=c?(int)CGLGetContextRetainCount(c):-1) +#else + #define CGLRETAINCOUNT(c) +#endif + - (void)dealloc { + /** + * The explicit CGLContext destruction below + * ensures that it is not left behind. + * Tests show that w/o these gymnastics, the CGLContext is not freed immediately after calling dealloc. + * The retain, release and dealloc ensures [super dealloc] won't message 'invalid context'. + */ CGLContextObj cglCtx = [self CGLContextObj]; - DBG_PRINT("MyNSOpenGLContext::dealloc.0 %p (refcnt %d) - CGL-Ctx %p\n", self, (int)[self retainCount], cglCtx); + DBG_PRINT("MyNSOpenGLContext::dealloc.0 %p (refcnt %d) - CGL-Ctx %p\n", self, (int)[self retainCount], cglCtx, CGLRETAINCOUNT(cglCtx)); // NSLog(@"MyNSOpenGLContext::dealloc: %@",[NSThread callStackSymbols]); + [self clearDrawable]; + DBG_PRINT("MyNSOpenGLContext.dealloc.1 %d\n", CGLRETAINCOUNT(cglCtx)); if( NULL != cglCtx ) { - CGLDestroyContext( cglCtx ); + CGLRetainContext( cglCtx ); + DBG_PRINT("MyNSOpenGLContext.dealloc.2 %d\n", CGLRETAINCOUNT(cglCtx)); } [super dealloc]; - // DBG_PRINT("MyNSOpenGLContext.dealloc.X: %p\n", self); + DBG_PRINT("MyNSOpenGLContext.dealloc.3 %d\n", CGLRETAINCOUNT(cglCtx)); + if( NULL != cglCtx ) { + CGLReleaseContext( cglCtx ); + DBG_PRINT("MyNSOpenGLContext.dealloc.4 %d\n", CGLRETAINCOUNT(cglCtx)); + CGLDestroyContext( cglCtx ); + DBG_PRINT("MyNSOpenGLContext.dealloc.5 %d\n", CGLRETAINCOUNT(cglCtx)); + } + DBG_PRINT("MyNSOpenGLContext.dealloc.X\n"); } @end diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 5d292d76e..d6a63702b 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -433,8 +433,8 @@ static void FixCALayerLayout0(MyCALayer* rootLayer, CALayer* subLayer, jint widt if( NULL != rootLayer ) { CGRect lRect = [rootLayer frame]; if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { - DBG_PRINT("CALayer::FixCALayerLayout0.0: Root %p exp 0/0 %dx%d -> frame0: %lf/%lf %lfx%lf\n", - rootLayer, (int)width, (int)height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + DBG_PRINT("CALayer::FixCALayerLayout0.0: Root %p frame %lf/%lf %lfx%lf -> 0/0 %dx%d\n", + rootLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, (int)width, (int)height); lRect.origin.x = 0; lRect.origin.y = 0; lRect.size.width = width; @@ -445,8 +445,8 @@ static void FixCALayerLayout0(MyCALayer* rootLayer, CALayer* subLayer, jint widt if( NULL != subLayer ) { CGRect lRect = [subLayer frame]; if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { - DBG_PRINT("CALayer::FixCALayerLayout0.0: SubL %p exp 0/0 %dx%d -> frame0: %lf/%lf %lfx%lf\n", - subLayer, (int)width, (int)height, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + DBG_PRINT("CALayer::FixCALayerLayout0.0: SubL %p frame %lf/%lf %lfx%lf -> 0/0 %dx%d\n", + subLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, (int)width, (int)height); lRect.origin.x = 0; lRect.origin.y = 0; lRect.size.width = width; -- cgit v1.2.3 From f354fb204d8973453c538dda78a2c82c87be61dc Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 19 Mar 2013 00:22:28 +0100 Subject: OSX/CALayer: OSX/CALayer Threading Part3 - Run CALayer ops in a streaming design on main-thread w/o [infinitive] blocking History: Part1 commit 896e8b021b39e9415040a57a1d540d7d24b02db1 (Run CALayer Ops on current thread to avoid blocking) Part2 commit 28c6472335b924080d638b33a28f8f4eedb459b1 (Run CALayer Ops on main-thread w/o blocking) Dependency: GlueGen commit 4becdfa125b07ff969d6540e1112735b53cd15eb (Fix RecursiveLockImpl* Timeout corner case) Part2 misses essential locking of the OpenGL context (and it's surface upfront) while creating the NSOpenGLLayer instance. The latter instantiates a OpenGL context shared w/ JOGL's, hence it cannot be locked. Encapsulating NSOpenGLLayer creation/attachment and it's detachment/release in sub-classes AttachNSOpenGLLayer and DetachNSOpenGLLayer, where instances will be streamed on main-thread. Both tasks are triggered at associateDrawable(boolean bound). The mentioned GL context locking requires disturbs the 'streaming' design considerably in AttachNSOpenGLLayer. It is solved by attempt to acquire the recursive lock of the surface and the context via 'tryLock(maxwait)' w/ screen-vSync-period/2. If the locks could not be acquired completly, the AttachNSOpenGLLayer instance will be re-queued to the main-thread for later execution. Before DetachNSOpenGLLayer is being streamed, it is validated whether AttachNSOpenGLLayer did run. A recursive situation does happen w/ resizing an offscreen pbuffer drawable! Hence extra care is being taken. --- src/jogl/classes/jogamp/opengl/GLContextImpl.java | 2 +- .../classes/jogamp/opengl/GLDrawableHelper.java | 2 +- .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 358 +++++++++++++-------- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 73 ++--- .../media/nativewindow/OffscreenLayerSurface.java | 5 + .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 58 ++-- .../jawt/windows/WindowsJAWTWindow.java | 7 - .../nativewindow/jawt/x11/X11JAWTWindow.java | 7 - .../jogamp/nativewindow/macosx/OSXUtil.java | 64 +++- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 9 +- .../acore/TestAddRemove01GLCanvasSwingAWT.java | 52 ++- .../TestAddRemove02GLWindowNewtCanvasAWT.java | 47 ++- ...TestSwingAWTRobotUsageBeforeJOGLInitBug411.java | 10 +- .../junit/newt/parenting/TestParenting04AWT.java | 4 + 14 files changed, 439 insertions(+), 259 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index 4121e8f77..64ade3eff 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -367,7 +367,7 @@ public abstract class GLContextImpl extends GLContext { try { // release current context if(lock.getHoldCount() == 1) { - // needs current context to disable debug handler + // needs current context to call associateDrawable(..) and to disable debug handler makeCurrent(); } try { diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java index 1caa942ba..9c1cd478b 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java @@ -190,7 +190,7 @@ public class GLDrawableHelper { *
      • make context current, if it was current
      • * *

        - * No locking is being performed, caller is required to take care of it. + * Locking is performed via {@link GLContext#makeCurrent()} on the passed context. *

        * * @param drawable diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index f01e03a2f..33893e456 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -71,6 +71,7 @@ import com.jogamp.common.nio.Buffers; import com.jogamp.common.nio.PointerBuffer; import com.jogamp.common.os.Platform; import com.jogamp.common.util.VersionNumber; +import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.gluegen.runtime.ProcAddressTable; import com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver; import com.jogamp.opengl.GLExtensions; @@ -461,10 +462,13 @@ public abstract class MacOSXCGLContext extends GLContextImpl // NSOpenGLContext-based implementation class NSOpenGLImpl implements GLBackendImpl { - private long pixelFormat = 0; // lifecycle: [create - destroy] - private volatile long nsOpenGLLayer = 0; // lifecycle: [associateDrawable_true - associateDrawable_false] - private float screenVSyncTimeout = 16666; // microSec - defaults to 1/60s - private volatile int vsyncTimeout = 16666 + 1000; // microSec - for nsOpenGLLayer mode - defaults to 1/60s + 1ms + private OffscreenLayerSurface backingLayerHost = null; + /** lifecycle: [create - destroy] */ + private long pixelFormat = 0; + /** microSec - defaults to 1/60s */ + private int screenVSyncTimeout = 16666; + /** microSec - for nsOpenGLLayer mode - defaults to 1/60s + 1ms */ + private volatile int vsyncTimeout = 16666 + 1000; private int lastWidth=0, lastHeight=0; // allowing to detect size change private boolean needsSetContextPBuffer = false; private ShaderProgram gl3ShaderProgram = null; @@ -562,7 +566,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl } final int sRefreshRate = OSXUtil.GetScreenRefreshRate(drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getIndex()); if( 0 < sRefreshRate ) { - screenVSyncTimeout = 1000000f / sRefreshRate; + screenVSyncTimeout = 1000000 / sRefreshRate; } if(DEBUG) { System.err.println("NS create OSX>=lion "+isLionOrLater); @@ -608,32 +612,147 @@ public abstract class MacOSXCGLContext extends GLContextImpl return CGL.deleteContext(ctx, true); } + /** + * NSOpenGLLayer creation and it's attachment is performed on the main-thread w/o [infinite] blocking. + *

        + * Since NSOpenGLLayer creation requires this context for it's shared context creation, + * this method attempts to acquire the surface and context lock with {@link #screenVSyncTimeout}/2 maximum wait time. + * If the surface and context lock could not be acquired, this runnable is being re-queued for later execution. + *

        + *

        + * Hence this method blocks the main-thread only for a short period of time. + *

        + */ + class AttachNSOpenGLLayer implements Runnable { + final OffscreenLayerSurface ols; + final long ctx; + final int shaderProgram; + final long pfmt; + final long pbuffer; + final int texID; + final boolean isOpaque; + final int width; + final int height; + /** Synchronized by instance's monitor */ + long nsOpenGLLayer; + /** Synchronized by instance's monitor */ + boolean valid; + + AttachNSOpenGLLayer(OffscreenLayerSurface ols, long ctx, int shaderProgram, long pfmt, long pbuffer, int texID, boolean isOpaque, int width, int height) { + this.ols = ols; + this.ctx = ctx; + this.shaderProgram = shaderProgram; + this.pfmt = pfmt; + this.pbuffer = pbuffer; + this.texID = texID; + this.isOpaque = isOpaque; + this.width = width; + this.height = height; + this.valid = false; + this.nsOpenGLLayer = 0; + } + + @Override + public void run() { + synchronized(this) { + if( !valid ) { + try { + final int maxwait = screenVSyncTimeout/2000; // TO 1/2 of current screen-vsync in [ms] + final RecursiveLock surfaceLock = ols.getLock(); + if( surfaceLock.tryLock( maxwait ) ) { + try { + if( MacOSXCGLContext.this.lock.tryLock( maxwait ) ) { + try { + nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, shaderProgram, pfmt, pbuffer, texID, isOpaque, width, height); + ols.attachSurfaceLayer(nsOpenGLLayer); + final int currentInterval = MacOSXCGLContext.this.getSwapInterval(); + final int interval = 0 <= currentInterval ? currentInterval : 1; + setSwapIntervalImpl(nsOpenGLLayer, interval); // enabled per default in layered surface + valid = true; + if (DEBUG) { + System.err.println("NSOpenGLLayer.Attach: OK, layer "+toHexString(nsOpenGLLayer)+" w/ pbuffer "+toHexString(pbuffer)+", texID "+texID+", texSize "+lastWidth+"x"+lastHeight+", drawableHandle "+toHexString(drawable.getHandle())+" - "+Thread.currentThread().getName()); + } + } finally { + MacOSXCGLContext.this.lock.unlock(); + } + } + } finally { + surfaceLock.unlock(); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + if( !valid ) { + // could not acquire lock, re-queue + if (DEBUG) { + System.err.println("NSOpenGLLayer.Attach: Re-Queue, drawableHandle "+toHexString(drawable.getHandle())+" - "+Thread.currentThread().getName()); + } + OSXUtil.RunLater(this, 1); + } + } + } + } + } + AttachNSOpenGLLayer attachCALayerCmd = null; + + class DetachNSOpenGLLayer implements Runnable { + final AttachNSOpenGLLayer cmd; + + DetachNSOpenGLLayer(AttachNSOpenGLLayer cmd) { + this.cmd = cmd; + } + @Override + public void run() { + synchronized( cmd ) { + if( cmd.valid ) { + // still having a valid OLS attached to surface (parent OLS could have been removed) + try { + final OffscreenLayerSurface ols = cmd.ols; + final long l = ols.getAttachedSurfaceLayer(); + if( 0 != l ) { + ols.detachSurfaceLayer(); + } + } catch(Throwable t) { + System.err.println("Catched exception @ "+Thread.currentThread().getName()+": "); + t.printStackTrace(); + } + CGL.releaseNSOpenGLLayer(cmd.nsOpenGLLayer); + if(DEBUG) { + System.err.println("NSOpenGLLayer.Detach: OK, layer "+toHexString(cmd.nsOpenGLLayer)+", drawableHandle "+toHexString(drawable.getHandle())+" - "+Thread.currentThread().getName()); + } + cmd.nsOpenGLLayer = 0; + cmd.valid = false; + } else if(DEBUG) { + System.err.println("NSOpenGLLayer.Detach: Skipped "+toHexString(cmd.nsOpenGLLayer)+", drawableHandle "+toHexString(drawable.getHandle())+" - "+Thread.currentThread().getName()); + } + } + } + } + @Override public void associateDrawable(boolean bound) { - final OffscreenLayerSurface backingLayerHost = NativeWindowFactory.getOffscreenLayerSurface(drawable.getNativeSurface(), true); + backingLayerHost = NativeWindowFactory.getOffscreenLayerSurface(drawable.getNativeSurface(), true); if(DEBUG) { System.err.println("MaxOSXCGLContext.NSOpenGLImpl.associateDrawable: "+bound+", ctx "+toHexString(contextHandle)+", hasBackingLayerHost "+(null!=backingLayerHost)); + // Thread.dumpStack(); } if( bound ) { - if( null != backingLayerHost ) { - if( 0 != nsOpenGLLayer ) { // FIXME: redundant - throw new InternalError("Lifecycle: bound=true, hasBackingLayerHost=true, but 'nsOpenGLLayer' is already/still set local: "+nsOpenGLLayer+", "+this); - } - nsOpenGLLayer = backingLayerHost.getAttachedSurfaceLayer(); - if( 0 != nsOpenGLLayer ) { // FIXME: redundant - throw new InternalError("Lifecycle: bound=true, hasBackingLayerHost=true, but 'nsOpenGLLayer' is already/still set on backingLayerHost: "+nsOpenGLLayer+", "+this); - } + if( null != backingLayerHost ) { + final GLCapabilitiesImmutable chosenCaps; + final long ctx; + final int texID; + final long pbufferHandle; + final int gl3ShaderProgramName; // // handled layered surface // - final GLCapabilitiesImmutable chosenCaps = drawable.getChosenGLCapabilities(); - final long ctx = MacOSXCGLContext.this.getHandle(); - final int texID; + chosenCaps = drawable.getChosenGLCapabilities(); + ctx = MacOSXCGLContext.this.getHandle(); final long drawableHandle = drawable.getHandle(); - final long pbufferHandle; if(drawable instanceof GLFBODrawableImpl) { final GLFBODrawableImpl fbod = (GLFBODrawableImpl)drawable; texID = fbod.getTextureBuffer(GL.GL_FRONT).getName(); @@ -657,7 +776,6 @@ public abstract class MacOSXCGLContext extends GLContextImpl if(0>=lastWidth || 0>=lastHeight || !drawable.isRealized()) { throw new GLException("Drawable not realized yet or invalid texture size, texSize "+lastWidth+"x"+lastHeight+", "+drawable); } - final int gl3ShaderProgramName; if( MacOSXCGLContext.this.isGL3core() ) { if( null == gl3ShaderProgram) { gl3ShaderProgram = createCALayerShader(MacOSXCGLContext.this.gl.getGL3()); @@ -665,88 +783,42 @@ public abstract class MacOSXCGLContext extends GLContextImpl gl3ShaderProgramName = gl3ShaderProgram.program(); } else { gl3ShaderProgramName = 0; - } + } - /** - * NSOpenGLLayer creation and it's attachment is performed on the main w/o blocking, - * due to OSX main-thread requirements. - * Note: It somewhat works from another thread, however, - * GC-dealloc of the 'released' resources would happen very late! - * - * NSOpenGLLayer initialization creates it's own GL ctx sharing - * this ctx, hence we have to lock this ctx in the main-thread. - * - * Locking of this ctx while creation and attachment - * also gives us good means of synchronization, i.e. it will be - * performed after this thread ends it's associateDrawable() [makeCurrent(), setDrawable(..)] - * and before the next display cycle involving makeCurrent(). - */ - OSXUtil.RunOnMainThread(false, new Runnable() { - public void run() { - if (DEBUG) { - System.err.println("NS create nsOpenGLLayer.0 "+Thread.currentThread().getName()); - } - final long cglCtx = CGL.getCGLContext(ctx); - if(0 == cglCtx) { - throw new GLException("Null CGLContext for: "+MacOSXCGLContext.this); - } - if( CGL.kCGLNoError != CGL.CGLLockContext(cglCtx) ) { - throw new GLException("Could not lock CGLContext for: "+MacOSXCGLContext.this); - } - try { - nsOpenGLLayer = CGL.createNSOpenGLLayer(ctx, gl3ShaderProgramName, pixelFormat, pbufferHandle, texID, chosenCaps.isBackgroundOpaque(), lastWidth, lastHeight); - if (DEBUG) { - System.err.println("NS create nsOpenGLLayer.2 "+Thread.currentThread().getName()+": "+toHexString(nsOpenGLLayer)+" w/ pbuffer "+toHexString(pbufferHandle)+", texID "+texID+", texSize "+lastWidth+"x"+lastHeight+", "+drawable); - } - backingLayerHost.attachSurfaceLayer(nsOpenGLLayer); - setSwapInterval(1); // enabled per default in layered surface - } catch (Throwable t) { - throw new GLException("createNSOpenGLLayer failed for: "+MacOSXCGLContext.this, t); - } finally { - if(CGL.kCGLNoError != CGL.CGLUnlockContext(cglCtx)) { - throw new GLException("Could not unlock CGLContext for: "+MacOSXCGLContext.this); - } - } - if (DEBUG) { - System.err.println("NS create nsOpenGLLayer.X "+Thread.currentThread().getName()); - } - } - }); - CGL.setContextView(contextHandle, 0); // [ctx clearDrawable] + // All CALayer lifecycle ops are deferred on main-thread + attachCALayerCmd = new AttachNSOpenGLLayer( + backingLayerHost, ctx, gl3ShaderProgramName, pixelFormat, pbufferHandle, texID, + chosenCaps.isBackgroundOpaque(), lastWidth, lastHeight ); + OSXUtil.RunOnMainThread(false, attachCALayerCmd); } else { // -> null == backingLayerHost lastWidth = drawable.getWidth(); lastHeight = drawable.getHeight(); boolean[] isPBuffer = { false }; boolean[] isFBO = { false }; - CGL.setContextView(contextHandle, getNSViewHandle(isPBuffer, isFBO)); // will call [ctx clearDrawable] if view == 0, otherwise [ctx setView: view] if valid + CGL.setContextView(contextHandle, getNSViewHandle(isPBuffer, isFBO)); } } else { // -> !bound - if( 0 != nsOpenGLLayer ) { - if( null == backingLayerHost ) { // FIXME: redundant - throw new InternalError("Lifecycle: bound=false, hasNSOpneGLLayer=true, but 'backingLayerHost' is null local: "+nsOpenGLLayer+", "+this); + if( null != backingLayerHost ) { + final AttachNSOpenGLLayer cmd = attachCALayerCmd; + attachCALayerCmd = null; + if( 0 != cmd.pbuffer ) { + CGL.setContextPBuffer(contextHandle, 0); } - - if (DEBUG) { - System.err.println("NS destroy nsOpenGLLayer "+toHexString(nsOpenGLLayer)+", "+drawable); - } - if( backingLayerHost.isSurfaceLayerAttached() ) { - // still having a valid OLS attached to surface (parent OLS could have been removed) - backingLayerHost.detachSurfaceLayer(); - } - // All CALayer lifecycle calls are deferred on main-thread, so is this. - final long _nsOpenGLLayer = nsOpenGLLayer; - nsOpenGLLayer = 0; - OSXUtil.RunOnMainThread(false, new Runnable() { - public void run() { - CGL.releaseNSOpenGLLayer(_nsOpenGLLayer); - } - }); - if( null != gl3ShaderProgram ) { - gl3ShaderProgram.destroy(MacOSXCGLContext.this.gl.getGL3()); - gl3ShaderProgram = null; + synchronized(cmd) { + if( !cmd.valid ) { + cmd.valid = true; // skip pending creation + } else { + // All CALayer lifecycle ops are deferred on main-thread + OSXUtil.RunOnMainThread(false, new DetachNSOpenGLLayer(cmd)); + if( null != gl3ShaderProgram ) { + gl3ShaderProgram.destroy(MacOSXCGLContext.this.gl.getGL3()); + gl3ShaderProgram = null; + } + } } } - CGL.setContextView(contextHandle, 0); // [ctx clearDrawable] + CGL.clearDrawable(contextHandle); + backingLayerHost = null; } } @@ -832,65 +904,83 @@ public abstract class MacOSXCGLContext extends GLContextImpl @Override public boolean setSwapInterval(int interval) { - if(0 != nsOpenGLLayer) { - CGL.setNSOpenGLLayerSwapInterval(nsOpenGLLayer, interval); + final AttachNSOpenGLLayer cmd = attachCALayerCmd; + if(null != cmd) { + synchronized(cmd) { + if( cmd.valid && 0 != cmd.nsOpenGLLayer) { + setSwapIntervalImpl(cmd.nsOpenGLLayer, interval); + return true; + } + } + } + setSwapIntervalImpl(0, interval); + return true; + } + + private void setSwapIntervalImpl(final long l, int interval) { + if( 0 != l ) { + CGL.setNSOpenGLLayerSwapInterval(l, interval); if( 0 < interval ) { - vsyncTimeout = interval * (int)screenVSyncTimeout + 1000; // +1ms + vsyncTimeout = interval * screenVSyncTimeout + 1000; // +1ms } if(DEBUG) { System.err.println("NS setSwapInterval: "+interval+" -> "+vsyncTimeout+" micros"); } } + if(DEBUG) { System.err.println("CGL setSwapInterval: "+interval); } CGL.setSwapInterval(contextHandle, interval); - return true; } - + private int skipSync=0; @Override public boolean swapBuffers() { - final boolean res; - if( 0 != nsOpenGLLayer ) { - if( validateDrawableSizeConfig(contextHandle) ) { - // skip wait-for-vsync for a few frames if size has changed, - // allowing to update the texture IDs ASAP. - skipSync = 10; - } - - final int texID; - final boolean valid; - final boolean isFBO = drawable instanceof GLFBODrawableImpl; - if( isFBO ){ - texID = ((GLFBODrawableImpl)drawable).getTextureBuffer(GL.GL_FRONT).getName(); - valid = 0 != texID; - } else { - texID = 0; - valid = 0 != drawable.getHandle(); - } - if(valid) { - if(0 == skipSync) { - // If v-sync is disabled, frames will be drawn as quickly as possible w/o delay, - // while still synchronizing w/ CALayer. - // If v-sync is enabled wait until next swap interval (v-sync). - CGL.waitUntilNSOpenGLLayerIsReady(nsOpenGLLayer, vsyncTimeout); - } else { - skipSync--; - } - res = CGL.flushBuffer(contextHandle); - if(res) { - if(isFBO) { - // trigger CALayer to update incl. possible surface change (texture) - CGL.setNSOpenGLLayerNeedsDisplayFBO(nsOpenGLLayer, texID); + final AttachNSOpenGLLayer cmd = attachCALayerCmd; + if(null != cmd) { + synchronized(cmd) { + if( cmd.valid && 0 != cmd.nsOpenGLLayer) { + if( validateDrawableSizeConfig(contextHandle) ) { + // skip wait-for-vsync for a few frames if size has changed, + // allowing to update the texture IDs ASAP. + skipSync = 10; + } + + final boolean res; + final int texID; + final boolean valid; + final boolean isFBO = drawable instanceof GLFBODrawableImpl; + if( isFBO ){ + texID = ((GLFBODrawableImpl)drawable).getTextureBuffer(GL.GL_FRONT).getName(); + valid = 0 != texID; + } else { + texID = 0; + valid = 0 != drawable.getHandle(); + } + if(valid) { + res = CGL.flushBuffer(contextHandle); + if(res) { + if(0 == skipSync) { + // If v-sync is disabled, frames will be drawn as quickly as possible w/o delay, + // while still synchronizing w/ CALayer. + // If v-sync is enabled wait until next swap interval (v-sync). + CGL.waitUntilNSOpenGLLayerIsReady(cmd.nsOpenGLLayer, vsyncTimeout); + } else { + skipSync--; + } + if(isFBO) { + // trigger CALayer to update incl. possible surface change (texture) + CGL.setNSOpenGLLayerNeedsDisplayFBO(cmd.nsOpenGLLayer, texID); + } else { + // trigger CALayer to update incl. possible surface change (new pbuffer handle) + CGL.setNSOpenGLLayerNeedsDisplayPBuffer(cmd.nsOpenGLLayer, drawable.getHandle()); + } + } } else { - // trigger CALayer to update incl. possible surface change (new pbuffer handle) - CGL.setNSOpenGLLayerNeedsDisplayPBuffer(nsOpenGLLayer, drawable.getHandle()); + res = true; } + return res; } - } else { - res = true; } - } else { - res = CGL.flushBuffer(contextHandle); } - return res; + return CGL.flushBuffer(contextHandle); } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 15a0f550f..16d4a07ef 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -85,7 +85,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected long drawable; protected Rectangle bounds; protected Insets insets; - private long offscreenSurfaceLayer; + private volatile long offscreenSurfaceLayer; private long drawable_old; @@ -135,12 +135,12 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected synchronized void invalidate() { if(DEBUG) { - System.err.println("JAWTWindow.invalidate()"); + System.err.println("JAWTWindow.invalidate() - "+Thread.currentThread().getName()); + if( isSurfaceLayerAttached() ) { + System.err.println("OffscreenSurfaceLayer still attached: 0x"+Long.toHexString(offscreenSurfaceLayer)); + } // Thread.dumpStack(); } - if( isSurfaceLayerAttached() ) { - detachSurfaceLayer(); - } invalidateNative(); jawt = null; isOffscreenLayerSurface = false; @@ -227,21 +227,16 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if( !isOffscreenLayerSurfaceEnabled() ) { throw new NativeWindowException("Not an offscreen layer surface"); } - int lockRes = lockSurface(); - if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { - throw new NativeWindowException("Could not lock (offscreen layer): "+this); - } - try { - if(DEBUG) { - System.err.println("JAWTWindow.attachSurfaceHandle: "+toHexString(layerHandle) + ", bounds "+bounds); - } - attachSurfaceLayerImpl(layerHandle); - offscreenSurfaceLayer = layerHandle; - } finally { - unlockSurface(); + if(DEBUG) { + System.err.println("JAWTWindow.attachSurfaceHandle: "+toHexString(layerHandle) + ", bounds "+bounds); } + attachSurfaceLayerImpl(layerHandle); + offscreenSurfaceLayer = layerHandle; + layoutSurfaceLayerImpl(layerHandle, getWidth(), getHeight()); + } + protected void attachSurfaceLayerImpl(final long layerHandle) { + throw new UnsupportedOperationException("offscreen layer not supported"); } - protected abstract void attachSurfaceLayerImpl(final long layerHandle); /** * Layout the offscreen layer according to the implementing class's constraints. @@ -256,38 +251,39 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, * @see #isOffscreenLayerSurfaceEnabled() * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false */ - protected void layoutSurfaceLayerImpl() {} + protected void layoutSurfaceLayerImpl(long layerHandle, int width, int height) {} private final void layoutSurfaceLayerIfEnabled() throws NativeWindowException { if( isOffscreenLayerSurfaceEnabled() && 0 != offscreenSurfaceLayer ) { - layoutSurfaceLayerImpl(); + layoutSurfaceLayerImpl(offscreenSurfaceLayer, getWidth(), getHeight()); } } @Override public final void detachSurfaceLayer() throws NativeWindowException { - if( !isOffscreenLayerSurfaceEnabled() ) { - throw new java.lang.UnsupportedOperationException("Not an offscreen layer surface"); - } if( 0 == offscreenSurfaceLayer) { throw new NativeWindowException("No offscreen layer attached: "+this); } - int lockRes = lockSurface(); - if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { - throw new NativeWindowException("Could not lock (offscreen layer): "+this); - } - try { - if(DEBUG) { - System.err.println("JAWTWindow.detachSurfaceHandle(): osh "+toHexString(offscreenSurfaceLayer)); - } - detachSurfaceLayerImpl(offscreenSurfaceLayer); - offscreenSurfaceLayer = 0; - } finally { - unlockSurface(); + if(DEBUG) { + System.err.println("JAWTWindow.detachSurfaceHandle(): osh "+toHexString(offscreenSurfaceLayer)); } + detachSurfaceLayerImpl(offscreenSurfaceLayer, detachSurfaceLayerNotify); } - protected abstract void detachSurfaceLayerImpl(final long layerHandle); + private final Runnable detachSurfaceLayerNotify = new Runnable() { + @Override + public void run() { + offscreenSurfaceLayer = 0; + } + }; + + /** + * @param detachNotify Runnable to be called before native detachment + */ + protected void detachSurfaceLayerImpl(final long layerHandle, final Runnable detachNotify) { + throw new UnsupportedOperationException("offscreen layer not supported"); + } + @Override public final long getAttachedSurfaceLayer() { @@ -305,6 +301,11 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, getPrivateGraphicsConfiguration().setChosenCapabilities(caps); } + @Override + public final RecursiveLock getLock() { + return surfaceLock; + } + // // SurfaceUpdateListener // diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index 8c02a68bb..1826008ad 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -27,6 +27,8 @@ */ package javax.media.nativewindow; +import com.jogamp.common.util.locks.RecursiveLock; + /** * Interface specifying the offscreen layer surface protocol. */ @@ -60,4 +62,7 @@ public interface OffscreenLayerSurface { /** Sets the capabilities of this instance, allowing upstream API's to refine it, i.e. OpenGL related settings. */ public void setChosenCapabilities(CapabilitiesImmutable caps); + /** Returns the recursive lock object of this surface, which synchronizes multithreaded access. */ + public RecursiveLock getLock(); + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index d11d24664..9f76392a9 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -69,16 +69,18 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } } + @Override protected void invalidateNative() { if(DEBUG) { System.err.println("MacOSXJAWTWindow.invalidateNative(): osh-enabled "+isOffscreenLayerSurfaceEnabled()+ - ", osh-set "+offscreenSurfaceHandleSet+ - ", osh "+toHexString(offscreenSurfaceHandle)+ - ", rsh "+toHexString(rootSurfaceLayer)+ + ", osd-set "+offscreenSurfaceDrawableSet+ + ", osd "+toHexString(offscreenSurfaceDrawable)+ + ", osl "+toHexString(getAttachedSurfaceLayer())+ + ", rsl "+toHexString(rootSurfaceLayer)+ ", wh "+toHexString(windowHandle)+" - "+Thread.currentThread().getName()); } - offscreenSurfaceHandle=0; - offscreenSurfaceHandleSet=false; + offscreenSurfaceDrawable=0; + offscreenSurfaceDrawableSet=false; if( isOffscreenLayerSurfaceEnabled() ) { if(0 != windowHandle) { OSXUtil.DestroyNSWindow(windowHandle); @@ -108,29 +110,41 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { jawt.FreeDrawingSurface(ds); } } - OSXUtil.DestroyCALayer(rootSurfaceLayer); - rootSurfaceLayer = 0; + + OSXUtil.RunOnMainThread(false, new Runnable() { + public void run() { + OSXUtil.DestroyCALayer(rootSurfaceLayer, false); + rootSurfaceLayer = 0; + } + }); } } windowHandle=0; } + @Override protected void attachSurfaceLayerImpl(final long layerHandle) { OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, getWidth(), getHeight()); } - protected void layoutSurfaceLayerImpl() { - final long osl = getAttachedSurfaceLayer(); - final int w = getWidth(); - final int h = getHeight(); + @Override + protected void layoutSurfaceLayerImpl(long layerHandle, int width, int height) { if(DEBUG) { - System.err.println("JAWTWindow.fixSurfaceLayerLayout: "+toHexString(osl) + ", bounds "+bounds+", "+w+"x"+h); + System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", "+width+"x"+height+"; "+this); } - OSXUtil.FixCALayerLayout(rootSurfaceLayer, osl, w, h); + OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, width, height); } - protected void detachSurfaceLayerImpl(final long layerHandle) { - OSXUtil.RemoveCASublayer(rootSurfaceLayer, layerHandle); + @Override + protected void detachSurfaceLayerImpl(final long layerHandle, final Runnable detachNotify) { + OSXUtil.RunOnMainThread(false, new Runnable() { + public void run() { + final long l = MacOSXJAWTWindow.this.getAttachedSurfaceLayer(); + if( 0 != l ) { + detachNotify.run(); + OSXUtil.RemoveCASublayer(rootSurfaceLayer, layerHandle, false); + } + } } ); } @Override @@ -140,7 +154,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { @Override public final long getSurfaceHandle() { - return offscreenSurfaceHandleSet ? offscreenSurfaceHandle : drawable /* super.getSurfaceHandle() */ ; + return offscreenSurfaceDrawableSet ? offscreenSurfaceDrawable : drawable /* super.getSurfaceHandle() */ ; } public void setSurfaceHandle(long surfaceHandle) { @@ -150,8 +164,8 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { if(DEBUG) { System.err.println("MacOSXJAWTWindow.setSurfaceHandle(): "+toHexString(surfaceHandle)); } - this.offscreenSurfaceHandle = surfaceHandle; - this.offscreenSurfaceHandleSet = true; + this.offscreenSurfaceDrawable = surfaceHandle; + this.offscreenSurfaceDrawableSet = true; } protected JAWT fetchJAWTImpl() throws NativeWindowException { @@ -257,7 +271,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } if(null != errMsg) { if(0 != rootSurfaceLayer) { - OSXUtil.DestroyCALayer(rootSurfaceLayer); + OSXUtil.DestroyCALayer(rootSurfaceLayer, true); rootSurfaceLayer = 0; } if(0 != windowHandle) { @@ -329,11 +343,11 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { private JAWT_MacOSXDrawingSurfaceInfo macosxdsi; - private long rootSurfaceLayer = 0; // attached to the JAWT_SurfaceLayer + private volatile long rootSurfaceLayer = 0; // attached to the JAWT_SurfaceLayer private long windowHandle = 0; - private long offscreenSurfaceHandle = 0; - private boolean offscreenSurfaceHandleSet = false; + private long offscreenSurfaceDrawable = 0; + private boolean offscreenSurfaceDrawableSet = false; // Workaround for instance of 4796548 private boolean firstLock = true; diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java index 5d1d43792..905a313d5 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java @@ -64,13 +64,6 @@ public class WindowsJAWTWindow extends JAWTWindow { windowHandle = 0; } - protected void attachSurfaceLayerImpl(final long layerHandle) { - throw new UnsupportedOperationException("offscreen layer not supported"); - } - protected void detachSurfaceLayerImpl(final long layerHandle) { - throw new UnsupportedOperationException("offscreen layer not supported"); - } - protected JAWT fetchJAWTImpl() throws NativeWindowException { return JAWTUtil.getJAWT(false); // no offscreen } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java index 467809284..2e5dc7fb5 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java @@ -59,13 +59,6 @@ public class X11JAWTWindow extends JAWTWindow { protected void invalidateNative() { } - protected void attachSurfaceLayerImpl(final long layerHandle) { - throw new UnsupportedOperationException("offscreen layer not supported"); - } - protected void detachSurfaceLayerImpl(final long layerHandle) { - throw new UnsupportedOperationException("offscreen layer not supported"); - } - protected JAWT fetchJAWTImpl() throws NativeWindowException { return JAWTUtil.getJAWT(false); // no offscreen } diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 703c3d972..4b102be00 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -138,11 +138,15 @@ public class OSXUtil implements ToolkitProperties { /** * Create a CALayer suitable to act as a root CALayer. - * @see #DestroyCALayer(long) + * @see #DestroyCALayer(long, boolean) * @see #AddCASublayer(long, long) */ public static long CreateCALayer(final int x, final int y, final int width, final int height) { - return CreateCALayer0(x, y, width, height); + final long l = CreateCALayer0(x, y, width, height); + if(DEBUG) { + System.err.println("OSXUtil.CreateCALayer: 0x"+Long.toHexString(l)+" - "+Thread.currentThread().getName()); + } + return l; } /** @@ -156,7 +160,7 @@ public class OSXUtil implements ToolkitProperties { * they will be used for creation. *

        * @see #CreateCALayer(int, int, int, int) - * @see #RemoveCASublayer(long, long) + * @see #RemoveCASublayer(long, long, boolean) */ public static void AddCASublayer(final long rootCALayer, final long subCALayer, final int width, final int height) { if(0==rootCALayer || 0==subCALayer) { @@ -164,6 +168,9 @@ public class OSXUtil implements ToolkitProperties { } RunOnMainThread(false, new Runnable() { public void run() { + if(DEBUG) { + System.err.println("OSXUtil.AttachCALayer: 0x"+Long.toHexString(subCALayer)+" - "+Thread.currentThread().getName()); + } AddCASublayer0(rootCALayer, subCALayer, width, height); } }); @@ -193,32 +200,48 @@ public class OSXUtil implements ToolkitProperties { } /** - * Detach a sub CALayer from the root CALayer on the main-thread w/o blocking. + * Detach a sub CALayer from the root CALayer. + * @param onMainThread if true method will be performed on the main-thread w/o blocking. */ - public static void RemoveCASublayer(final long rootCALayer, final long subCALayer) { + public static void RemoveCASublayer(final long rootCALayer, final long subCALayer, boolean onMainThread) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } - RunOnMainThread(false, new Runnable() { + final Runnable action = new Runnable() { public void run() { + if(DEBUG) { + System.err.println("OSXUtil.DetachCALayer: 0x"+Long.toHexString(subCALayer)+" - "+Thread.currentThread().getName()); + } RemoveCASublayer0(rootCALayer, subCALayer); - } - }); + } }; + if( onMainThread ) { + RunOnMainThread(false, action); + } else { + action.run(); + } } /** - * Destroy a CALayer on main-thread w/o blocking. + * Destroy a CALayer. + * @param onMainThread if true method will be performed on the main-thread w/o blocking. * @see #CreateCALayer(int, int, int, int) */ - public static void DestroyCALayer(final long caLayer) { + public static void DestroyCALayer(final long caLayer, boolean onMainThread) { if(0==caLayer) { throw new IllegalArgumentException("caLayer 0x"+Long.toHexString(caLayer)); } - RunOnMainThread(false, new Runnable() { + final Runnable action = new Runnable() { public void run() { + if(DEBUG) { + System.err.println("OSXUtil.DestroyCALayer: 0x"+Long.toHexString(caLayer)+" - "+Thread.currentThread().getName()); + } DestroyCALayer0(caLayer); - } - }); + } }; + if( onMainThread ) { + RunOnMainThread(false, action); + } else { + action.run(); + } } /** @@ -238,7 +261,7 @@ public class OSXUtil implements ToolkitProperties { // otherwise we may freeze the OSX main thread. Throwable throwable = null; final Object sync = new Object(); - final RunnableTask rt = new RunnableTask( runnable, waitUntilDone ? sync : null, true ); + final RunnableTask rt = new RunnableTask( runnable, waitUntilDone ? sync : null, true, waitUntilDone ? null : System.err ); synchronized(sync) { RunOnMainThread0(rt); if( waitUntilDone ) { @@ -258,6 +281,16 @@ public class OSXUtil implements ToolkitProperties { } } + /** + * Run later on current OSX thread. + * + * @param runnable + * @param delay delay to run the runnable in milliseconds + */ + public static void RunLater(Runnable runnable, int delay) { + RunLater0(new RunnableTask( runnable, null, true, System.err ), delay); + } + private static Runnable _nop = new Runnable() { public void run() {}; }; /** Issues a {@link #RunOnMainThread(boolean, Runnable)} w/ an NOP runnable, while waiting until done. */ @@ -282,7 +315,7 @@ public class OSXUtil implements ToolkitProperties { // otherwise we may freeze the OSX main thread. Throwable throwable = null; final Object sync = new Object(); - final FunctionTask rt = new FunctionTask( func, waitUntilDone ? sync : null, true ); + final FunctionTask rt = new FunctionTask( func, waitUntilDone ? sync : null, true, waitUntilDone ? null : System.err ); synchronized(sync) { rt.setArgs(args); RunOnMainThread0(rt); @@ -349,6 +382,7 @@ public class OSXUtil implements ToolkitProperties { private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); private static native void RunOnMainThread0(Runnable runnable); + private static native void RunLater0(Runnable runnable, int delay); private static native boolean IsMainThread0(); private static native int GetScreenRefreshRate0(int scrn_idx); } diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index d902b0f09..a3c2a5dc8 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -43,9 +43,7 @@ import java.security.PrivilegedAction; import java.util.Set; import javax.media.nativewindow.NativeWindow; -import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.OffscreenLayerOption; -import javax.media.nativewindow.OffscreenLayerSurface; import javax.media.nativewindow.WindowClosingProtocol; import javax.swing.MenuSelectionManager; @@ -615,12 +613,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto configureNewtChild(false); newtChild.setVisible(false); - // Detach OLS early.. - final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(newtChild, true); - if(null != ols && ols.isSurfaceLayerAttached()) { - ols.detachSurfaceLayer(); - } - newtChild.reparentWindow(null); // will destroy context (offscreen -> onscreen) and implicit detachSurfaceLayer (if still attached) + newtChild.reparentWindow(null); // will destroy context (offscreen -> onscreen) and implicit detachSurfaceLayer if(DEBUG) { System.err.println("NewtCanvasAWT.detachNewtChild.X: win "+newtWinHandleToHexString(newtChild)+", EDTUtil: cur "+newtChild.getScreen().getDisplay().getEDTUtil()+", comp "+this); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java index 48c3c89b3..c2eebbfd8 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAddRemove01GLCanvasSwingAWT.java @@ -55,13 +55,14 @@ import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; public class TestAddRemove01GLCanvasSwingAWT extends UITestCase { - static long durationPerTest = 50; + static long durationPerTest = 100; static int addRemoveCount = 15; static int pauseEach = 0; static int pauseDuration = 500; static boolean noOnscreenTest = false; static boolean noOffscreenTest = false; - static boolean shallUseOffscreenPBufferLayer = false; + static boolean offscreenPBufferOnly = false; + static boolean offscreenFBOOnly = false; static GLProfile glp; static int width, height; static boolean waitForKey = false; @@ -143,6 +144,9 @@ public class TestAddRemove01GLCanvasSwingAWT extends UITestCase { throws AWTException, InterruptedException, InvocationTargetException { + if(waitForKey) { + UITestCase.waitForKey("Start"); + } for(int i=0; i w1. free g1 of w1 canvas2.setNEWTChild(glWindow1); // put g1 -> w2 + frame1.invalidate(); + frame2.invalidate(); frame1.validate(); frame2.validate(); } @@ -176,6 +178,8 @@ public class TestParenting04AWT extends UITestCase { } canvas1.setNEWTChild(glWindow1); canvas2.setNEWTChild(glWindow2); + frame1.invalidate(); + frame2.invalidate(); frame1.validate(); frame2.validate(); } -- cgit v1.2.3 From 0b242442fba01df86be636f54e3d478aa722d6a7 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 28 Mar 2013 23:24:39 +0100 Subject: Adapt to new version scheme, see GlueGen a3f2ef50ad33c58a240a17fcf03e415d772207c3, etc; Fix NewtVersion, NativeWindowVersion and NewtVersionActivityLauncher NewtVersion, NativeWindowVersion: Also search for extension javax.media.opengl (all packaging) NewtVersionActivityLauncher: Use new launcher URI --- make/build-common.xml | 11 +---- make/build-jogl.xml | 9 +++-- make/build-nativewindow.xml | 9 +++-- make/build-newt.xml | 9 +++-- make/build-test.xml | 14 ++++--- make/build.xml | 13 +++--- make/joglversion | 1 + make/joglversion-test | 3 +- make/joglversion-test-android | 3 +- make/scripts/tests.sh | 12 +++--- make/versions.xml | 47 ---------------------- .../jogamp/nativewindow/NativeWindowVersion.java | 8 ++-- src/newt/classes/com/jogamp/newt/NewtVersion.java | 7 ++-- .../android/NewtVersionActivityLauncher.java | 2 +- 14 files changed, 51 insertions(+), 97 deletions(-) delete mode 100644 make/versions.xml (limited to 'src/nativewindow') diff --git a/make/build-common.xml b/make/build-common.xml index f68cc43be..dd33b1683 100644 --- a/make/build-common.xml +++ b/make/build-common.xml @@ -27,8 +27,6 @@ - - - - - - + diff --git a/make/build-jogl.xml b/make/build-jogl.xml index c481eb0f5..ce532c2b4 100644 --- a/make/build-jogl.xml +++ b/make/build-jogl.xml @@ -150,7 +150,7 @@ value="com/jogamp/opengl/**/swt/**"/> + value="com/jogamp/opengl/util/texture/** com/jogamp/opengl/util/av/* com/jogamp/opengl/util/packrect/** jogamp/opengl/util/av/** jogamp/opengl/util/jpeg/** jogamp/opengl/util/pngj/**"/> @@ -298,7 +298,7 @@ - + @@ -1551,10 +1551,11 @@ tofile="${build.jogl}/manifest.mf" overwrite="true"> - + + - +
        diff --git a/make/build-nativewindow.xml b/make/build-nativewindow.xml index d7ef73a46..6a42d72d4 100644 --- a/make/build-nativewindow.xml +++ b/make/build-nativewindow.xml @@ -149,7 +149,7 @@ - + @@ -794,10 +794,11 @@ tofile="${build.nativewindow}/manifest.mf" overwrite="true"> - + + - + @@ -934,7 +935,7 @@ - + diff --git a/make/build-newt.xml b/make/build-newt.xml index c3b51141f..864e0f93e 100644 --- a/make/build-newt.xml +++ b/make/build-newt.xml @@ -188,7 +188,7 @@ - + @@ -733,10 +733,11 @@ tofile="${build.newt}/manifest.mf" overwrite="true"> - + + - + @@ -907,7 +908,7 @@ - + diff --git a/make/build-test.xml b/make/build-test.xml index da6e3ec29..dd072bddb 100644 --- a/make/build-test.xml +++ b/make/build-test.xml @@ -78,10 +78,11 @@ tofile="${build.test}/manifest-test.mf" overwrite="true"> - + + - + @@ -114,10 +115,11 @@ tofile="${build.test}/manifest-test-android.mf" overwrite="true"> - + + - + @@ -142,8 +144,8 @@ androidmanifest.path="resources/android/AndroidManifest-test.xml" androidresources.path="resources/android/res-test" jarmanifest.path="${build.test}/manifest-test-android.mf" - version.code="${jogl_int_version}" - version.name="${jogl.version.plus}" /> + version.code="${jogamp.version.int}" + version.name="${jogamp.version}" /> diff --git a/make/build.xml b/make/build.xml index 44adf805f..0c6c97d34 100644 --- a/make/build.xml +++ b/make/build.xml @@ -165,8 +165,8 @@ androidmanifest.path="resources/android/AndroidManifest-jogl.xml" androidresources.path="resources/android/res-jogl" jarmanifest.path="${build.jogl}/manifest.mf" - version.code="${jogl_int_version}" - version.name="${jogl.version.plus}" /> + version.code="${jogamp.version.int}" + version.name="${jogamp.version}" /> @@ -241,10 +241,11 @@ tofile="${archive}/README.txt" overwrite="true"> - + + - + @@ -343,10 +344,10 @@ - + - + diff --git a/make/joglversion b/make/joglversion index bf0220fa0..3dc57cf32 100644 --- a/make/joglversion +++ b/make/joglversion @@ -4,6 +4,7 @@ Specification-Version: @BASEVERSION@ Specification-Vendor: JogAmp Community Implementation-Title: Java Bindings for OpenGL Runtime Environment Implementation-Version: @VERSION@ +Implementation-Build: @BUILD_VERSION@ Implementation-Branch: @SCM_BRANCH@ Implementation-Commit: @SCM_COMMIT@ Implementation-Vendor: JogAmp Community diff --git a/make/joglversion-test b/make/joglversion-test index cee93dbb4..b130bb279 100644 --- a/make/joglversion-test +++ b/make/joglversion-test @@ -2,8 +2,9 @@ Manifest-Version: 1.0 Specification-Title: Test Java Bindings for OpenGL API Specification Specification-Version: @BASEVERSION@ Specification-Vendor: JogAmp Community -Implementation-Title: Test Java Bindings for OpenGL Runtime Environment +Implementation-Title: Test JOGL Runtime Environment Implementation-Version: @VERSION@ +Implementation-Build: @BUILD_VERSION@ Implementation-Branch: @SCM_BRANCH@ Implementation-Commit: @SCM_COMMIT@ Implementation-Vendor: JogAmp Community diff --git a/make/joglversion-test-android b/make/joglversion-test-android index 88c35bed1..153b3c3b9 100644 --- a/make/joglversion-test-android +++ b/make/joglversion-test-android @@ -2,8 +2,9 @@ Manifest-Version: 1.0 Specification-Title: Test Java Bindings for OpenGL API Specification Specification-Version: @BASEVERSION@ Specification-Vendor: JogAmp Community -Implementation-Title: Test Java Bindings for OpenGL Runtime Environment on Android +Implementation-Title: Test JOGL Android Runtime Environment Implementation-Version: @VERSION@ +Implementation-Build: @BUILD_VERSION@ Implementation-Branch: @SCM_BRANCH@ Implementation-Commit: @SCM_COMMIT@ Implementation-Vendor: JogAmp Community diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index c5d00fb97..41a06ea90 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -170,7 +170,7 @@ function jrun() { #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT -Djogl.debug.GLContext" #D_ARGS="-Dnewt.debug.Window -Djogl.debug.Animator -Dnewt.debug.Screen" #D_ARGS="-Dnativewindow.debug.JAWT -Dnewt.debug.Window" - D_ARGS="-Dnewt.debug.Window.KeyEvent" + #D_ARGS="-Dnewt.debug.Window.KeyEvent" #D_ARGS="-Dnewt.debug.Window.MouseEvent" #D_ARGS="-Dnewt.debug.Window -Dnativewindow.debug=all" #D_ARGS="-Dnewt.debug.Window -Dnativewindow.debug.JAWT -Djogl.debug.Animator" @@ -294,7 +294,7 @@ function testawtswt() { # #testnoawt com.jogamp.nativewindow.NativeWindowVersion $* #testnoawt com.jogamp.opengl.JoglVersion $* -#testnoawt com.jogamp.newt.NewtVersion $* +testnoawt com.jogamp.newt.NewtVersion $* #testnoawt com.jogamp.newt.opengl.GLWindow $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestFloatUtil01MatrixMatrixMultNOUI $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestPMVMatrix01NEWT $* @@ -433,7 +433,7 @@ function testawtswt() { # #testawt com.jogamp.opengl.test.junit.jogl.newt.TestSwingAWTRobotUsageBeforeJOGLInitBug411 $* #testawt com.jogamp.opengl.test.junit.newt.TestEventSourceNotAWTBug -testawt com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot $* +#testawt com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot $* #testawt com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyEventOrderAWT $* #testawt com.jogamp.opengl.test.junit.newt.event.TestNewtKeyEventAutoRepeatAWT $* @@ -494,8 +494,9 @@ testawt com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot $* # # Texture / TextureUtils # -#testnoawt com.jogamp.opengl.test.junit.jogl.util.TestPNGImage01NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestTexture01AWT +#testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestJPEGImage01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGImage01NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGTextureFromFileAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGTextureFromFileNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite01AWT $* @@ -544,9 +545,6 @@ testawt com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot $* # # regressions # -#Windows -#testawt com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot $* -#testawt com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot $* # osx: #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDrawable02NEWT $* diff --git a/make/versions.xml b/make/versions.xml deleted file mode 100644 index 6256831d3..000000000 --- a/make/versions.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java b/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java index 38bd70a90..29f4964c0 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java @@ -31,6 +31,7 @@ package com.jogamp.nativewindow; import com.jogamp.common.GlueGenVersion; import com.jogamp.common.util.JogampVersion; import com.jogamp.common.util.VersionUtil; + import java.util.jar.Manifest; public class NativeWindowVersion extends JogampVersion { @@ -45,9 +46,10 @@ public class NativeWindowVersion extends JogampVersion { if(null == jogampCommonVersionInfo) { // volatile: ok synchronized(NativeWindowVersion.class) { if( null == jogampCommonVersionInfo ) { - final String packageName = "javax.media.nativewindow"; - final Manifest mf = VersionUtil.getManifest(NativeWindowVersion.class.getClassLoader(), packageName); - jogampCommonVersionInfo = new NativeWindowVersion(packageName, mf); + final String packageName1 = "javax.media.nativewindow"; // atomic packaging - and identity + final String packageName2 = "javax.media.opengl"; // all packaging + final Manifest mf = VersionUtil.getManifest(NativeWindowVersion.class.getClassLoader(), new String[]{ packageName1, packageName2 } ); + jogampCommonVersionInfo = new NativeWindowVersion(packageName1, mf); } } } diff --git a/src/newt/classes/com/jogamp/newt/NewtVersion.java b/src/newt/classes/com/jogamp/newt/NewtVersion.java index 961ffdf6a..9adb7aac5 100644 --- a/src/newt/classes/com/jogamp/newt/NewtVersion.java +++ b/src/newt/classes/com/jogamp/newt/NewtVersion.java @@ -46,9 +46,10 @@ public class NewtVersion extends JogampVersion { if(null == jogampCommonVersionInfo) { // volatile: ok synchronized(NewtVersion.class) { if( null == jogampCommonVersionInfo ) { - final String packageName = "com.jogamp.newt"; - final Manifest mf = VersionUtil.getManifest(NewtVersion.class.getClassLoader(), packageName); - jogampCommonVersionInfo = new NewtVersion(packageName, mf); + final String packageName1 = "com.jogamp.newt"; // atomic packaging - and identity + final String packageName2 = "javax.media.opengl"; // all packaging + final Manifest mf = VersionUtil.getManifest(NativeWindowVersion.class.getClassLoader(), new String[]{ packageName1, packageName2 } ); + jogampCommonVersionInfo = new NewtVersion(packageName1, mf); } } } diff --git a/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivityLauncher.java b/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivityLauncher.java index cb8799b19..9b3c6e24b 100644 --- a/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivityLauncher.java +++ b/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivityLauncher.java @@ -11,7 +11,7 @@ public class NewtVersionActivityLauncher extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - final Uri uri = Uri.parse("launch://jogamp.org/jogamp.newt.driver.android.NewtVersionActivity"); + final Uri uri = Uri.parse("launch://jogamp.org/jogamp.newt.driver.android.NewtVersionActivity?sys=com.jogamp.common&sys=javax.media.opengl&pkg=com.jogamp.opengl.test"); final Intent intent = new Intent("org.jogamp.launcher.action.LAUNCH_ACTIVITY_NORMAL", uri); Log.d(getClass().getSimpleName(), "Launching Activity: "+intent); startActivity (intent); -- cgit v1.2.3 From 15e20956fc6a700c12b54342b6e1320a150ce039 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 3 Apr 2013 18:15:36 +0200 Subject: JAWTWindow: Issue component.repaint() after attachSurfaceLayer(..), otherwise no rendering result might be visible w/o Animator --- src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 16d4a07ef..a71356b1c 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -232,7 +232,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } attachSurfaceLayerImpl(layerHandle); offscreenSurfaceLayer = layerHandle; - layoutSurfaceLayerImpl(layerHandle, getWidth(), getHeight()); + component.repaint(); } protected void attachSurfaceLayerImpl(final long layerHandle) { throw new UnsupportedOperationException("offscreen layer not supported"); -- cgit v1.2.3 From 68526d3f9432ea9c80e444146fc99b4ae1352d50 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 4 Apr 2013 05:34:57 +0200 Subject: OSX/CALayer Threading Part4: Stream all JAWT Root CALayer Operations on OSX Main-Thread Previous code created, set and unset the root CALayer on the current thread, which lead to a very delayed destruction of the root CALayer w/. With Java7 this lead to a possible resource starvation in certain situations, since Java7 uses an CAOpenGLLayer. Similar w/ f354fb204d8973453c538dda78a2c82c87be61dc, creation, set and unset is operated on main-thread. --- .../macosx/MacOSXWindowSystemInterface-calayer.m | 24 +++--- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 97 ++++++++++------------ .../jogamp/nativewindow/macosx/OSXUtil.java | 50 ++++------- src/nativewindow/native/macosx/OSXmisc.m | 44 +++++----- 4 files changed, 95 insertions(+), 120 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index 35c9b6a7f..6738364a7 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -67,29 +67,29 @@ extern GLboolean glIsVertexArray (GLuint array); - (id)initWithFormat:(NSOpenGLPixelFormat *)format shareContext:(NSOpenGLContext *)share { - DBG_PRINT("MyNSOpenGLContext.initWithFormat.0: format %p, share %p\n", format, share); + DBG_PRINT("MyNSOpenGLContext::initWithFormat.0: format %p, share %p\n", format, share); MyNSOpenGLContext * o = [super initWithFormat:format shareContext:share]; - DBG_PRINT("MyNSOpenGLContext.initWithFormat.X: new %p\n", o); + DBG_PRINT("MyNSOpenGLContext::initWithFormat.X: new %p\n", o); return o; } - (void)setView:(NSView *)view { - DBG_PRINT("MyNSOpenGLContext.setView: this.0 %p, view %p\n", self, view); + DBG_PRINT("MyNSOpenGLContext::setView: this.0 %p, view %p\n", self, view); // NSLog(@"MyNSOpenGLContext::setView: %@",[NSThread callStackSymbols]); if(NULL != view) { [super setView:view]; } else { [self clearDrawable]; } - DBG_PRINT("MyNSOpenGLContext.setView.X\n"); + DBG_PRINT("MyNSOpenGLContext::setView.X\n"); } - (void)update { - DBG_PRINT("MyNSOpenGLContext.update: this.0 %p, view %p\n", self, [self view]); + DBG_PRINT("MyNSOpenGLContext::update: this.0 %p, view %p\n", self, [self view]); [super update]; - DBG_PRINT("MyNSOpenGLContext.update.X\n"); + DBG_PRINT("MyNSOpenGLContext::update.X\n"); } #ifdef DBG_LIFECYCLE @@ -132,20 +132,20 @@ extern GLboolean glIsVertexArray (GLuint array); // NSLog(@"MyNSOpenGLContext::dealloc: %@",[NSThread callStackSymbols]); [self clearDrawable]; - DBG_PRINT("MyNSOpenGLContext.dealloc.1 %d\n", CGLRETAINCOUNT(cglCtx)); + DBG_PRINT("MyNSOpenGLContext::dealloc.1 %d\n", CGLRETAINCOUNT(cglCtx)); if( NULL != cglCtx ) { CGLRetainContext( cglCtx ); - DBG_PRINT("MyNSOpenGLContext.dealloc.2 %d\n", CGLRETAINCOUNT(cglCtx)); + DBG_PRINT("MyNSOpenGLContext::dealloc.2 %d\n", CGLRETAINCOUNT(cglCtx)); } [super dealloc]; - DBG_PRINT("MyNSOpenGLContext.dealloc.3 %d\n", CGLRETAINCOUNT(cglCtx)); + DBG_PRINT("MyNSOpenGLContext::dealloc.3 %d\n", CGLRETAINCOUNT(cglCtx)); if( NULL != cglCtx ) { CGLReleaseContext( cglCtx ); - DBG_PRINT("MyNSOpenGLContext.dealloc.4 %d\n", CGLRETAINCOUNT(cglCtx)); + DBG_PRINT("MyNSOpenGLContext::dealloc.4 %d\n", CGLRETAINCOUNT(cglCtx)); CGLDestroyContext( cglCtx ); - DBG_PRINT("MyNSOpenGLContext.dealloc.5 %d\n", CGLRETAINCOUNT(cglCtx)); + DBG_PRINT("MyNSOpenGLContext::dealloc.5 %d\n", CGLRETAINCOUNT(cglCtx)); } - DBG_PRINT("MyNSOpenGLContext.dealloc.X\n"); + DBG_PRINT("MyNSOpenGLContext::dealloc.X\n"); } @end diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 9f76392a9..080504a5c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -85,46 +85,28 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { if(0 != windowHandle) { OSXUtil.DestroyNSWindow(windowHandle); } - if(0 != rootSurfaceLayer) { - final JAWT jawt = getJAWT(); - if( null != jawt ) { - final JAWT_DrawingSurface ds = jawt.GetDrawingSurface(component); - if (ds != null) { - if ( 0 == ( ds.Lock() & JAWTFactory.JAWT_LOCK_ERROR ) ) { - JAWT_DrawingSurfaceInfo dsi = null; - try { - dsi = ds.GetDrawingSurfaceInfo(); - try { - UnsetJAWTRootSurfaceLayer0(dsi.getBuffer(), rootSurfaceLayer); - } catch (Exception e) { - System.err.println("Error clearing JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayer)); - e.printStackTrace(); - } - } finally { - if ( null != dsi ) { - ds.FreeDrawingSurfaceInfo(dsi); - } - ds.Unlock(); - } + OSXUtil.RunOnMainThread(false, new Runnable() { + public void run() { + if( 0 != rootSurfaceLayer ) { + if( 0 != jawtSurfaceLayersHandle) { + UnsetJAWTRootSurfaceLayer0(jawtSurfaceLayersHandle, rootSurfaceLayer); } - jawt.FreeDrawingSurface(ds); - } - } - - OSXUtil.RunOnMainThread(false, new Runnable() { - public void run() { - OSXUtil.DestroyCALayer(rootSurfaceLayer, false); + OSXUtil.DestroyCALayer(rootSurfaceLayer); rootSurfaceLayer = 0; } - }); - } + jawtSurfaceLayersHandle = 0; + } + }); } windowHandle=0; } @Override protected void attachSurfaceLayerImpl(final long layerHandle) { - OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, getWidth(), getHeight()); + OSXUtil.RunOnMainThread(false, new Runnable() { + public void run() { + OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, getWidth(), getHeight()); + } } ); } @Override @@ -139,11 +121,8 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { protected void detachSurfaceLayerImpl(final long layerHandle, final Runnable detachNotify) { OSXUtil.RunOnMainThread(false, new Runnable() { public void run() { - final long l = MacOSXJAWTWindow.this.getAttachedSurfaceLayer(); - if( 0 != l ) { - detachNotify.run(); - OSXUtil.RemoveCASublayer(rootSurfaceLayer, layerHandle, false); - } + detachNotify.run(); + OSXUtil.RemoveCASublayer(rootSurfaceLayer, layerHandle); } } ); } @@ -256,24 +235,32 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } } if(null == errMsg) { - if(0 == rootSurfaceLayer) { - rootSurfaceLayer = OSXUtil.CreateCALayer(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); - if(0 == rootSurfaceLayer) { - errMsg = "Could not create root CALayer"; - } else { - try { - SetJAWTRootSurfaceLayer0(dsi.getBuffer(), rootSurfaceLayer); - } catch(Exception e) { - errMsg = "Could not set JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayer)+", cause: "+e.getMessage(); + jawtSurfaceLayersHandle = GetJAWTSurfaceLayersHandle0(dsi.getBuffer()); + OSXUtil.RunOnMainThread(false, new Runnable() { + public void run() { + String errMsg = null; + if(0 == rootSurfaceLayer && 0 != jawtSurfaceLayersHandle) { + rootSurfaceLayer = OSXUtil.CreateCALayer(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); + if(0 == rootSurfaceLayer) { + errMsg = "Could not create root CALayer"; + } else { + try { + SetJAWTRootSurfaceLayer0(jawtSurfaceLayersHandle, rootSurfaceLayer); + } catch(Exception e) { + errMsg = "Could not set JAWT rootSurfaceLayerHandle "+toHexString(rootSurfaceLayer)+", cause: "+e.getMessage(); + } + } + if(null != errMsg) { + if(0 != rootSurfaceLayer) { + OSXUtil.DestroyCALayer(rootSurfaceLayer); + rootSurfaceLayer = 0; + } + throw new NativeWindowException(errMsg+": "+MacOSXJAWTWindow.this); + } } - } - } + } } ); } if(null != errMsg) { - if(0 != rootSurfaceLayer) { - OSXUtil.DestroyCALayer(rootSurfaceLayer, true); - rootSurfaceLayer = 0; - } if(0 != windowHandle) { OSXUtil.DestroyNSWindow(windowHandle); windowHandle = 0; @@ -326,20 +313,24 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } protected Point getLocationOnScreenNativeImpl(final int x0, final int y0) { return null; } + + private static native long GetJAWTSurfaceLayersHandle0(Buffer jawtDrawingSurfaceInfoBuffer); + /** * Set the given root CALayer in the JAWT surface */ - private static native void SetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); + private static native void SetJAWTRootSurfaceLayer0(long jawtSurfaceLayersHandle, long caLayer); /** * Unset the given root CALayer in the JAWT surface, passing the NIO DrawingSurfaceInfo buffer */ - private static native void UnsetJAWTRootSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer); + private static native void UnsetJAWTRootSurfaceLayer0(long jawtSurfaceLayersHandle, long caLayer); // Variables for lockSurface/unlockSurface private JAWT_DrawingSurface ds; private boolean dsLocked; private JAWT_DrawingSurfaceInfo dsi; + private long jawtSurfaceLayersHandle; private JAWT_MacOSXDrawingSurfaceInfo macosxdsi; diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 4b102be00..1a90c095d 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -138,7 +138,7 @@ public class OSXUtil implements ToolkitProperties { /** * Create a CALayer suitable to act as a root CALayer. - * @see #DestroyCALayer(long, boolean) + * @see #DestroyCALayer(long) * @see #AddCASublayer(long, long) */ public static long CreateCALayer(final int x, final int y, final int width, final int height) { @@ -150,7 +150,7 @@ public class OSXUtil implements ToolkitProperties { } /** - * Attach a sub CALayer to the root CALayer on the main-thread w/o blocking. + * Attach a sub CALayer to the root CALayer *

        * Method will trigger a display * call to the CALayer hierarchy to enforce resource creation if required, e.g. an NSOpenGLContext. @@ -166,14 +166,10 @@ public class OSXUtil implements ToolkitProperties { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } - RunOnMainThread(false, new Runnable() { - public void run() { - if(DEBUG) { - System.err.println("OSXUtil.AttachCALayer: 0x"+Long.toHexString(subCALayer)+" - "+Thread.currentThread().getName()); - } - AddCASublayer0(rootCALayer, subCALayer, width, height); - } - }); + if(DEBUG) { + System.err.println("OSXUtil.AttachCALayer: 0x"+Long.toHexString(subCALayer)+" - "+Thread.currentThread().getName()); + } + AddCASublayer0(rootCALayer, subCALayer, width, height); } /** @@ -201,47 +197,29 @@ public class OSXUtil implements ToolkitProperties { /** * Detach a sub CALayer from the root CALayer. - * @param onMainThread if true method will be performed on the main-thread w/o blocking. */ - public static void RemoveCASublayer(final long rootCALayer, final long subCALayer, boolean onMainThread) { + public static void RemoveCASublayer(final long rootCALayer, final long subCALayer) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } - final Runnable action = new Runnable() { - public void run() { - if(DEBUG) { - System.err.println("OSXUtil.DetachCALayer: 0x"+Long.toHexString(subCALayer)+" - "+Thread.currentThread().getName()); - } - RemoveCASublayer0(rootCALayer, subCALayer); - } }; - if( onMainThread ) { - RunOnMainThread(false, action); - } else { - action.run(); + if(DEBUG) { + System.err.println("OSXUtil.DetachCALayer: 0x"+Long.toHexString(subCALayer)+" - "+Thread.currentThread().getName()); } + RemoveCASublayer0(rootCALayer, subCALayer); } /** * Destroy a CALayer. - * @param onMainThread if true method will be performed on the main-thread w/o blocking. * @see #CreateCALayer(int, int, int, int) */ - public static void DestroyCALayer(final long caLayer, boolean onMainThread) { + public static void DestroyCALayer(final long caLayer) { if(0==caLayer) { throw new IllegalArgumentException("caLayer 0x"+Long.toHexString(caLayer)); } - final Runnable action = new Runnable() { - public void run() { - if(DEBUG) { - System.err.println("OSXUtil.DestroyCALayer: 0x"+Long.toHexString(caLayer)+" - "+Thread.currentThread().getName()); - } - DestroyCALayer0(caLayer); - } }; - if( onMainThread ) { - RunOnMainThread(false, action); - } else { - action.run(); + if(DEBUG) { + System.err.println("OSXUtil.DestroyCALayer: 0x"+Long.toHexString(caLayer)+" - "+Thread.currentThread().getName()); } + DestroyCALayer0(caLayer); } /** diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index d6a63702b..688ef79b8 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -348,10 +348,9 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 - (id)init { - DBG_PRINT("MyCALayer.0\n"); + DBG_PRINT("MyCALayer::init.0\n"); MyCALayer * o = [super init]; - DBG_PRINT("MyNSOpenGLContext.init.X: new %p\n", o); - DBG_PRINT("MyCALayer.0\n"); + DBG_PRINT("MyCALayer::init.X: new %p\n", o); return o; } @@ -593,27 +592,39 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyCALayer0 DBG_PRINT("CALayer::DestroyCALayer0.X: root %p\n", layer); } +/* + * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow + * Method: GetJAWTSurfaceLayersHandle0 + * Signature: (J)J + */ +JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_GetJAWTSurfaceLayersHandle0 + (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer) +{ + JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); + if (NULL == dsi) { + NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); + return 0; + } + id surfaceLayers = (id )dsi->platformInfo; + return (jlong) ((intptr_t) surfaceLayers); +} + /* * Class: Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow * Method: SetJAWTRootSurfaceLayer0 * Signature: (JJ)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_SetJAWTRootSurfaceLayer0 - (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) + (JNIEnv *env, jclass unused, jlong jawtSurfaceLayersHandle, jlong caLayer) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; - JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); - if (NULL == dsi) { - NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); - return; - } + id surfaceLayers = (id )(intptr_t)jawtSurfaceLayersHandle; MyCALayer* layer = (MyCALayer*) (intptr_t) caLayer; - id surfaceLayers = (id )dsi->platformInfo; - DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.0: pre %p -> root %p (refcnt %d)\n", surfaceLayers.layer, layer, (int)[layer retainCount]); + DBG_PRINT("CALayer::SetJAWTRootSurfaceLayer.0: pre %p -> root %p (refcnt %d)\n", [surfaceLayers layer], layer, (int)[layer retainCount]); [surfaceLayers setLayer: [layer retain]]; // Pairs w/ Unset [CATransaction commit]; @@ -628,21 +639,16 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Set * Signature: (JJ)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_UnsetJAWTRootSurfaceLayer0 - (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer) + (JNIEnv *env, jclass unused, jlong jawtSurfaceLayersHandle, jlong caLayer) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; - JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer); - if (NULL == dsi) { - NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer"); - return; - } + id surfaceLayers = (id )(intptr_t)jawtSurfaceLayersHandle; MyCALayer* layer = (MyCALayer*) (intptr_t) caLayer; - id surfaceLayers = (id )dsi->platformInfo; - if(layer != surfaceLayers.layer) { + if(layer != [surfaceLayers layer]) { NativewindowCommon_throwNewRuntimeException(env, "Attached layer %p doesn't match given layer %p\n", surfaceLayers.layer, layer); return; } -- cgit v1.2.3 From 5b47372590ec715647ebbd75d70c41ec7a64485a Mon Sep 17 00:00:00 2001 From: Martin Hegedus Date: Tue, 2 Apr 2013 09:31:41 -0700 Subject: Fix Bug 705 - Make Mesa X11 driver < 8.0 use new Quirk DontCloseX11DisplayConnection --- .../com/jogamp/opengl/GLRendererQuirks.java | 33 +++++++++++++++++-- src/jogl/classes/javax/media/opengl/GLProfile.java | 25 +++++++++++++++ src/jogl/classes/jogamp/opengl/GLContextImpl.java | 32 +++++++++++++++++++ .../classes/jogamp/nativewindow/x11/X11Util.java | 37 +++++++++++++++++++--- 4 files changed, 121 insertions(+), 6 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java b/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java index 715511d1b..7203ba214 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java +++ b/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java @@ -81,12 +81,41 @@ public class GLRendererQuirks { */ public static final int GLFlushBeforeRelease = 7; + // + // The JVM for the following system crashes on the second call to glXDestroyContext after + // XCloseDisplay has been called once. + // + // The following will crash the system: + // XOpenDisplay(A), glXCreateNewContext(A), XOpenDisplay(B), glXCreateNewContext(B), + // glXDestroyContext(A/B), XCloseDisplay(A/B), glXDestroyContext(B/A) (crash) + // + // Dell Latitude D520 + // Intel(R) Core(TM)2 CPU T7200 + // i810 Monitor driver + // Platform LINUX / Linux 2.6.18.8-0.3-default (os), i386 (arch), GENERIC_ABI, 2 cores + // Platform Java Version: 1.6.0_18, VM: Java HotSpot(TM) Server VM, Runtime: Java(TM) SE Runtime Environment + // Platform Java Vendor: Sun Microsystems Inc., http://java.sun.com/, JavaSE: true, Java6: true, AWT enabled: true + // GL Profile GLProfile[GL2/GL2.sw] + // CTX VERSION 2.1 (Compatibility profile, FBO, software) - 2.1 Mesa 7.8.2 + // GL jogamp.opengl.gl4.GL4bcImpl@472d48 + // GL_VENDOR Brian Paul + // GL_RENDERER Mesa X11 + // GL_VERSION 2.1 Mesa 7.8.2 + // + // The error can be reproduced using a C code, thus the error is indpendent of Java and JOGL. + // The work around is to close all the X11 displays upon exit for a "Mesa X11" version < 8. + // At this moment, it is unknown if the error exists in versions greater than 7. + // + // Martin C. Hegedus, March 30, 2013 + // + public static final int DontCloseX11DisplayConnection = 8; + /** Number of quirks known. */ - public static final int COUNT = 8; + public static final int COUNT = 9; private static final String[] _names = new String[] { "NoDoubleBufferedPBuffer", "NoDoubleBufferedBitmap", "NoSetSwapInterval", "NoOffscreenBitmap", "NoSetSwapIntervalPostRetarget", "GLSLBuggyDiscard", - "GLNonCompliant", "GLFlushBeforeRelease" + "GLNonCompliant", "GLFlushBeforeRelease", "DontCloseX11DisplayConnection" }; private final int _bitmask; diff --git a/src/jogl/classes/javax/media/opengl/GLProfile.java b/src/jogl/classes/javax/media/opengl/GLProfile.java index 25bba1725..54ed479a9 100644 --- a/src/jogl/classes/javax/media/opengl/GLProfile.java +++ b/src/jogl/classes/javax/media/opengl/GLProfile.java @@ -64,6 +64,11 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; +// Added to check if X11 Displays should be closed on exit +// Martin C. Hegedus, March 30, 2013 +import com.jogamp.opengl.GLRendererQuirks; +import jogamp.nativewindow.x11.X11Util; + /** * Specifies the the OpenGL profile. * @@ -1524,6 +1529,26 @@ public class GLProfile { final boolean addedEGLProfile = null != defaultEGLDevice ? initProfilesForDevice(defaultEGLDevice) : false; final boolean addedDesktopProfile = null != defaultDesktopDevice ? initProfilesForDevice(defaultDesktopDevice) : false; final boolean addedAnyProfile = addedEGLProfile || addedDesktopProfile ; + + // Added to check if X11 Displays should be closed on exit + // NOTE: This checks defaultEGLDevice and defaultDesktopDevice to determine if XCloseDisplay should be called on exit + // NOTE: These checks must be done after initProfilesForDevice since GLContext must set up the renderer quirks. + // NOTE: At this point the shared resource has already opened a display, created a new context, made it current, and + // released it. Let's cross our fingers that at this point in the code the context will not be destroyed and + // the display closed under any circumstances. + // NOTE: The checks can be tricked if the default screen is using a driver other than X11 and later a X11 Display, + // such as a remote display, is opened. If this occurs then markAllDisplaysUnclosable will not have been + // correctly set. Something to deal with at a later date. + // + // Martin C. Hegedus, March 30, 2013 + if (eglFactory != null && defaultEGLDevice != null && + eglFactory.hasRendererQuirk(defaultEGLDevice,GLRendererQuirks.DontCloseX11DisplayConnection) && + NativeWindowFactory.getNativeWindowType(true) == NativeWindowFactory.TYPE_X11) + X11Util.markAllDisplaysUnclosable(); + if (desktopFactory != null && defaultDesktopDevice != null && + desktopFactory.hasRendererQuirk(defaultDesktopDevice,GLRendererQuirks.DontCloseX11DisplayConnection) && + NativeWindowFactory.getNativeWindowType(true) == NativeWindowFactory.TYPE_X11) + X11Util.markAllDisplaysUnclosable(); if(DEBUG) { System.err.println("GLProfile.init addedAnyProfile "+addedAnyProfile+" (desktop: "+addedDesktopProfile+", egl "+addedEGLProfile+")"); diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index 9f7c9cf57..74bc59c7c 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -1562,9 +1562,41 @@ public abstract class GLContextImpl extends GLContext { quirks[i++] = quirk; } } + + // + // Mesa RENDERER related quirks + // + if( glRendererLowerCase.contains("mesa") ) { + // Added March 30, 2013 + // Martin C. Hegedus + if ( glRendererLowerCase.contains("x11") && getMesaMajorVersion(glVersion) < 8.0 ) { + final int quirk = GLRendererQuirks.DontCloseX11DisplayConnection; + if(DEBUG) { + System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: Mesa X11 < 8 : Renderer=" + glRenderer + ", Version=" +glVersion); + } + quirks[i++] = quirk; + } + } glRendererQuirks = new GLRendererQuirks(quirks, 0, i); } + + // Added by Martin C. Hegedus, March 30, 2013 + private static final int getMesaMajorVersion(String version) { + if (version == null || version.length() <= 0) return -1; + String[] strings = version.trim().split("\\s+"); + if (strings.length <= 0) return -1; + version = strings[strings.length-1]; + int index = version.indexOf("."); + if (index == 0) return -1; + if (index != -1) version = version.substring(0,index); + try { + Integer iNumber = new Integer(version); + return (iNumber == null) ? -1 : iNumber.intValue(); + } catch (Throwable t) { + return -1; + } + } private static final boolean hasFBOImpl(int major, int ctp, ExtensionAvailabilityCache extCache) { diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index c771cd67a..2fb780fa2 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -138,7 +138,13 @@ public class X11Util implements ToolkitProperties { hasX11_EXTENSION_ATIFGLEXTENSION = false; } hasThreadingIssues = ATI_HAS_MULTITHREADING_BUG && ( hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ); - markAllDisplaysUnclosable = ATI_HAS_XCLOSEDISPLAY_BUG && ( hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ); + // A check on nativewindow.debug.X11Util.HasX11CloseDisplayBug added March 30, 2013 + // Martin C. Hegedus + if (!markAllDisplaysUnclosable) { + markAllDisplaysUnclosable = ATI_HAS_XCLOSEDISPLAY_BUG && ( hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ); + if (Debug.isPropertyDefined("nativewindow.debug.X11Util.HasX11CloseDisplayBug", true)) + markAllDisplaysUnclosable = true; + } if(DEBUG) { System.err.println("X11Util.initSingleton(): OK "+isInitOK+"]"+ @@ -178,7 +184,10 @@ public class X11Util implements ToolkitProperties { synchronized(X11Util.class) { if(isInit) { final boolean isJVMShuttingDown = NativeWindowFactory.isJVMShuttingDown() ; - if(DEBUG || openDisplayMap.size() > 0 || reusableDisplayList.size() > 0 || pendingDisplayList.size() > 0) { + // Modified March 30, 2013 so output is not created under "expected" circumstances + // Martin C. Hegedus + if(DEBUG || ((openDisplayMap.size() > 0 || reusableDisplayList.size() > 0 || pendingDisplayList.size() > 0) && + !(reusableDisplayList.size() == pendingDisplayList.size() && markAllDisplaysUnclosable))) { System.err.println("X11Util.Display: Shutdown (JVM shutdown: "+isJVMShuttingDown+ ", open (no close attempt): "+openDisplayMap.size()+"/"+openDisplayList.size()+ ", reusable (open, marked uncloseable): "+reusableDisplayList.size()+ @@ -242,6 +251,20 @@ public class X11Util implements ToolkitProperties { return nullDisplayName; } + // Added March 30, 2013 + // Martin C. Hegedus + public static void markAllDisplaysUnclosable() { + synchronized(globalLock) { + markAllDisplaysUnclosable = true; + for(int i=0; i Date: Tue, 16 Apr 2013 05:50:55 +0200 Subject: Fix Bug 705 - Cleanup & Generalize Commit 5b47372590ec715647ebbd75d70c41ec7a64485a ; Close X11 Display in isDeviceSupported() - Moved GL vendor version parsing to GLVersionNumber - Moved X11Util.markAllDisplaysUnclosable() trigger into SharedResource creation of - X11GLXDrawableFactory - EGLDrawableFactory - GLProfile is back to pre 5b47372590ec715647ebbd75d70c41ec7a64485a, i.e. contains no quirk artifact (clean) - Close X11 Display in X11GLXDrawableFactory.isDeviceSupported() Regression of 9a4fcc7ea4ec61e4ceed791acced734ac04ea270 - TODO: Remove X11Util markAllDisplaysUnclosable detection code ? Notes to Martin: - Use TAB == 4 SPACES - No author names into source code, git commit log is enough. - No need to tag your edits, the diff is enough. --- make/scripts/tests.sh | 4 +- .../com/jogamp/opengl/GLRendererQuirks.java | 66 ++++++++++--------- .../classes/com/jogamp/opengl/JoglVersion.java | 6 +- src/jogl/classes/javax/media/opengl/GLContext.java | 18 ++--- src/jogl/classes/javax/media/opengl/GLProfile.java | 25 ------- src/jogl/classes/jogamp/opengl/GLContextImpl.java | 62 ++++++++--------- .../classes/jogamp/opengl/GLVersionNumber.java | 77 +++++++++++++++------- .../jogamp/opengl/egl/EGLDrawableFactory.java | 12 ++++ .../opengl/x11/glx/X11GLXDrawableFactory.java | 5 ++ .../classes/jogamp/nativewindow/x11/X11Util.java | 73 ++++++++++---------- src/test-native/make.sh | 2 + 11 files changed, 186 insertions(+), 164 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 17b3187e6..fa965d83b 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -306,7 +306,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestPMVMatrix01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestPMVMatrix02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestNEWTCloseX11DisplayBug565 $* -#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile00NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $* @@ -319,7 +319,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMapBufferRead01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestBug669RecursiveGLContext01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestBug669RecursiveGLContext02NEWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestBug692GL3VAO $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestBug692GL3VAO $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT2 $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES1NEWT $* diff --git a/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java b/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java index 7203ba214..0b136d460 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java +++ b/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java @@ -59,7 +59,7 @@ public class GLRendererQuirks { /** SIGSEGV on setSwapInterval() after changing the context's drawable w/ 'Mesa 8.0.4' dri2SetSwapInterval/DRI2 (soft & intel) */ public static final int NoSetSwapIntervalPostRetarget = 4; - /** GLSL discard command leads to undefined behavior or won't get compiled if being used. Appears to happen on Nvidia Tegra2. FIXME: Constrain version. */ + /** GLSL discard command leads to undefined behavior or won't get compiled if being used. Appears to have happened on Nvidia Tegra2, but seems to be fine now. FIXME: Constrain version. */ public static final int GLSLBuggyDiscard = 5; /** @@ -81,41 +81,47 @@ public class GLRendererQuirks { */ public static final int GLFlushBeforeRelease = 7; - // - // The JVM for the following system crashes on the second call to glXDestroyContext after - // XCloseDisplay has been called once. - // - // The following will crash the system: - // XOpenDisplay(A), glXCreateNewContext(A), XOpenDisplay(B), glXCreateNewContext(B), - // glXDestroyContext(A/B), XCloseDisplay(A/B), glXDestroyContext(B/A) (crash) - // - // Dell Latitude D520 - // Intel(R) Core(TM)2 CPU T7200 - // i810 Monitor driver - // Platform LINUX / Linux 2.6.18.8-0.3-default (os), i386 (arch), GENERIC_ABI, 2 cores - // Platform Java Version: 1.6.0_18, VM: Java HotSpot(TM) Server VM, Runtime: Java(TM) SE Runtime Environment - // Platform Java Vendor: Sun Microsystems Inc., http://java.sun.com/, JavaSE: true, Java6: true, AWT enabled: true - // GL Profile GLProfile[GL2/GL2.sw] - // CTX VERSION 2.1 (Compatibility profile, FBO, software) - 2.1 Mesa 7.8.2 - // GL jogamp.opengl.gl4.GL4bcImpl@472d48 - // GL_VENDOR Brian Paul - // GL_RENDERER Mesa X11 - // GL_VERSION 2.1 Mesa 7.8.2 - // - // The error can be reproduced using a C code, thus the error is indpendent of Java and JOGL. - // The work around is to close all the X11 displays upon exit for a "Mesa X11" version < 8. - // At this moment, it is unknown if the error exists in versions greater than 7. - // - // Martin C. Hegedus, March 30, 2013 - // - public static final int DontCloseX11DisplayConnection = 8; + /** + * Closing X11 displays may cause JVM crashes or X11 errors with some buggy drivers + * while being used in concert w/ OpenGL. + *

        + * Some drivers may require X11 displays to be closed in the same order as they were created, + * some may not allow them to be closed at all while resources are being used somehow. + *

        + *

        + * Drivers known exposing such bug: + *

          + *
        • Mesa < 8.0 _with_ X11 software renderer Mesa X11, not with GLX/DRI renderer.
        • + *
        • ATI proprietary Catalyst X11 driver (RENDERER vendor version): + *
            + *
          • 8.78.6
          • + *
          • 8.881
          • + *
          • 8.911
          • + *
          • 9.01.8
          • + *
        • + *
        + *

        + *

        + * TODO: Validate whether Mesa's X11 driver exposes this bug w/ version >= 8, currently we assume not ! + * Impact would be to set this quirk on all 'Mesa X11' software renderer! + *

        + * + *

        + * See Bug 515 - https://jogamp.org/bugzilla/show_bug.cgi?id=515 + * and {@link jogamp.nativewindow.x11.X11Util#ATI_HAS_XCLOSEDISPLAY_BUG}. + *

        + *

        + * See Bug 705 - https://jogamp.org/bugzilla/show_bug.cgi?id=705 + *

        + */ + public static final int DontCloseX11Display = 8; /** Number of quirks known. */ public static final int COUNT = 9; private static final String[] _names = new String[] { "NoDoubleBufferedPBuffer", "NoDoubleBufferedBitmap", "NoSetSwapInterval", "NoOffscreenBitmap", "NoSetSwapIntervalPostRetarget", "GLSLBuggyDiscard", - "GLNonCompliant", "GLFlushBeforeRelease", "DontCloseX11DisplayConnection" + "GLNonCompliant", "GLFlushBeforeRelease", "DontCloseX11Display" }; private final int _bitmask; diff --git a/src/jogl/classes/com/jogamp/opengl/JoglVersion.java b/src/jogl/classes/com/jogamp/opengl/JoglVersion.java index 4246d74c7..11e76ef6f 100644 --- a/src/jogl/classes/com/jogamp/opengl/JoglVersion.java +++ b/src/jogl/classes/com/jogamp/opengl/JoglVersion.java @@ -160,9 +160,11 @@ public class JoglVersion extends JogampVersion { sb.append(Platform.getNewline()); sb.append("GL Profile ").append(gl.getGLProfile()); sb.append(Platform.getNewline()); - sb.append("CTX VERSION ").append(gl.getContext().getGLVersion()); + sb.append("GL Version ").append(ctx.getGLVersion()).append(" [GL ").append(ctx.getGLVersionNumber()).append(", vendor ").append(ctx.getGLVendorVersionNumber()).append("]"); sb.append(Platform.getNewline()); - sb.append("GL ").append(gl); + sb.append("Quirks ").append(ctx.getRendererQuirks()); + sb.append(Platform.getNewline()); + sb.append("Impl. class ").append(gl.getClass().getCanonicalName()); sb.append(Platform.getNewline()); sb.append("GL_VENDOR ").append(gl.glGetString(GL.GL_VENDOR)); sb.append(Platform.getNewline()); diff --git a/src/jogl/classes/javax/media/opengl/GLContext.java b/src/jogl/classes/javax/media/opengl/GLContext.java index be947e5f5..23ca96504 100644 --- a/src/jogl/classes/javax/media/opengl/GLContext.java +++ b/src/jogl/classes/javax/media/opengl/GLContext.java @@ -53,6 +53,7 @@ import jogamp.opengl.GLContextImpl; import com.jogamp.common.os.Platform; import com.jogamp.common.util.VersionNumber; +import com.jogamp.common.util.VersionNumberString; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.opengl.GLExtensions; @@ -126,6 +127,8 @@ public abstract class GLContext { /** Version 3.0. As an OpenGL version, it qualifies for {@link #isGL2()} only */ public static final VersionNumber Version30 = new VersionNumber(3, 0, 0); + protected static final VersionNumber Version80 = new VersionNumber(8, 0, 0); + /** ARB_create_context related: created via ARB_create_context. Cache key value. See {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ protected static final int CTX_IS_ARB_CREATED = 1 << 0; /** ARB_create_context related: desktop compatibility profile. Cache key value. See {@link #isGLCompatibilityProfile()}, {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ @@ -169,9 +172,11 @@ public abstract class GLContext { protected VersionNumber ctxVersion; protected int ctxOptions; protected String ctxVersionString; + protected VersionNumberString ctxVendorVersion; protected VersionNumber ctxGLSLVersion; private int currentSwapInterval; protected GLRendererQuirks glRendererQuirks; + private static final VersionNumberString nullVersion = new VersionNumberString(-1, -1, -1, "n/a"); /** Did the drawable association changed ? see {@link GLRendererQuirks#NoSetSwapIntervalPostRetarget} */ protected boolean drawableRetargeted; @@ -181,7 +186,8 @@ public abstract class GLContext { System.err.println(getThreadName() + ": GLContext.resetStates()"); // Thread.dumpStack(); } - ctxVersion = new VersionNumber(-1, -1, -1); + ctxVersion = nullVersion; + ctxVendorVersion = nullVersion; ctxOptions=0; ctxVersionString=null; ctxGLSLVersion=null; @@ -521,14 +527,9 @@ public abstract class GLContext { } public final StringBuilder append(StringBuilder sb) { - sb.append("OpenGL "); - sb.append(getGLVersionMajor()); - sb.append("."); - sb.append(getGLVersionMinor()); - sb.append(", options 0x"); + sb.append("Version ").append(getGLVersion()).append(" [GL ").append(getGLVersionNumber()).append(", vendor ").append(getGLVendorVersionNumber()); + sb.append("], options 0x"); sb.append(Integer.toHexString(ctxOptions)); - sb.append(", "); - sb.append(getGLVersion()); sb.append(", this "); sb.append(toHexString(hashCode())); sb.append(", handle "); @@ -667,6 +668,7 @@ public abstract class GLContext { * @see #getGLSLVersionNumber() **/ public final VersionNumber getGLVersionNumber() { return ctxVersion; } + public final VersionNumberString getGLVendorVersionNumber() { return ctxVendorVersion; } public final boolean isGLCompatibilityProfile() { return ( 0 != ( CTX_PROFILE_COMPAT & ctxOptions ) ); } public final boolean isGLCoreProfile() { return ( 0 != ( CTX_PROFILE_CORE & ctxOptions ) ); } public final boolean isGLForwardCompatible() { return ( 0 != ( CTX_OPTION_FORWARD & ctxOptions ) ); } diff --git a/src/jogl/classes/javax/media/opengl/GLProfile.java b/src/jogl/classes/javax/media/opengl/GLProfile.java index 54ed479a9..1b6af22d4 100644 --- a/src/jogl/classes/javax/media/opengl/GLProfile.java +++ b/src/jogl/classes/javax/media/opengl/GLProfile.java @@ -64,11 +64,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; -// Added to check if X11 Displays should be closed on exit -// Martin C. Hegedus, March 30, 2013 -import com.jogamp.opengl.GLRendererQuirks; -import jogamp.nativewindow.x11.X11Util; - /** * Specifies the the OpenGL profile. * @@ -1530,26 +1525,6 @@ public class GLProfile { final boolean addedDesktopProfile = null != defaultDesktopDevice ? initProfilesForDevice(defaultDesktopDevice) : false; final boolean addedAnyProfile = addedEGLProfile || addedDesktopProfile ; - // Added to check if X11 Displays should be closed on exit - // NOTE: This checks defaultEGLDevice and defaultDesktopDevice to determine if XCloseDisplay should be called on exit - // NOTE: These checks must be done after initProfilesForDevice since GLContext must set up the renderer quirks. - // NOTE: At this point the shared resource has already opened a display, created a new context, made it current, and - // released it. Let's cross our fingers that at this point in the code the context will not be destroyed and - // the display closed under any circumstances. - // NOTE: The checks can be tricked if the default screen is using a driver other than X11 and later a X11 Display, - // such as a remote display, is opened. If this occurs then markAllDisplaysUnclosable will not have been - // correctly set. Something to deal with at a later date. - // - // Martin C. Hegedus, March 30, 2013 - if (eglFactory != null && defaultEGLDevice != null && - eglFactory.hasRendererQuirk(defaultEGLDevice,GLRendererQuirks.DontCloseX11DisplayConnection) && - NativeWindowFactory.getNativeWindowType(true) == NativeWindowFactory.TYPE_X11) - X11Util.markAllDisplaysUnclosable(); - if (desktopFactory != null && defaultDesktopDevice != null && - desktopFactory.hasRendererQuirk(defaultDesktopDevice,GLRendererQuirks.DontCloseX11DisplayConnection) && - NativeWindowFactory.getNativeWindowType(true) == NativeWindowFactory.TYPE_X11) - X11Util.markAllDisplaysUnclosable(); - if(DEBUG) { System.err.println("GLProfile.init addedAnyProfile "+addedAnyProfile+" (desktop: "+addedDesktopProfile+", egl "+addedEGLProfile+")"); System.err.println("GLProfile.init isAWTAvailable "+isAWTAvailable); diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index 74bc59c7c..3657cacda 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -49,6 +49,7 @@ import com.jogamp.common.os.DynamicLookupHelper; import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; import com.jogamp.common.util.VersionNumber; +import com.jogamp.common.util.VersionNumberString; import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.gluegen.runtime.FunctionAddressResolver; import com.jogamp.gluegen.runtime.ProcAddressTable; @@ -1023,7 +1024,7 @@ public abstract class GLContextImpl extends GLContext { * If major > 0 || minor > 0 : Use passed values, determined at creation time * Otherwise .. don't touch .. */ - private final void setContextVersion(int major, int minor, int ctp, boolean setVersionString) { + private final void setContextVersion(int major, int minor, int ctp, VersionNumberString glVendorVersion, boolean useGL) { if ( 0 == ctp ) { throw new GLException("Invalid GL Version "+major+"."+minor+", ctp "+toHexString(ctp)); } @@ -1032,9 +1033,10 @@ public abstract class GLContextImpl extends GLContext { throw new GLException("Invalid GL Version "+major+"."+minor+", ctp "+toHexString(ctp)); } ctxVersion = new VersionNumber(major, minor, 0); + ctxVersionString = getGLVersion(major, minor, ctxOptions, glVersion); + ctxVendorVersion = glVendorVersion; ctxOptions = ctp; - if(setVersionString) { - ctxVersionString = getGLVersion(major, minor, ctxOptions, gl.glGetString(GL.GL_VERSION)); + if(useGL) { ctxGLSLVersion = null; if(major >= 2) { // >= ES2 || GL2.0 final String glslVersion = gl.glGetString(GL2ES2.GL_SHADING_LANGUAGE_VERSION); @@ -1192,7 +1194,7 @@ public abstract class GLContextImpl extends GLContext { */ private static final VersionNumber getGLVersionNumber(int ctp, String glVersionStr) { if( null != glVersionStr ) { - final GLVersionNumber version = new GLVersionNumber(glVersionStr); + final GLVersionNumber version = GLVersionNumber.create(glVersionStr); if ( version.isValid() ) { int[] major = new int[] { version.getMajor() }; int[] minor = new int[] { version.getMinor() }; @@ -1384,7 +1386,9 @@ public abstract class GLContextImpl extends GLContext { ctxProfileBits &= ~GLContext.CTX_IMPL_ES2_COMPAT; } - setRendererQuirks(major, minor, ctxProfileBits); + final VersionNumberString vendorVersion = GLVersionNumber.createVendorVersion(glVersion); + + setRendererQuirks(major, minor, ctxProfileBits, vendorVersion); if( strictMatch && glRendererQuirks.exist(GLRendererQuirks.GLNonCompliant) ) { if(DEBUG) { @@ -1445,7 +1449,7 @@ public abstract class GLContextImpl extends GLContext { } } else { extensionAvailability = new ExtensionAvailabilityCache(); - setContextVersion(major, minor, ctxProfileBits, false); // pre-set of GL version, required for extension cache usage + setContextVersion(major, minor, ctxProfileBits, vendorVersion, false); // pre-set of GL version, required for extension cache usage extensionAvailability.reset(this); synchronized(mappedContextTypeObjectLock) { mappedExtensionAvailabilityCache.put(contextFQN, extensionAvailability); @@ -1469,7 +1473,7 @@ public abstract class GLContextImpl extends GLContext { // // Set GL Version (complete w/ version string) // - setContextVersion(major, minor, ctxProfileBits, true); + setContextVersion(major, minor, ctxProfileBits, vendorVersion, true); setDefaultSwapInterval(); @@ -1481,7 +1485,7 @@ public abstract class GLContextImpl extends GLContext { return true; } - private final void setRendererQuirks(int major, int minor, int ctp) { + private final void setRendererQuirks(int major, int minor, int ctp, VersionNumberString vendorVersion) { int[] quirks = new int[GLRendererQuirks.COUNT]; int i = 0; @@ -1555,6 +1559,7 @@ public abstract class GLContextImpl extends GLContext { } if( glRendererLowerCase.contains("intel(r)") && compatCtx && ( major>3 || major==3 && minor>=1 ) ) { + // FIXME: Apply vendor version constraints! final int quirk = GLRendererQuirks.GLNonCompliant; if(DEBUG) { System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: Renderer " + glRenderer); @@ -1562,43 +1567,28 @@ public abstract class GLContextImpl extends GLContext { quirks[i++] = quirk; } } - - // - // Mesa RENDERER related quirks - // if( glRendererLowerCase.contains("mesa") ) { - // Added March 30, 2013 - // Martin C. Hegedus - if ( glRendererLowerCase.contains("x11") && getMesaMajorVersion(glVersion) < 8.0 ) { - final int quirk = GLRendererQuirks.DontCloseX11DisplayConnection; + if ( glRendererLowerCase.contains("x11") && vendorVersion.compareTo(Version80) < 0 ) { + final int quirk = GLRendererQuirks.DontCloseX11Display; if(DEBUG) { - System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: Mesa X11 < 8 : Renderer=" + glRenderer + ", Version=" +glVersion); + System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: Renderer=" + glRenderer + ", Version=[vendor " + vendorVersion + ", GL " + glVersion+"]"); } quirks[i++] = quirk; - } + } + } + if( glRendererLowerCase.contains("ati technologies") || glRendererLowerCase.startsWith("ati ") ) { + { + final int quirk = GLRendererQuirks.DontCloseX11Display; + if(DEBUG) { + System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: Renderer=" + glRenderer); + } + quirks[i++] = quirk; + } } glRendererQuirks = new GLRendererQuirks(quirks, 0, i); } - // Added by Martin C. Hegedus, March 30, 2013 - private static final int getMesaMajorVersion(String version) { - if (version == null || version.length() <= 0) return -1; - String[] strings = version.trim().split("\\s+"); - if (strings.length <= 0) return -1; - version = strings[strings.length-1]; - int index = version.indexOf("."); - if (index == 0) return -1; - if (index != -1) version = version.substring(0,index); - try { - Integer iNumber = new Integer(version); - return (iNumber == null) ? -1 : iNumber.intValue(); - } catch (Throwable t) { - return -1; - } - } - - private static final boolean hasFBOImpl(int major, int ctp, ExtensionAvailabilityCache extCache) { return ( 0 != (ctp & CTX_PROFILE_ES) && major >= 2 ) || // ES >= 2.0 diff --git a/src/jogl/classes/jogamp/opengl/GLVersionNumber.java b/src/jogl/classes/jogamp/opengl/GLVersionNumber.java index 83815f7a4..1784cd772 100644 --- a/src/jogl/classes/jogamp/opengl/GLVersionNumber.java +++ b/src/jogl/classes/jogamp/opengl/GLVersionNumber.java @@ -32,24 +32,23 @@ import java.util.StringTokenizer; import javax.media.opengl.GLContext; -import com.jogamp.common.util.VersionNumber; +import com.jogamp.common.util.VersionNumberString; /** * A class for storing and comparing OpenGL version numbers. * This only works for desktop OpenGL at the moment. */ -class GLVersionNumber extends VersionNumber { +class GLVersionNumber extends VersionNumberString { - protected boolean valid; + private final boolean valid; - public GLVersionNumber(int majorRev, int minorRev, int subMinorRev) { - super(majorRev, minorRev, subMinorRev); - valid = true; + private GLVersionNumber(int[] val, String versionString, boolean valid) { + super(val[0], val[1], val[2], versionString); + this.valid = valid; } - - public GLVersionNumber(String versionString) { - super(); - valid = false; + + public static GLVersionNumber create(String versionString) { + int[] val = new int[] { 0, 0, 0 }; try { if (versionString.startsWith("GL_VERSION_")) { StringTokenizer tok = new StringTokenizer(versionString, "_"); @@ -57,19 +56,19 @@ class GLVersionNumber extends VersionNumber { tok.nextToken(); // VERSION_ if (!tok.hasMoreTokens()) { val[0] = 0; - return; - } - val[0] = Integer.valueOf(tok.nextToken()).intValue(); - if (!tok.hasMoreTokens()) { - val[1] = 0; - return; - } - val[1] = Integer.valueOf(tok.nextToken()).intValue(); - if (!tok.hasMoreTokens()) { - val[2] = 0; - return; + } else { + val[0] = Integer.valueOf(tok.nextToken()).intValue(); + if (!tok.hasMoreTokens()) { + val[1] = 0; + } else { + val[1] = Integer.valueOf(tok.nextToken()).intValue(); + if (!tok.hasMoreTokens()) { + val[2] = 0; + } else { + val[2] = Integer.valueOf(tok.nextToken()).intValue(); + } + } } - val[2] = Integer.valueOf(tok.nextToken()).intValue(); } else { int radix = 10; if (versionString.length() > 2) { @@ -105,7 +104,7 @@ class GLVersionNumber extends VersionNumber { } } } - valid = true; + return new GLVersionNumber(val, versionString, true); } catch (Exception e) { e.printStackTrace(); // FIXME: refactor desktop OpenGL dependencies and make this @@ -118,11 +117,41 @@ class GLVersionNumber extends VersionNumber { new IllegalArgumentException( "Illegally formatted version identifier: \"" + versionString + "\"") .initCause(e); - */ + */ } + return new GLVersionNumber(val, versionString, false); } public final boolean isValid() { return valid; } + + /** + * Returns the optional vendor version at the end of the + * GL_VERSION string if exists, otherwise null. + *
        +     *   2.1 Mesa 7.0.3-rc2 -> 7.0.3 (7.0.3-rc2)
        +     *   4.2.12171 Compatibility Profile Context 9.01.8 -> 9.1.8 (9.01.8)
        +     *   4.3.0 NVIDIA 310.32 -> 310.32 (310.32)
        +     * 
        + */ + public static final VersionNumberString createVendorVersion(String versionString) { + if (versionString == null || versionString.length() <= 0) { + return null; + } + final String[] strings = versionString.trim().split("\\s+"); + if ( strings.length <= 0 ) { + return null; + } + // Test all segments backwards from [len-1..1], skipping the 1st entry (GL version) + // If a segment represents a valid VersionNumber - use it. + for(int i=strings.length-1; i>=1; i--) { + final String s = strings[i]; + final VersionNumberString version = new VersionNumberString(s, "."); + if( !version.isZero() ) { + return version; + } + } + return null; + } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index be3729a7d..9b87860cb 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -113,6 +113,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { // Check for other underlying stuff .. if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(true)) { + hasX11 = true; try { ReflectionUtil.createInstance("jogamp.opengl.x11.glx.X11GLXGraphicsConfigurationFactory", EGLDrawableFactory.class.getClassLoader()); } catch (Exception jre) { /* n/a .. */ } @@ -262,6 +263,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { private EGLGraphicsDevice defaultDevice = null; private SharedResource defaultSharedResource = null; private boolean isANGLE = false; + private boolean hasX11 = false; static class SharedResource { private final EGLGraphicsDevice device; @@ -568,6 +570,10 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { // avoid exception due to double 'set' - carefull exception of the rule. EGLContext.setAvailableGLVersionsSet(adevice); } + if( hasX11 ) { + handleDontCloseX11DisplayQuirk(rendererQuirksES1[0]); + handleDontCloseX11DisplayQuirk(rendererQuirksES2[0]); + } final SharedResource sr = new SharedResource(defaultDevice, madeCurrentES1, hasPBufferES1[0], rendererQuirksES1[0], ctpES1[0], madeCurrentES2, hasPBufferES2[0], rendererQuirksES2[0], ctpES2[0]); @@ -582,6 +588,12 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } return sr; } + + private void handleDontCloseX11DisplayQuirk(GLRendererQuirks quirks) { + if( null != quirks && quirks.exist( GLRendererQuirks.DontCloseX11Display ) ) { + jogamp.nativewindow.x11.X11Util.markAllDisplaysUnclosable(); + } + } @Override protected final Thread getSharedResourceThread() { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index 2f3940baa..9486b5875 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -73,6 +73,7 @@ import jogamp.opengl.SharedResourceRunner; import com.jogamp.common.util.VersionNumber; import com.jogamp.nativewindow.x11.X11GraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsScreen; +import com.jogamp.opengl.GLRendererQuirks; public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { @@ -236,6 +237,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { res = GLXUtil.isGLXAvailableOnServer(x11Device); } finally { x11Device.unlock(); + x11Device.close(); } if(DEBUG) { System.err.println("GLX "+(res ? "is" : "not")+" available on device/server: "+x11Device); @@ -276,6 +278,9 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { } finally { sharedContext.release(); } + if( sharedContext.hasRendererQuirk( GLRendererQuirks.DontCloseX11Display ) ) { + X11Util.markAllDisplaysUnclosable(); + } if (DEBUG) { System.err.println("SharedDevice: " + sharedDevice); System.err.println("SharedScreen: " + sharedScreen); diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 2fb780fa2..e28aff116 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -82,6 +82,9 @@ public class X11Util implements ToolkitProperties { *

        */ public static final boolean ATI_HAS_XCLOSEDISPLAY_BUG = !Debug.isPropertyDefined("nativewindow.debug.X11Util.ATI_HAS_NO_XCLOSEDISPLAY_BUG", true); + + /** See {@link #ATI_HAS_XCLOSEDISPLAY_BUG}. */ + public static final boolean HAS_XCLOSEDISPLAY_BUG = Debug.isPropertyDefined("nativewindow.debug.X11Util.HAS_XCLOSEDISPLAY_BUG", true); /** * See Bug 623 - https://jogamp.org/bugzilla/show_bug.cgi?id=623 @@ -137,14 +140,11 @@ public class X11Util implements ToolkitProperties { hasX11_EXTENSION_ATIFGLRXDRI = false; hasX11_EXTENSION_ATIFGLEXTENSION = false; } - hasThreadingIssues = ATI_HAS_MULTITHREADING_BUG && ( hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ); - // A check on nativewindow.debug.X11Util.HasX11CloseDisplayBug added March 30, 2013 - // Martin C. Hegedus - if (!markAllDisplaysUnclosable) { - markAllDisplaysUnclosable = ATI_HAS_XCLOSEDISPLAY_BUG && ( hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ); - if (Debug.isPropertyDefined("nativewindow.debug.X11Util.HasX11CloseDisplayBug", true)) - markAllDisplaysUnclosable = true; - } + final boolean isATIFGLRX = hasX11_EXTENSION_ATIFGLRXDRI || hasX11_EXTENSION_ATIFGLEXTENSION ; + hasThreadingIssues = ATI_HAS_MULTITHREADING_BUG && isATIFGLRX; + if ( !markAllDisplaysUnclosable ) { + markAllDisplaysUnclosable = ( ATI_HAS_XCLOSEDISPLAY_BUG && isATIFGLRX ) || HAS_XCLOSEDISPLAY_BUG; + } if(DEBUG) { System.err.println("X11Util.initSingleton(): OK "+isInitOK+"]"+ @@ -184,10 +184,10 @@ public class X11Util implements ToolkitProperties { synchronized(X11Util.class) { if(isInit) { final boolean isJVMShuttingDown = NativeWindowFactory.isJVMShuttingDown() ; - // Modified March 30, 2013 so output is not created under "expected" circumstances - // Martin C. Hegedus - if(DEBUG || ((openDisplayMap.size() > 0 || reusableDisplayList.size() > 0 || pendingDisplayList.size() > 0) && - !(reusableDisplayList.size() == pendingDisplayList.size() && markAllDisplaysUnclosable))) { + if( DEBUG || + ( ( openDisplayMap.size() > 0 || reusableDisplayList.size() > 0 || pendingDisplayList.size() > 0 ) && + ( reusableDisplayList.size() != pendingDisplayList.size() || !markAllDisplaysUnclosable ) + ) ) { System.err.println("X11Util.Display: Shutdown (JVM shutdown: "+isJVMShuttingDown+ ", open (no close attempt): "+openDisplayMap.size()+"/"+openDisplayList.size()+ ", reusable (open, marked uncloseable): "+reusableDisplayList.size()+ @@ -250,21 +250,22 @@ public class X11Util implements ToolkitProperties { public static String getNullDisplayName() { return nullDisplayName; } - - // Added March 30, 2013 - // Martin C. Hegedus + public static void markAllDisplaysUnclosable() { synchronized(globalLock) { - markAllDisplaysUnclosable = true; - for(int i=0; i Date: Wed, 17 Apr 2013 14:57:24 +0200 Subject: *Capabilities: Cleanup string ctor; GLGraphicsConfigurationUtil: Clean getExclusiveWinAttributeBits(..); WGLGLCapabilities: Add PFD2String(..) --- .../classes/javax/media/opengl/GLCapabilities.java | 8 ++-- .../jogamp/opengl/GLGraphicsConfigurationUtil.java | 44 ++++++++++++++++---- .../opengl/windows/wgl/WGLGLCapabilities.java | 47 ++++++++++++++++++++-- .../javax/media/nativewindow/Capabilities.java | 11 +++-- 4 files changed, 92 insertions(+), 18 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilities.java b/src/jogl/classes/javax/media/opengl/GLCapabilities.java index 9b004a0af..09db70f64 100644 --- a/src/jogl/classes/javax/media/opengl/GLCapabilities.java +++ b/src/jogl/classes/javax/media/opengl/GLCapabilities.java @@ -493,8 +493,8 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil super.toString(sink, false); - sink.append(", accum-rgba ").append(accumRedBits).append("/").append(accumGreenBits).append("/").append(accumBlueBits).append("/").append(accumAlphaBits); - sink.append(", dp/st/ms: ").append(depthBits).append("/").append(stencilBits).append("/").append(samples); + sink.append(", accum-rgba ").append(accumRedBits).append(ESEP).append(accumGreenBits).append(ESEP).append(accumBlueBits).append(ESEP).append(accumAlphaBits); + sink.append(", dp/st/ms ").append(depthBits).append(ESEP).append(stencilBits).append(ESEP).append(samples); if(samples>0) { sink.append(", sample-ext ").append(sampleExtension); } @@ -525,7 +525,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil ns = true; } if(isPBuffer()) { - if(ns) { sink.append(", "); } + if(ns) { sink.append(CSEP); } sink.append("pbuffer [r2t ").append(pbufferRenderToTexture?1:0) .append(", r2tr ").append(pbufferRenderToTextureRectangle?1:0) .append(", float ").append(pbufferFloatingPointBuffers?1:0) @@ -533,7 +533,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil ns = true; } if(isBitmap()) { - if(ns) { sink.append(", "); } + if(ns) { sink.append(CSEP); } sink.append("bitmap"); ns = true; } diff --git a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java index 31e52b86c..d69b02bb9 100644 --- a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java +++ b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java @@ -101,17 +101,16 @@ public class GLGraphicsConfigurationUtil { * @return bitmask representing the input boolean in exclusive or logic, ie only one bit will be set. */ public static final int getExclusiveWinAttributeBits(boolean isOnscreen, boolean isFBO, boolean isPBuffer, boolean isBitmap) { - int winattrbits = 0; + final int winattrbits; if(isOnscreen) { - winattrbits |= WINDOW_BIT; + winattrbits = WINDOW_BIT; } else if(isFBO) { - winattrbits |= FBO_BIT; + winattrbits = FBO_BIT; } else if(isPBuffer ){ - winattrbits |= PBUFFER_BIT; + winattrbits = PBUFFER_BIT; } else if(isBitmap) { - winattrbits |= BITMAP_BIT; - } - if(0 == winattrbits) { + winattrbits = BITMAP_BIT; + } else { throw new InternalError("Empty bitmask"); } return winattrbits; @@ -287,4 +286,35 @@ public class GLGraphicsConfigurationUtil { } return capsRequested; } + + public static GLCapabilitiesImmutable clipRGBAGLCapabilities(GLCapabilitiesImmutable caps, boolean allowRGB555) + { + final int iR = caps.getRedBits(); + final int iG = caps.getGreenBits(); + final int iB = caps.getBlueBits(); + final int iA = caps.getAlphaBits(); + final int oR = clipColor(iR, allowRGB555); + final int oG = clipColor(iG, allowRGB555); + final int oB = clipColor(iB, allowRGB555); + final int oA = 0 < iA ? oR : 0 ; // align alpha to red if requested + if( iR != oR || iG != oG || iB != oB || iA != oA ) { + final GLCapabilities caps2 = (GLCapabilities) caps.cloneMutable(); + caps2.setRedBits(oR); + caps2.setGreenBits(oG); + caps2.setBlueBits(oB); + caps2.setAlphaBits(oA); + return caps2; + } + return caps; + } + + public static int clipColor(final int compIn, final boolean allowRGB555) { + final int compOut; + if( 5 < compIn || !allowRGB555 ) { + compOut = 8; + } else { + compOut = 5; + } + return compOut; + } } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java index 99064b123..10a4b56d5 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java @@ -32,7 +32,9 @@ import java.nio.IntBuffer; import jogamp.nativewindow.windows.GDI; import jogamp.nativewindow.windows.PIXELFORMATDESCRIPTOR; +import jogamp.opengl.GLGraphicsConfigurationUtil; +import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowException; import javax.media.opengl.GL; import javax.media.opengl.GLCapabilities; @@ -65,10 +67,11 @@ public class WGLGLCapabilities extends GLCapabilities { setAccumAlphaBits(pfd.getCAccumAlphaBits()); setDepthBits(pfd.getCDepthBits()); setStencilBits(pfd.getCStencilBits()); - setDoubleBuffered((pfd.getDwFlags() & GDI.PFD_DOUBLEBUFFER) != 0); - setStereo((pfd.getDwFlags() & GDI.PFD_STEREO) != 0); - setHardwareAccelerated((pfd.getDwFlags() & GDI.PFD_GENERIC_FORMAT) == 0 - || (pfd.getDwFlags() & GDI.PFD_GENERIC_ACCELERATED) != 0); + final int dwFlags = pfd.getDwFlags(); + setDoubleBuffered((dwFlags & GDI.PFD_DOUBLEBUFFER) != 0); + setStereo((dwFlags & GDI.PFD_STEREO) != 0); + setHardwareAccelerated((dwFlags & GDI.PFD_GENERIC_FORMAT) == 0 + || (dwFlags & GDI.PFD_GENERIC_ACCELERATED) != 0); // n/a with non ARB/GDI method: // multisample // opaque @@ -76,6 +79,42 @@ public class WGLGLCapabilities extends GLCapabilities { return true; } + + public static final String PFD2String(PIXELFORMATDESCRIPTOR pfd, int pfdID) { + final int dwFlags = pfd.getDwFlags(); + StringBuffer sb = new StringBuffer(); + boolean sep = false; + + if( 0 != (GDI.PFD_DRAW_TO_WINDOW & dwFlags ) ) { + sep = true; + sb.append("window"); + } + if( 0 != (GDI.PFD_DRAW_TO_BITMAP & dwFlags ) ) { + if(sep) { sb.append(CSEP); } sep=true; + sb.append("bitmap"); + } + if( 0 != (GDI.PFD_SUPPORT_OPENGL & dwFlags ) ) { + if(sep) { sb.append(CSEP); } sep=true; + sb.append("opengl"); + } + if( 0 != (GDI.PFD_DOUBLEBUFFER & dwFlags ) ) { + if(sep) { sb.append(CSEP); } sep=true; + sb.append("dblbuf"); + } + if( 0 != (GDI.PFD_STEREO & dwFlags ) ) { + if(sep) { sb.append(CSEP); } sep=true; + sb.append("stereo"); + } + if( 0 == (GDI.PFD_GENERIC_FORMAT & dwFlags ) || 0 == (GDI.PFD_GENERIC_ACCELERATED & dwFlags ) ) { + if(sep) { sb.append(CSEP); } sep=true; + sb.append("hw-accel"); + } + return "PFD[id = "+pfdID+" (0x"+Integer.toHexString(pfdID)+ + "), colorBits "+pfd.getCColorBits()+", rgba "+pfd.getCRedBits()+ESEP+pfd.getCGreenBits()+ESEP+pfd.getCBlueBits()+ESEP+pfd.getCAlphaBits()+ + ", accum-rgba "+pfd.getCAccumRedBits()+ESEP+pfd.getCAccumGreenBits()+ESEP+pfd.getCAccumBlueBits()+ESEP+pfd.getCAccumAlphaBits()+ + ", dp/st/ms: "+pfd.getCDepthBits()+ESEP+pfd.getCStencilBits()+ESEP+"0"+ + ", flags: "+sb.toString(); + } public boolean setValuesByARB(final IntBuffer iattribs, final int niattribs, final IntBuffer iresults) { arb_pixelformat = 1; diff --git a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java index d35f92fea..8e83eda33 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java +++ b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java @@ -388,18 +388,23 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { return sink; } + /** Element separator */ + protected static final String ESEP = "/"; + /** Component separator */ + protected static final String CSEP = ", "; + protected StringBuilder toString(StringBuilder sink, boolean withOnOffScreen) { if(null == sink) { sink = new StringBuilder(); } - sink.append("rgba 0x").append(toHexString(redBits)).append("/").append(toHexString(greenBits)).append("/").append(toHexString(blueBits)).append("/").append(toHexString(alphaBits)); + sink.append("rgba ").append(redBits).append(ESEP).append(greenBits).append(ESEP).append(blueBits).append(ESEP).append(alphaBits); if(backgroundOpaque) { sink.append(", opaque"); } else { - sink.append(", trans-rgba 0x").append(toHexString(transparentValueRed)).append("/").append(toHexString(transparentValueGreen)).append("/").append(toHexString(transparentValueBlue)).append("/").append(toHexString(transparentValueAlpha)); + sink.append(", trans-rgba 0x").append(toHexString(transparentValueRed)).append(ESEP).append(toHexString(transparentValueGreen)).append(ESEP).append(toHexString(transparentValueBlue)).append(ESEP).append(toHexString(transparentValueAlpha)); } if(withOnOffScreen) { - sink.append(", "); + sink.append(CSEP); onoffScreenToString(sink); } return sink; -- cgit v1.2.3 From 0f7412855c118cb501d8a001df7a7487354b5029 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 23 Apr 2013 07:53:31 +0200 Subject: Fix Bug 722: Make GLEventListenerState 'transaction' safe Animator.pause[ surface.lock[ modify ] ] GLEventListenerState: New model for GLEventListenerState's transaction safety: - Z Decorate-1: Animator.pause [ X ] Animator.resume - X Decorate-2: Surface.lock [ Y ] Surface.unlock - Instead of setting AbstractGraphicsDevice, just swap the handle and ownership. - Issuing setRealized(..) only if required, i.e. having an upstream-surface (EGL..) depending on used device - Utilizing setRealized(..) on the GLAD's delegated 'real' drawable, avoiding optional GLAD locking. - Cleanup and above changes shall render impl. easier to read. GLEventListenerState Unit Tests: - If swapping/moving from AWT -> NEWT, use a NEWT dedicated Display avoiding ATI driver XCB crash - read comment. --- make/build-test.xml | 1 + make/scripts/tests.sh | 8 +- .../com/jogamp/opengl/GLEventListenerState.java | 332 ++++++++++++--------- .../jogamp/nativewindow/egl/EGLGraphicsDevice.java | 11 +- .../jogamp/nativewindow/x11/X11GraphicsDevice.java | 10 + .../media/nativewindow/DefaultGraphicsDevice.java | 40 ++- .../acore/glels/GLContextDrawableSwitchBase.java | 37 ++- .../TestBug722GLContextDrawableSwitchNewt2AWT.java | 143 +++++++++ .../TestGLContextDrawableSwitch11NewtAWT.java | 16 +- .../glels/TestGLContextDrawableSwitch12AWT.java | 16 +- .../TestGLContextDrawableSwitch21Newt2AWT.java | 61 ++-- 11 files changed, 485 insertions(+), 190 deletions(-) create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/acore/glels/TestBug722GLContextDrawableSwitchNewt2AWT.java (limited to 'src/nativewindow') diff --git a/make/build-test.xml b/make/build-test.xml index 3d9c31d83..e00348c38 100644 --- a/make/build-test.xml +++ b/make/build-test.xml @@ -437,6 +437,7 @@ + diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 75e5f7fd6..65e070a99 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -115,6 +115,7 @@ function jrun() { #D_ARGS="-Djogl.debug.EGLDisplayUtil -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.GLCanvas" #D_ARGS="-Djogl.debug.GLDrawable" + #D_ARGS="-Djogl.debug.GLEventListenerState" #D_ARGS="-Djogl.fbo.force.none" #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all -Djogamp.debug.Lock" #D_ARGS="-Djogl.debug=all" @@ -362,8 +363,9 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.glels.TestGLContextDrawableSwitch01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.glels.TestGLContextDrawableSwitch10NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.glels.TestGLContextDrawableSwitch11NewtAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.acore.glels.TestGLContextDrawableSwitch12AWT $* -##testawt com.jogamp.opengl.test.junit.jogl.acore.glels.TestGLContextDrawableSwitch21Newt2AWT $* +testawt com.jogamp.opengl.test.junit.jogl.acore.glels.TestGLContextDrawableSwitch12AWT $* +#testawt com.jogamp.opengl.test.junit.jogl.acore.glels.TestGLContextDrawableSwitch21Newt2AWT $* +#testawt com.jogamp.opengl.test.junit.jogl.acore.glels.TestBug722GLContextDrawableSwitchNewt2AWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableDeadlockAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461FBOSupersamplingSwingAWT @@ -379,7 +381,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.newt.TestGLWindowInvisiblePointer01NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle01NEWT #testnoawt com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle02NEWT -testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT $* +#testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00bNEWT #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01NEWT #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01bNEWT diff --git a/src/jogl/classes/com/jogamp/opengl/GLEventListenerState.java b/src/jogl/classes/com/jogamp/opengl/GLEventListenerState.java index 2914a1bf9..21dafecb1 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLEventListenerState.java +++ b/src/jogl/classes/com/jogamp/opengl/GLEventListenerState.java @@ -32,11 +32,9 @@ import java.util.List; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; -import javax.media.nativewindow.AbstractGraphicsScreen; +import javax.media.nativewindow.DefaultGraphicsDevice; import javax.media.nativewindow.NativeSurface; -import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.ProxySurface; -import javax.media.nativewindow.VisualIDHolder; import javax.media.opengl.GLAnimatorControl; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilitiesImmutable; @@ -57,8 +55,8 @@ import com.jogamp.nativewindow.MutableGraphicsConfiguration; *
      • {@link GLContext}
      • *
      • All {@link GLEventListener}, incl. their init state
      • *
      • {@link GLAnimatorControl}
      • - *
      • {@link GLCapabilitiesImmutable} for compatibility check
      • - *
      • {@link AbstractGraphicsScreen} for compatibility check and preserving the {@link AbstractGraphicsDevice}
      • + * + *
      • {@link AbstractGraphicsDevice} for compatibility check and preserving the native device handle incl. ownership
      • * *

        * A GLEventListenerState instance can be created while components are {@link #moveFrom(GLAutoDrawable) moved from} a {@link GLAutoDrawable} @@ -68,16 +66,16 @@ import com.jogamp.nativewindow.MutableGraphicsConfiguration; * A GLEventListenerState instance's components can be {@link #moveTo(GLAutoDrawable) moved to} a {@link GLAutoDrawable}, * while loosing {@link #isOwner() ownership} of the moved components. *

        - *

        */ public class GLEventListenerState { - private static final boolean DEBUG = Debug.debug("GLDrawable"); + private static final boolean DEBUG = Debug.debug("GLDrawable") || Debug.debug("GLEventListenerState"); - private GLEventListenerState(AbstractGraphicsScreen upstreamScreen, boolean proxyOwnsUpstreamDevice, AbstractGraphicsScreen screen, GLCapabilitiesImmutable caps, + private GLEventListenerState(AbstractGraphicsDevice upstreamDevice, boolean proxyOwnsUpstreamDevice, AbstractGraphicsDevice device, + GLCapabilitiesImmutable caps, GLContext context, int count, GLAnimatorControl anim, boolean animStarted) { - this.upstreamScreen = upstreamScreen; + this.upstreamDevice = upstreamDevice; this.proxyOwnsUpstreamDevice = proxyOwnsUpstreamDevice; - this.screen = screen; + this.device = device; this.caps = caps; this.context = context; this.listeners = new GLEventListener[count]; @@ -99,9 +97,9 @@ public class GLEventListenerState { public final int listenerCount() { return listeners.length; } - public final AbstractGraphicsScreen upstreamScreen; + public final AbstractGraphicsDevice upstreamDevice; public final boolean proxyOwnsUpstreamDevice; - public final AbstractGraphicsScreen screen; + public final AbstractGraphicsDevice device; public final GLCapabilitiesImmutable caps; public final GLContext context; public final GLEventListener[] listeners; @@ -121,14 +119,13 @@ public class GLEventListenerState { listeners[i] = null; } // context.destroy(); - NPE (null drawable) - screen.getDevice().close(); + device.close(); owner = false; } } - private static AbstractGraphicsScreen cloneScreen(AbstractGraphicsScreen aScreen) { - final AbstractGraphicsDevice aDevice2 = (AbstractGraphicsDevice) aScreen.getDevice().clone(); - return NativeWindowFactory.createScreen( aDevice2, aScreen.getIndex() ); + private static AbstractGraphicsDevice cloneDevice(AbstractGraphicsDevice aDevice) { + return (AbstractGraphicsDevice) aDevice.clone(); } /** @@ -152,51 +149,6 @@ public class GLEventListenerState { * @see #moveTo(GLAutoDrawable) */ public static GLEventListenerState moveFrom(GLAutoDrawable a) { - final int aSz = a.getGLEventListenerCount(); - - // Create new AbstractGraphicsScreen w/ cloned AbstractGraphicsDevice for future GLAutoDrawable - // allowing this AbstractGraphicsDevice to loose ownership -> not closing display/device! - final NativeSurface aSurface = a.getNativeSurface(); - final AbstractGraphicsConfiguration aCfg = aSurface.getGraphicsConfiguration(); - final AbstractGraphicsScreen aScreen1 = aCfg.getScreen(); - final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) aCfg.getChosenCapabilities(); - final AbstractGraphicsScreen aScreen2 = cloneScreen(aScreen1); - aScreen1.getDevice().clearHandleOwner(); // don't close device handle - if( DEBUG ) { - System.err.println("GLEventListenerState.moveFrom.0a: orig 0x"+Integer.toHexString(aScreen1.getDevice().hashCode())+", "+aScreen1.getDevice()); - System.err.println("GLEventListenerState.moveFrom.0b: pres 0x"+Integer.toHexString(aScreen2.getDevice().hashCode())+", "+aScreen2.getDevice()); - System.err.println("GLEventListenerState.moveFrom.1: "+aSurface.getClass().getName()+", "+aSurface); - } - final AbstractGraphicsScreen aUpScreen2; - final boolean proxyOwnsUpstreamDevice; - { - AbstractGraphicsScreen _aUpScreen2=null; - if(aSurface instanceof ProxySurface) { - final ProxySurface aProxy = (ProxySurface)aSurface; - proxyOwnsUpstreamDevice = aProxy.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); - final NativeSurface aUpSurface = aProxy.getUpstreamSurface(); - if(DEBUG && null != aUpSurface) { - System.err.println("GLEventListenerState.moveFrom.2: "+aUpSurface.getClass().getName()+", "+aUpSurface); - } - if(null != aUpSurface) { - final AbstractGraphicsScreen aUpScreen1 = aUpSurface.getGraphicsConfiguration().getScreen(); - _aUpScreen2 = cloneScreen(aUpScreen1); - if(null != aUpScreen1) { - aUpScreen1.getDevice().clearHandleOwner(); // don't close device handle - } - if(DEBUG) { - System.err.println("GLEventListenerState.moveFrom.3a: up-orig 0x"+Integer.toHexString(aUpScreen1.getDevice().hashCode())+", "+aUpScreen1.getDevice()); - System.err.println("GLEventListenerState.moveFrom.3b: up-pres 0x"+Integer.toHexString(_aUpScreen2.getDevice().hashCode())+", "+_aUpScreen2.getDevice()); - System.err.println("GLEventListenerState.moveFrom.3c: "+aSurface.getClass().getName()+", "+aSurface); - System.err.println("GLEventListenerState.moveFrom.3d: "+aUpSurface.getClass().getName()+", "+aUpSurface); - } - } - } else { - proxyOwnsUpstreamDevice = false; - } - aUpScreen2=_aUpScreen2; - } - final GLAnimatorControl aAnim = a.getAnimator(); final boolean aAnimStarted; if( null != aAnim ) { @@ -206,23 +158,75 @@ public class GLEventListenerState { aAnimStarted = false; } - final GLEventListenerState glls = new GLEventListenerState(aUpScreen2, proxyOwnsUpstreamDevice, aScreen2, caps, a.getContext(), aSz, aAnim, aAnimStarted); - - // - // remove and cache all GLEventListener and their init-state - // - for(int i=0; i not closing display/device! + final AbstractGraphicsConfiguration aCfg = aSurface.getGraphicsConfiguration(); + final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) aCfg.getChosenCapabilities(); + final AbstractGraphicsDevice aDevice1 = aCfg.getScreen().getDevice(); + final AbstractGraphicsDevice aDevice2 = cloneDevice(aDevice1); + aDevice1.clearHandleOwner(); // don't close device handle + if( DEBUG ) { + System.err.println("GLEventListenerState.moveFrom.0a: orig 0x"+Integer.toHexString(aDevice1.hashCode())+", "+aDevice1); + System.err.println("GLEventListenerState.moveFrom.0b: pres 0x"+Integer.toHexString(aDevice2.hashCode())+", "+aDevice2); + System.err.println("GLEventListenerState.moveFrom.1: "+aSurface.getClass().getName()/*+", "+aSurface*/); + } + final AbstractGraphicsDevice aUpDevice2; + final boolean proxyOwnsUpstreamDevice; + { + AbstractGraphicsDevice _aUpDevice2 = null; + if(aSurface instanceof ProxySurface) { + final ProxySurface aProxy = (ProxySurface)aSurface; + proxyOwnsUpstreamDevice = aProxy.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + final NativeSurface aUpSurface = aProxy.getUpstreamSurface(); + if(DEBUG && null != aUpSurface) { + System.err.println("GLEventListenerState.moveFrom.2: "+aUpSurface.getClass().getName()+", "+aUpSurface); + } + if(null != aUpSurface) { + final AbstractGraphicsDevice aUpDevice1 = aUpSurface.getGraphicsConfiguration().getScreen().getDevice(); + _aUpDevice2 = cloneDevice(aUpDevice1); + aUpDevice1.clearHandleOwner(); // don't close device handle + if(DEBUG) { + System.err.println("GLEventListenerState.moveFrom.3a: up-orig 0x"+Integer.toHexString(aUpDevice1.hashCode())+", "+aUpDevice1); + System.err.println("GLEventListenerState.moveFrom.3b: up-pres 0x"+Integer.toHexString(_aUpDevice2.hashCode())+", "+_aUpDevice2); + System.err.println("GLEventListenerState.moveFrom.3c: "+aSurface.getClass().getName()+", "+aSurface); + System.err.println("GLEventListenerState.moveFrom.3d: "+aUpSurface.getClass().getName()/*+", "+aUpSurface+", "*/+aProxy.getUpstreamOptionBits(null).toString()); + } + } + } else { + proxyOwnsUpstreamDevice = false; + } + aUpDevice2 = _aUpDevice2; + } + + glls = new GLEventListenerState(aUpDevice2, proxyOwnsUpstreamDevice, aDevice2, caps, a.getContext(), aSz, aAnim, aAnimStarted); + + // + // remove and cache all GLEventListener and their init-state + // + for(int i=0; i + * @throws GLException if this preserved {@link AbstractGraphicsDevice} is incompatible w/ the given destination one. * * @see #moveFrom(GLAutoDrawable) * @see #isOwner() */ public final void moveTo(GLAutoDrawable a) { + final GLAnimatorControl aAnim = a.getAnimator(); + final boolean hasAnimator = null != aAnim; + final boolean aPaused; + if( hasAnimator ) { + aPaused = aAnim.pause(); + aAnim.remove(a); // also handles ECT + if( aPaused ) { + aAnim.resume(); + } + } else { + aPaused = false; + } + final List aGLCmds = new ArrayList(); final int aSz = listenerCount(); final NativeSurface aSurface = a.getNativeSurface(); - final MutableGraphicsConfiguration aCfg = (MutableGraphicsConfiguration) aSurface.getGraphicsConfiguration(); - final GLCapabilitiesImmutable aCaps = (GLCapabilitiesImmutable) aCfg.getChosenCapabilities(); - if( caps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) != aCaps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) || - caps.getVisualID(VisualIDHolder.VIDType.NATIVE) != aCaps.getVisualID(VisualIDHolder.VIDType.NATIVE) ) { - throw new GLException("Incompatible Capabilities - Prev-Holder: "+caps+", New-Holder "+caps); - } - // Destroy and remove currently associated GLContext, if any (will be replaced) - a.setContext( null, true ); - final boolean aRealized = a.isRealized(); - if( aRealized ) { - a.setRealized(false); - } - // Set new Screen and close previous one - { - final AbstractGraphicsScreen aScreen1 = aCfg.getScreen(); - if( DEBUG ) { - System.err.println("GLEventListenerState.moveTo.0a: orig 0x"+Integer.toHexString(aScreen1.getDevice().hashCode())+", "+aScreen1.getDevice()); - System.err.println("GLEventListenerState.moveTo.0b: pres 0x"+Integer.toHexString(screen.getDevice().hashCode())+", "+screen.getDevice()); + final boolean surfaceLocked = false; // NativeSurface.LOCK_SURFACE_NOT_READY < aSurface.lockSurface(); + final boolean aRealized; + try { + + final MutableGraphicsConfiguration aCfg = (MutableGraphicsConfiguration) aSurface.getGraphicsConfiguration(); + /** + final GLCapabilitiesImmutable aCaps = (GLCapabilitiesImmutable) aCfg.getChosenCapabilities(); + if( caps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) != aCaps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) || + caps.getVisualID(VisualIDHolder.VIDType.NATIVE) != aCaps.getVisualID(VisualIDHolder.VIDType.NATIVE) ) { + throw new GLException("Incompatible Capabilities - Prev-Holder: "+caps+", New-Holder "+caps); + } */ + final DefaultGraphicsDevice aDevice1 = (DefaultGraphicsDevice) aCfg.getScreen().getDevice(); + final DefaultGraphicsDevice aDevice2 = (DefaultGraphicsDevice) device; + if( !aDevice1.getUniqueID().equals( aDevice2.getUniqueID() ) ) { + throw new GLException("Incompatible devices: Preserved <"+aDevice2.getUniqueID()+">, target <"+aDevice1.getUniqueID()+">"); + } + + // collect optional upstream surface info + final ProxySurface aProxy; + final NativeSurface aUpSurface; + if(aSurface instanceof ProxySurface) { + aProxy = (ProxySurface)aSurface; + aUpSurface = aProxy.getUpstreamSurface(); + } else { + aProxy = null; + aUpSurface = null; } - aCfg.setScreen( screen ); - aScreen1.getDevice().close(); if( DEBUG ) { - System.err.println("GLEventListenerState.moveTo.1a: orig 0x"+Integer.toHexString(aScreen1.getDevice().hashCode())+", "+aScreen1.getDevice()); - System.err.println("GLEventListenerState.moveTo.1b: pres 0x"+Integer.toHexString(screen.getDevice().hashCode())+", "+screen.getDevice()); + System.err.println("GLEventListenerState.moveTo.0 : has aProxy "+(null!=aProxy)); + System.err.println("GLEventListenerState.moveTo.0 : has aUpSurface "+(null!=aUpSurface)); } - } - - // If using a ProxySurface w/ an upstream surface, set new Screen and close previous one on it - { - boolean upstreamSet = false; - if(aSurface instanceof ProxySurface) { - final ProxySurface aProxy = (ProxySurface)aSurface; - final NativeSurface aUpSurface = aProxy.getUpstreamSurface(); - if(null != aUpSurface) { - final MutableGraphicsConfiguration aUpCfg = (MutableGraphicsConfiguration) aUpSurface.getGraphicsConfiguration(); - if( null != upstreamScreen ) { - final AbstractGraphicsScreen aUpScreen1 = aUpCfg.getScreen(); - if( DEBUG ) { - System.err.println("GLEventListenerState.moveTo.2a: up-orig 0x"+Integer.toHexString(aUpScreen1.getDevice().hashCode())+", "+aUpScreen1.getDevice()); - System.err.println("GLEventListenerState.moveTo.2b: up-pres 0x"+Integer.toHexString(upstreamScreen.getDevice().hashCode())+", "+upstreamScreen.getDevice()); - System.err.println("GLEventListenerState.moveTo.2c: "+aUpSurface.getClass().getName()+", "+aUpSurface+", "+aProxy.getUpstreamOptionBits(null).toString()); - } - aUpScreen1.getDevice().close(); - aUpCfg.setScreen( upstreamScreen ); - if( proxyOwnsUpstreamDevice ) { - aProxy.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); - } - upstreamSet = true; - if( DEBUG ) { - System.err.println("GLEventListenerState.moveTo.3a: up-orig 0x"+Integer.toHexString(aUpScreen1.getDevice().hashCode())+", "+aUpScreen1.getDevice()); - System.err.println("GLEventListenerState.moveTo.3b: up-pres 0x"+Integer.toHexString(upstreamScreen.getDevice().hashCode())+", "+upstreamScreen.getDevice()); - System.err.println("GLEventListenerState.moveTo.3c: "+aUpSurface.getClass().getName()+", "+aUpSurface+", "+aProxy.getUpstreamOptionBits(null).toString()); - } - } else { - throw new GLException("Incompatible Surface config - Has Upstream-Surface: Prev-Holder = false, New-Holder = true"); + if( null==aUpSurface && null != upstreamDevice ) { + throw new GLException("Incompatible Surface config - Has Upstream-Surface: Prev-Holder = true, New-Holder = false"); + } + + // Destroy and remove currently associated GLContext, if any (will be replaced) + a.setContext( null, true ); + aRealized = a.isRealized(); + if( aRealized && null != aUpSurface ) { + // Unrealize due to device dependencies of an upstream surface, e.g. EGLUpstreamSurfaceHook + a.getDelegatedDrawable().setRealized(false); + } + + // Set new Screen and close previous one + { + if( DEBUG ) { + System.err.println("GLEventListenerState.moveTo.0a: orig 0x"+Integer.toHexString(aDevice1.hashCode())+", "+aDevice1); + System.err.println("GLEventListenerState.moveTo.0b: pres 0x"+Integer.toHexString(aDevice2.hashCode())+", "+aDevice2); + } + DefaultGraphicsDevice.swapDeviceHandleAndOwnership(aDevice1, aDevice2); + aDevice2.close(); + if( DEBUG ) { + System.err.println("GLEventListenerState.moveTo.1a: orig 0x"+Integer.toHexString(aDevice1.hashCode())+", "+aDevice1); + System.err.println("GLEventListenerState.moveTo.1b: pres 0x"+Integer.toHexString(aDevice2.hashCode())+", "+aDevice2); + } + } + + // If using a ProxySurface w/ an upstream surface, set new Screen and close previous one on it + if( null != aUpSurface ) { + final MutableGraphicsConfiguration aUpCfg = (MutableGraphicsConfiguration) aUpSurface.getGraphicsConfiguration(); + if( null != upstreamDevice ) { + final DefaultGraphicsDevice aUpDevice1 = (DefaultGraphicsDevice) aUpCfg.getScreen().getDevice(); + final DefaultGraphicsDevice aUpDevice2 = (DefaultGraphicsDevice)upstreamDevice; + if( !aUpDevice1.getUniqueID().equals( aUpDevice2.getUniqueID() ) ) { + throw new GLException("Incompatible updtream devices: Preserved <"+aUpDevice2.getUniqueID()+">, target <"+aUpDevice1.getUniqueID()+">"); + } + if( DEBUG ) { + System.err.println("GLEventListenerState.moveTo.2a: up-orig 0x"+Integer.toHexString(aUpDevice1.hashCode())+", "+aUpDevice1); + System.err.println("GLEventListenerState.moveTo.2b: up-pres 0x"+Integer.toHexString(aUpDevice2.hashCode())+", "+aUpDevice2); + System.err.println("GLEventListenerState.moveTo.2c: "+aUpSurface.getClass().getName()/*+", "+aUpSurface+", "*/+aProxy.getUpstreamOptionBits(null).toString()); + } + DefaultGraphicsDevice.swapDeviceHandleAndOwnership(aUpDevice1, aUpDevice2); + aUpDevice2.close(); + if( proxyOwnsUpstreamDevice ) { + aProxy.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); + } + if( DEBUG ) { + System.err.println("GLEventListenerState.moveTo.3a: up-orig 0x"+Integer.toHexString(aUpDevice1.hashCode())+", "+aUpDevice1); + System.err.println("GLEventListenerState.moveTo.3b: up-pres 0x"+Integer.toHexString(aUpDevice2.hashCode())+", "+aUpDevice2); + System.err.println("GLEventListenerState.moveTo.3c: "+aUpSurface.getClass().getName()/*+", "+aUpSurface+", "*/+aProxy.getUpstreamOptionBits(null).toString()); } + } else { + throw new GLException("Incompatible Surface config - Has Upstream-Surface: Prev-Holder = false, New-Holder = true"); } } - if( !upstreamSet && null != upstreamScreen ) { - throw new GLException("Incompatible Surface config - Has Upstream-Surface: Prev-Holder = true, New-Holder = false"); + + if( aRealized && null != aUpSurface ) { + a.getDelegatedDrawable().setRealized(true); + } + if( DEBUG ) { + System.err.println("GLEventListenerState.moveTo.X : has aProxy "+(null!=aProxy)); + System.err.println("GLEventListenerState.moveTo.X : has aUpSurface "+(null!=aUpSurface)); } - } - - if( aRealized ) { - a.setRealized(true); - } - final boolean surfaceLocked = false; // NativeSurface.LOCK_SURFACE_NOT_READY < aSurface.lockSurface(); - try { a.setContext( context, false ); } finally { if( surfaceLocked ) { @@ -347,7 +390,14 @@ public class GLEventListenerState { listeners[i] = null; } - if( null != anim && null == a.getAnimator() ) { + if( hasAnimator ) { + // prefer already bound animator + aAnim.add(a); + if( aPaused ) { + aAnim.resume(); + } + } else if ( null != anim ) { + // use previously bound animator anim.add(a); // also handles ECT if(animStarted) { anim.start(); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java index 63200b393..fb6d39b2f 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java @@ -120,6 +120,15 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl public void clearHandleOwner() { eglLifecycleCallback = null; } - + @Override + protected Object getHandleOwnership() { + return eglLifecycleCallback; + } + @Override + protected Object setHandleOwnership(Object newOwnership) { + final EGLDisplayLifecycleCallback oldOwnership = eglLifecycleCallback; + eglLifecycleCallback = (EGLDisplayLifecycleCallback) newOwnership; + return oldOwnership; + } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index da3b31de4..e630e012e 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -162,4 +162,14 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl public void clearHandleOwner() { handleOwner = false; } + @Override + protected Object getHandleOwnership() { + return Boolean.valueOf(handleOwner); + } + @Override + protected Object setHandleOwnership(Object newOwnership) { + final Boolean oldOwnership = Boolean.valueOf(handleOwner); + handleOwner = ((Boolean) newOwnership).booleanValue(); + return oldOwnership; + } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java index b3ae4628c..66b81d7fa 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java @@ -184,6 +184,42 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice return getClass().getSimpleName()+"[type "+getType()+", connection "+getConnection()+", unitID "+getUnitID()+", handle 0x"+Long.toHexString(getHandle())+", owner "+isHandleOwner()+", "+toolkitLock+"]"; } + /** + * Set the native handle of the underlying native device + * and return the previous one. + */ + protected final long setHandle(long newHandle) { + final long oldHandle = handle; + handle = newHandle; + return oldHandle; + } + + protected Object getHandleOwnership() { + return null; + } + protected Object setHandleOwnership(Object newOwnership) { + return null; + } + + public static final void swapDeviceHandleAndOwnership(final DefaultGraphicsDevice aDevice1, final DefaultGraphicsDevice aDevice2) { + aDevice1.lock(); + try { + aDevice2.lock(); + try { + final long aDevice1Handle = aDevice1.getHandle(); + final long aDevice2Handle = aDevice2.setHandle(aDevice1Handle); + aDevice1.setHandle(aDevice2Handle); + final Object aOwnership1 = aDevice1.getHandleOwnership(); + final Object aOwnership2 = aDevice2.setHandleOwnership(aOwnership1); + aDevice1.setHandleOwnership(aOwnership2); + } finally { + aDevice2.unlock(); + } + } finally { + aDevice1.unlock(); + } + } + /** * Set the internal ToolkitLock, which is used within the * {@link #lock()} and {@link #unlock()} implementation. @@ -194,8 +230,9 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice *

        * * @param locker the ToolkitLock, if null, {@link jogamp.nativewindow.NullToolkitLock} is being used + * @return the previous ToolkitLock instance */ - protected void setToolkitLock(ToolkitLock locker) { + protected ToolkitLock setToolkitLock(ToolkitLock locker) { final ToolkitLock _toolkitLock = toolkitLock; _toolkitLock.lock(); try { @@ -203,6 +240,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice } finally { _toolkitLock.unlock(); } + return _toolkitLock; } /** diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/glels/GLContextDrawableSwitchBase.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/glels/GLContextDrawableSwitchBase.java index 300b4ec85..905cbcf25 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/glels/GLContextDrawableSwitchBase.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/glels/GLContextDrawableSwitchBase.java @@ -42,6 +42,7 @@ import javax.media.opengl.awt.GLCanvas; import jogamp.nativewindow.jawt.JAWTUtil; +import com.jogamp.newt.Screen; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.GLEventListenerState; @@ -150,11 +151,12 @@ public abstract class GLContextDrawableSwitchBase extends UITestCase { return true; } - protected void testGLADOneLifecycle(GLCapabilities caps, GLADType gladType, int width, int height, - GLEventListenerCounter glelTracker, SnapshotGLEventListener snapshotGLEventListener, - GLEventListenerState glelsIn, GLEventListenerState glelsOut[], GLAnimatorControl animator) + protected void testGLADOneLifecycle(Screen screen, GLCapabilities caps, GLADType gladType, int width, + int height, GLEventListenerCounter glelTracker, + SnapshotGLEventListener snapshotGLEventListener, final GLEventListenerState glelsIn, final GLEventListenerState glelsOut[], GLAnimatorControl animator) throws InterruptedException { + System.err.println("GLAD Lifecycle.0 "+gladType+", restoring "+((null!=glelsIn)?true:false)+", preserving "+((null!=glelsOut)?true:false)); final Frame frame; final GLAutoDrawable glad; if( GLADType.GLCanvasOnscreen == gladType ) { @@ -179,7 +181,11 @@ public abstract class GLContextDrawableSwitchBase extends UITestCase { } else if( GLADType.GLWindow == gladType ) { frame = null; - glad = GLWindow.create(caps); + if( null != screen ) { + glad = GLWindow.create(screen, caps); + } else { + glad = GLWindow.create(caps); + } ((GLWindow)glad).setTitle("Newt GLWindow"); ((GLWindow)glad).setSize(width, height); } else if( GLADType.GLOffscreen == gladType ) { @@ -212,7 +218,9 @@ public abstract class GLContextDrawableSwitchBase extends UITestCase { if( null != glelsIn ) { Assert.assertEquals(0, glad.getGLEventListenerCount()); - glelsIn.moveTo(glad); + System.err.println(".. restoring.0"); + glelsIn.moveTo(glad); + System.err.println(".. restoring.X"); Assert.assertEquals(1, glelTracker.initCount); Assert.assertTrue(1 <= glelTracker.reshapeCount); @@ -227,6 +235,12 @@ public abstract class GLContextDrawableSwitchBase extends UITestCase { Assert.assertEquals(false, glelsIn.isOwner()); } + for (int wait=0; wait glelTracker.initCount || 1 > glelTracker.reshapeCount || 1 > glelTracker.displayCount ); + wait++) { + Thread.sleep(AWTRobotUtil.TIME_SLICE); + } + final long t0 = System.currentTimeMillis(); long t1 = t0; @@ -242,17 +256,17 @@ public abstract class GLContextDrawableSwitchBase extends UITestCase { if( null != glelsOut ) { final GLContext context1 = glad.getContext(); - final GLEventListenerState _gllsOut = GLEventListenerState.moveFrom(glad); + System.err.println(".. preserving.0"); + glelsOut[0] = GLEventListenerState.moveFrom(glad); + System.err.println(".. preserving.X"); - Assert.assertEquals(context1, _gllsOut.context); + Assert.assertEquals(context1, glelsOut[0].context); Assert.assertNull(context1.getGLReadDrawable()); Assert.assertNull(context1.getGLDrawable()); - Assert.assertEquals(3, _gllsOut.listenerCount()); - Assert.assertEquals(true, _gllsOut.isOwner()); + Assert.assertEquals(3, glelsOut[0].listenerCount()); + Assert.assertEquals(true, glelsOut[0].isOwner()); Assert.assertEquals(null, glad.getContext()); Assert.assertEquals(0, glad.getGLEventListenerCount()); - - glelsOut[0] = _gllsOut; } if( GLADType.GLCanvasOnscreen == gladType || GLADType.GLCanvasOffscreen == gladType ) { destroyFrame(frame); @@ -272,5 +286,6 @@ public abstract class GLContextDrawableSwitchBase extends UITestCase { } else { Assert.assertEquals(1, glelTracker.disposeCount); } + System.err.println("GLAD Lifecycle.X "+gladType); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/glels/TestBug722GLContextDrawableSwitchNewt2AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/glels/TestBug722GLContextDrawableSwitchNewt2AWT.java new file mode 100644 index 000000000..a11978784 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/glels/TestBug722GLContextDrawableSwitchNewt2AWT.java @@ -0,0 +1,143 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.acore.glels; + +import java.io.IOException; + +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLProfile; + + +import com.jogamp.newt.Display; +import com.jogamp.newt.NewtFactory; +import com.jogamp.newt.Screen; +import com.jogamp.opengl.GLEventListenerState; +import com.jogamp.opengl.util.Animator; +import com.jogamp.opengl.GLRendererQuirks; +import com.jogamp.opengl.test.junit.util.GLEventListenerCounter; +import com.jogamp.opengl.test.junit.util.MiscUtils; + +import org.junit.Test; + +/** + * Tests Bug 722 + *

        + * See Bug 722 - https://jogamp.org/bugzilla/show_bug.cgi?id=722. + *

        + */ +public class TestBug722GLContextDrawableSwitchNewt2AWT extends GLContextDrawableSwitchBase { + + static int loops = 10; + static long duration2 = 100; // ms + + /** + * Interesting artifact w/ ATI proprietary driver is that the + * bug causing the quirk {@link GLRendererQuirks#DontCloseX11Display} + * also causes an XCB crash when reusing the X11 display connection + * from AWT -> NEWT. Pre-allocating the X11 Display and keeping it referenced + * to avoid such re-usage worksaround this problem. + */ + public static boolean fixedNewtDisplay = true; + + @Test(timeout=3000000) + public void test11GLWindow2GLCanvasOnScrnGL2ES2() throws InterruptedException { + final GLCapabilities caps = getCaps(GLProfile.GL2ES2); + if(null == caps) return; + + GLADType gladType1 = GLADType.GLWindow; + GLADType gladType2 = GLADType.GLCanvasOnscreen; + + final SnapshotGLEventListener snapshotGLEventListener = new SnapshotGLEventListener(); + final Animator animator = new Animator(); + animator.start(); + + final Display dpy; + final Screen screen; + if( fixedNewtDisplay ) { + dpy = NewtFactory.createDisplay(null); + screen = NewtFactory.createScreen(dpy, 0); + screen.addReference(); + } else { + dpy = null; + screen = null; + } + + duration = duration2; + + for(int i=0; i * See Bug 665 - https://jogamp.org/bugzilla/show_bug.cgi?id=665. *

        + *

        + * Interesting artifact w/ ATI proprietary driver is that the + * bug causing the quirk {@link GLRendererQuirks#DontCloseX11Display} + * also causes an XCB crash when reusing the X11 display connection + * from AWT -> NEWT. Pre-allocating the X11 Display and keeping it referenced + * to avoid such re-usage worksaround this problem. + *

        */ public class TestGLContextDrawableSwitch21Newt2AWT extends GLContextDrawableSwitchBase { @@ -65,59 +76,75 @@ public class TestGLContextDrawableSwitch21Newt2AWT extends GLContextDrawableSwit public void test01GLCanvasOnScrn2GLWindowGL2ES2() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2ES2); if(null == reqGLCaps) return; - testGLCanvas2GLWindowImpl(reqGLCaps, GLADType.GLCanvasOnscreen, GLADType.GLWindow); + testGLCanvas2GLWindowImpl(null, reqGLCaps, GLADType.GLCanvasOnscreen, GLADType.GLWindow); } @Test(timeout=30000) public void test02GLCanvasOnScrn2GLWindowGLES2() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); if(null == reqGLCaps) return; - testGLCanvas2GLWindowImpl(reqGLCaps, GLADType.GLCanvasOnscreen, GLADType.GLWindow); + testGLCanvas2GLWindowImpl(null, reqGLCaps, GLADType.GLCanvasOnscreen, GLADType.GLWindow); } @Test(timeout=30000) public void test11GLWindow2GLCanvasOnScrnGL2ES2() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2ES2); if(null == reqGLCaps) return; - testGLCanvas2GLWindowImpl(reqGLCaps, GLADType.GLWindow, GLADType.GLCanvasOnscreen); + final Display dpy = NewtFactory.createDisplay(null); + final Screen screen = NewtFactory.createScreen(dpy, 0); + screen.addReference(); + testGLCanvas2GLWindowImpl(screen, reqGLCaps, GLADType.GLWindow, GLADType.GLCanvasOnscreen); + screen.removeReference(); } @Test(timeout=30000) public void test12GLWindow2GLCanvasOnScrnGLES2() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); if(null == reqGLCaps) return; - testGLCanvas2GLWindowImpl(reqGLCaps, GLADType.GLWindow, GLADType.GLCanvasOnscreen); + final Display dpy = NewtFactory.createDisplay(null); + final Screen screen = NewtFactory.createScreen(dpy, 0); + screen.addReference(); + testGLCanvas2GLWindowImpl(screen, reqGLCaps, GLADType.GLWindow, GLADType.GLCanvasOnscreen); + screen.removeReference(); } @Test(timeout=30000) public void test21GLCanvasOffScrn2GLWindowGL2ES2() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2ES2); if(null == reqGLCaps) return; - testGLCanvas2GLWindowImpl(reqGLCaps, GLADType.GLCanvasOffscreen, GLADType.GLWindow); + testGLCanvas2GLWindowImpl(null, reqGLCaps, GLADType.GLCanvasOffscreen, GLADType.GLWindow); } @Test(timeout=30000) public void test22GLCanvasOffScrn2GLWindowGLES2() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); if(null == reqGLCaps) return; - testGLCanvas2GLWindowImpl(reqGLCaps, GLADType.GLCanvasOffscreen, GLADType.GLWindow); + testGLCanvas2GLWindowImpl(null, reqGLCaps, GLADType.GLCanvasOffscreen, GLADType.GLWindow); } @Test(timeout=30000) public void test31GLWindow2GLCanvasOffScrnGL2ES2() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GL2ES2); if(null == reqGLCaps) return; - testGLCanvas2GLWindowImpl(reqGLCaps, GLADType.GLWindow, GLADType.GLCanvasOffscreen); + final Display dpy = NewtFactory.createDisplay(null); + final Screen screen = NewtFactory.createScreen(dpy, 0); + screen.addReference(); + testGLCanvas2GLWindowImpl(screen, reqGLCaps, GLADType.GLWindow, GLADType.GLCanvasOffscreen); + screen.removeReference(); } @Test(timeout=30000) public void test32GLWindow2GLCanvasOffScrnGLES2() throws InterruptedException { final GLCapabilities reqGLCaps = getCaps(GLProfile.GLES2); if(null == reqGLCaps) return; - testGLCanvas2GLWindowImpl(reqGLCaps, GLADType.GLWindow, GLADType.GLCanvasOffscreen); + final Display dpy = NewtFactory.createDisplay(null); + final Screen screen = NewtFactory.createScreen(dpy, 0); + screen.addReference(); + testGLCanvas2GLWindowImpl(screen, reqGLCaps, GLADType.GLWindow, GLADType.GLCanvasOffscreen); + screen.removeReference(); } - private void testGLCanvas2GLWindowImpl(GLCapabilities caps, GLADType gladType1, GLADType gladType2) throws InterruptedException { + private void testGLCanvas2GLWindowImpl(Screen screen, GLCapabilities caps, GLADType gladType1, GLADType gladType2) throws InterruptedException { if( !validateOnOffscreenLayer(gladType1, gladType2) ) { return; } @@ -131,18 +158,18 @@ public class TestGLContextDrawableSwitch21Newt2AWT extends GLContextDrawableSwit // - create glad1 w/o context // - create context using glad1 and assign it to glad1 { - testGLADOneLifecycle(caps, gladType1, width, height, - glelTracker, snapshotGLEventListener, - null, - glels, animator); + testGLADOneLifecycle(screen, caps, gladType1, width, + height, glelTracker, + snapshotGLEventListener, + null, glels, animator); } // - create glad2 w/ survived context { - testGLADOneLifecycle(caps, gladType2, width+100, height+100, - glelTracker, snapshotGLEventListener, - glels[0], - null, null); + testGLADOneLifecycle(screen, caps, gladType2, width+100, + height+100, glelTracker, + snapshotGLEventListener, + glels[0], null, null); } animator.stop(); } -- cgit v1.2.3 From 8a66294628589d765c1c5d5b3cafe7b939179dc2 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 23 Apr 2013 08:02:02 +0200 Subject: Fix JAWTUtil's ToolkitLock: Using RecursiveLock instance covering the AWT lock instead of simple volatile fields (bug). --- .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 127 +++++++++------------ 1 file changed, 57 insertions(+), 70 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index 349da8ee6..1f5d33746 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -55,6 +55,8 @@ import jogamp.nativewindow.Debug; import com.jogamp.common.os.Platform; import com.jogamp.common.util.VersionNumber; +import com.jogamp.common.util.locks.LockFactory; +import com.jogamp.common.util.locks.RecursiveLock; public class JAWTUtil { public static final boolean DEBUG = Debug.debug("JAWT"); @@ -80,9 +82,7 @@ public class JAWTUtil { private static final Method sunToolkitAWTUnlockMethod; private static final boolean hasSunToolkitAWTLock; - private static volatile Thread exclusiveOwnerThread; - private static int lockCounter; - + private static final RecursiveLock jawtLock; private static final ToolkitLock jawtToolkitLock; private static class PrivilegedDataBlob1 { @@ -232,26 +232,28 @@ public class JAWTUtil { } hasSunToolkitAWTLock = _hasSunToolkitAWTLock; // hasSunToolkitAWTLock = false; - exclusiveOwnerThread = null; - lockCounter = 0; + jawtLock = LockFactory.createRecursiveLock(); - jawtToolkitLock = new ToolkitLock() { + jawtToolkitLock = new ToolkitLock() { public final void lock() { JAWTUtil.lockToolkit(); - if(TRACE_LOCK) { System.err.println("JAWTToolkitLock.lock()"); } } public final void unlock() { - if(TRACE_LOCK) { System.err.println("JAWTToolkitLock.unlock()"); } JAWTUtil.unlockToolkit(); } @Override public final void validateLocked() throws RuntimeException { JAWTUtil.validateLocked(); } + @Override public final void dispose() { // nop - } - }; + } + @Override + public String toString() { + return "JAWTToolkitLock[obj 0x"+Integer.toHexString(hashCode())+", isOwner "+jawtLock.isOwner(Thread.currentThread())+", "+jawtLock+"]"; + } + }; // trigger native AWT toolkit / properties initialization Map desktophints = null; @@ -318,80 +320,65 @@ public class JAWTUtil { } /** - * Locks the AWT's global ReentrantLock.
        - * + * Locks the AWT's global ReentrantLock. + *

        * JAWT's native Lock() function calls SunToolkit.awtLock(), - * which just uses AWT's global ReentrantLock.
        + * which just uses AWT's global ReentrantLock. + *

        + *

        + * AWT locking is wrapped through a recursive lock object. + *

        */ - private static final void awtLock() { - if(hasSunToolkitAWTLock) { - try { - sunToolkitAWTLockMethod.invoke(null, (Object[])null); - } catch (Exception e) { - throw new NativeWindowException("SunToolkit.awtLock failed", e); + public static void lockToolkit() throws NativeWindowException { + jawtLock.lock(); + if( 1 == jawtLock.getHoldCount() ) { + if(!headlessMode && !isJava2DQueueFlusherThread()) { + if(hasSunToolkitAWTLock) { + try { + sunToolkitAWTLockMethod.invoke(null, (Object[])null); + } catch (Exception e) { + throw new NativeWindowException("SunToolkit.awtLock failed", e); + } + } else { + jawtLockObject.Lock(); + } } - } else { - jawtLockObject.Lock(); } - if(0 == lockCounter) { - exclusiveOwnerThread = Thread.currentThread(); - } - lockCounter++; + if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.lock(): "+jawtLock); } } /** - * Unlocks the AWT's global ReentrantLock.
        - * + * Unlocks the AWT's global ReentrantLock. + *

        * JAWT's native Unlock() function calls SunToolkit.awtUnlock(), - * which just uses AWT's global ReentrantLock.
        + * which just uses AWT's global ReentrantLock. + *

        + *

        + * AWT unlocking is wrapped through a recursive lock object. + *

        */ - private static final void awtUnlock() { - awtValidateLocked(); - lockCounter--; - if(0 == lockCounter) { - exclusiveOwnerThread = null; - } - if(hasSunToolkitAWTLock) { - try { - sunToolkitAWTUnlockMethod.invoke(null, (Object[])null); - } catch (Exception e) { - throw new NativeWindowException("SunToolkit.awtUnlock failed", e); - } - } else { - jawtLockObject.Unlock(); - } - } - - private static final void awtValidateLocked() throws RuntimeException { - final Thread ct = Thread.currentThread(); - if( ct != exclusiveOwnerThread ) { - if ( null == exclusiveOwnerThread ) { - throw new RuntimeException(ct.getName()+": JAWT-ToolkitLock not locked"); - } - throw new RuntimeException(ct.getName()+": Not JAWT-ToolkitLock owner. Owner is "+exclusiveOwnerThread.getName()); - } - } - - public static void lockToolkit() throws NativeWindowException { - if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.lock()"); } - if(!headlessMode && !isJava2DQueueFlusherThread()) { - awtLock(); - } - } - public static void unlockToolkit() { - if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.unlock()"); } - if(!headlessMode && !isJava2DQueueFlusherThread()) { - awtUnlock(); + jawtLock.validateLocked(); + if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.unlock(): "+jawtLock); } + if( 1 == jawtLock.getHoldCount() ) { + if(!headlessMode && !isJava2DQueueFlusherThread()) { + if(hasSunToolkitAWTLock) { + try { + sunToolkitAWTUnlockMethod.invoke(null, (Object[])null); + } catch (Exception e) { + throw new NativeWindowException("SunToolkit.awtUnlock failed", e); + } + } else { + jawtLockObject.Unlock(); + } + } } + jawtLock.unlock(); } public static final void validateLocked() throws RuntimeException { - if(!headlessMode && !isJava2DQueueFlusherThread()) { - awtValidateLocked(); - } - } - + jawtLock.validateLocked(); + } public static ToolkitLock getJAWTToolkitLock() { return jawtToolkitLock; -- cgit v1.2.3 From 8b70108d6fd04b2ab97cbd1b6729361b5ce98a6b Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 24 Apr 2013 18:48:14 +0200 Subject: X11 Error Handler: Start quiet; Init: quite = !debug; Internal calls: Pass through errorHandlerQuiet state. --- src/nativewindow/native/x11/Xmisc.c | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 77e6ea978..69f0c0746 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -174,7 +174,7 @@ static void setupJVMVars(JNIEnv * env) { } static XErrorHandler origErrorHandler = NULL ; -static int errorHandlerQuiet = 0 ; +static int errorHandlerQuiet = 1 ; static int errorHandlerDebug = 0 ; static int errorHandlerThrowException = 0; @@ -300,7 +300,7 @@ Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass clazz, jboo _initClazzAccess(env); x11IOErrorHandlerEnable(1, env); - NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, 1, 0, 0 /* no dpy, force, no sync */); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, 1, debug ? 0 : 1, 0 /* no dpy, force, no sync */); _initialized=1; if(JNI_TRUE == debug) { fprintf(stderr, "Info: NativeWindow native init passed\n"); @@ -311,7 +311,7 @@ Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass clazz, jboo JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Util_shutdown0(JNIEnv *env, jclass _unused) { - NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, 0, 0 /* no dpy, no sync */); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, errorHandlerQuiet, 0 /* no dpy, no sync */); x11IOErrorHandlerEnable(0, env); } @@ -342,9 +342,9 @@ Java_jogamp_nativewindow_x11_X11Lib_XGetVisualInfo1__JJLjava_nio_ByteBuffer_2Lja if (arg3 != NULL) { _ptr3 = (int *) (((char*) (*env)->GetPrimitiveArrayCritical(env, arg3, NULL)) + arg3_byte_offset); } - NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 1, errorHandlerQuiet, 0); _res = XGetVisualInfo((Display *) (intptr_t) arg0, (long) arg1, (XVisualInfo *) _ptr2, (int *) _ptr3); - // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 0, errorHandlerQuiet, 0); count = _ptr3[0]; if (arg3 != NULL) { (*env)->ReleasePrimitiveArrayCritical(env, arg3, _ptr3, 0); @@ -371,7 +371,7 @@ Java_jogamp_nativewindow_x11_X11Lib_GetVisualIDFromWindow(JNIEnv *env, jclass _u return; } - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, 0, 1); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, errorHandlerQuiet, 1); memset(&xwa, 0, sizeof(XWindowAttributes)); XGetWindowAttributes(dpy, w, &xwa); if(NULL != xwa.visual) { @@ -379,7 +379,7 @@ Java_jogamp_nativewindow_x11_X11Lib_GetVisualIDFromWindow(JNIEnv *env, jclass _u } else { r = 0; } - // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 1); return r; } @@ -391,9 +391,9 @@ Java_jogamp_nativewindow_x11_X11Lib_DefaultVisualID(JNIEnv *env, jclass _unused, if(0==display) { NativewindowCommon_FatalError(env, "invalid display connection.."); } - NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 1, errorHandlerQuiet, 0); r = (jint) XVisualIDFromVisual( DefaultVisual( (Display*) (intptr_t) display, screen ) ); - // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) display, 0, 0, errorHandlerQuiet, 0); return r; } @@ -434,9 +434,9 @@ Java_jogamp_nativewindow_x11_X11Lib_XCloseDisplay__J(JNIEnv *env, jclass _unused if(0==display) { NativewindowCommon_FatalError(env, "invalid display connection.."); } - NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 1, errorHandlerQuiet, 0); _res = XCloseDisplay((Display *) (intptr_t) display); - // NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 0, 0, errorHandlerQuiet, 0); return _res; } @@ -519,7 +519,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateWindow return 0; } - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, errorHandlerQuiet, 0); scrn = ScreenOfDisplay(dpy, scrn_idx); if(0==windowParent) { @@ -542,7 +542,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateWindow if (visual==NULL) { - // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 1); NativewindowCommon_throwNewRuntimeException(env, "could not query Visual by given VisualID, bail out!"); return 0; } @@ -606,7 +606,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateWindow XSelectInput(dpy, window, 0); // no events } - // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 1); DBG_PRINT( "X11: [CreateWindow] created window %p on display %p\n", window, dpy); @@ -630,12 +630,12 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_DestroyWindow return; } - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, errorHandlerQuiet, 0); XSelectInput(dpy, w, 0); XUnmapWindow(dpy, w); XSync(dpy, False); XDestroyWindow(dpy, w); - // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 1); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 1); } JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_SetWindowPosSize @@ -683,11 +683,11 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_x11_X11Lib_GetRelativeLocatio if( 0 == jdest_win ) { dest_win = root; } if( 0 == jsrc_win ) { src_win = root; } - NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, 0, 0); + NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, errorHandlerQuiet, 0); res = XTranslateCoordinates(dpy, src_win, dest_win, src_x, src_y, &dest_x, &dest_y, &child); - // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, 0, 0); + // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 0); DBG_PRINT( "X11: GetRelativeLocation0: %p %d/%d -> %p %d/%d - ok: %d\n", (void*)src_win, src_x, src_y, (void*)dest_win, dest_x, dest_y, (int)res); -- cgit v1.2.3 From 75b3d37a3b15c071b49609921244bcb62d329fa9 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 25 Apr 2013 06:08:01 +0200 Subject: Fix Bug 706 and Bug 520: Certain ATI GPU/driver require a current context when calling wglCreateContextAttribsARB (Windows) See discussion at https://jogamp.org/bugzilla/show_bug.cgi?id=520 https://jogamp.org/bugzilla/show_bug.cgi?id=706 --- make/scripts/tests-x64.bat | 6 +-- .../opengl/windows/wgl/WindowsWGLContext.java | 25 ++++++++--- .../windows/wgl/WindowsWGLDrawableFactory.java | 51 ++++++++++++++-------- .../opengl/x11/glx/X11GLXDrawableFactory.java | 14 +++--- .../native/win32/DeviceDriverQuery.txt | 41 +++++++++++++++++ 5 files changed, 103 insertions(+), 34 deletions(-) create mode 100644 src/nativewindow/native/win32/DeviceDriverQuery.txt (limited to 'src/nativewindow') diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat index d196b1d29..0133859fd 100755 --- a/make/scripts/tests-x64.bat +++ b/make/scripts/tests-x64.bat @@ -33,7 +33,7 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAut REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLWindowOnOffscrnCapsNEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableGLCanvasOnOffscrnCapsAWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryGL2OffscrnCapsNEWT %* -scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryGLnBitmapCapsNEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryGLnBitmapCapsNEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableFactoryES2OffscrnCapsNEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableFactoryNEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestFBOAutoDrawableOffThreadSharedContextES2NEWT %* @@ -55,11 +55,11 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestIsReali REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT -time 30000 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT %* -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* +scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 4000 -x 10 -y 10 -width 100 -height 100 -screen 0 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 40000 -width 100 -height 100 -screen 0 %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT -time 5000 -scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.gl3.newt.TestGeomShader01TextureGL3NEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.newt.TestSwingAWTRobotUsageBeforeJOGLInitBug411 diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java index 77d06f548..92b12a7ff 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java @@ -218,7 +218,6 @@ public class WindowsWGLContext extends GLContextImpl { }; if ( major > 3 || major == 3 && minor >= 2 ) { - // FIXME: Verify with a None drawable binding (default framebuffer) attribs[idx_profile+0] = WGLExt.WGL_CONTEXT_PROFILE_MASK_ARB; if( ctBwdCompat ) { attribs[idx_profile+1] = WGLExt.WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; @@ -269,11 +268,12 @@ public class WindowsWGLContext extends GLContextImpl { */ @Override protected boolean createImpl(GLContextImpl shareWith) { - AbstractGraphicsConfiguration config = drawable.getNativeSurface().getGraphicsConfiguration(); - AbstractGraphicsDevice device = config.getScreen().getDevice(); - WindowsWGLDrawableFactory factory = (WindowsWGLDrawableFactory)drawable.getFactoryImpl(); - WindowsWGLContext sharedContext = (WindowsWGLContext) factory.getOrCreateSharedContextImpl(device); - GLCapabilitiesImmutable glCaps = drawable.getChosenGLCapabilities(); + final AbstractGraphicsConfiguration config = drawable.getNativeSurface().getGraphicsConfiguration(); + final AbstractGraphicsDevice device = config.getScreen().getDevice(); + final WindowsWGLDrawableFactory factory = (WindowsWGLDrawableFactory)drawable.getFactoryImpl(); + final WindowsWGLDrawableFactory.SharedResource sharedResource = factory.getOrCreateSharedResource(device); + final WindowsWGLContext sharedContext = (WindowsWGLContext) ( null != sharedResource ? sharedResource.getContext() : null ); + final GLCapabilitiesImmutable glCaps = drawable.getChosenGLCapabilities(); isGLReadDrawableAvailable(); // trigger setup wglGLReadDrawableAvailable @@ -296,7 +296,18 @@ public class WindowsWGLContext extends GLContextImpl { // utilize the shared context's GLXExt in case it was using the ARB method and it already exists ; exclude BITMAP if( null != sharedContext && sharedContext.isCreatedWithARBMethod() && !glCaps.isBitmap() ) { - contextHandle = createContextARB(share, true); + if ( sharedResource.needsCurrenContext4ARBCreateContextAttribs() ) { + if(GLContext.CONTEXT_NOT_CURRENT == sharedContext.makeCurrent()) { + throw new GLException("Could not make Shared Context current: "+sharedContext); + } + contextHandle = createContextARB(share, true); + sharedContext.release(); + if (!wglMakeContextCurrent(drawable.getHandle(), drawableRead.getHandle(), contextHandle)) { + throw new GLException("Cannot make previous verified context current: 0x" + toHexString(contextHandle) + ", werr: " + GDI.GetLastError()); + } + } else { + contextHandle = createContextARB(share, true); + } createContextARBTried = true; if ( DEBUG && 0 != contextHandle ) { System.err.println(getThreadName() + ": createImpl: OK (ARB, using sharedContext) share "+share); diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java index e9742c4fe..483e31611 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java @@ -208,18 +208,19 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { static final VersionNumber winXPVersionNumber = new VersionNumber ( 5, 1, 0); static class SharedResource implements SharedResourceRunner.Resource { + private final boolean hasARBPixelFormat; + private final boolean hasARBMultisample; + private final boolean hasARBPBuffer; + private final boolean hasARBReadDrawable; + private final String vendor; + private final boolean isVendorATI; + private final boolean isVendorNVIDIA; + private final boolean needsCurrenContext4ARBPFDQueries; + private final boolean needsCurrenContext4ARBCreateContextAttribs; private WindowsGraphicsDevice device; private AbstractGraphicsScreen screen; private GLDrawableImpl drawable; private GLContextImpl context; - private boolean hasARBPixelFormat; - private boolean hasARBMultisample; - private boolean hasARBPBuffer; - private boolean hasARBReadDrawable; - private String vendor; - private boolean isVendorATI; - private boolean isVendorNVIDIA; - private boolean needsCurrenContext4ARBPFDQueries; SharedResource(WindowsGraphicsDevice dev, AbstractGraphicsScreen scrn, GLDrawableImpl draw, GLContextImpl ctx, boolean arbPixelFormat, boolean arbMultisample, boolean arbPBuffer, boolean arbReadDrawable, String glVendor) { @@ -235,20 +236,26 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { if(null != vendor) { isVendorNVIDIA = vendor.startsWith("NVIDIA") ; isVendorATI = vendor.startsWith("ATI") ; + } else { + isVendorNVIDIA = false; + isVendorATI = false; } - if ( isVendorATI() ) { + if ( isVendorATI ) { + needsCurrenContext4ARBCreateContextAttribs = true; final VersionNumber winVersion = Platform.getOSVersionNumber(); final boolean isWinXPOrLess = winVersion.compareTo(winXPVersionNumber) <= 0; - if(DEBUG) { - System.err.println("needsCurrenContext4ARBPFDQueries: "+winVersion+" <= "+winXPVersionNumber+" = "+isWinXPOrLess+" - "+Platform.getOSVersion()); - } needsCurrenContext4ARBPFDQueries = isWinXPOrLess; - } else { - if(DEBUG) { - System.err.println("needsCurrenContext4ARBPFDQueries: false"); + if(DEBUG) { + System.err.println("ATI && isWinXPOrLess = "+winVersion+" <= "+winXPVersionNumber+" = "+isWinXPOrLess+" - "+Platform.getOSVersion()); } + } else { needsCurrenContext4ARBPFDQueries = false; + needsCurrenContext4ARBCreateContextAttribs = false; + } + if(DEBUG) { + System.err.println("needsCurrenContext4ARBCreateContextAttribs: "+needsCurrenContext4ARBCreateContextAttribs); + System.err.println("needsCurrenContext4ARBPFDQueries: "+needsCurrenContext4ARBPFDQueries); } } @@ -273,12 +280,22 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { /** * Solves bug #480 * - * TODO: Validate if bug is actually relates to the 'old' ATI Windows driver for old GPU's like X300 etc - * and unrelated to the actual Windows version ! + * TODO: Validate if bug actually relates to the 'old' ATI Windows driver for old GPU's like X300 etc + * and not to the Windows version ! * * @return true if GL_VENDOR is ATI _and_ platform is Windows version XP or less! */ final boolean needsCurrentContext4ARBPFDQueries() { return needsCurrenContext4ARBPFDQueries; } + + /** + * Solves bug #706 and bug #520 + * + * TODO: Validate if quirk can be reduced to a certain range of GPUs and/or driver versions, + * where we would also need a method to query the latter (-> jogl/src/nativewindow/native/win32/DeviceDriverQuery.txt). + * + * @return true if GL_VENDOR is ATI + */ + final boolean needsCurrenContext4ARBCreateContextAttribs() { return needsCurrenContext4ARBCreateContextAttribs; } } class SharedResourceImplementation implements SharedResourceRunner.Implementation { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index 19005e48c..0d89468a9 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -157,17 +157,17 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { private HashMap sharedMap; static class SharedResource implements SharedResourceRunner.Resource { + private final String glXServerVendorName; + private final boolean isGLXServerVendorATI; + private final boolean isGLXServerVendorNVIDIA; + private final VersionNumber glXServerVersion; + private final boolean glXServerVersionOneOneCapable; + private final boolean glXServerVersionOneThreeCapable; + private final boolean glXMultisampleAvailable; X11GraphicsDevice device; X11GraphicsScreen screen; GLDrawableImpl drawable; GLContextImpl context; - String glXServerVendorName; - boolean isGLXServerVendorATI; - boolean isGLXServerVendorNVIDIA; - VersionNumber glXServerVersion; - boolean glXServerVersionOneOneCapable; - boolean glXServerVersionOneThreeCapable; - boolean glXMultisampleAvailable; SharedResource(X11GraphicsDevice dev, X11GraphicsScreen scrn, GLDrawableImpl draw, GLContextImpl ctx, diff --git a/src/nativewindow/native/win32/DeviceDriverQuery.txt b/src/nativewindow/native/win32/DeviceDriverQuery.txt new file mode 100644 index 000000000..7401ed83b --- /dev/null +++ b/src/nativewindow/native/win32/DeviceDriverQuery.txt @@ -0,0 +1,41 @@ + + // INCOMPLETE ! + // + // See Bug 706 and Bug 520 + // https://jogamp.org/bugzilla/show_bug.cgi?id=520 + // https://jogamp.org/bugzilla/show_bug.cgi?id=706 + // + // Device Driver SDK + // http://msdn.microsoft.com/en-us/library/ff553567.aspx#ddk_setupdi_device_information_functions_dg + { + /** + System-Defined Device Setup Classes Available to Vendors (GUID) + + Display Adapters + Class = Display + ClassGuid = {4d36e968-e325-11ce-bfc1-08002be10318} + This class includes video adapters. Drivers for this class include display drivers and video miniport drivers. + + /opt-windows/mingw/include/devguid.h GUID_DEVCLASS_DISPLAY + GUID_DEVCLASS_DISPLAY + HDEVINFO SetupDiGetClassDevs( + _In_opt_ const GUID *ClassGuid, + _In_opt_ PCTSTR Enumerator, + _In_opt_ HWND hwndParent, + _In_ DWORD Flags + ); + + */ + const GUID devClassDisplay = GUID_DEVCLASS_DISPLAY; + // http://msdn.microsoft.com/en-us/library/ff551069.aspx + HDEVINFO DeviceInfoSet = SetupDiGetClassDevs(&GUID_DEVCLASS_DISPLAY, NULL /* bus */, NULL /* windows */, DIGCF_PRESENT | DIGCF_PROFILE /* flags */); + DWORD MemberIndex = 0; + SP_DEVINFO_DATA DeviceInfoData; + DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); + while( TRUE == SetupDiEnumDeviceInfo(DeviceInfoSet, MemberIndex, &DeviceInfoData) ) { + SetupDiGetSelectedDevice(); + MemberIndex++; + } + SetupDiDestroyDeviceInfoList(hDevInfo); + } + -- cgit v1.2.3 From 6ebf649d1b87944257fe492e0aef842d1b8debc2 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Mon, 6 May 2013 17:27:09 +0200 Subject: Fix Bug 600 and Bug 721: Adding support for multiple monitors w/ NEWT - Support for all monitor devices and their available modes - X11: Use RandR 1.3 if available - Retrieve information - Changing a monitor device's mode - Support for dedicated and spannig fullscreen - See - TODO: - X11 RandR does _not_ relayout the virtual screen size and neither the CRT's viewport. We may need to relayout them if they were covering a seamless region to achieve same experience! - OSX: No machine to attach a secondary CRT -> TEST! - Tested Manually for Regressions - Linux ARMv6hf (Rasp-Pi/BCM, Panda/X11) - Android (Huawei, Kindle) - Tested Manually and junit: - X11/Linux - NV, ATI-Catalyst w/ 2 CRTs - VBox w/ 4 CRTs - Win/Windows - NV, w/ 2 CRTs - VBox w/ 4 CRTs - X11/OpenIndiana, NV, 1 CRT --- make/build-newt.xml | 1 + make/scripts/java-win64-dbg.bat | 1 + make/scripts/tests-x64.bat | 13 +- make/scripts/tests.sh | 18 +- .../javax/media/nativewindow/util/Dimension.java | 5 + .../javax/media/nativewindow/util/Insets.java | 8 + .../javax/media/nativewindow/util/Point.java | 4 + .../javax/media/nativewindow/util/Rectangle.java | 86 ++- .../nativewindow/util/RectangleImmutable.java | 20 + .../javax/media/nativewindow/util/SurfaceSize.java | 4 +- .../classes/com/jogamp/newt/MonitorDevice.java | 235 ++++++++ src/newt/classes/com/jogamp/newt/MonitorMode.java | 346 ++++++++++++ src/newt/classes/com/jogamp/newt/Screen.java | 93 ++-- src/newt/classes/com/jogamp/newt/ScreenMode.java | 208 ------- src/newt/classes/com/jogamp/newt/Window.java | 38 +- .../com/jogamp/newt/event/MonitorEvent.java | 71 +++ .../com/jogamp/newt/event/MonitorModeListener.java | 37 ++ .../classes/com/jogamp/newt/event/NEWTEvent.java | 7 +- .../classes/com/jogamp/newt/event/OutputEvent.java | 51 ++ .../com/jogamp/newt/event/ScreenModeListener.java | 39 -- .../classes/com/jogamp/newt/opengl/GLWindow.java | 13 + .../classes/com/jogamp/newt/util/MonitorMode.java | 102 ---- .../com/jogamp/newt/util/MonitorModeUtil.java | 247 +++++++++ .../com/jogamp/newt/util/ScreenModeUtil.java | 341 ------------ .../classes/jogamp/newt/MonitorDeviceImpl.java | 147 +++++ src/newt/classes/jogamp/newt/MonitorModeProps.java | 355 ++++++++++++ src/newt/classes/jogamp/newt/OffscreenWindow.java | 13 +- src/newt/classes/jogamp/newt/ScreenImpl.java | 569 ++++++++++---------- src/newt/classes/jogamp/newt/ScreenModeStatus.java | 231 -------- .../classes/jogamp/newt/ScreenMonitorState.java | 195 +++++++ src/newt/classes/jogamp/newt/WindowImpl.java | 201 +++++-- .../jogamp/newt/driver/android/ScreenDriver.java | 99 +++- .../jogamp/newt/driver/android/WindowDriver.java | 16 +- .../jogamp/newt/driver/awt/ScreenDriver.java | 24 +- .../jogamp/newt/driver/bcm/egl/ScreenDriver.java | 56 +- .../jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java | 56 +- .../jogamp/newt/driver/intel/gdl/ScreenDriver.java | 56 +- .../jogamp/newt/driver/kd/ScreenDriver.java | 54 +- .../jogamp/newt/driver/macosx/ScreenDriver.java | 129 ++--- .../jogamp/newt/driver/macosx/WindowDriver.java | 15 +- .../jogamp/newt/driver/windows/ScreenDriver.java | 146 +++-- src/newt/classes/jogamp/newt/driver/x11/RandR.java | 47 +- .../classes/jogamp/newt/driver/x11/RandR11.java | 320 +++++++---- .../classes/jogamp/newt/driver/x11/RandR13.java | 276 +++++++++- .../jogamp/newt/driver/x11/ScreenDriver.java | 146 +++-- src/newt/native/MacWindow.m | 235 ++++---- src/newt/native/NewtMacWindow.h | 1 - src/newt/native/NewtMacWindow.m | 4 +- src/newt/native/ScreenMode.h | 15 +- src/newt/native/Window.h | 17 +- src/newt/native/WindowsWindow.c | 305 ++++++++--- src/newt/native/X11RandR11.c | 44 +- src/newt/native/X11RandR13.c | 597 ++++++++++++--------- src/newt/native/X11Screen.c | 31 +- src/newt/native/X11Screen.h | 1 + src/newt/native/X11Window.c | 18 +- .../opengl/test/android/NEWTElektronActivity.java | 16 +- .../opengl/test/android/NEWTGearsES1Activity.java | 16 +- .../opengl/test/android/NEWTGearsES2Activity.java | 16 +- .../test/android/NEWTGearsES2ActivityLauncher.java | 1 + .../test/android/NEWTGearsES2TransActivity.java | 16 +- .../opengl/test/android/NEWTGraphUI1pActivity.java | 16 +- .../opengl/test/android/NEWTGraphUI2pActivity.java | 16 +- .../test/android/NEWTRedSquareES1Activity.java | 16 +- .../test/android/NEWTRedSquareES2Activity.java | 16 +- .../jogl/demos/es2/newt/TestGearsES2NEWT.java | 16 +- .../test/junit/jogl/glsl/TestRulerNEWT01.java | 16 +- .../test/junit/newt/ManualScreenMode03NEWT.java | 32 +- .../test/junit/newt/TestScreenMode00NEWT.java | 119 ++-- .../test/junit/newt/TestScreenMode00bNEWT.java | 24 +- .../test/junit/newt/TestScreenMode01NEWT.java | 133 ++--- .../test/junit/newt/TestScreenMode01aNEWT.java | 212 ++++++++ .../test/junit/newt/TestScreenMode01bNEWT.java | 210 +++++--- .../test/junit/newt/TestScreenMode01cNEWT.java | 249 +++++++++ .../test/junit/newt/TestScreenMode02NEWT.java | 75 +-- 75 files changed, 5159 insertions(+), 2463 deletions(-) create mode 100644 src/newt/classes/com/jogamp/newt/MonitorDevice.java create mode 100644 src/newt/classes/com/jogamp/newt/MonitorMode.java delete mode 100644 src/newt/classes/com/jogamp/newt/ScreenMode.java create mode 100644 src/newt/classes/com/jogamp/newt/event/MonitorEvent.java create mode 100644 src/newt/classes/com/jogamp/newt/event/MonitorModeListener.java create mode 100644 src/newt/classes/com/jogamp/newt/event/OutputEvent.java delete mode 100644 src/newt/classes/com/jogamp/newt/event/ScreenModeListener.java delete mode 100644 src/newt/classes/com/jogamp/newt/util/MonitorMode.java create mode 100644 src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java delete mode 100644 src/newt/classes/com/jogamp/newt/util/ScreenModeUtil.java create mode 100644 src/newt/classes/jogamp/newt/MonitorDeviceImpl.java create mode 100644 src/newt/classes/jogamp/newt/MonitorModeProps.java delete mode 100644 src/newt/classes/jogamp/newt/ScreenModeStatus.java create mode 100644 src/newt/classes/jogamp/newt/ScreenMonitorState.java create mode 100644 src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01aNEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01cNEWT.java (limited to 'src/nativewindow') diff --git a/make/build-newt.xml b/make/build-newt.xml index 862b78422..30c2ddfd1 100644 --- a/make/build-newt.xml +++ b/make/build-newt.xml @@ -593,6 +593,7 @@ + diff --git a/make/scripts/java-win64-dbg.bat b/make/scripts/java-win64-dbg.bat index 8669ba8f8..136fe4667 100755 --- a/make/scripts/java-win64-dbg.bat +++ b/make/scripts/java-win64-dbg.bat @@ -52,6 +52,7 @@ REM set D_ARGS="-Dnativewindow.debug.TraceLock" REM set D_ARGS="-Dnewt.debug.Display" "-Dnewt.debug.EDT" "-Dnewt.debug.Window" REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display" "-Dnewt.debug.EDT" "-Djogl.debug.GLContext" REM set D_ARGS="-Dnewt.debug.Screen" "-Dnewt.debug.EDT" "-Dnativewindow.debug=all" +REM set D_ARGS="-Dnewt.debug.Screen" REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display" "-Dnewt.test.Window.reparent.incompatible=true" REM set X_ARGS="-Dsun.java2d.noddraw=true" "-Dsun.java2d.opengl=true" "-Dsun.awt.noerasebackground=true" diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat index 0133859fd..27ecfb2cc 100755 --- a/make/scripts/tests-x64.bat +++ b/make/scripts/tests-x64.bat @@ -55,7 +55,7 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestIsReali REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT -time 30000 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT %* -scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 4000 -x 10 -y 10 -width 100 -height 100 -screen 0 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 40000 -width 100 -height 100 -screen 0 %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT -time 5000 @@ -106,10 +106,13 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestFocus01Swin REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.nativewindow.TestRecursiveToolkitLockCORE -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode01NEWT -REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode02NEWT -REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.ManualScreenMode03NEWT +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode01aNEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode01bNEWT %* +scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode01cNEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode01NEWT %* +REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode02NEWT %* +REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.ManualScreenMode03NEWT %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple %* REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube %* diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index b53c2f760..c6f69ab74 100755 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -135,6 +135,8 @@ function jrun() { #D_ARGS="-Djogl.debug.EGLDisplayUtil -Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.EGLDisplayUtil -Dnativewindow.debug.X11Util" #D_ARGS="-Djogl.debug.GLDrawable" + #D_ARGS="-Dnewt.debug.Screen" + #D_ARGS="-Dnewt.test.Screen.disableRandR13" #D_ARGS="-Dnewt.test.Screen.disableScreenMode -Dnewt.debug.Screen" #D_ARGS="-Dnewt.debug.Screen -Djogl.debug.Animator" #D_ARGS="-Djogl.debug.ExtensionAvailabilityCache -Djogl.debug=all -Dnativewindow.debug=all -Djogamp.debug.ProcAddressHelper=true -Djogamp.debug.NativeLibrary=true -Djogamp.debug.NativeLibrary.Lookup=true" @@ -284,7 +286,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT $* #testswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT $* #testswt com.jogamp.opengl.test.junit.jogl.demos.es2.swt.TestGearsES2SWT $* @@ -384,10 +386,12 @@ testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00bNEWT #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01NEWT -#testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01bNEWT -#testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode02NEWT -#testnoawt com.jogamp.opengl.test.junit.newt.ManualScreenMode03NEWT -#testnoawt -Djava.awt.headless=true com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT +#testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01aNEWT $* +#testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01bNEWT $* +testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01cNEWT $* +#testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode02NEWT $* +#testnoawt com.jogamp.opengl.test.junit.newt.ManualScreenMode03NEWT $* +#testnoawt -Djava.awt.headless=true com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT $* # # awt (testawt) @@ -509,7 +513,9 @@ testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* # # Texture / TextureUtils # -#testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestTexture01AWT +#testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestTexture01AWT $* +#testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestTexture02AWT $* + #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestJPEGImage00NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestJPEGImage01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestJPEGJoglAWTCompareNewtAWT $* diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java index 0a5a94565..4fae98f08 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java @@ -57,7 +57,9 @@ public class Dimension implements Cloneable, DimensionImmutable { } } + @Override public int getWidth() { return width; } + @Override public int getHeight() { return height; } public void setWidth(int width) { @@ -77,10 +79,12 @@ public class Dimension implements Cloneable, DimensionImmutable { return this; } + @Override public String toString() { return new String(width+" x "+height); } + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof Dimension) { @@ -91,6 +95,7 @@ public class Dimension implements Cloneable, DimensionImmutable { return false; } + @Override public int hashCode() { // 31 * x == (x << 5) - x int hash = 31 + width; diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java index 199ec27cb..f22668f55 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java @@ -57,11 +57,17 @@ public class Insets implements Cloneable, InsetsImmutable { } } + @Override public final int getLeftWidth() { return l; } + @Override public final int getRightWidth() { return r; } + @Override public final int getTotalWidth() { return l + r; } + @Override public final int getTopHeight() { return t; } + @Override public final int getBottomHeight() { return b; } + @Override public final int getTotalHeight() { return t + b; } public void setLeftWidth(int left) { l = left; } @@ -69,6 +75,7 @@ public class Insets implements Cloneable, InsetsImmutable { public void setTopHeight(int top) { t = top; } public void setBottomHeight(int bottom) { b = bottom; } + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof Insets) { @@ -79,6 +86,7 @@ public class Insets implements Cloneable, InsetsImmutable { return false; } + @Override public int hashCode() { int sum1 = l + b; int sum2 = t + r; diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java index c53b16928..8e6caf72b 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java @@ -54,6 +54,7 @@ public class Point implements Cloneable, PointImmutable { } } + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof Point) { @@ -63,14 +64,17 @@ public class Point implements Cloneable, PointImmutable { return false; } + @Override public final int getX() { return x; } + @Override public final int getY() { return y; } + @Override public int hashCode() { // 31 * x == (x << 5) - x int hash = 31 + x; diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java index 8d6bfe48f..8e6fc8e36 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java @@ -28,6 +28,8 @@ package javax.media.nativewindow.util; +import java.util.List; + public class Rectangle implements Cloneable, RectangleImmutable { int x; int y; @@ -57,15 +59,90 @@ public class Rectangle implements Cloneable, RectangleImmutable { } } + @Override public final int getX() { return x; } + @Override public final int getY() { return y; } + @Override public final int getWidth() { return width; } + @Override public final int getHeight() { return height; } - public void setX(int x) { this.x = x; } - public void setY(int y) { this.y = y; } - public void setWidth(int width) { this.width = width; } - public void setHeight(int height) { this.height = height; } + + public final void setX(int x) { this.x = x; } + public final void setY(int y) { this.y = y; } + public final void setWidth(int width) { this.width = width; } + public final void setHeight(int height) { this.height = height; } + @Override + public final RectangleImmutable union(final RectangleImmutable r) { + return union(r.getX(), r.getY(), r.getX() + r.getWidth(), r.getY() + r.getHeight()); + } + @Override + public final RectangleImmutable union(final int rx1, final int ry1, final int rx2, final int ry2) { + final int x1 = Math.min(x, rx1); + final int y1 = Math.min(y, ry1); + final int x2 = Math.max(x + width, rx2); + final int y2 = Math.max(y + height, ry2); + return new Rectangle(x1, y1, x2 - x1, y2 - y1); + } + /** + * Calculates the union of the given rectangles, stores it in this instance and returns this instance. + * @param rectangles given list of rectangles + * @return this instance holding the union of given rectangles. + */ + public final Rectangle union(final List rectangles) { + int x1=Integer.MAX_VALUE, y1=Integer.MAX_VALUE; + int x2=Integer.MIN_VALUE, y2=Integer.MIN_VALUE; + for(int i=rectangles.size()-1; i>=0; i--) { + final RectangleImmutable vp = rectangles.get(i); + x1 = Math.min(x1, vp.getX()); + x2 = Math.max(x2, vp.getX() + vp.getWidth()); + y1 = Math.min(y1, vp.getY()); + y2 = Math.max(y2, vp.getY() + vp.getHeight()); + } + setX(x1); + setY(y1); + setWidth(x2 - x1); + setHeight(y2 - y1); + return this; + } + + @Override + public final RectangleImmutable intersection(RectangleImmutable r) { + return intersection(r.getX(), r.getY(), r.getX() + r.getWidth(), r.getY() + r.getHeight()); + } + @Override + public final RectangleImmutable intersection(final int rx1, final int ry1, final int rx2, final int ry2) { + final int x1 = Math.max(x, rx1); + final int y1 = Math.max(y, ry1); + final int x2 = Math.min(x + width, rx2); + final int y2 = Math.min(y + height, ry2); + final int ix, iy, iwidth, iheight; + if( x2 < x1 ) { + ix = 0; + iwidth = 0; + } else { + ix = x1; + iwidth = x2 - x1; + } + if( y2 < y1 ) { + iy = 0; + iheight = 0; + } else { + iy = y1; + iheight = y2 - y1; + } + return new Rectangle (ix, iy, iwidth, iheight); + } + @Override + public final float coverage(RectangleImmutable r) { + final RectangleImmutable isect = intersection(r); + final float sqI = (float) ( isect.getWidth()*isect.getHeight() ); + final float sqT = (float) ( width*height ); + return sqI / sqT; + } + + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof Rectangle) { @@ -76,6 +153,7 @@ public class Rectangle implements Cloneable, RectangleImmutable { return false; } + @Override public int hashCode() { int sum1 = x + height; int sum2 = width + y; diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java index d3b43c864..7531989de 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java @@ -41,6 +41,26 @@ public interface RectangleImmutable extends WriteCloneable { int getY(); + /** Returns the union of this rectangle and the given rectangle. */ + RectangleImmutable union(final RectangleImmutable r); + /** Returns the union of this rectangleand the given coordinates. */ + RectangleImmutable union(final int rx1, final int ry1, final int rx2, final int ry2); + /** Returns the intersection of this rectangleand the given rectangle. */ + RectangleImmutable intersection(RectangleImmutable r); + /** Returns the intersection of this rectangleand the given coordinates. */ + RectangleImmutable intersection(final int rx1, final int ry1, final int rx2, final int ry2); + /** + * Returns the coverage of given rectangle w/ this this one, i.e. between 0.0 and 1.0. + *

        + * Coverage is computed by: + *

        +     *    isect = this.intersection(r);
        +     *    coverage = area( isect ) / area( this ) ;
        +     * 
        + *

        + */ + float coverage(RectangleImmutable r); + /** * Checks whether two rect objects are equal. Two instances * of Rectangle are equal if the four integer values diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java index 8f21bc49b..d7e451af8 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java @@ -36,8 +36,8 @@ package javax.media.nativewindow.util; * */ public class SurfaceSize { - DimensionImmutable resolution; - int bitsPerPixel; + final DimensionImmutable resolution; + final int bitsPerPixel; public SurfaceSize(DimensionImmutable resolution, int bitsPerPixel) { if(null==resolution || bitsPerPixel<=0) { diff --git a/src/newt/classes/com/jogamp/newt/MonitorDevice.java b/src/newt/classes/com/jogamp/newt/MonitorDevice.java new file mode 100644 index 000000000..fbe4d8cf0 --- /dev/null +++ b/src/newt/classes/com/jogamp/newt/MonitorDevice.java @@ -0,0 +1,235 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.newt; + +import java.util.List; + +import javax.media.nativewindow.util.DimensionImmutable; +import javax.media.nativewindow.util.Rectangle; +import javax.media.nativewindow.util.RectangleImmutable; + +import com.jogamp.common.util.ArrayHashSet; + +/** + * Visual output device, i.e. a CRT, LED ..consisting of it's components:
        + * + *
      • Immutable + *
          + *
        • nativeId
        • + *
        • {@link DimensionImmutable} size in [mm]
        • + *
        • {@link MonitorMode} original mode
        • + *
        • List<MonitorMode> supportedModes
        • + *
      • + *
      • Mutable + *
          + *
        • {@link MonitorMode} current mode
        • + *
        • {@link RectangleImmutable} viewport (rotated)
        • + *
      • + * + */ +public abstract class MonitorDevice { + protected final Screen screen; // backref + protected final int nativeId; // unique monitor device ID + protected final DimensionImmutable sizeMM; // in [mm] + protected final MonitorMode originalMode; + protected final ArrayHashSet supportedModes; // FIXME: May need to support mutable mode, i.e. adding modes on the fly! + protected MonitorMode currentMode; + protected boolean modeChanged; + protected Rectangle viewport; + + protected MonitorDevice(Screen screen, int nativeId, DimensionImmutable sizeMM, Rectangle viewport, MonitorMode currentMode, ArrayHashSet supportedModes) { + this.screen = screen; + this.nativeId = nativeId; + this.sizeMM = sizeMM; + this.originalMode = currentMode; + this.supportedModes = supportedModes; + this.currentMode = currentMode; + this.viewport = viewport; + this.modeChanged = false; + } + + /** Returns the {@link Screen} owning this monitor. */ + public final Screen getScreen() { + return screen; + } + + /** + * Tests equality of two MonitorDevice objects + * by evaluating equality of it's components:
        + *
          + *
        • nativeID
        • + *
        + *
        + */ + public final boolean equals(Object obj) { + if (this == obj) { return true; } + if (obj instanceof MonitorDevice) { + MonitorDevice md = (MonitorDevice)obj; + return md.nativeId == nativeId; + } + return false; + } + + /** + * Returns a combined hash code of it's elements:
        + *
          + *
        • nativeID
        • + *
        + */ + public final int hashCode() { + return nativeId; + } + + /** @return the immutable unique native Id of this monitor device. */ + public final int getId() { return nativeId; } + + /** + * @return the immutable monitor size in millimeters. + */ + public final DimensionImmutable getSizeMM() { + return sizeMM; + } + + /** + * Return the immutable original {@link com.jogamp.newt.MonitorMode}, as used at NEWT initialization. + * @return original {@link MonitorMode} which is element of the list {@link #getSupportedModes()} and {@link Screen#getMonitorModes()}. + */ + public final MonitorMode getOriginalMode() { + return originalMode; + } + + /** + * FIXME: May need to support mutable mode, i.e. adding modes on the fly! + * @return the immutable list of {@link MonitorMode}s supported by this monitor. Use w/ care, it's not a copy! + */ + public final List getSupportedModes() { + return supportedModes.getData(); + } + + /** @return the {@link RectangleImmutable rectangular} portion of the rotated virtual {@link Screen} size represented by this monitor. */ + public final RectangleImmutable getViewport() { + return viewport; + } + + /** Returns true if given coordinates are contained by this {@link #getViewport() viewport}, otherwise false. */ + public final boolean contains(int x, int y) { + return x >= viewport.getX() && + x < viewport.getX() + viewport.getWidth() && + y >= viewport.getY() && + y < viewport.getY() + viewport.getHeight() ; + } + + /** + * Returns the coverage of given rectangle w/ this this {@link #getViewport() viewport}, i.e. between 0.0 and 1.0. + *

        + * Coverage is computed by: + *

        +     *    isect = viewport.intersection(r);
        +     *    coverage = area( isect ) / area( viewport ) ;
        +     * 
        + *

        + */ + public final float coverage(RectangleImmutable r) { + return viewport.coverage(r); + } + + /** + * Returns the union of the given monitor's {@link #getViewport() viewport}. + * @param result storage for result, will be returned + * @param monitors given list of monitors + * @return viewport representing the union of given monitor's viewport. + */ + public static Rectangle unionOfViewports(final Rectangle result, final List monitors) { + int x1=Integer.MAX_VALUE, y1=Integer.MAX_VALUE; + int x2=Integer.MIN_VALUE, y2=Integer.MIN_VALUE; + for(int i=monitors.size()-1; i>=0; i--) { + final RectangleImmutable vp = monitors.get(i).getViewport(); + x1 = Math.min(x1, vp.getX()); + x2 = Math.max(x2, vp.getX() + vp.getWidth()); + y1 = Math.min(y1, vp.getY()); + y2 = Math.max(y2, vp.getY() + vp.getHeight()); + } + result.setX(x1); + result.setY(y1); + result.setWidth(x2 - x1); + result.setHeight(y2 - y1); + return result; + } + + public final boolean isOriginalMode() { + return currentMode.hashCode() == originalMode.hashCode(); + } + + /** + * Returns true if the {@link MonitorMode} + * has been changed programmatic via this API only, otherwise false. + *

        + * Note: We cannot guarantee that we won't interfere w/ another running + * application's screen mode change or vice versa. + *

        + */ + public final boolean isModeChangedByUs() { + return modeChanged && !isOriginalMode(); + } + + /** + * Return the current cached {@link MonitorMode} w/o native query. + *

        + * If {@link MonitorMode}s are not supported for this + * native type {@link com.jogamp.newt.Display#getType()}, it returns one with the current screen size.

        + * + * @return current {@link MonitorMode} which is element of the list {@link #getSupportedModes()} and {@link Screen#getMonitorModes()}. + */ + public final MonitorMode getCurrentMode() { + return currentMode; + } + + /** + * Return the current {@link MonitorMode} including a native query. + *

        + * If {@link MonitorMode}s are not supported for this + * native type {@link com.jogamp.newt.Display#getType()}, it returns one with the current screen size.

        + * + * @return current {@link MonitorMode} which is element of the list {@link #getSupportedModes()} and {@link Screen#getMonitorModes()}. + */ + public abstract MonitorMode queryCurrentMode(); + + /** + * Set the current {@link com.jogamp.newt.MonitorMode}. + * @param mode to be made current, must be element of the list {@link #getSupportedModes()} and {@link Screen#getMonitorModes()}. + * @return true if successful, otherwise false + */ + public abstract boolean setCurrentMode(MonitorMode mode); + + public String toString() { + return "Monitor[Id "+Display.toHexString(nativeId)+", "+sizeMM+" mm, viewport "+viewport+ ", orig "+originalMode+", curr "+currentMode+ + ", modeChanged "+modeChanged+", modeCount "+supportedModes.size()+"]"; + } +} + diff --git a/src/newt/classes/com/jogamp/newt/MonitorMode.java b/src/newt/classes/com/jogamp/newt/MonitorMode.java new file mode 100644 index 000000000..e5b329d47 --- /dev/null +++ b/src/newt/classes/com/jogamp/newt/MonitorMode.java @@ -0,0 +1,346 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.newt; + +import javax.media.nativewindow.util.DimensionImmutable; +import javax.media.nativewindow.util.SurfaceSize; + + +/** Immutable MonitorMode Class, consisting of it's read only components:
        + *
          + *
        • nativeId
        • + *
        • {@link SizeAndRRate}, non rotated surfaceSize and refreshRate
        • + *
        • rotation, measured counter clockwise (CCW)
        • + *
        + * + * Aquire and filter MonitorMode
        + *
          + *
        • A List of read only MonitorModes is being returned by {@link com.jogamp.newt.Screen#getMonitorModes()}.
        • + *
        • You may utilize {@link com.jogamp.newt.util.MonitorModeUtil} to filter and select a desired ScreenMode.
        • + *
        • The current ScreenMode can be obtained via {@link com.jogamp.newt.Screen#getCurrentScreenMode()}.
        • + *
        • The initial original ScreenMode (at startup) can be obtained via {@link com.jogamp.newt.Screen#getOriginalScreenMode()}.
        • + *
        + *
        + * + * Changing ScreenModes
        + * FIXME!!!!! + *
          + *
        • Use {@link com.jogamp.newt.Screen#setCurrentScreenMode(com.jogamp.newt.MonitorMode)}
        • + * to change the current ScreenMode of all Screen's referenced via the full qualified name (FQN) + * {@link com.jogamp.newt.Screen#getFQName()}. + *
        • When the last FQN referenced Screen closes, the original ScreenMode ({@link com.jogamp.newt.Screen#getOriginalScreenMode()}) + * is restored.
        • + *
        + *
        + * Example for changing the ScreenMode: + *
        +        // determine target refresh rate
        +        ScreenMode orig = screen.getOriginalScreenMode();
        +        int freq = orig.getOutputMode().getRefreshRate();
        +
        +        // target resolution
        +        Dimension res = new Dimension(800, 600);
        +
        +        // target rotation
        +        int rot = 0;
        +
        +        // filter available ScreenModes
        +        List screenModes = screen.getScreenModes();
        +        screenModes = ScreenModeUtil.filterByRate(screenModes, freq); // get the nearest ones
        +        screenModes = ScreenModeUtil.filterByRotation(screenModes, rot);
        +        screenModes = ScreenModeUtil.filterByResolution(screenModes, res); // get the nearest ones
        +        screenModes = ScreenModeUtil.getHighestAvailableBpp(screenModes);
        +
        +        // pick 1st one ..
        +        screen.setCurrentScreenMode((ScreenMode) screenModes.get(0)); 
        + * 
        + * + * X11 / AMD just works
        + *
        + * X11 / NVidia difficulties + *
        +    NVidia RANDR RefreshRate Bug
        +        If NVidia's 'DynamicTwinView' is enabled, all refresh rates are
        +        unique, ie consequent numbers starting with the default refresh, ie 50, 51, ..
        +        The only way to workaround it is to disable 'DynamicTwinView'.
        +        Read: http://us.download.nvidia.com/XFree86/Linux-x86/260.19.12/README/configtwinview.html
        +
        +        Check to see if 'DynamicTwinView' is enable:
        +            nvidia-settings -q :0/DynamicTwinview
        +
        +        To disable it (workaround), add the following option to your xorg.conf device section:
        +            Option "DynamicTwinView" "False"
        +
        +    NVidia RANDR Rotation:
        +        To enable it, add the following option to your xorg.conf device section:
        +            Option "RandRRotation" "on"
        + * 
        + * + */ +public class MonitorMode { + /** + * Immutable surfaceSize and refreshRate Class, consisting of it's read only components:
        + *
          + *
        • nativeId
        • + *
        • {@link SurfaceSize} surface memory size
        • + *
        • refresh rate
        • + *
        + */ + public static class SizeAndRRate { + public final SurfaceSize surfaceSize; + public final float refreshRate; + public final int flags; + public final int hashCode; + + public SizeAndRRate(SurfaceSize surfaceSize, float refreshRate, int flags) { + if(null==surfaceSize) { + throw new IllegalArgumentException("surfaceSize must be set ("+surfaceSize+")"); + } + this.surfaceSize=surfaceSize; + this.refreshRate=refreshRate; + this.flags = flags; + this.hashCode = getHashCode(); + } + + private final static String STR_INTERLACE = "Interlace"; + private final static String STR_DOUBLESCAN = "DoubleScan"; + private final static String STR_SEP = ", "; + + public static final StringBuffer flags2String(int flags) { + final StringBuffer sb = new StringBuffer(); + boolean sp = false; + if( 0 != ( flags & FLAG_INTERLACE ) ) { + sb.append(STR_INTERLACE); + sp = true; + } + if( 0 != ( flags & FLAG_DOUBLESCAN ) ) { + if( sp ) { + sb.append(STR_SEP); + } + sb.append(STR_DOUBLESCAN); + sp = true; + } + return sb; + } + public final String toString() { + return new String(surfaceSize+" @ "+refreshRate+" Hz, flags ["+flags2String(flags).toString()+"]"); + } + + /** + * Tests equality of two {@link SizeAndRRate} objects + * by evaluating equality of it's components:
        + *
          + *
        • surfaceSize
        • + *
        • refreshRate
        • + *
        • flags
        • + *
        + */ + public final boolean equals(Object obj) { + if (this == obj) { return true; } + if (obj instanceof SizeAndRRate) { + final SizeAndRRate p = (SizeAndRRate)obj; + return surfaceSize.equals(p.surfaceSize) && + refreshRate == p.refreshRate && + flags == p.flags ; + } + return false; + } + + /** + * Returns a combined hash code of it's elements:
        + *
          + *
        • surfaceSize
        • + *
        • refreshRate
        • + *
        • flags
        • + *
        + */ + public final int hashCode() { + return hashCode; + } + private final int getHashCode() { + // 31 * x == (x << 5) - x + int hash = 31 + surfaceSize.hashCode(); + hash = ((hash << 5) - hash) + (int)(refreshRate*100.0f); + hash = ((hash << 5) - hash) + flags; + return hash; + } + } + + /** zero rotation, compared to normal settings */ + public static final int ROTATE_0 = 0; + + /** 90 degrees CCW rotation */ + public static final int ROTATE_90 = 90; + + /** 180 degrees CCW rotation */ + public static final int ROTATE_180 = 180; + + /** 270 degrees CCW rotation */ + public static final int ROTATE_270 = 270; + + /** Frame is split into two fields. See {@link #getFlags()}. */ + public static final int FLAG_INTERLACE = 1 << 0; + + /** Lines are doubled. See {@link #getFlags()}. */ + public static final int FLAG_DOUBLESCAN = 1 << 1; + + /** The immutable native Id of this instance, which may not be unique. */ + private final int nativeId; + private final SizeAndRRate sizeAndRRate; + private final int rotation; + private final int hashCode; + + public static boolean isRotationValid(int rotation) { + return rotation == MonitorMode.ROTATE_0 || rotation == MonitorMode.ROTATE_90 || + rotation == MonitorMode.ROTATE_180 || rotation == MonitorMode.ROTATE_270 ; + } + + /** + * @param sizeAndRRate the surface size and refresh rate mode + * @param rotation the screen rotation, measured counter clockwise (CCW) + */ + public MonitorMode(int nativeId, SizeAndRRate sizeAndRRate, int rotation) { + if ( !isRotationValid(rotation) ) { + throw new RuntimeException("invalid rotation: "+rotation); + } + this.nativeId = nativeId; + this.sizeAndRRate = sizeAndRRate; + this.rotation = rotation; + this.hashCode = getHashCode(); + } + + /** + * Creates a user instance w/o {@link #getId() identity} to filter our matching modes w/ identity. + *

        + * See {@link com.jogamp.newt.util.MonitorModeUtil} for filter utilities. + *

        + * @param surfaceSize + * @param refreshRate + * @param flags + * @param rotation + */ + public MonitorMode(SurfaceSize surfaceSize, float refreshRate, int flags, int rotation) { + this(0, new SizeAndRRate(surfaceSize, refreshRate, flags), rotation); + } + + /** @return the immutable native Id of this mode, may not be unique, may be 0. */ + public final int getId() { return nativeId; } + + /** Returns the surfaceSize and refreshRate instance. */ + public final SizeAndRRate getSizeAndRRate() { + return sizeAndRRate; + } + + /** Returns the unrotated {@link SurfaceSize} */ + public final SurfaceSize getSurfaceSize() { + return sizeAndRRate.surfaceSize; + } + + public final float getRefreshRate() { + return sizeAndRRate.refreshRate; + } + + /** Returns bitfield w/ flags, i.e. {@link #FLAG_DOUBLESCAN}, {@link #FLAG_INTERLACE}, .. */ + public final int getFlags() { + return sizeAndRRate.flags; + } + + /** Returns the CCW rotation of this mode */ + public final int getRotation() { + return rotation; + } + + /** Returns the rotated screen width, + * derived from getMonitorMode().getSurfaceSize().getResolution() + * and getRotation() + */ + public final int getRotatedWidth() { + return getRotatedWH(true); + } + + /** Returns the rotated screen height, + * derived from getMonitorMode().getSurfaceSize().getResolution() + * and getRotation() + */ + public final int getRotatedHeight() { + return getRotatedWH(false); + } + + public final String toString() { + return "[Id "+Display.toHexString(nativeId)+", " + sizeAndRRate + ", " + rotation + " degr]"; + } + + /** + * Tests equality of two {@link MonitorMode} objects + * by evaluating equality of it's components:
        + *
          + *
        • nativeId
        • + *
        • sizeAndRRate
        • + *
        • rotation
        • + *
        + */ + public final boolean equals(Object obj) { + if (this == obj) { return true; } + if (obj instanceof MonitorMode) { + MonitorMode sm = (MonitorMode)obj; + return sm.nativeId == this.nativeId && + sm.sizeAndRRate.equals(sizeAndRRate) && + sm.rotation == this.rotation ; + } + return false; + } + + /** + * Returns a combined hash code of it's elements:
        + *
          + *
        • nativeId
        • + *
        • sizeAndRRate
        • + *
        • rotation
        • + *
        + */ + public final int hashCode() { + return hashCode; + } + private final int getHashCode() { + // 31 * x == (x << 5) - x + int hash = 31 + getId(); + hash = ((hash << 5) - hash) + sizeAndRRate.hashCode(); + hash = ((hash << 5) - hash) + getRotation(); + return hash; + } + + private final int getRotatedWH(boolean width) { + final DimensionImmutable d = sizeAndRRate.surfaceSize.getResolution(); + final boolean swap = MonitorMode.ROTATE_90 == rotation || MonitorMode.ROTATE_270 == rotation ; + if ( ( width && swap ) || ( !width && !swap ) ) { + return d.getHeight(); + } + return d.getWidth(); + } +} diff --git a/src/newt/classes/com/jogamp/newt/Screen.java b/src/newt/classes/com/jogamp/newt/Screen.java index a09748d52..81a62d898 100644 --- a/src/newt/classes/com/jogamp/newt/Screen.java +++ b/src/newt/classes/com/jogamp/newt/Screen.java @@ -27,14 +27,19 @@ */ package com.jogamp.newt; -import com.jogamp.newt.event.ScreenModeListener; +import com.jogamp.newt.event.MonitorModeListener; import jogamp.newt.Debug; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.NativeWindowException; +import javax.media.nativewindow.util.Rectangle; +import javax.media.nativewindow.util.RectangleImmutable; +/** + * A screen may span multiple {@link MonitorDevice}s representing their combined virtual size. + */ public abstract class Screen { /** @@ -122,25 +127,30 @@ public abstract class Screen { public abstract int getIndex(); /** - * @return the x position of the virtual top-left origin. + * @return the x position of the virtual viewport's top-left origin. */ public abstract int getX(); /** - * @return the y position of the virtual top-left origin. + * @return the y position of the virtual viewport's top-left origin. */ public abstract int getY(); /** - * @return the rotated virtual width. + * @return the rotated virtual viewport's width. */ public abstract int getWidth(); /** - * @return the rotated virtual height. + * @return the rotated virtual viewport's height. */ public abstract int getHeight(); + /** + * @return the rotated virtual viewport, i.e. origin and size. + */ + public abstract RectangleImmutable getViewport(); + /** * @return the associated Display */ @@ -152,48 +162,68 @@ public abstract class Screen { */ public abstract String getFQName(); - /** - * @param sml ScreenModeListener to be added for ScreenMode change events - */ - public abstract void addScreenModeListener(ScreenModeListener sml); - - /** - * @param sml ScreenModeListener to be removed from ScreenMode change events + /** + * Return a list of all available {@link MonitorMode}s for all {@link MonitorDevice}s. + *

        + * If {@link com.jogamp.newt.MonitorMode ScreenMode}s are not supported for this + * native type {@link com.jogamp.newt.Display#getType()}, it returns a list of size one with the current screen size.

        */ - public abstract void removeScreenModeListener(ScreenModeListener sml); + public abstract List getMonitorModes(); /** - * Return a list of available {@link com.jogamp.newt.ScreenMode ScreenMode}s. + * Return a list of all available {@link MonitorDevice}s. *

        - * If {@link com.jogamp.newt.ScreenMode ScreenMode}s are not supported for this + * If {@link com.jogamp.newt.MonitorMode ScreenMode}s are not supported for this * native type {@link com.jogamp.newt.Display#getType()}, it returns a list of size one with the current screen size.

        - * - * @return a shallow copy of the internal immutable {@link com.jogamp.newt.ScreenMode ScreenMode}s. */ - public abstract List getScreenModes(); + public abstract List getMonitorDevices(); /** - * Return the original {@link com.jogamp.newt.ScreenMode}, as used at NEWT initialization. - * @return original ScreenMode which is element of the list {@link #getScreenModes()}. + * Returns the {@link MonitorDevice} which {@link MonitorDevice#getViewport() viewport} + * {@link MonitorDevice#coverage(RectangleImmutable) covers} the given rectangle the most. + *

        + * If no coverage is detected the first {@link MonitorDevice} is returned. + *

        */ - public abstract ScreenMode getOriginalScreenMode(); + public final MonitorDevice getMainMonitor(RectangleImmutable r) { + MonitorDevice res = null; + float maxCoverage = Float.MIN_VALUE; + final List monitors = getMonitorDevices(); + for(int i=monitors.size()-1; i>=0; i--) { + final MonitorDevice monitor = monitors.get(i); + final float coverage = monitor.coverage(r); + if( coverage > maxCoverage ) { + maxCoverage = coverage; + res = monitor; + } + } + if( maxCoverage > 0.0f && null != res ) { + return res; + } + return monitors.get(0); + } /** - * Return the current {@link com.jogamp.newt.ScreenMode}. + * Returns the union of all monitor's {@link MonitorDevice#getViewport() viewport}. *

        - * If {@link com.jogamp.newt.ScreenMode ScreenMode}s are not supported for this - * native type {@link com.jogamp.newt.Display#getType()}, it returns one with the current screen size.

        - * - * @return current ScreenMode which is element of the list {@link #getScreenModes()}. + * Should be equal to {@link #getX()}, {@link #getY()}, {@link #getWidth()} and {@link #getHeight()}, + * however, some native toolkits may choose a different virtual screen area. + *

        + * @param result storage for result, will be returned + */ + public final Rectangle unionOfMonitorViewportSize(final Rectangle result) { + return MonitorDevice.unionOfViewports(result, getMonitorDevices()); + } + + /** + * @param sml {@link MonitorModeListener} to be added for {@link MonitorEvent} */ - public abstract ScreenMode getCurrentScreenMode(); + public abstract void addMonitorModeListener(MonitorModeListener sml); /** - * Set the current {@link com.jogamp.newt.ScreenMode}. - * @param screenMode to be made current, must be element of the list {@link #getScreenModes()}. - * @return true if successful, otherwise false + * @param sml {@link MonitorModeListener} to be removed from {@link MonitorEvent} */ - public abstract boolean setCurrentScreenMode(ScreenMode screenMode); + public abstract void removeMonitorModeListener(MonitorModeListener sml); // Global Screens protected static ArrayList screenList = new ArrayList(); @@ -236,6 +266,7 @@ public abstract class Screen { return null; } /** Returns the global display collection */ + @SuppressWarnings("unchecked") public static Collection getAllScreens() { ArrayList list; synchronized(screenList) { diff --git a/src/newt/classes/com/jogamp/newt/ScreenMode.java b/src/newt/classes/com/jogamp/newt/ScreenMode.java deleted file mode 100644 index 1f12217bb..000000000 --- a/src/newt/classes/com/jogamp/newt/ScreenMode.java +++ /dev/null @@ -1,208 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package com.jogamp.newt; - -import javax.media.nativewindow.util.DimensionImmutable; - -import com.jogamp.newt.util.MonitorMode; - -/** Immutable ScreenMode Class, consisting of it's read only components:
        - *
          - *
        • {@link com.jogamp.newt.util.MonitorMode}, non rotated values
        • - *
        • rotation, measured counter clockwise (CCW)
        • - *
        - * - * Aquire and filter ScreenModes
        - *
          - *
        • A List of read only ScreenMode's is being returned by {@link com.jogamp.newt.Screen#getScreenModes()}.
        • - *
        • You may utilize {@link com.jogamp.newt.util.ScreenModeUtil} to filter and select a desired ScreenMode.
        • - *
        • The current ScreenMode can be obtained via {@link com.jogamp.newt.Screen#getCurrentScreenMode()}.
        • - *
        • The initial original ScreenMode (at startup) can be obtained via {@link com.jogamp.newt.Screen#getOriginalScreenMode()}.
        • - *
        - *
        - * - * Changing ScreenModes
        - *
          - *
        • Use {@link com.jogamp.newt.Screen#setCurrentScreenMode(com.jogamp.newt.ScreenMode)}
        • - * to change the current ScreenMode of all Screen's referenced via the full qualified name (FQN) - * {@link com.jogamp.newt.Screen#getFQName()}. - *
        • When the last FQN referenced Screen closes, the original ScreenMode ({@link com.jogamp.newt.Screen#getOriginalScreenMode()}) - * is restored.
        • - *
        - *
        - * Example for changing the ScreenMode: - *
        -        // determine target refresh rate
        -        ScreenMode orig = screen.getOriginalScreenMode();
        -        int freq = orig.getMonitorMode().getRefreshRate();
        -
        -        // target resolution
        -        Dimension res = new Dimension(800, 600);
        -
        -        // target rotation
        -        int rot = 0;
        -
        -        // filter available ScreenModes
        -        List screenModes = screen.getScreenModes();
        -        screenModes = ScreenModeUtil.filterByRate(screenModes, freq); // get the nearest ones
        -        screenModes = ScreenModeUtil.filterByRotation(screenModes, rot);
        -        screenModes = ScreenModeUtil.filterByResolution(screenModes, res); // get the nearest ones
        -        screenModes = ScreenModeUtil.getHighestAvailableBpp(screenModes);
        -
        -        // pick 1st one ..
        -        screen.setCurrentScreenMode((ScreenMode) screenModes.get(0)); 
        - * 
        - * - * X11 / AMD just works
        - *
        - * X11 / NVidia difficulties - *
        -    NVidia RANDR RefreshRate Bug
        -        If NVidia's 'DynamicTwinView' is enabled, all refresh rates are
        -        unique, ie consequent numbers starting with the default refresh, ie 50, 51, ..
        -        The only way to workaround it is to disable 'DynamicTwinView'.
        -        Read: http://us.download.nvidia.com/XFree86/Linux-x86/260.19.12/README/configtwinview.html
        -
        -        Check to see if 'DynamicTwinView' is enable:
        -            nvidia-settings -q :0/DynamicTwinview
        -
        -        To disable it (workaround), add the following option to your xorg.conf device section:
        -            Option "DynamicTwinView" "False"
        -
        -    NVidia RANDR Rotation:
        -        To enable it, add the following option to your xorg.conf device section:
        -            Option "RandRRotation" "on"
        - * 
        - * - */ -public class ScreenMode { - /** zero rotation, compared to normal settings */ - public static final int ROTATE_0 = 0; - - /** 90 degrees CCW rotation */ - public static final int ROTATE_90 = 90; - - /** 180 degrees CCW rotation */ - public static final int ROTATE_180 = 180; - - /** 270 degrees CCW rotation */ - public static final int ROTATE_270 = 270; - - MonitorMode monitorMode; - int rotation; - - public static boolean isRotationValid(int rotation) { - return rotation == ScreenMode.ROTATE_0 || rotation == ScreenMode.ROTATE_90 || - rotation == ScreenMode.ROTATE_180 || rotation == ScreenMode.ROTATE_270 ; - } - - /** - * @param monitorMode the monitor mode - * @param rotation the screen rotation, measured counter clockwise (CCW) - */ - public ScreenMode(MonitorMode monitorMode, int rotation) { - if ( !isRotationValid(rotation) ) { - throw new RuntimeException("invalid rotation: "+rotation); - } - this.monitorMode = monitorMode; - this.rotation = rotation; - } - - /** Returns the unrotated MonitorMode */ - public final MonitorMode getMonitorMode() { - return monitorMode; - } - - /** Returns the CCW rotation of this mode */ - public final int getRotation() { - return rotation; - } - - /** Returns the rotated screen width, - * derived from getMonitorMode().getSurfaceSize().getResolution() - * and getRotation() - */ - public final int getRotatedWidth() { - return getRotatedWH(true); - } - - /** Returns the rotated screen height, - * derived from getMonitorMode().getSurfaceSize().getResolution() - * and getRotation() - */ - public final int getRotatedHeight() { - return getRotatedWH(false); - } - - public final String toString() { - return "[ " + getMonitorMode() + ", " + rotation + " degr ]"; - } - - /** - * Tests equality of two ScreenMode objects - * by evaluating equality of it's components:
        - *
          - *
        • monitorMode
        • - *
        • rotation
        • - *
        - *
        - */ - public final boolean equals(Object obj) { - if (this == obj) { return true; } - if (obj instanceof ScreenMode) { - ScreenMode sm = (ScreenMode)obj; - return sm.getMonitorMode().equals(getMonitorMode()) && - sm.getRotation() == this.getRotation() ; - } - return false; - } - - /** - * Returns a combined hash code of it's elements:
        - *
          - *
        • monitorMode
        • - *
        • rotation
        • - *
        - */ - public final int hashCode() { - // 31 * x == (x << 5) - x - int hash = 31 + getMonitorMode().hashCode(); - hash = ((hash << 5) - hash) + getRotation(); - return hash; - } - - private final int getRotatedWH(boolean width) { - final DimensionImmutable d = getMonitorMode().getSurfaceSize().getResolution(); - final boolean swap = ScreenMode.ROTATE_90 == rotation || ScreenMode.ROTATE_270 == rotation ; - if ( ( width && swap ) || ( !width && !swap ) ) { - return d.getHeight(); - } - return d.getWidth(); - } -} diff --git a/src/newt/classes/com/jogamp/newt/Window.java b/src/newt/classes/com/jogamp/newt/Window.java index ab1eef308..0bebf330a 100644 --- a/src/newt/classes/com/jogamp/newt/Window.java +++ b/src/newt/classes/com/jogamp/newt/Window.java @@ -28,6 +28,8 @@ package com.jogamp.newt; +import java.util.List; + import com.jogamp.newt.event.WindowEvent; import com.jogamp.newt.event.WindowListener; import com.jogamp.newt.event.KeyListener; @@ -41,6 +43,7 @@ import javax.media.nativewindow.CapabilitiesChooser; import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.WindowClosingProtocol; +import javax.media.nativewindow.util.RectangleImmutable; /** * Specifying NEWT's Window functionality: @@ -80,10 +83,19 @@ public interface Window extends NativeWindow, WindowClosingProtocol { boolean isNativeValid(); /** - * @return The associated Screen + * @return The associated {@link Screen} */ Screen getScreen(); + /** + * Returns the {@link MonitorDevice} which {@link MonitorDevice#getViewport() viewport} + * {@link MonitorDevice#coverage(RectangleImmutable) covers} this window the most. + *

        + * If no coverage is detected the first {@link MonitorDevice} is returned. + *

        + */ + MonitorDevice getMainMonitor(); + /** * Set the CapabilitiesChooser to help determine the native visual type. * @@ -344,8 +356,32 @@ public interface Window extends NativeWindow, WindowClosingProtocol { ReparentOperation reparentWindow(NativeWindow newParent, boolean forceDestroyCreate); + /** + * Enable or disable fullscreen mode for this window. + *

        + * Fullscreen mode is established on the {@link #getMainMonitor() main monitor}. + *

        + * @param fullscreen enable or disable fullscreen mode + * @return success + * @see #setFullscreen(List) + * @see #isFullscreen() + */ boolean setFullscreen(boolean fullscreen); + /** + * Enable fullscreen mode for this window spanning across the given {@link MonitorDevice}s + * or across all {@link MonitorDevice}s. + *

        + * Disable fullscreen via {@link #setFullscreen(boolean)}. + *

        + * @param monitors if null fullscreen will be spanned across all {@link MonitorDevice}s, + * otherwise across the given list of {@link MonitorDevice}. + * @return success + * @see #setFullscreen(boolean) + * @see #isFullscreen() + */ + boolean setFullscreen(List monitors); + boolean isFullscreen(); static interface FocusRunnable { diff --git a/src/newt/classes/com/jogamp/newt/event/MonitorEvent.java b/src/newt/classes/com/jogamp/newt/event/MonitorEvent.java new file mode 100644 index 000000000..c47936a7a --- /dev/null +++ b/src/newt/classes/com/jogamp/newt/event/MonitorEvent.java @@ -0,0 +1,71 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.newt.event; + +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; + +@SuppressWarnings("serial") +public class MonitorEvent extends OutputEvent { + public static final short EVENT_MONITOR_MODE_CHANGE_NOTIFY = 600; + public static final short EVENT_MONITOR_MODE_CHANGED = 601; + + private final MonitorMode mode; + + public MonitorEvent (short eventType, MonitorDevice source, long when, MonitorMode mode) { + super(eventType, source, when); + this.mode = mode; + } + + /** Returns the {@link #getSource() source}, which is a {@link MonitorDevice}. */ + public final MonitorDevice getMonitor() { return (MonitorDevice)source; } + + public final MonitorMode getMode() { return mode; } + + public static String getEventTypeString(short type) { + switch(type) { + case EVENT_MONITOR_MODE_CHANGE_NOTIFY: return "EVENT_MONITOR_MODE_CHANGE_NOTIFY"; + case EVENT_MONITOR_MODE_CHANGED: return "EVENT_MONITOR_MODE_CHANGED"; + default: return "unknown (" + type + ")"; + } + } + + public final String toString() { + return toString(null).toString(); + } + + public final StringBuilder toString(StringBuilder sb) { + if(null == sb) { + sb = new StringBuilder(); + } + sb.append("MonitorEvent[").append(getEventTypeString(getEventType())).append(", source ").append(source) + .append(", mode ").append(mode).append(", "); + return super.toString(sb).append("]"); + } +} diff --git a/src/newt/classes/com/jogamp/newt/event/MonitorModeListener.java b/src/newt/classes/com/jogamp/newt/event/MonitorModeListener.java new file mode 100644 index 000000000..11e23def1 --- /dev/null +++ b/src/newt/classes/com/jogamp/newt/event/MonitorModeListener.java @@ -0,0 +1,37 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.newt.event; + +public interface MonitorModeListener { + /** called before the monitor mode will be changed */ + void monitorModeChangeNotify(MonitorEvent me); + + /** called after the monitor mode has been changed */ + void monitorModeChanged(MonitorEvent me, boolean success); +} diff --git a/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java b/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java index ea96f634f..c1bc791d8 100644 --- a/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java @@ -41,9 +41,10 @@ package com.jogamp.newt.event; * * Event type registry:
        *
          - *
        • WindowEvent 100..10x
        • - *
        • MouseEvent 200..20x
        • - *
        • KeyEvent 300..30x
        • + *
        • WindowEvent 100..10x
        • + *
        • MouseEvent 200..20x
        • + *
        • KeyEvent 300..30x
        • + *
        • MonitorEvent 600..60x
        • *

        */ @SuppressWarnings("serial") diff --git a/src/newt/classes/com/jogamp/newt/event/OutputEvent.java b/src/newt/classes/com/jogamp/newt/event/OutputEvent.java new file mode 100644 index 000000000..86fa95877 --- /dev/null +++ b/src/newt/classes/com/jogamp/newt/event/OutputEvent.java @@ -0,0 +1,51 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.newt.event; + +@SuppressWarnings("serial") +public abstract class OutputEvent extends NEWTEvent +{ + protected OutputEvent(short eventType, Object source, long when) { + super(eventType, source, when); + } + + /** + public String toString() { + return toString(null).toString(); + } + + public StringBuilder toString(StringBuilder sb) { + if(null == sb) { + sb = new StringBuilder(); + } + sb.append("OutputEvent["); + super.toString(sb).append("]"); + return sb; + } */ +} diff --git a/src/newt/classes/com/jogamp/newt/event/ScreenModeListener.java b/src/newt/classes/com/jogamp/newt/event/ScreenModeListener.java deleted file mode 100644 index 7bca23cfe..000000000 --- a/src/newt/classes/com/jogamp/newt/event/ScreenModeListener.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package com.jogamp.newt.event; - -import com.jogamp.newt.ScreenMode; - -public interface ScreenModeListener { - /** called before the screen mode will be changed */ - void screenModeChangeNotify(ScreenMode sm); - - /** called after the screen mode has been changed */ - void screenModeChanged(ScreenMode sm, boolean success); -} diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index de62747be..1500d48e6 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -34,6 +34,8 @@ package com.jogamp.newt.opengl; +import java.util.List; + import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.CapabilitiesChooser; import javax.media.nativewindow.CapabilitiesImmutable; @@ -64,6 +66,7 @@ import jogamp.opengl.GLDrawableImpl; import com.jogamp.common.GlueGenVersion; import com.jogamp.common.util.VersionUtil; import com.jogamp.common.util.locks.RecursiveLock; +import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; import com.jogamp.newt.Window; @@ -224,6 +227,11 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind return window.getScreen(); } + @Override + public final MonitorDevice getMainMonitor() { + return window.getMainMonitor(); + } + @Override public final void setTitle(String title) { window.setTitle(title); @@ -341,6 +349,11 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind public final boolean setFullscreen(boolean fullscreen) { return window.setFullscreen(fullscreen); } + + @Override + public boolean setFullscreen(List monitors) { + return window.setFullscreen(monitors); + } @Override public final boolean isFullscreen() { diff --git a/src/newt/classes/com/jogamp/newt/util/MonitorMode.java b/src/newt/classes/com/jogamp/newt/util/MonitorMode.java deleted file mode 100644 index 8104f207a..000000000 --- a/src/newt/classes/com/jogamp/newt/util/MonitorMode.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package com.jogamp.newt.util; - -import javax.media.nativewindow.util.*; - -/** Immutable MonitorMode Class, consisting of it's read only components:
        - *
          - *
        • {@link javax.media.nativewindow.util.SurfaceSize} surface memory size
        • - *
        • {@link javax.media.nativewindow.util.DimensionImmutable} size in [mm]
        • - *
        • refresh rate
        • - *
        - */ -public class MonitorMode { - SurfaceSize surfaceSize; - DimensionImmutable screenSizeMM; // in [mm] - int refreshRate; - - public MonitorMode(SurfaceSize surfaceSize, DimensionImmutable screenSizeMM, int refreshRate) { - // Don't validate screenSizeMM and refreshRate, since they may not be supported by the OS - if(null==surfaceSize) { - throw new IllegalArgumentException("surfaceSize must be set ("+surfaceSize+")"); - } - this.surfaceSize=surfaceSize; - this.screenSizeMM=screenSizeMM; - this.refreshRate=refreshRate; - } - - public final SurfaceSize getSurfaceSize() { - return surfaceSize; - } - - public final DimensionImmutable getScreenSizeMM() { - return screenSizeMM; - } - - public final int getRefreshRate() { - return refreshRate; - } - - public final String toString() { - return new String("[ "+surfaceSize+" x "+refreshRate+" Hz, "+screenSizeMM+" mm ]"); - } - - /** - * Checks whether two size objects are equal. Two instances - * of MonitorMode are equal if the three components - * surfaceSize and refreshRate - * are equal. screenSizeMM is kept out intentional to reduce the requirements for finding the current mode. - * @return true if the two dimensions are equal; - * otherwise false. - */ - public final boolean equals(Object obj) { - if (this == obj) { return true; } - if (obj instanceof MonitorMode) { - MonitorMode p = (MonitorMode)obj; - return getSurfaceSize().equals(p.getSurfaceSize()) && - /* getScreenSizeMM().equals(p.getScreenSizeMM()) && */ - getRefreshRate() == p.getRefreshRate() ; - } - return false; - } - - /** - * returns a hash code over surfaceSize and refreshRate. - * screenSizeMM is kept out intentional to reduce the requirements for finding the current mode. - */ - public final int hashCode() { - // 31 * x == (x << 5) - x - int hash = 31 + getSurfaceSize().hashCode(); - /* hash = ((hash << 5) - hash) + getScreenSizeMM().hashCode(); */ - hash = ((hash << 5) - hash) + getRefreshRate(); - return hash; - } -} - diff --git a/src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java b/src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java new file mode 100644 index 000000000..16ffe754f --- /dev/null +++ b/src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java @@ -0,0 +1,247 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.newt.util; + +import com.jogamp.newt.MonitorMode; + +import java.util.ArrayList; +import java.util.List; +import javax.media.nativewindow.util.DimensionImmutable; +import javax.media.nativewindow.util.SurfaceSize; + +/** + * Convenient {@link com.jogamp.newt.MonitorMode} utility methods, + * filters etc. + */ +public class MonitorModeUtil { + + public static int getIndex(List monitorModes, MonitorMode search) { + return monitorModes.indexOf(search); + } + + public static int getIndexByHashCode(List monitorModes, MonitorMode search) { + if( null!=monitorModes && monitorModes.size()>0 ) { + for (int i=0; i monitorModes, MonitorMode.SizeAndRRate sizeAndRate, int modeId, int rotation) { + if( null!=monitorModes && monitorModes.size()>0 ) { + for (int i=0; i filterBySurfaceSize(List monitorModes, SurfaceSize surfaceSize) { + final List out = new ArrayList(); + if( null!=monitorModes && monitorModes.size()>0 ) { + for (int i=0; null!=monitorModes && i filterByRotation(List monitorModes, int rotation) { + final List out = new ArrayList(); + if( null!=monitorModes && monitorModes.size()>0 ) { + for (int i=0; null!=monitorModes && i filterByBpp(List monitorModes, int bitsPerPixel) { + final List out = new ArrayList(); + if( null!=monitorModes && monitorModes.size()>0 ) { + for (int i=0; null!=monitorModes && i filterByFlags(List monitorModes, int flags) { + final List out = new ArrayList(); + if( null!=monitorModes && monitorModes.size()>0 ) { + for (int i=0; null!=monitorModes && i filterByResolution(List monitorModes, DimensionImmutable resolution) { + final List out = new ArrayList(); + if( null!=monitorModes && monitorModes.size()>0 ) { + final int resolution_sq = resolution.getHeight()*resolution.getWidth(); + int mode_dsq=Integer.MAX_VALUE, mode_dsq_idx=0; + + for (int i=0; null!=monitorModes && i filterByRate(List monitorModes, float refreshRate) { + final List out = new ArrayList(); + if( null!=monitorModes && monitorModes.size()>0 ) { + float mode_dr = Float.MAX_VALUE; + int mode_dr_idx = -1; + for (int i=0; null!=monitorModes && i getHighestAvailableBpp(List monitorModes) { + if( null!=monitorModes && monitorModes.size()>0 ) { + int highest = -1; + for (int i=0; null!=monitorModes && i < monitorModes.size(); i++) { + final MonitorMode mode = monitorModes.get(i); + final int bpp = mode.getSurfaceSize().getBitsPerPixel(); + if (bpp > highest) { + highest = bpp; + } + } + return filterByBpp(monitorModes, highest); + } + return new ArrayList(); + } + + /** + * + * @param monitorModes + * @return modes with highest available refresh rate. May return zero sized list for non. + */ + public static List getHighestAvailableRate(List monitorModes) { + if( null!=monitorModes && monitorModes.size()>0 ) { + float highest = -1; + for (int i=0; null!=monitorModes && i < monitorModes.size(); i++) { + final MonitorMode mode = monitorModes.get(i); + final float rate = mode.getRefreshRate(); + if (rate > highest) { + highest = rate; + } + } + return filterByRate(monitorModes, highest); + } + return new ArrayList(); + } + +} diff --git a/src/newt/classes/com/jogamp/newt/util/ScreenModeUtil.java b/src/newt/classes/com/jogamp/newt/util/ScreenModeUtil.java deleted file mode 100644 index 93797c5fb..000000000 --- a/src/newt/classes/com/jogamp/newt/util/ScreenModeUtil.java +++ /dev/null @@ -1,341 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package com.jogamp.newt.util; - -import com.jogamp.common.util.ArrayHashSet; -import com.jogamp.newt.ScreenMode; -import java.util.ArrayList; -import java.util.List; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.DimensionImmutable; -import javax.media.nativewindow.util.SurfaceSize; - -/** - * Convenient {@link com.jogamp.newt.ScreenMode} utility methods, - * filters etc. - */ -public class ScreenModeUtil { - /** WARNING: must be synchronized with ScreenMode.h, native implementation - * 2: width and height - */ - public static final int NUM_RESOLUTION_PROPERTIES = 2; - - /** WARNING: must be synchronized with ScreenMode.h, native implementation - * 1: bpp - */ - public static final int NUM_SURFACE_SIZE_PROPERTIES = 1; - - /** WARNING: must be synchronized with ScreenMode.h, native implementation - * 3: ScreenSizeMM[width, height], refresh-rate - */ - public static final int NUM_MONITOR_MODE_PROPERTIES = 3; - - /** WARNING: must be synchronized with ScreenMode.h, native implementation - * 1: rotation, native_mode_id - */ - public static final int NUM_SCREEN_MODE_PROPERTIES = 1; - - /** WARNING: must be synchronized with ScreenMode.h, native implementation - * count + all the above - */ - public static final int NUM_SCREEN_MODE_PROPERTIES_ALL = 8; - - public static int getIndex(List screenModes, ScreenMode search) { - return screenModes.indexOf(search); - } - - public static int getIndexByHashCode(List screenModes, ScreenMode search) { - for (int i=0; null!=screenModes && i filterByResolution(List screenModes, DimensionImmutable resolution) { - if(null==screenModes || screenModes.size()==0) { - return null; - } - List out = new ArrayList(); - int resolution_sq = resolution.getHeight()*resolution.getWidth(); - int sm_dsq=resolution_sq, sm_dsq_idx=0; - - for (int i=0; null!=screenModes && i0) { - return out; - } - // nearest .. - resolution = screenModes.get(sm_dsq_idx).getMonitorMode().getSurfaceSize().getResolution(); - return filterByResolution(screenModes, resolution); - } - - public static List filterBySurfaceSize(List screenModes, SurfaceSize surfaceSize) { - if(null==screenModes || screenModes.size()==0) { - return null; - } - List out = new ArrayList(); - for (int i=0; null!=screenModes && i0 ? out : null; - } - - public static List filterByRotation(List screenModes, int rotation) { - if(null==screenModes || screenModes.size()==0) { - return null; - } - List out = new ArrayList(); - for (int i=0; null!=screenModes && i0 ? out : null; - } - - public static List filterByBpp(List screenModes, int bitsPerPixel) { - if(null==screenModes || screenModes.size()==0) { - return null; - } - List out = new ArrayList(); - for (int i=0; null!=screenModes && i0 ? out : null; - } - - /** - * - * @param screenModes - * @param refreshRate - * @return modes with nearest refreshRate, or matching ones - */ - public static List filterByRate(List screenModes, int refreshRate) { - if(null==screenModes || screenModes.size()==0) { - return null; - } - int sm_dr = refreshRate; - int sm_dr_idx = -1; - List out = new ArrayList(); - for (int i=0; null!=screenModes && i0) { - return out; - } - refreshRate = screenModes.get(sm_dr_idx).getMonitorMode().getRefreshRate(); - return filterByRate(screenModes, refreshRate); - } - - public static List getHighestAvailableBpp(List screenModes) { - if(null==screenModes || screenModes.size()==0) { - return null; - } - int highest = -1; - for (int i=0; null!=screenModes && i < screenModes.size(); i++) { - ScreenMode sm = screenModes.get(i); - int bpp = sm.getMonitorMode().getSurfaceSize().getBitsPerPixel(); - if (bpp > highest) { - highest = bpp; - } - } - return filterByBpp(screenModes, highest); - } - - public static List getHighestAvailableRate(List screenModes) { - if(null==screenModes || screenModes.size()==0) { - return null; - } - int highest = -1; - for (int i=0; null!=screenModes && i < screenModes.size(); i++) { - ScreenMode sm = screenModes.get(i); - int rate = sm.getMonitorMode().getRefreshRate(); - if (rate > highest) { - highest = rate; - } - } - return filterByRate(screenModes, highest); - } - - /** WARNING: must be synchronized with ScreenMode.h, native implementation */ - public static DimensionImmutable streamInResolution(int[] resolutionProperties, int offset) { - Dimension resolution = new Dimension(resolutionProperties[offset++], resolutionProperties[offset++]); - return resolution; - } - - /** WARNING: must be synchronized with ScreenMode.h, native implementation */ - public static SurfaceSize streamInSurfaceSize(DimensionImmutable resolution, int[] sizeProperties, int offset) { - SurfaceSize surfaceSize = new SurfaceSize(resolution, sizeProperties[offset++]); - return surfaceSize; - } - - /** WARNING: must be synchronized with ScreenMode.h, native implementation */ - public static MonitorMode streamInMonitorMode(SurfaceSize surfaceSize, DimensionImmutable screenSizeMM, int[] monitorProperties, int offset) { - int refreshRate = monitorProperties[offset++]; - return new MonitorMode(surfaceSize, screenSizeMM, refreshRate); - } - - /** WARNING: must be synchronized with ScreenMode.h, native implementation */ - public static ScreenMode streamInScreenMode(MonitorMode monitorMode, int[] modeProperties, int offset) { - int rotation = modeProperties[offset++]; - return new ScreenMode(monitorMode, rotation); - } - - /** - * WARNING: must be synchronized with ScreenMode.h, native implementation - * - * @param modeProperties the input data - * @param offset the offset to the input data - * @return ScreenMode element matching the input modeProperties, - * or null if input could not be processed. - */ - public static ScreenMode streamIn(int[] modeProperties, int offset) { - return streamInImpl(null, null, null, null, null, modeProperties, offset); - } - - /** - * WARNING: must be synchronized with ScreenMode.h, native implementation - * - * @param resolutionPool hash array of unique resolutions, no duplicates - * @param surfaceSizePool hash array of unique SurfaceSize, no duplicates - * @param monitorModePool hash array of unique MonitorMode, no duplicates - * @param screenModePool hash array of unique ScreenMode, no duplicates - * @param modeProperties the input data - * @param offset the offset to the input data - * @return index of the identical (old or new) ScreenMode element in screenModePool, - * matching the input modeProperties, or -1 if input could not be processed. - */ - public static int streamIn(ArrayHashSet resolutionPool, - ArrayHashSet surfaceSizePool, - ArrayHashSet screenSizeMMPool, - ArrayHashSet monitorModePool, - ArrayHashSet screenModePool, - int[] modeProperties, int offset) { - ScreenMode screenMode = streamInImpl(resolutionPool, surfaceSizePool, screenSizeMMPool, monitorModePool, screenModePool, - modeProperties, offset); - return screenModePool.indexOf(screenMode); - } - - - private static ScreenMode streamInImpl(ArrayHashSet resolutionPool, - ArrayHashSet surfaceSizePool, - ArrayHashSet screenSizeMMPool, - ArrayHashSet monitorModePool, - ArrayHashSet screenModePool, - int[] modeProperties, int offset) { - int count = modeProperties[offset]; - if(NUM_SCREEN_MODE_PROPERTIES_ALL != count) { - throw new RuntimeException("NUM_SCREEN_MODE_PROPERTIES should be "+NUM_SCREEN_MODE_PROPERTIES_ALL+", is "+count+", len "+(modeProperties.length-offset)); - } - if(NUM_SCREEN_MODE_PROPERTIES_ALL > modeProperties.length-offset) { - throw new RuntimeException("properties array too short, should be >= "+NUM_SCREEN_MODE_PROPERTIES_ALL+", is "+(modeProperties.length-offset)); - } - offset++; - DimensionImmutable resolution = ScreenModeUtil.streamInResolution(modeProperties, offset); - offset += ScreenModeUtil.NUM_RESOLUTION_PROPERTIES; - if(null!=resolutionPool) { - resolution = resolutionPool.getOrAdd(resolution); - } - - SurfaceSize surfaceSize = ScreenModeUtil.streamInSurfaceSize(resolution, modeProperties, offset); - offset += ScreenModeUtil.NUM_SURFACE_SIZE_PROPERTIES; - if(null!=surfaceSizePool) { - surfaceSize = surfaceSizePool.getOrAdd(surfaceSize); - } - - DimensionImmutable screenSizeMM = ScreenModeUtil.streamInResolution(modeProperties, offset); - offset += ScreenModeUtil.NUM_RESOLUTION_PROPERTIES; - if(null!=screenSizeMMPool) { - screenSizeMM = screenSizeMMPool.getOrAdd(screenSizeMM); - } - - MonitorMode monitorMode = ScreenModeUtil.streamInMonitorMode(surfaceSize, screenSizeMM, modeProperties, offset); - offset += ScreenModeUtil.NUM_MONITOR_MODE_PROPERTIES - ScreenModeUtil.NUM_RESOLUTION_PROPERTIES; - if(null!=monitorModePool) { - monitorMode = monitorModePool.getOrAdd(monitorMode); - } - - ScreenMode screenMode = ScreenModeUtil.streamInScreenMode(monitorMode, modeProperties, offset); - if(null!=screenModePool) { - screenMode = screenModePool.getOrAdd(screenMode); - } - return screenMode; - } - - /** WARNING: must be synchronized with ScreenMode.h, native implementation */ - public static int[] streamOut (ScreenMode screenMode) { - int[] data = new int[NUM_SCREEN_MODE_PROPERTIES_ALL]; - int idx=0; - data[idx++] = NUM_SCREEN_MODE_PROPERTIES_ALL; - data[idx++] = screenMode.getMonitorMode().getSurfaceSize().getResolution().getWidth(); - data[idx++] = screenMode.getMonitorMode().getSurfaceSize().getResolution().getHeight(); - data[idx++] = screenMode.getMonitorMode().getSurfaceSize().getBitsPerPixel(); - data[idx++] = screenMode.getMonitorMode().getScreenSizeMM().getWidth(); - data[idx++] = screenMode.getMonitorMode().getScreenSizeMM().getHeight(); - data[idx++] = screenMode.getMonitorMode().getRefreshRate(); - data[idx++] = screenMode.getRotation(); - if(NUM_SCREEN_MODE_PROPERTIES_ALL != idx) { - throw new InternalError("wrong number of attributes: got "+idx+" != should "+NUM_SCREEN_MODE_PROPERTIES_ALL); - } - return data; - } - -} diff --git a/src/newt/classes/jogamp/newt/MonitorDeviceImpl.java b/src/newt/classes/jogamp/newt/MonitorDeviceImpl.java new file mode 100644 index 000000000..96daed54a --- /dev/null +++ b/src/newt/classes/jogamp/newt/MonitorDeviceImpl.java @@ -0,0 +1,147 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.newt; + +import javax.media.nativewindow.util.DimensionImmutable; +import javax.media.nativewindow.util.Rectangle; + +import com.jogamp.common.util.ArrayHashSet; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; +import com.jogamp.newt.Screen; + +public class MonitorDeviceImpl extends MonitorDevice { + + public MonitorDeviceImpl(ScreenImpl screen, int nativeId, DimensionImmutable sizeMM, Rectangle viewport, MonitorMode currentMode, ArrayHashSet supportedModes) { + super(screen, nativeId, sizeMM, viewport, currentMode, supportedModes); + } + + @Override + public final MonitorMode queryCurrentMode() { + final ScreenImpl screenImpl = (ScreenImpl)screen; + final ScreenMonitorState sms = screenImpl.getScreenMonitorStatus(true); + sms.lock(); + try { + final MonitorMode mm0 = screenImpl.queryCurrentMonitorModeIntern(this); + if(null == mm0) { + throw new InternalError("getCurrentMonitorModeIntern() == null"); + } + MonitorMode mmU = supportedModes.get(mm0); // unified instance + if( null == mmU ) { + // add new mode avoiding exception! + mmU = sms.getMonitorModes().getOrAdd(mm0); + mmU = supportedModes.getOrAdd(mmU); + if( Screen.DEBUG ) { + System.err.println("Adding new mode: "+mm0+" -> "+mmU); + } + } + // if mode has changed somehow, update it .. + if( getCurrentMode().hashCode() != mmU.hashCode() ) { + setCurrentModeValue(mmU); + sms.fireScreenModeChanged(this, mmU, true); + } + return mmU; + } finally { + sms.unlock(); + } + } + + @Override + public final boolean setCurrentMode(MonitorMode mode) { + if(Screen.DEBUG) { + System.err.println("Screen.setCurrentScreenMode.0: "+this+" -> "+mode); + } + final ScreenImpl screenImpl = (ScreenImpl)screen; + final ScreenMonitorState sms = screenImpl.getScreenMonitorStatus(true); + sms.lock(); + try { + final MonitorMode mmC = queryCurrentMode(); + final MonitorMode mmU = supportedModes.get(mode); // unify via value hash + if( null == mmU ) { + throw new IllegalArgumentException("Given mode not in set of modes. Current mode "+mode+", "+this); + } + if( mmU.equals( mmC ) ) { + if(Screen.DEBUG) { + System.err.println("Screen.setCurrentScreenMode: 0.0 is-current (skip) "+mmU+" == "+mmC); + } + return true; + } + final long tStart; + if(Screen.DEBUG) { + tStart = System.nanoTime(); + } else { + tStart = 0; + } + + sms.fireScreenModeChangeNotify(this, mmU); + if(Screen.DEBUG) { + System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tStart)/1e6+"ms): fireScreenModeChangeNotify() "+mmU); + } + + boolean success = screenImpl.setCurrentMonitorModeImpl(this, mmU); + if(success) { + if(Screen.DEBUG) { + System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tStart)/1e6+"ms): setCurrentScreenModeImpl() "+mmU+", success(1): "+success); + } + } else { + // 2nd attempt validate! + final MonitorMode queriedCurrent = queryCurrentMode(); // may fireScreenModeChanged(..) if successful and differs! + success = queriedCurrent.hashCode() == mmU.hashCode() ; + if(Screen.DEBUG) { + System.err.println("Screen.setCurrentScreenMode.2: queried "+queriedCurrent); + System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tStart)/1e6+"ms): setCurrentScreenModeImpl() "+mmU+", success(2): "+success); + } + } + if( success ) { + setCurrentModeValue(mmU); + modeChanged = !isOriginalMode(); + } + sms.fireScreenModeChanged(this, mmU, success); + if(Screen.DEBUG) { + System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tStart)/1e6+"ms): X.X "+this+", success: "+success); + } + return success; + } finally { + sms.unlock(); + } + } + + private final void setCurrentModeValue(MonitorMode currentMode) { + this.currentMode = currentMode; + } + + /* pp */ final void setViewportValue(Rectangle viewport) { + this.viewport = viewport; + } + + /* pp */ ArrayHashSet getSupportedModesImpl() { + return supportedModes; + } + +} \ No newline at end of file diff --git a/src/newt/classes/jogamp/newt/MonitorModeProps.java b/src/newt/classes/jogamp/newt/MonitorModeProps.java new file mode 100644 index 000000000..820807e15 --- /dev/null +++ b/src/newt/classes/jogamp/newt/MonitorModeProps.java @@ -0,0 +1,355 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package jogamp.newt; + +import com.jogamp.common.util.ArrayHashSet; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; + +import java.util.List; +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.DimensionImmutable; +import javax.media.nativewindow.util.Rectangle; +import javax.media.nativewindow.util.SurfaceSize; + +import jogamp.newt.MonitorDeviceImpl; +import jogamp.newt.ScreenImpl; + +/** + * Encodes and decodes {@link MonitorMode} and {@link MonitorDevice} properties. + */ +public class MonitorModeProps { + /** WARNING: must be synchronized with ScreenMode.h, native implementation + * 2: width, height + */ + public static final int NUM_RESOLUTION_PROPERTIES = 2; + + /** WARNING: must be synchronized with ScreenMode.h, native implementation + * 1: bpp + */ + public static final int NUM_SURFACE_SIZE_PROPERTIES = 1; + + /** WARNING: must be synchronized with ScreenMode.h, native implementation + * 2: refresh-rate (Hz*100), flags + */ + public static final int NUM_SIZEANDRATE_PROPERTIES = 2; + + /** WARNING: must be synchronized with ScreenMode.h, native implementation + * 2: id, rotation + */ + public static final int NUM_MONITOR_MODE_PROPERTIES = 2; + + /** WARNING: must be synchronized with ScreenMode.h, native implementation + * count + all the above + */ + public static final int NUM_MONITOR_MODE_PROPERTIES_ALL = 8; + + public static final int IDX_MONITOR_MODE_BPP = 1 // count + + MonitorModeProps.NUM_RESOLUTION_PROPERTIES + ; + public static final int IDX_MONITOR_MODE_ROT = 1 // count + + MonitorModeProps.NUM_RESOLUTION_PROPERTIES + + MonitorModeProps.NUM_SURFACE_SIZE_PROPERTIES + + MonitorModeProps.NUM_SIZEANDRATE_PROPERTIES + + 1 // id of MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES + ; + + /** WARNING: must be synchronized with ScreenMode.h, native implementation + * 10: count + id, ScreenSizeMM[width, height], rotated Viewport[x, y, width, height], currentMonitorModeId, rotation, supportedModeId+ + */ + public static final int MIN_MONITOR_DEVICE_PROPERTIES = 11; + + public static final int IDX_MONITOR_DEVICE_VIEWPORT = 1 // count + + 1 // native mode + + MonitorModeProps.NUM_RESOLUTION_PROPERTIES // sizeMM + ; + + public static class Cache { + public final ArrayHashSet resolutions = new ArrayHashSet(); + public final ArrayHashSet surfaceSizes = new ArrayHashSet(); + public final ArrayHashSet sizeAndRates = new ArrayHashSet(); + public final ArrayHashSet monitorModes = new ArrayHashSet(); + public final ArrayHashSet monitorDevices = new ArrayHashSet(); + } + + /** WARNING: must be synchronized with ScreenMode.h, native implementation */ + private static DimensionImmutable streamInResolution(int[] resolutionProperties, int offset) { + Dimension resolution = new Dimension(resolutionProperties[offset++], resolutionProperties[offset++]); + return resolution; + } + + /** WARNING: must be synchronized with ScreenMode.h, native implementation */ + private static SurfaceSize streamInSurfaceSize(DimensionImmutable resolution, int[] sizeProperties, int offset) { + SurfaceSize surfaceSize = new SurfaceSize(resolution, sizeProperties[offset++]); + return surfaceSize; + } + + /** WARNING: must be synchronized with ScreenMode.h, native implementation */ + private static MonitorMode.SizeAndRRate streamInSizeAndRRate(SurfaceSize surfaceSize, int[] sizeAndRRateProperties, int offset) { + final float refreshRate = sizeAndRRateProperties[offset++]/100.0f; + final int flags = sizeAndRRateProperties[offset++]; + return new MonitorMode.SizeAndRRate(surfaceSize, refreshRate, flags); + } + + /** WARNING: must be synchronized with ScreenMode.h, native implementation */ + private static MonitorMode streamInMonitorMode0(MonitorMode.SizeAndRRate sizeAndRate, int[] modeProperties, int offset) { + final int id = modeProperties[offset++]; + final int rotation = modeProperties[offset++]; + return new MonitorMode(id, sizeAndRate, rotation); + } + + /** + * WARNING: must be synchronized with ScreenMode.h, native implementation + * + * @param mode_idx if not null and cache is given, returns the index of resulting {@link MonitorMode} within {@link Cache#monitorModes}. + * @param cache optional hash arrays of unique {@link MonitorMode} components and {@link MonitorDevice}s, allowing to avoid duplicates + * @param modeProperties the input data + * @param offset the offset to the input data + * @return {@link MonitorMode} of the identical (old or new) element in {@link Cache#monitorModes}, + * matching the input modeProperties, or null if input could not be processed. + */ + public static MonitorMode streamInMonitorMode(int[] mode_idx, Cache cache, + int[] modeProperties, int offset) { + final int count = modeProperties[offset]; + if(NUM_MONITOR_MODE_PROPERTIES_ALL != count) { + throw new RuntimeException("property count should be "+NUM_MONITOR_MODE_PROPERTIES_ALL+", but is "+count+", len "+(modeProperties.length-offset)); + } + if(NUM_MONITOR_MODE_PROPERTIES_ALL > modeProperties.length-offset) { + throw new RuntimeException("properties array too short, should be >= "+NUM_MONITOR_MODE_PROPERTIES_ALL+", is "+(modeProperties.length-offset)); + } + offset++; + DimensionImmutable resolution = MonitorModeProps.streamInResolution(modeProperties, offset); + offset += MonitorModeProps.NUM_RESOLUTION_PROPERTIES; + if(null!=cache) { + resolution = cache.resolutions.getOrAdd(resolution); + } + + SurfaceSize surfaceSize = MonitorModeProps.streamInSurfaceSize(resolution, modeProperties, offset); + offset += MonitorModeProps.NUM_SURFACE_SIZE_PROPERTIES; + if(null!=cache) { + surfaceSize = cache.surfaceSizes.getOrAdd(surfaceSize); + } + + MonitorMode.SizeAndRRate sizeAndRate = MonitorModeProps.streamInSizeAndRRate(surfaceSize, modeProperties, offset); + offset += MonitorModeProps.NUM_SIZEANDRATE_PROPERTIES; + if(null!=cache) { + sizeAndRate = cache.sizeAndRates.getOrAdd(sizeAndRate); + } + + MonitorMode monitorMode = MonitorModeProps.streamInMonitorMode0(sizeAndRate, modeProperties, offset); + if(null!=cache) { + monitorMode = cache.monitorModes.getOrAdd(monitorMode); + } + if( null != mode_idx && null!=cache) { + int _modeIdx = cache.monitorModes.indexOf(monitorMode); + if( 0 > _modeIdx ) { + throw new InternalError("Invalid index of current unified mode "+monitorMode); + } + mode_idx[0] = _modeIdx; + } + return monitorMode; + } + + /** WARNING: must be synchronized with ScreenMode.h, native implementation */ + public static int[] streamOutMonitorMode (MonitorMode monitorMode) { + int[] data = new int[NUM_MONITOR_MODE_PROPERTIES_ALL]; + int idx=0; + data[idx++] = NUM_MONITOR_MODE_PROPERTIES_ALL; + data[idx++] = monitorMode.getSurfaceSize().getResolution().getWidth(); + data[idx++] = monitorMode.getSurfaceSize().getResolution().getHeight(); + data[idx++] = monitorMode.getSurfaceSize().getBitsPerPixel(); + data[idx++] = (int)(monitorMode.getRefreshRate()*100.0f); // Hz*100 + data[idx++] = monitorMode.getFlags(); + data[idx++] = monitorMode.getId(); + data[idx++] = monitorMode.getRotation(); + if(NUM_MONITOR_MODE_PROPERTIES_ALL != idx) { + throw new InternalError("wrong number of attributes: got "+idx+" != should "+NUM_MONITOR_MODE_PROPERTIES_ALL); + } + return data; + } + + /** + * WARNING: must be synchronized with ScreenMode.h, native implementation + *

        + * Note: This variant only works for impl. w/ a unique mode key pair modeId, rotation. + *

        + * @param mode_idx if not null, returns the index of resulting {@link MonitorDevice} within {@link Cache#monitorDevices}. + * @param cache hash arrays of unique {@link MonitorMode} components and {@link MonitorDevice}s, allowing to avoid duplicates + * @param modeProperties the input data + * @param offset the offset to the input data + * @return {@link MonitorDevice} of the identical (old or new) element in {@link Cache#monitorDevices}, + * matching the input modeProperties, or null if input could not be processed. + */ + public static MonitorDevice streamInMonitorDevice(int[] monitor_idx, Cache cache, ScreenImpl screen, int[] monitorProperties, int offset) { + // min 11: count, id, ScreenSizeMM[width, height], Viewport[x, y, width, height], currentMonitorModeId, rotation, supportedModeId+ + final int count = monitorProperties[offset]; + if(MIN_MONITOR_DEVICE_PROPERTIES > count) { + throw new RuntimeException("property count should be >= "+MIN_MONITOR_DEVICE_PROPERTIES+", but is "+count+", len "+(monitorProperties.length-offset)); + } + if(MIN_MONITOR_DEVICE_PROPERTIES > monitorProperties.length-offset) { + throw new RuntimeException("properties array too short (min), should be >= "+MIN_MONITOR_DEVICE_PROPERTIES+", is "+(monitorProperties.length-offset)); + } + if(count > monitorProperties.length-offset) { + throw new RuntimeException("properties array too short (count), should be >= "+count+", is "+(monitorProperties.length-offset)); + } + final int limit = offset + count; + offset++; + final List allMonitorModes = cache.monitorModes.getData(); + final int id = monitorProperties[offset++]; + final DimensionImmutable sizeMM = streamInResolution(monitorProperties, offset); offset+=NUM_RESOLUTION_PROPERTIES; + final Rectangle viewport = new Rectangle(monitorProperties[offset++], monitorProperties[offset++], monitorProperties[offset++], monitorProperties[offset++]); + final MonitorMode currentMode; + { + final int modeId = monitorProperties[offset++]; + final int rotation = monitorProperties[offset++]; + currentMode = getByNativeIdAndRotation(allMonitorModes, modeId, rotation); + } + final ArrayHashSet supportedModes = new ArrayHashSet(); + while( offset < limit ) { + final int modeId = monitorProperties[offset++]; + for (int i=0; i _monitorIdx ) { + throw new InternalError("Invalid index of current unified mode "+monitorDevice); + } + monitor_idx[0] = _monitorIdx; + } + return monitorDevice; + } + private static MonitorMode getByNativeIdAndRotation(List monitorModes, int modeId, int rotation) { + if( null!=monitorModes && monitorModes.size()>0 ) { + for (int i=0; i + * This variant expects count to be {@link MIN_MONITOR_DEVICE_PROPERTIES} - 1 - {@link NUM_MONITOR_MODE_PROPERTIES}, + * due to lack of supported mode and current mode. + *

        + * + * @param mode_idx if not null, returns the index of resulting {@link MonitorDevice} within {@link Cache#monitorDevices}. + * @param cache hash arrays of unique {@link MonitorMode} components and {@link MonitorDevice}s, allowing to avoid duplicates + * @param supportedModes pre-assembled list of supported {@link MonitorMode}s from cache. + * @param currentMode pre-fetched current {@link MonitorMode}s from cache. + * @param modeProperties the input data minus supported modes! + * @param offset the offset to the input data + * @return {@link MonitorDevice} of the identical (old or new) element in {@link Cache#monitorDevices}, + * matching the input modeProperties, or null if input could not be processed. + */ + public static MonitorDevice streamInMonitorDevice(int[] monitor_idx, Cache cache, ScreenImpl screen, ArrayHashSet supportedModes, MonitorMode currentMode, int[] monitorProperties, int offset) { + // min 11: count, id, ScreenSizeMM[width, height], Viewport[x, y, width, height], currentMonitorModeId, rotation, supportedModeId+ + final int count = monitorProperties[offset]; + if(MIN_MONITOR_DEVICE_PROPERTIES - 1 - NUM_MONITOR_MODE_PROPERTIES != count) { + throw new RuntimeException("property count should be == "+(MIN_MONITOR_DEVICE_PROPERTIES-1-NUM_MONITOR_MODE_PROPERTIES)+", but is "+count+", len "+(monitorProperties.length-offset)); + } + if(MIN_MONITOR_DEVICE_PROPERTIES - 1 - NUM_MONITOR_MODE_PROPERTIES > monitorProperties.length-offset) { + throw new RuntimeException("properties array too short (min), should be >= "+(MIN_MONITOR_DEVICE_PROPERTIES-1-NUM_MONITOR_MODE_PROPERTIES)+", is "+(monitorProperties.length-offset)); + } + if(count > monitorProperties.length-offset) { + throw new RuntimeException("properties array too short (count), should be >= "+count+", is "+(monitorProperties.length-offset)); + } + offset++; + final int id = monitorProperties[offset++]; + final DimensionImmutable sizeMM = streamInResolution(monitorProperties, offset); offset+=NUM_RESOLUTION_PROPERTIES; + final Rectangle viewport = new Rectangle(monitorProperties[offset++], monitorProperties[offset++], monitorProperties[offset++], monitorProperties[offset++]); + MonitorDevice monitorDevice = new MonitorDeviceImpl(screen, id, sizeMM, viewport, currentMode, supportedModes); + if(null!=cache) { + monitorDevice = cache.monitorDevices.getOrAdd(monitorDevice); + } + if( null != monitor_idx ) { + int _monitorIdx = cache.monitorDevices.indexOf(monitorDevice); + if( 0 > _monitorIdx ) { + throw new InternalError("Invalid index of current unified mode "+monitorDevice); + } + monitor_idx[0] = _monitorIdx; + } + return monitorDevice; + } + + /** WARNING: must be synchronized with ScreenMode.h, native implementation */ + public static int[] streamOutMonitorDevice (MonitorDevice monitorDevice) { + // min 11: count, id, ScreenSizeMM[width, height], Viewport[x, y, width, height], currentMonitorModeId, rotation, supportedModeId+ + int supportedModeCount = monitorDevice.getSupportedModes().size(); + if( 0 == supportedModeCount ) { + throw new RuntimeException("no supported modes: "+monitorDevice); + } + int[] data = new int[MIN_MONITOR_DEVICE_PROPERTIES + supportedModeCount - 1]; + int idx=0; + data[idx++] = data.length; + data[idx++] = monitorDevice.getId(); + data[idx++] = monitorDevice.getSizeMM().getWidth(); + data[idx++] = monitorDevice.getSizeMM().getHeight(); + data[idx++] = monitorDevice.getViewport().getX(); + data[idx++] = monitorDevice.getViewport().getY(); + data[idx++] = monitorDevice.getViewport().getWidth(); + data[idx++] = monitorDevice.getViewport().getHeight(); + data[idx++] = monitorDevice.getCurrentMode().getId(); + data[idx++] = monitorDevice.getCurrentMode().getRotation(); + final List supportedModes = monitorDevice.getSupportedModes(); + for(int i=0; i monitors) { + return false; // nop + } + + protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { sizeChanged(false, width, height, false); if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { diff --git a/src/newt/classes/jogamp/newt/ScreenImpl.java b/src/newt/classes/jogamp/newt/ScreenImpl.java index 1282e5dc5..4d20fdb83 100644 --- a/src/newt/classes/jogamp/newt/ScreenImpl.java +++ b/src/newt/classes/jogamp/newt/ScreenImpl.java @@ -43,22 +43,19 @@ import java.util.List; import javax.media.nativewindow.AbstractGraphicsScreen; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.DimensionImmutable; -import javax.media.nativewindow.util.Point; -import javax.media.nativewindow.util.SurfaceSize; - +import javax.media.nativewindow.util.Rectangle; +import javax.media.nativewindow.util.RectangleImmutable; import com.jogamp.common.util.ArrayHashSet; -import com.jogamp.common.util.IntIntHashMap; import com.jogamp.newt.Display; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.event.ScreenModeListener; -import com.jogamp.newt.util.MonitorMode; -import com.jogamp.newt.util.ScreenModeUtil; +import com.jogamp.newt.event.MonitorEvent; +import com.jogamp.newt.event.MonitorModeListener; -public abstract class ScreenImpl extends Screen implements ScreenModeListener { +public abstract class ScreenImpl extends Screen implements MonitorModeListener { protected static final boolean DEBUG_TEST_SCREENMODE_DISABLED = Debug.isPropertyDefined("newt.test.Screen.disableScreenMode", true); public static final int default_sm_bpp = 32; @@ -73,11 +70,11 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { protected int hashCode; protected AbstractGraphicsScreen aScreen; protected int refCount; // number of Screen references by Window - protected Point vOrigin = new Point(0, 0); // virtual top-left origin - protected Dimension vSize = new Dimension(0, 0); // virtual rotated screen size + protected Rectangle vOriginSize = new Rectangle(0, 0, 0, 0); // virtual rotated screen origin and size protected static Dimension usrSize = null; // property values: newt.ws.swidth and newt.ws.sheight protected static volatile boolean usrSizeQueried = false; - private ArrayList referencedScreenModeListener = new ArrayList(); + private ArrayList referencedScreenModeListener = new ArrayList(); + private long tCreated; // creationTime static { @@ -160,10 +157,12 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { return true; } + @Override public int hashCode() { return hashCode; } + @Override public synchronized final void createNative() throws NativeWindowException { @@ -182,8 +181,7 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { throw new NativeWindowException("Screen.createNative() failed to instanciate an AbstractGraphicsScreen"); } - initScreenModeStatus(); - updateVirtualScreenOriginAndSize(); + initScreenMonitorState(); if(DEBUG) { System.err.println("Screen.createNative() END ("+DisplayImpl.getThreadName()+", "+this+"), total "+ (System.nanoTime()-tCreated)/1e6 +"ms"); } @@ -191,10 +189,11 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { screensActive++; } } - ScreenModeStatus sms = ScreenModeStatus.getScreenModeStatus(this.getFQName()); + ScreenMonitorState sms = ScreenMonitorState.getScreenMonitorState(this.getFQName()); sms.addListener(this); } + @Override public synchronized final void destroy() { releaseScreenModeStatus(); @@ -213,6 +212,7 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { display.removeReference(); } + @Override public synchronized final int addReference() throws NativeWindowException { if(DEBUG) { System.err.println("Screen.addReference() ("+DisplayImpl.getThreadName()+"): "+refCount+" -> "+(refCount+1)); @@ -227,6 +227,7 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { return ++refCount; } + @Override public synchronized final int removeReference() { if(DEBUG) { System.err.println("Screen.removeReference() ("+DisplayImpl.getThreadName()+"): "+refCount+" -> "+(refCount-1)); @@ -240,6 +241,7 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { return refCount; } + @Override public synchronized final int getReferenceCount() { return refCount; } @@ -259,14 +261,20 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { /** * Stores the virtual origin and virtual rotated screen size. *

        - * This method is called after the ScreenMode has been set, + * This method is called after the ScreenMode has been set or changed, * hence you may utilize it. - *

        - * @param virtualOrigin the store for the virtual origin - * @param virtualSize the store for the virtual rotated size + *

        + *

        + * Default implementation uses the union of all monitor's viewport, + * calculated via {@link #unionOfMonitorViewportSize()}. + *

        + * @param vOriginSize storage for result */ - protected abstract void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize); + protected void calcVirtualScreenOriginAndSize(final Rectangle vOriginSize) { + unionOfMonitorViewportSize(vOriginSize); + } + @Override public final String getFQName() { return fqname; } @@ -275,258 +283,227 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { * Updates the rotated virtual ScreenSize using the native impl. */ protected void updateVirtualScreenOriginAndSize() { - getVirtualScreenOriginAndSize(vOrigin, vSize); - if(DEBUG) { - System.err.println("Detected virtual screen origin "+vOrigin+", size "+vSize); + if(null != usrSize ) { + vOriginSize.setX(0); + vOriginSize.setY(0); + vOriginSize.setWidth(usrSize.getWidth()); + vOriginSize.setHeight(usrSize.getHeight()); + if(DEBUG) { + System.err.println("User virtual screen viewport "+vOriginSize); + } + } else { + calcVirtualScreenOriginAndSize(vOriginSize); + if(DEBUG) { + System.err.println("Detected virtual screen viewport "+vOriginSize); + } } } + @Override public final Display getDisplay() { return display; } + @Override public final int getIndex() { return screen_idx; } + @Override public final AbstractGraphicsScreen getGraphicsScreen() { return aScreen; } + @Override public synchronized final boolean isNativeValid() { return null != aScreen; } - public int getX() { return vOrigin.getX(); } - public int getY() { return vOrigin.getY(); } - - public final int getWidth() { - return (null != usrSize) ? usrSize.getWidth() : vSize.getWidth(); - } - - public final int getHeight() { - return (null != usrSize) ? usrSize.getHeight() : vSize.getHeight(); - } + @Override + public final int getX() { return vOriginSize.getX(); } + @Override + public final int getY() { return vOriginSize.getY(); } + @Override + public final int getWidth() { return vOriginSize.getWidth(); } + @Override + public final int getHeight() { return vOriginSize.getHeight(); } + @Override + public final RectangleImmutable getViewport() { return vOriginSize; } @Override public String toString() { - return "NEWT-Screen["+getFQName()+", idx "+screen_idx+", refCount "+refCount+", "+getWidth()+"x"+getHeight()+", "+aScreen+", "+display+"]"; + return "NEWT-Screen["+getFQName()+", idx "+screen_idx+", refCount "+refCount+", vsize "+vOriginSize+", "+aScreen+", "+display+ + ", monitors: "+getMonitorDevices()+"]"; } - public final List getScreenModes() { - ArrayHashSet screenModes = getScreenModesOrig(); - if(null != screenModes && 0 < screenModes.size()) { - return screenModes.toArrayList(); - } - return null; + // + // MonitorDevice and MonitorMode + // + + /** + * To be implemented by the native specification.
        + * Is called within a thread safe environment.
        + * Is called only to collect the {@link MonitorMode}s and {@link MonitorDevice}s, usually at startup setting up modes.
        + *
        + * WARNING: must be synchronized with + *
          + *
        • {@link MonitorModeProps#NUM_SCREEN_MODE_PROPERTIES} and
        • + *
        • {@link MonitorModeProps#MIN_MONITOR_DEVICE_PROPERTIES}
        • + *
        , i.e. + *
          + *
        • {@link MonitorModeProps#streamInMonitorDevice(int[], jogamp.newt.MonitorModeProps.Cache, ScreenImpl, int[], int)}
        • + *
        • {@link MonitorModeProps#streamInMonitorDevice(int[], jogamp.newt.MonitorModeProps.Cache, ScreenImpl, ArrayHashSet, int[], int)}
        • + *
        • {@link MonitorModeProps#streamInMonitorMode(int[], jogamp.newt.MonitorModeProps.Cache, int[], int)}
        • + *
        + * @param cache memory pool caching the result + */ + protected abstract void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache); + + protected Rectangle getNativeMonitorDeviceViewportImpl(MonitorDevice monitor) { return null; } + + /** + * To be implemented by the native specification.
        + * Is called within a thread safe environment.
        + *

        + * Implementation shall not unify the result w/ monitor's supported modes or a locally + * saved {@link MonitorModeProps.Cache}, since caller will perform such tasks. + *

        + */ + protected abstract MonitorMode queryCurrentMonitorModeImpl(MonitorDevice monitor); + + /** + * To be implemented by the native specification.
        + * Is called within a thread safe environment.
        + */ + protected abstract boolean setCurrentMonitorModeImpl(MonitorDevice monitor, MonitorMode mode); + + @Override + public final List getMonitorModes() { + final ScreenMonitorState sms = getScreenMonitorStatus(false); + return null != sms ? sms.getMonitorModes().getData() : null; + } + + @Override + public final List getMonitorDevices() { + final ScreenMonitorState sms = getScreenMonitorStatus(false); + return null != sms ? sms.getMonitorDevices().getData() : null; } - private final ScreenModeStatus getScreenModeStatus(boolean throwException) { + final ScreenMonitorState getScreenMonitorStatus(boolean throwException) { final String key = this.getFQName(); - final ScreenModeStatus res = ScreenModeStatus.getScreenModeStatus(key); + final ScreenMonitorState res = ScreenMonitorState.getScreenMonitorState(key); if(null == res & throwException) { - throw new InternalError("ScreenModeStatus.getScreenModeStatus("+key+") == null"); + throw new InternalError("ScreenMonitorStatus.getScreenModeStatus("+key+") == null"); } return res; } - public ScreenMode getOriginalScreenMode() { - final ScreenModeStatus sms = getScreenModeStatus(false); - return ( null != sms ) ? sms.getOriginalScreenMode() : null ; - } - - public ScreenMode getCurrentScreenMode() { - ScreenMode smU = null; - final ScreenModeStatus sms = getScreenModeStatus(true); - final ScreenMode sm0 = getCurrentScreenModeIntern(); - if(null == sm0) { - throw new InternalError("getCurrentScreenModeImpl() == null"); + @Override + public void monitorModeChangeNotify(MonitorEvent me) { + if(DEBUG) { + System.err.println("monitorModeChangeNotify: "+me); } - sms.lock(); - try { - smU = sms.getScreenModes().getOrAdd(sm0); // unified instance, maybe new - - // if mode has changed somehow, update it .. - if( sms.getCurrentScreenMode().hashCode() != smU.hashCode() ) { - sms.fireScreenModeChanged(smU, true); - } - } finally { - sms.unlock(); + for(int i=0; i monitors = getMonitorDevices(); + for(int i=monitors.size()-1; i>=0; i--) { + final MonitorDeviceImpl monitor = (MonitorDeviceImpl) monitors.get(i); + final Rectangle newViewport = getNativeMonitorDeviceViewportImpl(monitor); + if( DEBUG ) { + System.err.println("Screen.updateMonitorViewport["+i+"]: "+monitor.getViewport()+" -> "+newViewport); } - - sms.fireScreenModeChangeNotify(smU); - if(DEBUG) { - System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tStart)/1e6+"ms): fireScreenModeChangeNotify() "+smU); + if( null != newViewport ) { + monitor.setViewportValue(newViewport); } - - success = setCurrentScreenModeImpl(smU); - if(success) { - if(DEBUG) { - System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tStart)/1e6+"ms): setCurrentScreenModeImpl() "+smU+", success(1): "+success); - } - } else { - // 2nd attempt validate! - final ScreenMode queriedCurrent = getCurrentScreenMode(); // may fireScreenModeChanged(..) if successful and differs! - final ScreenMode smsCurrent = sms.getCurrentScreenMode(); - success = smsCurrent.hashCode() == smU.hashCode() && queriedCurrent.hashCode() == smU.hashCode() ; - if(DEBUG) { - System.err.println("Screen.setCurrentScreenMode.2: queried "+queriedCurrent); - System.err.println("Screen.setCurrentScreenMode.2: SMS "+smsCurrent); - System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tStart)/1e6+"ms): setCurrentScreenModeImpl() "+smU+", success(2): "+success); - } - } - sms.fireScreenModeChanged(smU, success); - if(DEBUG) { - System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tStart)/1e6+"ms): X.X "+smU+", success: "+success); - } - } finally { - sms.unlock(); - } - return success; + } } - - public void screenModeChangeNotify(ScreenMode sm) { - for(int i=0; i getScreenModesOrig() { - ScreenModeStatus sms = ScreenModeStatus.getScreenModeStatus(this.getFQName()); - if(null!=sms) { - return sms.getScreenModes(); - } - return null; - } - - /** ScreenModeStatus bridge to native implementation */ - protected final IntIntHashMap getScreenModesIdx2NativeIdx() { - ScreenModeStatus sms = ScreenModeStatus.getScreenModeStatus(this.getFQName()); - if(null!=sms) { - return sms.getScreenModesIdx2NativeIdx(); - } - return null; - } - - /** - * To be implemented by the native specification.
        - * Is called within a thread safe environment.
        - * Is called only to collect the ScreenModes, usually at startup setting up modes.
        - *
        - * WARNING: must be synchronized with {@link com.jogamp.newt.util.ScreenModeUtil#NUM_SCREEN_MODE_PROPERTIES}, - * ie {@link com.jogamp.newt.util.ScreenModeUtil#streamIn(com.jogamp.common.util.ArrayHashSet, com.jogamp.common.util.ArrayHashSet, com.jogamp.common.util.ArrayHashSet, com.jogamp.common.util.ArrayHashSet, int[], int)}
        - *
        - * Note: Additional 1st element is native mode id. - */ - protected int[] getScreenModeFirstImpl() { - return null; - } - - /** - * To be implemented by the native specification.
        - * Is called within a thread safe environment.
        - * Is called only to collect the ScreenModes, usually at startup setting up modes.
        - *
        - * WARNING: must be synchronized with {@link com.jogamp.newt.util.ScreenModeUtil#NUM_SCREEN_MODE_PROPERTIES}, - * ie {@link com.jogamp.newt.util.ScreenModeUtil#streamIn(com.jogamp.common.util.ArrayHashSet, com.jogamp.common.util.ArrayHashSet, com.jogamp.common.util.ArrayHashSet, com.jogamp.common.util.ArrayHashSet, int[], int)}
        - *
        - * Note: Additional 1st element is native mode id. - */ - protected int[] getScreenModeNextImpl() { - return null; + + private final MonitorMode getVirtualMonitorMode(int modeId) { + final int[] props = new int[MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL]; + int i = 0; + props[i++] = MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL; + props[i++] = getWidth(); // width + props[i++] = getHeight(); // height + props[i++] = default_sm_bpp; + props[i++] = default_sm_rate * 100; + props[i++] = 0; // flags + props[i++] = modeId; + props[i++] = default_sm_rotation; + if( MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL != i ) { + throw new InternalError("XX"); + } + return MonitorModeProps.streamInMonitorMode(null, null, props, 0); } - - /** - * To be implemented by the native specification.
        - * Is called within a thread safe environment.
        - */ - protected ScreenMode getCurrentScreenModeImpl() { - return null; + + private final MonitorDevice getVirtualMonitorDevice(int monitorId, MonitorMode currentMode) { + int[] props = new int[MonitorModeProps.MIN_MONITOR_DEVICE_PROPERTIES]; + int i = 0; + props[i++] = MonitorModeProps.MIN_MONITOR_DEVICE_PROPERTIES; + props[i++] = monitorId; + props[i++] = default_sm_widthmm; + props[i++] = default_sm_heightmm; + props[i++] = 0; // rotated viewport x + props[i++] = 0; // rotated viewport y + props[i++] = currentMode.getRotatedWidth(); // rotated viewport width + props[i++] = currentMode.getRotatedHeight(); // rotated viewport height + props[i++] = currentMode.getId(); // current mode id + props[i++] = currentMode.getRotation(); + props[i++] = currentMode.getId(); // supported mode id #1 + if( MonitorModeProps.MIN_MONITOR_DEVICE_PROPERTIES != i ) { + throw new InternalError("XX"); + } + return MonitorModeProps.streamInMonitorDevice(null, null, this, props, 0); } /** - * Utilizes {@link #getCurrentScreenModeImpl()}, if the latter returns null it uses + * Utilizes {@link #getCurrentMonitorModeImpl()}, if the latter returns null it uses * the current screen size and dummy values. */ - protected ScreenMode getCurrentScreenModeIntern() { - ScreenMode res; + protected final MonitorMode queryCurrentMonitorModeIntern(MonitorDevice monitor) { + MonitorMode res; if(DEBUG_TEST_SCREENMODE_DISABLED) { res = null; } else { - res = getCurrentScreenModeImpl(); + res = queryCurrentMonitorModeImpl(monitor); } if(null == res) { if( 0>=getWidth() || 0>=getHeight() ) { updateVirtualScreenOriginAndSize(); } - int[] props = new int[ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL]; - int i = 0; - props[i++] = 0; // set later for verification of iterator - props[i++] = getWidth(); // width - props[i++] = getHeight(); // height - props[i++] = default_sm_bpp; - props[i++] = default_sm_widthmm; - props[i++] = default_sm_heightmm; - props[i++] = default_sm_rate; - props[i++] = default_sm_rotation; - props[i - ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL] = i; // count - res = ScreenModeUtil.streamIn(props, 0); + res = getVirtualMonitorMode(monitor.getCurrentMode().getId()); } return res; } - /** - * To be implemented by the native specification.
        - * Is called within a thread safe environment.
        - */ - protected boolean setCurrentScreenModeImpl(ScreenMode screenMode) { - return false; - } - - private ScreenModeStatus initScreenModeStatus() { + private final ScreenMonitorState initScreenMonitorState() { long t0; if(DEBUG) { t0 = System.nanoTime(); @@ -535,138 +512,139 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener { t0 = 0; } - ScreenModeStatus sms; - ScreenModeStatus.lockScreenModeStatus(); + boolean vScrnSizeUpdated = false; + ScreenMonitorState sms; + ScreenMonitorState.lockScreenMonitorState(); try { - sms = ScreenModeStatus.getScreenModeStatus(this.getFQName()); - if(null==sms) { - IntIntHashMap screenModesIdx2NativeIdx = new IntIntHashMap(); - final ScreenMode currentSM = getCurrentScreenModeIntern(); - if(null == currentSM) { - throw new InternalError("getCurrentScreenModeImpl() == null"); + sms = ScreenMonitorState.getScreenMonitorState(this.getFQName()); + if(null==sms) { + final MonitorModeProps.Cache cache = new MonitorModeProps.Cache(); + if( 0 >= collectNativeMonitorModes(cache) ) { + updateVirtualScreenOriginAndSize(); + vScrnSizeUpdated = true; + final MonitorMode mode = getVirtualMonitorMode(0); + cache.monitorModes.getOrAdd(mode); + final MonitorDevice monitor = getVirtualMonitorDevice(0, mode); + cache.monitorDevices.getOrAdd(monitor); } - - ArrayHashSet screenModes = collectNativeScreenModes(screenModesIdx2NativeIdx); - screenModes.getOrAdd(currentSM); if(DEBUG) { int i=0; - for(Iterator iter=screenModes.iterator(); iter.hasNext(); i++) { - System.err.println(i+": "+iter.next()); + for(Iterator iMode=cache.monitorModes.iterator(); iMode.hasNext(); i++) { + System.err.println("All["+i+"]: "+iMode.next()); + } + i=0; + for(Iterator iMonitor=cache.monitorDevices.iterator(); iMonitor.hasNext(); i++) { + final MonitorDevice crt = iMonitor.next(); + System.err.println("["+i+"]: "+crt); + int j=0; + for(Iterator iMode=crt.getSupportedModes().iterator(); iMode.hasNext(); j++) { + System.err.println("["+i+"]["+j+"]: "+iMode.next()); + } } } - - sms = new ScreenModeStatus(screenModes, screenModesIdx2NativeIdx); - ScreenMode originalScreenMode0 = screenModes.get(currentSM); // unify via value hash - if(null == originalScreenMode0) { - throw new RuntimeException(currentSM+" could not be hashed from ScreenMode list"); - } - sms.setOriginalScreenMode(originalScreenMode0); - ScreenModeStatus.mapScreenModeStatus(this.getFQName(), sms); + sms = new ScreenMonitorState(cache.monitorDevices, cache.monitorModes); + ScreenMonitorState.mapScreenMonitorState(this.getFQName(), sms); } } finally { - ScreenModeStatus.unlockScreenModeStatus(); + ScreenMonitorState.unlockScreenMonitorState(); } if(DEBUG) { System.err.println("Screen.initScreenModeStatus() END dt "+ (System.nanoTime()-t0)/1e6 +"ms"); } + if( !vScrnSizeUpdated ) { + updateVirtualScreenOriginAndSize(); + } + return sms; } - /** ignores bpp < 15 */ - private ArrayHashSet collectNativeScreenModes(IntIntHashMap screenModesIdx2NativeId) { - ArrayHashSet resolutionPool = new ArrayHashSet(); - ArrayHashSet surfaceSizePool = new ArrayHashSet(); - ArrayHashSet screenSizeMMPool = new ArrayHashSet(); - ArrayHashSet monitorModePool = new ArrayHashSet(); - ArrayHashSet screenModePool = new ArrayHashSet(); - - int[] smProps = null; - int num = 0; - final int idxBpp = 1 // native mode - + 1 // count - + ScreenModeUtil.NUM_RESOLUTION_PROPERTIES - + ScreenModeUtil.NUM_SURFACE_SIZE_PROPERTIES - - 1 ; // index 0 based - do { - if(DEBUG_TEST_SCREENMODE_DISABLED) { - smProps = null; - } else if(0 == num) { - smProps = getScreenModeFirstImpl(); - } else { - smProps = getScreenModeNextImpl(); - } - if(null != smProps && 0 < smProps.length && smProps[idxBpp] >= 15) { - int nativeId = smProps[0]; - int screenModeIdx = ScreenModeUtil.streamIn(resolutionPool, surfaceSizePool, screenSizeMMPool, - monitorModePool, screenModePool, smProps, 1); - if(DEBUG) { - System.err.println("ScreenImpl.collectNativeScreenModes: #"+num+": idx: "+nativeId+" native -> "+screenModeIdx+" newt"); + /** + * Returns the number of successful collected {@link MonitorDevice}s. + *

        + * Collects {@link MonitorDevice}s and {@link MonitorMode}s within the given cache. + *

        + */ + private final int collectNativeMonitorModes(MonitorModeProps.Cache cache) { + if(!DEBUG_TEST_SCREENMODE_DISABLED) { + collectNativeMonitorModesAndDevicesImpl(cache); + } + // filter out insufficient modes + for(int i=cache.monitorModes.size()-1; i>=0; i--) { + final MonitorMode mode = cache.monitorModes.get(i); + if( 16 > mode.getSurfaceSize().getBitsPerPixel() ) { + boolean keep = false; + for(int j=cache.monitorDevices.size()-1; !keep && j>=0; j--) { + final MonitorDevice monitor = cache.monitorDevices.get(j); + keep = monitor.getCurrentMode().equals(mode); } - - if(screenModeIdx >= 0) { - screenModesIdx2NativeId.put(screenModeIdx, nativeId); + if(!keep) { + cache.monitorModes.remove(i); + for(int j=cache.monitorDevices.size()-1; j>=0; j--) { + final MonitorDeviceImpl monitor = (MonitorDeviceImpl) cache.monitorDevices.get(j); + monitor.getSupportedModesImpl().remove(mode); + } } - } else if(DEBUG) { - System.err.println("ScreenImpl.collectNativeScreenModes: #"+num+": smProps: "+(null!=smProps)+ - ", len: "+(null != smProps ? smProps.length : 0)+ - ", bpp: "+(null != smProps && 0 < smProps.length ? smProps[idxBpp] : 0)+ - " - DROPPING"); } - num++; - } while ( null != smProps && 0 < smProps.length ); - - if(DEBUG) { - System.err.println("ScreenImpl.collectNativeScreenModes: ScreenMode number : "+screenModePool.size()); - System.err.println("ScreenImpl.collectNativeScreenModes: MonitorMode number : "+monitorModePool.size()); - System.err.println("ScreenImpl.collectNativeScreenModes: ScreenSizeMM number: "+screenSizeMMPool.size()); - System.err.println("ScreenImpl.collectNativeScreenModes: SurfaceSize number : "+surfaceSizePool.size()); - System.err.println("ScreenImpl.collectNativeScreenModes: Resolution number : "+resolutionPool.size()); } - - return screenModePool; + if( DEBUG ) { + System.err.println("ScreenImpl.collectNativeMonitorModes: MonitorDevice number : "+cache.monitorDevices.size()); + System.err.println("ScreenImpl.collectNativeMonitorModes: MonitorMode number : "+cache.monitorModes.size()); + System.err.println("ScreenImpl.collectNativeMonitorModes: SizeAndRate number : "+cache.sizeAndRates.size()); + System.err.println("ScreenImpl.collectNativeMonitorModes: SurfaceSize number : "+cache.surfaceSizes.size()); + System.err.println("ScreenImpl.collectNativeMonitorModes: Resolution number : "+cache.resolutions.size()); + } + return cache.monitorDevices.size(); } private void releaseScreenModeStatus() { - ScreenModeStatus sms; - ScreenModeStatus.lockScreenModeStatus(); + ScreenMonitorState sms; + ScreenMonitorState.lockScreenMonitorState(); try { - sms = ScreenModeStatus.getScreenModeStatus(getFQName()); + sms = ScreenMonitorState.getScreenMonitorState(getFQName()); if(null != sms) { sms.lock(); try { if(0 == sms.removeListener(this)) { - if(sms.isOriginalModeChangedByOwner()) { - System.err.println("Screen.destroy(): "+sms.getCurrentScreenMode()+" -> "+sms.getOriginalScreenMode()); - try { - setCurrentScreenMode(sms.getOriginalScreenMode()); - } catch (Throwable t) { - // be verbose but continue - t.printStackTrace(); + final ArrayList monitorDevices = sms.getMonitorDevices().getData(); + for(int i=0; i "+sms.getOriginalScreenMode()); - setCurrentScreenModeImpl(sms.getOriginalScreenMode()); - } catch (Throwable t) { - // be quiet .. shutdown + final ArrayList monitorDevices = sms.getMonitorDevices().getData(); + for(int i=0; i screenModes; - private IntIntHashMap screenModesIdx2NativeIdx; - private ScreenMode currentScreenMode; - private ScreenMode originalScreenMode; - private boolean screenModeChangedByOwner; - private ArrayList listener = new ArrayList(); - - private static HashMap screenFQN2ScreenModeStatus = new HashMap(); - private static RecursiveLock screen2ScreenModeStatusLock = LockFactory.createRecursiveLock(); - - protected static void mapScreenModeStatus(String screenFQN, ScreenModeStatus sms) { - screen2ScreenModeStatusLock.lock(); - try { - ScreenModeStatus _sms = screenFQN2ScreenModeStatus.get(screenFQN); - if( null != _sms ) { - throw new RuntimeException("ScreenModeStatus "+_sms+" already mapped to "+screenFQN); - } - screenFQN2ScreenModeStatus.put(screenFQN, sms); - if(DEBUG) { - System.err.println("ScreenModeStatus.map "+screenFQN+" -> "+sms); - } - } finally { - screen2ScreenModeStatusLock.unlock(); - } - } - - /** - * @param screen the prev user - * @return true if mapping is empty, ie no more usage of the mapped ScreenModeStatus - */ - protected static void unmapScreenModeStatus(String screenFQN) { - screen2ScreenModeStatusLock.lock(); - try { - unmapScreenModeStatusUnlocked(screenFQN); - } finally { - screen2ScreenModeStatusLock.unlock(); - } - } - protected static void unmapScreenModeStatusUnlocked(String screenFQN) { - ScreenModeStatus sms = screenFQN2ScreenModeStatus.remove(screenFQN); - if(DEBUG) { - System.err.println("ScreenModeStatus.unmap "+screenFQN+" -> "+sms); - } - } - - protected static ScreenModeStatus getScreenModeStatus(String screenFQN) { - screen2ScreenModeStatusLock.lock(); - try { - return getScreenModeStatusUnlocked(screenFQN); - } finally { - screen2ScreenModeStatusLock.unlock(); - } - } - protected static ScreenModeStatus getScreenModeStatusUnlocked(String screenFQN) { - return screenFQN2ScreenModeStatus.get(screenFQN); - } - - protected static void lockScreenModeStatus() { - screen2ScreenModeStatusLock.lock(); - } - - protected static void unlockScreenModeStatus() { - screen2ScreenModeStatusLock.unlock(); - } - - public ScreenModeStatus(ArrayHashSet screenModes, - IntIntHashMap screenModesIdx2NativeIdx) { - this.screenModes = screenModes; - this.screenModesIdx2NativeIdx = screenModesIdx2NativeIdx; - this.screenModeChangedByOwner = false; - } - - protected final void setOriginalScreenMode(ScreenMode originalScreenMode) { - this.originalScreenMode = originalScreenMode; - this.currentScreenMode = originalScreenMode; - } - - public final ScreenMode getOriginalScreenMode() { - return originalScreenMode; - } - - public final ScreenMode getCurrentScreenMode() { - lock(); - try { - return currentScreenMode; - } finally { - unlock(); - } - } - - /** - * We cannot guarantee that we won't interfere w/ another running - * application's screen mode change. - *

        - * At least we only return true if the owner, ie. the Screen, - * has changed the screen mode and if the original screen mode - * is not current the current one. - *

        - * @return - */ - public final boolean isOriginalModeChangedByOwner() { - lock(); - try { - return screenModeChangedByOwner && !isCurrentModeOriginalMode(); - } finally { - unlock(); - } - } - - protected final boolean isCurrentModeOriginalMode() { - if(null != currentScreenMode && null != originalScreenMode) { - return currentScreenMode.hashCode() == originalScreenMode.hashCode(); - } - return true; - } - - protected final ArrayHashSet getScreenModes() { - return screenModes; - } - - protected final IntIntHashMap getScreenModesIdx2NativeIdx() { - return screenModesIdx2NativeIdx; - } - - protected final int addListener(ScreenModeListener l) { - lock(); - try { - listener.add(l); - if(DEBUG) { - System.err.println("ScreenModeStatus.addListener (size: "+listener.size()+"): "+l); - } - return listener.size(); - } finally { - unlock(); - } - } - - protected final int removeListener(ScreenModeListener l) { - lock(); - try { - if(!listener.remove(l)) { - throw new RuntimeException("ScreenModeListener "+l+" not contained"); - } - if(DEBUG) { - System.err.println("ScreenModeStatus.removeListener (size: "+listener.size()+"): "+l); - } - return listener.size(); - } finally { - unlock(); - } - } - - protected final void fireScreenModeChangeNotify(ScreenMode desiredScreenMode) { - lock(); - try { - for(int i=0; i allMonitors; + private final ArrayHashSet allMonitorModes; + private ArrayList listener = new ArrayList(); + + private static HashMap screenFQN2ScreenMonitorState = new HashMap(); + private static RecursiveLock screen2ScreenMonitorState = LockFactory.createRecursiveLock(); + + protected static void mapScreenMonitorState(String screenFQN, ScreenMonitorState sms) { + screen2ScreenMonitorState.lock(); + try { + ScreenMonitorState _sms = screenFQN2ScreenMonitorState.get(screenFQN); + if( null != _sms ) { + throw new RuntimeException("ScreenMonitorState "+_sms+" already mapped to "+screenFQN); + } + screenFQN2ScreenMonitorState.put(screenFQN, sms); + if(DEBUG) { + System.err.println("ScreenMonitorState.map "+screenFQN+" -> "+sms); + } + } finally { + screen2ScreenMonitorState.unlock(); + } + } + + /** + * @param screen the prev user + * @return true if mapping is empty, ie no more usage of the mapped ScreenMonitorState + */ + protected static void unmapScreenMonitorState(String screenFQN) { + screen2ScreenMonitorState.lock(); + try { + unmapScreenMonitorStateUnlocked(screenFQN); + } finally { + screen2ScreenMonitorState.unlock(); + } + } + protected static void unmapScreenMonitorStateUnlocked(String screenFQN) { + ScreenMonitorState sms = screenFQN2ScreenMonitorState.remove(screenFQN); + if(DEBUG) { + System.err.println("ScreenMonitorState.unmap "+screenFQN+" -> "+sms); + } + } + + protected static ScreenMonitorState getScreenMonitorState(String screenFQN) { + screen2ScreenMonitorState.lock(); + try { + return getScreenMonitorStateUnlocked(screenFQN); + } finally { + screen2ScreenMonitorState.unlock(); + } + } + protected static ScreenMonitorState getScreenMonitorStateUnlocked(String screenFQN) { + return screenFQN2ScreenMonitorState.get(screenFQN); + } + + protected static void lockScreenMonitorState() { + screen2ScreenMonitorState.lock(); + } + + protected static void unlockScreenMonitorState() { + screen2ScreenMonitorState.unlock(); + } + + public ScreenMonitorState(ArrayHashSet allMonitors, + ArrayHashSet allMonitorModes) { + this.allMonitors = allMonitors; + this.allMonitorModes = allMonitorModes; + } + + protected ArrayHashSet getMonitorDevices() { + return allMonitors; + } + + protected ArrayHashSet getMonitorModes() { + return allMonitorModes; + } + + protected final int addListener(MonitorModeListener l) { + lock(); + try { + listener.add(l); + if(DEBUG) { + System.err.println("ScreenMonitorState.addListener (size: "+listener.size()+"): "+l); + } + return listener.size(); + } finally { + unlock(); + } + } + + protected final int removeListener(MonitorModeListener l) { + lock(); + try { + if(!listener.remove(l)) { + throw new RuntimeException("ScreenModeListener "+l+" not contained"); + } + if(DEBUG) { + System.err.println("ScreenMonitorState.removeListener (size: "+listener.size()+"): "+l); + } + return listener.size(); + } finally { + unlock(); + } + } + + protected final MonitorDevice getMonitor(MonitorDevice monitor) { + return allMonitors.get(monitor); + } + + protected final void validateMonitor(MonitorDevice monitor) { + final MonitorDevice md = allMonitors.get(monitor); + if( null == md ) { + throw new InternalError("Monitor unknown: "+monitor); + } + } + + protected final void fireScreenModeChangeNotify(MonitorDevice monitor, MonitorMode desiredMode) { + lock(); + try { + validateMonitor(monitor); + final MonitorEvent me = new MonitorEvent(MonitorEvent.EVENT_MONITOR_MODE_CHANGE_NOTIFY, monitor, System.currentTimeMillis(), desiredMode); + for(int i=0; i default - private boolean fullscreen = false, brokenFocusChange = false; + private boolean fullscreen = false, brokenFocusChange = false; + private List fullscreenMonitors = null; + private boolean fullscreenUseMainMonitor = true; private boolean autoPosition = true; // default: true (allow WM to choose top-level position, if not set by user) private int nfs_width, nfs_height, nfs_x, nfs_y; // non fullscreen client-area size/pos w/o insets @@ -294,19 +298,40 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer screenReferenceAdded = true; } if(canCreateNativeImpl()) { + final int wX, wY; + final boolean usePosition; + if( autoPosition ) { + wX = 0; + wY = 0; + usePosition = false; + } else { + wX = getX(); + wY = getY(); + usePosition = true; + } + final long t0 = System.currentTimeMillis(); createNativeImpl(); - screen.addScreenModeListener(screenModeListenerImpl); + screen.addMonitorModeListener(screenModeListenerImpl); setTitleImpl(title); setPointerVisibleImpl(pointerVisible); confinePointerImpl(pointerConfined); setKeyboardVisible(keyboardVisible); - if(waitForVisible(true, false)) { + final long remainingV = waitForVisible(true, false); + if( 0 <= remainingV ) { if(isFullscreen()) { synchronized(fullScreenAction) { fullscreen = false; // trigger a state change - fullScreenAction.init(true); + fullScreenAction.init(true, fullscreenUseMainMonitor, fullscreenMonitors); + fullscreenMonitors = null; // release references ASAP + fullscreenUseMainMonitor = true; fullScreenAction.run(); } + } else { + // Wait until position is reached within tolerances, either auto-position or custom position. + waitForPosition(usePosition, wX, wY, Window.TIMEOUT_NATIVEWINDOW); + } + if (DEBUG_IMPLEMENTATION) { + System.err.println("Window.createNative(): elapsed "+(System.currentTimeMillis()-t0)+" ms"); } postParentlockFocus = true; } @@ -463,8 +488,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public static final int FLAG_HAS_PARENT = 1 << 8; public static final int FLAG_IS_UNDECORATED = 1 << 9; public static final int FLAG_IS_FULLSCREEN = 1 << 10; - public static final int FLAG_IS_ALWAYSONTOP = 1 << 11; - public static final int FLAG_IS_VISIBLE = 1 << 12; + public static final int FLAG_IS_FULLSCREEN_SPAN = 1 << 11; + public static final int FLAG_IS_ALWAYSONTOP = 1 << 12; + public static final int FLAG_IS_VISIBLE = 1 << 13; /** * The native implementation should invoke the referenced java state callbacks @@ -509,6 +535,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } sb.append("FS_"); sb.append(0 != ( FLAG_IS_FULLSCREEN & flags)); + sb.append("_span_"); + sb.append(0 != ( FLAG_IS_FULLSCREEN_SPAN & flags)); sb.append(", "); if( 0 != ( FLAG_CHANGE_DECORATION & flags) ) { @@ -718,6 +746,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer return screen; } + @Override + public final MonitorDevice getMainMonitor() { + return screen.getMainMonitor(new Rectangle(getX(), getY(), getWidth(), getHeight())); + } + protected final void setVisibleImpl(boolean visible, int x, int y, int width, int height) { reconfigureWindowImpl(x, y, width, height, getReconfigureFlags(FLAG_CHANGE_VISIBILITY, visible)); } @@ -904,7 +937,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } if( isNativeValid() ) { - screen.removeScreenModeListener(screenModeListenerImpl); + screen.removeMonitorModeListener(screenModeListenerImpl); closeNativeImpl(); final AbstractGraphicsDevice cfgADevice = config.getScreen().getDevice(); if( cfgADevice != screen.getDisplay().getGraphicsDevice() ) { // don't pull display's device @@ -929,6 +962,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer setWindowHandle(0); visible = false; fullscreen = false; + fullscreenMonitors = null; + fullscreenUseMainMonitor = true; hasFocus = false; parentWindowHandle = 0; @@ -1212,7 +1247,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer display.dispatchMessagesNative(); // status up2date if(wasVisible) { setVisibleImpl(true, x, y, width, height); - ok = WindowImpl.this.waitForVisible(true, false); + ok = 0 <= WindowImpl.this.waitForVisible(true, false); if(ok) { ok = WindowImpl.this.waitForSize(width, height, false, TIMEOUT_NATIVEWINDOW); } @@ -1735,6 +1770,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if(isNativeValid()) { // this.x/this.y will be set by sizeChanged, triggered by windowing event system reconfigureWindowImpl(x, y, getWidth(), getHeight(), getReconfigureFlags(0, isVisible())); + + // Wait until custom position is reached within tolerances + waitForPosition(true, x, y, Window.TIMEOUT_NATIVEWINDOW); } else { definePosition(x, y); // set pos for createNative(..) } @@ -1758,13 +1796,25 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer private class FullScreenAction implements Runnable { boolean fullscreen; + List monitors; + boolean useMainMonitor; - private boolean init(boolean fullscreen) { + private boolean init(boolean fullscreen, boolean useMainMonitor, List monitors) { if(isNativeValid()) { this.fullscreen = fullscreen; - return isFullscreen() != fullscreen; + if( isFullscreen() != fullscreen ) { + this.monitors = monitors; + this.useMainMonitor = useMainMonitor; + return true; + } else { + this.monitors = null; + this.useMainMonitor = true; + return false; + } } else { WindowImpl.this.fullscreen = fullscreen; // set current state for createNative(..) + WindowImpl.this.fullscreenMonitors = monitors; + WindowImpl.this.fullscreenUseMainMonitor = useMainMonitor; return false; } } @@ -1777,19 +1827,32 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // set current state WindowImpl.this.fullscreen = fullscreen; - final ScreenMode sm = screen.getCurrentScreenMode(); int x,y,w,h; + final RectangleImmutable viewport; + final int fs_span_flag; if(fullscreen) { + if( null == monitors ) { + if( useMainMonitor ) { + monitors = new ArrayList(); + monitors.add( getMainMonitor() ); + } else { + monitors = getScreen().getMonitorDevices(); + } + } + fs_span_flag = monitors.size() > 1 ? FLAG_IS_FULLSCREEN_SPAN : 0 ; + viewport = MonitorDevice.unionOfViewports(new Rectangle(), monitors); nfs_x = getX(); nfs_y = getY(); nfs_width = getWidth(); nfs_height = getHeight(); - x = screen.getX(); - y = screen.getY(); - w = sm.getRotatedWidth(); - h = sm.getRotatedHeight(); + x = viewport.getX(); + y = viewport.getY(); + w = viewport.getWidth(); + h = viewport.getHeight(); } else { + fs_span_flag = 0; + viewport = null; x = nfs_x; y = nfs_y; w = nfs_width; @@ -1809,9 +1872,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } } + monitors = null; // clear references ASAP + useMainMonitor = true; if(DEBUG_IMPLEMENTATION) { System.err.println("Window fs: "+fullscreen+" "+x+"/"+y+" "+w+"x"+h+", "+isUndecorated()+ - ", virtl-size: "+screen.getWidth()+"x"+screen.getHeight()+", SM "+sm.getRotatedWidth()+"x"+sm.getRotatedHeight()); + ", virtl-size: "+screen.getWidth()+"x"+screen.getHeight()+", monitorsViewport "+viewport); } DisplayImpl display = (DisplayImpl) screen.getDisplay(); @@ -1831,7 +1896,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer try { reconfigureWindowImpl(x, y, w, h, getReconfigureFlags( ( ( null != parentWindowLocked ) ? FLAG_CHANGE_PARENTING : 0 ) | - FLAG_CHANGE_FULLSCREEN | FLAG_CHANGE_DECORATION, wasVisible) ); + fs_span_flag | FLAG_CHANGE_FULLSCREEN | FLAG_CHANGE_DECORATION, wasVisible) ); } finally { if(null!=parentWindowLocked) { parentWindowLocked.unlockSurface(); @@ -1860,8 +1925,17 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer @Override public boolean setFullscreen(boolean fullscreen) { + return setFullscreenImpl(fullscreen, true, null); + } + + @Override + public boolean setFullscreen(List monitors) { + return setFullscreenImpl(true, false, monitors); + } + + private boolean setFullscreenImpl(boolean fullscreen, boolean useMainMonitor, List monitors) { synchronized(fullScreenAction) { - if( fullScreenAction.init(fullscreen) ) { + if( fullScreenAction.init(fullscreen, useMainMonitor, monitors) ) { if(fullScreenAction.fsOn() && isOffscreenInstance(WindowImpl.this, parentWindow)) { // enable fullscreen on offscreen instance if(null != parentWindow) { @@ -1887,13 +1961,13 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer return this.fullscreen; } } - - private class ScreenModeListenerImpl implements ScreenModeListener { + + private class ScreenModeListenerImpl implements MonitorModeListener { boolean animatorPaused = false; - public void screenModeChangeNotify(ScreenMode sm) { + public void monitorModeChangeNotify(MonitorEvent me) { if(DEBUG_IMPLEMENTATION) { - System.err.println("Window.screenModeChangeNotify: "+sm); + System.err.println("Window.screenModeChangeNotify: "+me); } if(null!=lifecycleHook) { @@ -1901,9 +1975,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } - public void screenModeChanged(ScreenMode sm, boolean success) { + public void monitorModeChanged(MonitorEvent me, boolean success) { if(DEBUG_IMPLEMENTATION) { - System.err.println("Window.screenModeChanged: "+sm+", success: "+success); + System.err.println("Window.screenModeChanged: "+me+", success: "+success); } if(success) { @@ -1911,10 +1985,19 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // Didn't pass above notify method. probably detected screen change after it happened. animatorPaused = lifecycleHook.pauseRenderingAction(); } - DimensionImmutable screenSize = sm.getMonitorMode().getSurfaceSize().getResolution(); - if ( getHeight() > screenSize.getHeight() || - getWidth() > screenSize.getWidth() ) { - setSize(screenSize.getWidth(), screenSize.getHeight()); + if( !fullscreen ) { + // FIXME: Need to take all covered monitors into account + final MonitorDevice mainMonitor = getMainMonitor(); + final MonitorDevice eventMonitor = me.getMonitor(); + if( mainMonitor == eventMonitor ) { + final RectangleImmutable rect = new Rectangle(getX(), getY(), getWidth(), getHeight()); + final RectangleImmutable viewport = mainMonitor.getViewport(); + final RectangleImmutable isect = viewport.intersection(rect); + if ( getHeight() > isect.getHeight() || + getWidth() > isect.getWidth() ) { + setSize(isect.getWidth(), isect.getHeight()); + } + } } } @@ -2563,14 +2646,17 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } - private boolean waitForVisible(boolean visible, boolean failFast) { + /** Returns -1 if failed, otherwise remaining time until {@link #TIMEOUT_NATIVEWINDOW}, maybe zero. */ + private long waitForVisible(boolean visible, boolean failFast) { return waitForVisible(visible, failFast, TIMEOUT_NATIVEWINDOW); } - private boolean waitForVisible(boolean visible, boolean failFast, long timeOut) { + /** Returns -1 if failed, otherwise remaining time until timeOut, maybe zero. */ + private long waitForVisible(boolean visible, boolean failFast, long timeOut) { final DisplayImpl display = (DisplayImpl) screen.getDisplay(); display.dispatchMessagesNative(); // status up2date - for(long sleep = timeOut; 0 + * Since WM may not obey our positional request exactly, we allow a tolerance of 2 times insets[left/top], or 64 pixels, whatever is greater. + *

        + */ + private boolean waitForPosition(boolean useCustomPosition, int x, int y, long timeOut) { + final DisplayImpl display = (DisplayImpl) screen.getDisplay(); + final int maxDX, maxDY; + { + final InsetsImmutable insets = getInsets(); + maxDX = Math.max(64, insets.getLeftWidth() * 2); + maxDY = Math.max(64, insets.getTopHeight() * 2); + } + long remaining = timeOut; + boolean ok; + do { + if( useCustomPosition ) { + ok = Math.abs(x - getX()) <= maxDX && Math.abs(y - getY()) <= maxDY ; + } else { + ok = !autoPosition; + } + if( !ok ) { + try { Thread.sleep(10); } catch (InterruptedException ie) {} + display.dispatchMessagesNative(); // status up2date + remaining-=10; + } + } while ( 0getX() || 0>getY()) { diff --git a/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java index 6b1283a00..8e584fc58 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java @@ -35,12 +35,15 @@ package jogamp.newt.driver.awt; import java.awt.DisplayMode; +import jogamp.newt.MonitorModeProps.Cache; import jogamp.newt.ScreenImpl; import javax.media.nativewindow.util.Dimension; import javax.media.nativewindow.util.Point; import com.jogamp.nativewindow.awt.AWTGraphicsDevice; import com.jogamp.nativewindow.awt.AWTGraphicsScreen; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; public class ScreenDriver extends ScreenImpl { public ScreenDriver() { @@ -68,14 +71,19 @@ public class ScreenDriver extends ScreenImpl { return idx; // pass through ... } - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - final DisplayMode mode = ((AWTGraphicsDevice)getDisplay().getGraphicsDevice()).getGraphicsDevice().getDisplayMode(); - if(null != mode) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(mode.getWidth()); - virtualSize.setHeight(mode.getHeight()); - } + @Override + protected void collectNativeMonitorModesAndDevicesImpl(Cache cache) { + final DisplayMode mode = ((AWTGraphicsDevice)getDisplay().getGraphicsDevice()).getGraphicsDevice().getDisplayMode(); + } + + @Override + protected MonitorMode queryCurrentMonitorModeImpl(MonitorDevice monitor) { + return null; + } + + @Override + protected boolean setCurrentMonitorModeImpl(MonitorDevice monitor, MonitorMode mode) { + return false; } } diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java index deb2a534b..afaedffe3 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java @@ -35,8 +35,13 @@ package jogamp.newt.driver.bcm.egl; import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.util.Rectangle; + +import jogamp.newt.MonitorModeProps; +import jogamp.newt.ScreenImpl; + +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; public class ScreenDriver extends jogamp.newt.ScreenImpl { @@ -58,11 +63,48 @@ public class ScreenDriver extends jogamp.newt.ScreenImpl { return 0; // only one screen available } - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(fixedWidth); // FIXME - virtualSize.setHeight(fixedHeight); // FIXME + @Override + protected final void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache) { + int[] props = new int[ MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL ]; + int i = 0; + props[i++] = MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL; + props[i++] = fixedWidth; // FIXME + props[i++] = fixedHeight; // FIXME + props[i++] = ScreenImpl.default_sm_bpp; // FIXME + props[i++] = ScreenImpl.default_sm_rate * 100; // FIXME + props[i++] = 0; // flags + props[i++] = 0; // mode_idx + props[i++] = 0; // rotation + final MonitorMode currentMode = MonitorModeProps.streamInMonitorMode(null, cache, props, 0); + + props = new int[MonitorModeProps.MIN_MONITOR_DEVICE_PROPERTIES - 1 - MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES]; + i = 0; + props[i++] = props.length; + props[i++] = 0; // crt_idx + props[i++] = ScreenImpl.default_sm_widthmm; // FIXME + props[i++] = ScreenImpl.default_sm_heightmm; // FIXME + props[i++] = 0; // rotated viewport x + props[i++] = 0; // rotated viewport y + props[i++] = fixedWidth; // FIXME rotated viewport width + props[i++] = fixedHeight; // FIXME rotated viewport height + MonitorModeProps.streamInMonitorDevice(null, cache, this, cache.monitorModes, currentMode, props, 0); + } + + @Override + protected MonitorMode queryCurrentMonitorModeImpl(final MonitorDevice monitor) { + return monitor.getSupportedModes().get(0); + } + + @Override + protected boolean setCurrentMonitorModeImpl(final MonitorDevice monitor, final MonitorMode mode) { + return false; + } + + protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { + vOriginSize.setX(0); + vOriginSize.setY(0); + vOriginSize.setWidth(fixedWidth); // FIXME + vOriginSize.setHeight(fixedHeight); // FIXME } //---------------------------------------------------------------------- diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java index 787d1a1b4..f7973def8 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java @@ -29,9 +29,12 @@ package jogamp.newt.driver.bcm.vc.iv; import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.util.Rectangle; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; + +import jogamp.newt.MonitorModeProps; import jogamp.newt.ScreenImpl; public class ScreenDriver extends ScreenImpl { @@ -53,13 +56,52 @@ public class ScreenDriver extends ScreenImpl { return 0; // only one screen available } - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(cachedWidth); - virtualSize.setHeight(cachedHeight); + @Override + protected final void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache) { + int[] props = new int[ MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL ]; + int i = 0; + props[i++] = MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL; + props[i++] = cachedWidth; // width + props[i++] = cachedHeight; // height + props[i++] = ScreenImpl.default_sm_bpp; // FIXME + props[i++] = ScreenImpl.default_sm_rate * 100; // FIXME + props[i++] = 0; // flags + props[i++] = 0; // mode_idx + props[i++] = 0; // rotation + final MonitorMode currentMode = MonitorModeProps.streamInMonitorMode(null, cache, props, 0); + + props = new int[MonitorModeProps.MIN_MONITOR_DEVICE_PROPERTIES - 1 - MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES]; + i = 0; + props[i++] = props.length; + props[i++] = 0; // crt_idx + props[i++] = ScreenImpl.default_sm_widthmm; // FIXME + props[i++] = ScreenImpl.default_sm_heightmm; // FIXME + props[i++] = 0; // rotated viewport x + props[i++] = 0; // rotated viewport y + props[i++] = cachedWidth; // rotated viewport width + props[i++] = cachedWidth; // rotated viewport height + MonitorModeProps.streamInMonitorDevice(null, cache, this, cache.monitorModes, currentMode, props, 0); + } + + @Override + protected MonitorMode queryCurrentMonitorModeImpl(final MonitorDevice monitor) { + return monitor.getSupportedModes().get(0); + } + + @Override + protected boolean setCurrentMonitorModeImpl(final MonitorDevice monitor, final MonitorMode mode) { + return false; + } + + @Override + protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { + vOriginSize.setX(0); + vOriginSize.setY(0); + vOriginSize.setWidth(cachedWidth); + vOriginSize.setHeight(cachedHeight); } + /** Called from {@link #initNative()}. */ protected void setScreenSize(int width, int height) { cachedWidth = width; cachedHeight = height; diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java index 8eed14dde..4c47eb0d8 100644 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java @@ -36,8 +36,13 @@ package jogamp.newt.driver.intel.gdl; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.util.Rectangle; + +import jogamp.newt.MonitorModeProps; +import jogamp.newt.ScreenImpl; + +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; public class ScreenDriver extends jogamp.newt.ScreenImpl { @@ -60,11 +65,48 @@ public class ScreenDriver extends jogamp.newt.ScreenImpl { return 0; // only one screen available } - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(cachedWidth); - virtualSize.setHeight(cachedHeight); + @Override + protected final void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache) { + int[] props = new int[ MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL ]; + int i = 0; + props[i++] = MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL; + props[i++] = cachedWidth; // width + props[i++] = cachedHeight; // height + props[i++] = ScreenImpl.default_sm_bpp; // FIXME + props[i++] = ScreenImpl.default_sm_rate * 100; // FIXME + props[i++] = 0; // flags + props[i++] = 0; // mode_idx + props[i++] = 0; // rotation + final MonitorMode currentMode = MonitorModeProps.streamInMonitorMode(null, cache, props, 0); + + props = new int[MonitorModeProps.MIN_MONITOR_DEVICE_PROPERTIES - 1 - MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES]; + i = 0; + props[i++] = props.length; + props[i++] = 0; // crt_idx + props[i++] = ScreenImpl.default_sm_widthmm; // FIXME + props[i++] = ScreenImpl.default_sm_heightmm; // FIXME + props[i++] = 0; // rotated viewport x + props[i++] = 0; // rotated viewport y + props[i++] = cachedWidth; // rotated viewport width + props[i++] = cachedWidth; // rotated viewport height + MonitorModeProps.streamInMonitorDevice(null, cache, this, cache.monitorModes, currentMode, props, 0); + } + + @Override + protected MonitorMode queryCurrentMonitorModeImpl(final MonitorDevice monitor) { + return monitor.getSupportedModes().get(0); + } + + @Override + protected boolean setCurrentMonitorModeImpl(final MonitorDevice monitor, final MonitorMode mode) { + return false; + } + + protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { + vOriginSize.setX(0); + vOriginSize.setY(0); + vOriginSize.setWidth(cachedWidth); + vOriginSize.setHeight(cachedHeight); } //---------------------------------------------------------------------- diff --git a/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java index 656bcf5c9..dc87c3c08 100644 --- a/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java @@ -35,9 +35,12 @@ package jogamp.newt.driver.kd; import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.util.Rectangle; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; + +import jogamp.newt.MonitorModeProps; import jogamp.newt.ScreenImpl; public class ScreenDriver extends ScreenImpl { @@ -58,11 +61,48 @@ public class ScreenDriver extends ScreenImpl { return 0; // only one screen available } - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(cachedWidth); - virtualSize.setHeight(cachedHeight); + @Override + protected final void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache) { + int[] props = new int[ MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL ]; + int i = 0; + props[i++] = MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL; + props[i++] = cachedWidth; // width + props[i++] = cachedHeight; // height + props[i++] = ScreenImpl.default_sm_bpp; // FIXME + props[i++] = ScreenImpl.default_sm_rate * 100; // FIXME + props[i++] = 0; // flags + props[i++] = 0; // mode_idx + props[i++] = 0; // rotation + final MonitorMode currentMode = MonitorModeProps.streamInMonitorMode(null, cache, props, 0); + + props = new int[MonitorModeProps.MIN_MONITOR_DEVICE_PROPERTIES - 1 - MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES]; + i = 0; + props[i++] = props.length; + props[i++] = 0; // crt_idx + props[i++] = ScreenImpl.default_sm_widthmm; // FIXME + props[i++] = ScreenImpl.default_sm_heightmm; // FIXME + props[i++] = 0; // rotated viewport x + props[i++] = 0; // rotated viewport y + props[i++] = cachedWidth; // rotated viewport width + props[i++] = cachedWidth; // rotated viewport height + MonitorModeProps.streamInMonitorDevice(null, cache, this, cache.monitorModes, currentMode, props, 0); + } + + @Override + protected MonitorMode queryCurrentMonitorModeImpl(final MonitorDevice monitor) { + return monitor.getSupportedModes().get(0); + } + + @Override + protected boolean setCurrentMonitorModeImpl(final MonitorDevice monitor, final MonitorMode mode) { + return false; + } + + protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { + vOriginSize.setX(0); + vOriginSize.setY(0); + vOriginSize.setWidth(cachedWidth); + vOriginSize.setHeight(cachedHeight); } protected void sizeChanged(int w, int h) { diff --git a/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java index 24e60ba0a..a3bb26731 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java @@ -34,28 +34,19 @@ package jogamp.newt.driver.macosx; -import java.util.List; - import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.DimensionImmutable; -import javax.media.nativewindow.util.Point; +import jogamp.newt.MonitorModeProps; import jogamp.newt.ScreenImpl; -import com.jogamp.common.util.IntObjectHashMap; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.util.ScreenModeUtil; +import com.jogamp.common.util.ArrayHashSet; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; public class ScreenDriver extends ScreenImpl { - // caching native CGDisplayScreenSize() results, since it's ridiculous slow (~6 ms each call) - private static IntObjectHashMap/**/ scrnIdx2Dimension; - static { DisplayDriver.initSingleton(); - scrnIdx2Dimension = new IntObjectHashMap(); - scrnIdx2Dimension.setKeyNotFoundValue(null); } public ScreenDriver() { @@ -67,77 +58,67 @@ public class ScreenDriver extends ScreenImpl { protected void closeNativeImpl() { } - private static native int getWidthImpl0(int scrn_idx); - private static native int getHeightImpl0(int scrn_idx); - - private int[] getScreenModeIdx(int idx) { - // caching native CGDisplayScreenSize() results, since it's ridiculous slow (~6 ms each call) - DimensionImmutable dim = (DimensionImmutable) scrnIdx2Dimension.get(screen_idx); - if(null == dim) { - int[] res = getScreenSizeMM0(screen_idx); - if(null == res || 0 == res.length) { - return null; - } - dim = new Dimension(res[0], res[1]); - scrnIdx2Dimension.put(screen_idx, dim); - } - - int[] modeProps = getScreenMode0(screen_idx, idx, dim.getWidth(), dim.getHeight()); - if (null == modeProps || 0 == modeProps.length) { - return null; + private MonitorMode getMonitorModeImpl(MonitorModeProps.Cache cache, int crt_idx, int mode_idx) { + final int[] modeProps = getMonitorMode0(crt_idx, mode_idx); + final MonitorMode res; + if (null == modeProps || 0 >= modeProps.length) { + res = null; + } else { + res = MonitorModeProps.streamInMonitorMode(null, cache, modeProps, 0); } - if(modeProps.length < ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL) { - throw new RuntimeException("properties array too short, should be >= "+ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL+", is "+modeProps.length); - } - return modeProps; + return res; } - - private int nativeModeIdx; - protected int[] getScreenModeFirstImpl() { - nativeModeIdx = 0; - return getScreenModeNextImpl(); - } - - protected int[] getScreenModeNextImpl() { - int[] modeProps = getScreenModeIdx(nativeModeIdx); - if (null != modeProps && 0 < modeProps.length) { - nativeModeIdx++; - return modeProps; - } - return null; + @Override + protected final void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache) { + int crtIdx = 0; + int modeIdx = 0; + ArrayHashSet supportedModes = new ArrayHashSet(); + do { + final MonitorMode mode = getMonitorModeImpl(cache, crtIdx, modeIdx); + if( null != mode ) { + supportedModes.getOrAdd(mode); + // next mode on same monitor + modeIdx++; + } else if( 0 < modeIdx ) { + // end of monitor modes - got at least one mode + final MonitorMode currentMode = getMonitorModeImpl(cache, crtIdx, -1); + if ( null == currentMode ) { + throw new InternalError("Could not gather current mode of device "+crtIdx+", but gathered "+modeIdx+" modes"); + } + final int[] monitorProps = getMonitorProps0(crtIdx); + if ( null == monitorProps ) { + throw new InternalError("Could not gather device "+crtIdx+", but gathered "+modeIdx+" modes"); + } + // merge monitor-props + supported modes + MonitorModeProps.streamInMonitorDevice(null, cache, this, supportedModes, currentMode, monitorProps, 0); + + // next monitor, 1st mode + supportedModes= new ArrayHashSet(); + crtIdx++; + modeIdx=0; + } else { + // end of monitor + break; + } + } while ( true ); } - protected ScreenMode getCurrentScreenModeImpl() { - int[] modeProps = getScreenModeIdx(-1); - if (null != modeProps && 0 < modeProps.length) { - return ScreenModeUtil.streamIn(modeProps, 0); - } - return null; + @Override + protected MonitorMode queryCurrentMonitorModeImpl(MonitorDevice monitor) { + return getMonitorModeImpl(null, monitor.getId(), -1); } - protected boolean setCurrentScreenModeImpl(final ScreenMode screenMode) { - final List screenModes = this.getScreenModesOrig(); - final int screenModeIdx = screenModes.indexOf(screenMode); - if(0>screenModeIdx) { - throw new RuntimeException("ScreenMode not element of ScreenMode list: "+screenMode); - } - final int nativeModeIdx = getScreenModesIdx2NativeIdx().get(screenModeIdx); - return setScreenMode0(screen_idx, nativeModeIdx); + @Override + protected boolean setCurrentMonitorModeImpl(MonitorDevice monitor, MonitorMode mode) { + return setMonitorMode0(monitor.getId(), mode.getId(), mode.getRotation()); } protected int validateScreenIndex(int idx) { - return idx; + return 0; // big-desktop w/ multiple monitor attached, only one screen available } - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(getWidthImpl0(screen_idx)); - virtualSize.setHeight(getHeightImpl0(screen_idx)); - } - - private native int[] getScreenSizeMM0(int screen_idx); - private native int[] getScreenMode0(int screen_index, int mode_index, int widthMM, int heightMM); - private native boolean setScreenMode0(int screen_index, int mode_idx); + private native int[] getMonitorProps0(int crt_idx); + private native int[] getMonitorMode0(int crt_index, int mode_idx); + private native boolean setMonitorMode0(int crt_index, int nativeId, int rot); } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java index bb72350e3..6370782df 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java @@ -478,7 +478,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl if( 0 != surfaceHandle ) { throw new NativeWindowException("Internal Error - create w/o window, but has Newt NSView"); } - surfaceHandle = createView0(pS.getX(), pS.getY(), width, height, fullscreen, getScreen().getIndex()); + surfaceHandle = createView0(pS.getX(), pS.getY(), width, height, fullscreen); if( 0 == surfaceHandle ) { throw new NativeWindowException("Could not create native view "+Thread.currentThread().getName()+" "+this); } @@ -487,7 +487,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl final long newWin = createWindow0( pS.getX(), pS.getY(), width, height, fullscreen, ( isUndecorated() || offscreenInstance ) ? NSBorderlessWindowMask : NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask, - NSBackingStoreBuffered, getScreen().getIndex(), surfaceHandle); + NSBackingStoreBuffered, surfaceHandle); if ( newWin == 0 ) { throw new NativeWindowException("Could not create native window "+Thread.currentThread().getName()+" "+this); } @@ -497,9 +497,8 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl // Non blocking initialization on main-thread! OSXUtil.RunOnMainThread(false, new Runnable() { public void run() { - initWindow0( parentWin, newWin, - pS.getX(), pS.getY(), width, height, - isOpaque, fullscreen, visible && !offscreenInstance, getScreen().getIndex(), surfaceHandle); + initWindow0( parentWin, newWin, pS.getX(), pS.getY(), width, height, + isOpaque, fullscreen, visible && !offscreenInstance, surfaceHandle); if( offscreenInstance ) { orderOut0(0!=parentWin ? parentWin : newWin); } else { @@ -514,11 +513,11 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl } protected static native boolean initIDs0(); - private native long createView0(int x, int y, int w, int h, boolean fullscreen, int screen_idx); - private native long createWindow0(int x, int y, int w, int h, boolean fullscreen, int windowStyle, int backingStoreType, int screen_idx, long view); + private native long createView0(int x, int y, int w, int h, boolean fullscreen); + private native long createWindow0(int x, int y, int w, int h, boolean fullscreen, int windowStyle, int backingStoreType, long view); /** Must be called on Main-Thread */ private native void initWindow0(long parentWindow, long window, int x, int y, int w, int h, - boolean opaque, boolean fullscreen, boolean visible, int screen_idx, long view); + boolean opaque, boolean fullscreen, boolean visible, long view); private native boolean lockSurface0(long window, long view); private native boolean unlockSurface0(long window, long view); /** Must be called on Main-Thread */ diff --git a/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java index 948b29460..342829691 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java @@ -34,91 +34,143 @@ package jogamp.newt.driver.windows; import javax.media.nativewindow.DefaultGraphicsScreen; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.util.Rectangle; +import jogamp.newt.MonitorModeProps; import jogamp.newt.ScreenImpl; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.util.ScreenModeUtil; +import com.jogamp.common.util.ArrayHashSet; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; +import com.jogamp.newt.Screen; public class ScreenDriver extends ScreenImpl { static { DisplayDriver.initSingleton(); + if( Screen.DEBUG ) { + dumpMonitorInfo0(); + } } public ScreenDriver() { } + @Override protected void createNativeImpl() { aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); } + @Override protected void closeNativeImpl() { } - private int[] getScreenModeIdx(int idx) { - int[] modeProps = getScreenMode0(screen_idx, idx); - if (null == modeProps || 0 == modeProps.length) { + private final String getAdapterName(int crt_idx) { + return getAdapterName0(crt_idx); + } + private final String getActiveMonitorName(String adapterName, int monitor_idx) { + return getActiveMonitorName0(adapterName, monitor_idx); + } + + private final MonitorMode getMonitorModeImpl(MonitorModeProps.Cache cache, String adapterName, int crtModeIdx) { + if( null == adapterName ) { return null; } - if(modeProps.length < ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL) { - throw new RuntimeException("properties array too short, should be >= "+ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL+", is "+modeProps.length); + final String activeMonitorName = getActiveMonitorName(adapterName, 0); + final int[] modeProps = null != activeMonitorName ? getMonitorMode0(adapterName, crtModeIdx) : null; + if ( null == modeProps || 0 >= modeProps.length) { + return null; } - return modeProps; + return MonitorModeProps.streamInMonitorMode(null, cache, modeProps, 0); } - private int nativeModeIdx; - - protected int[] getScreenModeFirstImpl() { - nativeModeIdx = 0; - return getScreenModeNextImpl(); - } - - protected int[] getScreenModeNextImpl() { - int[] modeProps = getScreenModeIdx(nativeModeIdx); - if (null != modeProps && 0 < modeProps.length) { - nativeModeIdx++; - return modeProps; + @Override + protected void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache) { + int crtIdx = 0; + ArrayHashSet supportedModes = new ArrayHashSet(); + String adapterName = getAdapterName(crtIdx); + while( null != adapterName ) { + int crtModeIdx = 0; + MonitorMode mode; + do { + mode = getMonitorModeImpl(cache, adapterName, crtModeIdx); + if( null != mode ) { + supportedModes.getOrAdd(mode); + // next mode on same monitor + crtModeIdx++; + } + } while( null != mode); + if( 0 < crtModeIdx ) { + // has at least one mode -> add device + final MonitorMode currentMode = getMonitorModeImpl(cache, adapterName, -1); + if ( null != currentMode ) { // enabled + final int[] monitorProps = getMonitorDevice0(adapterName, crtIdx); + // merge monitor-props + supported modes + MonitorModeProps.streamInMonitorDevice(null, cache, this, supportedModes, currentMode, monitorProps, 0); + + // next monitor, 1st mode + supportedModes= new ArrayHashSet(); + } + } + crtIdx++; + adapterName = getAdapterName(crtIdx); } - return null; } - - protected ScreenMode getCurrentScreenModeImpl() { - int[] modeProps = getScreenModeIdx(-1); - if (null != modeProps && 0 < modeProps.length) { - return ScreenModeUtil.streamIn(modeProps, 0); + + @Override + protected Rectangle getNativeMonitorDeviceViewportImpl(MonitorDevice monitor) { + final String adapterName = getAdapterName(monitor.getId()); + if( null != adapterName ) { + final String activeMonitorName = getActiveMonitorName(adapterName, 0); + if( null != activeMonitorName ) { + final int[] monitorProps = getMonitorDevice0(adapterName, monitor.getId()); + int offset = MonitorModeProps.IDX_MONITOR_DEVICE_VIEWPORT; + return new Rectangle(monitorProps[offset++], monitorProps[offset++], monitorProps[offset++], monitorProps[offset++]); + } } return null; } - protected boolean setCurrentScreenModeImpl(ScreenMode sm) { - return setScreenMode0(screen_idx, - sm.getMonitorMode().getSurfaceSize().getResolution().getWidth(), - sm.getMonitorMode().getSurfaceSize().getResolution().getHeight(), - sm.getMonitorMode().getSurfaceSize().getBitsPerPixel(), - sm.getMonitorMode().getRefreshRate(), - sm.getRotation()); + @Override + protected MonitorMode queryCurrentMonitorModeImpl(MonitorDevice monitor) { + return getMonitorModeImpl(null, getAdapterName(monitor.getId()), -1); + } + + @Override + protected boolean setCurrentMonitorModeImpl(MonitorDevice monitor, MonitorMode mode) { + return setMonitorMode0(monitor.getId(), + -1, -1, // no fixed position! + mode.getSurfaceSize().getResolution().getWidth(), + mode.getSurfaceSize().getResolution().getHeight(), + mode.getSurfaceSize().getBitsPerPixel(), + (int)mode.getRefreshRate(), // simply cut-off, orig is int + mode.getFlags(), + mode.getRotation()); } + @Override protected int validateScreenIndex(int idx) { - return 0; // big-desktop, only one screen available + return 0; // big-desktop w/ multiple monitor attached, only one screen available } - protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) { - virtualOrigin.setX(getOriginX0(screen_idx)); - virtualOrigin.setY(getOriginY0(screen_idx)); - virtualSize.setWidth(getWidthImpl0(screen_idx)); - virtualSize.setHeight(getHeightImpl0(screen_idx)); + @Override + protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { + vOriginSize.setX(getVirtualOriginX0()); + vOriginSize.setY(getVirtualOriginY0()); + vOriginSize.setWidth(getVirtualWidthImpl0()); + vOriginSize.setHeight(getVirtualHeightImpl0()); } // Native calls - private native int getOriginX0(int screen_idx); - private native int getOriginY0(int screen_idx); - private native int getWidthImpl0(int scrn_idx); - private native int getHeightImpl0(int scrn_idx); + private native int getVirtualOriginX0(); + private native int getVirtualOriginY0(); + private native int getVirtualWidthImpl0(); + private native int getVirtualHeightImpl0(); - private native int[] getScreenMode0(int screen_index, int mode_index); - private native boolean setScreenMode0(int screen_index, int width, int height, int bits, int freq, int rot); + private static native void dumpMonitorInfo0(); + private native String getAdapterName0(int crt_index); + private native String getActiveMonitorName0(String adapterName, int crtModeIdx); + private native int[] getMonitorMode0(String adapterName, int crtModeIdx); + private native int[] getMonitorDevice0(String adapterName, int monitor_index); + private native boolean setMonitorMode0(int monitor_index, int x, int y, int width, int height, int bits, int freq, int flags, int rot); } diff --git a/src/newt/classes/jogamp/newt/driver/x11/RandR.java b/src/newt/classes/jogamp/newt/driver/x11/RandR.java index 485d976ec..c569e5fd8 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/RandR.java +++ b/src/newt/classes/jogamp/newt/driver/x11/RandR.java @@ -27,13 +27,50 @@ */ package jogamp.newt.driver.x11; -import com.jogamp.newt.ScreenMode; +import java.util.List; + +import jogamp.newt.MonitorModeProps; + +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; public interface RandR { - int[] getScreenModeFirstImpl(final long dpy, final int screen_idx); - int[] getScreenModeNextImpl(final long dpy, final int screen_idx); - ScreenMode getCurrentScreenModeImpl(final long dpy, final int screen_idx); - boolean setCurrentScreenModeImpl(final long dpy, final int screen_idx, final ScreenMode screenMode, final int screenModeIdx, final int resolutionIdx); + void dumpInfo(final long dpy, final int screen_idx); + + /** + * Encapsulate initial device query allowing caching of internal data structures. + * Methods covered: + *
          + *
        • {@link #getMonitorDeviceCount(long, ScreenDriver)}
        • + *
        • {@link #getAvailableRotations(long, ScreenDriver, int)}
        • + *
        • {@link #getMonitorModeProps(long, ScreenDriver, int)}
        • + *
        • {@link #getCurrentMonitorModeProps(long, ScreenDriver, int)
        • + *
        • {@link #getMonitorDeviceProps(long, ScreenDriver, List, int, MonitorMode)}
        • + *
        + *

        + * Above methods may be called w/o begin/end, in which case no + * internal data structures can be cached: + *

        + * @param dpy TODO + * @param screen TODO + * @return TODO + */ + boolean beginInitialQuery(long dpy, ScreenDriver screen); + void endInitialQuery(long dpy, ScreenDriver screen); + int getMonitorDeviceCount(final long dpy, final ScreenDriver screen); + int[] getAvailableRotations(final long dpy, final ScreenDriver screen, final int crt_idx); + /** + * + * @param dpy + * @param screen + * @param mode_idx w/o indexing rotation + * @return props w/o actual rotation + */ + int[] getMonitorModeProps(final long dpy, final ScreenDriver screen, final int mode_idx); + int[] getMonitorDeviceProps(final long dpy, final ScreenDriver screen, MonitorModeProps.Cache cache, final int crt_idx); + int[] getMonitorDeviceViewport(final long dpy, final ScreenDriver screen, final int crt_idx); + int[] getCurrentMonitorModeProps(final long dpy, final ScreenDriver screen, final int crt_idx); + boolean setCurrentMonitorMode(final long dpy, final ScreenDriver screen, MonitorDevice monitor, final MonitorMode mode); } diff --git a/src/newt/classes/jogamp/newt/driver/x11/RandR11.java b/src/newt/classes/jogamp/newt/driver/x11/RandR11.java index ee67bd304..a938b4064 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/RandR11.java +++ b/src/newt/classes/jogamp/newt/driver/x11/RandR11.java @@ -27,139 +27,257 @@ */ package jogamp.newt.driver.x11; +import jogamp.newt.MonitorModeProps; import jogamp.newt.ScreenImpl; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.util.ScreenModeUtil; +import com.jogamp.common.util.VersionNumber; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; public class RandR11 implements RandR { private static final boolean DEBUG = ScreenDriver.DEBUG; - private int[] nrotations; - private int nrotation_index; - private int nres_number; - private int nres_index; - private int[] nrates; - private int nrate_index; - private int nmode_number; + public static VersionNumber version = new VersionNumber(1, 1, 0); + + public static RandR11 createInstance(VersionNumber rAndRVersion) { + if( rAndRVersion.compareTo(version) >= 0 ) { + return new RandR11(); + } + return null; + } + private RandR11() { + } + + @Override + public void dumpInfo(final long dpy, final int screen_idx) { + // NOP + } + + private int widthMM=0, heightMM=0; + private int modeCount = 0; + private int resolutionCount = 0; + private int[][] nrates = null; // [nres_number][nrate_number] + private int[] idx_rate = null, idx_res = null; @Override - public int[] getScreenModeFirstImpl(final long dpy, final int screen_idx) { + public boolean beginInitialQuery(long dpy, ScreenDriver screen) { // initialize iterators and static data - nrotations = getAvailableScreenModeRotations0(dpy, screen_idx); - if(null==nrotations || 0==nrotations.length) { - return null; + final int screen_idx = screen.getIndex(); + resolutionCount = getNumScreenResolutions0(dpy, screen_idx); + if(0==resolutionCount) { + endInitialQuery(dpy, screen); + return false; } - nrotation_index = 0; - nres_number = getNumScreenModeResolutions0(dpy, screen_idx); - if(0==nres_number) { - return null; + nrates = new int[resolutionCount][]; + for(int i=0; i= modeCount ) { + return null; + } + final int screen_idx = screen.getIndex(); + + final int nres_index = idx_res[mode_idx]; + final int nrate_index = idx_rate[mode_idx]; + + final int[] res = getScreenResolution0(dpy, screen_idx, nres_index); if(null==res || 0==res.length) { return null; } if(0>=res[0] || 0>=res[1]) { - throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+nres_index+"/"+nres_number); + throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+nres_index+"/"+resolutionCount); + } + if( res[2] > widthMM ) { + widthMM = res[2]; } - int rate = nrates[nrate_index]; + if( res[3] > heightMM ) { + heightMM = res[3]; + } + + int rate = nrates[nres_index][nrate_index]; if(0>=rate) { rate = ScreenImpl.default_sm_rate; if(DEBUG) { System.err.println("Invalid rate: "+rate+" at index "+nrate_index+"/"+nrates.length+", using default: "+ScreenImpl.default_sm_rate); } } - int rotation = nrotations[nrotation_index]; - int[] props = new int[ 1 + ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL ]; + int[] props = new int[ MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL ]; int i = 0; - props[i++] = nres_index; // use resolution index, not unique for native -> ScreenMode - props[i++] = 0; // set later for verification of iterator + props[i++] = MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL; props[i++] = res[0]; // width props[i++] = res[1]; // height - props[i++] = ScreenImpl.default_sm_bpp; // FIXME - props[i++] = res[2]; // widthmm - props[i++] = res[3]; // heightmm - props[i++] = rate; // rate - props[i++] = rotation; - props[i - ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL] = i - 1; // count without extra element - - nmode_number++; - - // iteration: r -> f -> bpp -> [w x h] - nrotation_index++; - if(nrotation_index == nrotations.length) { - nrotation_index=0; - nrate_index++; - if(null == nrates || nrate_index == nrates.length){ - nres_index++; - if(nres_index == nres_number) { - // done - nrates=null; - nrotations=null; - return null; - } - - nrates = getScreenModeRates0(dpy, screen_idx, nres_index); - if(null==nrates || 0==nrates.length) { - return null; - } - nrate_index = 0; - } + props[i++] = ScreenImpl.default_sm_bpp; // bpp n/a in RandR11 + props[i++] = rate*100; // rate (Hz*100) + props[i++] = 0; // flags; + props[i++] = nres_index; + props[i++] = -1; // rotation placeholder; + if( MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL != i ) { + throw new InternalError("XX"); + } + return props; + } + + @Override + public int[] getMonitorDeviceProps(final long dpy, final ScreenDriver screen, final MonitorModeProps.Cache cache, final int crt_idx) { + if( 0 < crt_idx ) { + // RandR11 only supports 1 CRT + return null; + } + final int[] currentModeProps = getCurrentMonitorModeProps(dpy, screen, crt_idx); + if( null == currentModeProps) { // disabled + return null; + } + final MonitorMode currentMode = MonitorModeProps.streamInMonitorMode(null, cache, currentModeProps, 0); + final int allModesCount = cache.monitorModes.size(); + final int[] props = new int[MonitorModeProps.MIN_MONITOR_DEVICE_PROPERTIES - 1 + allModesCount]; + int i = 0; + props[i++] = props.length; + props[i++] = crt_idx; + props[i++] = widthMM; + props[i++] = heightMM; + props[i++] = 0; // rotated viewport x + props[i++] = 0; // rotated viewport y + props[i++] = currentMode.getRotatedWidth(); // rotated viewport width + props[i++] = currentMode.getRotatedHeight(); // rotated viewport height + props[i++] = currentMode.getId(); // current mode id + props[i++] = currentMode.getRotation(); + for(int j=0; jnres_idx) { + return null; + } + if(nres_idx>=resNumber) { + throw new RuntimeException("Invalid resolution index: ! "+nres_idx+" < "+resNumber); + } + res = getScreenResolution0(dpy, screen_idx, nres_idx); + if(null==res || 0==res.length) { + return null; + } + if(0>=res[0] || 0>=res[1]) { + throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+nres_idx+"/"+resNumber); + } + } finally { + freeScreenConfiguration0(screenConfigHandle); + } + int[] props = new int[4]; + int i = 0; + props[i++] = 0; + props[i++] = 0; + props[i++] = res[0]; // width + props[i++] = res[1]; // height + return props; + } + @Override - public ScreenMode getCurrentScreenModeImpl(final long dpy, final int screen_idx) { + public int[] getCurrentMonitorModeProps(final long dpy, final ScreenDriver screen, final int crt_idx) { + if( 0 < crt_idx ) { + // RandR11 only supports 1 CRT + return null; + } + final int screen_idx = screen.getIndex(); long screenConfigHandle = getScreenConfiguration0(dpy, screen_idx); if(0 == screenConfigHandle) { return null; } int[] res; int rate, rot; + final int nres_idx; try { - int resNumber = getNumScreenModeResolutions0(dpy, screen_idx); + int resNumber = getNumScreenResolutions0(dpy, screen_idx); if(0==resNumber) { return null; } - int resIdx = getCurrentScreenResolutionIndex0(screenConfigHandle); - if(0>resIdx) { + nres_idx = getCurrentScreenResolutionIndex0(screenConfigHandle); + if(0>nres_idx) { return null; } - if(resIdx>=resNumber) { - throw new RuntimeException("Invalid resolution index: ! "+resIdx+" < "+resNumber); + if(nres_idx>=resNumber) { + throw new RuntimeException("Invalid resolution index: ! "+nres_idx+" < "+resNumber); } - res = getScreenModeResolution0(dpy, screen_idx, resIdx); + res = getScreenResolution0(dpy, screen_idx, nres_idx); if(null==res || 0==res.length) { return null; } if(0>=res[0] || 0>=res[1]) { - throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+resIdx+"/"+resNumber); + throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+nres_idx+"/"+resNumber); } rate = getCurrentScreenRate0(screenConfigHandle); if(0>rate) { @@ -172,40 +290,42 @@ public class RandR11 implements RandR { } finally { freeScreenConfiguration0(screenConfigHandle); } - int[] props = new int[ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL]; + int[] props = new int[ MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL ]; int i = 0; - props[i++] = 0; // set later for verification of iterator + props[i++] = MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL; props[i++] = res[0]; // width props[i++] = res[1]; // height - props[i++] = ScreenImpl.default_sm_bpp; // FIXME - props[i++] = res[2]; // widthmm - props[i++] = res[3]; // heightmm - props[i++] = rate; // rate + props[i++] = ScreenImpl.default_sm_bpp; + props[i++] = rate*100; // rate (Hz*100) + props[i++] = 0; // flags; + props[i++] = nres_idx; // mode_idx; props[i++] = rot; - props[i - ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL] = i; // count - return ScreenModeUtil.streamIn(props, 0); + if( MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL != i ) { + throw new InternalError("XX"); + } + return props; } @Override - public boolean setCurrentScreenModeImpl(final long dpy, final int screen_idx, final ScreenMode screenMode, final int screenModeIdx, final int resolutionIdx) { + public boolean setCurrentMonitorMode(final long dpy, final ScreenDriver screen, MonitorDevice monitor, final MonitorMode mode) { final long t0 = System.currentTimeMillis(); boolean done = false; + final int screen_idx = screen.getIndex(); long screenConfigHandle = getScreenConfiguration0(dpy, screen_idx); if(0 == screenConfigHandle) { return Boolean.valueOf(done); } try { - int resNumber = getNumScreenModeResolutions0(dpy, screen_idx); - if(0>resolutionIdx || resolutionIdx>=resNumber) { - throw new RuntimeException("Invalid resolution index: ! 0 < "+resolutionIdx+" < "+resNumber+", screenMode["+screenModeIdx+"] "+screenMode); - } - - final int f = screenMode.getMonitorMode().getRefreshRate(); - final int r = screenMode.getRotation(); + final int resId = mode.getId(); + if(0>resId || resId>=resolutionCount) { + throw new RuntimeException("Invalid resolution index: ! 0 < "+resId+" < "+resolutionCount+", "+monitor+", "+mode); + } + final int f = (int)mode.getRefreshRate(); // simply cut-off, orig is int + final int r = mode.getRotation(); - if( setCurrentScreenModeStart0(dpy, screen_idx, screenConfigHandle, resolutionIdx, f, r) ) { + if( setCurrentScreenModeStart0(dpy, screen_idx, screenConfigHandle, resId, f, r) ) { while(!done && System.currentTimeMillis()-t0 < ScreenImpl.SCREEN_MODE_CHANGE_TIMEOUT) { - done = setCurrentScreenModePollEnd0(dpy, screen_idx, resolutionIdx, f, r); + done = setCurrentScreenModePollEnd0(dpy, screen_idx, resId, f, r); if(!done) { try { Thread.sleep(10); } catch (InterruptedException e) { } } @@ -218,14 +338,14 @@ public class RandR11 implements RandR { } /** @return int[] { rot1, .. } */ - private static native int[] getAvailableScreenModeRotations0(long display, int screen_index); + private static native int[] getAvailableScreenRotations0(long display, int screen_index); - private static native int getNumScreenModeResolutions0(long display, int screen_index); + private static native int getNumScreenResolutions0(long display, int screen_index); /** @return int[] { width, height, widthmm, heightmm } */ - private static native int[] getScreenModeResolution0(long display, int screen_index, int mode_index); + private static native int[] getScreenResolution0(long display, int screen_index, int mode_index); - private static native int[] getScreenModeRates0(long display, int screen_index, int mode_index); + private static native int[] getScreenRates0(long display, int screen_index, int mode_index); private static native long getScreenConfiguration0(long display, int screen_index); private static native void freeScreenConfiguration0(long screenConfiguration); diff --git a/src/newt/classes/jogamp/newt/driver/x11/RandR13.java b/src/newt/classes/jogamp/newt/driver/x11/RandR13.java index 24c9806af..d10591381 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/RandR13.java +++ b/src/newt/classes/jogamp/newt/driver/x11/RandR13.java @@ -27,25 +27,283 @@ */ package jogamp.newt.driver.x11; -import com.jogamp.newt.ScreenMode; +import java.util.Iterator; +import jogamp.newt.MonitorModeProps; + +import com.jogamp.common.util.IntLongHashMap; +import com.jogamp.common.util.VersionNumber; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; + +/** + * Mapping details: + *
        + * MonitorMode.id   == XRR mode-id (not index)
        + * MonitorDevice.id == XRR monitor-idx (not id)
        + * 
        + */ public class RandR13 implements RandR { + private static final boolean DEBUG = ScreenDriver.DEBUG; + + public static VersionNumber version = new VersionNumber(1, 3, 0); - public int[] getScreenModeFirstImpl(final long dpy, final int screen_idx) { + public static RandR13 createInstance(VersionNumber rAndRVersion) { + if( rAndRVersion.compareTo(version) >= 0 ) { + return new RandR13(); + } return null; + } + private RandR13() { + } + + @Override + public void dumpInfo(final long dpy, final int screen_idx) { + long screenResources = getScreenResources0(dpy, screen_idx); + if(0 == screenResources) { + return; + } + try { + dumpInfo0(dpy, screen_idx, screenResources); + } finally { + freeScreenResources0(screenResources); + } + } + + long sessionScreenResources = 0; + IntLongHashMap crtInfoHandleMap = null; + + @Override + public boolean beginInitialQuery(long dpy, ScreenDriver screen) { + final int screen_idx = screen.getIndex(); + sessionScreenResources = getScreenResources0(dpy, screen_idx); + if( 0 != sessionScreenResources ) { + crtInfoHandleMap = new IntLongHashMap(); + crtInfoHandleMap.setKeyNotFoundValue(0); + return true; + } else { + return false; + } + } + + @Override + public void endInitialQuery(long dpy, ScreenDriver screen) { + if( null != crtInfoHandleMap ) { + for(Iterator iter = crtInfoHandleMap.iterator(); iter.hasNext(); ) { + final IntLongHashMap.Entry entry = iter.next(); + freeMonitorInfoHandle0(entry.value); + } + crtInfoHandleMap.clear(); + crtInfoHandleMap = null; + } + if( 0 != sessionScreenResources ) { + freeScreenResources0( sessionScreenResources ); + sessionScreenResources = 0; + } } - public int[] getScreenModeNextImpl(final long dpy, final int screen_idx) { - return null; + + private final long getScreenResourceHandle(final long dpy, final int screen_idx) { + if( 0 != sessionScreenResources ) { + return sessionScreenResources; + } + return getScreenResources0(dpy, screen_idx); + } + private final void releaseScreenResourceHandle(final long screenResourceHandle) { + if( 0 == sessionScreenResources ) { + freeScreenResources0( screenResourceHandle ); + } } - public ScreenMode getCurrentScreenModeImpl(final long dpy, final int screen_idx) { - return null; + + private final long getMonitorInfoHandle(final long dpy, final int screen_idx, long screenResources, final int monitor_idx) { + if( null != crtInfoHandleMap ) { + long h = crtInfoHandleMap.get(monitor_idx); + if( 0 == h ) { + h = getMonitorInfoHandle0(dpy, screen_idx, screenResources, monitor_idx); + crtInfoHandleMap.put(monitor_idx, h); + } + return h; + } else { + return getMonitorInfoHandle0(dpy, screen_idx, screenResources, monitor_idx); + } } + private final void releaseMonitorInfoHandle(final long monitorInfoHandle) { + if( null == crtInfoHandleMap ) { + freeMonitorInfoHandle0(monitorInfoHandle); + } + } - public boolean setCurrentScreenModeImpl(final long dpy, final int screen_idx, final ScreenMode screenMode, final int screenModeIdx, final int resolutionIdx) { - return false; + @Override + public int getMonitorDeviceCount(final long dpy, final ScreenDriver screen) { + final int screen_idx = screen.getIndex(); + final long screenResources = getScreenResourceHandle(dpy, screen_idx); + try { + return getMonitorDeviceCount0(screenResources); + } finally { + releaseScreenResourceHandle(screenResources); + } } + @Override + public int[] getAvailableRotations(final long dpy, final ScreenDriver screen, final int crt_idx) { + final int screen_idx = screen.getIndex(); + final long screenResources = getScreenResourceHandle(dpy, screen_idx); + try { + final long monitorInfo = getMonitorInfoHandle(dpy, screen_idx, screenResources, crt_idx); + try { + final int[] availRotations = getAvailableRotations0(monitorInfo); + if(null==availRotations || 0==availRotations.length) { + return null; + } + return availRotations; + } finally { + releaseMonitorInfoHandle(monitorInfo); + } + } finally { + releaseScreenResourceHandle(screenResources); + } + } + + @Override + public int[] getMonitorModeProps(final long dpy, final ScreenDriver screen, final int mode_idx) { + final int screen_idx = screen.getIndex(); + final long screenResources = getScreenResourceHandle(dpy, screen_idx); + try { + return getMonitorMode0(screenResources, mode_idx); + } finally { + releaseScreenResourceHandle(screenResources); + } + } + + @Override + public int[] getMonitorDeviceProps(final long dpy, final ScreenDriver screen, MonitorModeProps.Cache cache, final int crt_idx) { + final int screen_idx = screen.getIndex(); + final long screenResources = getScreenResourceHandle(dpy, screen_idx); + try { + final long monitorInfo = getMonitorInfoHandle(dpy, screen_idx, screenResources, crt_idx); + try { + return getMonitorDevice0(dpy, screenResources, monitorInfo, crt_idx); + } finally { + releaseMonitorInfoHandle(monitorInfo); + } + } finally { + releaseScreenResourceHandle(screenResources); + } + } + + @Override + public int[] getMonitorDeviceViewport(final long dpy, final ScreenDriver screen, final int crt_idx) { + final int screen_idx = screen.getIndex(); + final long screenResources = getScreenResourceHandle(dpy, screen_idx); + try { + final long monitorInfo = getMonitorInfoHandle(dpy, screen_idx, screenResources, crt_idx); + try { + return getMonitorViewport0(monitorInfo); + } finally { + releaseMonitorInfoHandle(monitorInfo); + } + } finally { + releaseScreenResourceHandle(screenResources); + } + } + + @Override + public int[] getCurrentMonitorModeProps(final long dpy, final ScreenDriver screen, final int crt_idx) { + final int screen_idx = screen.getIndex(); + final long screenResources = getScreenResourceHandle(dpy, screen_idx); + try { + final long monitorInfo = getMonitorInfoHandle(dpy, screen_idx, screenResources, crt_idx); + try { + return getMonitorCurrentMode0(screenResources, monitorInfo); + } finally { + releaseMonitorInfoHandle(monitorInfo); + } + } finally { + releaseScreenResourceHandle(screenResources); + } + } + + @Override + public boolean setCurrentMonitorMode(final long dpy, final ScreenDriver screen, MonitorDevice monitor, final MonitorMode mode) { + final int screen_idx = screen.getIndex(); + final long screenResources = getScreenResourceHandle(dpy, screen_idx); + final boolean res; + try { + final long monitorInfo = getMonitorInfoHandle(dpy, screen_idx, screenResources, monitor.getId()); + try { + res = setMonitorMode0(dpy, screenResources, monitorInfo, monitor.getId(), mode.getId(), mode.getRotation(), + -1, -1); // no fixed position! + } finally { + releaseMonitorInfoHandle(monitorInfo); + } + } finally { + releaseScreenResourceHandle(screenResources); + } + /*** + * TODO: Would need a complete re-layout of crt positions, + * which is _not_ implicit by XRandR .. sadly. + * + if( res ) { + updateScreenViewport(dpy, screen, monitor); + } */ + return res; + } + + /** See above .. + private final void updateScreenViewport(final long dpy, final ScreenDriver screen, MonitorDevice monitor) { + final int screen_idx = screen.getIndex(); + final long screenResources = getScreenResourceHandle(dpy, screen_idx); + try { + RectangleImmutable newViewp = null; + final long monitorInfo = getMonitorInfoHandle(dpy, screen_idx, screenResources, monitor.getId()); + try { + final int[] vprops = getMonitorViewport0(monitorInfo); + if( null != vprops ) { + newViewp = new Rectangle(vprops[0], vprops[1], vprops[2], vprops[3]); + } + System.err.println("XXX setScreenViewport: newVp "+newViewp); + } finally { + releaseMonitorInfoHandle(monitorInfo); + } + if( null != newViewp ) { + final List monitors = screen.getMonitorDevices(); + final ArrayList viewports = new ArrayList(); + for(int i=0; i "+newScrnViewp); + setScreenViewport0(dpy, screen_idx, screenResources, newScrnViewp.getX(), newScrnViewp.getY(), newScrnViewp.getWidth(), newScrnViewp.getHeight()); + } + } finally { + dumpInfo0(dpy, screen_idx, screenResources); + releaseScreenResourceHandle(screenResources); + } + } */ + private static native long getScreenResources0(long display, int screen_index); - private static native void freeScreenResources0(long screenConfiguration); + private static native void freeScreenResources0(long screenResources); + private static native void dumpInfo0(long display, int screen_index, long screenResources); + + private static native int getMonitorDeviceCount0(long screenResources); + + private static native long getMonitorInfoHandle0(long display, int screen_index, long screenResources, int monitor_index); + private static native void freeMonitorInfoHandle0(long monitorInfoHandle); + + private static native int[] getAvailableRotations0(long monitorInfo); + private static native int[] getMonitorViewport0(long monitorInfo); + private static native int[] getMonitorCurrentMode0(long monitorInfo); + + private static native int[] getMonitorMode0(long screenResources, int mode_index); + private static native int[] getMonitorCurrentMode0(long screenResources, long monitorInfo); + private static native int[] getMonitorDevice0(long display, long screenResources, long monitorInfo, int monitor_idx); + private static native boolean setMonitorMode0(long display, long screenResources, long monitorInfo, int monitor_idx, int mode_id, int rotation, int x, int y); + private static native boolean setScreenViewport0(long display, int screen_index, long screenResources, int x, int y, int width, int height); } diff --git a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java index cd8da9b60..ba22a6ce4 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java @@ -33,23 +33,29 @@ */ package jogamp.newt.driver.x11; +import java.util.ArrayList; import java.util.List; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.util.Rectangle; import jogamp.nativewindow.x11.X11Util; +import jogamp.newt.Debug; import jogamp.newt.DisplayImpl; +import jogamp.newt.MonitorModeProps; import jogamp.newt.DisplayImpl.DisplayRunnable; import jogamp.newt.ScreenImpl; +import com.jogamp.common.util.ArrayHashSet; import com.jogamp.common.util.VersionNumber; import com.jogamp.nativewindow.x11.X11GraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsScreen; -import com.jogamp.newt.ScreenMode; - -public class ScreenDriver extends ScreenImpl { +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; +public class ScreenDriver extends ScreenImpl { + protected static final boolean DEBUG_TEST_RANDR13_DISABLED = Debug.isPropertyDefined("newt.test.Screen.disableRandR13", true); + static { DisplayDriver.initSingleton(); } @@ -57,12 +63,13 @@ public class ScreenDriver extends ScreenImpl { public ScreenDriver() { } + @Override protected void createNativeImpl() { // validate screen index Long handle = runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public Long run(long dpy) { return new Long(GetScreen0(dpy, screen_idx)); - } } ); + } } ); if (handle.longValue() == 0) { throw new RuntimeException("Error creating screen: " + screen_idx); } @@ -73,73 +80,116 @@ public class ScreenDriver extends ScreenImpl { int v[] = getRandRVersion0(dpy); randrVersion = new VersionNumber(v[0], v[1], 0); } - if( DEBUG ) { - System.err.println("RandR "+randrVersion); + { + final RandR13 rAndR13 = DEBUG_TEST_RANDR13_DISABLED ? null : RandR13.createInstance(randrVersion); + if( null != rAndR13 ) { + rAndR = rAndR13; + } else { + rAndR = RandR11.createInstance(randrVersion); + } } - if( !randrVersion.isZero() ) { - rAndR = new RandR11(); - } else { - rAndR = null; + if( DEBUG ) { + System.err.println("RandR "+randrVersion+", "+rAndR); + rAndR.dumpInfo(dpy, screen_idx); } } + @Override protected void closeNativeImpl() { } private VersionNumber randrVersion; private RandR rAndR; - + @Override - protected int[] getScreenModeFirstImpl() { - if( null == rAndR ) { return null; } - - return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { - public int[] run(long dpy) { - return rAndR.getScreenModeFirstImpl(dpy, screen_idx); - } } ); + protected final void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache) { + if( null == rAndR ) { return; } + final AbstractGraphicsDevice device = getDisplay().getGraphicsDevice(); + device.lock(); + try { + if( rAndR.beginInitialQuery(device.getHandle(), this) ) { + try { + final int crtCount = rAndR.getMonitorDeviceCount(device.getHandle(), this); + + // Gather all available rotations + final ArrayHashSet availableRotations = new ArrayHashSet(); + for(int i = 0; i < crtCount; i++) { + final int[] rotations = rAndR.getAvailableRotations(device.getHandle(), this, i); + if( null != rotations ) { + final List rotationList = new ArrayList(rotations.length); + for(int j=0; j 0 ) { + for(int i = 0; i < crtCount; i++) { + final int[] monitorProps = rAndR.getMonitorDeviceProps(device.getHandle(), this, cache, i); + if( null != monitorProps ) { // enabled + MonitorModeProps.streamInMonitorDevice(null, cache, this, monitorProps, 0); + } + } + } + } finally { + rAndR.endInitialQuery(device.getHandle(), this); + } + } + } finally { + device.unlock(); + } } @Override - protected int[] getScreenModeNextImpl() { - if( null == rAndR ) { return null; } - - // assemble: w x h x bpp x f x r - return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { - public int[] run(long dpy) { - return rAndR.getScreenModeNextImpl(dpy, screen_idx); - } } ); + protected Rectangle getNativeMonitorDeviceViewportImpl(MonitorDevice monitor) { + final AbstractGraphicsDevice device = getDisplay().getGraphicsDevice(); + device.lock(); + try { + int[] viewportProps = rAndR.getMonitorDeviceViewport(device.getHandle(), this, monitor.getId()); + return new Rectangle(viewportProps[0], viewportProps[1], viewportProps[2], viewportProps[3]); + } finally { + device.unlock(); + } } - + @Override - protected ScreenMode getCurrentScreenModeImpl() { + protected MonitorMode queryCurrentMonitorModeImpl(final MonitorDevice monitor) { if( null == rAndR ) { return null; } - return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { - public ScreenMode run(long dpy) { - return rAndR.getCurrentScreenModeImpl(dpy, screen_idx); + return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + public MonitorMode run(long dpy) { + final int[] currentModeProps = rAndR.getCurrentMonitorModeProps(dpy, ScreenDriver.this, monitor.getId()); + return MonitorModeProps.streamInMonitorMode(null, null, currentModeProps, 0); } } ); } @Override - protected boolean setCurrentScreenModeImpl(final ScreenMode screenMode) { + protected boolean setCurrentMonitorModeImpl(final MonitorDevice monitor, final MonitorMode mode) { if( null == rAndR ) { return false; } - final List screenModes = this.getScreenModesOrig(); - final int screenModeIdx = screenModes.indexOf(screenMode); - if(0>screenModeIdx) { - throw new RuntimeException("ScreenMode not element of ScreenMode list: "+screenMode); - } final long t0 = System.currentTimeMillis(); boolean done = runWithTempDisplayHandle( new DisplayImpl.DisplayRunnable() { public Boolean run(long dpy) { - final int resIdx = getScreenModesIdx2NativeIdx().get(screenModeIdx); - return Boolean.valueOf( rAndR.setCurrentScreenModeImpl(dpy, screen_idx, screenMode, screenModeIdx, resIdx) ); + return Boolean.valueOf( rAndR.setCurrentMonitorMode(dpy, ScreenDriver.this, monitor, mode) ); } }).booleanValue(); if(DEBUG || !done) { System.err.println("X11Screen.setCurrentScreenModeImpl: TO ("+SCREEN_MODE_CHANGE_TIMEOUT+") reached: "+ - (System.currentTimeMillis()-t0)+"ms; Current: "+getCurrentScreenMode()+"; Desired: "+screenMode); + (System.currentTimeMillis()-t0)+"ms; "+monitor.getCurrentMode()+" -> "+mode); } return done; } @@ -149,6 +199,7 @@ public class ScreenDriver extends ScreenImpl { return new Boolean(X11Util.XineramaIsEnabled(dpy)); } }; + @Override protected int validateScreenIndex(final int idx) { final DisplayDriver x11Display = (DisplayDriver) getDisplay(); final Boolean r = x11Display.isXineramaEnabled(); @@ -159,13 +210,14 @@ public class ScreenDriver extends ScreenImpl { } } - protected void getVirtualScreenOriginAndSize(final Point virtualOrigin, final Dimension virtualSize) { + @Override + protected void calcVirtualScreenOriginAndSize(final Rectangle vOriginSize) { runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public Object run(long dpy) { - virtualOrigin.setX(0); - virtualOrigin.setY(0); - virtualSize.setWidth(getWidth0(dpy, screen_idx)); - virtualSize.setHeight(getHeight0(dpy, screen_idx)); + vOriginSize.setX(0); + vOriginSize.setY(0); + vOriginSize.setWidth(getWidth0(dpy, screen_idx)); + vOriginSize.setHeight(getHeight0(dpy, screen_idx)); return null; } } ); } diff --git a/src/newt/native/MacWindow.m b/src/newt/native/MacWindow.m index c0552216e..1c7064a66 100644 --- a/src/newt/native/MacWindow.m +++ b/src/newt/native/MacWindow.m @@ -285,47 +285,32 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_DisplayDriver_stopNSApplic [pool release]; } -static NSScreen * NewtScreen_getNSScreenByIndex(int screen_idx) { +static NSScreen * NewtScreen_getNSScreenByIndex(int screen_idx, BOOL cap) { NSArray *screens = [NSScreen screens]; - if(screen_idx<0) screen_idx=0; - if(screen_idx>=[screens count]) screen_idx=0; + if( screen_idx<0 || screen_idx>=[screens count] ) { + if( cap ) { + screen_idx=0; + } else { + return NULL; + } + } return (NSScreen *) [screens objectAtIndex: screen_idx]; } -/* - * Class: jogamp_newt_driver_macosx_ScreenDriver - * Method: getWidthImpl - * Signature: (I)I - */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getWidthImpl0 - (JNIEnv *env, jclass clazz, jint screen_idx) -{ - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - - NSScreen *screen = NewtScreen_getNSScreenByIndex((int)screen_idx); - NSRect rect = [screen frame]; - - [pool release]; - - return (jint) (rect.size.width); -} - -/* - * Class: jogamp_newt_driver_macosx_ScreenDriver - * Method: getHeightImpl - * Signature: (I)I - */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getHeightImpl0 - (JNIEnv *env, jclass clazz, jint screen_idx) -{ - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - - NSScreen *screen = NewtScreen_getNSScreenByIndex((int)screen_idx); - NSRect rect = [screen frame]; - - [pool release]; - - return (jint) (rect.size.height); +static NSScreen * NewtScreen_getNSScreenByCoord(int x, int y) { + NSArray *screens = [NSScreen screens]; + int i; + for(i=[screens count]-1; i>=0; i--) { + NSScreen * screen = (NSScreen *) [screens objectAtIndex: i]; + NSRect frame = [screen frame]; + if( x >= frame.origin.x && + y >= frame.origin.y && + x < frame.origin.x + frame.size.width && + y < frame.origin.y + frame.size.height ) { + return screen; + } + } + return (NSScreen *) [screens objectAtIndex: 0]; } static CGDirectDisplayID NewtScreen_getCGDirectDisplayIDByNSScreen(NSScreen *screen) { @@ -362,11 +347,11 @@ static long GetDictionaryLong(CFDictionaryRef theDict, const void* key) /* * Class: jogamp_newt_driver_macosx_ScreenDriver - * Method: getScreenSizeMM0 + * Method: getMonitorProps0 * Signature: (I)[I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScreenSizeMM0 - (JNIEnv *env, jobject obj, jint scrn_idx) +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getMonitorProps0 + (JNIEnv *env, jobject obj, jint crt_idx) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -376,33 +361,46 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScree timespec_now(&t0); #endif - NSScreen *screen = NewtScreen_getNSScreenByIndex((int)scrn_idx); #ifdef DBG_PERF timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td); - fprintf(stderr, "MacScreen_getScreenSizeMM0.1: %ld ms\n", td_ms); fflush(NULL); + fprintf(stderr, "MacScreen_getMonitorProps0.1: %ld ms\n", td_ms); fflush(NULL); #endif - + NSScreen *screen = NewtScreen_getNSScreenByIndex((int)crt_idx, false); + if( NULL == screen ) { + [pool release]; + return NULL; + } CGDirectDisplayID display = NewtScreen_getCGDirectDisplayIDByNSScreen(screen); #ifdef DBG_PERF timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td); - fprintf(stderr, "MacScreen_getScreenSizeMM0.2: %ld ms\n", td_ms); fflush(NULL); + fprintf(stderr, "MacScreen_getMonitorProps0.2: %ld ms\n", td_ms); fflush(NULL); #endif - CGSize screenDim = CGDisplayScreenSize(display); + CGSize sizeMM = CGDisplayScreenSize(display); #ifdef DBG_PERF timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td); - fprintf(stderr, "MacScreen_getScreenSizeMM0.3: %ld ms\n", td_ms); fflush(NULL); + fprintf(stderr, "MacScreen_getMonitorProps0.3: %ld ms\n", td_ms); fflush(NULL); #endif - jint prop[ 2 ]; - prop[0] = (jint) screenDim.width; - prop[1] = (jint) screenDim.height; - - jintArray properties = (*env)->NewIntArray(env, 2); + CGRect bounds = CGDisplayBounds (display); + + jsize propCount = MIN_MONITOR_DEVICE_PROPERTIES - 1 - NUM_MONITOR_MODE_PROPERTIES; + jint prop[ propCount ]; + int offset = 0; + prop[offset++] = propCount; + prop[offset++] = crt_idx; + prop[offset++] = (jint) sizeMM.width; + prop[offset++] = (jint) sizeMM.height; + prop[offset++] = (jint) bounds.origin.x; // rotated viewport x + prop[offset++] = (jint) bounds.origin.y; // rotated viewport y + prop[offset++] = (jint) bounds.size.width; // rotated viewport width + prop[offset++] = (jint) bounds.size.height; // rotated viewport height + + jintArray properties = (*env)->NewIntArray(env, propCount); if (properties == NULL) { - NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size 2"); + NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", propCount); } - (*env)->SetIntArrayRegion(env, properties, 0, 2, prop); + (*env)->SetIntArrayRegion(env, properties, 0, propCount, prop); [pool release]; @@ -411,16 +409,19 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScree /* * Class: jogamp_newt_driver_macosx_ScreenDriver - * Method: getScreenMode0 - * Signature: (IIII)[I + * Method: getMonitorMode0 + * Signature: (II)[I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScreenMode0 - (JNIEnv *env, jobject obj, jint scrn_idx, jint mode_idx, jint widthMM, jint heightMM) +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getMonitorMode0 + (JNIEnv *env, jobject obj, jint crt_idx, jint mode_idx) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - int prop_num = NUM_SCREEN_MODE_PROPERTIES_ALL; - NSScreen *screen = NewtScreen_getNSScreenByIndex((int)scrn_idx); + NSScreen *screen = NewtScreen_getNSScreenByIndex((int)crt_idx, false); + if( NULL == screen ) { + [pool release]; + return NULL; + } CGDirectDisplayID display = NewtScreen_getCGDirectDisplayIDByNSScreen(screen); CFArrayRef availableModes = CGDisplayAvailableModes(display); @@ -429,12 +430,13 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScree CFDictionaryRef mode = NULL; int currentCCWRot = (int)CGDisplayRotation(display); jint ccwRot = 0; + int nativeId = 0; #ifdef VERBOSE_ON if(0 >= mode_idx) { // only for current mode (-1) and first mode (scanning) DBG_PRINT( "getScreenMode0: scrn %d (%p, %p), mode %d, avail: %d/%d, current rot %d ccw\n", - (int)scrn_idx, screen, (void*)(intptr_t)display, (int)mode_idx, (int)numberOfAvailableModes, (int)numberOfAvailableModesRots, currentCCWRot); + (int)crt_idx, screen, (void*)(intptr_t)display, (int)mode_idx, (int)numberOfAvailableModes, (int)numberOfAvailableModesRots, currentCCWRot); } #endif @@ -443,16 +445,18 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScree DBG_PRINT( "getScreenMode0: end of modes: mode %d, avail: %d/%d\n", (int)mode_idx, (int)numberOfAvailableModes, (int)numberOfAvailableModesRots); [pool release]; - return (*env)->NewIntArray(env, 0); + return NULL; } else if(-1 < mode_idx) { // only at initialization time, where index >= 0 - prop_num++; // add 1st extra prop, mode_idx - mode = (CFDictionaryRef)CFArrayGetValueAtIndex(availableModes, mode_idx / ROTMODES_PER_REALMODE); + nativeId = mode_idx / ROTMODES_PER_REALMODE; ccwRot = mode_idx % ROTMODES_PER_REALMODE * 90; + mode = (CFDictionaryRef)CFArrayGetValueAtIndex(availableModes, nativeId); } else { // current mode mode = CGDisplayCurrentMode(display); ccwRot = currentCCWRot; + CFRange range = CFRangeMake (0, numberOfAvailableModes); + nativeId = CFArrayGetFirstIndexOfValue(availableModes, range, (CFDictionaryRef)mode); } // mode = CGDisplayModeRetain(mode); // 10.6 on CGDisplayModeRef @@ -466,36 +470,30 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScree mHeight = tempWidth; } - jint prop[ prop_num ]; + jint prop[ NUM_MONITOR_MODE_PROPERTIES_ALL ]; int propIndex = 0; - int propIndexRes = 0; - if( -1 < mode_idx ) { - prop[propIndex++] = mode_idx; - } int refreshRate = CGDDGetModeRefreshRate(mode); int fRefreshRate = ( 0 < refreshRate ) ? refreshRate : 60; // default .. (experienced on OSX 10.6.8) - prop[propIndex++] = 0; // set later for verification of iterator - propIndexRes = propIndex; + prop[propIndex++] = NUM_MONITOR_MODE_PROPERTIES_ALL; prop[propIndex++] = mWidth; prop[propIndex++] = mHeight; prop[propIndex++] = CGDDGetModeBitsPerPixel(mode); - prop[propIndex++] = widthMM; - prop[propIndex++] = heightMM; - prop[propIndex++] = fRefreshRate; + prop[propIndex++] = fRefreshRate * 100; // Hz*100 + prop[propIndex++] = 0; // flags + prop[propIndex++] = nativeId; prop[propIndex++] = ccwRot; - prop[propIndex - NUM_SCREEN_MODE_PROPERTIES_ALL] = ( -1 < mode_idx ) ? propIndex-1 : propIndex ; // count == NUM_SCREEN_MODE_PROPERTIES_ALL - DBG_PRINT( "getScreenMode0: Mode %d/%d (%d): %dx%d, %d bpp, %dx%d mm, %d / %d Hz, rot %d ccw\n", + DBG_PRINT( "getScreenMode0: Mode %d/%d (%d): %dx%d, %d bpp, %d / %d Hz, nativeId %d, rot %d ccw\n", (int)mode_idx, (int)numberOfAvailableModesRots, (int)numberOfAvailableModes, - (int)prop[propIndexRes+0], (int)prop[propIndexRes+1], (int)prop[propIndexRes+2], - (int)prop[propIndexRes+3], (int)prop[propIndexRes+4], (int)prop[propIndexRes+5], refreshRate, (int)prop[propIndexRes+6]); + (int)prop[1], (int)prop[2], (int)prop[3], + (int)prop[4], refreshRate, (int)prop[6], (int)prop[7]); - jintArray properties = (*env)->NewIntArray(env, prop_num); + jintArray properties = (*env)->NewIntArray(env, NUM_MONITOR_MODE_PROPERTIES_ALL); if (properties == NULL) { - NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", prop_num); + NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", NUM_MONITOR_MODE_PROPERTIES_ALL); } - (*env)->SetIntArrayRegion(env, properties, 0, prop_num, prop); + (*env)->SetIntArrayRegion(env, properties, 0, NUM_MONITOR_MODE_PROPERTIES_ALL, prop); // CGDisplayModeRelease(mode); // 10.6 on CGDisplayModeRef [pool release]; @@ -505,36 +503,47 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_getScree /* * Class: jogamp_newt_driver_macosx_ScreenDriver - * Method: setScreenMode0 - * Signature: (II)Z + * Method: setMonitorMode0 + * Signature: (III)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_setScreenMode0 - (JNIEnv *env, jobject object, jint scrn_idx, jint mode_idx) +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_ScreenDriver_setMonitorMode0 + (JNIEnv *env, jobject object, jint crt_idx, jint nativeId, jint ccwRot) { jboolean res = JNI_TRUE; NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - NSScreen *screen = NewtScreen_getNSScreenByIndex((int)scrn_idx); + NSScreen *screen = NewtScreen_getNSScreenByIndex((int)crt_idx, false); + if( NULL == screen ) { + [pool release]; + return JNI_FALSE; + } CGDirectDisplayID display = NewtScreen_getCGDirectDisplayIDByNSScreen(screen); CFArrayRef availableModes = CGDisplayAvailableModes(display); -#ifdef VERBOSE_ON CFIndex numberOfAvailableModes = CFArrayGetCount(availableModes); +#ifdef VERBOSE_ON CFIndex numberOfAvailableModesRots = ROTMODES_PER_REALMODE * numberOfAvailableModes; #endif - CFDictionaryRef mode = (CFDictionaryRef)CFArrayGetValueAtIndex(availableModes, mode_idx / ROTMODES_PER_REALMODE); - // mode = CGDisplayModeRetain(mode); // 10.6 on CGDisplayModeRef - int ccwRot = mode_idx % ROTMODES_PER_REALMODE * 90; - DBG_PRINT( "setScreenMode0: scrn %d (%p, %p), mode %d, rot %d ccw, avail: %d/%d\n", - (int)scrn_idx, screen, (void*)(intptr_t)display, (int)mode_idx, ccwRot, (int)numberOfAvailableModes, (int)numberOfAvailableModesRots); + DBG_PRINT( "setScreenMode0: scrn %d (%p, %p), nativeID %d, rot %d ccw, avail: %d/%d\n", + (int)crt_idx, screen, (void*)(intptr_t)display, (int)nativeId, ccwRot, (int)numberOfAvailableModes, (int)numberOfAvailableModesRots); + + CFDictionaryRef mode = NULL; - if(ccwRot!=0) { + if( 0 != ccwRot ) { // FIXME: How to rotate the display/screen on OSX programmatically ? DBG_PRINT( "setScreenMode0: Don't know how to rotate screen on OS X: rot %d ccw\n", ccwRot); res = JNI_FALSE; + } else { + if( numberOfAvailableModes <= nativeId ) { + res = JNI_FALSE; + } else { + mode = (CFDictionaryRef)CFArrayGetValueAtIndex(availableModes, nativeId); + // mode = CGDisplayModeRetain(mode); // 10.6 on CGDisplayModeRef + } } - if(JNI_TRUE == res) { + + if( NULL != mode ) { CGError err = CGDisplaySwitchToMode(display, mode); if(kCGErrorSuccess != err) { DBG_PRINT( "setScreenMode0: SetMode failed: %d\n", (int)err); @@ -593,21 +602,18 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_initIDs0 /** * Class: jogamp_newt_driver_macosx_WindowDriver * Method: createView0 - * Signature: (IIIIZI)J + * Signature: (IIIIZ)J */ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_createView0 (JNIEnv *env, jobject jthis, jint x, jint y, jint w, jint h, - jboolean fullscreen, jint screen_idx) + jboolean fullscreen) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - DBG_PRINT( "createView0 - %p (this), %d/%d %dx%d, fs %d, screenidx %d (START)\n", - (void*)(intptr_t)jthis, (int)x, (int)y, (int)w, (int)h, (int)fullscreen, (int)screen_idx); + DBG_PRINT( "createView0 - %p (this), %d/%d %dx%d, fs %d (START)\n", + (void*)(intptr_t)jthis, (int)x, (int)y, (int)w, (int)h, (int)fullscreen); - NSArray *screens = [NSScreen screens]; - if(screen_idx<0) screen_idx=0; - if(screen_idx>=[screens count]) screen_idx=0; - NSScreen *myScreen = (NSScreen *) [screens objectAtIndex: screen_idx]; + NSScreen *myScreen = NewtScreen_getNSScreenByCoord(x, y); NSRect rectWin; if (fullscreen) { @@ -634,24 +640,21 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_createView0 * * Class: jogamp_newt_driver_macosx_WindowDriver * Method: createWindow0 - * Signature: (IIIIZIIIJ)J + * Signature: (IIIIZIIJ)J */ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_createWindow0 (JNIEnv *env, jobject jthis, jint x, jint y, jint w, jint h, - jboolean fullscreen, jint styleMask, jint bufferingType, jint screen_idx, jlong jview) + jboolean fullscreen, jint styleMask, jint bufferingType, jlong jview) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; NewtView* myView = (NewtView*) (intptr_t) jview ; DBG_PRINT( "createWindow0 - %p (this), %d/%d %dx%d, fs %d, style %X, buffType %X, screenidx %d, view %p (START)\n", (void*)(intptr_t)jthis, (int)x, (int)y, (int)w, (int)h, (int)fullscreen, - (int)styleMask, (int)bufferingType, (int)screen_idx, myView); + (int)styleMask, (int)bufferingType, myView); (void)myView; - NSArray *screens = [NSScreen screens]; - if(screen_idx<0) screen_idx=0; - if(screen_idx>=[screens count]) screen_idx=0; - NSScreen *myScreen = (NSScreen *) [screens objectAtIndex: screen_idx]; + NSScreen *myScreen = NewtScreen_getNSScreenByCoord(x, y); NSRect rectWin; if (fullscreen) { @@ -670,7 +673,6 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_createWindow styleMask: (NSUInteger) styleMask backing: (NSBackingStoreType) bufferingType defer: YES - screen: myScreen isFullscreenWindow: fullscreen]; // DBG_PRINT( "createWindow0.1 - %p, isVisible %d\n", myWindow, [myWindow isVisible]); @@ -687,26 +689,23 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_createWindow * * Class: jogamp_newt_driver_macosx_WindowDriver * Method: initWindow0 - * Signature: (JJIIIIZZZIJ)V + * Signature: (JJIIIIZZZJ)V */ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_initWindow0 (JNIEnv *env, jobject jthis, jlong parent, jlong window, jint x, jint y, jint w, jint h, - jboolean opaque, jboolean fullscreen, jboolean visible, jint screen_idx, jlong jview) + jboolean opaque, jboolean fullscreen, jboolean visible, jlong jview) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; NewtMacWindow* myWindow = (NewtMacWindow*) ((intptr_t) window); NewtView* myView = (NewtView*) (intptr_t) jview ; - DBG_PRINT( "initWindow0 - %p (this), %p (parent), %p (window), %d/%d %dx%d, opaque %d, fs %d, visible %d, screenidx %d, view %p (START)\n", + DBG_PRINT( "initWindow0 - %p (this), %p (parent), %p (window), %d/%d %dx%d, opaque %d, fs %d, visible %d, view %p (START)\n", (void*)(intptr_t)jthis, (void*)(intptr_t)parent, myWindow, (int)x, (int)y, (int)w, (int)h, - (int) opaque, (int)fullscreen, (int)visible, (int)screen_idx, myView); + (int) opaque, (int)fullscreen, (int)visible, myView); - NSArray *screens = [NSScreen screens]; - if(screen_idx<0) screen_idx=0; - if(screen_idx>=[screens count]) screen_idx=0; - NSScreen *myScreen = (NSScreen *) [screens objectAtIndex: screen_idx]; - NSRect rectWin; + NSScreen *myScreen = NewtScreen_getNSScreenByCoord(x, y); + NSRect rectWin; if (fullscreen) { rectWin = [myScreen frame]; x = 0; diff --git a/src/newt/native/NewtMacWindow.h b/src/newt/native/NewtMacWindow.h index 09f4a1fd3..c9d53f53b 100644 --- a/src/newt/native/NewtMacWindow.h +++ b/src/newt/native/NewtMacWindow.h @@ -128,7 +128,6 @@ styleMask: (NSUInteger) windowStyle backing: (NSBackingStoreType) bufferingType defer: (BOOL) deferCreation - screen:(NSScreen *)screen isFullscreenWindow:(BOOL)isfs; #ifdef DBG_LIFECYCLE - (void) release; diff --git a/src/newt/native/NewtMacWindow.m b/src/newt/native/NewtMacWindow.m index 005e82d72..35d3ffbc5 100644 --- a/src/newt/native/NewtMacWindow.m +++ b/src/newt/native/NewtMacWindow.m @@ -439,14 +439,12 @@ static UniChar CKCH_CharForKeyCode(jshort keyCode) { styleMask: (NSUInteger) windowStyle backing: (NSBackingStoreType) bufferingType defer: (BOOL) deferCreation - screen:(NSScreen *)screen isFullscreenWindow:(BOOL)isfs { id res = [super initWithContentRect: contentRect styleMask: windowStyle backing: bufferingType - defer: deferCreation - screen: screen]; + defer: deferCreation]; isFullscreenWindow = isfs; // Why is this necessary? Without it we don't get any of the // delegate methods like resizing and window movement. diff --git a/src/newt/native/ScreenMode.h b/src/newt/native/ScreenMode.h index bb782910e..110f1c493 100644 --- a/src/newt/native/ScreenMode.h +++ b/src/newt/native/ScreenMode.h @@ -33,12 +33,17 @@ #ifndef _SCREEN_MODE_H #define _SCREEN_MODE_H -#define NUM_RESOLUTION_PROPERTIES 2 /* width, height */ -#define NUM_SURFACE_SIZE_PROPERTIES 1 /* bpp */ -#define NUM_MONITOR_MODE_PROPERTIES 3 /* ScreenSizeMM[width, height], refresh-rate */ -#define NUM_SCREEN_MODE_PROPERTIES 1 /* rotation */ +#define NUM_RESOLUTION_PROPERTIES 2 /* width, height */ +#define NUM_SURFACE_SIZE_PROPERTIES 1 /* bpp */ +#define NUM_SIZEANDRATE_PROPERTIES 2 /* refresh-rate, flags */ +#define NUM_MONITOR_MODE_PROPERTIES 2 /* id, rotation */ -#define NUM_SCREEN_MODE_PROPERTIES_ALL 8 /* count + the above */ +#define NUM_MONITOR_MODE_PROPERTIES_ALL 8 /* count + the above */ + +#define MIN_MONITOR_DEVICE_PROPERTIES 11 /* count + id, ScreenSizeMM[width, height], rotated Viewport[x, y, width, height], currentMonitorModeId, rotation, supportedModeId+ */ + +#define FLAG_INTERLACE ( 1 << 0 ) +#define FLAG_DOUBLESCAN ( 1 << 1 ) #endif diff --git a/src/newt/native/Window.h b/src/newt/native/Window.h index 4755c4fc5..d9ee5fd1f 100644 --- a/src/newt/native/Window.h +++ b/src/newt/native/Window.h @@ -38,8 +38,9 @@ #define FLAG_HAS_PARENT ( 1 << 8 ) #define FLAG_IS_UNDECORATED ( 1 << 9 ) #define FLAG_IS_FULLSCREEN ( 1 << 10 ) -#define FLAG_IS_ALWAYSONTOP ( 1 << 11 ) -#define FLAG_IS_VISIBLE ( 1 << 12 ) +#define FLAG_IS_FULLSCREEN_SPAN ( 1 << 11 ) +#define FLAG_IS_ALWAYSONTOP ( 1 << 12 ) +#define FLAG_IS_VISIBLE ( 1 << 13 ) #define TST_FLAG_CHANGE_PARENTING(f) ( 0 != ( (f) & FLAG_CHANGE_PARENTING ) ) #define TST_FLAG_CHANGE_DECORATION(f) ( 0 != ( (f) & FLAG_CHANGE_DECORATION ) ) @@ -47,11 +48,11 @@ #define TST_FLAG_CHANGE_ALWAYSONTOP(f) ( 0 != ( (f) & FLAG_CHANGE_ALWAYSONTOP ) ) #define TST_FLAG_CHANGE_VISIBILITY(f) ( 0 != ( (f) & FLAG_CHANGE_VISIBILITY ) ) -#define TST_FLAG_HAS_PARENT(f) ( 0 != ( (f) & FLAG_HAS_PARENT ) ) -#define TST_FLAG_IS_UNDECORATED(f) ( 0 != ( (f) & FLAG_IS_UNDECORATED ) ) -#define TST_FLAG_IS_FULLSCREEN(f) ( 0 != ( (f) & FLAG_IS_FULLSCREEN ) ) -#define TST_FLAG_IS_FULLSCREEN(f) ( 0 != ( (f) & FLAG_IS_FULLSCREEN ) ) -#define TST_FLAG_IS_ALWAYSONTOP(f) ( 0 != ( (f) & FLAG_IS_ALWAYSONTOP ) ) -#define TST_FLAG_IS_VISIBLE(f) ( 0 != ( (f) & FLAG_IS_VISIBLE ) ) +#define TST_FLAG_HAS_PARENT(f) ( 0 != ( (f) & FLAG_HAS_PARENT ) ) +#define TST_FLAG_IS_UNDECORATED(f) ( 0 != ( (f) & FLAG_IS_UNDECORATED ) ) +#define TST_FLAG_IS_FULLSCREEN(f) ( 0 != ( (f) & FLAG_IS_FULLSCREEN ) ) +#define TST_FLAG_IS_FULLSCREEN_SPAN(f) ( 0 != ( (f) & FLAG_IS_FULLSCREEN_SPAN ) ) +#define TST_FLAG_IS_ALWAYSONTOP(f) ( 0 != ( (f) & FLAG_IS_ALWAYSONTOP ) ) +#define TST_FLAG_IS_VISIBLE(f) ( 0 != ( (f) & FLAG_IS_VISIBLE ) ) #endif diff --git a/src/newt/native/WindowsWindow.c b/src/newt/native/WindowsWindow.c index 5c1115592..7ede3a20d 100644 --- a/src/newt/native/WindowsWindow.c +++ b/src/newt/native/WindowsWindow.c @@ -101,6 +101,9 @@ #ifndef DISPLAY_DEVICE_ACTIVE #define DISPLAY_DEVICE_ACTIVE 0x00000001 #endif +#ifndef DM_INTERLACED +#define DM_INTERLACED 2 +#endif #include "jogamp_newt_driver_windows_DisplayDriver.h" #include "jogamp_newt_driver_windows_ScreenDriver.h" @@ -1116,11 +1119,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_DisplayDriver_DispatchMes /* * Class: jogamp_newt_driver_windows_ScreenDriver - * Method: getOriginX0 - * Signature: (I)I + * Method: getVirtualOriginX0 + * Signature: ()I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getOriginX0 - (JNIEnv *env, jobject obj, jint scrn_idx) +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getVirtualOriginX0 + (JNIEnv *env, jobject obj) { if( GetSystemMetrics( SM_CMONITORS) > 1) { return (jint)GetSystemMetrics(SM_XVIRTUALSCREEN); @@ -1131,11 +1134,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getOriginX0 /* * Class: jogamp_newt_driver_windows_ScreenDriver - * Method: getOriginY0 - * Signature: (I)I + * Method: getVirtualOriginY0 + * Signature: ()I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getOriginY0 - (JNIEnv *env, jobject obj, jint scrn_idx) +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getVirtualOriginY0 + (JNIEnv *env, jobject obj) { if( GetSystemMetrics( SM_CMONITORS ) > 1) { return (jint)GetSystemMetrics(SM_YVIRTUALSCREEN); @@ -1146,11 +1149,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getOriginY0 /* * Class: jogamp_newt_driver_windows_ScreenDriver - * Method: getWidthImpl - * Signature: (I)I + * Method: getVirtualWidthImpl + * Signature: ()I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getWidthImpl0 - (JNIEnv *env, jobject obj, jint scrn_idx) +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getVirtualWidthImpl0 + (JNIEnv *env, jobject obj) { if( GetSystemMetrics( SM_CMONITORS) > 1) { return (jint)GetSystemMetrics(SM_CXVIRTUALSCREEN); @@ -1161,11 +1164,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getWidthImpl /* * Class: jogamp_newt_driver_windows_ScreenDriver - * Method: getHeightImpl - * Signature: (I)I + * Method: getVirtualHeightImpl + * Signature: ()I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getHeightImpl0 - (JNIEnv *env, jobject obj, jint scrn_idx) +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getVirtualHeightImpl0 + (JNIEnv *env, jobject obj) { if( GetSystemMetrics( SM_CMONITORS ) > 1) { return (jint)GetSystemMetrics(SM_CYVIRTUALSCREEN); @@ -1217,65 +1220,137 @@ static int NewtScreen_RotationNewtCCW2NativeCCW(JNIEnv *env, jint newt) { return native; } -/* -static void NewtScreen_scanDisplayDevices() { - DISPLAY_DEVICE device; - int i = 0; - LPCTSTR name; - while(NULL != (name = NewtScreen_getDisplayDeviceName(&device, i))) { - DBG_PRINT("*** [%d]: <%s> active %d\n", i, name, ( 0 != ( device.StateFlags & DISPLAY_DEVICE_ACTIVE ) ) ); - i++; +static LPCTSTR NewtScreen_getAdapterName(DISPLAY_DEVICE * device, int crt_idx) { + memset(device, 0, sizeof(DISPLAY_DEVICE)); + device->cb = sizeof(DISPLAY_DEVICE); + if( FALSE == EnumDisplayDevices(NULL, crt_idx, device, 0) ) { + DBG_PRINT("*** WindowsWindow: getAdapterName.EnumDisplayDevices(crt_idx %d) -> FALSE\n", crt_idx); + return NULL; } -}*/ -static LPCTSTR NewtScreen_getDisplayDeviceName(DISPLAY_DEVICE * device, int scrn_idx) { - device->cb = sizeof(DISPLAY_DEVICE); - if( FALSE == EnumDisplayDevices(NULL, scrn_idx, device, 0) ) { - DBG_PRINT("*** WindowsWindow: getDisplayDeviceName.EnumDisplayDevices(scrn_idx %d) -> FALSE\n", scrn_idx); + if( NULL == device->DeviceName || 0 == _tcslen(device->DeviceName) ) { return NULL; } - if( 0 == ( device->StateFlags & DISPLAY_DEVICE_ACTIVE ) ) { - DBG_PRINT("*** WindowsWindow: !DISPLAY_DEVICE_ACTIVE(scrn_idx %d)\n", scrn_idx); + return device->DeviceName; +} + +static LPCTSTR NewtScreen_getMonitorName(LPCTSTR adapterName, DISPLAY_DEVICE * device, int monitor_idx, BOOL onlyActive) { + memset(device, 0, sizeof(DISPLAY_DEVICE)); + device->cb = sizeof(DISPLAY_DEVICE); + if( 0 == monitor_idx ) { + if( FALSE == EnumDisplayDevices(adapterName, monitor_idx, device, 0) ) { + DBG_PRINT("*** WindowsWindow: getDisplayName.EnumDisplayDevices(monitor_idx %d).adapter -> FALSE\n", monitor_idx); + return NULL; + } + } + + if( onlyActive && 0 == ( device->StateFlags & DISPLAY_DEVICE_ACTIVE ) ) { + DBG_PRINT("*** WindowsWindow: !DISPLAY_DEVICE_ACTIVE(monitor_idx %d).display\n", monitor_idx); + return NULL; + } + if( NULL == device->DeviceName || 0 == _tcslen(device->DeviceName) ) { return NULL; } return device->DeviceName; } +JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_dumpMonitorInfo0 + (JNIEnv *env, jclass clazz) +{ + DISPLAY_DEVICE aDevice, dDevice; + int i = 0, j; + LPCTSTR aName, dName; + while(NULL != (aName = NewtScreen_getAdapterName(&aDevice, i))) { + fprintf(stderr, "*** [%d]: <%s> flags 0x%X active %d\n", i, aName, aDevice.StateFlags, ( 0 != ( aDevice.StateFlags & DISPLAY_DEVICE_ACTIVE ) ) ); + j=0; + while(NULL != (dName = NewtScreen_getMonitorName(aName, &dDevice, j, FALSE))) { + fprintf(stderr, "*** [%d][%d]: <%s> flags 0x%X active %d\n", i, j, dName, dDevice.StateFlags, ( 0 != ( dDevice.StateFlags & DISPLAY_DEVICE_ACTIVE ) ) ); + j++; + } + i++; + } +} + static HDC NewtScreen_createDisplayDC(LPCTSTR displayDeviceName) { return CreateDC("DISPLAY", displayDeviceName, NULL, NULL); } /* * Class: jogamp_newt_driver_windows_ScreenDriver - * Method: getScreenMode0 - * Signature: (II)[I + * Method: getAdapterName0 + * Signature: (I)Ljava/lang/String; */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getScreenMode0 - (JNIEnv *env, jobject obj, jint scrn_idx, jint mode_idx) +JNIEXPORT jstring JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getAdapterName0 + (JNIEnv *env, jobject obj, jint crt_idx) { DISPLAY_DEVICE device; - int prop_num = NUM_SCREEN_MODE_PROPERTIES_ALL; - LPCTSTR deviceName = NewtScreen_getDisplayDeviceName(&device, scrn_idx); - if(NULL == deviceName) { - DBG_PRINT("*** WindowsWindow: getScreenMode.getDisplayDeviceName(scrn_idx %d) -> NULL\n", scrn_idx); - return (*env)->NewIntArray(env, 0); + LPCTSTR adapterName = NewtScreen_getAdapterName(&device, crt_idx); + DBG_PRINT("*** WindowsWindow: getAdapterName(crt_idx %d) -> %s, active %d\n", crt_idx, + (NULL==adapterName?"nil":adapterName), 0 == ( device.StateFlags & DISPLAY_DEVICE_ACTIVE )); + if(NULL == adapterName) { + return NULL; } +#ifdef UNICODE + return (*env)->NewString(env, adapterName, wcslen(adapterName)); +#else + return (*env)->NewStringUTF(env, adapterName); +#endif +} + +/* + * Class: jogamp_newt_driver_windows_ScreenDriver + * Method: getActiveMonitorName0 + * Signature: (Ljava/lang/String;I)Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getActiveMonitorName0 + (JNIEnv *env, jobject obj, jstring jAdapterName, jint monitor_idx) +{ + DISPLAY_DEVICE device; + LPCTSTR monitorName; +#ifdef UNICODE + LPCTSTR adapterName = NewtCommon_GetNullTerminatedStringChars(env, jAdapterName); + monitorName = NewtScreen_getMonitorName(adapterName, &device, monitor_idx, TRUE); + DBG_PRINT("*** WindowsWindow: getMonitorName(%s, monitor_idx %d) -> %s\n", adapterName, monitor_idx, (NULL==monitorName?"nil":monitorName)); + free((void*) adapterName); +#else + LPCTSTR adapterName = (*env)->GetStringUTFChars(env, jAdapterName, NULL); + monitorName = NewtScreen_getMonitorName(adapterName, &device, monitor_idx, TRUE); + DBG_PRINT("*** WindowsWindow: getMonitorName(%s, monitor_idx %d) -> %s\n", adapterName, monitor_idx, (NULL==monitorName?"nil":monitorName)); + (*env)->ReleaseStringUTFChars(env, jAdapterName, adapterName); +#endif + if(NULL == monitorName) { + return NULL; + } +#ifdef UNICODE + return (*env)->NewString(env, monitorName, wcslen(monitorName)); +#else + return (*env)->NewStringUTF(env, monitorName); +#endif +} +/* + * Class: jogamp_newt_driver_windows_ScreenDriver + * Method: getMonitorMode0 + * Signature: (Ljava/lang/String;I)[I + */ +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getMonitorMode0 + (JNIEnv *env, jobject obj, jstring jAdapterName, jint mode_idx) +{ + DISPLAY_DEVICE device; + LPCTSTR adapterName; + { +#ifdef UNICODE + adapterName = NewtCommon_GetNullTerminatedStringChars(env, jAdapterName); +#else + adapterName = (*env)->GetStringUTFChars(env, jAdapterName, NULL); +#endif + } int devModeID; - int widthmm, heightmm; if(-1 < mode_idx) { - // only at initialization time, where index >= 0 - HDC hdc = NewtScreen_createDisplayDC(deviceName); - widthmm = GetDeviceCaps(hdc, HORZSIZE); - heightmm = GetDeviceCaps(hdc, VERTSIZE); - DeleteDC(hdc); devModeID = (int) mode_idx; - prop_num++; // add 1st extra prop, mode_idx } else { - widthmm = 0; - heightmm = 0; devModeID = ENUM_CURRENT_SETTINGS; } @@ -1283,11 +1358,18 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getScre ZeroMemory(&dm, sizeof(dm)); dm.dmSize = sizeof(dm); - if (0 == EnumDisplaySettingsEx(deviceName, devModeID, &dm, ( ENUM_CURRENT_SETTINGS == devModeID ) ? 0 : EDS_ROTATEDMODE)) { - DBG_PRINT("*** WindowsWindow: getScreenMode.EnumDisplaySettingsEx(mode_idx %d/%d) -> NULL\n", mode_idx, devModeID); + int res = EnumDisplaySettingsEx(adapterName, devModeID, &dm, ( ENUM_CURRENT_SETTINGS == devModeID ) ? 0 : EDS_ROTATEDMODE); + DBG_PRINT("*** WindowsWindow: getMonitorMode.EnumDisplaySettingsEx(%s, mode_idx %d/%d) -> %d\n", adapterName, mode_idx, devModeID, res); +#ifdef UNICODE + free((void*) adapterName); +#else + (*env)->ReleaseStringUTFChars(env, jAdapterName, adapterName); +#endif + + if (0 == res) { return (*env)->NewIntArray(env, 0); } - + // swap width and height, since Windows reflects rotated dimension, we don't if (DMDO_90 == dm.dmDisplayOrientation || DMDO_270 == dm.dmDisplayOrientation) { int tempWidth = dm.dmPelsWidth; @@ -1295,43 +1377,110 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getScre dm.dmPelsHeight = tempWidth; } - jint prop[ prop_num ]; + int flags = 0; + if( 0 != ( dm.dmDisplayFlags & DM_INTERLACED ) ) { + flags |= FLAG_INTERLACE; + } + + jint prop[ NUM_MONITOR_MODE_PROPERTIES_ALL ]; int propIndex = 0; - if( -1 < mode_idx ) { - prop[propIndex++] = mode_idx; - } - prop[propIndex++] = 0; // set later for verification of iterator + prop[propIndex++] = NUM_MONITOR_MODE_PROPERTIES_ALL; prop[propIndex++] = dm.dmPelsWidth; prop[propIndex++] = dm.dmPelsHeight; prop[propIndex++] = dm.dmBitsPerPel; - prop[propIndex++] = widthmm; - prop[propIndex++] = heightmm; - prop[propIndex++] = dm.dmDisplayFrequency; + prop[propIndex++] = dm.dmDisplayFrequency * 100; // Hz*100 + prop[propIndex++] = flags; + prop[propIndex++] = 0; // not bound to id prop[propIndex++] = NewtScreen_RotationNativeCCW2NewtCCW(env, dm.dmDisplayOrientation); - prop[propIndex - NUM_SCREEN_MODE_PROPERTIES_ALL] = ( -1 < mode_idx ) ? propIndex-1 : propIndex ; // count == NUM_SCREEN_MODE_PROPERTIES_ALL - jintArray properties = (*env)->NewIntArray(env, prop_num); + jintArray properties = (*env)->NewIntArray(env, NUM_MONITOR_MODE_PROPERTIES_ALL); if (properties == NULL) { - NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", prop_num); + NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", NUM_MONITOR_MODE_PROPERTIES_ALL); } - (*env)->SetIntArrayRegion(env, properties, 0, prop_num, prop); + (*env)->SetIntArrayRegion(env, properties, 0, NUM_MONITOR_MODE_PROPERTIES_ALL, prop); return properties; } /* * Class: jogamp_newt_driver_windows_ScreenDriver - * Method: setScreenMode0 - * Signature: (IIIIII)Z + * Method: getMonitorDevice0 + * Signature: (Ljava/lang/String;I)[I */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_setScreenMode0 - (JNIEnv *env, jobject object, jint scrn_idx, jint width, jint height, jint bits, jint rate, jint rot) +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_getMonitorDevice0 + (JNIEnv *env, jobject obj, jstring jAdapterName, jint monitor_idx) { DISPLAY_DEVICE device; - LPCTSTR deviceName = NewtScreen_getDisplayDeviceName(&device, scrn_idx); - if(NULL == deviceName) { - DBG_PRINT("*** WindowsWindow: setScreenMode.getDisplayDeviceName(scrn_idx %d) -> NULL\n", scrn_idx); + LPCTSTR adapterName; + { +#ifdef UNICODE + adapterName = NewtCommon_GetNullTerminatedStringChars(env, jAdapterName); +#else + adapterName = (*env)->GetStringUTFChars(env, jAdapterName, NULL); +#endif + } + + HDC hdc = NewtScreen_createDisplayDC(adapterName); + int widthmm = GetDeviceCaps(hdc, HORZSIZE); + int heightmm = GetDeviceCaps(hdc, VERTSIZE); + DeleteDC(hdc); + int devModeID = ENUM_CURRENT_SETTINGS; + + DEVMODE dm; + ZeroMemory(&dm, sizeof(dm)); + dm.dmSize = sizeof(dm); + + int res = EnumDisplaySettingsEx(adapterName, devModeID, &dm, 0); + DBG_PRINT("*** WindowsWindow: getMonitorDevice.EnumDisplaySettingsEx(%s, devModeID %d) -> %d\n", adapterName, devModeID, res); +#ifdef UNICODE + free((void*) adapterName); +#else + (*env)->ReleaseStringUTFChars(env, jAdapterName, adapterName); +#endif + if (0 == res) { + return (*env)->NewIntArray(env, 0); + } + + jsize propCount = MIN_MONITOR_DEVICE_PROPERTIES - 1 - NUM_MONITOR_MODE_PROPERTIES; + jint prop[ propCount ]; + int propIndex = 0; + + prop[propIndex++] = propCount; + prop[propIndex++] = monitor_idx; + prop[propIndex++] = widthmm; + prop[propIndex++] = heightmm; + prop[propIndex++] = dm.dmPosition.x; // rotated viewport + prop[propIndex++] = dm.dmPosition.y; // rotated viewport + prop[propIndex++] = dm.dmPelsWidth; // rotated viewport + prop[propIndex++] = dm.dmPelsHeight; // rotated viewport + + jintArray properties = (*env)->NewIntArray(env, propCount); + if (properties == NULL) { + NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", propCount); + } + (*env)->SetIntArrayRegion(env, properties, 0, propCount, prop); + + return properties; +} + +/* + * Class: jogamp_newt_driver_windows_ScreenDriver + * Method: setMonitorMode0 + * Signature: (IIIIIIIII)Z + */ +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_setMonitorMode0 + (JNIEnv *env, jobject object, jint monitor_idx, jint x, jint y, jint width, jint height, jint bits, jint rate, jint flags, jint rot) +{ + DISPLAY_DEVICE adapterDevice, monitorDevice; + LPCTSTR adapterName = NewtScreen_getAdapterName(&adapterDevice, monitor_idx); + if(NULL == adapterName) { + DBG_PRINT("*** WindowsWindow: setMonitorMode.getAdapterName(monitor_idx %d) -> NULL\n", monitor_idx); + return JNI_FALSE; + } + LPCTSTR monitorName = NewtScreen_getMonitorName(adapterName, &monitorDevice, 0, TRUE); + if(NULL == monitorName) { + DBG_PRINT("*** WindowsWindow: setMonitorMode.getMonitorName(monitor_idx 0) -> NULL\n"); return JNI_FALSE; } @@ -1339,10 +1488,17 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_setScree // initialize the DEVMODE structure ZeroMemory(&dm, sizeof(dm)); dm.dmSize = sizeof(dm); + if( 0 <= x && 0 <= y ) { + dm.dmPosition.x = (int)x; + dm.dmPosition.y = (int)y; + } dm.dmPelsWidth = (int)width; dm.dmPelsHeight = (int)height; dm.dmBitsPerPel = (int)bits; dm.dmDisplayFrequency = (int)rate; + if( 0 != ( flags & FLAG_INTERLACE ) ) { + dm.dmDisplayFlags |= DM_INTERLACED; + } dm.dmDisplayOrientation = NewtScreen_RotationNewtCCW2NativeCCW(env, rot); // swap width and height, since Windows reflects rotated dimension, we don't @@ -1352,9 +1508,12 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_ScreenDriver_setScree dm.dmPelsHeight = tempWidth; } - dm.dmFields = DM_DISPLAYORIENTATION | DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY; + dm.dmFields = DM_DISPLAYORIENTATION | DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY | DM_DISPLAYFLAGS; + if( 0 <= x && 0 <= y ) { + dm.dmFields |= DM_POSITION; + } - return ( DISP_CHANGE_SUCCESSFUL == ChangeDisplaySettings(&dm, 0) ) ? JNI_TRUE : JNI_FALSE ; + return ( DISP_CHANGE_SUCCESSFUL == ChangeDisplaySettingsEx(adapterName, &dm, NULL, 0, NULL) ) ? JNI_TRUE : JNI_FALSE ; } /* diff --git a/src/newt/native/X11RandR11.c b/src/newt/native/X11RandR11.c index cbf911a38..81a6726b5 100644 --- a/src/newt/native/X11RandR11.c +++ b/src/newt/native/X11RandR11.c @@ -30,10 +30,10 @@ /* * Class: jogamp_newt_driver_x11_RandR11 - * Method: getAvailableScreenModeRotations0 + * Method: getAvailableScreenRotations0 * Signature: (JI)I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR11_getAvailableScreenModeRotations0 +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR11_getAvailableScreenRotations0 (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) { Display *dpy = (Display *) (intptr_t) display; @@ -75,10 +75,10 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR11_getAvailableScre /* * Class: jogamp_newt_driver_x11_RandR11 - * Method: getNumScreenModeResolution0 + * Method: getNumScreenResolution0 * Signature: (JI)I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_RandR11_getNumScreenModeResolutions0 +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_RandR11_getNumScreenResolutions0 (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) { Display *dpy = (Display *) (intptr_t) display; @@ -90,7 +90,7 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_RandR11_getNumScreenModeResol #ifdef DBG_PERF timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td); - fprintf(stderr, "X11Screen_getNumScreenModeResolution0.1: %ld ms\n", td_ms); fflush(NULL); + fprintf(stderr, "X11Screen_getNumScreenResolution0.1: %ld ms\n", td_ms); fflush(NULL); #endif int num_sizes; @@ -98,20 +98,20 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_RandR11_getNumScreenModeResol #ifdef DBG_PERF timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td); - fprintf(stderr, "X11Screen_getNumScreenModeResolution0.2 (XRRSizes): %ld ms\n", td_ms); fflush(NULL); + fprintf(stderr, "X11Screen_getNumScreenResolution0.2 (XRRSizes): %ld ms\n", td_ms); fflush(NULL); #endif - DBG_PRINT("getNumScreenModeResolutions0: %p:%d -> %d\n", dpy, (int)scrn_idx, num_sizes); + DBG_PRINT("getNumScreenResolutions0: %p:%d -> %d\n", dpy, (int)scrn_idx, num_sizes); return num_sizes; } /* * Class: jogamp_newt_driver_x11_RandR11 - * Method: getScreenModeResolutions0 + * Method: getScreenResolutions0 * Signature: (JII)[I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR11_getScreenModeResolution0 +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR11_getScreenResolution0 (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx, jint resMode_idx) { Display *dpy = (Display *) (intptr_t) display; @@ -145,10 +145,10 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR11_getScreenModeRes /* * Class: jogamp_newt_driver_x11_RandR11 - * Method: getScreenModeRates0 + * Method: getScreenRates0 * Signature: (JII)[I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR11_getScreenModeRates0 +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR11_getScreenRates0 (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx, jint resMode_idx) { Display *dpy = (Display *) (intptr_t) display; @@ -289,36 +289,20 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_RandR11_setCurrentScreenM int num_sizes; XRRScreenSize *xrrs = XRRSizes(dpy, (int)screen_idx, &num_sizes); //get possible screen resolutions - int rot; if( 0 > resMode_idx || resMode_idx >= num_sizes ) { NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes); } - switch(rotation) { - case 0: - rot = RR_Rotate_0; - break; - case 90: - rot = RR_Rotate_90; - break; - case 180: - rot = RR_Rotate_180; - break; - case 270: - rot = RR_Rotate_270; - break; - default: - NewtCommon_throwNewRuntimeException(env, "Invalid rotation: %d", rotation); - } - DBG_PRINT("X11Screen.setCurrentScreenMode0: CHANGED TO %d: %d x %d PIXELS, %d Hz, %d degree\n", resMode_idx, xrrs[resMode_idx].width, xrrs[resMode_idx].height, (int)freq, rotation); + int xrot = NewtScreen_Degree2XRotation(env, rotation); + XRRSelectInput (dpy, root, RRScreenChangeNotifyMask); XSync(dpy, False); - XRRSetScreenConfigAndRate(dpy, conf, root, (int)resMode_idx, rot, (short)freq, CurrentTime); + XRRSetScreenConfigAndRate(dpy, conf, root, (int)resMode_idx, xrot, (short)freq, CurrentTime); XSync(dpy, False); return JNI_TRUE; diff --git a/src/newt/native/X11RandR13.c b/src/newt/native/X11RandR13.c index ea72cd35d..92c20e893 100644 --- a/src/newt/native/X11RandR13.c +++ b/src/newt/native/X11RandR13.c @@ -38,22 +38,9 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_RandR13_getScreenResources0 { Display *dpy = (Display *) (intptr_t) display; Window root = RootWindow(dpy, (int)screen_idx); -#ifdef DBG_PERF - struct timespec t0, t1, td; - long td_ms; - timespec_now(&t0); -#endif - -#ifdef DBG_PERF - timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td); - fprintf(stderr, "X11Screen_getScreenResources0.1: %ld ms\n", td_ms); fflush(NULL); -#endif - - XRRScreenResources *res = XRRGetScreenResourcesCurrent( dpy, root); -#ifdef DBG_PERF - timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td); - fprintf(stderr, "X11Screen_getScreenResources0.2 (XRRScreenResources): %ld ms\n", td_ms); fflush(NULL); -#endif + + XRRScreenResources *res = XRRGetScreenResourcesCurrent( dpy, root); // 1.3 + // XRRScreenResources *res = XRRGetScreenResources( dpy, root); // 1.2 return (jlong) (intptr_t) res; } @@ -66,48 +53,166 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_RandR13_getScreenResources0 JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_RandR13_freeScreenResources0 (JNIEnv *env, jclass clazz, jlong screenResources) { - XRRFreeScreenResources( (XRRScreenResources *) (intptr_t) screenResources ); + XRRScreenResources *resources = (XRRScreenResources *) (intptr_t) screenResources; + if( NULL != resources ) { + XRRFreeScreenResources( resources ); + } +} + +#define SAFE_STRING(s) (NULL==s?"":s) + +static void dumpOutputs(const char *prefix, Display *dpy, XRRScreenResources *resources, int noutput, RROutput * outputs) { + int i, j; + fprintf(stderr, "%s %p: Output count %d\n", prefix, resources, noutput); + for(i=0; icrtc, SAFE_STRING(xrrOutputInfo->name), xrrOutputInfo->nameLen, xrrOutputInfo->mm_width, xrrOutputInfo->mm_height, + xrrOutputInfo->ncrtc, xrrOutputInfo->nmode, xrrOutputInfo->npreferred); + for(j=0; jnmode; j++) { + fprintf(stderr, " Output[%d].Mode[%d].id %#lx\n", i, j, xrrOutputInfo->modes[j]); + } + XRRFreeOutputInfo (xrrOutputInfo); + } } -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR13_getOrigin0 - (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) +/** Returns vertical refresh rate in hertz */ +static float getVRefresh(XRRModeInfo *mode) { + float rate; + unsigned int vTotal = mode->vTotal; + + if (mode->modeFlags & RR_DoubleScan) { + /* doublescan doubles the number of lines */ + vTotal *= 2; + } + + if (mode->modeFlags & RR_Interlace) { + /* interlace splits the frame into two fields */ + /* the field rate is what is typically reported by monitors */ + vTotal /= 2; + } + + if (mode->hTotal && vTotal) { + rate = ( (float) mode->dotClock / + ( (float) mode->hTotal * (float) vTotal ) + ); + } else { + rate = 0; + } + return rate; +} + + +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_RandR13_dumpInfo0 + (JNIEnv *env, jclass clazz, jlong display, jint screen_idx, jlong screenResources) { Display * dpy = (Display *) (intptr_t) display; - Window root = RootWindow(dpy, (int)scrn_idx); + Window root = RootWindow(dpy, (int)screen_idx); + XRRScreenResources *resources = (XRRScreenResources *) (intptr_t) screenResources; int pos[] = { 0, 0 } ; + int i, j, minWidth, minHeight, maxWidth, maxHeight; - int i; - XRRScreenResources *xrrScreenResources = XRRGetScreenResources(dpy, root); - fprintf(stderr, "XRRScreenResources %p: RRCrtc crtcs %d\n", xrrScreenResources, xrrScreenResources->ncrtc); - for(i=0; incrtc; i++) { - RRCrtc crtc = xrrScreenResources->crtcs[i]; - XRRCrtcInfo *xrrCrtcInfo = XRRGetCrtcInfo (dpy, xrrScreenResources, crtc); - fprintf(stderr, "RRCrtc %d: %d/%d %dx%d\n", i, xrrCrtcInfo->x, xrrCrtcInfo->y, xrrCrtcInfo->width, xrrCrtcInfo->height); + int vs_width = DisplayWidth(dpy, screen_idx); + int vs_height = DisplayHeight(dpy, screen_idx); + int vs_width_mm = DisplayWidthMM(dpy, screen_idx); + int vs_height_mm = DisplayHeightMM(dpy, screen_idx); + fprintf(stderr, "ScreenVirtualSize: %dx%d %dx%d mm\n", vs_width, vs_height, vs_width_mm, vs_height_mm); + + XRRGetScreenSizeRange (dpy, root, &minWidth, &minHeight, &maxWidth, &maxHeight); + fprintf(stderr, "XRRGetScreenSizeRange: %dx%d .. %dx%d\n", minWidth, minHeight, maxWidth, maxHeight); + + if( NULL == resources ) { + fprintf(stderr, "XRRScreenResources NULL\n"); + return; + } + fprintf(stderr, "XRRScreenResources %p: Crtc count %d\n", resources, resources->ncrtc); + for(i=0; incrtc; i++) { + RRCrtc crtc = resources->crtcs[i]; + XRRCrtcInfo *xrrCrtcInfo = XRRGetCrtcInfo (dpy, resources, crtc); + fprintf(stderr, "Crtc[%d]: %d/%d %dx%d, rot 0x%X, mode.id %#lx\n", + i, xrrCrtcInfo->x, xrrCrtcInfo->y, xrrCrtcInfo->width, xrrCrtcInfo->height, xrrCrtcInfo->rotations, xrrCrtcInfo->mode); + for(j=0; jnoutput; j++) { + fprintf(stderr, " Crtc[%d].Output[%d].id %#lx\n", i, j, xrrCrtcInfo->outputs[j]); + } XRRFreeCrtcInfo(xrrCrtcInfo); } - jintArray jpos = (*env)->NewIntArray(env, num_rotations); - if (properties == NULL) { - NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", 2); + dumpOutputs("XRRScreenResources.outputs", dpy, resources, resources->noutput, resources->outputs); + + fprintf(stderr, "XRRScreenResources %p: Mode count %d\n", resources, resources->nmode); + for(i=0; inmode; i++) { + XRRModeInfo *mode = &resources->modes[i]; + + unsigned int dots = mode->hTotal * mode->vTotal; + float refresh = getVRefresh(mode); + fprintf(stderr, "Mode[%d, id %#lx]: %ux%u@%f, name %s\n", i, mode->id, mode->width, mode->height, refresh, SAFE_STRING(mode->name)); } - - // move from the temp structure to the java structure - (*env)->SetIntArrayRegion(env, jpos, 0, 2, pos); - return jpos; } -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR13_getAvailableScreenModeRotations0 - (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) +/* + * Class: jogamp_newt_driver_x11_RandR13 + * Method: getMonitorDeviceCount0 + * Signature: (J)I + */ +JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_RandR13_getMonitorDeviceCount0 + (JNIEnv *env, jclass clazz, jlong screenResources) +{ + XRRScreenResources *resources = (XRRScreenResources *) (intptr_t) screenResources; + return ( NULL != resources ) ? resources->ncrtc : 0; +} + +/* + * Class: jogamp_newt_driver_x11_RandR13 + * Method: getMonitorInfoHandle0 + * Signature: (JIJI)J + */ +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_RandR13_getMonitorInfoHandle0 + (JNIEnv *env, jclass clazz, jlong display, jint screen_idx, jlong screenResources, jint crt_idx) { Display *dpy = (Display *) (intptr_t) display; - Window root = RootWindow(dpy, (int)scrn_idx); - int num_rotations = 0; - Rotation cur_rotation, rotations_supported; - int rotations[4]; - int major, minor; + Window root = RootWindow(dpy, (int)screen_idx); + XRRScreenResources *resources = (XRRScreenResources *) (intptr_t) screenResources; - rotations_supported = XRRRotations (dpy, (int)scrn_idx, &cur_rotation); + if( NULL == resources || crt_idx >= resources->ncrtc ) { + return 0; + } + RRCrtc crtc = resources->crtcs[crt_idx]; + XRRCrtcInfo *xrrCrtcInfo = XRRGetCrtcInfo (dpy, resources, crtc); + return (jlong) (intptr_t) xrrCrtcInfo; +} + +/* + * Class: jogamp_newt_driver_x11_RandR13 + * Method: freeMonitorInfoHandle0 + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_RandR13_freeMonitorInfoHandle0 + (JNIEnv *env, jclass clazz, jlong monitorInfo) +{ + XRRCrtcInfo *xrrCrtcInfo = (XRRCrtcInfo *) (intptr_t) monitorInfo; + if( NULL != xrrCrtcInfo ) { + XRRFreeCrtcInfo( xrrCrtcInfo ); + } +} + +/* + * Class: jogamp_newt_driver_x11_RandR13 + * Method: getAvailableRotations0 + * Signature: (J)I + */ +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR13_getAvailableRotations0 + (JNIEnv *env, jclass clazz, jlong monitorInfo) +{ + XRRCrtcInfo *xrrCrtcInfo = (XRRCrtcInfo *) (intptr_t) monitorInfo; + if( NULL == xrrCrtcInfo ) { + return NULL; + } + Rotation rotations_supported = xrrCrtcInfo->rotations; + + int num_rotations = 0; + int rotations[4]; if(0 != (rotations_supported & RR_Rotate_0)) { rotations[num_rotations++] = 0; } @@ -120,7 +225,7 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR13_getAvailableScre if(0 != (rotations_supported & RR_Rotate_270)) { rotations[num_rotations++] = 270; } - + jintArray properties = NULL; if(num_rotations>0) { @@ -136,273 +241,275 @@ JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR13_getAvailableScre return properties; } -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_RandR13_getNumScreenModeResolutions0 - (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) +/* + * Class: jogamp_newt_driver_x11_RandR13 + * Method: getMonitorViewport0 + * Signature: (J)[I + */ +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR13_getMonitorViewport0 + (JNIEnv *env, jclass clazz, jlong monitorInfo) { - Display *dpy = (Display *) (intptr_t) display; - Window root = RootWindow(dpy, (int)scrn_idx); - - int num_sizes; - XRRScreenSize *xrrs = XRRSizes(dpy, (int)scrn_idx, &num_sizes); //get possible screen resolutions - - DBG_PRINT("getNumScreenModeResolutions0: %d\n", num_sizes); + XRRCrtcInfo *xrrCrtcInfo = (XRRCrtcInfo *) (intptr_t) monitorInfo; - int i; - XRRScreenResources *xrrScreenResources = XRRGetScreenResources(dpy, root); - fprintf(stderr, "XRRScreenResources %p: RRCrtc crtcs %d\n", xrrScreenResources, xrrScreenResources->ncrtc); - for(i=0; incrtc; i++) { - RRCrtc crtc = xrrScreenResources->crtcs[i]; - XRRCrtcInfo *xrrCrtcInfo = XRRGetCrtcInfo (dpy, xrrScreenResources, crtc); - fprintf(stderr, "RRCrtc %d: %d/%d %dx%d\n", i, xrrCrtcInfo->x, xrrCrtcInfo->y, xrrCrtcInfo->width, xrrCrtcInfo->height); - XRRFreeCrtcInfo(xrrCrtcInfo); + if( NULL == xrrCrtcInfo ) { + // n/a + return NULL; } - fprintf(stderr, "XRRScreenResources %p: XRRModeInfo modes %d\n", xrrScreenResources, xrrScreenResources->nmode); - for(i=0; inmode; i++) { - XRRModeInfo xrrModeInfo = xrrScreenResources->modes[i]; - fprintf(stderr, "XRRModeInfo %d: %dx%d, %s, %X\n", i, xrrModeInfo.width, xrrModeInfo.height, xrrModeInfo.name, xrrModeInfo.id); + + if( None == xrrCrtcInfo->mode || 0 == xrrCrtcInfo->noutput ) { + // disabled + return NULL; } - XRRFreeScreenResources(xrrScreenResources); - return num_sizes; + jsize propCount = 4; + jint prop[ propCount ]; + int propIndex = 0; + + prop[propIndex++] = xrrCrtcInfo->x; + prop[propIndex++] = xrrCrtcInfo->y; + prop[propIndex++] = xrrCrtcInfo->width; + prop[propIndex++] = xrrCrtcInfo->height; + + jintArray properties = (*env)->NewIntArray(env, propCount); + if (properties == NULL) { + NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", propCount); + } + (*env)->SetIntArrayRegion(env, properties, 0, propCount, prop); + + return properties; } /* * Class: jogamp_newt_driver_x11_RandR13 - * Method: getScreenModeResolutions0 - * Signature: (JII)[I + * Method: getMonitorMode0 + * Signature: (JI)[I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR13_getScreenModeResolution0 - (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx, jint resMode_idx) +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR13_getMonitorMode0 + (JNIEnv *env, jclass clazz, jlong screenResources, jint mode_idx) { - Display *dpy = (Display *) (intptr_t) display; - - int num_sizes; - XRRScreenSize *xrrs = XRRSizes(dpy, (int)scrn_idx, &num_sizes); //get possible screen resolutions + XRRScreenResources *resources = (XRRScreenResources *) (intptr_t) screenResources; + + if( NULL == resources || mode_idx >= resources->nmode ) { + return NULL; + } - if( 0 > resMode_idx || resMode_idx >= num_sizes ) { - NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes); + XRRModeInfo *mode = &resources->modes[mode_idx]; + unsigned int dots = mode->hTotal * mode->vTotal; + int refresh = (int) ( getVRefresh(mode) * 100.0f ); // Hz * 100 + int flags = 0; + if (mode->modeFlags & RR_Interlace) { + flags |= FLAG_INTERLACE; } - - // Fill the properties in temp jint array + if (mode->modeFlags & RR_DoubleScan) { + flags |= FLAG_DOUBLESCAN; + } + + jint prop[ NUM_MONITOR_MODE_PROPERTIES_ALL ]; int propIndex = 0; - jint prop[4]; - - prop[propIndex++] = xrrs[(int)resMode_idx].width; - prop[propIndex++] = xrrs[(int)resMode_idx].height; - prop[propIndex++] = xrrs[(int)resMode_idx].mwidth; - prop[propIndex++] = xrrs[(int)resMode_idx].mheight; - - jintArray properties = (*env)->NewIntArray(env, 4); + + prop[propIndex++] = NUM_MONITOR_MODE_PROPERTIES_ALL; + prop[propIndex++] = mode->width; + prop[propIndex++] = mode->height; + prop[propIndex++] = 32; // TODO: XRandR > 1.4 may support bpp + prop[propIndex++] = refresh; + prop[propIndex++] = flags; + prop[propIndex++] = mode->id; + prop[propIndex++] = -1; // rotation placeholder + + jintArray properties = (*env)->NewIntArray(env, NUM_MONITOR_MODE_PROPERTIES_ALL); if (properties == NULL) { - NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", 4); + NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", NUM_MONITOR_MODE_PROPERTIES_ALL); } - - // move from the temp structure to the java structure - (*env)->SetIntArrayRegion(env, properties, 0, 4, prop); + (*env)->SetIntArrayRegion(env, properties, 0, NUM_MONITOR_MODE_PROPERTIES_ALL, prop); return properties; } /* * Class: jogamp_newt_driver_x11_RandR13 - * Method: getScreenModeRates0 - * Signature: (JII)[I + * Method: getMonitorCurrentMode0 + * Signature: (JJ)[I */ -JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR13_getScreenModeRates0 - (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx, jint resMode_idx) +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR13_getMonitorCurrentMode0 + (JNIEnv *env, jclass clazz, jlong screenResources, jlong monitorInfo) { - Display *dpy = (Display *) (intptr_t) display; - - int num_sizes; - XRRScreenSize *xrrs = XRRSizes(dpy, (int)scrn_idx, &num_sizes); //get possible screen resolutions + XRRScreenResources *resources = (XRRScreenResources *) (intptr_t) screenResources; + XRRCrtcInfo *xrrCrtcInfo = (XRRCrtcInfo *) (intptr_t) monitorInfo; - if( 0 > resMode_idx || resMode_idx >= num_sizes ) { - NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes); + if( NULL == resources || NULL == xrrCrtcInfo ) { + // n/a + return NULL; } - - int num_rates; - short *rates = XRRRates(dpy, (int)scrn_idx, (int)resMode_idx, &num_rates); - - jint prop[num_rates]; + + if( None == xrrCrtcInfo->mode || 0 == xrrCrtcInfo->noutput ) { + // disabled + return NULL; + } + + int modeId = xrrCrtcInfo->mode; + XRRModeInfo *mode = NULL; int i; - for(i=0; inmode; i++) { + XRRModeInfo *imode = &resources->modes[i]; + if( imode->id == modeId ) { + mode = imode; + break; + } } - - jintArray properties = (*env)->NewIntArray(env, num_rates); + if( NULL == mode ) { + // oops .. + return NULL; + } + + unsigned int dots = mode->hTotal * mode->vTotal; + int refresh = (int) ( getVRefresh(mode) * 100.0f ); // Hz * 100 + int flags = 0; + if (mode->modeFlags & RR_Interlace) { + flags |= FLAG_INTERLACE; + } + if (mode->modeFlags & RR_DoubleScan) { + flags |= FLAG_DOUBLESCAN; + } + + jint prop[ NUM_MONITOR_MODE_PROPERTIES_ALL ]; + int propIndex = 0; + + prop[propIndex++] = NUM_MONITOR_MODE_PROPERTIES_ALL; + prop[propIndex++] = mode->width; + prop[propIndex++] = mode->height; + prop[propIndex++] = 32; // TODO: XRandR > 1.4 may support bpp + prop[propIndex++] = refresh; + prop[propIndex++] = flags; + prop[propIndex++] = mode->id; + prop[propIndex++] = NewtScreen_XRotation2Degree(env, xrrCrtcInfo->rotation); + + jintArray properties = (*env)->NewIntArray(env, NUM_MONITOR_MODE_PROPERTIES_ALL); if (properties == NULL) { - NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", num_rates); + NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", NUM_MONITOR_MODE_PROPERTIES_ALL); } - - // move from the temp structure to the java structure - (*env)->SetIntArrayRegion(env, properties, 0, num_rates, prop); + (*env)->SetIntArrayRegion(env, properties, 0, NUM_MONITOR_MODE_PROPERTIES_ALL, prop); return properties; } /* * Class: jogamp_newt_driver_x11_RandR13 - * Method: getCurrentScreenRate0 - * Signature: (JI)I + * Method: getMonitorDevice0 + * Signature: (JJJJ)[I */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_RandR13_getCurrentScreenRate0 - (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) +JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_RandR13_getMonitorDevice0 + (JNIEnv *env, jclass clazz, jlong display, jlong screenResources, jlong monitorInfo, jint crt_idx) { - Display *dpy = (Display *) (intptr_t) display; - Window root = RootWindow(dpy, (int)scrn_idx); - - // get current resolutions and frequencies - XRRScreenConfiguration *conf = XRRGetScreenInfo(dpy, root); - short original_rate = XRRConfigCurrentRate(conf); + Display * dpy = (Display *) (intptr_t) display; + XRRScreenResources *resources = (XRRScreenResources *) (intptr_t) screenResources; + XRRCrtcInfo *xrrCrtcInfo = (XRRCrtcInfo *) (intptr_t) monitorInfo; - //free - XRRFreeScreenConfigInfo(conf); - - DBG_PRINT("getCurrentScreenRate0: %d\n", (int)original_rate); + if( NULL == resources || NULL == xrrCrtcInfo || crt_idx >= resources->ncrtc ) { + // n/a + return NULL; + } - return (jint) original_rate; -} + if( None == xrrCrtcInfo->mode || 0 == xrrCrtcInfo->noutput ) { + // disabled + return NULL; + } -/* - * Class: jogamp_newt_driver_x11_RandR13 - * Method: getCurrentScreenRotation0 - * Signature: (JI)I - */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_RandR13_getCurrentScreenRotation0 - (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) -{ - Display *dpy = (Display *) (intptr_t) display; - Window root = RootWindow(dpy, (int)scrn_idx); - - //get current resolutions and frequencies - XRRScreenConfiguration *conf = XRRGetScreenInfo(dpy, root); - - Rotation rotation; - XRRConfigCurrentConfiguration(conf, &rotation); + RROutput output = xrrCrtcInfo->outputs[0]; + XRROutputInfo * xrrOutputInfo = XRRGetOutputInfo (dpy, resources, output); + int numModes = xrrOutputInfo->nmode; - //free - XRRFreeScreenConfigInfo(conf); - - return NewtScreen_XRotation2Degree(env, rotation); -} + jsize propCount = MIN_MONITOR_DEVICE_PROPERTIES - 1 + numModes; + jint prop[ propCount ]; + int propIndex = 0; + prop[propIndex++] = propCount; + prop[propIndex++] = crt_idx; + prop[propIndex++] = xrrOutputInfo->mm_width; + prop[propIndex++] = xrrOutputInfo->mm_height; + prop[propIndex++] = xrrCrtcInfo->x; + prop[propIndex++] = xrrCrtcInfo->y; + prop[propIndex++] = xrrCrtcInfo->width; + prop[propIndex++] = xrrCrtcInfo->height; + prop[propIndex++] = xrrCrtcInfo->mode; // current mode id + prop[propIndex++] = NewtScreen_XRotation2Degree(env, xrrCrtcInfo->rotation); + int i; + for(i=0; imodes[i]; + } -/* - * Class: jogamp_newt_driver_x11_RandR13 - * Method: getCurrentScreenResolutionIndex0 - * Signature: (JI)I - */ -JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_RandR13_getCurrentScreenResolutionIndex0 - (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) -{ - Display *dpy = (Display *) (intptr_t) display; - Window root = RootWindow(dpy, (int)scrn_idx); - - // get current resolutions and frequency configuration - XRRScreenConfiguration *conf = XRRGetScreenInfo(dpy, root); - short original_rate = XRRConfigCurrentRate(conf); - - Rotation original_rotation; - SizeID original_size_id = XRRConfigCurrentConfiguration(conf, &original_rotation); - - //free - XRRFreeScreenConfigInfo(conf); - - DBG_PRINT("getCurrentScreenResolutionIndex0: %d\n", (int)original_size_id); - return (jint)original_size_id; + XRRFreeOutputInfo (xrrOutputInfo); + + jintArray properties = (*env)->NewIntArray(env, propCount); + if (properties == NULL) { + NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", propCount); + } + (*env)->SetIntArrayRegion(env, properties, 0, propCount, prop); + + return properties; } /* * Class: jogamp_newt_driver_x11_RandR13 - * Method: setCurrentScreenModeStart0 - * Signature: (JIIII)Z + * Method: setMonitorMode0 + * Signature: (JJJIIIII)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_RandR13_setCurrentScreenModeStart0 - (JNIEnv *env, jclass clazz, jlong display, jint screen_idx, jint resMode_idx, jint freq, jint rotation) +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_RandR13_setMonitorMode0 + (JNIEnv *env, jclass clazz, jlong display, jlong screenResources, jlong monitorInfo, jint crt_idx, jint modeId, jint rotation, jint x, jint y) { - Display *dpy = (Display *) (intptr_t) display; - Window root = RootWindow(dpy, (int)screen_idx); + Display * dpy = (Display *) (intptr_t) display; + XRRScreenResources *resources = (XRRScreenResources *) (intptr_t) screenResources; + XRRCrtcInfo *xrrCrtcInfo = (XRRCrtcInfo *) (intptr_t) monitorInfo; + jboolean res = JNI_FALSE; - int num_sizes; - XRRScreenSize *xrrs = XRRSizes(dpy, (int)screen_idx, &num_sizes); //get possible screen resolutions - XRRScreenConfiguration *conf; - int rot; - - if( 0 > resMode_idx || resMode_idx >= num_sizes ) { - NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes); + if( NULL == resources || NULL == xrrCrtcInfo || crt_idx >= resources->ncrtc ) { + // n/a + return res; } - conf = XRRGetScreenInfo(dpy, root); - - rot = int NewtScreen_Degree2XRotation(env, rotation); - - DBG_PRINT("X11Screen.setCurrentScreenMode0: CHANGED TO %d: %d x %d PIXELS, %d Hz, %d degree\n", - resMode_idx, xrrs[resMode_idx].width, xrrs[resMode_idx].height, (int)freq, rotation); + if( None == xrrCrtcInfo->mode || 0 == xrrCrtcInfo->noutput ) { + // disabled + return res; + } - XRRSelectInput (dpy, root, RRScreenChangeNotifyMask); + if( 0 >= modeId ) { + // oops .. + return res; + } - XSync(dpy, False); - XRRSetScreenConfigAndRate(dpy, conf, root, (int)resMode_idx, rot, (short)freq, CurrentTime); - XSync(dpy, False); + if( 0 > x || 0 > y ) { + x = xrrCrtcInfo->x; + y = xrrCrtcInfo->y; + } - //free - XRRFreeScreenConfigInfo(conf); - XSync(dpy, False); + Status status = XRRSetCrtcConfig( dpy, resources, resources->crtcs[crt_idx], CurrentTime, + x, y, modeId, NewtScreen_Degree2XRotation(env, rotation), + xrrCrtcInfo->outputs, xrrCrtcInfo->noutput ); + res = status == RRSetConfigSuccess; - return JNI_TRUE; + return res; } /* * Class: jogamp_newt_driver_x11_RandR13 - * Method: setCurrentScreenModePollEnd0 - * Signature: (J)Z + * Method: setScreenViewport0 + * Signature: (JIJIIII)Z */ -JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_RandR13_setCurrentScreenModePollEnd0 - (JNIEnv *env, jclass clazz, jlong display, jint screen_idx, jint resMode_idx, jint freq, jint rotation) +JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_RandR13_setScreenViewport0 + (JNIEnv *env, jclass clazz, jlong display, jint screen_idx, jlong screenResources, jint x, jint y, jint width, jint height) { - Display *dpy = (Display *) (intptr_t) display; - int randr_event_base, randr_error_base; - XEvent evt; - XRRScreenChangeNotifyEvent * scn_event = (XRRScreenChangeNotifyEvent *) &evt; + Display * dpy = (Display *) (intptr_t) display; + Window root = RootWindow(dpy, (int)screen_idx); + XRRScreenResources *resources = (XRRScreenResources *) (intptr_t) screenResources; + jboolean res = JNI_FALSE; - int num_sizes; - XRRScreenSize *xrrs = XRRSizes(dpy, (int)screen_idx, &num_sizes); //get possible screen resolutions - XRRScreenConfiguration *conf; - - if( 0 > resMode_idx || resMode_idx >= num_sizes ) { - NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes); + if( NULL == resources ) { + // n/a + return JNI_FALSE; } - XRRQueryExtension(dpy, &randr_event_base, &randr_error_base); - - int done = 0; - int rot; - do { - if ( 0 >= XEventsQueued(dpy, QueuedAfterFlush) ) { - return; - } - XNextEvent(dpy, &evt); - - switch (evt.type - randr_event_base) { - case RRScreenChangeNotify: - rot = NewtScreen_XRotation2Degree(env, (int)scn_event->rotation); - DBG_PRINT( "XRANDR: event . RRScreenChangeNotify call %p (root %p) resIdx %d rot %d %dx%d\n", - (void*)scn_event->window, (void*)scn_event->root, - (int)scn_event->size_index, rot, - scn_event->width, scn_event->height); - // done = scn_event->size_index == resMode_idx; // not reliable .. - done = rot == rotation && - scn_event->width == xrrs[resMode_idx].width && - scn_event->height == xrrs[resMode_idx].height; - break; - default: - DBG_PRINT("RANDR: event . unhandled %d 0x%X call %p\n", (int)evt.type, (int)evt.type, (void*)evt.xany.window); - } - XRRUpdateConfiguration(&evt); - } while(!done); - - XSync(dpy, False); - + XRRSetScreenSize (dpy, root, width, height, DisplayWidthMM(dpy, screen_idx), DisplayHeightMM(dpy, screen_idx)); + return JNI_TRUE; } + diff --git a/src/newt/native/X11Screen.c b/src/newt/native/X11Screen.c index 3d4b2a26c..152a092c9 100644 --- a/src/newt/native/X11Screen.c +++ b/src/newt/native/X11Screen.c @@ -75,22 +75,41 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_ScreenDriver_getHeight0 } int NewtScreen_XRotation2Degree(JNIEnv *env, int xrotation) { - int rot; + int degree; if(xrotation == RR_Rotate_0) { - rot = 0; + degree = 0; } else if(xrotation == RR_Rotate_90) { - rot = 90; + degree = 90; } else if(xrotation == RR_Rotate_180) { - rot = 180; + degree = 180; } else if(xrotation == RR_Rotate_270) { - rot = 270; + degree = 270; } else { NewtCommon_throwNewRuntimeException(env, "invalid native rotation: %d", xrotation); } - return rot; + return degree; +} + +int NewtScreen_Degree2XRotation(JNIEnv *env, int degree) { + int xrot; + if(degree == 0) { + xrot = RR_Rotate_0; + } + else if(degree == 90) { + xrot = RR_Rotate_90; + } + else if(degree == 180) { + xrot = RR_Rotate_180; + } + else if(degree == 270) { + xrot = RR_Rotate_270; + } else { + NewtCommon_throwNewRuntimeException(env, "invalid degree: %d", degree); + } + return xrot; } /* diff --git a/src/newt/native/X11Screen.h b/src/newt/native/X11Screen.h index 1a1440054..c81ee05d5 100644 --- a/src/newt/native/X11Screen.h +++ b/src/newt/native/X11Screen.h @@ -33,5 +33,6 @@ #include "X11Common.h" int NewtScreen_XRotation2Degree(JNIEnv *env, int xrotation); +int NewtScreen_Degree2XRotation(JNIEnv *env, int degree); #endif /* _X11SCREEN_H */ diff --git a/src/newt/native/X11Window.c b/src/newt/native/X11Window.c index 9e96169f5..6c5a127b6 100644 --- a/src/newt/native/X11Window.c +++ b/src/newt/native/X11Window.c @@ -438,7 +438,7 @@ Status NewtWindows_updateInsets(JNIEnv *env, jobject jwindow, Display *dpy, Wind return 0; // Error } -static void NewtWindows_requestFocus (JNIEnv *env, jobject window, Display *dpy, Window w, jboolean force) { +static void NewtWindows_requestFocus (Display *dpy, Window w, Bool force) { XWindowAttributes xwa; Window focus_return; int revert_to_return; @@ -447,7 +447,7 @@ static void NewtWindows_requestFocus (JNIEnv *env, jobject window, Display *dpy, XGetInputFocus(dpy, &focus_return, &revert_to_return); DBG_PRINT( "X11: requestFocus dpy %p,win %p, force %d, hasFocus %d\n", dpy, (void*)w, force, focus_return==w); - if( JNI_TRUE==force || focus_return!=w) { + if( True==force || focus_return!=w) { DBG_PRINT( "X11: XRaiseWindow dpy %p, win %p\n", dpy, (void*)w); XRaiseWindow(dpy, w); NewtWindows_setCWAbove(dpy, w); @@ -743,7 +743,9 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_reconfigureWindo Bool tempInvisible = ( TST_FLAG_CHANGE_FULLSCREEN(flags) || TST_FLAG_CHANGE_PARENTING(flags) ) && isVisible ; int fsEWMHFlags = 0; if( TST_FLAG_CHANGE_FULLSCREEN(flags) ) { - fsEWMHFlags |= _NET_WM_FULLSCREEN; + if( !TST_FLAG_IS_FULLSCREEN_SPAN(flags) ) { // doesn't work w/ spanning across monitors + fsEWMHFlags |= _NET_WM_FULLSCREEN; + } if( TST_FLAG_IS_FULLSCREEN(flags) ) { if( TST_FLAG_IS_ALWAYSONTOP(flags) ) { fsEWMHFlags |= _NET_WM_ABOVE; // fs on, above on @@ -756,12 +758,12 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_reconfigureWindo fsEWMHFlags |= _NET_WM_ABOVE; // toggle above } - DBG_PRINT( "X11: reconfigureWindow0 dpy %p, scrn %d, parent %p/%p, win %p, %d/%d %dx%d, parentChange %d, hasParent %d, decorationChange %d, undecorated %d, fullscreenChange %d, fullscreen %d, alwaysOnTopChange %d, alwaysOnTop %d, visibleChange %d, visible %d, tempInvisible %d, fsEWMHFlags %d\n", + DBG_PRINT( "X11: reconfigureWindow0 dpy %p, scrn %d, parent %p/%p, win %p, %d/%d %dx%d, parentChange %d, hasParent %d, decorationChange %d, undecorated %d, fullscreenChange %d, fullscreen %d (span %d), alwaysOnTopChange %d, alwaysOnTop %d, visibleChange %d, visible %d, tempInvisible %d, fsEWMHFlags %d\n", (void*)dpy, screen_index, (void*) jparent, (void*)parent, (void*)w, x, y, width, height, TST_FLAG_CHANGE_PARENTING(flags), TST_FLAG_HAS_PARENT(flags), TST_FLAG_CHANGE_DECORATION(flags), TST_FLAG_IS_UNDECORATED(flags), - TST_FLAG_CHANGE_FULLSCREEN(flags), TST_FLAG_IS_FULLSCREEN(flags), + TST_FLAG_CHANGE_FULLSCREEN(flags), TST_FLAG_IS_FULLSCREEN(flags), TST_FLAG_IS_FULLSCREEN_SPAN(flags), TST_FLAG_CHANGE_ALWAYSONTOP(flags), TST_FLAG_IS_ALWAYSONTOP(flags), TST_FLAG_CHANGE_VISIBILITY(flags), TST_FLAG_IS_VISIBLE(flags), tempInvisible, fsEWMHFlags); @@ -769,9 +771,13 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_reconfigureWindo // However, we have to consider other cases like reparenting and WM which don't support it. if( fsEWMHFlags && !TST_FLAG_CHANGE_PARENTING(flags) && isVisible && + !TST_FLAG_IS_FULLSCREEN_SPAN(flags) && ( TST_FLAG_CHANGE_FULLSCREEN(flags) || TST_FLAG_CHANGE_ALWAYSONTOP(flags) ) ) { Bool enable = TST_FLAG_CHANGE_FULLSCREEN(flags) ? TST_FLAG_IS_FULLSCREEN(flags) : TST_FLAG_IS_ALWAYSONTOP(flags) ; if( NewtWindows_setFullscreenEWMH(dpy, root, w, fsEWMHFlags, isVisible, enable) ) { + if ( TST_FLAG_CHANGE_FULLSCREEN(flags) && !TST_FLAG_IS_FULLSCREEN(flags) ) { // FS off - restore decoration + NewtWindows_setDecorations (dpy, w, TST_FLAG_IS_UNDECORATED(flags) ? False : True); + } #ifdef FS_GRAB_KEYBOARD if(TST_FLAG_CHANGE_FULLSCREEN(flags)) { if(TST_FLAG_IS_FULLSCREEN(flags)) { @@ -866,7 +872,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_reconfigureWindo JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_requestFocus0 (JNIEnv *env, jobject obj, jlong display, jlong window, jboolean force) { - NewtWindows_requestFocus ( env, obj, (Display *) (intptr_t) display, (Window)window, force ) ; + NewtWindows_requestFocus ( (Display *) (intptr_t) display, (Window)window, JNI_TRUE==force?True:False ) ; } /* diff --git a/src/test/com/jogamp/opengl/test/android/NEWTElektronActivity.java b/src/test/com/jogamp/opengl/test/android/NEWTElektronActivity.java index 0dead125a..88cd9a719 100644 --- a/src/test/com/jogamp/opengl/test/android/NEWTElektronActivity.java +++ b/src/test/com/jogamp/opengl/test/android/NEWTElektronActivity.java @@ -32,8 +32,8 @@ import javax.media.opengl.GLProfile; import jogamp.newt.driver.android.NewtBaseActivity; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.event.ScreenModeListener; +import com.jogamp.newt.event.MonitorEvent; +import com.jogamp.newt.event.MonitorModeListener; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.jogl.demos.es2.ElektronenMultiplizierer; @@ -58,11 +58,13 @@ public class NEWTElektronActivity extends NewtBaseActivity { setContentView(getWindow(), glWindow); glWindow.addGLEventListener(new ElektronenMultiplizierer()); - glWindow.getScreen().addScreenModeListener(new ScreenModeListener() { - public void screenModeChangeNotify(ScreenMode sm) { } - public void screenModeChanged(ScreenMode sm, boolean success) { - System.err.println("ScreenMode Changed: "+sm); - } + glWindow.getScreen().addMonitorModeListener(new MonitorModeListener() { + @Override + public void monitorModeChangeNotify(MonitorEvent me) { } + @Override + public void monitorModeChanged(MonitorEvent me, boolean success) { + System.err.println("MonitorMode Changed (success "+success+"): "+me); + } }); glWindow.setVisible(true); Animator animator = new Animator(glWindow); diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES1Activity.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES1Activity.java index c020413cf..f10cfc11f 100644 --- a/src/test/com/jogamp/opengl/test/android/NEWTGearsES1Activity.java +++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES1Activity.java @@ -32,8 +32,8 @@ import javax.media.opengl.GLProfile; import jogamp.newt.driver.android.NewtBaseActivity; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.event.ScreenModeListener; +import com.jogamp.newt.event.MonitorEvent; +import com.jogamp.newt.event.MonitorModeListener; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.jogl.demos.es1.GearsES1; @@ -63,11 +63,13 @@ public class NEWTGearsES1Activity extends NewtBaseActivity { setContentView(getWindow(), glWindow); glWindow.addGLEventListener(new GearsES1(-1)); - glWindow.getScreen().addScreenModeListener(new ScreenModeListener() { - public void screenModeChangeNotify(ScreenMode sm) { } - public void screenModeChanged(ScreenMode sm, boolean success) { - System.err.println("ScreenMode Changed: "+sm); - } + glWindow.getScreen().addMonitorModeListener(new MonitorModeListener() { + @Override + public void monitorModeChangeNotify(MonitorEvent me) { } + @Override + public void monitorModeChanged(MonitorEvent me, boolean success) { + System.err.println("MonitorMode Changed (success "+success+"): "+me); + } }); glWindow.setVisible(true); Animator animator = new Animator(glWindow); diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java index 542912c08..2e9774565 100644 --- a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java +++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java @@ -36,10 +36,10 @@ import javax.media.opengl.GLProfile; import jogamp.newt.driver.android.NewtBaseActivity; -import com.jogamp.newt.ScreenMode; +import com.jogamp.newt.event.MonitorEvent; import com.jogamp.newt.event.MouseAdapter; import com.jogamp.newt.event.MouseEvent; -import com.jogamp.newt.event.ScreenModeListener; +import com.jogamp.newt.event.MonitorModeListener; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; @@ -75,11 +75,13 @@ public class NEWTGearsES2Activity extends NewtBaseActivity { GearsES2 demo = new GearsES2(-1); // demo.enableAndroidTrace(true); glWindow.addGLEventListener(demo); - glWindow.getScreen().addScreenModeListener(new ScreenModeListener() { - public void screenModeChangeNotify(ScreenMode sm) { } - public void screenModeChanged(ScreenMode sm, boolean success) { - System.err.println("ScreenMode Changed: "+sm); - } + glWindow.getScreen().addMonitorModeListener(new MonitorModeListener() { + @Override + public void monitorModeChangeNotify(MonitorEvent me) { } + @Override + public void monitorModeChanged(MonitorEvent me, boolean success) { + System.err.println("MonitorMode Changed (success "+success+"): "+me); + } }); if( null != System.getProperty(forceKillProcessTest) ) { Log.d(TAG, "forceKillProcessTest"); diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2ActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2ActivityLauncher.java index 5e7a5c489..c87e66189 100644 --- a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2ActivityLauncher.java +++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2ActivityLauncher.java @@ -57,6 +57,7 @@ public class NEWTGearsES2ActivityLauncher extends LauncherUtil.BaseActivityLaunc // props.setProperty("jogl.debug.DebugGL", "true"); // props.setProperty("jogl.debug.TraceGL", "true"); // props.setProperty("newt.debug", "all"); + props.setProperty("newt.debug.Screen", "true"); props.setProperty("newt.debug.Window", "true"); props.setProperty("newt.debug.Window.MouseEvent", "true"); props.setProperty("newt.debug.Window.KeyEvent", "true"); diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2TransActivity.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2TransActivity.java index 18c3cb042..98e6b7c5f 100644 --- a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2TransActivity.java +++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2TransActivity.java @@ -34,8 +34,8 @@ import jogamp.newt.driver.android.NewtBaseActivity; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.event.ScreenModeListener; +import com.jogamp.newt.event.MonitorEvent; +import com.jogamp.newt.event.MonitorModeListener; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; @@ -65,11 +65,13 @@ public class NEWTGearsES2TransActivity extends NewtBaseActivity { setContentView(getWindow(), glWindow); glWindow.addGLEventListener(new GearsES2(-1)); - glWindow.getScreen().addScreenModeListener(new ScreenModeListener() { - public void screenModeChangeNotify(ScreenMode sm) { } - public void screenModeChanged(ScreenMode sm, boolean success) { - System.err.println("ScreenMode Changed: "+sm); - } + glWindow.getScreen().addMonitorModeListener(new MonitorModeListener() { + @Override + public void monitorModeChangeNotify(MonitorEvent me) { } + @Override + public void monitorModeChanged(MonitorEvent me, boolean success) { + System.err.println("MonitorMode Changed (success "+success+"): "+me); + } }); Animator animator = new Animator(glWindow); // glWindow.setSkipContextReleaseThread(animator.getThread()); diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivity.java b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivity.java index bbd4f9f20..42db9d8dd 100644 --- a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivity.java +++ b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivity.java @@ -32,8 +32,8 @@ import javax.media.opengl.GLProfile; import jogamp.newt.driver.android.NewtBaseActivity; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.event.ScreenModeListener; +import com.jogamp.newt.event.MonitorEvent; +import com.jogamp.newt.event.MonitorModeListener; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.graph.demos.GPUUISceneGLListener0A; @@ -61,11 +61,13 @@ public class NEWTGraphUI1pActivity extends NewtBaseActivity { setContentView(getWindow(), glWindow); glWindow.addGLEventListener(new GPUUISceneGLListener0A(0)); - glWindow.getScreen().addScreenModeListener(new ScreenModeListener() { - public void screenModeChangeNotify(ScreenMode sm) { } - public void screenModeChanged(ScreenMode sm, boolean success) { - System.err.println("ScreenMode Changed: "+sm); - } + glWindow.getScreen().addMonitorModeListener(new MonitorModeListener() { + @Override + public void monitorModeChangeNotify(MonitorEvent me) { } + @Override + public void monitorModeChanged(MonitorEvent me, boolean success) { + System.err.println("MonitorMode Changed (success "+success+"): "+me); + } }); glWindow.setVisible(true); Animator animator = new Animator(glWindow); diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI2pActivity.java b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI2pActivity.java index 20ba3f484..c68de95cc 100644 --- a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI2pActivity.java +++ b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI2pActivity.java @@ -33,8 +33,8 @@ import javax.media.opengl.GLProfile; import jogamp.newt.driver.android.NewtBaseActivity; import com.jogamp.graph.curve.Region; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.event.ScreenModeListener; +import com.jogamp.newt.event.MonitorEvent; +import com.jogamp.newt.event.MonitorModeListener; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.graph.demos.GPUUISceneGLListener0A; @@ -62,11 +62,13 @@ public class NEWTGraphUI2pActivity extends NewtBaseActivity { setContentView(getWindow(), glWindow); glWindow.addGLEventListener(new GPUUISceneGLListener0A(Region.VBAA_RENDERING_BIT)); - glWindow.getScreen().addScreenModeListener(new ScreenModeListener() { - public void screenModeChangeNotify(ScreenMode sm) { } - public void screenModeChanged(ScreenMode sm, boolean success) { - System.err.println("ScreenMode Changed: "+sm); - } + glWindow.getScreen().addMonitorModeListener(new MonitorModeListener() { + @Override + public void monitorModeChangeNotify(MonitorEvent me) { } + @Override + public void monitorModeChanged(MonitorEvent me, boolean success) { + System.err.println("MonitorMode Changed (success "+success+"): "+me); + } }); glWindow.setVisible(true); Animator animator = new Animator(glWindow); diff --git a/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES1Activity.java b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES1Activity.java index 06ce75ac5..08fbf643d 100644 --- a/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES1Activity.java +++ b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES1Activity.java @@ -32,8 +32,8 @@ import javax.media.opengl.GLProfile; import jogamp.newt.driver.android.NewtBaseActivity; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.event.ScreenModeListener; +import com.jogamp.newt.event.MonitorEvent; +import com.jogamp.newt.event.MonitorModeListener; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.jogl.demos.es1.RedSquareES1; @@ -57,11 +57,13 @@ public class NEWTRedSquareES1Activity extends NewtBaseActivity { setContentView(getWindow(), glWindow); glWindow.addGLEventListener(new RedSquareES1(-1)); - glWindow.getScreen().addScreenModeListener(new ScreenModeListener() { - public void screenModeChangeNotify(ScreenMode sm) { } - public void screenModeChanged(ScreenMode sm, boolean success) { - System.err.println("ScreenMode Changed: "+sm); - } + glWindow.getScreen().addMonitorModeListener(new MonitorModeListener() { + @Override + public void monitorModeChangeNotify(MonitorEvent me) { } + @Override + public void monitorModeChanged(MonitorEvent me, boolean success) { + System.err.println("MonitorMode Changed (success "+success+"): "+me); + } }); glWindow.setVisible(true); Animator animator = new Animator(glWindow); diff --git a/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES2Activity.java b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES2Activity.java index 02e2d8f01..cefdd842b 100644 --- a/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES2Activity.java +++ b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES2Activity.java @@ -32,8 +32,8 @@ import javax.media.opengl.GLProfile; import jogamp.newt.driver.android.NewtBaseActivity; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.event.ScreenModeListener; +import com.jogamp.newt.event.MonitorEvent; +import com.jogamp.newt.event.MonitorModeListener; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.jogl.demos.es2.RedSquareES2; @@ -62,11 +62,13 @@ public class NEWTRedSquareES2Activity extends NewtBaseActivity { final RedSquareES2 demo = new RedSquareES2(-1); // demo.enableAndroidTrace(true); glWindow.addGLEventListener(demo); - glWindow.getScreen().addScreenModeListener(new ScreenModeListener() { - public void screenModeChangeNotify(ScreenMode sm) { } - public void screenModeChanged(ScreenMode sm, boolean success) { - System.err.println("ScreenMode Changed: "+sm); - } + glWindow.getScreen().addMonitorModeListener(new MonitorModeListener() { + @Override + public void monitorModeChangeNotify(MonitorEvent me) { } + @Override + public void monitorModeChanged(MonitorEvent me, boolean success) { + System.err.println("MonitorMode Changed (success "+success+"): "+me); + } }); Animator animator = new Animator(glWindow); // animator.setRunAsFastAsPossible(true); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java index 50f759079..4c6cae501 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java @@ -163,13 +163,25 @@ public class TestGearsES2NEWT extends UITestCase { }); glWindow.addKeyListener(new KeyAdapter() { - public void keyTyped(KeyEvent e) { + @Override + public void keyPressed(final KeyEvent e) { + if( e.isAutoRepeat() ) { + return; + } if(e.getKeyChar()=='f') { new Thread() { public void run() { final Thread t = glWindow.setExclusiveContextThread(null); System.err.println("[set fullscreen pre]: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", f "+glWindow.isFullscreen()+", a "+glWindow.isAlwaysOnTop()+", "+glWindow.getInsets()); - glWindow.setFullscreen(!glWindow.isFullscreen()); + if( glWindow.isFullscreen() ) { + glWindow.setFullscreen( false ); + } else { + if( e.isAltDown() ) { + glWindow.setFullscreen( null ); + } else { + glWindow.setFullscreen( true ); + } + } System.err.println("[set fullscreen post]: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", f "+glWindow.isFullscreen()+", a "+glWindow.isAlwaysOnTop()+", "+glWindow.getInsets()); glWindow.setExclusiveContextThread(t); } }.start(); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestRulerNEWT01.java b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestRulerNEWT01.java index 98620e0c1..90d4a9c1f 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestRulerNEWT01.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestRulerNEWT01.java @@ -28,8 +28,8 @@ package com.jogamp.opengl.test.junit.jogl.glsl; import com.jogamp.common.nio.Buffers; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.util.MonitorMode; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.MonitorMode; import com.jogamp.opengl.util.GLArrayDataServer; import com.jogamp.opengl.util.PMVMatrix; import com.jogamp.opengl.util.glsl.ShaderCode; @@ -109,11 +109,13 @@ public class TestRulerNEWT01 extends UITestCase { Assert.assertNotNull(winctx); Assert.assertNotNull(winctx.window); Assert.assertNotNull(winctx.window.getScreen()); - ScreenMode sm = winctx.window.getScreen().getCurrentScreenMode(); - Assert.assertNotNull(sm); - System.err.println(sm); - final MonitorMode mmode = sm.getMonitorMode(); - final DimensionImmutable sdim = mmode.getScreenSizeMM(); + final MonitorDevice monitor = winctx.window.getMainMonitor(); + Assert.assertNotNull(monitor); + System.err.println(monitor); + final MonitorMode mmode = monitor.getCurrentMode(); + Assert.assertNotNull(mmode); + System.err.println(mmode); + final DimensionImmutable sdim = monitor.getSizeMM(); final DimensionImmutable spix = mmode.getSurfaceSize().getResolution(); final GLUniformData rulerPixFreq = new GLUniformData("gcu_RulerPixFreq", 2, Buffers.newDirectFloatBuffer(2)); final FloatBuffer rulerPixFreqV = (FloatBuffer) rulerPixFreq.getBuffer(); diff --git a/src/test/com/jogamp/opengl/test/junit/newt/ManualScreenMode03NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/ManualScreenMode03NEWT.java index 29ec443f7..a7b65545a 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/ManualScreenMode03NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/ManualScreenMode03NEWT.java @@ -35,11 +35,12 @@ import javax.media.opengl.GLProfile; import com.jogamp.opengl.util.Animator; import com.jogamp.newt.Display; +import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; -import com.jogamp.newt.ScreenMode; +import com.jogamp.newt.MonitorMode; import com.jogamp.newt.opengl.GLWindow; -import com.jogamp.newt.util.ScreenModeUtil; +import com.jogamp.newt.util.MonitorModeUtil; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; import com.jogamp.opengl.test.junit.util.UITestCase; import java.util.List; @@ -72,8 +73,8 @@ public class ManualScreenMode03NEWT extends UITestCase { Screen screen = NewtFactory.createScreen(display, 0); // screen 0 GLWindow window = createWindow(screen, caps, width, height, true /* onscreen */, false /* undecorated */); - List screenModes = screen.getScreenModes(); - if(null==screenModes) { + List monitorModes = screen.getMonitorModes(); + if(null==monitorModes) { // no support .. System.err.println("Your platform has no ScreenMode change support, sorry"); return; @@ -81,18 +82,21 @@ public class ManualScreenMode03NEWT extends UITestCase { Animator animator = new Animator(window); animator.start(); - ScreenMode smCurrent = screen.getCurrentScreenMode(); - ScreenMode smOrig = screen.getOriginalScreenMode(); - System.err.println("[0] current/orig: "+smCurrent); + MonitorDevice monitor = window.getMainMonitor(); + MonitorMode mmCurrent = monitor.queryCurrentMode(); + MonitorMode mmOrig = monitor.getOriginalMode(); + System.err.println("[0] orig : "+mmOrig); + System.err.println("[0] current: "+mmCurrent); - screenModes = ScreenModeUtil.filterByRate(screenModes, smOrig.getMonitorMode().getRefreshRate()); - screenModes = ScreenModeUtil.filterByRotation(screenModes, 0); - screenModes = ScreenModeUtil.filterByResolution(screenModes, new Dimension(801, 601)); - screenModes = ScreenModeUtil.getHighestAvailableBpp(screenModes); + monitorModes = MonitorModeUtil.filterByFlags(monitorModes, 0); // no interlace, double-scan etc + monitorModes = MonitorModeUtil.filterByRotation(monitorModes, 0); + monitorModes = MonitorModeUtil.filterByRate(monitorModes, mmOrig.getRefreshRate()); + monitorModes = MonitorModeUtil.filterByResolution(monitorModes, new Dimension(801, 601)); + monitorModes = MonitorModeUtil.getHighestAvailableBpp(monitorModes); - ScreenMode sm = (ScreenMode) screenModes.get(0); - System.err.println("[0] set current: "+sm); - screen.setCurrentScreenMode(sm); + MonitorMode mm = (MonitorMode) monitorModes.get(0); + System.err.println("[0] set current: "+mm); + monitor.setCurrentMode(mm); System.err.print("[0] post setting .. wait <"); try { diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java index 577119bcd..f64cf2eb8 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java @@ -35,18 +35,23 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; +import com.jogamp.common.util.ArrayHashSet; import com.jogamp.newt.Display; +import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.NewtFactory; +import com.jogamp.newt.MonitorMode; import com.jogamp.newt.Screen; -import com.jogamp.newt.ScreenMode; -import com.jogamp.newt.util.MonitorMode; -import com.jogamp.newt.util.ScreenModeUtil; import com.jogamp.opengl.test.junit.util.UITestCase; import java.util.Iterator; import java.util.List; import javax.media.nativewindow.util.Dimension; import javax.media.nativewindow.util.DimensionImmutable; +import javax.media.nativewindow.util.Rectangle; import javax.media.nativewindow.util.SurfaceSize; +import javax.media.opengl.GLProfile; + +import jogamp.newt.MonitorDeviceImpl; +import jogamp.newt.MonitorModeProps; public class TestScreenMode00NEWT extends UITestCase { static int screenIdx = 0; @@ -59,6 +64,7 @@ public class TestScreenMode00NEWT extends UITestCase { @BeforeClass public static void initClass() { + GLProfile.initSingleton(); // hack to initialize GL for BCM_IV (Rasp.Pi) NativeWindowFactory.initSingleton(); width = 640; height = 480; @@ -66,31 +72,46 @@ public class TestScreenMode00NEWT extends UITestCase { @Test public void testScreenModeInfo00() throws InterruptedException { - DimensionImmutable res = new Dimension(640, 480); - SurfaceSize surfsz = new SurfaceSize(res, 32); - DimensionImmutable mm = new Dimension(500, 400); - MonitorMode mon = new MonitorMode(surfsz, mm, 60); - ScreenMode sm_out = new ScreenMode(mon, 90); - System.err.println("00 out: "+sm_out); - - int[] props = ScreenModeUtil.streamOut(sm_out); - ScreenMode sm_in = ScreenModeUtil.streamIn(props, 0); - System.err.println("00 in : "+sm_in); - - Assert.assertEquals(sm_in.getMonitorMode().getSurfaceSize().getResolution(), - sm_out.getMonitorMode().getSurfaceSize().getResolution()); - - Assert.assertEquals(sm_in.getMonitorMode().getSurfaceSize(), - sm_out.getMonitorMode().getSurfaceSize()); - - Assert.assertEquals(sm_in.getMonitorMode().getScreenSizeMM(), - sm_out.getMonitorMode().getScreenSizeMM()); - - Assert.assertEquals(sm_in.getMonitorMode(), sm_out.getMonitorMode()); - - Assert.assertEquals(sm_in, sm_out); + final DimensionImmutable res = new Dimension(640, 480); + final SurfaceSize surfsz = new SurfaceSize(res, 32); + final MonitorMode modeOut = new MonitorMode(surfsz, 60.0f, 0, 0); + System.err.println("00 out: "+modeOut); + final MonitorModeProps.Cache cache = new MonitorModeProps.Cache(); + cache.monitorModes.add(modeOut); + { + final int[] props = MonitorModeProps.streamOutMonitorMode(modeOut); + final MonitorMode modeIn = MonitorModeProps.streamInMonitorMode(null, cache, props, 0); + System.err.println("00 in : "+modeIn); + + Assert.assertEquals(modeOut.getSurfaceSize().getResolution(), modeIn.getSurfaceSize().getResolution()); + + Assert.assertEquals(modeOut.getSurfaceSize(), modeIn.getSurfaceSize()); + + Assert.assertEquals(modeOut.hashCode(), modeIn.hashCode()); + + Assert.assertEquals(modeOut, modeIn); + } - Assert.assertEquals(sm_out.hashCode(), sm_in.hashCode()); + final DimensionImmutable sizeMM = new Dimension(50, 50); + final Rectangle viewport = new Rectangle(0, 0, 1920, 1080); + final ArrayHashSet supportedModes = new ArrayHashSet(); + supportedModes.add(modeOut); + final MonitorDevice monOut = new MonitorDeviceImpl(null, -1, sizeMM, viewport, modeOut, supportedModes); + System.err.println("01 out : "+monOut); + cache.monitorDevices.add(monOut); + { + final int[] props = MonitorModeProps.streamOutMonitorDevice(monOut); + final MonitorDevice monIn = MonitorModeProps.streamInMonitorDevice(null, cache, null, props, 0); + System.err.println("01 in : "+monIn); + + Assert.assertEquals(monOut.getCurrentMode(), monOut.getOriginalMode()); + Assert.assertEquals(monOut.getSupportedModes(), monIn.getSupportedModes()); + Assert.assertEquals(monOut.getViewport(), monIn.getViewport()); + Assert.assertEquals(monOut.getOriginalMode(), monIn.getOriginalMode()); + Assert.assertEquals(monOut.getCurrentMode(), monIn.getCurrentMode()); + Assert.assertEquals(monOut.hashCode(), monIn.hashCode()); + Assert.assertEquals(monOut, monIn); + } } @Test @@ -101,21 +122,37 @@ public class TestScreenMode00NEWT extends UITestCase { Assert.assertEquals(true,screen.isNativeValid()); Assert.assertEquals(true,screen.getDisplay().isNativeValid()); System.err.println("Screen: "+screen.toString()); - - List screenModes = screen.getScreenModes(); - Assert.assertTrue(screenModes.size()>0); - int i=0; - for(Iterator iter=screenModes.iterator(); iter.hasNext(); i++) { - System.err.println(i+": "+iter.next()); + List allMonitorModes = screen.getMonitorModes(); + Assert.assertTrue(allMonitorModes.size()>0); + { + int i=0; + for(Iterator iMode=allMonitorModes.iterator(); iMode.hasNext(); i++) { + System.err.println("All["+i+"]: "+iMode.next()); + } + } + + List monitors = screen.getMonitorDevices(); + Assert.assertTrue(monitors.size()>0); + int j=0; + for(Iterator iMonitor=monitors.iterator(); iMonitor.hasNext(); j++) { + MonitorDevice monitor = iMonitor.next(); + System.err.println(j+": "+monitor); + List modes = monitor.getSupportedModes(); + Assert.assertTrue(modes.size()>0); + int i=0; + for(Iterator iMode=modes.iterator(); iMode.hasNext(); i++) { + System.err.println("["+j+"]["+i+"]: "+iMode.next()); + } + Assert.assertTrue(allMonitorModes.containsAll(modes)); + + MonitorMode sm_o = monitor.getOriginalMode(); + Assert.assertNotNull(sm_o); + MonitorMode sm_c = monitor.queryCurrentMode(); + System.err.println("[0] orig : "+sm_o); + System.err.println("[0] current: "+sm_c); + Assert.assertNotNull(sm_c); + Assert.assertEquals(sm_o, sm_c); } - ScreenMode sm_o = screen.getOriginalScreenMode(); - Assert.assertNotNull(sm_o); - ScreenMode sm_c = screen.getCurrentScreenMode(); - Assert.assertNotNull(sm_c); - System.err.println("orig SM: "+sm_o); - System.err.println("curr SM: "+sm_c); - System.err.println("curr sz: "+screen.getWidth()+"x"+screen.getHeight()); - Assert.assertEquals(sm_o, sm_c); screen.removeReference(); diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00bNEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00bNEWT.java index 75a312686..f4eaec5fa 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00bNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00bNEWT.java @@ -36,9 +36,10 @@ import org.junit.BeforeClass; import org.junit.Test; import com.jogamp.newt.Display; +import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; -import com.jogamp.newt.ScreenMode; +import com.jogamp.newt.MonitorMode; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; import com.jogamp.opengl.test.junit.util.UITestCase; @@ -81,23 +82,24 @@ public class TestScreenMode00bNEWT extends UITestCase { Assert.assertEquals(true,screen.isNativeValid()); Assert.assertEquals(true,display.isNativeValid()); - List screenModes = screen.getScreenModes(); + List screenModes = screen.getMonitorModes(); Assert.assertTrue(screenModes.size()>0); int i=0; - for(Iterator iter=screenModes.iterator(); iter.hasNext(); i++) { + for(Iterator iter=screenModes.iterator(); iter.hasNext(); i++) { System.err.println(i+": "+iter.next()); } - ScreenMode sm_o = screen.getOriginalScreenMode(); + MonitorDevice monitor = window.getMainMonitor(); + MonitorMode mm_o = monitor.getOriginalMode(); - Assert.assertNotNull(sm_o); - ScreenMode sm_c = screen.getCurrentScreenMode(); - Assert.assertNotNull(sm_c); - System.err.println("orig: "+sm_o); - System.err.println("curr: "+sm_c); + Assert.assertNotNull(mm_o); + MonitorMode mm_c = monitor.queryCurrentMode(); + Assert.assertNotNull(mm_c); + System.err.println("orig: "+mm_o); + System.err.println("curr: "+mm_c); for(i=0; i<50; i++) { - sm_c = screen.getCurrentScreenMode(); - Assert.assertNotNull(sm_c); + mm_c = monitor.queryCurrentMode(); + Assert.assertNotNull(mm_c); System.err.print("."+i); } System.err.println("!"); diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01NEWT.java index f253f3b58..78dd9fbc1 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01NEWT.java @@ -40,12 +40,13 @@ import org.junit.BeforeClass; import org.junit.Test; import com.jogamp.newt.Display; +import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; import com.jogamp.newt.Window; -import com.jogamp.newt.ScreenMode; +import com.jogamp.newt.MonitorMode; import com.jogamp.newt.opengl.GLWindow; -import com.jogamp.newt.util.ScreenModeUtil; +import com.jogamp.newt.util.MonitorModeUtil; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; import com.jogamp.opengl.test.junit.util.AWTRobotUtil; import com.jogamp.opengl.test.junit.util.UITestCase; @@ -149,14 +150,16 @@ public class TestScreenMode01NEWT extends UITestCase { Animator animator = new Animator(window); animator.start(); + final MonitorDevice monitor = window.getMainMonitor(); + Assert.assertEquals(false, window.isFullscreen()); Assert.assertEquals(width, window.getWidth()); Assert.assertEquals(height, window.getHeight()); window.setFullscreen(true); - Assert.assertEquals(true, window.isFullscreen()); - Assert.assertEquals(window.getScreen().getWidth(), window.getWidth()); - Assert.assertEquals(window.getScreen().getHeight(), window.getHeight()); + Assert.assertEquals(true, window.isFullscreen()); + Assert.assertEquals(monitor.getViewport().getWidth(), window.getWidth()); + Assert.assertEquals(monitor.getViewport().getHeight(), window.getHeight()); Thread.sleep(waitTimeShort); @@ -192,45 +195,53 @@ public class TestScreenMode01NEWT extends UITestCase { GLWindow window = createWindow(screen, caps, width, height, true /* onscreen */, false /* undecorated */); Assert.assertNotNull(window); - List screenModes = screen.getScreenModes(); - if(screenModes.size()==1) { + MonitorDevice monitor = window.getMainMonitor(); + + List monitorModes = monitor.getSupportedModes(); + Assert.assertTrue(monitorModes.size()>0); + if(monitorModes.size()==1) { // no support .. - System.err.println("Your platform has no ScreenMode change support, sorry"); + System.err.println("Your platform has no MonitorMode change support, sorry"); destroyWindow(window); return; } - Assert.assertTrue(screenModes.size()>0); Animator animator = new Animator(window); animator.start(); - ScreenMode smCurrent = screen.getCurrentScreenMode(); - Assert.assertNotNull(smCurrent); - ScreenMode smOrig = screen.getOriginalScreenMode(); - Assert.assertNotNull(smOrig); - Assert.assertEquals(smCurrent, smOrig); - System.err.println("[0] current/orig: "+smCurrent); - - screenModes = ScreenModeUtil.filterByRate(screenModes, smOrig.getMonitorMode().getRefreshRate()); - Assert.assertNotNull(screenModes); - Assert.assertTrue(screenModes.size()>0); - screenModes = ScreenModeUtil.filterByRotation(screenModes, 0); - Assert.assertNotNull(screenModes); - Assert.assertTrue(screenModes.size()>0); - screenModes = ScreenModeUtil.filterByResolution(screenModes, new Dimension(801, 601)); - Assert.assertNotNull(screenModes); - Assert.assertTrue(screenModes.size()>0); + MonitorMode mmCurrent = monitor.queryCurrentMode(); + Assert.assertNotNull(mmCurrent); + MonitorMode mmOrig = monitor.getOriginalMode(); + Assert.assertNotNull(mmOrig); + System.err.println("[0] orig : "+mmOrig); + System.err.println("[0] current: "+mmCurrent); + Assert.assertEquals(mmCurrent, mmOrig); + + monitorModes = MonitorModeUtil.filterByFlags(monitorModes, 0); // no interlace, double-scan etc + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByRotation(monitorModes, 0); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByRate(monitorModes, mmOrig.getRefreshRate()); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByResolution(monitorModes, new Dimension(801, 601)); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); - screenModes = ScreenModeUtil.getHighestAvailableBpp(screenModes); - Assert.assertNotNull(screenModes); - Assert.assertTrue(screenModes.size()>0); + monitorModes = MonitorModeUtil.getHighestAvailableBpp(monitorModes); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); - ScreenMode sm = (ScreenMode) screenModes.get(0); + MonitorMode sm = (MonitorMode) monitorModes.get(0); System.err.println("[0] set current: "+sm); - screen.setCurrentScreenMode(sm); - Assert.assertEquals(sm, screen.getCurrentScreenMode()); - Assert.assertNotSame(smOrig, screen.getCurrentScreenMode()); - + monitor.setCurrentMode(sm); + Assert.assertTrue(monitor.isModeChangedByUs()); + Assert.assertEquals(sm, monitor.getCurrentMode()); + Assert.assertNotSame(mmOrig, monitor.getCurrentMode()); + Assert.assertEquals(sm, monitor.queryCurrentMode()); + Thread.sleep(waitTimeLong); // check reset .. @@ -258,15 +269,14 @@ public class TestScreenMode01NEWT extends UITestCase { Assert.assertEquals(true,display.isNativeValid()); Assert.assertEquals(true,screen.isNativeValid()); - smCurrent = screen.getCurrentScreenMode(); - System.err.println("[1] current/orig: "+smCurrent); + mmCurrent = monitor.getCurrentMode(); + System.err.println("[1] current/orig: "+mmCurrent); screen.destroy(); Assert.assertEquals(false,screen.isNativeValid()); Assert.assertEquals(false,display.isNativeValid()); - Assert.assertNotNull(smCurrent); - Assert.assertEquals(smCurrent, smOrig); - + Assert.assertNotNull(mmCurrent); + Assert.assertEquals(mmCurrent, mmOrig); cleanupGL(); } @@ -291,27 +301,30 @@ public class TestScreenMode01NEWT extends UITestCase { Animator animator = new Animator(window); animator.start(); - ScreenMode smCurrent = screen.getCurrentScreenMode(); - Assert.assertNotNull(smCurrent); - ScreenMode smOrig = screen.getOriginalScreenMode(); - Assert.assertNotNull(smOrig); - Assert.assertEquals(smCurrent, smOrig); - System.err.println("[0] current/orig: "+smCurrent); + MonitorDevice monitor = window.getMainMonitor(); + MonitorMode mmCurrent = monitor.queryCurrentMode(); + Assert.assertNotNull(mmCurrent); + MonitorMode mmOrig = monitor.getOriginalMode(); + Assert.assertNotNull(mmOrig); + System.err.println("[0] orig : "+mmOrig); + System.err.println("[0] current: "+mmCurrent); + Assert.assertEquals(mmCurrent, mmOrig); - List screenModes = screen.getScreenModes(); - if(screenModes.size()==1) { + List monitorModes = monitor.getSupportedModes(); + if(monitorModes.size()==1) { // no support .. destroyWindow(window); return; } - Assert.assertTrue(screenModes.size()>0); - screenModes = ScreenModeUtil.filterByRate(screenModes, smOrig.getMonitorMode().getRefreshRate()); - screenModes = ScreenModeUtil.filterByRotation(screenModes, 0); - screenModes = ScreenModeUtil.filterByResolution(screenModes, new Dimension(801, 601)); - screenModes = ScreenModeUtil.getHighestAvailableBpp(screenModes); - - ScreenMode screenMode = (ScreenMode) screenModes.get(0); - Assert.assertNotNull(screenMode); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByFlags(monitorModes, 0); // no interlace, double-scan etc + monitorModes = MonitorModeUtil.filterByRotation(monitorModes, 0); + monitorModes = MonitorModeUtil.filterByRate(monitorModes, mmOrig.getRefreshRate()); + monitorModes = MonitorModeUtil.filterByResolution(monitorModes, new Dimension(801, 601)); + monitorModes = MonitorModeUtil.getHighestAvailableBpp(monitorModes); + + MonitorMode monitorMode = (MonitorMode) monitorModes.get(0); + Assert.assertNotNull(monitorMode); if(preFS) { System.err.println("[0] set FS pre 0: "+window.isFullscreen()); @@ -321,8 +334,8 @@ public class TestScreenMode01NEWT extends UITestCase { System.err.println("[0] set FS pre X: "+window.isFullscreen()); } - System.err.println("[0] set current: "+screenMode); - screen.setCurrentScreenMode(screenMode); + System.err.println("[0] set current: "+monitorMode); + monitor.setCurrentMode(monitorMode); if(!preFS) { System.err.println("[0] set FS post 0: "+window.isFullscreen()); @@ -358,14 +371,14 @@ public class TestScreenMode01NEWT extends UITestCase { Assert.assertEquals(true,display.isNativeValid()); Assert.assertEquals(true,screen.isNativeValid()); - smCurrent = screen.getCurrentScreenMode(); - System.err.println("[1] current/orig: "+smCurrent); + mmCurrent = monitor.getCurrentMode(); + System.err.println("[1] current/orig: "+mmCurrent); screen.destroy(); Assert.assertEquals(false,screen.isNativeValid()); Assert.assertEquals(false,display.isNativeValid()); - Assert.assertNotNull(smCurrent); - Assert.assertEquals(smCurrent, smOrig); + Assert.assertNotNull(mmCurrent); + Assert.assertEquals(mmCurrent, mmOrig); cleanupGL(); } diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01aNEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01aNEWT.java new file mode 100644 index 000000000..35390636f --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01aNEWT.java @@ -0,0 +1,212 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.newt; + +import java.io.IOException; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLProfile; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.jogamp.newt.Display; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.NewtFactory; +import com.jogamp.newt.Screen; +import com.jogamp.newt.Window; +import com.jogamp.newt.MonitorMode; +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.newt.util.MonitorModeUtil; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.UITestCase; + +import java.util.List; +import javax.media.nativewindow.util.Dimension; + +/** + * Documents remedy B) for NV RANDR/GL bug + * + * @see TestScreenMode01NEWT#cleanupGL() + */ +public class TestScreenMode01aNEWT extends UITestCase { + static GLProfile glp; + static int width, height; + + static int waitTimeShort = 2000; + static int waitTimeLong = 2000; + + @BeforeClass + public static void initClass() { + width = 100; + height = 100; + glp = GLProfile.getDefault(); + } + + @AfterClass + public static void releaseClass() throws InterruptedException { + Thread.sleep(waitTimeShort); + } + + static Window createWindow(Screen screen, GLCapabilities caps, String name, int x, int y, int width, int height) { + Assert.assertNotNull(caps); + + GLWindow window = GLWindow.create(screen, caps); + // Window window = NewtFactory.createWindow(screen, caps); + window.setTitle(name); + window.setPosition(x, y); + window.setSize(width, height); + window.addGLEventListener(new GearsES2()); + Assert.assertNotNull(window); + window.setVisible(true); + return window; + } + + static void destroyWindow(Window window) { + if(null!=window) { + window.destroy(); + } + } + + @Test + public void testScreenModeChange01() throws InterruptedException { + Thread.sleep(waitTimeShort); + + GLCapabilities caps = new GLCapabilities(glp); + Assert.assertNotNull(caps); + Display display = NewtFactory.createDisplay(null); // local display + Assert.assertNotNull(display); + Screen screen = NewtFactory.createScreen(display, 0); // screen 0 + Assert.assertNotNull(screen); + Window window0 = createWindow(screen, caps, "win0", 0, 0, width, height); + Assert.assertNotNull(window0); + + List allMonitorModes = screen.getMonitorModes(); + Assert.assertTrue(allMonitorModes.size()>0); + if(allMonitorModes.size()==1) { + // no support .. + System.err.println("Your platform has no MonitorMode change support (all), sorry"); + destroyWindow(window0); + return; + } + + MonitorDevice monitor = window0.getMainMonitor(); + + List monitorModes = monitor.getSupportedModes(); + Assert.assertTrue(monitorModes.size()>0); + if(monitorModes.size()==1) { + // no support .. + System.err.println("Your platform has no MonitorMode change support (monitor), sorry"); + destroyWindow(window0); + return; + } + Assert.assertTrue(allMonitorModes.containsAll(monitorModes)); + + MonitorMode mmCurrent = monitor.queryCurrentMode(); + Assert.assertNotNull(mmCurrent); + MonitorMode mmOrig = monitor.getOriginalMode(); + Assert.assertNotNull(mmOrig); + System.err.println("[0] orig : "+mmOrig); + System.err.println("[0] current: "+mmCurrent); + Assert.assertEquals(mmCurrent, mmOrig); + + + monitorModes = MonitorModeUtil.filterByFlags(monitorModes, 0); // no interlace, double-scan etc + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByRotation(monitorModes, 0); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByRate(monitorModes, mmOrig.getRefreshRate()); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByResolution(monitorModes, new Dimension(801, 601)); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + + monitorModes = MonitorModeUtil.getHighestAvailableBpp(monitorModes); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + + MonitorMode sm = (MonitorMode) monitorModes.get(0); + System.err.println("[0] set current: "+sm); + Assert.assertTrue(monitor.setCurrentMode(sm)); + Assert.assertTrue(monitor.isModeChangedByUs()); + Assert.assertEquals(sm, monitor.getCurrentMode()); + Assert.assertNotSame(mmOrig, monitor.getCurrentMode()); + Assert.assertEquals(sm, monitor.queryCurrentMode()); + + Thread.sleep(waitTimeShort); + + // check manual reset .. + + Assert.assertEquals(true,display.isNativeValid()); + Assert.assertEquals(true,screen.isNativeValid()); + Assert.assertEquals(true,window0.isNativeValid()); + Assert.assertEquals(true,window0.isVisible()); + + screen.addReference(); // keep it alive ! + Assert.assertTrue(monitor.setCurrentMode(mmOrig)); + Assert.assertFalse(monitor.isModeChangedByUs()); + Assert.assertEquals(mmOrig, monitor.getCurrentMode()); + Assert.assertNotSame(sm, monitor.getCurrentMode()); + Assert.assertEquals(mmOrig, monitor.queryCurrentMode()); + + destroyWindow(window0); + Assert.assertEquals(false,window0.isVisible()); + Assert.assertEquals(false,window0.isNativeValid()); + Assert.assertEquals(true,screen.isNativeValid()); // alive ! + Assert.assertEquals(true,display.isNativeValid()); + + Thread.sleep(waitTimeShort); + + Window window1 = createWindow(screen, caps, "win1", + width+window0.getInsets().getTotalWidth(), 0, + width, height); + Assert.assertNotNull(window1); + Assert.assertEquals(true,window1.isNativeValid()); + Assert.assertEquals(true,window1.isVisible()); + + Thread.sleep(waitTimeShort); + + destroyWindow(window1); + Assert.assertEquals(false,window1.isNativeValid()); + Assert.assertEquals(false,window1.isVisible()); + + screen.removeReference(); + Assert.assertEquals(false,screen.isNativeValid()); + Assert.assertEquals(false,display.isNativeValid()); + } + + public static void main(String args[]) throws IOException { + String tstname = TestScreenMode01aNEWT.class.getName(); + org.junit.runner.JUnitCore.main(tstname); + } +} diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01bNEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01bNEWT.java index 38612faa8..7e18f396a 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01bNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01bNEWT.java @@ -1,5 +1,5 @@ /** - * Copyright 2010 JogAmp Community. All rights reserved. + * Copyright 2013 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: @@ -29,7 +29,6 @@ package com.jogamp.opengl.test.junit.newt; import java.io.IOException; -import javax.media.nativewindow.NativeWindowFactory; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLProfile; @@ -39,34 +38,36 @@ import org.junit.BeforeClass; import org.junit.Test; import com.jogamp.newt.Display; +import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; import com.jogamp.newt.Window; -import com.jogamp.newt.ScreenMode; +import com.jogamp.newt.MonitorMode; import com.jogamp.newt.opengl.GLWindow; -import com.jogamp.newt.util.ScreenModeUtil; +import com.jogamp.newt.util.MonitorModeUtil; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.util.Animator; import java.util.List; import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.RectangleImmutable; /** - * Documents remedy B) for NV RANDR/GL bug - * - * @see TestScreenMode01NEWT#cleanupGL() + * Mode change on separate monitors .. */ public class TestScreenMode01bNEWT extends UITestCase { static GLProfile glp; static int width, height; - static int waitTimeShort = 2000; - static int waitTimeLong = 2000; + static long waitTimeShort = 2000; + static long duration = 6000; @BeforeClass public static void initClass() { - width = 100; - height = 100; + width = 200; + height = 200; glp = GLProfile.getDefault(); } @@ -75,7 +76,7 @@ public class TestScreenMode01bNEWT extends UITestCase { Thread.sleep(waitTimeShort); } - static Window createWindow(Screen screen, GLCapabilities caps, String name, int x, int y, int width, int height) { + static GLWindow createWindow(Screen screen, GLCapabilities caps, String name, int x, int y, int width, int height) throws InterruptedException { Assert.assertNotNull(caps); GLWindow window = GLWindow.create(screen, caps); @@ -85,7 +86,9 @@ public class TestScreenMode01bNEWT extends UITestCase { window.setSize(width, height); window.addGLEventListener(new GearsES2()); Assert.assertNotNull(window); + final long t0 = System.currentTimeMillis(); window.setVisible(true); + System.err.println("Time for visible/pos: "+(System.currentTimeMillis()-t0)+" ms"); return window; } @@ -96,93 +99,150 @@ public class TestScreenMode01bNEWT extends UITestCase { } @Test - public void testScreenModeChange01() throws InterruptedException { + public void testScreenModeChangeSingleQ1() throws InterruptedException { + final Display display = NewtFactory.createDisplay(null); // local display + Assert.assertNotNull(display); + final Screen screen = NewtFactory.createScreen(display, 0); // screen 0 + Assert.assertNotNull(screen); + screen.addReference(); // trigger creation + try { + RectangleImmutable monitorVp = screen.getMonitorDevices().get(0).getViewport(); + testScreenModeChangeImpl(screen, monitorVp.getX(), monitorVp.getY()); + } finally { + screen.removeReference(); + } + } + + @Test + public void testScreenModeChangeSingleQ2() throws InterruptedException { + final Display display = NewtFactory.createDisplay(null); // local display + Assert.assertNotNull(display); + final Screen screen = NewtFactory.createScreen(display, 0); // screen 0 + Assert.assertNotNull(screen); + screen.addReference(); // trigger creation + try { + if( 2 > screen.getMonitorDevices().size() ) { + System.err.println("Test Disabled (1): Monitor count < 2: "+screen); + return; + } + RectangleImmutable monitorVp = screen.getMonitorDevices().get(1).getViewport(); + testScreenModeChangeImpl(screen, monitorVp.getX(), monitorVp.getY()); + } finally { + screen.removeReference(); + } + } + + void testScreenModeChangeImpl(final Screen screen, int xpos, int ypos) throws InterruptedException { Thread.sleep(waitTimeShort); - GLCapabilities caps = new GLCapabilities(glp); + final GLCapabilities caps = new GLCapabilities(glp); Assert.assertNotNull(caps); - Display display = NewtFactory.createDisplay(null); // local display - Assert.assertNotNull(display); - Screen screen = NewtFactory.createScreen(display, 0); // screen 0 - Assert.assertNotNull(screen); - Window window0 = createWindow(screen, caps, "win0", 0, 0, width, height); + final Display display = screen.getDisplay(); + System.err.println("Test.0: Window screen: "+screen); + + System.err.println("Test.0: Window bounds (pre): "+xpos+"/"+ypos+" "+width+"x"+height+" within "+screen.getViewport()); + + GLWindow window0 = createWindow(screen, caps, "win0", xpos, ypos, width, height); Assert.assertNotNull(window0); + System.err.println("Test.0: Window bounds: "+window0.getX()+"/"+window0.getY()+" "+window0.getWidth()+"x"+window0.getHeight()+" within "+screen.getViewport()); - List screenModes = screen.getScreenModes(); - if(screenModes.size()==1) { + final Animator anim = new Animator(window0); + anim.start(); + + List allMonitorModes = screen.getMonitorModes(); + Assert.assertTrue(allMonitorModes.size()>0); + if(allMonitorModes.size()==1) { // no support .. - System.err.println("Your platform has no ScreenMode change support, sorry"); + System.err.println("Your platform has no MonitorMode change support (all), sorry"); destroyWindow(window0); return; } - Assert.assertTrue(screenModes.size()>0); - - ScreenMode smCurrent = screen.getCurrentScreenMode(); - Assert.assertNotNull(smCurrent); - ScreenMode smOrig = screen.getOriginalScreenMode(); - Assert.assertNotNull(smOrig); - Assert.assertEquals(smCurrent, smOrig); - System.err.println("[0] current/orig: "+smCurrent); - - screenModes = ScreenModeUtil.filterByRate(screenModes, smOrig.getMonitorMode().getRefreshRate()); - Assert.assertNotNull(screenModes); - Assert.assertTrue(screenModes.size()>0); - screenModes = ScreenModeUtil.filterByRotation(screenModes, 0); - Assert.assertNotNull(screenModes); - Assert.assertTrue(screenModes.size()>0); - screenModes = ScreenModeUtil.filterByResolution(screenModes, new Dimension(801, 601)); - Assert.assertNotNull(screenModes); - Assert.assertTrue(screenModes.size()>0); - - screenModes = ScreenModeUtil.getHighestAvailableBpp(screenModes); - Assert.assertNotNull(screenModes); - Assert.assertTrue(screenModes.size()>0); - ScreenMode sm = (ScreenMode) screenModes.get(0); - System.err.println("[0] set current: "+sm); - screen.setCurrentScreenMode(sm); - Assert.assertEquals(sm, screen.getCurrentScreenMode()); - Assert.assertNotSame(smOrig, screen.getCurrentScreenMode()); - - Thread.sleep(waitTimeShort); - - // check reset .. + MonitorDevice monitor = window0.getMainMonitor(); + System.err.println("Test.0: Window monitor: "+monitor); + + List monitorModes = monitor.getSupportedModes(); + Assert.assertTrue(monitorModes.size()>0); + if(monitorModes.size()==1) { + // no support .. + System.err.println("Your platform has no MonitorMode change support (monitor), sorry"); + destroyWindow(window0); + return; + } + Assert.assertTrue(allMonitorModes.containsAll(monitorModes)); + + MonitorMode mmCurrent = monitor.getCurrentMode(); + Assert.assertNotNull(mmCurrent); + MonitorMode mmOrig = monitor.getOriginalMode(); + Assert.assertNotNull(mmOrig); + System.err.println("[0] orig : "+mmOrig); + System.err.println("[0] current: "+mmCurrent); + Assert.assertEquals(mmCurrent, mmOrig); + + monitorModes = MonitorModeUtil.filterByFlags(monitorModes, 0); // no interlace, double-scan etc + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByRotation(monitorModes, 0); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByRate(monitorModes, mmOrig.getRefreshRate()); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByResolution(monitorModes, new Dimension(801, 601)); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + + monitorModes = MonitorModeUtil.getHighestAvailableBpp(monitorModes); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + + MonitorMode sm = (MonitorMode) monitorModes.get(0); + System.err.println("[1] set current: "+sm); + Assert.assertTrue(monitor.setCurrentMode(sm)); + mmCurrent = monitor.getCurrentMode(); + System.err.println("[1] current: "+mmCurrent); + Assert.assertTrue(monitor.isModeChangedByUs()); + Assert.assertEquals(sm, monitor.getCurrentMode()); + Assert.assertNotSame(mmOrig, monitor.getCurrentMode()); + Assert.assertEquals(sm, monitor.queryCurrentMode()); + + System.err.println("Test.1: Window screen: "+screen); + System.err.println("Test.1: Window bounds: "+window0.getX()+"/"+window0.getY()+" "+window0.getWidth()+"x"+window0.getHeight()+" within "+screen.getViewport()); + System.err.println("Test.1: Window monitor: "+window0.getMainMonitor()); + + Thread.sleep(duration); Assert.assertEquals(true,display.isNativeValid()); Assert.assertEquals(true,screen.isNativeValid()); Assert.assertEquals(true,window0.isNativeValid()); Assert.assertEquals(true,window0.isVisible()); - screen.addReference(); // keep it alive ! - screen.setCurrentScreenMode(smOrig); + Assert.assertTrue(monitor.setCurrentMode(mmOrig)); + Assert.assertFalse(monitor.isModeChangedByUs()); + Assert.assertEquals(mmOrig, monitor.getCurrentMode()); + Assert.assertNotSame(sm, monitor.getCurrentMode()); + Assert.assertEquals(mmOrig, monitor.queryCurrentMode()); + + System.err.println("Test.2: Window screen: "+screen); + System.err.println("Test.2: Window bounds: "+window0.getX()+"/"+window0.getY()+" "+window0.getWidth()+"x"+window0.getHeight()+" within "+screen.getViewport()); + System.err.println("Test.2: Window monitor: "+window0.getMainMonitor()); + Thread.sleep(duration); + anim.stop(); destroyWindow(window0); Assert.assertEquals(false,window0.isVisible()); Assert.assertEquals(false,window0.isNativeValid()); - Assert.assertEquals(true,screen.isNativeValid()); // alive ! Assert.assertEquals(true,display.isNativeValid()); - - Thread.sleep(waitTimeShort); - - Window window1 = createWindow(screen, caps, "win1", - width+window0.getInsets().getTotalWidth(), 0, - width, height); - Assert.assertNotNull(window1); - Assert.assertEquals(true,window1.isNativeValid()); - Assert.assertEquals(true,window1.isVisible()); - - Thread.sleep(waitTimeShort); - - destroyWindow(window1); - Assert.assertEquals(false,window1.isNativeValid()); - Assert.assertEquals(false,window1.isVisible()); - - screen.removeReference(); - Assert.assertEquals(false,screen.isNativeValid()); - Assert.assertEquals(false,display.isNativeValid()); + Assert.assertEquals(true,screen.isNativeValid()); } public static void main(String args[]) throws IOException { + for(int i=0; i screen.getMonitorDevices().size() ) { + System.err.println("Test Disabled (1): Monitor count < 2: "+screen); + return; + } + RectangleImmutable monitorVp = screen.getMonitorDevices().get(1).getViewport(); + testScreenFullscreenImpl(screen, monitorVp.getX(), monitorVp.getY(), false, null); + } finally { + screen.removeReference(); + } + } + + @Test + public void testScreenFullscreenSpanQ1Q2() throws InterruptedException { + final Display display = NewtFactory.createDisplay(null); // local display + Assert.assertNotNull(display); + final Screen screen = NewtFactory.createScreen(display, 0); // screen 0 + Assert.assertNotNull(screen); + screen.addReference(); // trigger creation + try { + final int crtCount = screen.getMonitorDevices().size(); + if( 2 >= crtCount ) { + System.err.println("Test Disabled (2): Spanning monitor count "+2+" >= screen monitor count: "+screen); + return; + } + final ArrayList monitors = new ArrayList(); + monitors.add(screen.getMonitorDevices().get(0)); // Q1 + monitors.add(screen.getMonitorDevices().get(1)); // Q2 + RectangleImmutable monitorVp = screen.getMonitorDevices().get(0).getViewport(); + testScreenFullscreenImpl(screen, monitorVp.getX()+50, monitorVp.getY()+50, true, monitors); + } finally { + screen.removeReference(); + } + } + + @Test + public void testScreenFullscreenSpanALL() throws InterruptedException { + final Display display = NewtFactory.createDisplay(null); // local display + Assert.assertNotNull(display); + final Screen screen = NewtFactory.createScreen(display, 0); // screen 0 + Assert.assertNotNull(screen); + screen.addReference(); // trigger creation + try { + if( 2 > screen.getMonitorDevices().size() ) { + System.err.println("Test Disabled (3): Monitor count < 2: "+screen); + return; + } + RectangleImmutable monitorVp = screen.getMonitorDevices().get(1).getViewport(); + testScreenFullscreenImpl(screen, monitorVp.getX()-50, monitorVp.getY()+50, true, null); + } finally { + screen.removeReference(); + } + } + + void testScreenFullscreenImpl(final Screen screen, int xpos, int ypos, boolean spanAcrossMonitors, List monitors) throws InterruptedException { + Thread.sleep(waitTimeShort); + + final GLCapabilities caps = new GLCapabilities(glp); + Assert.assertNotNull(caps); + final Display display = screen.getDisplay(); + + System.err.println("Test.0: Window screen: "+screen); + + System.err.println("Test.0: Window bounds (pre): "+xpos+"/"+ypos+" "+width+"x"+height+" within "+screen.getViewport()); + + GLWindow window0 = createWindow(screen, caps, "win0", xpos, ypos, width, height); + Assert.assertNotNull(window0); + System.err.println("Test.0: Window bounds: "+window0.getX()+"/"+window0.getY()+" "+window0.getWidth()+"x"+window0.getHeight()+" within "+screen.getViewport()); + + final Animator anim = new Animator(window0); + anim.start(); + + List allMonitorModes = screen.getMonitorModes(); + Assert.assertTrue(allMonitorModes.size()>0); + + MonitorDevice monitor = window0.getMainMonitor(); + System.err.println("Test.0: Window monitor: "+monitor); + if( !spanAcrossMonitors ) { + window0.setFullscreen(true); + } else { + window0.setFullscreen(monitors); + } + + monitor = window0.getMainMonitor(); + System.err.println("Test.1: Window bounds: "+window0.getX()+"/"+window0.getY()+" "+window0.getWidth()+"x"+window0.getHeight()+" within "+screen.getViewport()); + System.err.println("Test.1: Window monitor: "+monitor.getViewport()); + Rectangle window0Rect = new Rectangle(window0.getX(), window0.getY(), window0.getWidth(), window0.getHeight()); + if( !spanAcrossMonitors ) { + Assert.assertEquals(monitor.getViewport(), window0Rect); + } else { + List monitorsUsed = monitors; + if( null == monitorsUsed ) { + monitorsUsed = window0.getScreen().getMonitorDevices(); + } + Rectangle monitorsUsedViewport = MonitorDevice.unionOfViewports(new Rectangle(), monitorsUsed); + Assert.assertEquals(monitorsUsedViewport, window0Rect); + } + + Thread.sleep(duration); + + window0.setFullscreen(false); + + window0Rect = new Rectangle(window0.getX(), window0.getY(), window0.getWidth(), window0.getHeight()); + monitor = window0.getMainMonitor(); + System.err.println("Test.2: Window bounds: "+window0.getX()+"/"+window0.getY()+" "+window0.getWidth()+"x"+window0.getHeight()+" within "+screen.getViewport()); + System.err.println("Test.2: Window monitor: "+monitor.getViewport()); + + Thread.sleep(duration); + anim.stop(); + destroyWindow(window0); + Assert.assertEquals(false,window0.isVisible()); + Assert.assertEquals(false,window0.isNativeValid()); + Assert.assertEquals(true,display.isNativeValid()); + Assert.assertEquals(true,screen.isNativeValid()); + } + + public static void main(String args[]) throws IOException { + for(int i=0; i screenModes = screen.getScreenModes(); - if(screenModes.size()==1) { + MonitorDevice monitor = window.getMainMonitor(); + List monitorModes = monitor.getSupportedModes(); + if(monitorModes.size()==1) { // no support .. System.err.println("Your platform has no ScreenMode change support, sorry"); destroyWindow(window); return; } - Assert.assertTrue(screenModes.size()>0); + Assert.assertTrue(monitorModes.size()>0); Animator animator = new Animator(window); animator.start(); - ScreenMode smCurrent = screen.getCurrentScreenMode(); - Assert.assertNotNull(smCurrent); - ScreenMode smOrig = screen.getOriginalScreenMode(); - Assert.assertNotNull(smOrig); - Assert.assertEquals(smCurrent, smOrig); - System.err.println("[0] current/orig: "+smCurrent); - - screenModes = ScreenModeUtil.filterByRate(screenModes, smOrig.getMonitorMode().getRefreshRate()); - Assert.assertNotNull(screenModes); - Assert.assertTrue(screenModes.size()>0); - screenModes = ScreenModeUtil.filterByRotation(screenModes, 90); - if(null==screenModes) { + MonitorMode mmCurrent = monitor.getCurrentMode(); + Assert.assertNotNull(mmCurrent); + MonitorMode mmOrig = monitor.getOriginalMode(); + Assert.assertNotNull(mmOrig); + System.err.println("[0] orig : "+mmOrig); + System.err.println("[0] current: "+mmCurrent); + Assert.assertEquals(mmCurrent, mmOrig); + + monitorModes = MonitorModeUtil.filterByFlags(monitorModes, 0); // no interlace, double-scan etc + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByRotation(monitorModes, 90); + if(null==monitorModes || Platform.getOSType() == Platform.OSType.MACOS ) { // no rotation support .. System.err.println("Your platform has no rotation support, sorry"); destroyWindow(window); return; } - Assert.assertTrue(screenModes.size()>0); - screenModes = ScreenModeUtil.filterByResolution(screenModes, new Dimension(801, 601)); - Assert.assertNotNull(screenModes); - Assert.assertTrue(screenModes.size()>0); - screenModes = ScreenModeUtil.getHighestAvailableBpp(screenModes); - Assert.assertNotNull(screenModes); - Assert.assertTrue(screenModes.size()>0); - - ScreenMode sm = (ScreenMode) screenModes.get(0); + monitorModes = MonitorModeUtil.filterByRate(monitorModes, mmOrig.getRefreshRate()); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByResolution(monitorModes, new Dimension(801, 601)); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.getHighestAvailableBpp(monitorModes); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + + MonitorMode sm = (MonitorMode) monitorModes.get(0); System.err.println("[0] set current: "+sm); - screen.setCurrentScreenMode(sm); - Assert.assertEquals(sm, screen.getCurrentScreenMode()); - Assert.assertNotSame(smOrig, screen.getCurrentScreenMode()); + monitor.setCurrentMode(sm); + Assert.assertTrue(monitor.isModeChangedByUs()); + Assert.assertEquals(sm, monitor.getCurrentMode()); + Assert.assertNotSame(mmOrig, monitor.getCurrentMode()); + Assert.assertEquals(sm, monitor.queryCurrentMode()); Thread.sleep(waitTimeLong); @@ -167,11 +176,11 @@ public class TestScreenMode02NEWT extends UITestCase { Assert.assertEquals(true,display.isNativeValid()); Assert.assertEquals(true,screen.isNativeValid()); - smCurrent = screen.getCurrentScreenMode(); - System.err.println("[1] current/orig: "+smCurrent); + mmCurrent = monitor.getCurrentMode(); + System.err.println("[1] current/orig: "+mmCurrent); - Assert.assertNotNull(smCurrent); - Assert.assertEquals(smCurrent, smOrig); + Assert.assertNotNull(mmCurrent); + Assert.assertEquals(mmCurrent, mmOrig); screen.destroy(); -- cgit v1.2.3 From 1c1ffed31548094cf7afbb4c83b0cb627ae3a1ad Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 9 Jun 2013 06:11:33 +0200 Subject: Bug 747: Allow usage of IdentityHashMap w/ keys: AbstractGraphicsDevice.getUniqueID() and GLContext.getDeviceVersionAvailableKey() .. both value classes unique, long lived and rare. --- src/jogl/classes/javax/media/opengl/GLContext.java | 28 ++++++++++++---------- .../media/nativewindow/AbstractGraphicsDevice.java | 12 +++++++--- .../media/nativewindow/DefaultGraphicsDevice.java | 7 +++++- 3 files changed, 31 insertions(+), 16 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/GLContext.java b/src/jogl/classes/javax/media/opengl/GLContext.java index abafabb1c..fd3c31b6d 100644 --- a/src/jogl/classes/javax/media/opengl/GLContext.java +++ b/src/jogl/classes/javax/media/opengl/GLContext.java @@ -42,7 +42,7 @@ package javax.media.opengl; import java.nio.IntBuffer; import java.util.HashMap; -import java.util.HashSet; +import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Set; @@ -1209,12 +1209,12 @@ public abstract class GLContext { /** * @see #getDeviceVersionAvailableKey(javax.media.nativewindow.AbstractGraphicsDevice, int, int) */ - protected static /*final*/ HashMap deviceVersionAvailable = new HashMap(); + protected static /*final*/ IdentityHashMap deviceVersionAvailable = new IdentityHashMap(); /** * @see #getUniqueDeviceString(javax.media.nativewindow.AbstractGraphicsDevice) */ - private static /*final*/ HashSet deviceVersionsAvailableSet = new HashSet(); + private static /*final*/ IdentityHashMap deviceVersionsAvailableSet = new IdentityHashMap(); /** clears the device/context mappings as well as the GL/GLX proc address tables. */ protected static void shutdown() { @@ -1225,17 +1225,16 @@ public abstract class GLContext { protected static boolean getAvailableGLVersionsSet(AbstractGraphicsDevice device) { synchronized ( deviceVersionsAvailableSet ) { - return deviceVersionsAvailableSet.contains(device.getUniqueID()); + return deviceVersionsAvailableSet.containsKey(device.getUniqueID()); } } protected static void setAvailableGLVersionsSet(AbstractGraphicsDevice device) { synchronized ( deviceVersionsAvailableSet ) { - String devKey = device.getUniqueID(); - if ( deviceVersionsAvailableSet.contains(devKey) ) { + final String devKey = device.getUniqueID(); + if( null != deviceVersionsAvailableSet.put(devKey, devKey) ) { throw new InternalError("Already set: "+devKey); } - deviceVersionsAvailableSet.add(devKey); if (DEBUG) { System.err.println(getThreadName() + ": createContextARB: SET mappedVersionsAvailableSet "+devKey); System.err.println(GLContext.dumpAvailableGLVersions(null).toString()); @@ -1243,8 +1242,13 @@ public abstract class GLContext { } } + /** + * Returns a unique String object using {@link String#intern()} for the given arguments, + * which object reference itself can be used as a key. + */ protected static String getDeviceVersionAvailableKey(AbstractGraphicsDevice device, int major, int profile) { - return device.getUniqueID() + "-" + toHexString(composeBits(major, profile, 0)); + final String r = device.getUniqueID() + "-" + toHexString(composeBits(major, profile, 0)); + return r.intern(); } /** @@ -1272,10 +1276,10 @@ public abstract class GLContext { System.err.println("GLContext.mapAvailableGLVersion: "+device+": "+getGLVersion(reqMajor, 0, profile, null)+" -> "+getGLVersion(resMajor, resMinor, resCtp, null)); // Thread.dumpStack(); } - final String key = getDeviceVersionAvailableKey(device, reqMajor, profile); + final String objectKey = getDeviceVersionAvailableKey(device, reqMajor, profile); final Integer val = new Integer(composeBits(resMajor, resMinor, resCtp)); synchronized(deviceVersionAvailable) { - return deviceVersionAvailable.put( key, val ); + return deviceVersionAvailable.put( objectKey, val ); } } @@ -1315,10 +1319,10 @@ public abstract class GLContext { * @return the available GL version as encoded with {@link #composeBits(int, int, int), otherwise null */ protected static Integer getAvailableGLVersion(AbstractGraphicsDevice device, int reqMajor, int reqProfile) { - String key = getDeviceVersionAvailableKey(device, reqMajor, reqProfile); + final String objectKey = getDeviceVersionAvailableKey(device, reqMajor, reqProfile); Integer val; synchronized(deviceVersionAvailable) { - val = deviceVersionAvailable.get( key ); + val = deviceVersionAvailable.get( objectKey ); } return val; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java index 585cd1f09..ed305d49e 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java @@ -89,10 +89,16 @@ public interface AbstractGraphicsDevice extends Cloneable { public int getUnitID(); /** - * Returns a unique ID String of this device using {@link #getType() type}, - * {@link #getConnection() connection} and {@link #getUnitID() unitID}.
        - * The unique ID does not reflect the instance of the device, hence the handle is not included.
        + * Returns a unique ID object of this device using {@link #getType() type}, + * {@link #getConnection() connection} and {@link #getUnitID() unitID} as it's key components. + *

        + * The unique ID does not reflect the instance of the device, hence the handle is not included. * The unique ID may be used as a key for semantic device mapping. + *

        + *

        + * The returned string object reference is unique using {@link String#intern()} + * and hence can be used as a key itself. + *

        */ public String getUniqueID(); diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java index 66b81d7fa..0bf5c2937 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java @@ -253,7 +253,12 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice return toolkitLock; } + /** + * Returns a unique String object using {@link String#intern()} for the given arguments, + * which object reference itself can be used as a key. + */ protected static String getUniqueID(String type, String connection, int unitID) { - return (type + separator + connection + separator + unitID).intern(); + final String r = (type + separator + connection + separator + unitID).intern(); + return r.intern(); } } -- cgit v1.2.3 From 05eef46e33f41f5c234ffb1563fd8f641208fe85 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 11 Jun 2013 16:29:48 +0200 Subject: Adapt to GlueGen commit 1a01dce6c42b398cdd68d405828774a3ab366456 --- make/config/jogl/cg-common-CustomJavaCode.java | 6 +++++- make/config/jogl/cg-common.cfg | 2 ++ make/scripts/tests.sh | 4 ++-- .../classes/com/jogamp/graph/font/FontFactory.java | 8 ++++--- .../font/typecast/TypecastFontConstructor.java | 2 +- src/jogl/classes/jogamp/opengl/Debug.java | 25 ++++++++++------------ .../av/impl/FFMPEGDynamicLibraryBundleInfo.java | 7 +++++- .../classes/jogamp/nativewindow/Debug.java | 24 +++++++++------------ .../jogamp/newt/awt/applet/JOGLNewtAppletBase.java | 6 ++++-- src/newt/classes/jogamp/newt/Debug.java | 25 ++++++++++------------ 10 files changed, 57 insertions(+), 52 deletions(-) (limited to 'src/nativewindow') diff --git a/make/config/jogl/cg-common-CustomJavaCode.java b/make/config/jogl/cg-common-CustomJavaCode.java index 31d1961fc..cc1fefd1a 100644 --- a/make/config/jogl/cg-common-CustomJavaCode.java +++ b/make/config/jogl/cg-common-CustomJavaCode.java @@ -6,7 +6,11 @@ static { if(null==cgProcAddressTable) { throw new RuntimeException("Couldn't instantiate CgProcAddressTable"); } - cgDynamicLookupHelper = new DynamicLibraryBundle(new CgDynamicLibraryBundleInfo()); + + cgDynamicLookupHelper = AccessController.doPrivileged(new PrivilegedAction() { + public DynamicLibraryBundle run() { + return new DynamicLibraryBundle(new CgDynamicLibraryBundleInfo()); + } } ); if(null==cgDynamicLookupHelper) { throw new RuntimeException("Null CgDynamicLookupHelper"); } diff --git a/make/config/jogl/cg-common.cfg b/make/config/jogl/cg-common.cfg index 35805bf01..d6a5367a6 100644 --- a/make/config/jogl/cg-common.cfg +++ b/make/config/jogl/cg-common.cfg @@ -105,6 +105,8 @@ Import jogamp.opengl.* Import com.jogamp.common.os.DynamicLookupHelper Import com.jogamp.common.os.DynamicLibraryBundle Import com.jogamp.opengl.cg.CgDynamicLibraryBundleInfo +Import java.security.PrivilegedAction +Import java.security.AccessController # # NIODirectOnly directives for routines requiring them for semantic reasons diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 693683827..2a75ffc5b 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -284,7 +284,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelsAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testawtswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple $* @@ -312,7 +312,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.math.TestPMVMatrix01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.math.TestPMVMatrix02NOUI $* -testnoawt com.jogamp.opengl.test.junit.jogl.math.TestPMVMatrix03NOUI $* +#testnoawt com.jogamp.opengl.test.junit.jogl.math.TestPMVMatrix03NOUI $* #testnoawt com.jogamp.opengl.test.junit.jogl.math.TestGluUnprojectFloatNOUI $* #testnoawt com.jogamp.opengl.test.junit.jogl.math.TestGluUnprojectDoubleNOUI $* #testnoawt com.jogamp.opengl.test.junit.jogl.math.TestFloatUtil01MatrixMatrixMultNOUI $* diff --git a/src/jogl/classes/com/jogamp/graph/font/FontFactory.java b/src/jogl/classes/com/jogamp/graph/font/FontFactory.java index 33d487355..33a977bba 100644 --- a/src/jogl/classes/com/jogamp/graph/font/FontFactory.java +++ b/src/jogl/classes/com/jogamp/graph/font/FontFactory.java @@ -33,13 +33,15 @@ import java.net.URLConnection; import com.jogamp.common.util.PropertyAccess; import com.jogamp.common.util.ReflectionUtil; -import com.jogamp.common.util.SecurityUtil; import jogamp.graph.font.FontConstructor; import jogamp.graph.font.JavaFontLoader; import jogamp.graph.font.UbuntuFontLoader; public class FontFactory { + public static final String FontConstructorPropKey = "jogamp.graph.font.ctor"; + public static final String DefaultFontConstructor = "jogamp.graph.font.typecast.TypecastFontConstructor"; + /** Ubuntu is the default font family */ public static final int UBUNTU = 0; @@ -54,9 +56,9 @@ public class FontFactory { * "jogamp.graph.font.typecast.TypecastFontFactory" (default) * "jogamp.graph.font.ttf.TTFFontImpl" */ - String fontImplName = PropertyAccess.getProperty("FontImpl", true, SecurityUtil.getCommonAccessControlContext(FontFactory.class)); + String fontImplName = PropertyAccess.getProperty(FontConstructorPropKey, true); if(null == fontImplName) { - fontImplName = "jogamp.graph.font.typecast.TypecastFontConstructor"; + fontImplName = DefaultFontConstructor; } fontConstr = (FontConstructor) ReflectionUtil.createInstance(fontImplName, FontFactory.class.getClassLoader()); } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java index 0f762e79c..8479c08ca 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java @@ -71,7 +71,7 @@ public class TypecastFontConstructor implements FontConstructor { int len=0; Font f = null; try { - tf = IOUtil.createTempFile( "jogl.font", ".ttf", false, null); + tf = IOUtil.createTempFile( "jogl.font", ".ttf", false); len = IOUtil.copyURLConn2File(fconn, tf); if(len==0) { tf.delete(); diff --git a/src/jogl/classes/jogamp/opengl/Debug.java b/src/jogl/classes/jogamp/opengl/Debug.java index 4287c1960..f87f1bb3f 100644 --- a/src/jogl/classes/jogamp/opengl/Debug.java +++ b/src/jogl/classes/jogamp/opengl/Debug.java @@ -1,5 +1,6 @@ /* - * Copyright (c) 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * 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 @@ -39,6 +40,9 @@ package jogamp.opengl; +import java.security.AccessController; +import java.security.PrivilegedAction; + import com.jogamp.common.util.PropertyAccess; /** Helper routines for logging and debugging. */ @@ -49,7 +53,12 @@ public class Debug extends PropertyAccess { private static final boolean debugAll; static { - PropertyAccess.addTrustedPrefix("jogl.", Debug.class); + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + PropertyAccess.addTrustedPrefix("jogl."); + return null; + } } ); + verbose = isPropertyDefined("jogl.verbose", true); debugAll = isPropertyDefined("jogl.debug", true); if (verbose) { @@ -60,18 +69,6 @@ public class Debug extends PropertyAccess { } } - public static final boolean isPropertyDefined(final String property, final boolean jnlpAlias) { - return PropertyAccess.isPropertyDefined(property, jnlpAlias, null); - } - - public static String getProperty(final String property, final boolean jnlpAlias) { - return PropertyAccess.getProperty(property, jnlpAlias, null); - } - - public static final boolean getBooleanProperty(final String property, final boolean jnlpAlias) { - return PropertyAccess.getBooleanProperty(property, jnlpAlias, null); - } - public static boolean verbose() { return verbose; } diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGDynamicLibraryBundleInfo.java index 32c863553..883c13f51 100644 --- a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGDynamicLibraryBundleInfo.java @@ -28,6 +28,8 @@ package jogamp.opengl.util.av.impl; +import java.security.AccessController; +import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -132,7 +134,10 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { static boolean initSingleton() { return ready; } private static boolean initSymbols() { - final DynamicLibraryBundle dl = new DynamicLibraryBundle(new FFMPEGDynamicLibraryBundleInfo()); + final DynamicLibraryBundle dl = AccessController.doPrivileged(new PrivilegedAction() { + public DynamicLibraryBundle run() { + return new DynamicLibraryBundle(new FFMPEGDynamicLibraryBundleInfo()); + } } ); final boolean avutilLoaded = dl.isToolLibLoaded(0); final boolean avformatLoaded = dl.isToolLibLoaded(1); final boolean avcodecLoaded = dl.isToolLibLoaded(2); diff --git a/src/nativewindow/classes/jogamp/nativewindow/Debug.java b/src/nativewindow/classes/jogamp/nativewindow/Debug.java index e07fd1b57..95547c971 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/Debug.java +++ b/src/nativewindow/classes/jogamp/nativewindow/Debug.java @@ -1,5 +1,6 @@ /* - * Copyright (c) 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * 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 @@ -39,6 +40,9 @@ package jogamp.nativewindow; +import java.security.AccessController; +import java.security.PrivilegedAction; + import com.jogamp.common.util.PropertyAccess; /** Helper routines for logging and debugging. */ @@ -49,7 +53,11 @@ public class Debug extends PropertyAccess { private static final boolean debugAll; static { - PropertyAccess.addTrustedPrefix("nativewindow.", Debug.class); + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + PropertyAccess.addTrustedPrefix("nativewindow."); + return null; + } } ); verbose = isPropertyDefined("nativewindow.verbose", true); debugAll = isPropertyDefined("nativewindow.debug", true); @@ -61,18 +69,6 @@ public class Debug extends PropertyAccess { } } - public static final boolean isPropertyDefined(final String property, final boolean jnlpAlias) { - return PropertyAccess.isPropertyDefined(property, jnlpAlias, null); - } - - public static String getProperty(final String property, final boolean jnlpAlias) { - return PropertyAccess.getProperty(property, jnlpAlias, null); - } - - public static final boolean getBooleanProperty(final String property, final boolean jnlpAlias) { - return PropertyAccess.getBooleanProperty(property, jnlpAlias, null); - } - public static boolean verbose() { return verbose; } diff --git a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java index c3ad51c96..091a1a5cf 100644 --- a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java +++ b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java @@ -164,12 +164,14 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener { // Closing action: back to parent! @Override public void windowDestroyNotify(WindowEvent e) { - if( WindowClosingMode.DO_NOTHING_ON_CLOSE == glWindow.getDefaultCloseOperation() ) { + if( isValid() && WindowClosingMode.DO_NOTHING_ON_CLOSE == glWindow.getDefaultCloseOperation() ) { if(null == glWindow.getParent()) { // we may be called directly by the native EDT new Thread(new Runnable() { public void run() { - glWindow.reparentWindow(awtParent); + if( glWindow.isNativeValid() ) { + glWindow.reparentWindow(awtParent); + } } }).start(); } diff --git a/src/newt/classes/jogamp/newt/Debug.java b/src/newt/classes/jogamp/newt/Debug.java index 3c83da4d9..676d9b758 100644 --- a/src/newt/classes/jogamp/newt/Debug.java +++ b/src/newt/classes/jogamp/newt/Debug.java @@ -1,5 +1,6 @@ /* - * Copyright (c) 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * 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 @@ -39,6 +40,9 @@ package jogamp.newt; +import java.security.AccessController; +import java.security.PrivilegedAction; + import com.jogamp.common.util.PropertyAccess; /** Helper routines for logging and debugging. */ @@ -49,7 +53,12 @@ public class Debug extends PropertyAccess { private static final boolean debugAll; static { - PropertyAccess.addTrustedPrefix("newt.", Debug.class); + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + PropertyAccess.addTrustedPrefix("newt."); + return null; + } } ); + verbose = isPropertyDefined("newt.verbose", true); debugAll = isPropertyDefined("newt.debug", true); if (verbose) { @@ -60,18 +69,6 @@ public class Debug extends PropertyAccess { } } - public static final boolean isPropertyDefined(final String property, final boolean jnlpAlias) { - return PropertyAccess.isPropertyDefined(property, jnlpAlias, null); - } - - public static final int getIntProperty(final String property, final boolean jnlpAlias, int defaultValue) { - return PropertyAccess.getIntProperty(property, jnlpAlias, null, defaultValue); - } - - public static final boolean getBooleanProperty(final String property, final boolean jnlpAlias) { - return PropertyAccess.getBooleanProperty(property, jnlpAlias, null); - } - public static boolean verbose() { return verbose; } -- cgit v1.2.3 From aed9662552503b0a2fa67bcddbb7063b16d003d5 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 12 Jun 2013 11:58:55 +0200 Subject: Fix Bug 750: Leaked X11 ColorMap for each created X11 Window in NativeWindow (dummy) and NEWT Free the colormap at WindowDestroy, which we have created at WindowCreate w/ AllocNone. Due to the fact we used 'AllocNone' the leak is minimal though .. --- src/nativewindow/native/x11/Xmisc.c | 7 +++++++ src/newt/native/X11Window.c | 7 +++++++ 2 files changed, 14 insertions(+) (limited to 'src/nativewindow') diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 69f0c0746..31620d752 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -624,6 +624,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_DestroyWindow { Display * dpy = (Display *)(intptr_t)display; Window w = (Window) window; + XWindowAttributes xwa; if(NULL==dpy) { NativewindowCommon_throwNewRuntimeException(env, "invalid display connection.."); @@ -631,10 +632,16 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_x11_X11Lib_DestroyWindow } NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, errorHandlerQuiet, 0); + XSync(dpy, False); + memset(&xwa, 0, sizeof(XWindowAttributes)); + XGetWindowAttributes(dpy, w, &xwa); // prefetch colormap to be destroyed after window destruction XSelectInput(dpy, w, 0); XUnmapWindow(dpy, w); XSync(dpy, False); XDestroyWindow(dpy, w); + if( None != xwa.colormap ) { + XFreeColormap(dpy, xwa.colormap); + } // NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 0, errorHandlerQuiet, 1); } diff --git a/src/newt/native/X11Window.c b/src/newt/native/X11Window.c index 6c5a127b6..e567781cf 100644 --- a/src/newt/native/X11Window.c +++ b/src/newt/native/X11Window.c @@ -676,6 +676,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CloseWindow0 Display * dpy = (Display *) (intptr_t) display; Window w = (Window)window; jobject jwindow; + XWindowAttributes xwa; if(dpy==NULL) { NewtCommon_FatalError(env, "invalid display connection.."); @@ -694,13 +695,19 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CloseWindow0 } XSync(dpy, False); + memset(&xwa, 0, sizeof(XWindowAttributes)); + XGetWindowAttributes(dpy, w, &xwa); // prefetch colormap to be destroyed after window destruction XSelectInput(dpy, w, 0); XUnmapWindow(dpy, w); + XSync(dpy, False); // Drain all events related to this window .. Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessages0(env, obj, display, javaObjectAtom, windowDeleteAtom /*, kbdHandle */); // XKB disabled for now XDestroyWindow(dpy, w); + if( None != xwa.colormap ) { + XFreeColormap(dpy, xwa.colormap); + } XSync(dpy, True); // discard all events now, no more handler (*env)->DeleteGlobalRef(env, jwindow); -- cgit v1.2.3 From f21f4d8e0f125f6c054b9f07e707fdf900fe4b35 Mon Sep 17 00:00:00 2001 From: Maik Riechert Date: Wed, 12 Jun 2013 22:57:54 +0200 Subject: Support specifying the X11 default display with a system property Usually, the environment variable DISPLAY is used to define the default display under X11. There are cases where the default display has to be defined or overridden programmatically. For those cases, the new system property nativewindow.x11.display.default can be used (as environment variables can't be changed in Java). Its semantics are identical to the DISPLAY environment variable. --- src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index e28aff116..2d9c42e09 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -46,6 +46,7 @@ import jogamp.nativewindow.NWJNILibLoader; import jogamp.nativewindow.ToolkitProperties; import com.jogamp.common.util.LongObjectHashMap; +import com.jogamp.common.util.PropertyAccess; import com.jogamp.nativewindow.x11.X11GraphicsDevice; /** @@ -123,7 +124,7 @@ public class X11Util implements ToolkitProperties { final boolean isInitOK = initialize0( XERROR_STACKDUMP ); final boolean hasX11_EXTENSION_ATIFGLRXDRI, hasX11_EXTENSION_ATIFGLEXTENSION; - final long dpy = X11Lib.XOpenDisplay(null); + final long dpy = X11Lib.XOpenDisplay(PropertyAccess.getProperty("nativewindow.x11.display.default", true)); if(0 != dpy) { if(XSYNC_ENABLED) { X11Lib.XSynchronize(dpy, true); -- cgit v1.2.3 From 2d83e346b1e737f9efc0e782ddbd2a9be6a4cd35 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 15 Jun 2013 08:14:19 +0200 Subject: AWTGraphicsConfiguration: Allow null capsRequested; NewtCanvasAWT: Avoid NPE @ addNotify() w/o newtChild --- .../com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java | 6 +++++- src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java index 2a152ff35..7e3d30a47 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java @@ -74,8 +74,9 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple /** * @param capsChosen if null, capsRequested is copied and aligned - * with the graphics Capabilities of the AWT Component to produce the chosen Capabilities. + * with the graphics {@link Capabilities} of the AWT Component to produce the chosen {@link Capabilities}. * Otherwise the capsChosen is used. + * @param capsRequested if null, default {@link Capabilities} are used, otherwise the given values. */ public static AWTGraphicsConfiguration create(Component awtComp, CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested) { final GraphicsConfiguration awtGfxConfig = awtComp.getGraphicsConfiguration(); @@ -91,6 +92,9 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple final AWTGraphicsDevice awtDevice = new AWTGraphicsDevice(awtGraphicsDevice, AbstractGraphicsDevice.DEFAULT_UNIT); final AWTGraphicsScreen awtScreen = new AWTGraphicsScreen(awtDevice); + if(null==capsRequested) { + capsRequested = new Capabilities(); + } if(null==capsChosen) { GraphicsConfiguration gc = awtGraphicsDevice.getDefaultConfiguration(); capsChosen = AWTGraphicsConfiguration.setupCapabilitiesRGBABits(capsRequested, gc); diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index d0a4b7e98..32a92ec8b 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -355,8 +355,8 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto // after native peer is valid: Windows disableBackgroundErase(); - - jawtWindow = NewtFactoryAWT.getNativeWindow(this, newtChild.getRequestedCapabilities()); + + jawtWindow = NewtFactoryAWT.getNativeWindow(this, null != newtChild ? newtChild.getRequestedCapabilities() : null); jawtWindow.setShallUseOffscreenLayer(shallUseOffscreenLayer); if(DEBUG) { -- cgit v1.2.3 From 455c305ef9ca3db975de589dc4b9d078f2b5cc7a Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 23 Jun 2013 01:00:52 +0200 Subject: X11Util: Fix comment on markAllDisplaysUnclosable semantics, add 'final', reorder globalLock/isJVMShuttingDown branch/sync --- .../classes/jogamp/nativewindow/x11/X11Util.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 2d9c42e09..bbc58b73a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -98,10 +98,10 @@ public class X11Util implements ToolkitProperties { private static final boolean TRACE_DISPLAY_LIFECYCLE = Debug.isPropertyDefined("nativewindow.debug.X11Util.TraceDisplayLifecycle", true); private static String nullDisplayName = null; private static volatile boolean isInit = false; - private static boolean markAllDisplaysUnclosable = false; // ATI/AMD X11 driver issues + private static boolean markAllDisplaysUnclosable = false; // ATI/AMD X11 driver issues, or GLRendererQuirks.DontCloseX11Display private static boolean hasThreadingIssues = false; // ATI/AMD X11 driver issues - private static Object setX11ErrorHandlerLock = new Object(); + private static final Object setX11ErrorHandlerLock = new Object(); private static final String X11_EXTENSION_ATIFGLRXDRI = "ATIFGLRXDRI"; private static final String X11_EXTENSION_ATIFGLEXTENSION = "ATIFGLEXTENSION"; @@ -207,12 +207,12 @@ public class X11Util implements ToolkitProperties { } } - synchronized(globalLock) { - // Only at JVM shutdown time, since AWT impl. seems to - // dislike closing of X11 Display's (w/ ATI driver). - if( isJVMShuttingDown ) { - isInit = false; - closePendingDisplayConnections(); + // Only at JVM shutdown time, since AWT impl. seems to + // dislike closing of X11 Display's (w/ ATI driver). + if( isJVMShuttingDown ) { + synchronized(globalLock) { + isInit = false; + closePendingDisplayConnections(); openDisplayList.clear(); reusableDisplayList.clear(); pendingDisplayList.clear(); -- cgit v1.2.3 From 41c626d8a27981e694b3b728a9a2f2bc8def939d Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 23 Jun 2013 01:10:04 +0200 Subject: Fix Bug 761 (part 1/2): Move GLDrawableFactory.shutdownHook -> NativeWindowFactory.shutdownHook, the latter handles customShutdownHooks for NativeWindow, JOGL and NEWT. Unifying our shutdown mechanism is required to provide a controlled shutdown sequence. NativeWindowFactory is chosen to be the new central entry point, since it is the lowest denominator (common module). - Move GLDrawableFactory.shutdownHook -> NativeWindowFactory.shutdownHook Reverse the shutdown dependency for clarity and availability to all modules, i.e. NEWT may not know about JOGL. Remove the 'gamma' shutdown hook, instead simply call GLDrawableFactoryImpl.resetDisplayGamma() before destroy. NativeWindowFactory.shutdownHook handles customShutdownHooks for NativeWindow, JOGL and NEWT - Modules can register their shutdown runnable at head or tail of list. - Allows controlled shutdown across all modules. --- .../javax/media/opengl/GLDrawableFactory.java | 56 +++++-------- .../jogamp/opengl/GLDrawableFactoryImpl.java | 43 ++-------- .../media/nativewindow/NativeWindowFactory.java | 98 +++++++++++++++++----- 3 files changed, 104 insertions(+), 93 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java index 55ad85c9c..f1d8ff95e 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java @@ -40,8 +40,6 @@ package javax.media.opengl; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.List; @@ -118,13 +116,8 @@ public abstract class GLDrawableFactory { private static GLDrawableFactory eglFactory; private static GLDrawableFactory nativeOSFactory; - protected static ArrayList glDrawableFactories = new ArrayList(); - - // Shutdown hook mechanism for the factory - private static boolean factoryShutdownHookRegistered = false; - private static Thread factoryShutdownHook = null; - private static volatile boolean isJVMShuttingDown = false; - + private static ArrayList glDrawableFactories = new ArrayList(); + /** * Instantiate singleton factories if available, EGLES1, EGLES2 and the OS native ones. */ @@ -139,7 +132,12 @@ public abstract class GLDrawableFactory { } } private static final void initSingletonImpl() { - registerFactoryShutdownHook(); + NativeWindowFactory.initSingleton(); + NativeWindowFactory.addCustomShutdownHook(false /* head */, new Runnable() { + public void run() { + shutdown0(); + } + }); final String nwt = NativeWindowFactory.getNativeWindowType(true); GLDrawableFactory tmp = null; @@ -199,23 +197,31 @@ public abstract class GLDrawableFactory { synchronized (GLDrawableFactory.class) { if (isInit) { isInit=false; - shutdownImpl(); + shutdown0(); } } } } - private static void shutdownImpl() { + private static void shutdown0() { // Following code will _always_ remain in shutdown hook // due to special semantics of native utils, i.e. X11Utils. // The latter requires shutdown at JVM-Shutdown only. synchronized(glDrawableFactories) { - for(int i=0; i() { - public Object run() { - Runtime.getRuntime().addShutdownHook(factoryShutdownHook); - return null; - } - }); - factoryShutdownHookRegistered = true; - } - protected GLDrawableFactory() { synchronized(glDrawableFactories) { glDrawableFactories.add(this); @@ -266,6 +252,8 @@ public abstract class GLDrawableFactory { protected abstract void destroy(); + public abstract void resetDisplayGamma(); + /** * Retrieve the default device {@link AbstractGraphicsDevice#getConnection() connection}, * {@link AbstractGraphicsDevice#getUnitID() unit ID} and {@link AbstractGraphicsDevice#getUniqueID() unique ID name}. for this factory
        diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index 06e856d41..4ac413545 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -575,16 +575,16 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { rampEntry = 0.0f; gammaRamp[i] = rampEntry; } - registerGammaShutdownHook(); + needsGammaRampReset = true; return setGammaRamp(gammaRamp); } + @Override public synchronized void resetDisplayGamma() { - if (gammaShutdownHook == null) { - throw new IllegalArgumentException("Should not call this unless setDisplayGamma called first"); + if( needsGammaRampReset ) { + resetGammaRamp(originalGammaRamp); + needsGammaRampReset = false; } - resetGammaRamp(originalGammaRamp); - unregisterGammaShutdownHook(); } //------------------------------------------------------ @@ -616,35 +616,6 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { } // 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 - } + private volatile Buffer originalGammaRamp; + private volatile boolean needsGammaRampReset = false; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index b6a052253..bf37b8d0c 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -37,8 +37,10 @@ import java.io.File; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import jogamp.nativewindow.Debug; @@ -108,7 +110,9 @@ public abstract class NativeWindowFactory { private static boolean requiresToolkitLock; private static boolean desktopHasThreadingIssues; + // Shutdown hook mechanism for the factory private static volatile boolean isJVMShuttingDown = false; + private static final List customShutdownHooks = new ArrayList(); /** Creates a new NativeWindowFactory instance. End users do not need to call this method. */ @@ -160,6 +164,11 @@ public abstract class NativeWindowFactory { Platform.initSingleton(); // last resort .. _DEBUG[0] = Debug.debug("NativeWindow"); _tmp[0] = Debug.getProperty("nativewindow.ws.name", true); + Runtime.getRuntime().addShutdownHook( + new Thread(new Runnable() { + public void run() { + NativeWindowFactory.shutdown(true); + } }, "NativeWindowFactory_ShutdownHook" ) ) ; return null; } } ) ; @@ -204,6 +213,72 @@ public abstract class NativeWindowFactory { } } + /** Returns true if the JVM is shutting down, otherwise false. */ + public static final boolean isJVMShuttingDown() { return isJVMShuttingDown; } + + /** + * Add a custom shutdown hook to be performed at JVM shutdown before shutting down NativeWindowFactory instance. + * + * @param head if true add runnable at the start, otherwise at the end + * @param runnable runnable to be added. + */ + public static void addCustomShutdownHook(boolean head, Runnable runnable) { + synchronized( customShutdownHooks ) { + if( !customShutdownHooks.contains( runnable ) ) { + if( head ) { + customShutdownHooks.add(0, runnable); + } else { + customShutdownHooks.add( runnable ); + } + } + } + } + + /** + * Cleanup resources at JVM shutdown + */ + public static synchronized void shutdown(boolean _isJVMShuttingDown) { + isJVMShuttingDown = _isJVMShuttingDown; + if(DEBUG) { + System.err.println("NativeWindowFactory.shutdown() START: JVM Shutdown "+isJVMShuttingDown+", on thread "+Thread.currentThread().getName()); + } + synchronized(customShutdownHooks) { + final int cshCount = customShutdownHooks.size(); + for(int i=0; i < cshCount; i++) { + try { + if( DEBUG ) { + System.err.println("NativeWindowFactory.shutdown - customShutdownHook #"+(i+1)+"/"+cshCount); + } + customShutdownHooks.get(i).run(); + } catch(Throwable t) { + System.err.println("NativeWindowFactory.shutdown: Catched "+t.getClass().getName()+" during customShutdownHook #"+(i+1)+"/"+cshCount); + if( DEBUG ) { + t.printStackTrace(); + } + } + } + customShutdownHooks.clear(); + } + if(DEBUG) { + System.err.println("NativeWindowFactory.shutdown(): Post customShutdownHook"); + } + + if(initialized) { + initialized = false; + if(null != registeredFactories) { + registeredFactories.clear(); + registeredFactories = null; + } + GraphicsConfigurationFactory.shutdown(); + } + + shutdownNativeImpl(NativeWindowFactory.class.getClassLoader()); // always re-shutdown + // SharedResourceToolkitLock.shutdown(DEBUG); // not used yet + if(DEBUG) { + System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() END JVM Shutdown "+isJVMShuttingDown); + } + } + private static void shutdownNativeImpl(final ClassLoader cl) { final String clazzName; if( TYPE_X11 == nativeWindowingTypePure ) { @@ -310,29 +385,6 @@ public abstract class NativeWindowFactory { } } - public static synchronized void shutdown(boolean _isJVMShuttingDown) { - isJVMShuttingDown = _isJVMShuttingDown; - if(DEBUG) { - System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() START: JVM Shutdown "+isJVMShuttingDown); - } - if(initialized) { - initialized = false; - if(null != registeredFactories) { - registeredFactories.clear(); - registeredFactories = null; - } - GraphicsConfigurationFactory.shutdown(); - } - shutdownNativeImpl(NativeWindowFactory.class.getClassLoader()); // always re-shutdown - // SharedResourceToolkitLock.shutdown(DEBUG); // not used yet - if(DEBUG) { - System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() END JVM Shutdown "+isJVMShuttingDown); - } - } - - /** Returns true if the JVM is shutting down, otherwise false. */ - public static final boolean isJVMShuttingDown() { return isJVMShuttingDown; } - /** @return true if the underlying toolkit requires locking, otherwise false. */ public static boolean requiresToolkitLock() { return requiresToolkitLock; -- cgit v1.2.3 From cb7118fc875b6722803e4b11d5681671962a8d3a Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 23 Jun 2013 20:15:38 +0200 Subject: Fix NewtCanvasAWT focus traversal for Java7 (Take 2): Commit 70bf3a4ec44504b86294a332255aaae8d2e86bf4 was not sufficient. Commit 70bf3a4ec44504b86294a332255aaae8d2e86bf4 did not work out on Windows. Solution now gathers the next or previous 'to be focused' component, using the FocusTraversalPolicy of the visible/focusable/enabled container. Then we simply request it's focus. Works w/ Java7 on Linux and Windows. --- make/scripts/tests-win.bat | 4 +-- make/scripts/tests-x64-dbg.bat | 3 +- .../classes/jogamp/nativewindow/awt/AWTMisc.java | 39 ++++++++++++++++++++++ .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 19 ++++------- 4 files changed, 50 insertions(+), 15 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests-win.bat b/make/scripts/tests-win.bat index bcec0c5b6..bdef9cc10 100755 --- a/make/scripts/tests-win.bat +++ b/make/scripts/tests-win.bat @@ -55,7 +55,7 @@ REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.awt.TestIsRealizedCon REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT -time 30000 REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT %* -scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* +REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 4000 -x 10 -y 10 -width 100 -height 100 -screen 0 REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 40000 -width 100 -height 100 -screen 0 %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT -time 5000 @@ -84,7 +84,7 @@ REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenti REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cAWT -time 50000 REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03AWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03bAWT -time 100000 -REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT %* +scripts\java-win.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01AWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01aSWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting04AWT %* diff --git a/make/scripts/tests-x64-dbg.bat b/make/scripts/tests-x64-dbg.bat index a370ebfc8..cb40125f2 100755 --- a/make/scripts/tests-x64-dbg.bat +++ b/make/scripts/tests-x64-dbg.bat @@ -27,7 +27,7 @@ REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" REM set D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.CapabilitiesChooser -Djogl.debug.GLProfile" REM set D_ARGS="-Djogamp.debug.IOUtil" "-Djogl.debug.GLSLCode" "-Djogl.debug.GLMediaPlayer" REM set D_ARGS="-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" "-Djogl.debug.GLSLCode" -set D_ARGS="-Djogl.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.ProcAddressHelper" "-Djogamp.debug.NativeLibrary" "-Djogamp.debug.NativeLibrary.Lookup" "-Djogamp.debug.JNILibLoader" "-Djogamp.debug.TempJarCache" "-Djogamp.debug.JarUtil" +REM set D_ARGS="-Djogl.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.ProcAddressHelper" "-Djogamp.debug.NativeLibrary" "-Djogamp.debug.NativeLibrary.Lookup" "-Djogamp.debug.JNILibLoader" "-Djogamp.debug.TempJarCache" "-Djogamp.debug.JarUtil" REM set D_ARGS="-Djogl.debug.ExtensionAvailabilityCache" "-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.ProcAddressHelper=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.NativeLibrary=true" REM set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.ExtensionAvailabilityCache" "-Djogamp.debug.ProcAddressHelper=true" @@ -41,6 +41,7 @@ REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLC REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch" "-Djogl.windows.useWGLVersionOf5WGLGDIFuncSet" REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch" REM set D_ARGS="-Dnewt.debug.Window" +set D_ARGS="-Dnewt.debug.Window.KeyEvent" "-Dnewt.debug.Window" REM set D_ARGS="-Dnewt.debug.Window.KeyEvent" REM set D_ARGS="-Dnewt.debug.Window.MouseEvent" REM set D_ARGS="-Dnewt.debug.Window.MouseEvent" "-Dnewt.debug.Window.KeyEvent" diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java index d77cd75ef..2524f107a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java +++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java @@ -27,6 +27,7 @@ */ package jogamp.nativewindow.awt; +import java.awt.FocusTraversalPolicy; import java.awt.Window; import java.awt.Component; import java.awt.Container; @@ -68,6 +69,44 @@ public class AWTMisc { return (Container) c; } + public static Component getNextFocus(Component comp) { + Container focusContainer = comp.getFocusCycleRootAncestor(); + while ( focusContainer != null && + ( !focusContainer.isShowing() || !focusContainer.isFocusable() || !focusContainer.isEnabled() ) ) + { + comp = focusContainer; + focusContainer = comp.getFocusCycleRootAncestor(); + } + Component next = null; + if (focusContainer != null) { + final FocusTraversalPolicy policy = focusContainer.getFocusTraversalPolicy(); + next = policy.getComponentAfter(focusContainer, comp); + if (next == null) { + next = policy.getDefaultComponent(focusContainer); + } + } + return next; + } + + public static Component getPrevFocus(Component comp) { + Container focusContainer = comp.getFocusCycleRootAncestor(); + while ( focusContainer != null && + ( !focusContainer.isShowing() || !focusContainer.isFocusable() || !focusContainer.isEnabled() ) ) + { + comp = focusContainer; + focusContainer = comp.getFocusCycleRootAncestor(); + } + Component prev = null; + if (focusContainer != null) { + final FocusTraversalPolicy policy = focusContainer.getFocusTraversalPolicy(); + prev = policy.getComponentBefore(focusContainer, comp); + if (prev == null) { + prev = policy.getDefaultComponent(focusContainer); + } + } + return prev; + } + /** * Issue this when your non AWT toolkit gains focus to clear AWT menu path */ diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index e5db8fd14..dd8939e43 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -31,6 +31,7 @@ package com.jogamp.newt.awt; import java.awt.AWTKeyStroke; import java.awt.Canvas; +import java.awt.Component; import java.awt.Graphics; import java.awt.GraphicsConfiguration; import java.awt.KeyboardFocusManager; @@ -222,26 +223,20 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto final Set fwdKeys = keyboardFocusManager.getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS); final Set bwdKeys = keyboardFocusManager.getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS); if(fwdKeys.contains(ks)) { + final Component nextFocus = AWTMisc.getNextFocus(NewtCanvasAWT.this); if(DEBUG) { - System.err.println("NewtCanvasAWT.focusKey (fwd): "+ks+", current focusOwner "+keyboardFocusManager.getFocusOwner()+", hasFocus: "+hasFocus()); + System.err.println("NewtCanvasAWT.focusKey (fwd): "+ks+", current focusOwner "+keyboardFocusManager.getFocusOwner()+", hasFocus: "+hasFocus()+", nextFocus "+nextFocus); } // Newt-EDT -> AWT-EDT may freeze Window's native peer requestFocus. - if(!hasFocus()) { - // Acquire the AWT focus 1st for proper AWT traversal - NewtCanvasAWT.super.requestFocus(); - } - NewtCanvasAWT.this.transferFocus(); + nextFocus.requestFocus(); suppress = true; } else if(bwdKeys.contains(ks)) { + final Component prevFocus = AWTMisc.getPrevFocus(NewtCanvasAWT.this); if(DEBUG) { - System.err.println("NewtCanvasAWT.focusKey (bwd): "+ks+", current focusOwner "+keyboardFocusManager.getFocusOwner()+", hasFocus: "+hasFocus()); + System.err.println("NewtCanvasAWT.focusKey (bwd): "+ks+", current focusOwner "+keyboardFocusManager.getFocusOwner()+", hasFocus: "+hasFocus()+", prevFocus "+prevFocus); } // Newt-EDT -> AWT-EDT may freeze Window's native peer requestFocus. - if(!hasFocus()) { - // Acquire the AWT focus 1st for proper AWT traversal - NewtCanvasAWT.super.requestFocus(); - } - NewtCanvasAWT.this.transferFocusBackward(); + prevFocus.requestFocus(); suppress = true; } } -- cgit v1.2.3 From 62f9525a9caba51fc4484c2ab47d64b516dc9d43 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Mon, 24 Jun 2013 06:50:40 +0200 Subject: Refine cb7118fc875b6722803e4b11d5681671962a8d3a: Unify get next/prev focus component method. --- .../classes/jogamp/nativewindow/awt/AWTMisc.java | 31 +++++++--------------- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 4 +-- 2 files changed, 12 insertions(+), 23 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java index 2524f107a..66be82a44 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java +++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java @@ -69,7 +69,15 @@ public class AWTMisc { return (Container) c; } - public static Component getNextFocus(Component comp) { + /** + * Traverse to the next forward or backward component using the + * container's FocusTraversalPolicy. + * + * @param comp the assumed current focuse component + * @param forward if true, returns the next focus component, otherwise the previous one. + * @return + */ + public static Component getNextFocus(Component comp, boolean forward) { Container focusContainer = comp.getFocusCycleRootAncestor(); while ( focusContainer != null && ( !focusContainer.isShowing() || !focusContainer.isFocusable() || !focusContainer.isEnabled() ) ) @@ -80,7 +88,7 @@ public class AWTMisc { Component next = null; if (focusContainer != null) { final FocusTraversalPolicy policy = focusContainer.getFocusTraversalPolicy(); - next = policy.getComponentAfter(focusContainer, comp); + next = forward ? policy.getComponentAfter(focusContainer, comp) : policy.getComponentBefore(focusContainer, comp); if (next == null) { next = policy.getDefaultComponent(focusContainer); } @@ -88,25 +96,6 @@ public class AWTMisc { return next; } - public static Component getPrevFocus(Component comp) { - Container focusContainer = comp.getFocusCycleRootAncestor(); - while ( focusContainer != null && - ( !focusContainer.isShowing() || !focusContainer.isFocusable() || !focusContainer.isEnabled() ) ) - { - comp = focusContainer; - focusContainer = comp.getFocusCycleRootAncestor(); - } - Component prev = null; - if (focusContainer != null) { - final FocusTraversalPolicy policy = focusContainer.getFocusTraversalPolicy(); - prev = policy.getComponentBefore(focusContainer, comp); - if (prev == null) { - prev = policy.getDefaultComponent(focusContainer); - } - } - return prev; - } - /** * Issue this when your non AWT toolkit gains focus to clear AWT menu path */ diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index dd8939e43..6ba7a1a61 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -223,7 +223,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto final Set fwdKeys = keyboardFocusManager.getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS); final Set bwdKeys = keyboardFocusManager.getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS); if(fwdKeys.contains(ks)) { - final Component nextFocus = AWTMisc.getNextFocus(NewtCanvasAWT.this); + final Component nextFocus = AWTMisc.getNextFocus(NewtCanvasAWT.this, true /* forward */); if(DEBUG) { System.err.println("NewtCanvasAWT.focusKey (fwd): "+ks+", current focusOwner "+keyboardFocusManager.getFocusOwner()+", hasFocus: "+hasFocus()+", nextFocus "+nextFocus); } @@ -231,7 +231,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto nextFocus.requestFocus(); suppress = true; } else if(bwdKeys.contains(ks)) { - final Component prevFocus = AWTMisc.getPrevFocus(NewtCanvasAWT.this); + final Component prevFocus = AWTMisc.getNextFocus(NewtCanvasAWT.this, false /* forward */); if(DEBUG) { System.err.println("NewtCanvasAWT.focusKey (bwd): "+ks+", current focusOwner "+keyboardFocusManager.getFocusOwner()+", hasFocus: "+hasFocus()+", prevFocus "+prevFocus); } -- cgit v1.2.3 From 1c717a781702b0decb0c4da71a9dadc2a8255d5b Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 30 Jun 2013 03:52:16 +0200 Subject: Add Comparable: Point*, Dimension*, Rectangle*, SurfaceSize* and MonitorMode* ; Sort List in descending order to be well determined. Add Comparable: Point*, Dimension*, Rectangle*, SurfaceSize* and MonitorMode*: - Compare square values - See API doc for order of special semantics (flags, rotation, ..) Sort List in descending order to be well determined: - Removes order by native mode id, give user a reliable natural order. --- make/scripts/tests.sh | 5 +- .../javax/media/nativewindow/util/Dimension.java | 13 +++ .../nativewindow/util/DimensionImmutable.java | 11 +- .../javax/media/nativewindow/util/Point.java | 13 +++ .../media/nativewindow/util/PointImmutable.java | 11 +- .../javax/media/nativewindow/util/Rectangle.java | 25 +++++ .../nativewindow/util/RectangleImmutable.java | 11 +- .../javax/media/nativewindow/util/SurfaceSize.java | 26 ++++- .../classes/com/jogamp/newt/MonitorDevice.java | 4 + src/newt/classes/com/jogamp/newt/MonitorMode.java | 115 +++++++++++++++++++-- src/newt/classes/com/jogamp/newt/Screen.java | 4 + .../com/jogamp/newt/util/MonitorModeUtil.java | 11 ++ src/newt/classes/jogamp/newt/ScreenImpl.java | 8 +- .../test/junit/newt/mm/TestScreenMode00aNEWT.java | 34 +++++- 14 files changed, 271 insertions(+), 20 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 84e536017..5acced4af 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -284,7 +284,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelsAWT $* -testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NewtCanvasAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NEWT $* @@ -400,13 +400,14 @@ testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasA #testnoawt com.jogamp.opengl.test.junit.newt.TestGLWindowInvisiblePointer01NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle01NEWT #testnoawt com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle02NEWT -#testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode00aNEWT $* +testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode00aNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode00bNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01aNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01bNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01cNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01dNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode02aNEWT $* +#testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode02bNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.mm.ManualScreenMode03aNEWT $* #testnoawt -Djava.awt.headless=true com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestGLWindowWarpPointer01NEWT $* diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java index 4fae98f08..b52414146 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java @@ -84,6 +84,19 @@ public class Dimension implements Cloneable, DimensionImmutable { return new String(width+" x "+height); } + @Override + public int compareTo(final DimensionImmutable d) { + final int tsq = width*height; + final int xsq = d.getWidth()*d.getHeight(); + + if(tsq > xsq) { + return 1; + } else if(tsq < xsq) { + return -1; + } + return 0; + } + @Override public boolean equals(Object obj) { if(this == obj) { return true; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java index d14e94c10..22bd3f48b 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java @@ -37,12 +37,21 @@ import com.jogamp.common.type.WriteCloneable; *
      • height
      • * */ -public interface DimensionImmutable extends WriteCloneable { +public interface DimensionImmutable extends WriteCloneable, Comparable { int getHeight(); int getWidth(); + /** + *

        + * Compares square of size. + *

        + * {@inheritDoc} + */ + @Override + public int compareTo(final DimensionImmutable d); + /** * Checks whether two dimensions objects are equal. Two instances * of DimensionReadOnly are equal if two components diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java index 8e6caf72b..a30d3030e 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java @@ -54,6 +54,19 @@ public class Point implements Cloneable, PointImmutable { } } + @Override + public int compareTo(final PointImmutable d) { + final int sq = x*y; + final int xsq = d.getX()*d.getY(); + + if(sq > xsq) { + return 1; + } else if(sq < xsq) { + return -1; + } + return 0; + } + @Override public boolean equals(Object obj) { if(this == obj) { return true; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java index d7eb0e7b4..b00329bb5 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java @@ -32,12 +32,21 @@ package javax.media.nativewindow.util; import com.jogamp.common.type.WriteCloneable; /** Immutable Point interface */ -public interface PointImmutable extends WriteCloneable { +public interface PointImmutable extends WriteCloneable, Comparable { int getX(); int getY(); + /** + *

        + * Compares the square of the position. + *

        + * {@inheritDoc} + */ + @Override + public int compareTo(final PointImmutable d); + /** * Checks whether two points objects are equal. Two instances * of PointReadOnly are equal if the two components diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java index 8e6fc8e36..7576f4ec7 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java @@ -142,6 +142,31 @@ public class Rectangle implements Cloneable, RectangleImmutable { return sqI / sqT; } + @Override + public int compareTo(final RectangleImmutable d) { + { + final int sq = width*height; + final int xsq = d.getWidth()*d.getHeight(); + + if(sq > xsq) { + return 1; + } else if(sq < xsq) { + return -1; + } + } + { + final int sq = x*y; + final int xsq = d.getX()*d.getY(); + + if(sq > xsq) { + return 1; + } else if(sq < xsq) { + return -1; + } + } + return 0; + } + @Override public boolean equals(Object obj) { if(this == obj) { return true; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java index 7531989de..440d9e000 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java @@ -31,7 +31,7 @@ package javax.media.nativewindow.util; import com.jogamp.common.type.WriteCloneable; /** Immutable Rectangle interface */ -public interface RectangleImmutable extends WriteCloneable { +public interface RectangleImmutable extends WriteCloneable, Comparable { int getHeight(); @@ -61,6 +61,15 @@ public interface RectangleImmutable extends WriteCloneable { */ float coverage(RectangleImmutable r); + /** + *

        + * Compares square of size 1st, if equal the square of position. + *

        + * {@inheritDoc} + */ + @Override + public int compareTo(final RectangleImmutable d); + /** * Checks whether two rect objects are equal. Two instances * of Rectangle are equal if the four integer values diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java index d7e451af8..3084816a5 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java @@ -29,13 +29,14 @@ package javax.media.nativewindow.util; -/** Immutable SurfaceSize Class, consisting of it's read only components:
        +/** + * Immutable SurfaceSize Class, consisting of it's read only components:
        *
          *
        • {@link javax.media.nativewindow.util.DimensionImmutable} size in pixels
        • *
        • bits per pixel
        • *
        */ -public class SurfaceSize { +public class SurfaceSize implements Comparable { final DimensionImmutable resolution; final int bitsPerPixel; @@ -59,6 +60,27 @@ public class SurfaceSize { return new String("[ "+resolution+" x "+bitsPerPixel+" bpp ]"); } + /** + *

        + * Compares {@link DimensionImmutable#compareTo(DimensionImmutable) resolution} 1st, if equal the bitsPerPixel. + *

        + * {@inheritDoc} + */ + @Override + public int compareTo(final SurfaceSize ssz) { + final int rres = resolution.compareTo(ssz.getResolution()); + if( 0 != rres ) { + return rres; + } + final int xbpp = ssz.getBitsPerPixel(); + if(bitsPerPixel > xbpp) { + return 1; + } else if(bitsPerPixel < xbpp) { + return -1; + } + return 0; + } + /** * Checks whether two size objects are equal. Two instances * of SurfaceSize are equal if the two components diff --git a/src/newt/classes/com/jogamp/newt/MonitorDevice.java b/src/newt/classes/com/jogamp/newt/MonitorDevice.java index 4b0a760a4..8bc7f40e3 100644 --- a/src/newt/classes/com/jogamp/newt/MonitorDevice.java +++ b/src/newt/classes/com/jogamp/newt/MonitorDevice.java @@ -129,6 +129,10 @@ public abstract class MonitorDevice { /** * Returns a list of immutable {@link MonitorMode}s supported by this monitor. *

        + * The list is ordered in descending order, + * see {@link MonitorMode#compareTo(MonitorMode)}. + *

        + *

        * Use w/ care, it's not a copy! *

        */ diff --git a/src/newt/classes/com/jogamp/newt/MonitorMode.java b/src/newt/classes/com/jogamp/newt/MonitorMode.java index 914aa880f..dc7ae2c03 100644 --- a/src/newt/classes/com/jogamp/newt/MonitorMode.java +++ b/src/newt/classes/com/jogamp/newt/MonitorMode.java @@ -28,6 +28,8 @@ package com.jogamp.newt; +import java.util.Comparator; + import javax.media.nativewindow.util.DimensionImmutable; import javax.media.nativewindow.util.RectangleImmutable; import javax.media.nativewindow.util.SurfaceSize; @@ -108,22 +110,36 @@ import com.jogamp.newt.util.MonitorModeUtil; monitor.setCurrentMode(mm); * */ -public class MonitorMode { +public class MonitorMode implements Comparable { + + /** Comparator for 2 {@link MonitorMode}s, following comparison order as described in {@link MonitorMode#compareTo(MonitorMode)}, returning the ascending order. */ + public static final Comparator monitorModeComparator = new Comparator() { + public int compare(MonitorMode mm1, MonitorMode mm2) { + return mm1.compareTo(mm2); + } }; + + /** Comparator for 2 {@link MonitorMode}s, following comparison order as described in {@link MonitorMode#compareTo(MonitorMode)}, returning the descending order. */ + public static final Comparator monitorModeComparatorInv = new Comparator() { + public int compare(MonitorMode mm1, MonitorMode mm2) { + return mm2.compareTo(mm1); + } }; + /** - * Immutable surfaceSize and refreshRate Class, consisting of it's read only components:
        + * Immutable surfaceSize, flags and refreshRate Class, consisting of it's read only components:
        *
          *
        • nativeId
        • *
        • {@link SurfaceSize} surface memory size
        • + *
        • flags
        • *
        • refresh rate
        • *
        */ - public static class SizeAndRRate { + public static class SizeAndRRate implements Comparable { /** Non rotated surface size */ public final SurfaceSize surfaceSize; - /** Vertical refresh rate */ - public final float refreshRate; /** Mode bitfield flags, i.e. {@link #FLAG_DOUBLESCAN}, {@link #FLAG_INTERLACE}, .. */ public final int flags; + /** Vertical refresh rate */ + public final float refreshRate; public final int hashCode; public SizeAndRRate(SurfaceSize surfaceSize, float refreshRate, int flags) { @@ -131,8 +147,8 @@ public class MonitorMode { throw new IllegalArgumentException("surfaceSize must be set ("+surfaceSize+")"); } this.surfaceSize=surfaceSize; - this.refreshRate=refreshRate; this.flags = flags; + this.refreshRate=refreshRate; this.hashCode = getHashCode(); } @@ -160,6 +176,49 @@ public class MonitorMode { return new String(surfaceSize+" @ "+refreshRate+" Hz, flags ["+flags2String(flags).toString()+"]"); } + /** + *

        + * Compares {@link SurfaceSize#compareTo(SurfaceSize) surfaceSize} 1st, then {@link #flags}, then {@link #refreshRate}. + *

        + *

        + * Flags are compared as follows: + *

        +         *   NONE > DOUBLESCAN > INTERLACE
        +         * 
        + *

        + *

        + * Refresh rate differences of < 0.01 are considered equal (epsilon). + *

        + * {@inheritDoc} + */ + @Override + public int compareTo(final SizeAndRRate sszr) { + final int rssz = surfaceSize.compareTo(sszr.surfaceSize); + if( 0 != rssz ) { + return rssz; + } + final int tflags = 0 == flags ? Integer.MAX_VALUE : flags; // normalize NONE + final int xflags = 0 == sszr.flags ? Integer.MAX_VALUE : sszr.flags; // normalize NONE + if( tflags == xflags ) { + final float refreshEpsilon = 0.01f; // reasonable sorting granularity of refresh rate + final float drate = refreshRate - sszr.refreshRate; + if( Math.abs(drate) < refreshEpsilon ) { + return 0; + } else if( drate > refreshEpsilon ) { + return 1; + } else { + return -1; + } + } else { + if(tflags > xflags) { + return 1; + } else if(tflags < xflags) { + return -1; + } + return 0; + } + } + /** * Tests equality of two {@link SizeAndRRate} objects * by evaluating equality of it's components:
        @@ -174,8 +233,8 @@ public class MonitorMode { if (obj instanceof SizeAndRRate) { final SizeAndRRate p = (SizeAndRRate)obj; return surfaceSize.equals(p.surfaceSize) && - refreshRate == p.refreshRate && - flags == p.flags ; + flags == p.flags && + refreshRate == p.refreshRate ; } return false; } @@ -184,8 +243,8 @@ public class MonitorMode { * Returns a combined hash code of it's elements:
        *
          *
        • surfaceSize
        • - *
        • refreshRate
        • *
        • flags
        • + *
        • refreshRate
        • *
        */ public final int hashCode() { @@ -194,8 +253,8 @@ public class MonitorMode { private final int getHashCode() { // 31 * x == (x << 5) - x int hash = 31 + surfaceSize.hashCode(); - hash = ((hash << 5) - hash) + (int)(refreshRate*100.0f); hash = ((hash << 5) - hash) + flags; + hash = ((hash << 5) - hash) + (int)(refreshRate*100.0f); return hash; } } @@ -305,6 +364,42 @@ public class MonitorMode { return "[Id "+Display.toHexString(nativeId)+", " + sizeAndRRate + ", " + rotation + " degr]"; } + /** + *

        + * Compares {@link SizeAndRRate#compareTo(SizeAndRRate) sizeAndRRate} 1st, then {@link #rotation}. + *

        + *

        + * Rotation is compared inverted, i.e. 360 - rotation, + * so the lowest rotation reflects a higher value. + *

        + *

        + * Order of comparing MonitorMode: + *

          + *
        • resolution
        • + *
        • bits per pixel
        • + *
        • flags
        • + *
        • refresh rate
        • + *
        • rotation
        • + *
        + *

        + * {@inheritDoc} + */ + @Override + public int compareTo(final MonitorMode mm) { + final int c = sizeAndRRate.compareTo(mm.sizeAndRRate); + if( 0 != c ) { + return c; + } + final int trot = 360 - rotation; // normalize rotation + final int xrot = 360 - mm.rotation; // normalize rotation + if(trot > xrot) { + return 1; + } else if(trot < xrot) { + return -1; + } + return 0; + } + /** * Tests equality of two {@link MonitorMode} objects * by evaluating equality of it's components:
        diff --git a/src/newt/classes/com/jogamp/newt/Screen.java b/src/newt/classes/com/jogamp/newt/Screen.java index f56aff964..9b349b527 100644 --- a/src/newt/classes/com/jogamp/newt/Screen.java +++ b/src/newt/classes/com/jogamp/newt/Screen.java @@ -164,6 +164,10 @@ public abstract class Screen { /** * Return a list of all {@link MonitorMode}s for all {@link MonitorDevice}s. + *

        + * The list is ordered in descending order, + * see {@link MonitorMode#compareTo(MonitorMode)}. + *

        */ public abstract List getMonitorModes(); diff --git a/src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java b/src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java index 16ffe754f..c30b427d6 100644 --- a/src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java +++ b/src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java @@ -31,7 +31,9 @@ package com.jogamp.newt.util; import com.jogamp.newt.MonitorMode; import java.util.ArrayList; +import java.util.Collections; import java.util.List; + import javax.media.nativewindow.util.DimensionImmutable; import javax.media.nativewindow.util.SurfaceSize; @@ -68,6 +70,15 @@ public class MonitorModeUtil { return null; } + /** Sort the given {@link MonitorMode} collection w/ {@link MonitorMode#compareTo(MonitorMode)} function. */ + public static void sort(List monitorModes, boolean ascendingOrder) { + if( ascendingOrder ) { + Collections.sort(monitorModes); + } else { + Collections.sort(monitorModes, MonitorMode.monitorModeComparatorInv); + } + } + /** * * @param monitorModes diff --git a/src/newt/classes/jogamp/newt/ScreenImpl.java b/src/newt/classes/jogamp/newt/ScreenImpl.java index f63d1499e..28f3e876c 100644 --- a/src/newt/classes/jogamp/newt/ScreenImpl.java +++ b/src/newt/classes/jogamp/newt/ScreenImpl.java @@ -52,6 +52,7 @@ import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; import com.jogamp.newt.event.MonitorEvent; import com.jogamp.newt.event.MonitorModeListener; +import com.jogamp.newt.util.MonitorModeUtil; public abstract class ScreenImpl extends Screen implements MonitorModeListener { protected static final boolean DEBUG_TEST_SCREENMODE_DISABLED = Debug.isPropertyDefined("newt.test.Screen.disableScreenMode", true); @@ -536,6 +537,11 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { final MonitorDevice monitor = getVirtualMonitorDevice(cache, 0, mode); cache.monitorDevices.getOrAdd(monitor); } + // Sort MonitorModes (all and per device) in descending order - default! + MonitorModeUtil.sort(cache.monitorModes.getData(), false /* ascendingOrder*/); + for(Iterator iMonitor=cache.monitorDevices.iterator(); iMonitor.hasNext(); ) { + MonitorModeUtil.sort(iMonitor.next().getSupportedModes(), false /* ascendingOrder*/); + } if(DEBUG) { int i=0; for(Iterator iMode=cache.monitorModes.iterator(); iMode.hasNext(); i++) { @@ -550,7 +556,7 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { System.err.println("["+i+"]["+j+"]: "+iMode.next()); } } - } + } sms = new ScreenMonitorState(cache.monitorDevices, cache.monitorModes); ScreenMonitorState.mapScreenMonitorState(this.getFQName(), sms); } diff --git a/src/test/com/jogamp/opengl/test/junit/newt/mm/TestScreenMode00aNEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/mm/TestScreenMode00aNEWT.java index 123199427..7a15971d5 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/mm/TestScreenMode00aNEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/mm/TestScreenMode00aNEWT.java @@ -41,7 +41,9 @@ import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.MonitorMode; import com.jogamp.newt.Screen; +import com.jogamp.newt.util.MonitorModeUtil; import com.jogamp.opengl.test.junit.util.UITestCase; + import java.util.Iterator; import java.util.List; import javax.media.nativewindow.util.Dimension; @@ -56,6 +58,9 @@ import jogamp.newt.MonitorModeProps; /** * Validating consistency of MonitorMode data from Screen (all modes) * and from a particular MonitorDevice. + *

        + * Also validates the descending order of the given MonitorMode lists. + *

        */ public class TestScreenMode00aNEWT extends UITestCase { static int screenIdx = 0; @@ -130,8 +135,27 @@ public class TestScreenMode00aNEWT extends UITestCase { Assert.assertTrue(allMonitorModes.size()>0); { int i=0; + MonitorMode mmPre = null; + for(Iterator iMode=allMonitorModes.iterator(); iMode.hasNext(); i++) { + final MonitorMode mm = iMode.next(); + System.err.println(String.format("All-0[%03d]: %s", i, mm)); + if( null != mmPre ) { + Assert.assertTrue("Wrong order", mmPre.compareTo(mm) >= 0); + } + mmPre = mm; + } + } + MonitorModeUtil.sort(allMonitorModes, true /* ascendingOrder*/); + { + int i=0; + MonitorMode mmPre = null; for(Iterator iMode=allMonitorModes.iterator(); iMode.hasNext(); i++) { - System.err.println("All["+i+"]: "+iMode.next()); + final MonitorMode mm = iMode.next(); + System.err.println(String.format("All-1[%03d]: %s", i, mm)); + if( null != mmPre ) { + Assert.assertTrue("Wrong order", mmPre.compareTo(mm) <= 0); + } + mmPre = mm; } } @@ -144,8 +168,14 @@ public class TestScreenMode00aNEWT extends UITestCase { List modes = monitor.getSupportedModes(); Assert.assertTrue(modes.size()>0); int i=0; + MonitorMode mmPre = null; for(Iterator iMode=modes.iterator(); iMode.hasNext(); i++) { - System.err.println("["+j+"]["+i+"]: "+iMode.next()); + final MonitorMode mm = iMode.next(); + System.err.println(String.format("[%02d][%03d]: %s", j, i, mm)); + if( null != mmPre ) { + Assert.assertTrue("Wrong order", mmPre.compareTo(mm) >= 0); + } + mmPre = mm; } Assert.assertTrue(allMonitorModes.containsAll(modes)); -- cgit v1.2.3 From 95ffc6f73b460a24e8f117060de1d80ec85e4c25 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 9 Jul 2013 16:30:45 +0200 Subject: NEWT MonitorMode test cases: Add X11 XRandR commandline reset to UITestCase's AfterClass if available (X11). In case a MonitorMode test case fails, force XRandR reset '-s 0 -o normal' at end of test class if X11. Unit Test: TestScreenMode00cNEWT --- make/scripts/tests-win.bat | 3 +- make/scripts/tests.sh | 5 +- .../media/nativewindow/NativeWindowFactory.java | 5 +- .../test/junit/newt/mm/TestScreenMode00cNEWT.java | 221 +++++++++++++++++++++ .../jogamp/opengl/test/junit/util/MiscUtils.java | 30 +++ .../jogamp/opengl/test/junit/util/UITestCase.java | 20 ++ 6 files changed, 280 insertions(+), 4 deletions(-) create mode 100644 src/test/com/jogamp/opengl/test/junit/newt/mm/TestScreenMode00cNEWT.java (limited to 'src/nativewindow') diff --git a/make/scripts/tests-win.bat b/make/scripts/tests-win.bat index da531dd66..872ba3716 100755 --- a/make/scripts/tests-win.bat +++ b/make/scripts/tests-win.bat @@ -115,10 +115,11 @@ REM scripts\java-win.bat com.jogamp.opengl.test.junit.nativewindow.TestRecursive REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.mm.TestScreenMode00aNEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.mm.TestScreenMode00bNEWT %* +scripts\java-win.bat com.jogamp.opengl.test.junit.newt.mm.TestScreenMode00cNEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01aNEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01bNEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01cNEWT %* -scripts\java-win.bat com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01dNEWT %* +REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01dNEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.mm.TestScreenMode02aNEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.mm.TestScreenMode02bNEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.mm.ManualScreenMode03sNEWT %* diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index a5ce8d2e9..bc37f2845 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -152,7 +152,7 @@ function jrun() { #D_ARGS="-Djogl.debug.GLProfile" #D_ARGS="-Dnativewindow.debug.NativeWindow -Dnewt.debug.Window -Dnewt.debug.Screen -Dnewt.debug.Display" #D_ARGS="-Djogl.debug.GLCanvas -Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT -Djogl.debug.Animator" - D_ARGS="-Dnewt.debug.Display -Dnewt.debug.EDT -Dnewt.debug.Window" + #D_ARGS="-Dnewt.debug.Display -Dnewt.debug.EDT -Dnewt.debug.Window" #D_ARGS="-Dnewt.debug.EDT -Dnewt.debug.Window -Djogl.debug.GLContext" #D_ARGS="-Dnativewindow.debug.X11Util.XErrorStackDump -Dnativewindow.debug.X11Util.TraceDisplayLifecycle -Dnativewindow.debug.X11Util" #D_ARGS="-Dnativewindow.debug.X11Util -Djogl.debug.GLContext -Djogl.debug.GLDrawable -Dnewt.debug=all" @@ -405,6 +405,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle02NEWT #testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode00aNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode00bNEWT $* +testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode00cNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01aNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01bNEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.mm.TestScreenMode01cNEWT $* @@ -515,7 +516,7 @@ function testawtswt() { # # NEWT Parenting (w/ NEWT, AWT or SWT) # -testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $* #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cSwingAWT $* diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index bf37b8d0c..07d1008b4 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -187,7 +187,7 @@ public abstract class NativeWindowFactory { } } - static boolean initialized = false; + private static boolean initialized = false; private static void initSingletonNativeImpl(final ClassLoader cl) { final String clazzName; @@ -295,6 +295,9 @@ public abstract class NativeWindowFactory { } } + /** Returns true if {@link #initSingleton()} has been called w/o subsequent {@link #shutdown(boolean)}. */ + public static synchronized boolean isInitialized() { return initialized; } + /** * Static one time initialization of this factory.
        * This initialization method must be called once by the program or utilizing modules! diff --git a/src/test/com/jogamp/opengl/test/junit/newt/mm/TestScreenMode00cNEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/mm/TestScreenMode00cNEWT.java new file mode 100644 index 000000000..dc3bf3c97 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/newt/mm/TestScreenMode00cNEWT.java @@ -0,0 +1,221 @@ +/** + * Copyright 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.newt.mm; + +import java.io.IOException; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLProfile; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.jogamp.newt.Display; +import com.jogamp.newt.MonitorDevice; +import com.jogamp.newt.NewtFactory; +import com.jogamp.newt.Screen; +import com.jogamp.newt.Window; +import com.jogamp.newt.MonitorMode; +import com.jogamp.newt.opengl.GLWindow; +import com.jogamp.newt.util.MonitorModeUtil; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.MiscUtils; +import com.jogamp.opengl.test.junit.util.UITestCase; + +import java.util.List; + +import javax.media.nativewindow.NativeWindowFactory; +import javax.media.nativewindow.util.Dimension; + +/** + * Tests X11 XRandR MonitorMode reset via {@link UITestCase#resetXRandRIfX11()}. + */ +public class TestScreenMode00cNEWT extends UITestCase { + static GLProfile glp; + static int width, height; + + static final int waitTimeShort = 2000; + static long duration = waitTimeShort; + + @BeforeClass + public static void initClass() { + NativeWindowFactory.initSingleton(); + if( NativeWindowFactory.TYPE_X11 != NativeWindowFactory.getNativeWindowType(true) ) { + setTestSupported(false); + return; + } + width = 100; + height = 100; + glp = GLProfile.getDefault(); + } + + @AfterClass + public static void releaseClass() throws InterruptedException { + Thread.sleep(waitTimeShort); + } + + static Window createWindow(Screen screen, GLCapabilities caps, String name, int x, int y, int width, int height) { + Assert.assertNotNull(caps); + + GLWindow window = GLWindow.create(screen, caps); + // Window window = NewtFactory.createWindow(screen, caps); + window.setTitle(name); + window.setPosition(x, y); + window.setSize(width, height); + window.addGLEventListener(new GearsES2()); + Assert.assertNotNull(window); + window.setVisible(true); + return window; + } + + static void destroyWindow(Window window) throws InterruptedException { + if(null!=window) { + window.destroy(); + Assert.assertTrue(AWTRobotUtil.waitForRealized(window, false)); + } + } + + @Test + public void testScreenModeChange01() throws InterruptedException { + Thread.sleep(waitTimeShort); + + final GLCapabilities caps = new GLCapabilities(glp); + Assert.assertNotNull(caps); + final Display display = NewtFactory.createDisplay(null); // local display + Assert.assertNotNull(display); + final Screen screen = NewtFactory.createScreen(display, 0); // screen 0 + Assert.assertNotNull(screen); + final Window window0 = createWindow(screen, caps, "win0", 0, 0, width, height); + Assert.assertNotNull(window0); + + final List allMonitorModes = screen.getMonitorModes(); + Assert.assertTrue(allMonitorModes.size()>0); + if(allMonitorModes.size()==1) { + // no support .. + System.err.println("Your platform has no MonitorMode change support (all), sorry"); + destroyWindow(window0); + return; + } + + final MonitorDevice monitor = screen.getMonitorDevices().get(0); + + List monitorModes = monitor.getSupportedModes(); + Assert.assertTrue(monitorModes.size()>0); + if(monitorModes.size()==1) { + // no support .. + System.err.println("Your platform has no MonitorMode change support (monitor), sorry"); + destroyWindow(window0); + return; + } + Assert.assertTrue(allMonitorModes.containsAll(monitorModes)); + + final MonitorMode mmSet0 = monitor.queryCurrentMode(); + Assert.assertNotNull(mmSet0); + final MonitorMode mmOrig = monitor.getOriginalMode(); + Assert.assertNotNull(mmOrig); + System.err.println("[0] orig : "+mmOrig); + System.err.println("[0] current: "+mmSet0); + Assert.assertEquals(mmSet0, mmOrig); + + + monitorModes = MonitorModeUtil.filterByFlags(monitorModes, 0); // no interlace, double-scan etc + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByRotation(monitorModes, 0); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByResolution(monitorModes, new Dimension(801, 601)); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + monitorModes = MonitorModeUtil.filterByRate(monitorModes, mmOrig.getRefreshRate()); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + + monitorModes = MonitorModeUtil.getHighestAvailableBpp(monitorModes); + Assert.assertNotNull(monitorModes); + Assert.assertTrue(monitorModes.size()>0); + + // set mode + { + MonitorMode mm = monitorModes.get(0); + System.err.println("[0] set current: "+mm); + final boolean smOk = monitor.setCurrentMode(mm); + MonitorMode mmCurrent = monitor.getCurrentMode(); + System.err.println("[0] has current: "+mmCurrent+", changeOK "+smOk); + Assert.assertTrue(monitor.isModeChangedByUs()); + Assert.assertEquals(mm, mmCurrent); + Assert.assertNotSame(mmOrig, mmCurrent); + Assert.assertEquals(mmCurrent, monitor.queryCurrentMode()); + Assert.assertTrue(smOk); + } + + Thread.sleep(duration); + + Assert.assertEquals(true,display.isNativeValid()); + Assert.assertEquals(true,screen.isNativeValid()); + Assert.assertEquals(true,window0.isNativeValid()); + Assert.assertEquals(true,window0.isVisible()); + + UITestCase.resetXRandRIfX11(); + System.err.println("XRandR Reset :"+monitor.queryCurrentMode()); + validateScreenModeReset(mmOrig, 0); + + destroyWindow(window0); + + Thread.sleep(waitTimeShort); + } + + void validateScreenModeReset(final MonitorMode mmOrig, int mmIdx) { + final Display display = NewtFactory.createDisplay(null); // local display + Assert.assertNotNull(display); + final Screen screen = NewtFactory.createScreen(display, 0); // screen 0 + Assert.assertNotNull(screen); + screen.addReference(); + Assert.assertEquals(true,display.isNativeValid()); + Assert.assertEquals(true,screen.isNativeValid()); + + final MonitorDevice monitor = screen.getMonitorDevices().get(0); + Assert.assertEquals(mmOrig, monitor.queryCurrentMode()); + + screen.removeReference(); + } + + public static void main(String args[]) throws IOException { + for(int i=0; i " + line); + } + } + catch (IOException ioe) { + System.err.println("Catched "+ioe.getClass().getName()+": "+ioe.getMessage()); + ioe.printStackTrace(); + } + } + } } diff --git a/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java b/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java index 82a80ff49..90452ebfb 100644 --- a/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java +++ b/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java @@ -35,6 +35,7 @@ import java.io.InputStreamReader; import java.util.Iterator; import java.util.List; +import javax.media.nativewindow.NativeWindowFactory; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilitiesImmutable; @@ -90,6 +91,24 @@ public abstract class UITestCase { testSupported = v; } + public static void resetXRandRIfX11() { + if( NativeWindowFactory.isInitialized() && NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(true) ) { + try { + final ProcessBuilder pb = new ProcessBuilder("xrandr", "-s", "0", "-o", "normal"); + pb.redirectErrorStream(true); + System.err.println("XRandR Reset cmd: "+pb.command()); + final Process p = pb.start(); + new MiscUtils.StreamDump( p.getInputStream(), "xrandr-reset" ).start(); + p.waitFor(); + System.err.println("XRandR Reset result "+p.exitValue()); + } catch (Exception e) { + System.err.println("Catched "+e.getClass().getName()+": "+e.getMessage()); + e.printStackTrace(); + } + System.err.println("XRandR Reset done"); + } + } + public int getMaxTestNameLen() { if(0 == maxMethodNameLen) { int ml = 0; @@ -125,6 +144,7 @@ public abstract class UITestCase { @AfterClass public static void oneTimeTearDown() { // one-time cleanup code + resetXRandRIfX11(); System.gc(); // force cleanup singletonInstance.unlock(); } -- cgit v1.2.3 From d5599155b28f63a83112d4a4268c2cca246c9e28 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Mon, 15 Jul 2013 13:39:44 +0200 Subject: StringBuffer -> StringBuilder --- src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java | 4 ++-- src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java | 4 ++-- src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java | 4 ++-- src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java | 4 ++-- src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java | 4 ++-- src/nativewindow/classes/javax/media/nativewindow/Capabilities.java | 2 +- .../classes/javax/media/nativewindow/CapabilitiesImmutable.java | 2 +- src/newt/classes/com/jogamp/newt/MonitorMode.java | 4 ++-- src/newt/classes/jogamp/newt/driver/android/NewtVersionActivity.java | 2 +- 9 files changed, 15 insertions(+), 15 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java b/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java index b0fc7f332..2bd45e3e4 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java @@ -189,9 +189,9 @@ public class GLPixelBuffer { private boolean disposed = false; - public StringBuffer toString(StringBuffer sb) { + public StringBuilder toString(StringBuilder sb) { if(null == sb) { - sb = new StringBuffer(); + sb = new StringBuilder(); } sb.append(pixelAttributes).append(", dim ").append(width).append("x").append(height).append("x").append(depth).append(", pack ").append(pack) .append(", disposed ").append(disposed).append(", valid ").append(isValid()).append(", buffer[sz [bytes ").append(byteSize).append(", elemSize ").append(bufferElemSize).append(", ").append(buffer).append("]"); diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java b/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java index aceb609a1..df1bbdf26 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java @@ -109,7 +109,7 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { super.dispose(); } - public StringBuffer toString(StringBuffer sb) { + public StringBuilder toString(StringBuilder sb) { sb = super.toString(sb); sb.append(", allowRowStride ").append(allowRowStride).append(", image [").append(image.getWidth()).append("x").append(image.getHeight()).append(", ").append(image.toString()).append("]"); return sb; @@ -225,4 +225,4 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { } } } -} \ No newline at end of file +} diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java index 066b2054d..d18fd4bae 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java @@ -249,10 +249,10 @@ public class ShaderUtil { for(int i = source.length - 1; i>=0; i--) { final CharSequence csq = source[i]; if(csq instanceof String) { - // if ShaderCode.create(.. mutableStringBuffer == false ) + // if ShaderCode.create(.. mutableStringBuilder == false ) tmp[i] = (String) csq; } else { - // if ShaderCode.create(.. mutableStringBuffer == true ) + // if ShaderCode.create(.. mutableStringBuilder == true ) tmp[i] = source[i].toString(); } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java index 6b41c0bc8..9f951d5da 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java @@ -75,7 +75,7 @@ import javax.media.opengl.GL; // in case a fixed lookup function is being chosen, replace the name in our code rsFp.replaceInShaderSource(myTextureLookupName, texLookupFuncName); - // Cache the TextureSequence shader details in StringBuffer: + // Cache the TextureSequence shader details in StringBuilder: final StringBuilder sFpIns = new StringBuilder(); // .. declaration of the texture sampler using the implementation specific type @@ -217,4 +217,4 @@ public interface TextureSequence { * @throws IllegalStateException if instance is not initialized */ public String getTextureLookupFragmentShaderImpl() throws IllegalStateException ; -} \ No newline at end of file +} diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java index 4444e9d63..bf2d3fa47 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java @@ -80,7 +80,7 @@ public class WGLGLCapabilities extends GLCapabilities { public static final String PFD2String(PIXELFORMATDESCRIPTOR pfd, int pfdID) { final int dwFlags = pfd.getDwFlags(); - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); boolean sep = false; if( 0 != (GDI.PFD_DRAW_TO_WINDOW & dwFlags ) ) { @@ -270,4 +270,4 @@ public class WGLGLCapabilities extends GLCapabilities { sink.append(": "); return super.toString(sink); } -} \ No newline at end of file +} diff --git a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java index 8e83eda33..f2a8e2394 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java +++ b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java @@ -366,7 +366,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { return msg.toString(); } - /** Return a textual representation of this object's on/off screen state. Use the given StringBuffer [optional]. */ + /** Return a textual representation of this object's on/off screen state. Use the given StringBuilder [optional]. */ protected StringBuilder onoffScreenToString(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); diff --git a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java index b801ab457..85659f286 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java @@ -130,7 +130,7 @@ public interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable, C @Override int hashCode(); - /** Return a textual representation of this object. Use the given StringBuffer [optional]. */ + /** Return a textual representation of this object. Use the given StringBuilder [optional]. */ StringBuilder toString(StringBuilder sink); /** Returns a textual representation of this object. */ diff --git a/src/newt/classes/com/jogamp/newt/MonitorMode.java b/src/newt/classes/com/jogamp/newt/MonitorMode.java index dc7ae2c03..218cd8bd5 100644 --- a/src/newt/classes/com/jogamp/newt/MonitorMode.java +++ b/src/newt/classes/com/jogamp/newt/MonitorMode.java @@ -156,8 +156,8 @@ public class MonitorMode implements Comparable { private final static String STR_DOUBLESCAN = "DoubleScan"; private final static String STR_SEP = ", "; - public static final StringBuffer flags2String(int flags) { - final StringBuffer sb = new StringBuffer(); + public static final StringBuilder flags2String(int flags) { + final StringBuilder sb = new StringBuilder(); boolean sp = false; if( 0 != ( flags & FLAG_INTERLACE ) ) { sb.append(STR_INTERLACE); diff --git a/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivity.java b/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivity.java index de524d54c..9f6210269 100644 --- a/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivity.java +++ b/src/newt/classes/jogamp/newt/driver/android/NewtVersionActivity.java @@ -78,7 +78,7 @@ public class NewtVersionActivity extends NewtBaseActivity { glWindow.addGLEventListener(new GLEventListener() { public void init(GLAutoDrawable drawable) { GL gl = drawable.getGL(); - final StringBuffer sb = new StringBuffer(); + final StringBuilder sb = new StringBuilder(); sb.append(JoglVersion.getGLInfo(gl, null, true)).append(Platform.NEWLINE); sb.append("Requested: ").append(Platform.NEWLINE); sb.append(drawable.getNativeSurface().getGraphicsConfiguration().getRequestedCapabilities()).append(Platform.NEWLINE).append(Platform.NEWLINE); -- cgit v1.2.3 From 8ac3f344aded383ca9a3083a877af7bfdf6e1e48 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 17 Jul 2013 04:27:13 +0200 Subject: Remedy for Bug 782: Issue Debug.initSingleton() or Debug.debug(..) before calling 'PropertyAccess.isPropertyDefined(propName, default)' through Debug class. Calling 'Debug.isPropertyDefined(propName, default)' may be 'optimized' to 'PropertyAccess.isPropertyDefined(propName, default)', which would skip the modules Debug's class initialization. Iff that happens, an AccessControlException may happen, due to requesting an insecure property, since modules own Debug class has not been added it's trusted prefixes from within it's init block yet. This seems to be a bug of the JVM .. to me, however .. the above description is the only able to explain the issue at hand. +++ Fix calls Debug class own static methods, either Debug.initSingleton() or Debug.debug(), before calling 'isPropertyDefined(propName, default)'. +++ Also mark Debug class static methods final! +++ --- src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java | 13 ++++++++++--- .../classes/com/jogamp/opengl/util/awt/TextRenderer.java | 7 ++++++- .../classes/com/jogamp/opengl/util/glsl/ShaderState.java | 9 +++++++-- .../javax/media/opengl/DefaultGLCapabilitiesChooser.java | 7 ++++++- src/jogl/classes/javax/media/opengl/GLContext.java | 8 ++++---- src/jogl/classes/javax/media/opengl/awt/GLJPanel.java | 12 +++++++++--- src/jogl/classes/jogamp/opengl/Debug.java | 9 ++++++--- src/jogl/classes/jogamp/opengl/GLBufferSizeTracker.java | 10 ++++++++-- src/jogl/classes/jogamp/opengl/GLBufferStateTracker.java | 8 +++++++- src/jogl/classes/jogamp/opengl/GLDrawableHelper.java | 7 ++++++- src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java | 10 ++++++++-- src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java | 7 ++++++- .../opengl/util/glsl/fixedfunc/FixedFuncPipeline.java | 8 +++++++- src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java | 1 + .../jogamp/opengl/windows/wgl/WindowsWGLDrawable.java | 8 +++++++- .../media/nativewindow/DefaultCapabilitiesChooser.java | 7 ++++++- src/nativewindow/classes/jogamp/nativewindow/Debug.java | 9 ++++++--- .../classes/jogamp/nativewindow/x11/X11Util.java | 3 ++- src/newt/classes/jogamp/newt/Debug.java | 9 ++++++--- src/newt/classes/jogamp/newt/ScreenImpl.java | 7 ++++++- src/newt/classes/jogamp/newt/WindowImpl.java | 11 +++++++---- src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java | 5 ++++- 22 files changed, 135 insertions(+), 40 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java b/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java index 27ce7d8ec..dc96cb5f2 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java +++ b/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java @@ -48,9 +48,16 @@ import com.jogamp.opengl.util.glsl.ShaderState; *

        */ public class ImmModeSink { - protected static final boolean DEBUG_BEGIN_END = Debug.isPropertyDefined("jogl.debug.ImmModeSink.BeginEnd", true); - protected static final boolean DEBUG_DRAW = Debug.isPropertyDefined("jogl.debug.ImmModeSink.Draw", true); - protected static final boolean DEBUG_BUFFER = Debug.isPropertyDefined("jogl.debug.ImmModeSink.Buffer", true); + protected static final boolean DEBUG_BEGIN_END; + protected static final boolean DEBUG_DRAW; + protected static final boolean DEBUG_BUFFER; + + static { + Debug.initSingleton(); + DEBUG_BEGIN_END = Debug.isPropertyDefined("jogl.debug.ImmModeSink.BeginEnd", true); + DEBUG_DRAW = Debug.isPropertyDefined("jogl.debug.ImmModeSink.Draw", true); + DEBUG_BUFFER = Debug.isPropertyDefined("jogl.debug.ImmModeSink.Buffer", true); + } public static final int GL_QUADS = 0x0007; // Needs data manipulation on ES1/ES2 public static final int GL_QUAD_STRIP = 0x0008; diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java index 1735fcddd..c67141525 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java @@ -128,7 +128,12 @@ import jogamp.opengl.Debug; @author Kenneth Russell */ public class TextRenderer { - private static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.TextRenderer", true); + private static final boolean DEBUG; + + static { + Debug.initSingleton(); + DEBUG = Debug.isPropertyDefined("jogl.debug.TextRenderer", true); + } // These are occasionally useful for more in-depth debugging private static final boolean DISABLE_GLYPH_CACHE = false; diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java index 968391976..8e7781f07 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java @@ -55,8 +55,13 @@ import com.jogamp.opengl.util.GLArrayDataEditable; * and can be retrieved via {@link #getShaderState(GL)}. *

        */ -public class ShaderState { - public static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.GLSLState", true); +public class ShaderState { + public static final boolean DEBUG; + + static { + Debug.initSingleton(); + DEBUG = Debug.isPropertyDefined("jogl.debug.GLSLState", true); + } public ShaderState() { } diff --git a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java index b052769ca..b0f3da8e4 100644 --- a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java +++ b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java @@ -85,8 +85,13 @@ import jogamp.opengl.Debug; */ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { - private static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.CapabilitiesChooser", true); + private static final boolean DEBUG; + static { + Debug.initSingleton(); + DEBUG = Debug.isPropertyDefined("jogl.debug.CapabilitiesChooser", true); + } + private final static int NO_SCORE = -9999999; private final static int DOUBLE_BUFFER_MISMATCH_PENALTY = 1000; private final static int OPAQUE_MISMATCH_PENALTY = 750; diff --git a/src/jogl/classes/javax/media/opengl/GLContext.java b/src/jogl/classes/javax/media/opengl/GLContext.java index f36061c13..aa5fca2c2 100644 --- a/src/jogl/classes/javax/media/opengl/GLContext.java +++ b/src/jogl/classes/javax/media/opengl/GLContext.java @@ -73,6 +73,10 @@ import com.jogamp.opengl.GLRendererQuirks; refer to a given context. */ public abstract class GLContext { + public static final boolean DEBUG = Debug.debug("GLContext"); + public static final boolean TRACE_SWITCH = Debug.isPropertyDefined("jogl.debug.GLContext.TraceSwitch", true); + public static final boolean DEBUG_TRACE_SWITCH = DEBUG || TRACE_SWITCH; + /** * If true (default), bootstrapping the available GL profiles * will use the highest compatible GL context for each profile, @@ -102,10 +106,6 @@ public abstract class GLContext { protected static final boolean FORCE_NO_FBO_SUPPORT = Debug.isPropertyDefined("jogl.fbo.force.none", true); protected static final boolean FORCE_MIN_FBO_SUPPORT = Debug.isPropertyDefined("jogl.fbo.force.min", true); - public static final boolean DEBUG = Debug.debug("GLContext"); - public static final boolean TRACE_SWITCH = Debug.isPropertyDefined("jogl.debug.GLContext.TraceSwitch", true); - public static final boolean DEBUG_TRACE_SWITCH = DEBUG || TRACE_SWITCH; - /** Reflects property jogl.debug.DebugGL. If true, the debug pipeline is enabled at context creation. */ public static final boolean DEBUG_GL = Debug.isPropertyDefined("jogl.debug.DebugGL", true); /** Reflects property jogl.debug.TraceGL. If true, the trace pipeline is enabled at context creation. */ diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java index d3f20b2e5..2a23defbe 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java @@ -138,9 +138,9 @@ import com.jogamp.opengl.util.awt.AWTGLPixelBuffer.SingleAWTGLPixelBufferProvide @SuppressWarnings("serial") public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosingProtocol { - private static final boolean DEBUG = Debug.debug("GLJPanel"); - private static final boolean DEBUG_VIEWPORT = Debug.isPropertyDefined("jogl.debug.GLJPanel.Viewport", true); - private static final boolean USE_GLSL_TEXTURE_RASTERIZER = !Debug.isPropertyDefined("jogl.gljpanel.noglsl", true); + private static final boolean DEBUG; + private static final boolean DEBUG_VIEWPORT; + private static final boolean USE_GLSL_TEXTURE_RASTERIZER; /** Indicates whether the Java 2D OpenGL pipeline is requested by user. */ private static final boolean java2dOGLEnabledByProp; @@ -152,11 +152,17 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing private static boolean java2DGLPipelineOK; static { + Debug.initSingleton(); + DEBUG = Debug.debug("GLJPanel"); + DEBUG_VIEWPORT = Debug.isPropertyDefined("jogl.debug.GLJPanel.Viewport", true); + USE_GLSL_TEXTURE_RASTERIZER = !Debug.isPropertyDefined("jogl.gljpanel.noglsl", true); + boolean enabled = false; final String sVal = System.getProperty("sun.java2d.opengl"); if( null != sVal ) { enabled = Boolean.valueOf(sVal); } + Debug.initSingleton(); java2dOGLEnabledByProp = enabled && !Debug.isPropertyDefined("jogl.gljpanel.noogl", true); enabled = false; diff --git a/src/jogl/classes/jogamp/opengl/Debug.java b/src/jogl/classes/jogamp/opengl/Debug.java index f87f1bb3f..b88a09b71 100644 --- a/src/jogl/classes/jogamp/opengl/Debug.java +++ b/src/jogl/classes/jogamp/opengl/Debug.java @@ -68,16 +68,19 @@ public class Debug extends PropertyAccess { System.err.println("JOGL implementation vendor " + p.getImplementationVendor()); } } + + /** Ensures static init block has been issues, i.e. if calling through to {@link PropertyAccess#isPropertyDefined(String, boolean)}. */ + public static final void initSingleton() {} - public static boolean verbose() { + public static final boolean verbose() { return verbose; } - public static boolean debugAll() { + public static final boolean debugAll() { return debugAll; } - public static boolean debug(String subcomponent) { + public static final boolean debug(String subcomponent) { return debugAll() || isPropertyDefined("jogl.debug." + subcomponent, true); } } diff --git a/src/jogl/classes/jogamp/opengl/GLBufferSizeTracker.java b/src/jogl/classes/jogamp/opengl/GLBufferSizeTracker.java index 78ab7cc93..17646cc7b 100644 --- a/src/jogl/classes/jogamp/opengl/GLBufferSizeTracker.java +++ b/src/jogl/classes/jogamp/opengl/GLBufferSizeTracker.java @@ -87,6 +87,13 @@ import com.jogamp.common.util.IntLongHashMap; */ public class GLBufferSizeTracker { + protected static final boolean DEBUG; + + static { + Debug.initSingleton(); + DEBUG = Debug.isPropertyDefined("jogl.debug.GLBufferSizeTracker", true); + } + // Map from buffer names to sizes. // Note: should probably have some way of shrinking this map, but // can't just make it a WeakHashMap because nobody holds on to the @@ -95,8 +102,7 @@ public class GLBufferSizeTracker { // pattern of buffer objects indicates that the fact that this map // never shrinks is probably not that bad. private IntLongHashMap bufferSizeMap; - protected static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.GLBufferSizeTracker", true); - + public GLBufferSizeTracker() { bufferSizeMap = new IntLongHashMap(); bufferSizeMap.setKeyNotFoundValue(0xFFFFFFFFFFFFFFFFL); diff --git a/src/jogl/classes/jogamp/opengl/GLBufferStateTracker.java b/src/jogl/classes/jogamp/opengl/GLBufferStateTracker.java index 7f5316fbd..890c82c90 100644 --- a/src/jogl/classes/jogamp/opengl/GLBufferStateTracker.java +++ b/src/jogl/classes/jogamp/opengl/GLBufferStateTracker.java @@ -76,7 +76,13 @@ import com.jogamp.common.util.IntIntHashMap; */ public class GLBufferStateTracker { - protected static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.GLBufferStateTracker", true); + protected static final boolean DEBUG; + + static { + Debug.initSingleton(); + DEBUG = Debug.isPropertyDefined("jogl.debug.GLBufferStateTracker", true); + } + // Maps binding targets to buffer objects. A null value indicates // that the binding is unknown. A zero value indicates that it is // known that no buffer is bound to the target, according to the diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java index 8be910c1a..5418fbaf3 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java @@ -62,8 +62,13 @@ import javax.media.opengl.GLRunnable; methods to be able to share it between GLAutoDrawable implementations like GLAutoDrawableBase, GLCanvas and GLJPanel. */ public class GLDrawableHelper { /** true if property jogl.debug.GLDrawable.PerfStats is defined. */ - private static final boolean PERF_STATS = Debug.isPropertyDefined("jogl.debug.GLDrawable.PerfStats", true); + private static final boolean PERF_STATS; + static { + Debug.initSingleton(); + PERF_STATS = Debug.isPropertyDefined("jogl.debug.GLDrawable.PerfStats", true); + } + protected static final boolean DEBUG = GLDrawableImpl.DEBUG; private final Object listenersLock = new Object(); private final ArrayList listeners = new ArrayList(); diff --git a/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java index 27024d4e1..3833e6852 100644 --- a/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java @@ -37,8 +37,14 @@ import com.jogamp.opengl.JoglVersion; * @see GLDrawableImpl#getDefaultReadFramebuffer() */ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { - protected static final boolean DEBUG = GLDrawableImpl.DEBUG || Debug.debug("FBObject"); - protected static final boolean DEBUG_SWAP = Debug.isPropertyDefined("jogl.debug.FBObject.Swap", true); + protected static final boolean DEBUG; + protected static final boolean DEBUG_SWAP; + + static { + Debug.initSingleton(); + DEBUG = GLDrawableImpl.DEBUG || Debug.debug("FBObject"); + DEBUG_SWAP = Debug.isPropertyDefined("jogl.debug.FBObject.Swap", true); + } private final GLDrawableImpl parent; private GLCapabilitiesImmutable origParentChosenCaps; diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index 9c1cc7fc4..5d99e3eba 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -84,7 +84,12 @@ import com.jogamp.opengl.GLRendererQuirks; public class EGLDrawableFactory extends GLDrawableFactoryImpl { protected static final boolean DEBUG = GLDrawableFactoryImpl.DEBUG; // allow package access - /* package */ static final boolean QUERY_EGL_ES_NATIVE_TK = Debug.isPropertyDefined("jogl.debug.EGLDrawableFactory.QueryNativeTK", true); + /* package */ static final boolean QUERY_EGL_ES_NATIVE_TK; + + static { + Debug.initSingleton(); + QUERY_EGL_ES_NATIVE_TK = Debug.isPropertyDefined("jogl.debug.EGLDrawableFactory.QueryNativeTK", true); + } private static GLDynamicLookupHelper eglES1DynamicLookupHelper = null; private static GLDynamicLookupHelper eglES2DynamicLookupHelper = null; diff --git a/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java b/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java index f4f20ac7c..2e924cbfb 100644 --- a/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java +++ b/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java @@ -66,7 +66,13 @@ import com.jogamp.opengl.util.glsl.fixedfunc.ShaderSelectionMode; *

        */ public class FixedFuncPipeline { - protected static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.FixedFuncPipeline", true); + protected static final boolean DEBUG; + + static { + Debug.initSingleton(); + DEBUG = Debug.isPropertyDefined("jogl.debug.FixedFuncPipeline", true); + } + /** The maximum texture units which could be used, depending on {@link ShaderSelectionMode}. */ public static final int MAX_TEXTURE_UNITS = 8; public static final int MAX_LIGHTS = 8; diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java index f1598d580..3e788d286 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java @@ -51,6 +51,7 @@ public class WGLUtil { public static final boolean USE_WGLVersion_Of_5WGLGDIFuncSet; static { + Debug.initSingleton(); USE_WGLVersion_Of_5WGLGDIFuncSet = Debug.isPropertyDefined("jogl.windows.useWGLVersionOf5WGLGDIFuncSet", true); if(USE_WGLVersion_Of_5WGLGDIFuncSet) { System.err.println("Use WGL version of 5 WGL/GDI functions."); diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java index 8b8cb2052..741e671eb 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java @@ -51,7 +51,13 @@ import jogamp.opengl.GLDynamicLookupHelper; public abstract class WindowsWGLDrawable extends GLDrawableImpl { - private static final boolean PROFILING = Debug.isPropertyDefined("jogl.debug.GLDrawable.profiling", true); + private static final boolean PROFILING; + + static { + Debug.initSingleton(); + PROFILING = Debug.isPropertyDefined("jogl.debug.GLDrawable.profiling", true); + } + private static final int PROFILING_TICKS = 200; private int profilingSwapBuffersTicks; private long profilingSwapBuffersTime; diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java index 744c7e6d5..4f07bca9b 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java @@ -66,8 +66,13 @@ import jogamp.nativewindow.Debug; */ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { - private static final boolean DEBUG = Debug.isPropertyDefined("nativewindow.debug.CapabilitiesChooser", true); + private static final boolean DEBUG; + static { + Debug.initSingleton(); + DEBUG = Debug.isPropertyDefined("nativewindow.debug.CapabilitiesChooser", true); + } + private final static int NO_SCORE = -9999999; private final static int COLOR_MISMATCH_PENALTY_SCALE = 36; diff --git a/src/nativewindow/classes/jogamp/nativewindow/Debug.java b/src/nativewindow/classes/jogamp/nativewindow/Debug.java index 95547c971..c5e316364 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/Debug.java +++ b/src/nativewindow/classes/jogamp/nativewindow/Debug.java @@ -69,15 +69,18 @@ public class Debug extends PropertyAccess { } } - public static boolean verbose() { + /** Ensures static init block has been issues, i.e. if calling through to {@link PropertyAccess#isPropertyDefined(String, boolean)}. */ + public static final void initSingleton() {} + + public static final boolean verbose() { return verbose; } - public static boolean debugAll() { + public static final boolean debugAll() { return debugAll; } - public static boolean debug(String subcomponent) { + public static final boolean debug(String subcomponent) { return debugAll() || isPropertyDefined("nativewindow.debug." + subcomponent, true); } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index bbc58b73a..78e432b7f 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -53,6 +53,8 @@ import com.jogamp.nativewindow.x11.X11GraphicsDevice; * Contains a thread safe X11 utility to retrieve display connections. */ public class X11Util implements ToolkitProperties { + public static final boolean DEBUG = Debug.debug("X11Util"); + /** * See Bug 515 - https://jogamp.org/bugzilla/show_bug.cgi?id=515 *

        @@ -92,7 +94,6 @@ public class X11Util implements ToolkitProperties { */ public static final boolean ATI_HAS_MULTITHREADING_BUG = !Debug.isPropertyDefined("nativewindow.debug.X11Util.ATI_HAS_NO_MULTITHREADING_BUG", true); - public static final boolean DEBUG = Debug.debug("X11Util"); public static final boolean XSYNC_ENABLED = Debug.isPropertyDefined("nativewindow.debug.X11Util.XSync", true); public static final boolean XERROR_STACKDUMP = DEBUG || Debug.isPropertyDefined("nativewindow.debug.X11Util.XErrorStackDump", true); private static final boolean TRACE_DISPLAY_LIFECYCLE = Debug.isPropertyDefined("nativewindow.debug.X11Util.TraceDisplayLifecycle", true); diff --git a/src/newt/classes/jogamp/newt/Debug.java b/src/newt/classes/jogamp/newt/Debug.java index 676d9b758..4b0a98216 100644 --- a/src/newt/classes/jogamp/newt/Debug.java +++ b/src/newt/classes/jogamp/newt/Debug.java @@ -69,15 +69,18 @@ public class Debug extends PropertyAccess { } } - public static boolean verbose() { + /** Ensures static init block has been issues, i.e. if calling through to {@link PropertyAccess#isPropertyDefined(String, boolean)}. */ + public static final void initSingleton() {} + + public static final boolean verbose() { return verbose; } - public static boolean debugAll() { + public static final boolean debugAll() { return debugAll; } - public static boolean debug(String subcomponent) { + public static final boolean debug(String subcomponent) { return debugAll() || isPropertyDefined("newt.debug." + subcomponent, true); } } diff --git a/src/newt/classes/jogamp/newt/ScreenImpl.java b/src/newt/classes/jogamp/newt/ScreenImpl.java index fe9e91b57..5ffa2ebbf 100644 --- a/src/newt/classes/jogamp/newt/ScreenImpl.java +++ b/src/newt/classes/jogamp/newt/ScreenImpl.java @@ -55,7 +55,12 @@ import com.jogamp.newt.event.MonitorModeListener; import com.jogamp.newt.util.MonitorModeUtil; public abstract class ScreenImpl extends Screen implements MonitorModeListener { - protected static final boolean DEBUG_TEST_SCREENMODE_DISABLED = Debug.isPropertyDefined("newt.test.Screen.disableScreenMode", true); + protected static final boolean DEBUG_TEST_SCREENMODE_DISABLED; + + static { + Debug.initSingleton(); + DEBUG_TEST_SCREENMODE_DISABLED = Debug.isPropertyDefined("newt.test.Screen.disableScreenMode", true); + } public static final int default_sm_bpp = 32; public static final int default_sm_widthmm = 519; diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index 2c3c903f1..caa461e41 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -81,14 +81,17 @@ import jogamp.nativewindow.SurfaceUpdatedHelper; public abstract class WindowImpl implements Window, NEWTEventConsumer { - public static final boolean DEBUG_TEST_REPARENT_INCOMPATIBLE = Debug.isPropertyDefined("newt.test.Window.reparent.incompatible", true); - - protected static final ArrayList> windowList = new ArrayList>(); + public static final boolean DEBUG_TEST_REPARENT_INCOMPATIBLE; static { + Debug.initSingleton(); + DEBUG_TEST_REPARENT_INCOMPATIBLE = Debug.isPropertyDefined("newt.test.Window.reparent.incompatible", true); + ScreenImpl.initSingleton(); } - + + protected static final ArrayList> windowList = new ArrayList>(); + /** Maybe utilized at a shutdown hook, impl. does not block. */ public static final void shutdownAll() { final int wCount = windowList.size(); diff --git a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java index 1335f5697..f37556dd7 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java @@ -55,9 +55,12 @@ import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.MonitorMode; public class ScreenDriver extends ScreenImpl { - protected static final boolean DEBUG_TEST_RANDR13_DISABLED = Debug.isPropertyDefined("newt.test.Screen.disableRandR13", true); + protected static final boolean DEBUG_TEST_RANDR13_DISABLED; static { + Debug.initSingleton(); + DEBUG_TEST_RANDR13_DISABLED = Debug.isPropertyDefined("newt.test.Screen.disableRandR13", true); + DisplayDriver.initSingleton(); } -- cgit v1.2.3 From 5dc0e8c2bfc686ccac0902ff09448cd2f3ad65b4 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 17 Jul 2013 16:15:32 +0200 Subject: NativeWindow API Doc: Fix layout / Add version. --- .../classes/javax/media/nativewindow/package.html | 94 +++++++++------------- 1 file changed, 39 insertions(+), 55 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/package.html b/src/nativewindow/classes/javax/media/nativewindow/package.html index 14730a548..3fe42bab0 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/package.html +++ b/src/nativewindow/classes/javax/media/nativewindow/package.html @@ -1,7 +1,7 @@ - NativeWindow Protocol Draft Public Review Specification + NativeWindow Specification Overview @@ -10,7 +10,7 @@

        Preface

        This specification, an optional set of packages, describing a protocol for a native windowing interface binding to Java(TM).
        - Currently specified native windowing systems are:

        + Currently specified native windowing systems are:
        • EGL/OpenKODE Windowing System
        • X11 Windowing System
        • @@ -20,95 +20,79 @@

        However, any other native windowing system may be added to the implementation, - using a generic string identifier and an optional specialisation of:

        + using a generic string identifier and an optional specialisation of:
          -
        • {@link javax.media.nativewindow.AbstractGraphicsDevice AbstractGraphicsDevice},
          -
          - Shall return the new string identifier with {@link javax.media.nativewindow.AbstractGraphicsDevice#getType() getType()}
        • +
        • {@link javax.media.nativewindow.AbstractGraphicsDevice AbstractGraphicsDevice}, +

          Shall return the new string identifier with {@link javax.media.nativewindow.AbstractGraphicsDevice#getType() getType()}

        • {@link javax.media.nativewindow.AbstractGraphicsScreen AbstractGraphicsScreen}
        • {@link javax.media.nativewindow.AbstractGraphicsConfiguration AbstractGraphicsConfiguration}
        -
        - The implementor has to provide the following:

        +

        The implementor has to provide the following:

          -
        • The specialisation of the abstract class {@link javax.media.nativewindow.NativeWindowFactory NativeWindowFactory}
          -
          - shall be registered with {@link javax.media.nativewindow.NativeWindowFactory#registerFactory NativeWindowFactory.registerFactory(..)}.
        • +
        • The specialisation of the abstract class {@link javax.media.nativewindow.NativeWindowFactory NativeWindowFactory} +

          shall be registered with {@link javax.media.nativewindow.NativeWindowFactory#registerFactory NativeWindowFactory.registerFactory(..)}.

        • -
        • The specialisation of the abstract class {@link javax.media.nativewindow.GraphicsConfigurationFactory GraphicsConfigurationFactory}
          -
          - shall be registered with {@link javax.media.nativewindow.GraphicsConfigurationFactory#registerFactory GraphicsConfigurationFactory.registerFactory(..)}.
        • -

        - This protocol does not describe how to create native windows, but how to bind a native surface to an implementation of - and window to an implementation of {@link javax.media.nativewindow.NativeSurface NativeSurface}.
        - {@link javax.media.nativewindow.NativeWindow NativeWindow} specializes the NativeSurface.
        - However, an implementation of this protocol (e.g. {@link com.jogamp.newt}) may support the creation.
        +
      • The specialisation of the abstract class {@link javax.media.nativewindow.GraphicsConfigurationFactory GraphicsConfigurationFactory} +

        shall be registered with {@link javax.media.nativewindow.GraphicsConfigurationFactory#registerFactory GraphicsConfigurationFactory.registerFactory(..)}.

      • + +

        This protocol does not describe how to create native windows, but how to bind a native surface to an implementation of + and window to an implementation of {@link javax.media.nativewindow.NativeSurface NativeSurface}.

        +

        {@link javax.media.nativewindow.NativeWindow NativeWindow} specializes the NativeSurface.

        +

        However, an implementation of this protocol (e.g. {@link com.jogamp.newt}) may support the creation.

        Dependencies

        This binding has dependencies to the following:

        Package Structure

        - The packages defined by this specification include:

        + The packages defined by this specification include:
          -
        • The javax.media.nativewindow package
          -
          - This package contains Java bindings for a native windowing system.
          - Subsequent packages contain marker type classes, containing native characteristics of the windowing system. - -
            -
          • The javax.media.nativewindow.awt package
            -
            - This sub package contains classes to cover the native characteristics of the AWT windowing system.
          • +
          • The javax.media.nativewindow package +

            This package contains Java bindings for a native windowing system.

            +

            Subsequent packages contain marker type classes, containing native characteristics of the windowing system.

            +
              +
            • The javax.media.nativewindow.awt package +

              This sub package contains classes to cover the native characteristics of the AWT windowing system.

            • -
            • The javax.media.nativewindow.x11 package
              -
              - This sub package contains classes to cover the native characteristics of the X11 windowing system.
            • +
            • The javax.media.nativewindow.x11 package +

              This sub package contains classes to cover the native characteristics of the X11 windowing system.

            • -
            • The javax.media.nativewindow.windows package
              -
              - This sub package contains classes to cover the native characteristics of the Windows windowing system.
            • +
            • The javax.media.nativewindow.windows package +

              This sub package contains classes to cover the native characteristics of the Windows windowing system.

            • -
            • The javax.media.nativewindow.macosx package
              -
              - This sub package contains classes to cover the native characteristics of the MacOSX windowing system.
            • +
            • The javax.media.nativewindow.macosx package +

              This sub package contains classes to cover the native characteristics of the MacOSX windowing system.

            • -
            • The javax.media.nativewindow.egl package
              -
              - This sub package contains classes to cover the native characteristics of the EGL/OpenKODE windowing system.
            • +
            • The javax.media.nativewindow.egl package +

              This sub package contains classes to cover the native characteristics of the EGL/OpenKODE windowing system.

          Factory Model

          -Running on a platform with a supported windowing system, the factory model shall be used -to instantiate a native window, see {@link javax.media.nativewindow.NativeWindowFactory NativeWindowFactory}.
          -The implementor has to specialize -All supported -Regardless of the knowledge of the underly -
          +

          Running on a platform with a supported windowing system, the factory model shall be used +to instantiate a native window, see {@link javax.media.nativewindow.NativeWindowFactory NativeWindowFactory}.

          -

          Revision History
          -

          +

          Revision History

          • Early Draft Review, June 2009
          • 2.0.0 Maintenance Release, February 2011
          • +
          • 2.0.2 Major Release, July 18th 2013


          -- cgit v1.2.3 From 14eab8af439e6e7ce7ee08a9ca13fec3f3a80d25 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Mon, 2 Sep 2013 21:01:10 +0200 Subject: Fix Bug 810: Adding Julien Gouesse's fix while moved the new 'addNativeJarLibsJoglCfg(..)' to GlueGen, commit c0ead6fa10280f8076704726d59f482b183fd77e --- src/jogl/classes/javax/media/opengl/GLProfile.java | 8 ++---- .../jogamp/nativewindow/NWJNILibLoader.java | 30 +++++++++----------- src/newt/classes/jogamp/newt/NEWTJNILibLoader.java | 32 +++++++++------------- 3 files changed, 28 insertions(+), 42 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/GLProfile.java b/src/jogl/classes/javax/media/opengl/GLProfile.java index 51b822449..e3078271e 100644 --- a/src/jogl/classes/javax/media/opengl/GLProfile.java +++ b/src/jogl/classes/javax/media/opengl/GLProfile.java @@ -143,16 +143,12 @@ public class GLProfile { if(TempJarCache.isInitialized()) { final ClassLoader cl = GLProfile.class.getClassLoader(); - // either: [jogl-all.jar, jogl-all-noawt.jar, jogl-all-mobile.jar] -> jogl-all-natives-.jar - // or: nativewindow-core.jar -> nativewindow-natives-.jar, - // jogl-core.jar -> jogl-natives-.jar, - // (newt-core.jar -> newt-natives-.jar)? (if available) final String newtFactoryClassName = "com.jogamp.newt.NewtFactory"; final Class[] classesFromJavaJars = new Class[] { NWJNILibLoader.class, GLProfile.class, null }; if( ReflectionUtil.isClassAvailable(newtFactoryClassName, cl) ) { classesFromJavaJars[2] = ReflectionUtil.getClass(newtFactoryClassName, false, cl); } - JNILibLoaderBase.addNativeJarLibs(classesFromJavaJars, "-all", new String[] { "-noawt", "-mobile", "-core" } ); + JNILibLoaderBase.addNativeJarLibsJoglCfg(classesFromJavaJars); } initProfilesForDefaultDevices(); return null; @@ -170,7 +166,7 @@ public class GLProfile { } } } - + /** * Trigger eager initialization of GLProfiles for the given device, * in case it isn't done yet. diff --git a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java index 6c15f9a2b..1a106b1b9 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java @@ -36,21 +36,17 @@ import com.jogamp.common.jvm.JNILibLoaderBase; import com.jogamp.common.os.Platform; import com.jogamp.common.util.cache.TempJarCache; -public class NWJNILibLoader extends JNILibLoaderBase { - - public static boolean loadNativeWindow(final String ossuffix) { - return AccessController.doPrivileged(new PrivilegedAction() { - public Boolean run() { - Platform.initSingleton(); - final String libName = "nativewindow_"+ossuffix ; - if(TempJarCache.isInitialized() && null == TempJarCache.findLibrary(libName)) { - // either: [jogl-all.jar, jogl-all-noawt.jar, jogl-all-mobile.jar] -> jogl-all-natives-.jar - // or: nativewindow-core.jar -> nativewindow-natives-.jar - addNativeJarLibs(new Class[] { NWJNILibLoader.class }, "-all", new String[] { "-noawt", "-mobile", "-core" } ); - } - return new Boolean(loadLibrary(libName, false, NWJNILibLoader.class.getClassLoader())); - } - }).booleanValue(); - } - +public class NWJNILibLoader extends JNILibLoaderBase { + public static boolean loadNativeWindow(final String ossuffix) { + return AccessController.doPrivileged(new PrivilegedAction() { + public Boolean run() { + Platform.initSingleton(); + final String libName = "nativewindow_"+ossuffix ; + if(TempJarCache.isInitialized() && null == TempJarCache.findLibrary(libName)) { + JNILibLoaderBase.addNativeJarLibsJoglCfg(new Class[] { NWJNILibLoader.class }); + } + return Boolean.valueOf(loadLibrary(libName, false, NWJNILibLoader.class.getClassLoader())); + } + }).booleanValue(); + } } diff --git a/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java b/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java index bc0eb7531..bc12bf3ee 100644 --- a/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java +++ b/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java @@ -48,23 +48,17 @@ import com.jogamp.common.jvm.JNILibLoaderBase; import com.jogamp.common.os.Platform; import com.jogamp.common.util.cache.TempJarCache; -public class NEWTJNILibLoader extends JNILibLoaderBase { - - public static void loadNEWT() { - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - Platform.initSingleton(); - final String libName = "newt"; - if(TempJarCache.isInitialized() && null == TempJarCache.findLibrary(libName)) { - // either: [jogl-all.jar, jogl-all-noawt.jar, jogl-all-mobile.jar] -> jogl-all-natives-.jar - // or: nativewindow-core.jar -> nativewindow-natives-.jar, - // newt-core.jar -> newt-natives-.jar - JNILibLoaderBase.addNativeJarLibs(new Class[] { NWJNILibLoader.class, NEWTJNILibLoader.class }, "-all", new String[] { "-noawt", "-mobile", "-core" } ); - } - loadLibrary(libName, false, NEWTJNILibLoader.class.getClassLoader()); - return null; - } - }); - } - +public class NEWTJNILibLoader extends JNILibLoaderBase { + public static boolean loadNEWT() { + return AccessController.doPrivileged(new PrivilegedAction() { + public Boolean run() { + Platform.initSingleton(); + final String libName = "newt"; + if(TempJarCache.isInitialized() && null == TempJarCache.findLibrary(libName)) { + JNILibLoaderBase.addNativeJarLibsJoglCfg(new Class[] { NWJNILibLoader.class, NEWTJNILibLoader.class }); + } + return Boolean.valueOf(loadLibrary(libName, false, NEWTJNILibLoader.class.getClassLoader())); + } + }).booleanValue(); + } } -- cgit v1.2.3 From 76048cd784ea6df32f19e97bb228e4ead880ea07 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 8 Sep 2013 03:02:36 +0200 Subject: Test: Don't resize frame, tweek print-matrix; AWTPrintLifecycle: Add scale and convenient AWT container traversal context; GLCanvas/GLJPanel properly handle existing MSAA and req. AA; - Test: Don't resize frame, tweek print-matrix - Use scaleComp72 to scale the frame to fit on page, i.e. global print matrix - Use scaleGLMatXY = 72.0 / glDPI to locally scale on the GL drawable as being passed to AWTPrintLifecycle.setup(..) - Hence frame stays untouched/stable, no need for 'offscreen' print test, which is removed. - AWTPrintLifecycle: Add scale and convenient AWT container traversal context Use a simple decoration for all AWTPrintLifecycle impl. components within a container: final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(frame, g2d, scaleGLMatXY, scaleGLMatXY); try { } finally { ctx.releasePrint(); } - GLCanvas/GLJPanel properly handle existing MSAA and req. AA; - GLCanvas: Workaround bug where onscreen MSAA cannot switch to offscreen FBO, i.e. stay 'onscreen' - GLJPanel: Use new offscreen FBO if MSAA is requested and not yet used. - GLJPanel.Offscreen.postGL(): always swapBufer(), was missing for !GLSL swapping Results GLCanvas / GLJPanel: - Good scaling - Stable behavior / visibility - High DPI mode works --- make/scripts/tests.sh | 4 +- .../javax/media/opengl/awt/AWTPrintLifecycle.java | 49 +++++++- .../classes/javax/media/opengl/awt/GLCanvas.java | 85 ++++++++------ .../classes/javax/media/opengl/awt/GLJPanel.java | 121 ++++++++++++++------ .../classes/jogamp/opengl/awt/AWTTilePainter.java | 53 ++++++--- .../classes/jogamp/nativewindow/awt/AWTMisc.java | 27 +++++ .../junit/jogl/tile/TestTiledPrintingGearsAWT.java | 59 +++++----- .../jogl/tile/TestTiledPrintingGearsSwingAWT.java | 58 +++++----- .../test/junit/jogl/tile/TiledPrintingAWTBase.java | 124 +++++++-------------- 9 files changed, 345 insertions(+), 235 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index fee4b3ec0..2b7a2563e 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -216,7 +216,7 @@ function jrun() { #D_ARGS="-Djogl.debug.GLContext -Dnewt.debug=all -Djogamp.debug.Lock -Djogamp.common.utils.locks.Lock.timeout=10000" #D_ARGS="-Djogl.debug.GLContext -Dnewt.debug=all" #D_ARGS="-Dnewt.debug=all" - D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.GLJPanel -Djogl.debug.TileRenderer" + #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.GLJPanel -Djogl.debug.TileRenderer" #D_ARGS="-Djogl.debug.PNGImage" #D_ARGS="-Djogl.debug.JPEGImage" #D_ARGS="-Djogl.debug.GLDrawable -Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.CapabilitiesChooser" @@ -330,7 +330,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering2GL2NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering3GL2AWT $* testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* +testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* # # core/newt (testnoawt and testawt) diff --git a/src/jogl/classes/javax/media/opengl/awt/AWTPrintLifecycle.java b/src/jogl/classes/javax/media/opengl/awt/AWTPrintLifecycle.java index 077ee42a9..293bdb809 100644 --- a/src/jogl/classes/javax/media/opengl/awt/AWTPrintLifecycle.java +++ b/src/jogl/classes/javax/media/opengl/awt/AWTPrintLifecycle.java @@ -29,9 +29,12 @@ package javax.media.opengl.awt; import javax.media.opengl.GLAutoDrawable; import java.awt.Component; +import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; +import jogamp.nativewindow.awt.AWTMisc; + /** * Interface describing print lifecycle to support AWT printing * on AWT {@link GLAutoDrawable}s. @@ -41,11 +44,55 @@ public interface AWTPrintLifecycle { /** * Shall be called before {@link Component#print(Graphics)}. * @param g2d the {@link Graphics2D} instance, which will be used for printing. + * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels + * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels */ - void setupPrint(Graphics2D g2d); + void setupPrint(Graphics2D g2d, double scaleMatX, double scaleMatY); /** * Shall be called after very last {@link Component#print(Graphics)}. */ void releasePrint(); + + public static class Context { + public static Context setupPrint(Container c, Graphics2D g2d, double scaleMatX, double scaleMatY) { + final Context t = new Context(c, g2d, scaleMatX, scaleMatY); + t.setupPrint(c); + return t; + } + + public void releasePrint() { + count = AWTMisc.performAction(cont, AWTPrintLifecycle.class, releaseAction); + } + + public int getCount() { return count; } + + private final Container cont; + private final Graphics2D g2d; + private final double scaleMatX; + private final double scaleMatY; + private int count; + + private final AWTMisc.ComponentAction setupAction = new AWTMisc.ComponentAction() { + @Override + public void run(Component c) { + ((AWTPrintLifecycle)c).setupPrint(g2d, scaleMatX, scaleMatY); + } }; + private final AWTMisc.ComponentAction releaseAction = new AWTMisc.ComponentAction() { + @Override + public void run(Component c) { + ((AWTPrintLifecycle)c).releasePrint(); + } }; + + private Context(Container c, Graphics2D g2d, double scaleMatX, double scaleMatY) { + this.cont = c; + this.g2d = g2d; + this.scaleMatX = scaleMatX; + this.scaleMatY = scaleMatY; + this.count = 0; + } + private void setupPrint(Container c) { + count = AWTMisc.performAction(c, AWTPrintLifecycle.class, setupAction); + } + } } diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 8f9684db1..b2ffc17a2 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -86,7 +86,6 @@ import javax.media.opengl.GLDrawable; import javax.media.opengl.GLDrawableFactory; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLException; -import javax.media.opengl.GLOffscreenAutoDrawable; import javax.media.opengl.GLProfile; import javax.media.opengl.GLRunnable; import javax.media.opengl.Threading; @@ -733,11 +732,11 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing private volatile boolean printActive = false; private boolean printUseAA = false; private GLAnimatorControl printAnimator = null; - private GLOffscreenAutoDrawable printGLAD = null; + private GLAutoDrawable printGLAD = null; private AWTTilePainter printAWTTiles = null; @Override - public void setupPrint(Graphics2D g2d) { + public void setupPrint(Graphics2D g2d, double scaleMatX, double scaleMatY) { if( !validateGLDrawable() ) { if(DEBUG) { System.err.println(getThreadName()+": Info: GLCanvas setupPrint - skipped GL render, drawable not valid yet"); @@ -758,7 +757,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing printUseAA = null != _useAA && ( _useAA == RenderingHints.VALUE_ANTIALIAS_DEFAULT || _useAA == RenderingHints.VALUE_ANTIALIAS_ON ); } if( DEBUG ) { - System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", useAA "+printUseAA+", printAnimator "+printAnimator); + System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", scaleMat "+scaleMatX+" x "+scaleMatY+", useAA "+printUseAA+", printAnimator "+printAnimator); { final Set> rEntries = rHints.entrySet(); int count = 0; @@ -770,7 +769,10 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing final AffineTransform aTrans = g2d.getTransform(); System.err.println(" scale "+aTrans.getScaleX()+" x "+aTrans.getScaleY()); System.err.println(" move "+aTrans.getTranslateX()+" x "+aTrans.getTranslateY()); - } + } + final int componentCount = isOpaque() ? 3 : 4; + final TileRenderer printRenderer = new TileRenderer(); + printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, DEBUG); AWTEDTExecutor.singleton.invoke(getTreeLock(), true /* allowOnNonEDT */, true /* wait */, setupPrintOnEDT); } private final Runnable setupPrintOnEDT = new Runnable() { @@ -782,30 +784,31 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing printAnimator.remove(GLCanvas.this); } final GLCapabilities caps = (GLCapabilities)getChosenGLCapabilities().cloneMutable(); - caps.setDoubleBuffered(false); final GLProfile glp = caps.getGLProfile(); - if( printUseAA && !caps.getSampleBuffers() ) { - if ( !glp.isGL2ES3() ) { - if( DEBUG ) { - System.err.println("Ignore MSAA due to gl-profile < GL2ES3"); + if( caps.getSampleBuffers() ) { + // bug / issue w/ swapGLContextAndAllGLEventListener and onscreen MSAA w/ NV/GLX + printGLAD = GLCanvas.this; + } else { + caps.setDoubleBuffered(false); + caps.setOnscreen(false); + if( printUseAA && !caps.getSampleBuffers() ) { + if ( !glp.isGL2ES3() ) { + if( DEBUG ) { + System.err.println("Ignore MSAA due to gl-profile < GL2ES3"); + } + printUseAA = false; + } else { + caps.setSampleBuffers(true); + caps.setNumSamples(8); } - printUseAA = false; - } else { - caps.setSampleBuffers(true); - caps.setNumSamples(8); // FIXME } + final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); + printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, PRINT_TILE_SIZE, PRINT_TILE_SIZE, null); + GLDrawableUtil.swapGLContextAndAllGLEventListener(GLCanvas.this, printGLAD); } - caps.setOnscreen(false); - final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); - printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, PRINT_TILE_SIZE, PRINT_TILE_SIZE, null); - GLDrawableUtil.swapGLContextAndAllGLEventListener(GLCanvas.this, printGLAD); - destroyOnEDTAction.run(); - final int componentCount = isOpaque() ? 3 : 4; - final TileRenderer printRenderer = new TileRenderer(); - printRenderer.setTileSize(printGLAD.getWidth(), printGLAD.getHeight(), 0); - printRenderer.attachToAutoDrawable(printGLAD); - printAWTTiles = new AWTTilePainter(printRenderer, componentCount, DEBUG); + printAWTTiles.renderer.setTileSize(printGLAD.getWidth(), printGLAD.getHeight(), 0); + printAWTTiles.renderer.attachToAutoDrawable(printGLAD); if( DEBUG ) { System.err.println("AWT print.setup "+printAWTTiles); System.err.println("AWT print.setup AA "+printUseAA+", "+caps); @@ -832,9 +835,10 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } printAWTTiles.dispose(); printAWTTiles= null; - createDrawableAndContext( false ); - GLDrawableUtil.swapGLContextAndAllGLEventListener(printGLAD, GLCanvas.this); - printGLAD.destroy(); + if( printGLAD != GLCanvas.this ) { + GLDrawableUtil.swapGLContextAndAllGLEventListener(printGLAD, GLCanvas.this); + printGLAD.destroy(); + } printGLAD = null; if( null != printAnimator ) { printAnimator.add(GLCanvas.this); @@ -854,17 +858,26 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing // we cannot dispatch print on AWT-EDT due to printing internal locking .. } sendReshape = false; // clear reshape flag - final Graphics2D printGraphics = (Graphics2D)graphics; - printAWTTiles.updateGraphics2DAndClipBounds(printGraphics); - final TileRenderer tileRenderer = printAWTTiles.getTileRenderer(); - if( DEBUG ) { - System.err.println("AWT print.0: "+tileRenderer); + + final Graphics2D g2d = (Graphics2D)graphics; + printAWTTiles.setupGraphics2DAndClipBounds(g2d); + try { + final TileRenderer tileRenderer = printAWTTiles.renderer; + if( DEBUG ) { + System.err.println("AWT print.0: "+tileRenderer); + } + do { + if( printGLAD != GLCanvas.this ) { + tileRenderer.display(); + } else { + Threading.invoke(true, displayOnEDTAction, getTreeLock()); + } + } while ( !tileRenderer.eot() ); + } finally { + printAWTTiles.resetGraphics2D(); } - do { - tileRenderer.display(); - } while ( !tileRenderer.eot() ); if( DEBUG ) { - System.err.println("AWT print.X: "+tileRenderer); + System.err.println("AWT print.X: "+printAWTTiles); } } diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java index 2488bd443..b549ad30c 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java @@ -98,6 +98,7 @@ import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol; import com.jogamp.opengl.FBObject; import com.jogamp.opengl.util.GLPixelBuffer.GLPixelAttributes; import com.jogamp.opengl.util.GLPixelBuffer.SingletonGLPixelBufferProvider; +import com.jogamp.opengl.util.GLDrawableUtil; import com.jogamp.opengl.util.GLPixelStorageModes; import com.jogamp.opengl.util.TileRenderer; import com.jogamp.opengl.util.awt.AWTGLPixelBuffer; @@ -500,12 +501,15 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } } + private static final int PRINT_TILE_SIZE = 512; private volatile boolean printActive = false; + private boolean printUseAA = false; private GLAnimatorControl printAnimator = null; + private GLAutoDrawable printGLAD = null; private AWTTilePainter printAWTTiles = null; @Override - public void setupPrint(Graphics2D g2d) { + public void setupPrint(Graphics2D g2d, double scaleMatX, double scaleMatY) { if (!isInitialized) { if(DEBUG) { System.err.println(getThreadName()+": Info: GLJPanel setupPrint - skipped GL render, drawable not valid yet"); @@ -521,6 +525,28 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing printActive = true; sendReshape = false; // clear reshape flag handleReshape = false; // ditto + final RenderingHints rHints = g2d.getRenderingHints(); + { + final Object _useAA = rHints.get(RenderingHints.KEY_ANTIALIASING); + printUseAA = null != _useAA && ( _useAA == RenderingHints.VALUE_ANTIALIAS_DEFAULT || _useAA == RenderingHints.VALUE_ANTIALIAS_ON ); + } + if( DEBUG ) { + System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", scaleMat "+scaleMatX+" x "+scaleMatY+", useAA "+printUseAA+", printAnimator "+printAnimator); + { + final Set> rEntries = rHints.entrySet(); + int count = 0; + for(Iterator> rEntryIter = rEntries.iterator(); rEntryIter.hasNext(); count++) { + final Entry rEntry = rEntryIter.next(); + System.err.println("Hint["+count+"]: "+rEntry.getKey()+" -> "+rEntry.getValue()); + } + } + final AffineTransform aTrans = g2d.getTransform(); + System.err.println(" scale "+aTrans.getScaleX()+" x "+aTrans.getScaleY()); + System.err.println(" move "+aTrans.getTranslateX()+" x "+aTrans.getTranslateY()); + } + final int componentCount = isOpaque() ? 3 : 4; + final TileRenderer printRenderer = new TileRenderer(); + printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, DEBUG); AWTEDTExecutor.singleton.invoke(getTreeLock(), true /* allowOnNonEDT */, true /* wait */, setupPrintOnEDT); } private final Runnable setupPrintOnEDT = new Runnable() { @@ -531,14 +557,34 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing printAnimator = helper.getAnimator(); if( null != printAnimator ) { printAnimator.remove(GLJPanel.this); - } - final int componentCount = isOpaque() ? 3 : 4; - final TileRenderer printRenderer = new TileRenderer(); - printRenderer.setTileSize(getWidth(), getHeight(), 0); - printRenderer.attachToAutoDrawable(GLJPanel.this); - printAWTTiles = new AWTTilePainter(printRenderer, componentCount, DEBUG); + } + + printGLAD = GLJPanel.this; // default: re-use + final GLCapabilities caps = (GLCapabilities)getChosenGLCapabilities().cloneMutable(); + final GLProfile glp = caps.getGLProfile(); + if( printUseAA && !caps.getSampleBuffers() ) { + if ( !glp.isGL2ES3() ) { + if( DEBUG ) { + System.err.println("Ignore MSAA due to gl-profile < GL2ES3"); + } + printUseAA = false; + } else { + // MSAA FBO .. + caps.setDoubleBuffered(false); + caps.setOnscreen(false); + caps.setSampleBuffers(true); + caps.setNumSamples(8); + final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); + printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, PRINT_TILE_SIZE, PRINT_TILE_SIZE, null); + GLDrawableUtil.swapGLContextAndAllGLEventListener(GLJPanel.this, printGLAD); + } + } + printAWTTiles.renderer.setTileSize(printGLAD.getWidth(), printGLAD.getHeight(), 0); + printAWTTiles.renderer.attachToAutoDrawable(printGLAD); if( DEBUG ) { System.err.println("AWT print.setup "+printAWTTiles); + System.err.println("AWT print.setup AA "+printUseAA+", "+caps); + System.err.println("AWT print.setup "+printGLAD); } } }; @@ -563,6 +609,11 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } printAWTTiles.dispose(); printAWTTiles= null; + if( printGLAD != GLJPanel.this ) { + GLDrawableUtil.swapGLContextAndAllGLEventListener(printGLAD, GLJPanel.this); + printGLAD.destroy(); + } + printGLAD = null; if( null != printAnimator ) { printAnimator.add(GLJPanel.this); printAnimator = null; @@ -582,33 +633,26 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } sendReshape = false; // clear reshape flag handleReshape = false; // ditto - final Graphics2D printGraphics = (Graphics2D)graphics; - if( DEBUG ) { - System.err.println("AWT print.0: canvasSize "+getWidth()+"x"+getWidth()+", printAnimator "+printAnimator); - { - final RenderingHints rHints = printGraphics.getRenderingHints(); - final Set> rEntries = rHints.entrySet(); - int count = 0; - for(Iterator> rEntryIter = rEntries.iterator(); rEntryIter.hasNext(); count++) { - final Entry rEntry = rEntryIter.next(); - System.err.println("Hint["+count+"]: "+rEntry.getKey()+" -> "+rEntry.getValue()); - } + + final Graphics2D g2d = (Graphics2D)graphics; + printAWTTiles.setupGraphics2DAndClipBounds(g2d); + try { + final TileRenderer tileRenderer = printAWTTiles.renderer; + if( DEBUG ) { + System.err.println("AWT print.0: "+tileRenderer); } - final AffineTransform aTrans = printGraphics.getTransform(); - System.err.println(" scale "+aTrans.getScaleX()+" x "+aTrans.getScaleY()); - System.err.println(" move "+aTrans.getTranslateX()+" x "+aTrans.getTranslateY()); - } - printAWTTiles.updateGraphics2DAndClipBounds(printGraphics); - final TileRenderer tileRenderer = printAWTTiles.getTileRenderer(); - if( DEBUG ) { - System.err.println("AWT print.0: "+tileRenderer); + do { + if( printGLAD != GLJPanel.this ) { + tileRenderer.display(); + } else { + backend.doPlainPaint(); + } + } while ( !tileRenderer.eot() ); + } finally { + printAWTTiles.resetGraphics2D(); } - do { - // printRenderer.display(); - backend.doPlainPaint(); - } while ( !tileRenderer.eot() ); if( DEBUG ) { - System.err.println("AWT print.X: "+tileRenderer); + System.err.println("AWT print.X: "+printAWTTiles); } } @Override @@ -803,6 +847,12 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing // so swapping the buffers doesn't do anything. We also don't // currently have the provision to skip copying the data to the // Swing portion of the GLJPanel in any of the rendering paths. + if( printActive && isInitialized) { + final Backend b = backend; + if ( null != b ) { + b.getDrawable().swapBuffers(); + } + } } @Override @@ -1007,7 +1057,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing backend.postGL(g, true); } - public void print(GLAutoDrawable drawable) { + public void plainPaint(GLAutoDrawable drawable) { helper.display(GLJPanel.this); } @@ -1066,7 +1116,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing private final Runnable updaterPlainDisplayAction = new Runnable() { @Override public void run() { - updater.print(GLJPanel.this); + updater.plainPaint(GLJPanel.this); } }; @@ -1405,13 +1455,14 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing gl2es3.glPixelStorei(GL2ES3.GL_PACK_ROW_LENGTH, pixelBuffer.width); gl2es3.glReadBuffer(gl2es3.getDefaultReadBuffer()); } - + + offscreenDrawable.swapBuffers(); + if(null != glslTextureRaster) { // implies flippedVertical // perform vert-flipping via OpenGL/FBO final GLFBODrawable fboDrawable = (GLFBODrawable)offscreenDrawable; final FBObject.TextureAttachment fboTex = fboDrawable.getTextureBuffer(GL.GL_FRONT); - fboDrawable.swapBuffers(); fboFlipped.bind(gl); // gl.glActiveTexture(GL.GL_TEXTURE0 + fboDrawable.getTextureUnit()); // implicit by GLFBODrawableImpl: swapBuffers/contextMadeCurent -> swapFBOImpl diff --git a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java index 7493a19c5..8d07bdb8e 100644 --- a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java +++ b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java @@ -31,6 +31,7 @@ import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Shape; +import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; @@ -51,13 +52,15 @@ import com.jogamp.opengl.util.awt.AWTGLPixelBuffer.AWTGLPixelBufferProvider; *

          */ public class AWTTilePainter { - final private TileRenderer renderer; - final private int componentCount; - final private boolean verbose; + public final TileRenderer renderer; + public final int componentCount; + public final double scaleMatX, scaleMatY; + public final boolean verbose; private AWTGLPixelBuffer tBuffer = null; private BufferedImage vFlipImage = null; private Graphics2D g2d = null; + private AffineTransform saveAT = null; /** * Assumes a configured {@link TileRenderer}, i.e. @@ -69,30 +72,43 @@ public class AWTTilePainter { *

          * componentCount reflects opaque, i.e. 4 if non opaque. *

          + * @param renderer + * @param componentCount + * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels + * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels + * @param verbose */ - public AWTTilePainter(TileRenderer renderer, int componentCount, boolean verbose) { + public AWTTilePainter(TileRenderer renderer, int componentCount, double scaleMatX, double scaleMatY, boolean verbose) { this.renderer = renderer; this.renderer.setGLEventListener(preTileGLEL, postTileGLEL); this.componentCount = componentCount; + this.scaleMatX = scaleMatX; + this.scaleMatY = scaleMatY; this.verbose = verbose; this.renderer.setRowOrder(TileRenderer.TR_TOP_TO_BOTTOM); } public String toString() { return renderer.toString(); } - public TileRenderer getTileRenderer() { return renderer; } - /** * Caches the {@link Graphics2D} instance for rendering. *

          + * Copies the current {@link Graphics2D} {@link AffineTransform} + * and scales {@link Graphics2D} w/ scaleMatX x scaleMatY.
          + * After rendering, the {@link AffineTransform} should be reset via {@link #resetGraphics2D()}. + *

          + *

          * Sets the {@link TileRenderer}'s {@link TileRenderer#setImageSize(int, int) image size} * and {@link TileRenderer#setTileOffset(int, int) tile offset} according the * the {@link Graphics2D#getClipBounds() graphics clip bounds}. *

          * @param g2d */ - public void updateGraphics2DAndClipBounds(Graphics2D g2d) { + public void setupGraphics2DAndClipBounds(Graphics2D g2d) { this.g2d = g2d; + saveAT = g2d.getTransform(); + g2d.scale(scaleMatX, scaleMatY); + final Rectangle gClipOrig = g2d.getClipBounds(); final Rectangle gClip = new Rectangle(gClipOrig); if( 0 > gClip.x ) { @@ -106,10 +122,15 @@ public class AWTTilePainter { if( verbose ) { System.err.println("AWT print.0: "+gClipOrig+" -> "+gClip); } - renderer.setImageSize(gClip.width, gClip.height); + renderer.setImageSize(gClip.width, gClip.height); renderer.setTileOffset(gClip.x, gClip.y); } + /** See {@ #setupGraphics2DAndClipBounds(Graphics2D)}. */ + public void resetGraphics2D() { + g2d.setTransform(saveAT); + } + /** * Disposes resources and {@link TileRenderer#detachFromAutoDrawable() detaches} * the {@link TileRenderer}'s {@link GLAutoDrawable}. @@ -194,24 +215,20 @@ public class AWTTilePainter { } final Shape oClip = g2d.getClip(); g2d.clipRect(pX, pYf, tWidth, tHeight); - final Shape clip = g2d.getClip(); g2d.drawImage(dstImage, pX, pYf, dstImage.getWidth(), dstImage.getHeight(), null); // Null ImageObserver since image data is ready. - g2d.setColor(Color.BLACK); - g2d.drawRect(pX, pYf, tWidth, tHeight); - { + if( verbose ) { + System.err.println("XXX tile-post.X clip "+oClip+" -> "+g2d.getClip()); + g2d.setColor(Color.BLACK); + g2d.drawRect(pX, pYf, tWidth, tHeight); final Rectangle r = oClip.getBounds(); g2d.setColor(Color.YELLOW); g2d.drawRect(r.x, r.y, r.width, r.height); - } - g2d.setClip(oClip); - if( verbose ) { - System.err.println("XXX tile-post.X clip "+oClip+" -> "+clip); System.err.println("XXX tile-post.X "+renderer); System.err.println("XXX tile-post.X dst-img "+dstImage.getWidth()+"x"+dstImage.getHeight()+" -> "+pX+"/"+pYf); } + g2d.setClip(oClip); } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {} - }; - + }; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java index 66be82a44..f38e7ea2b 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java +++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java @@ -69,6 +69,33 @@ public class AWTMisc { return (Container) c; } + public static interface ComponentAction { + /** + * @param c the component to perform the action on + */ + public void run(Component c); + } + + public static int performAction(Container c, Class cType, ComponentAction action) { + int count = 0; + final int cc = c.getComponentCount(); + for(int i=0; i - * We assume AWT painting happens w/ 72 dpi! - *

          + * We fit the frame into the imageable area with for 72 dpi, + * assuming that is the default AWT painting density. *

          * The frame borders are considered. *

          + *

          + * The frame's scale factor is used for the graphics print matrix + * of the overall print-job, hence no frame resize is required. + *

          + *

          + * The GL scale factor 'scaleGLMatXY', 72dpi/glDPI, is passed to the GL object + * which locally scales the print matrix and renders the scene with 1/scaleGLMatXY pixels. + *

          */ final Insets frameInsets = frame.getInsets(); final int frameWidth = frame.getWidth(); final int frameHeight= frame.getHeight(); - final int frameWidthS; - final int frameHeightS; - final double scaleComp; + final double scaleComp72; { final int frameBorderW = frameInsets.left + frameInsets.right; final int frameBorderH = frameInsets.top + frameInsets.bottom; final double sx = pf.getImageableWidth() / ( frameWidth + frameBorderW ); final double sy = pf.getImageableHeight() / ( frameHeight + frameBorderH ); - scaleComp = Math.min(sx, sy) * ( printDPI/72.0 ); - if( 0f < scaleComp ) { - frameWidthS = (int) ( frameWidth*scaleComp ); // cut off FIXME - frameHeightS = (int) ( frameHeight*scaleComp ); // cut off FIXME - } else { - frameWidthS = frameWidth; - frameHeightS = frameHeight; - } + scaleComp72 = Math.min(sx, sy); } - // Since we fit the frame size into the imageable size respecting the DPI, - // we simply can scale the print graphics matrix to the DPI - // w/o the need to fiddle w/ the margins (matrix translation). - final double scaleGraphics = 72.0 / printDPI; - - System.err.println("PRINT offscreen: "+printOffscreen+", thread "+Thread.currentThread().getName()); - System.err.println("PRINT DPI: "+printDPI+", AA "+printAA+", scaleGraphics "+scaleGraphics+", scaleComp "+scaleComp+ - ", frame: border "+frameInsets+", size "+frameWidth+"x"+frameHeight+" -> "+frameWidthS+"x"+frameHeightS); + final double scaleGLMatXY = 72.0 / glDPI; + System.err.println("PRINT thread "+Thread.currentThread().getName()); + System.err.println("PRINT DPI: "+glDPI+", AA "+printAA+", scaleGL "+scaleGLMatXY+", scaleComp72 "+scaleComp72+ + ", frame: border "+frameInsets+", size "+frameWidth+"x"+frameHeight); final Graphics2D printG2D = (Graphics2D)g; - final Graphics2D offscreenG2D; - final BufferedImage offscreenImage; - final Graphics2D g2d; - if( printOffscreen ) { - offscreenImage = new BufferedImage(frameWidthS, frameHeightS, BufferedImage.TYPE_4BYTE_ABGR); - offscreenG2D = (Graphics2D) offscreenImage.getGraphics(); - offscreenG2D.setClip(0, 0, frameWidthS, frameHeightS); - g2d = offscreenG2D; - } else { - offscreenG2D = null; - offscreenImage = null; - g2d = printG2D; + final Graphics2D g2d = printG2D; - g2d.translate(pf.getImageableX(), pf.getImageableY()); - g2d.scale(scaleGraphics, scaleGraphics); - } + g2d.translate(pf.getImageableX(), pf.getImageableY()); + g2d.scale(scaleComp72, scaleComp72); + if( printAA ) { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } - awtPrintObject.setupPrint(g2d); + final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(frame, g2d, scaleGLMatXY, scaleGLMatXY); try { + System.err.println("PRINT AWTPrintLifecycle.setup.count "+ctx.getCount()); AWTEDTExecutor.singleton.invoke(true, new Runnable() { - public void run() { - frame.setSize(frameWidthS, frameHeightS); - frame.invalidate(); - frame.validate(); - } - }); - - AWTEDTExecutor.singleton.invoke(true, new Runnable() { - public void run() { - frame.printAll(g2d); - } } ); - - System.err.println("PRINT DPI: reset frame size "+frameWidth+"x"+frameHeight); - AWTEDTExecutor.singleton.invoke(true, new Runnable() { - public void run() { - frame.setSize(frameWidth, frameHeight); - frame.invalidate(); - frame.validate(); + public void run() { + frame.printAll(g2d); } }); } finally { - awtPrintObject.releasePrint(); - } - - if( printOffscreen ) { - printG2D.translate(pf.getImageableX(), pf.getImageableY()); - printG2D.scale(scaleGraphics, scaleGraphics); - printG2D.drawImage(offscreenImage, 0, 0, offscreenImage.getWidth(), offscreenImage.getHeight(), null); // Null ImageObserver since image data is ready. + ctx.releasePrint(); + System.err.println("PRINT AWTPrintLifecycle.release.count "+ctx.getCount()); } /* tell the caller that this page is part of the printed document */ @@ -230,8 +187,7 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab super(); } - public void doPrintAuto(Frame frame, AWTPrintLifecycle awtPrintObject, - Printable printable, int pOrientation, Paper paper, boolean offscreen, int dpi, boolean antialiasing) { + public void doPrintAuto(Frame frame, int pOrientation, Paper paper, int dpi, boolean antialiasing) { lock.lock(); try { final PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); @@ -253,7 +209,7 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab FileOutputStream outstream; try { outstream = new FileOutputStream(fname); - Assert.assertTrue(doPrintAutoImpl(frame, awtPrintObject, printable, pj, factories[0].getPrintService(outstream), pOrientation, paper, offscreen, dpi, antialiasing)); + Assert.assertTrue(doPrintAutoImpl(frame, pj, factories[0].getPrintService(outstream), pOrientation, paper, dpi, antialiasing)); } catch (FileNotFoundException e) { Assert.assertNull("Unexpected exception", e); } @@ -268,7 +224,7 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab FileOutputStream outstream; try { outstream = new FileOutputStream(fname); - Assert.assertTrue(doPrintAutoImpl(frame, awtPrintObject, printable, pj, factories[0].getPrintService(outstream), pOrientation, paper, offscreen, dpi, antialiasing)); + Assert.assertTrue(doPrintAutoImpl(frame, pj, factories[0].getPrintService(outstream), pOrientation, paper, dpi, antialiasing)); } catch (FileNotFoundException e) { Assert.assertNull("Unexpected exception", e); } @@ -285,13 +241,11 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab final String sAA = antialiasing ? "aa_" : "raw"; return String.format("%-"+maxSimpleTestNameLen+"s-n%04d-dpi%03d-%s.%s", simpleTestName, printCount, dpi, sAA, suffix).replace(' ', '_'); } - private boolean doPrintAutoImpl(Frame frame, AWTPrintLifecycle awtPrintObject, - Printable printable, PrinterJob job, StreamPrintService ps, int pOrientation, - Paper paper, boolean offscreen, int dpi, boolean antialiasing) { - this.awtPrintObject = awtPrintObject; + private boolean doPrintAutoImpl(Frame frame, PrinterJob job, + StreamPrintService ps, int pOrientation, Paper paper, int dpi, + boolean antialiasing) { this.frame = frame; - printOffscreen = offscreen; - printDPI = dpi; + glDPI = dpi; printAA = antialiasing; boolean ok = true; try { @@ -305,7 +259,7 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab } pageFormat.setOrientation(pOrientation); // PageFormat.LANDSCAPE or PageFormat.PORTRAIT job.setPrintService(ps); - job.setPrintable(printable, pageFormat); + job.setPrintable(this, pageFormat); job.print(); } catch (PrinterException pe) { pe.printStackTrace(); @@ -314,16 +268,14 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab return ok; } - public void doPrintManual(Frame frame, AWTPrintLifecycle awtPrintObject, Printable printable, boolean offscreen, int dpi, boolean antialiasing) { + public void doPrintManual(Frame frame, int dpi, boolean antialiasing) { lock.lock(); try { - this.awtPrintObject = awtPrintObject; this.frame = frame; - printOffscreen = offscreen; - printDPI = dpi; + glDPI = dpi; printAA = antialiasing; PrinterJob job = PrinterJob.getPrinterJob(); - job.setPrintable(printable); + job.setPrintable(this); boolean ok = job.printDialog(); if (ok) { try { -- cgit v1.2.3 From 6c823db5c504d29a4a54c6756e4e3113848d39dd Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 8 Sep 2013 13:39:27 +0200 Subject: Fix some JavaDoc and API doc (reference) bugs .. --- .../classes/javax/media/opengl/GLAutoDrawable.java | 24 ++++++----- src/jogl/classes/javax/media/opengl/GLBase.java | 9 ++-- .../classes/javax/media/opengl/GLCapabilities.java | 7 ++-- src/jogl/classes/javax/media/opengl/GLContext.java | 49 ++++++++++++---------- .../classes/javax/media/opengl/GLDebugMessage.java | 4 ++ .../classes/javax/media/opengl/GLDrawable.java | 2 +- .../javax/media/opengl/GLDrawableFactory.java | 12 +++--- .../classes/javax/media/opengl/GLFBODrawable.java | 8 ++-- src/jogl/classes/javax/media/opengl/GLProfile.java | 4 +- .../jogamp/nativewindow/WrappedSurface.java | 5 +++ .../jogamp/nativewindow/windows/GDISurface.java | 2 + 11 files changed, 72 insertions(+), 54 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java index bdbbd96a5..989a61aaf 100644 --- a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java +++ b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java @@ -48,12 +48,14 @@ import jogamp.opengl.Debug; 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. + the lifetime of the object. +

          + Since the {@link GLContext} {@link GLContext#makeCurrent makeCurrent} + implementation is synchronized, i.e. blocks if the context + is current on another thread, the internal + {@link GLContext} for the GLAutoDrawable can be used for the event + based rendering mechanism and by end users directly. +

          The implementation shall initialize itself as soon as possible, ie if the attached {@link javax.media.nativewindow.NativeSurface NativeSurface} becomes visible/realized. @@ -310,9 +312,9 @@ public interface GLAutoDrawable extends GLDrawable { *

          * Impacts {@link #display()} and {@link #invoke(boolean, GLRunnable)} semantics.


          * - * @param animator null reference indicates no animator is using - * this GLAutoDrawable,
          - * a valid reference indicates an animator is using this GLAutoDrawable. + * @param animatorControl null reference indicates no animator is using + * this GLAutoDrawable,
          + * a valid reference indicates an animator is using this GLAutoDrawable. * * @throws GLException if an animator is already registered. * @see #display() @@ -406,7 +408,7 @@ public interface GLAutoDrawable extends GLDrawable { * @see #setAnimator(GLAnimatorControl) * @see #display() * @see GLRunnable - * @see #enqueue(GLRunnable) + * @see #invoke(boolean, List) */ public boolean invoke(boolean wait, GLRunnable glRunnable); @@ -416,6 +418,7 @@ public interface GLAutoDrawable extends GLDrawable { * @param wait if true block until execution of the last glRunnable is finished, otherwise return immediately w/o waiting * @param glRunnables the {@link GLRunnable}s to execute within {@link #display()} * @return true if the {@link GLRunnable}s has been processed or queued, otherwise false. + * @see #invoke(boolean, GLRunnable) */ public boolean invoke(boolean wait, List glRunnables); @@ -540,7 +543,6 @@ public interface GLAutoDrawable extends GLDrawable { * This method may also return null if no UI toolkit is being used, * as common for offscreen rendering. *

          - * @return */ public Object getUpstreamWidget(); diff --git a/src/jogl/classes/javax/media/opengl/GLBase.java b/src/jogl/classes/javax/media/opengl/GLBase.java index 07dfc7e72..1f75a7b4a 100644 --- a/src/jogl/classes/javax/media/opengl/GLBase.java +++ b/src/jogl/classes/javax/media/opengl/GLBase.java @@ -436,7 +436,6 @@ public interface GLBase { * NPOT textures are supported in OpenGL >= 3, GLES2 or if the * 'GL_ARB_texture_non_power_of_two' extension is available. *

          - * @return */ public boolean isNPOTTextureAvailable(); @@ -518,12 +517,12 @@ public interface GLBase { public long glGetBufferSize(int buffer); /** - * @return true if a VBO is bound to {@link GL.GL_ARRAY_BUFFER} via {@link GL#glBindBuffer(int, int)}, otherwise false + * @return true if a VBO is bound to {@link GL#GL_ARRAY_BUFFER} via {@link GL#glBindBuffer(int, int)}, otherwise false */ public boolean glIsVBOArrayBound(); /** - * @return true if a VBO is bound to {@link GL.GL_ELEMENT_ARRAY_BUFFER} via {@link GL#glBindBuffer(int, int)}, otherwise false + * @return true if a VBO is bound to {@link GL#GL_ELEMENT_ARRAY_BUFFER} via {@link GL#glBindBuffer(int, int)}, otherwise false */ public boolean glIsVBOElementArrayBound(); @@ -537,7 +536,7 @@ public interface GLBase { * Return the default draw framebuffer name. *

          * May differ from it's default zero - * in case an framebuffer object ({@link FBObject}) based drawable + * in case an framebuffer object ({@link com.jogamp.opengl.FBObject}) based drawable * is being used. *

          */ @@ -547,7 +546,7 @@ public interface GLBase { * Return the default read framebuffer name. *

          * May differ from it's default zero - * in case an framebuffer object ({@link FBObject}) based drawable + * in case an framebuffer object ({@link com.jogamp.opengl.FBObject}) based drawable * is being used. *

          */ diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilities.java b/src/jogl/classes/javax/media/opengl/GLCapabilities.java index 5b3eb9119..872069fb8 100644 --- a/src/jogl/classes/javax/media/opengl/GLCapabilities.java +++ b/src/jogl/classes/javax/media/opengl/GLCapabilities.java @@ -50,7 +50,8 @@ import javax.media.nativewindow.CapabilitiesImmutable; must support, such as the OpenGL profile, color depth and whether stereo is enabled.
          The actual capabilites of created {@link GLDrawable}s are then reflected by their own - GLCapabilites instance, which can be queried with {@link GLDrawable#getGLCapabilities()}.
          + GLCapabilites instance, which can be queried with {@link GLDrawable#getChosenGLCapabilities()}. +
          It currently contains the minimal number of routines which allow configuration on all supported window systems. */ @@ -246,7 +247,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil /** * Requesting offscreen pbuffer mode. *

          - * If enabled this method also invokes {@link #setOnscreen(int) setOnscreen(false)}. + * If enabled this method also invokes {@link #setOnscreen(boolean) setOnscreen(false)}. *

          *

          * Defaults to false. @@ -270,7 +271,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil /** * Requesting offscreen FBO mode. *

          - * If enabled this method also invokes {@link #setOnscreen(int) setOnscreen(false)}. + * If enabled this method also invokes {@link #setOnscreen(boolean) setOnscreen(false)}. *

          *

          * Defaults to false. diff --git a/src/jogl/classes/javax/media/opengl/GLContext.java b/src/jogl/classes/javax/media/opengl/GLContext.java index 618ee2584..854d96807 100644 --- a/src/jogl/classes/javax/media/opengl/GLContext.java +++ b/src/jogl/classes/javax/media/opengl/GLContext.java @@ -283,8 +283,9 @@ public abstract class GLContext { * this context is made current on another thread. * * @see #isGLReadDrawableAvailable() + * @see #setGLReadDrawable(GLDrawable) * @see #getGLReadDrawable() - * @see #setGLReadDrawable() + * @see #setGLDrawable(GLDrawable, boolean) * @see #getGLDrawable() */ public abstract GLDrawable setGLDrawable(GLDrawable readWrite, boolean setWriteOnly); @@ -334,8 +335,8 @@ public abstract class GLContext { * it equals to the write-drawable (default). *

          * @see #isGLReadDrawableAvailable() - * @see #setGLReadDrawable(javax.media.opengl.GLDrawable) - * @see #getGLDrawable() + * @see #setGLReadDrawable(GLDrawable) + * @see #getGLReadDrawable() */ public abstract GLDrawable getGLReadDrawable(); @@ -407,7 +408,7 @@ public abstract class GLContext { * parameter indicates which groups of state variables are to be * copied. mask contains the bitwise OR of the same * symbolic names that are passed to the GL command {@link - * GL#glPushAttrib glPushAttrib}. The single symbolic constant + * GL2#glPushAttrib glPushAttrib}. The single symbolic constant * {@link GL2#GL_ALL_ATTRIB_BITS GL_ALL_ATTRIB_BITS} can be used to * copy the maximum possible portion of rendering state.

          * @@ -1115,7 +1116,9 @@ public abstract class GLContext { /** * Indicates whether this GLContext is capable of GL2ES3.

          Includes [ GL4bc, GL4, GL3bc, GL3, GLES3, GL3ES3, GL2, GL2GL3 ].

          - * @see GLProfile#isGL2ES3() + * @see GLProfile#isGL2ES3() + * @see #isGL3ES3() + * @see #isGL2GL3() */ public final boolean isGL2ES3() { return isGL3ES3() || isGL2GL3(); @@ -1216,7 +1219,7 @@ public abstract class GLContext { * Return the default draw framebuffer name. *

          * May differ from it's default zero - * in case an framebuffer object ({@link FBObject}) based drawable + * in case an framebuffer object ({@link com.jogamp.opengl.FBObject}) based drawable * is being used. *

          */ @@ -1226,7 +1229,7 @@ public abstract class GLContext { * Return the default read framebuffer name. *

          * May differ from it's default zero - * in case an framebuffer object ({@link FBObject}) based drawable + * in case an framebuffer object ({@link com.jogamp.opengl.FBObject}) based drawable * is being used. *

          */ @@ -1253,23 +1256,23 @@ public abstract class GLContext { /** * @return The extension implementing the GLDebugOutput feature, - * either GL_ARB_debug_output or GL_AMD_debug_output. + * either {@link GLExtensions#ARB_debug_output} or {@link GLExtensions#AMD_debug_output}. * If unavailable or called before initialized via {@link #makeCurrent()}, null is returned. */ public abstract String getGLDebugMessageExtension(); /** - * @return the current synchronous debug behavior via - * @see #setSynchronous(boolean) + * @return the current synchronous debug behavior, set via {@link #setGLDebugSynchronous(boolean)}. */ public abstract boolean isGLDebugSynchronous(); /** * Enables or disables the synchronous debug behavior via - * {@link GL2GL3#GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB glEnable/glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB)}, - * if extension is {@link #GL_ARB_debug_output}. - * There is no equivalent for {@link #GL_AMD_debug_output}. - *

          The default is true, ie {@link GL2GL3#GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB}.

          + * {@link GL2GL3#GL_DEBUG_OUTPUT_SYNCHRONOUS glEnable/glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS)}, + * if extension is {@link GLExtensions#ARB_debug_output}. + * There is no equivalent for {@link GLExtensions#AMD_debug_output}. + *

          The default is true, ie {@link GL2GL3#GL_DEBUG_OUTPUT_SYNCHRONOUS}.

          + * @link {@link #isGLDebugSynchronous()} */ public abstract void setGLDebugSynchronous(boolean synchronous); @@ -1279,8 +1282,8 @@ public abstract class GLContext { public abstract boolean isGLDebugMessageEnabled(); /** - * Enables or disables the GLDebugOutput feature of extension GL_ARB_debug_output - * or GL_AMD_debug_output, if available. + * Enables or disables the GLDebugOutput feature of extension {@link GLExtensions#ARB_debug_output} + * or {@link GLExtensions#AMD_debug_output}, if available. * *

          To enable the GLDebugOutput feature {@link #enableGLDebugMessage(boolean) enableGLDebugMessage(true)} * or {@link #setContextCreationFlags(int) setContextCreationFlags}({@link GLContext#CTX_OPTION_DEBUG}) @@ -1305,7 +1308,7 @@ public abstract class GLContext { /** * Add {@link GLDebugListener}.
          * - * @param listener {@link GLDebugListener} handling {@GLDebugMessage}s + * @param listener {@link GLDebugListener} handling {@link GLDebugMessage}s * @see #enableGLDebugMessage(boolean) * @see #removeGLDebugListener(GLDebugListener) */ @@ -1314,28 +1317,28 @@ public abstract class GLContext { /** * Remove {@link GLDebugListener}.
          * - * @param listener {@link GLDebugListener} handling {@GLDebugMessage}s + * @param listener {@link GLDebugListener} handling {@link GLDebugMessage}s * @see #enableGLDebugMessage(boolean) * @see #addGLDebugListener(GLDebugListener) */ public abstract void removeGLDebugListener(GLDebugListener listener); /** - * Generic entry for {@link GL2GL3#glDebugMessageControlARB(int, int, int, int, IntBuffer, boolean)} + * Generic entry for {@link GL2GL3#glDebugMessageControl(int, int, int, int, IntBuffer, boolean)} * and {@link GL2GL3#glDebugMessageEnableAMD(int, int, int, IntBuffer, boolean)} of the GLDebugOutput feature. * @see #enableGLDebugMessage(boolean) */ public abstract void glDebugMessageControl(int source, int type, int severity, int count, IntBuffer ids, boolean enabled); /** - * Generic entry for {@link GL2GL3#glDebugMessageControlARB(int, int, int, int, int[], int, boolean)} + * Generic entry for {@link GL2GL3#glDebugMessageControl(int, int, int, int, int[], int, boolean)} * and {@link GL2GL3#glDebugMessageEnableAMD(int, int, int, int[], int, boolean)} of the GLDebugOutput feature. * @see #enableGLDebugMessage(boolean) */ public abstract void glDebugMessageControl(int source, int type, int severity, int count, int[] ids, int ids_offset, boolean enabled); /** - * Generic entry for {@link GL2GL3#glDebugMessageInsertARB(int, int, int, int, int, String)} + * Generic entry for {@link GL2GL3#glDebugMessageInsert(int, int, int, int, int, String)} * and {@link GL2GL3#glDebugMessageInsertAMD(int, int, int, int, String)} of the GLDebugOutput feature. * @see #enableGLDebugMessage(boolean) */ @@ -1485,8 +1488,8 @@ public abstract class GLContext { } /** - * Called by {@link jogamp.opengl.GLContextImpl#createContextARBMapVersionsAvailable} not intended to be used by - * implementations. However, if {@link #createContextARB} is not being used within + * Called by {@link jogamp.opengl.GLContextImpl#createContextARBMapVersionsAvailable(int,int)} not intended to be used by + * implementations. However, if {@link jogamp.opengl.GLContextImpl#createContextARB(long, boolean)} is not being used within * {@link javax.media.opengl.GLDrawableFactory#getOrCreateSharedContext(javax.media.nativewindow.AbstractGraphicsDevice)}, * GLProfile has to map the available versions. * diff --git a/src/jogl/classes/javax/media/opengl/GLDebugMessage.java b/src/jogl/classes/javax/media/opengl/GLDebugMessage.java index f8959e653..4b8d62898 100644 --- a/src/jogl/classes/javax/media/opengl/GLDebugMessage.java +++ b/src/jogl/classes/javax/media/opengl/GLDebugMessage.java @@ -29,6 +29,10 @@ package javax.media.opengl; import com.jogamp.common.os.Platform; +/** + * OpenGL debug message generated by the driver + * and delivered via {@link GLDebugListener}. + */ public class GLDebugMessage { final GLContext source; final long when; diff --git a/src/jogl/classes/javax/media/opengl/GLDrawable.java b/src/jogl/classes/javax/media/opengl/GLDrawable.java index 369ea6d2b..46fa923ad 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawable.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawable.java @@ -202,7 +202,7 @@ public interface GLDrawable { *

          * On EGL it is represented by the EGLSurface.
          * On X11/GLX it is represented by either the Window XID, GLXPixmap, or GLXPbuffer.
          - * On Windows it is represented by the HDC, which may change with each {@link #lockSurface()}.
          + * On Windows it is represented by the HDC, which may change with each {@link NativeSurface#lockSurface()}.
          *

          * @see #setRealized(boolean) * @see NativeSurface#lockSurface() diff --git a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java index c2e7e0829..7c3c42e45 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java @@ -336,7 +336,7 @@ public abstract class GLDrawableFactory { * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be null for the platform's default device. * @param quirk the quirk to be tested, e.g. {@link GLRendererQuirks#NoDoubleBufferedPBuffer}. * @throws IllegalArgumentException if the quirk is out of range - * @see #getRendererQuirks() + * @see #getRendererQuirks(AbstractGraphicsDevice) * @see GLRendererQuirks */ public final boolean hasRendererQuirk(AbstractGraphicsDevice device, int quirk) { @@ -459,7 +459,7 @@ public abstract class GLDrawableFactory { * @see javax.media.opengl.GLCapabilities#isOnscreen() * @see javax.media.opengl.GLCapabilities#isFBO() * @see javax.media.opengl.GLCapabilities#isPBuffer() - * @see javax.media.nativewindow.GraphicsConfigurationFactory#chooseGraphicsConfiguration(Capabilities, CapabilitiesChooser, AbstractGraphicsScreen) + * @see javax.media.nativewindow.GraphicsConfigurationFactory#chooseGraphicsConfiguration(CapabilitiesImmutable, CapabilitiesImmutable, javax.media.nativewindow.CapabilitiesChooser, AbstractGraphicsScreen, int) */ public abstract GLDrawable createGLDrawable(NativeSurface target) throws IllegalArgumentException, GLException; @@ -560,7 +560,8 @@ public abstract class GLDrawableFactory { public abstract GLDrawable createDummyDrawable(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLProfile glp); /** - * Creates a proxy {@link NativeSurface} w/ defined surface handle, i.e. a {@link WrappedSurface} or {@link GDISurface} instance. + * Creates a proxy {@link NativeSurface} w/ defined surface handle, + * i.e. a {@link jogamp.nativewindow.WrappedSurface} or {@link jogamp.nativewindow.windows.GDISurface} instance. *

          * It's {@link AbstractGraphicsConfiguration} is properly set according to the given * windowHandle's native visualID if set or the given {@link GLCapabilitiesImmutable}. @@ -571,7 +572,8 @@ public abstract class GLDrawableFactory { *

          *

          * Such surface can be used to instantiate a GLDrawable. With the help of {@link GLAutoDrawableDelegate} - * you will be able to implement a new native windowing system binding almost on-the-fly, see {@link com.jogamp.opengl.swt.GLCanvas}. + * you will be able to implement a new native windowing system binding almost on-the-fly, + * see {@link com.jogamp.opengl.swt.GLCanvas}. *

          * * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be null for the platform's default device. @@ -580,7 +582,7 @@ public abstract class GLDrawableFactory { * @param windowHandle the native window handle * @param caps the requested GLCapabilties * @param chooser the custom chooser, may be null for default - * @param upstream optional {@link ProxySurface.UpstreamSurfaceHook} allowing control of the {@link ProxySurface}'s lifecycle and data it presents. + * @param upstream optional {@link UpstreamSurfaceHook} allowing control of the {@link ProxySurface}'s lifecycle and data it presents. * @return the created {@link ProxySurface} instance w/ defined surface handle. */ public abstract ProxySurface createProxySurface(AbstractGraphicsDevice device, diff --git a/src/jogl/classes/javax/media/opengl/GLFBODrawable.java b/src/jogl/classes/javax/media/opengl/GLFBODrawable.java index 4d6c7c20e..df38745d5 100644 --- a/src/jogl/classes/javax/media/opengl/GLFBODrawable.java +++ b/src/jogl/classes/javax/media/opengl/GLFBODrawable.java @@ -62,14 +62,14 @@ import com.jogamp.opengl.FBObject.TextureAttachment; *

          *

          * It would be possible to implement double buffering simply using - * {@link FBObject.TextureAttachment texture attachment}s with one {@link FBObject framebuffer}. + * {@link TextureAttachment}s with one {@link FBObject framebuffer}. * This would require mode selection and hence complicate the API. Besides, it would * not support differentiation of read and write framebuffer and hence not be spec compliant. *

          *

          - * Actual swapping of the {@link FBObject.TextureAttachment texture}s or {@link FBObject framebuffer} - * is performed either in the {@link #contextMadeCurrent(boolean) context current hook} - * or when {@link #swapBuffersImpl(boolean) swapping buffers}, whatever comes first.
          + * Actual swapping of the {@link TextureAttachment texture}s and/or {@link FBObject framebuffer} + * is performed either in the {@link jogamp.opengl.GLContextImpl#contextMadeCurrent(boolean) context current hook} + * or when {@link jogamp.opengl.GLDrawableImpl#swapBuffersImpl(boolean) swapping buffers}, whatever comes first. *

          */ public interface GLFBODrawable extends GLDrawable { diff --git a/src/jogl/classes/javax/media/opengl/GLProfile.java b/src/jogl/classes/javax/media/opengl/GLProfile.java index b5e89a23b..1dde2cbb6 100644 --- a/src/jogl/classes/javax/media/opengl/GLProfile.java +++ b/src/jogl/classes/javax/media/opengl/GLProfile.java @@ -1130,8 +1130,8 @@ public class GLProfile { /** * Indicates whether this profile is capable of GL2ES3.

          Includes [ GL4bc, GL4, GL3bc, GL3, GLES3, GL3ES3, GL2, GL2GL3 ].

          - * @see isGL3ES3() - * @see isGL2GL3() + * @see #isGL3ES3() + * @see #isGL2GL3() */ public final boolean isGL2ES3() { return isGL3ES3() || isGL2GL3(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java b/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java index e544bc61a..c94f249a1 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java +++ b/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java @@ -35,6 +35,11 @@ import javax.media.nativewindow.UpstreamSurfaceHook; import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; +/** + * Generic Surface implementation which wraps an existing window handle. + * + * @see ProxySurface + */ public class WrappedSurface extends ProxySurfaceImpl { protected long surfaceHandle; diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java index 3db2b5fc9..cc9c9853b 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java @@ -43,6 +43,8 @@ import jogamp.nativewindow.windows.GDI; * allowing the use of HDC via lockSurface()/unlockSurface() protocol. * The latter will get and release the HDC. * The size via getWidth()/getHeight() is invalid. + * + * @see ProxySurface */ public class GDISurface extends ProxySurfaceImpl { protected long windowHandle; -- cgit v1.2.3 From 5dce252bfcc49995c2bda1d91e010c4c73f71ddb Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 13 Sep 2013 19:21:52 +0200 Subject: Add support for clang ; Use __APPLE__ predefined macro --- make/config/jogl/gl-headers.cfg | 2 +- make/config/jogl/gl3-headers.cfg | 2 +- make/config/jogl/glu-gl2.cfg | 2 +- make/scripts/make.jogl.all.macosx-clang.sh | 28 +++++++++++++++++++++++ src/nativewindow/native/JAWT_DrawingSurfaceInfo.c | 2 +- 5 files changed, 32 insertions(+), 4 deletions(-) create mode 100755 make/scripts/make.jogl.all.macosx-clang.sh (limited to 'src/nativewindow') diff --git a/make/config/jogl/gl-headers.cfg b/make/config/jogl/gl-headers.cfg index 62f5e8dd4..073f9d9a0 100644 --- a/make/config/jogl/gl-headers.cfg +++ b/make/config/jogl/gl-headers.cfg @@ -15,7 +15,7 @@ CustomCCode #define WGL_GLEXT_PROTOTYPES CustomCCode /* Include the OpenGL headers */ CustomCCode #include CustomCCode #include -CustomCCode #elif defined(macosx) +CustomCCode #elif defined(__APPLE__) CustomCCode #include CustomCCode #include CustomCCode /* Include the OpenGL headers */ diff --git a/make/config/jogl/gl3-headers.cfg b/make/config/jogl/gl3-headers.cfg index 7ab5099c9..a4c5cf62a 100644 --- a/make/config/jogl/gl3-headers.cfg +++ b/make/config/jogl/gl3-headers.cfg @@ -10,7 +10,7 @@ CustomCCode #include CustomCCode #include CustomCCode #include CustomCCode #include -CustomCCode #elif defined(macosx) +CustomCCode #elif defined(__APPLE__) CustomCCode #include CustomCCode #include CustomCCode #include diff --git a/make/config/jogl/glu-gl2.cfg b/make/config/jogl/glu-gl2.cfg index 2dcc15a94..491d9224f 100644 --- a/make/config/jogl/glu-gl2.cfg +++ b/make/config/jogl/glu-gl2.cfg @@ -15,7 +15,7 @@ CustomCCode #include CustomCCode #undef WIN32_LEAN_AND_MEAN CustomCCode CustomCCode #include -CustomCCode #elif defined(macosx) +CustomCCode #elif defined(__APPLE__) CustomCCode #include CustomCCode #include CustomCCode #include diff --git a/make/scripts/make.jogl.all.macosx-clang.sh b/make/scripts/make.jogl.all.macosx-clang.sh new file mode 100755 index 000000000..af9f1e1fe --- /dev/null +++ b/make/scripts/make.jogl.all.macosx-clang.sh @@ -0,0 +1,28 @@ +#! /bin/sh + +if [ -e /opt-share/etc/profile.ant ] ; then + . /opt-share/etc/profile.ant +fi + +JAVA_HOME=`/usr/libexec/java_home -version 1.7` +PATH=$JAVA_HOME/bin:$PATH +export JAVA_HOME PATH + +# -Dc.compiler.debug=true \ +# -Djavacdebug="true" \ +# -Djavacdebuglevel="source,lines,vars" \ +# + +export SOURCE_LEVEL=1.6 +export TARGET_LEVEL=1.6 +export TARGET_RT_JAR=/opt-share/jre1.6.0_30/lib/rt.jar + +export GLUEGEN_PROPERTIES_FILE="../../gluegen/make/lib/gluegen-clang.properties" +# or -Dgcc.compat.compiler=clang + +#export JOGAMP_JAR_CODEBASE="Codebase: *.jogamp.org" +export JOGAMP_JAR_CODEBASE="Codebase: *.goethel.localnet" + +ant \ + -Drootrel.build=build-macosx \ + $* 2>&1 | tee make.jogl.all.macosx.log diff --git a/src/nativewindow/native/JAWT_DrawingSurfaceInfo.c b/src/nativewindow/native/JAWT_DrawingSurfaceInfo.c index 2a6651007..5c77b6d46 100644 --- a/src/nativewindow/native/JAWT_DrawingSurfaceInfo.c +++ b/src/nativewindow/native/JAWT_DrawingSurfaceInfo.c @@ -43,7 +43,7 @@ #define PLATFORM_DSI_SIZE sizeof(JAWT_Win32DrawingSurfaceInfo) #elif defined(linux) || defined(__sun) || defined(__FreeBSD__) || defined(_HPUX) #define PLATFORM_DSI_SIZE sizeof(JAWT_X11DrawingSurfaceInfo) -#elif defined(macosx) +#elif defined(__APPLE__) #define PLATFORM_DSI_SIZE sizeof(JAWT_MacOSXDrawingSurfaceInfo) #else ERROR: port JAWT_DrawingSurfaceInfo.c to your platform -- cgit v1.2.3 From c2ce31e11eefcf1b900c0e9b41264f5d5566dc46 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 15 Sep 2013 23:27:16 +0200 Subject: Fix AWT printing issues w/ overlapping and/or non-opaque contents ; Change AWTPrintLifecycle's lifecycle - AWTPrintLifecycle: - Should decorate: PrinterJob.print(..), instead of within Printable.print(..) { .. container.printAll(..); .. } This is due to AWT print implementation, i.e. AWT will issue Printable.print(..) multiple times for 'overlapping' or non-opaque elements! - Move from javax.media.opengl.awt -> com.jogamp.nativewindow.awt - Make _interface_ AWT agnostic, i.e. remove Graphics2D from 'setup(..)' - Add 'int numSamples' to 'setup(..)' to determine the number of samples - AWTTilePrinter: - Use double precision when scaling image-size and clip-rect, then round them to integer values. Otherwise AWT will use the bounding box for the clipping-rectangular. - Clip negative portion of clip-rect, this removes redundant overpaints, as well as increasing the tile count due to the increased clipping-size. - Clip the image-size in the tile-renderer according to the clip-rect. - DEBUG_TILES: Dump tiles to file - Use sub-image of final BuffereImage instead of adding another clipping region. This might increase performance if no clip-rect has been set. TODO: TestTiledPrintingGearsSwingAWT overlapping tests exposes a 'off by one' bug of the first layer's background! Note: The GL content seems to be correct though - maybe it's simply an AWT rounding error .. --- .../javax/media/opengl/awt/AWTPrintLifecycle.java | 162 ------------------ .../classes/javax/media/opengl/awt/GLCanvas.java | 33 ++-- .../classes/javax/media/opengl/awt/GLJPanel.java | 47 ++--- .../classes/jogamp/opengl/awt/AWTTilePainter.java | 189 ++++++++++++++++----- .../jogamp/nativewindow/awt/AWTPrintLifecycle.java | 168 ++++++++++++++++++ .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 63 +++---- .../junit/jogl/tile/TestTiledPrintingGearsAWT.java | 14 +- .../jogl/tile/TestTiledPrintingGearsNewtAWT.java | 14 +- .../jogl/tile/TestTiledPrintingGearsSwingAWT.java | 73 ++++++-- .../test/junit/jogl/tile/TiledPrintingAWTBase.java | 123 ++++++++------ 10 files changed, 501 insertions(+), 385 deletions(-) delete mode 100644 src/jogl/classes/javax/media/opengl/awt/AWTPrintLifecycle.java create mode 100644 src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/awt/AWTPrintLifecycle.java b/src/jogl/classes/javax/media/opengl/awt/AWTPrintLifecycle.java deleted file mode 100644 index 1a4c5bac0..000000000 --- a/src/jogl/classes/javax/media/opengl/awt/AWTPrintLifecycle.java +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Copyright 2013 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ -package javax.media.opengl.awt; - -import javax.media.opengl.GLAutoDrawable; -import java.awt.Component; -import java.awt.Container; -import java.awt.Graphics; -import java.awt.Graphics2D; - -import jogamp.nativewindow.awt.AWTMisc; - -/** - * Interface describing print lifecycle to support AWT printing - * on AWT {@link GLAutoDrawable}s. - *
          Implementations
          - *

          - * Implementing {@link GLAutoDrawable} classes based on AWT - * supporting {@link Component#print(Graphics)} shall implement this interface. - *

          - *
          Usage
          - *

          - * Users attempting to print an AWT {@link Container} containing {@link AWTPrintLifecycle} elements - * shall consider decorating the {@link Container#printAll(Graphics)} call with
          - * {@link #setupPrint(Graphics2D, double, double) setupPrint(..)} and {@link #releasePrint()} - * on all {@link AWTPrintLifecycle} elements in the {@link Container}.
          - * To minimize this burden, a user can use {@link Context#setupPrint(Container, Graphics2D, double, double) Context.setupPrint(..)}: - *

          - *  Graphics2D g2d;
          - *  Frame frame;
          - *  double scaleGLMatXY = 72.0/glDPI;
          - *  ...
          -    final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(frame, g2d, scaleGLMatXY, scaleGLMatXY);
          -    try {
          -       AWTEDTExecutor.singleton.invoke(true, new Runnable() {
          -            public void run() {
          -                frame.printAll(g2d);
          -           } });
          -    } finally {
          -       ctx.releasePrint();
          -    }
          - * 
          - * 
          - *

          - */ -public interface AWTPrintLifecycle { - - public static final int DEFAULT_PRINT_TILE_SIZE = 512; - - - /** - * Shall be called before {@link Component#print(Graphics)}. - *

          - * See Usage. - *

          - * @param g2d the {@link Graphics2D} instance, which will be used for printing. - * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels - * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels - */ - void setupPrint(Graphics2D g2d, double scaleMatX, double scaleMatY); - - /** - * Shall be called after very last {@link Component#print(Graphics)}. - *

          - * See Usage. - *

          - */ - void releasePrint(); - - /** - * Convenient {@link AWTPrintLifecycle} context simplifying calling {@link AWTPrintLifecycle#setupPrint(Graphics2D, double, double) setupPrint(..)} - * and {@link AWTPrintLifecycle#releasePrint()} on all {@link AWTPrintLifecycle} elements of a {@link Container}. - *

          - * See Usage. - *

          - */ - public static class Context { - /** - *

          - * See Usage. - *

          - * - * @param c container to be traversed through to perform {@link AWTPrintLifecycle#setupPrint(Graphics2D, double, double) setupPrint(..)} on all {@link AWTPrintLifecycle} elements. - * @param g2d the {@link Graphics2D} instance, which will be used for printing. - * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels - * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels - * @return the context - */ - public static Context setupPrint(Container c, Graphics2D g2d, double scaleMatX, double scaleMatY) { - final Context t = new Context(c, g2d, scaleMatX, scaleMatY); - t.setupPrint(c); - return t; - } - - /** - *

          - * See Usage. - *

          - */ - public void releasePrint() { - count = AWTMisc.performAction(cont, AWTPrintLifecycle.class, releaseAction); - } - - /** - * @return count of performed actions of last {@link #setupPrint(Container, Graphics2D, double, double) setupPrint(..)} or {@link #releasePrint()}. - */ - public int getCount() { return count; } - - private final Container cont; - private final Graphics2D g2d; - private final double scaleMatX; - private final double scaleMatY; - private int count; - - private final AWTMisc.ComponentAction setupAction = new AWTMisc.ComponentAction() { - @Override - public void run(Component c) { - ((AWTPrintLifecycle)c).setupPrint(g2d, scaleMatX, scaleMatY); - } }; - private final AWTMisc.ComponentAction releaseAction = new AWTMisc.ComponentAction() { - @Override - public void run(Component c) { - ((AWTPrintLifecycle)c).releasePrint(); - } }; - - private Context(Container c, Graphics2D g2d, double scaleMatX, double scaleMatY) { - this.cont = c; - this.g2d = g2d; - this.scaleMatX = scaleMatX; - this.scaleMatY = scaleMatY; - this.count = 0; - } - private void setupPrint(Container c) { - count = AWTMisc.performAction(c, AWTPrintLifecycle.class, setupAction); - } - } -} diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 4e0fdba5d..a519e33bb 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -53,7 +53,6 @@ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; -import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.EventQueue; @@ -94,6 +93,7 @@ import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration; import com.jogamp.nativewindow.awt.AWTGraphicsDevice; import com.jogamp.nativewindow.awt.AWTGraphicsScreen; +import com.jogamp.nativewindow.awt.AWTPrintLifecycle; import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol; import com.jogamp.nativewindow.awt.JAWTWindow; import com.jogamp.opengl.JoglVersion; @@ -725,13 +725,13 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } private volatile boolean printActive = false; - private boolean printUseAA = false; + private int printNumSamples = 0; private GLAnimatorControl printAnimator = null; private GLAutoDrawable printGLAD = null; private AWTTilePainter printAWTTiles = null; @Override - public void setupPrint(Graphics2D g2d, double scaleMatX, double scaleMatY) { + public void setupPrint(double scaleMatX, double scaleMatY, int numSamples) { if( !validateGLDrawable() ) { if(DEBUG) { System.err.println(getThreadName()+": Info: GLCanvas setupPrint - skipped GL render, drawable not valid yet"); @@ -746,14 +746,9 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } printActive = true; sendReshape = false; // clear reshape flag - final RenderingHints rHints = g2d.getRenderingHints(); - { - final Object _useAA = rHints.get(RenderingHints.KEY_ANTIALIASING); - printUseAA = null != _useAA && ( _useAA == RenderingHints.VALUE_ANTIALIAS_DEFAULT || _useAA == RenderingHints.VALUE_ANTIALIAS_ON ); - } + printNumSamples = AWTTilePainter.getNumSamples(numSamples, getChosenGLCapabilities()); if( DEBUG ) { - System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", scaleMat "+scaleMatX+" x "+scaleMatY+", useAA "+printUseAA+", printAnimator "+printAnimator); - AWTTilePainter.dumpHintsAndScale(g2d); + System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", scaleMat "+scaleMatX+" x "+scaleMatY+", numSamples "+numSamples+" -> "+printNumSamples+", printAnimator "+printAnimator); } final int componentCount = isOpaque() ? 3 : 4; final TileRenderer printRenderer = new TileRenderer(); @@ -769,23 +764,15 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing printAnimator.remove(GLCanvas.this); } final GLCapabilities caps = (GLCapabilities)getChosenGLCapabilities().cloneMutable(); - final GLProfile glp = caps.getGLProfile(); if( caps.getSampleBuffers() ) { - // bug / issue w/ swapGLContextAndAllGLEventListener and onscreen MSAA w/ NV/GLX + // Bug 830: swapGLContextAndAllGLEventListener and onscreen MSAA w/ NV/GLX printGLAD = GLCanvas.this; } else { caps.setDoubleBuffered(false); caps.setOnscreen(false); - if( printUseAA && !caps.getSampleBuffers() ) { - if ( !glp.isGL2ES3() ) { - if( DEBUG ) { - System.err.println("Ignore MSAA due to gl-profile < GL2ES3"); - } - printUseAA = false; - } else { - caps.setSampleBuffers(true); - caps.setNumSamples(8); - } + if( printNumSamples != caps.getNumSamples() ) { + caps.setSampleBuffers(0 < printNumSamples); + caps.setNumSamples(printNumSamples); } final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, DEFAULT_PRINT_TILE_SIZE, DEFAULT_PRINT_TILE_SIZE, null); @@ -796,7 +783,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing printAWTTiles.renderer.attachToAutoDrawable(printGLAD); if( DEBUG ) { System.err.println("AWT print.setup "+printAWTTiles); - System.err.println("AWT print.setup AA "+printUseAA+", "+caps); + System.err.println("AWT print.setup AA "+printNumSamples+", "+caps); System.err.println("AWT print.setup "+printGLAD); } } diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java index 02f4e54a7..f0c6b7beb 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java @@ -48,7 +48,6 @@ import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; -import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; @@ -90,6 +89,7 @@ import jogamp.opengl.awt.Java2D; import jogamp.opengl.util.glsl.GLSLTextureRaster; import com.jogamp.common.util.awt.AWTEDTExecutor; +import com.jogamp.nativewindow.awt.AWTPrintLifecycle; import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol; import com.jogamp.opengl.FBObject; import com.jogamp.opengl.util.GLPixelBuffer.GLPixelAttributes; @@ -424,7 +424,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing createAndInitializeBackend(); } - if (!isInitialized) { + if (!isInitialized || printActive) { return; } @@ -498,13 +498,13 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } private volatile boolean printActive = false; - private boolean printUseAA = false; + private int printNumSamples = 0; private GLAnimatorControl printAnimator = null; private GLAutoDrawable printGLAD = null; private AWTTilePainter printAWTTiles = null; @Override - public void setupPrint(Graphics2D g2d, double scaleMatX, double scaleMatY) { + public void setupPrint(double scaleMatX, double scaleMatY, int numSamples) { if (!isInitialized) { if(DEBUG) { System.err.println(getThreadName()+": Info: GLJPanel setupPrint - skipped GL render, drawable not valid yet"); @@ -520,14 +520,9 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing printActive = true; sendReshape = false; // clear reshape flag handleReshape = false; // ditto - final RenderingHints rHints = g2d.getRenderingHints(); - { - final Object _useAA = rHints.get(RenderingHints.KEY_ANTIALIASING); - printUseAA = null != _useAA && ( _useAA == RenderingHints.VALUE_ANTIALIAS_DEFAULT || _useAA == RenderingHints.VALUE_ANTIALIAS_ON ); - } + printNumSamples = AWTTilePainter.getNumSamples(numSamples, getChosenGLCapabilities()); if( DEBUG ) { - System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", scaleMat "+scaleMatX+" x "+scaleMatY+", useAA "+printUseAA+", printAnimator "+printAnimator); - AWTTilePainter.dumpHintsAndScale(g2d); + System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", scaleMat "+scaleMatX+" x "+scaleMatY+", numSamples "+numSamples+" -> "+printNumSamples+", printAnimator "+printAnimator); } final int componentCount = isOpaque() ? 3 : 4; final TileRenderer printRenderer = new TileRenderer(); @@ -546,30 +541,21 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing printGLAD = GLJPanel.this; // default: re-use final GLCapabilities caps = (GLCapabilities)getChosenGLCapabilities().cloneMutable(); - final GLProfile glp = caps.getGLProfile(); - if( printUseAA && !caps.getSampleBuffers() ) { - if ( !glp.isGL2ES3() ) { - if( DEBUG ) { - System.err.println("Ignore MSAA due to gl-profile < GL2ES3"); - } - printUseAA = false; - } else { - // MSAA FBO .. - caps.setDoubleBuffered(false); - caps.setOnscreen(false); - caps.setSampleBuffers(true); - caps.setNumSamples(8); - final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); - printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, DEFAULT_PRINT_TILE_SIZE, DEFAULT_PRINT_TILE_SIZE, null); - GLDrawableUtil.swapGLContextAndAllGLEventListener(GLJPanel.this, printGLAD); - } + if( printNumSamples != caps.getNumSamples() ) { + caps.setDoubleBuffered(false); + caps.setOnscreen(false); + caps.setSampleBuffers(0 < printNumSamples); + caps.setNumSamples(printNumSamples); + final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); + printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, DEFAULT_PRINT_TILE_SIZE, DEFAULT_PRINT_TILE_SIZE, null); + GLDrawableUtil.swapGLContextAndAllGLEventListener(GLJPanel.this, printGLAD); } printAWTTiles.setIsGLOriented(printGLAD.isGLOriented()); printAWTTiles.renderer.setTileSize(printGLAD.getWidth(), printGLAD.getHeight(), 0); printAWTTiles.renderer.attachToAutoDrawable(printGLAD); if( DEBUG ) { System.err.println("AWT print.setup "+printAWTTiles); - System.err.println("AWT print.setup AA "+printUseAA+", "+caps); + System.err.println("AWT print.setup AA "+printNumSamples+", "+caps); System.err.println("AWT print.setup "+printGLAD); } } @@ -624,9 +610,6 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing printAWTTiles.setupGraphics2DAndClipBounds(g2d, getWidth(), getHeight()); try { final TileRenderer tileRenderer = printAWTTiles.renderer; - if( DEBUG ) { - System.err.println("AWT print.0: "+tileRenderer); - } do { if( printGLAD != GLJPanel.this ) { tileRenderer.display(); diff --git a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java index 0ff733457..b16273b35 100644 --- a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java +++ b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java @@ -33,16 +33,25 @@ import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.AffineTransform; +import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; +import java.io.File; +import java.io.IOException; +import java.util.Arrays; import java.util.Iterator; import java.util.Set; import java.util.Map.Entry; +import javax.imageio.ImageIO; +import javax.media.nativewindow.util.DimensionImmutable; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLEventListener; +import jogamp.opengl.Debug; + import com.jogamp.opengl.util.TileRenderer; import com.jogamp.opengl.util.TileRendererBase; import com.jogamp.opengl.util.GLPixelBuffer.GLPixelAttributes; @@ -56,6 +65,8 @@ import com.jogamp.opengl.util.awt.AWTGLPixelBuffer.AWTGLPixelBufferProvider; *

          */ public class AWTTilePainter { + private static final boolean DEBUG_TILES = Debug.debug("TileRenderer"); + public final TileRenderer renderer; public final int componentCount; public final double scaleMatX, scaleMatY; @@ -76,8 +87,28 @@ public class AWTTilePainter { System.err.println("Hint["+count+"]: "+rEntry.getKey()+" -> "+rEntry.getValue()); } final AffineTransform aTrans = g2d.getTransform(); + System.err.println(" type "+aTrans.getType()); System.err.println(" scale "+aTrans.getScaleX()+" x "+aTrans.getScaleY()); System.err.println(" move "+aTrans.getTranslateX()+" x "+aTrans.getTranslateY()); + System.err.println(" mat "+aTrans); + } + + /** + * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param caps used capabilties + * @return resulting number of samples, 0 if disabled + */ + public static int getNumSamples(int numSamples, GLCapabilitiesImmutable caps) { + if( 0 > numSamples ) { + return 0; + } else if( 0 < numSamples ) { + if ( !caps.getGLProfile().isGL2ES3() ) { + return 0; + } + return Math.max(caps.getNumSamples(), numSamples); + } else { + return caps.getNumSamples(); + } } /** @@ -104,7 +135,6 @@ public class AWTTilePainter { this.scaleMatY = scaleMatY; this.verbose = verbose; this.flipVertical = true; - this.renderer.setRowOrder(TileRenderer.TR_TOP_TO_BOTTOM); } public String toString() { return renderer.toString(); } @@ -113,6 +143,25 @@ public class AWTTilePainter { flipVertical = v; } + private static Rectangle getRoundedRect(Rectangle2D r) { + if( null == r ) { return null; } + return new Rectangle((int)Math.round(r.getX()), (int)Math.round(r.getY()), + (int)Math.round(r.getWidth()), (int)Math.round(r.getHeight())); + } + private static Rectangle clipNegative(Rectangle in) { + if( null == in ) { return null; } + final Rectangle out = new Rectangle(in); + if( 0 > out.x ) { + out.width += out.x; + out.x = 0; + } + if( 0 > out.y ) { + out.height += out.y; + out.y = 0; + } + return out; + } + /** * Caches the {@link Graphics2D} instance for rendering. *

          @@ -132,31 +181,49 @@ public class AWTTilePainter { public void setupGraphics2DAndClipBounds(Graphics2D g2d, int width, int height) { this.g2d = g2d; saveAT = g2d.getTransform(); - final Rectangle gClipOrig = g2d.getClipBounds(); - if( null == gClipOrig ) { - g2d.setClip(0, 0, width, height); + final Rectangle gClipOrigR; + final Rectangle2D dClipOrig, dImageSizeOrig; // double precision for scaling + // setup original rectangles + { + gClipOrigR = g2d.getClipBounds(); + final Rectangle gClipOrig = clipNegative(gClipOrigR); + dClipOrig = null != gClipOrig ? new Rectangle2D.Double(gClipOrig.getX(), gClipOrig.getY(), gClipOrig.getWidth(), gClipOrig.getHeight()) : null; + dImageSizeOrig = new Rectangle2D.Double(0, 0, width, height); } - g2d.scale(scaleMatX, scaleMatY); - - final Rectangle gClipScaled = g2d.getClipBounds(); - if( 0 > gClipScaled.x ) { - gClipScaled.width += gClipScaled.x; - gClipScaled.x = 0; + final Rectangle2D dClipScaled, dImageSizeScaled; // double precision for scaling + // retrieve scaled image-size and clip-bounds + { + g2d.setClip(dImageSizeOrig); + g2d.scale(scaleMatX, scaleMatY); + dImageSizeScaled = (Rectangle2D) g2d.getClip(); + if( null == dClipOrig ) { + g2d.setClip(null); + dClipScaled = (Rectangle2D) dImageSizeScaled.clone(); + } else { + g2d.setTransform(saveAT); // reset + g2d.setClip(dClipOrig); + g2d.scale(scaleMatX, scaleMatY); + dClipScaled = (Rectangle2D) g2d.getClip(); + } } - if( 0 > gClipScaled.y ) { - gClipScaled.height += gClipScaled.y; - gClipScaled.y = 0; + final Rectangle iClipScaled = getRoundedRect(dClipScaled); + final Rectangle iImageSizeScaled = getRoundedRect(dImageSizeScaled); + scaledYOffset = iClipScaled.y; + renderer.setImageSize(iImageSizeScaled.width, iImageSizeScaled.height); + renderer.clipImageSize(iClipScaled.width, iClipScaled.height); + final int clipH = Math.min(iImageSizeScaled.height, iClipScaled.height); + if( flipVertical ) { + renderer.setTileOffset(iClipScaled.x, iImageSizeScaled.height - ( iClipScaled.y + clipH )); + } else { + renderer.setTileOffset(iClipScaled.x, iClipScaled.y); } if( verbose ) { - System.err.println("AWT print.0: "+gClipOrig+" -> "+gClipScaled); - } - renderer.setImageSize(gClipScaled.width, gClipScaled.height); - renderer.setTileOffset(gClipScaled.x, gClipScaled.y); - if( null == gClipOrig ) { - // reset - g2d.setClip(null); + System.err.println("AWT print.0: image "+dImageSizeOrig + " -> " + dImageSizeScaled + " -> " + iImageSizeScaled); + System.err.println("AWT print.0: clip "+gClipOrigR + " -> " + dClipOrig + " -> " + dClipScaled + " -> " + iClipScaled); + System.err.println("AWT print.0: "+renderer); } } + private int scaledYOffset; /** See {@ #setupGraphics2DAndClipBounds(Graphics2D)}. */ public void resetGraphics2D() { @@ -208,28 +275,55 @@ public class AWTTilePainter { @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {} }; + static int _counter = 0; final GLEventListener postTileGLEL = new GLEventListener() { - int tTopRowHeight = 0; @Override public void init(GLAutoDrawable drawable) { - tTopRowHeight = 0; } @Override public void dispose(GLAutoDrawable drawable) {} @Override public void display(GLAutoDrawable drawable) { + final DimensionImmutable cis = renderer.getClippedImageSize(); + final int tWidth = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_WIDTH); + final int tHeight = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_HEIGHT); + final int pX = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_X_POS); + final int pY = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_Y_POS); + final int pYOff = renderer.getParam(TileRenderer.TR_TILE_Y_OFFSET); + final int pYf; + if( flipVertical ) { + pYf = cis.getHeight() - ( pY - pYOff + tHeight ) + scaledYOffset; + } else { + pYf = pY; + } + // Copy temporary data into raster of BufferedImage for faster // blitting Note that we could avoid this copy in the cases // where !offscreenDrawable.isGLOriented(), // but that's the software rendering path which is very slow anyway. - final int tWidth = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_WIDTH); - final int tHeight = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_HEIGHT); final BufferedImage dstImage; + if( DEBUG_TILES ) { + final String fname = String.format("file_%03d_0_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png", + _counter, + renderer.getParam(TileRenderer.TR_CURRENT_COLUMN), renderer.getParam(TileRenderer.TR_CURRENT_ROW), + tWidth, tHeight, + pX, pY, pYOff, pX, pYf).replace(' ', '_'); + System.err.println("XXX file "+fname); + final File fout = new File(fname); + try { + ImageIO.write(tBuffer.image, "png", fout); + } catch (IOException e) { + e.printStackTrace(); + } + } if( flipVertical ) { final BufferedImage srcImage = tBuffer.image; dstImage = vFlipImage; final int[] src = ((DataBufferInt) srcImage.getRaster().getDataBuffer()).getData(); final int[] dst = ((DataBufferInt) dstImage.getRaster().getDataBuffer()).getData(); + if( DEBUG_TILES ) { + Arrays.fill(dst, 0x55); + } final int incr = tBuffer.width; int srcPos = 0; int destPos = (tHeight - 1) * tBuffer.width; @@ -239,28 +333,31 @@ public class AWTTilePainter { } else { dstImage = tBuffer.image; } - // Draw resulting image in one shot - final int tRows = renderer.getParam(TileRenderer.TR_ROWS); - final int tRow = renderer.getParam(TileRenderer.TR_CURRENT_ROW); - final int pX = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_X_POS); - final int pYf; - if( flipVertical ) { - if( tRow == tRows - 1 ) { - tTopRowHeight = tHeight; - pYf = 0; - } else if( tRow == tRows - 2 ){ - pYf = tTopRowHeight; - } else { - pYf = ( tRows - 2 - tRow ) * tHeight + tTopRowHeight; + if( DEBUG_TILES ) { + final String fname = String.format("file_%03d_1_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png", + _counter, + renderer.getParam(TileRenderer.TR_CURRENT_COLUMN), renderer.getParam(TileRenderer.TR_CURRENT_ROW), + tWidth, tHeight, + pX, pY, pYOff, pX, pYf).replace(' ', '_'); + System.err.println("XXX file "+fname); + final File fout = new File(fname); + try { + ImageIO.write(dstImage, "png", fout); + } catch (IOException e) { + e.printStackTrace(); } - } else { - pYf = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_Y_POS); - } + _counter++; + } + // Draw resulting image in one shot final Shape oClip = g2d.getClip(); - g2d.clipRect(pX, pYf, tWidth, tHeight); - g2d.drawImage(dstImage, pX, pYf, dstImage.getWidth(), dstImage.getHeight(), null); // Null ImageObserver since image data is ready. + // g2d.clipRect(pX, pYf, tWidth, tHeight); + final BufferedImage outImage = dstImage.getSubimage(0, 0, tWidth, tHeight); // instead of clipping + final boolean drawDone = g2d.drawImage(outImage, pX, pYf, null); // Null ImageObserver since image data is ready. + // final boolean drawDone = g2d.drawImage(dstImage, pX, pYf, dstImage.getWidth(), dstImage.getHeight(), null); // Null ImageObserver since image data is ready. if( verbose ) { - System.err.println("XXX tile-post.X clip "+oClip+" -> "+g2d.getClip()); + System.err.println("XXX tile-post.X clippedImageSize "+cis); + System.err.println("XXX tile-post.X pYf "+cis.getHeight()+" - ( "+pY+" - "+pYOff+" + "+tHeight+" ) "+scaledYOffset+" = "+ pYf); + System.err.println("XXX tile-post.X clip "+oClip+" + "+pX+" / [pY "+pY+", pYOff "+pYOff+", pYf "+pYf+"] "+tWidth+"x"+tHeight+" -> "+g2d.getClip()); g2d.setColor(Color.BLACK); g2d.drawRect(pX, pYf, tWidth, tHeight); if( null != oClip ) { @@ -269,9 +366,11 @@ public class AWTTilePainter { g2d.drawRect(r.x, r.y, r.width, r.height); } System.err.println("XXX tile-post.X "+renderer); - System.err.println("XXX tile-post.X dst-img "+dstImage.getWidth()+"x"+dstImage.getHeight()+", y-flip "+flipVertical+" -> "+pX+"/"+pYf); + System.err.println("XXX tile-post.X dst-img "+dstImage.getWidth()+"x"+dstImage.getHeight()); + System.err.println("XXX tile-post.X out-img "+outImage.getWidth()+"x"+dstImage.getHeight()); + System.err.println("XXX tile-post.X y-flip "+flipVertical+" -> "+pX+"/"+pYf+", drawDone "+drawDone); } - g2d.setClip(oClip); + // g2d.setClip(oClip); } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {} diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java new file mode 100644 index 000000000..a54f6bac6 --- /dev/null +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java @@ -0,0 +1,168 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.nativewindow.awt; + +import java.awt.Component; +import java.awt.Container; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.print.PrinterJob; + +import jogamp.nativewindow.awt.AWTMisc; + +/** + * Interface describing print lifecycle to support AWT printing, + * e.g. on AWT {@link javax.media.opengl.GLAutoDrawable GLAutoDrawable}s. + *

          Implementations
          + *

          + * Implementing {@link javax.media.opengl.GLAutoDrawable GLAutoDrawable} classes based on AWT + * supporting {@link Component#print(Graphics)} shall implement this interface. + *

          + *
          Usage
          + *

          + * Users attempting to print an AWT {@link Container} containing {@link AWTPrintLifecycle} elements + * shall consider decorating the {@link Container#printAll(Graphics)} call with
          + * {@link #setupPrint(double, double, int) setupPrint(..)} and {@link #releasePrint()} + * on all {@link AWTPrintLifecycle} elements in the {@link Container}.
          + * To minimize this burden, a user can use {@link Context#setupPrint(Container, double, double, int) Context.setupPrint(..)}: + *

          + *  Graphics2D g2d;
          + *  Container cont;
          + *  double scaleGLMatXY = 72.0/glDPI;
          + *  int numSamples = 0; // leave multisampling as-is
          + *  PrinterJob job;
          + *  ...
          +    final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(cont, scaleGLMatXY, scaleGLMatXY, numSamples);
          +    try {
          +       AWTEDTExecutor.singleton.invoke(true, new Runnable() {
          +            public void run() {
          +                try {
          +                    job.print();
          +                } catch (PrinterException ex) {
          +                    ex.printStackTrace();
          +                }
          +           } });
          +    } finally {
          +       ctx.releasePrint();
          +    }
          + * 
          + * 
          + *

          + */ +public interface AWTPrintLifecycle { + + public static final int DEFAULT_PRINT_TILE_SIZE = 512; + + + /** + * Shall be called before {@link PrinterJob#print()}. + *

          + * See Usage. + *

          + * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels + * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels + * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + */ + void setupPrint(double scaleMatX, double scaleMatY, int numSamples); + + /** + * Shall be called after {@link PrinterJob#print()}. + *

          + * See Usage. + *

          + */ + void releasePrint(); + + /** + * Convenient {@link AWTPrintLifecycle} context simplifying calling {@link AWTPrintLifecycle#setupPrint(double, double, int) setupPrint(..)} + * and {@link AWTPrintLifecycle#releasePrint()} on all {@link AWTPrintLifecycle} elements of a {@link Container}. + *

          + * See Usage. + *

          + */ + public static class Context { + /** + *

          + * See Usage. + *

          + * + * @param c container to be traversed through to perform {@link AWTPrintLifecycle#setupPrint(double, double, int) setupPrint(..)} on all {@link AWTPrintLifecycle} elements. + * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels + * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels + * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @return the context + */ + public static Context setupPrint(Container c, double scaleMatX, double scaleMatY, int numSamples) { + final Context t = new Context(c, scaleMatX, scaleMatY, numSamples); + t.setupPrint(c); + return t; + } + + /** + *

          + * See Usage. + *

          + */ + public void releasePrint() { + count = AWTMisc.performAction(cont, AWTPrintLifecycle.class, releaseAction); + } + + /** + * @return count of performed actions of last {@link #setupPrint(Container, double, double, int) setupPrint(..)} or {@link #releasePrint()}. + */ + public int getCount() { return count; } + + private final Container cont; + private final double scaleMatX; + private final double scaleMatY; + private final int numSamples; + private int count; + + private final AWTMisc.ComponentAction setupAction = new AWTMisc.ComponentAction() { + @Override + public void run(Component c) { + ((AWTPrintLifecycle)c).setupPrint(scaleMatX, scaleMatY, numSamples); + } }; + private final AWTMisc.ComponentAction releaseAction = new AWTMisc.ComponentAction() { + @Override + public void run(Component c) { + ((AWTPrintLifecycle)c).releasePrint(); + } }; + + private Context(Container c, double scaleMatX, double scaleMatY, int numSamples) { + this.cont = c; + this.scaleMatX = scaleMatX; + this.scaleMatY = scaleMatY; + this.numSamples = numSamples; + this.count = 0; + } + private void setupPrint(Container c) { + count = AWTMisc.performAction(c, AWTPrintLifecycle.class, setupAction); + } + } +} diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index cdf47cbb3..a2d4eb7f0 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -37,7 +37,6 @@ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.KeyboardFocusManager; -import java.awt.RenderingHints; import java.beans.Beans; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; @@ -53,8 +52,6 @@ import javax.media.opengl.GLAnimatorControl; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLDrawableFactory; -import javax.media.opengl.GLProfile; -import javax.media.opengl.awt.AWTPrintLifecycle; import javax.swing.MenuSelectionManager; import jogamp.nativewindow.awt.AWTMisc; @@ -67,6 +64,7 @@ import jogamp.opengl.awt.AWTTilePainter; import com.jogamp.common.os.Platform; import com.jogamp.common.util.awt.AWTEDTExecutor; +import com.jogamp.nativewindow.awt.AWTPrintLifecycle; import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol; import com.jogamp.nativewindow.awt.JAWTWindow; import com.jogamp.newt.Display; @@ -455,13 +453,20 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } private volatile boolean printActive = false; - private boolean printUseAA = false; + private int printNumSamples = 0; private GLAnimatorControl printAnimator = null; private GLAutoDrawable printGLAD = null; private AWTTilePainter printAWTTiles = null; + private final GLAutoDrawable getGLAD() { + if( null != newtChild && newtChild instanceof GLAutoDrawable ) { + return (GLAutoDrawable)newtChild; + } + return null; + } + @Override - public void setupPrint(Graphics2D g2d, double scaleMatX, double scaleMatY) { + public void setupPrint(double scaleMatX, double scaleMatY, int numSamples) { if( !validateComponent(true) ) { if(DEBUG) { System.err.println(getThreadName()+": Info: NewtCanvasAWT setupPrint - skipped GL render, drawable not valid yet"); @@ -474,15 +479,17 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } return; // not yet available .. } - printActive = true; - final RenderingHints rHints = g2d.getRenderingHints(); - { - final Object _useAA = rHints.get(RenderingHints.KEY_ANTIALIASING); - printUseAA = null != _useAA && ( _useAA == RenderingHints.VALUE_ANTIALIAS_DEFAULT || _useAA == RenderingHints.VALUE_ANTIALIAS_ON ); + final GLAutoDrawable glad = getGLAD(); + if( null == glad ) { + if( DEBUG ) { + System.err.println("AWT print.setup exit, newtChild not a GLAutoDrawable: "+newtChild); + } + return; } + printActive = true; + printNumSamples = AWTTilePainter.getNumSamples(numSamples, glad.getChosenGLCapabilities()); if( DEBUG ) { - System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", scaleMat "+scaleMatX+" x "+scaleMatY+", useAA "+printUseAA+", printAnimator "+printAnimator); - AWTTilePainter.dumpHintsAndScale(g2d); + System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", scaleMat "+scaleMatX+" x "+scaleMatY+", numSamples "+numSamples+" -> "+printNumSamples+", printAnimator "+printAnimator); } final int componentCount = isOpaque() ? 3 : 4; final TileRenderer printRenderer = new TileRenderer(); @@ -492,39 +499,21 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto private final Runnable setupPrintOnEDT = new Runnable() { @Override public void run() { - final GLAutoDrawable glad; - if( null != newtChild && newtChild instanceof GLAutoDrawable ) { - glad = (GLAutoDrawable)newtChild; - } else { - if( DEBUG ) { - System.err.println("AWT print.setup exit, newtChild not a GLAutoDrawable: "+newtChild); - } - printAWTTiles = null; - printActive = false; - return; - } + final GLAutoDrawable glad = getGLAD(); printAnimator = glad.getAnimator(); if( null != printAnimator ) { printAnimator.remove(glad); } final GLCapabilities caps = (GLCapabilities)glad.getChosenGLCapabilities().cloneMutable(); - final GLProfile glp = caps.getGLProfile(); if( caps.getSampleBuffers() ) { - // bug / issue w/ swapGLContextAndAllGLEventListener and onscreen MSAA w/ NV/GLX + // Bug 830: swapGLContextAndAllGLEventListener and onscreen MSAA w/ NV/GLX printGLAD = glad; } else { caps.setDoubleBuffered(false); caps.setOnscreen(false); - if( printUseAA && !caps.getSampleBuffers() ) { - if ( !glp.isGL2ES3() ) { - if( DEBUG ) { - System.err.println("Ignore MSAA due to gl-profile < GL2ES3"); - } - printUseAA = false; - } else { - caps.setSampleBuffers(true); - caps.setNumSamples(8); - } + if( printNumSamples != caps.getNumSamples() ) { + caps.setSampleBuffers(0 < printNumSamples); + caps.setNumSamples(printNumSamples); } final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, DEFAULT_PRINT_TILE_SIZE, DEFAULT_PRINT_TILE_SIZE, null); @@ -535,7 +524,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto printAWTTiles.renderer.attachToAutoDrawable(printGLAD); if( DEBUG ) { System.err.println("AWT print.setup "+printAWTTiles); - System.err.println("AWT print.setup AA "+printUseAA+", "+caps); + System.err.println("AWT print.setup AA "+printNumSamples+", "+caps); System.err.println("AWT print.setup "+printGLAD); } } @@ -557,7 +546,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto if( DEBUG ) { System.err.println("AWT print.release "+printAWTTiles); } - final GLAutoDrawable glad = (GLAutoDrawable)newtChild; + final GLAutoDrawable glad = getGLAD(); printAWTTiles.dispose(); printAWTTiles= null; if( printGLAD != glad ) { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java index 322d2d1b5..908a89a32 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java @@ -115,15 +115,15 @@ public class TestTiledPrintingGearsAWT extends TiledPrintingAWTBase { final ActionListener print72DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 72, false); + doPrintManual(frame, 72, 0); } }; final ActionListener print300DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 300, false); + doPrintManual(frame, 300, -1); } }; final ActionListener print600DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 600, false); + doPrintManual(frame, 600, -1); } }; final Button print72DPIButton = new Button("72dpi"); print72DPIButton.addActionListener(print72DPIAction); @@ -176,15 +176,15 @@ public class TestTiledPrintingGearsAWT extends TiledPrintingAWTBase { Thread.sleep(200); if( !printDone ) { printDone = true; - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, false); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, 0); waitUntilPrintJobsIdle(); - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, true); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, 8); waitUntilPrintJobsIdle(); // No AA needed for 300 dpi and greater :) - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 300, false); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 300, -1); waitUntilPrintJobsIdle(); if( allow600dpi ) { - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 600, false); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 600, -1); waitUntilPrintJobsIdle(); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java index f7f856676..c695febbe 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java @@ -120,15 +120,15 @@ public class TestTiledPrintingGearsNewtAWT extends TiledPrintingAWTBase { final ActionListener print72DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 72, false); + doPrintManual(frame, 72, 0); } }; final ActionListener print300DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 300, false); + doPrintManual(frame, 300, -1); } }; final ActionListener print600DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 600, false); + doPrintManual(frame, 600, -1); } }; final Button print72DPIButton = new Button("72dpi"); print72DPIButton.addActionListener(print72DPIAction); @@ -181,15 +181,15 @@ public class TestTiledPrintingGearsNewtAWT extends TiledPrintingAWTBase { Thread.sleep(200); if( !printDone ) { printDone = true; - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, false); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, 0); waitUntilPrintJobsIdle(); - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, true); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, 8); waitUntilPrintJobsIdle(); // No AA needed for 300 dpi and greater :) - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 300, false); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 300, -1); waitUntilPrintJobsIdle(); if( allow600dpi ) { - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 600, false); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 600, -1); waitUntilPrintJobsIdle(); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java index da577ea1d..9c5d6bf8b 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java @@ -45,7 +45,11 @@ import java.lang.reflect.InvocationTargetException; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLJPanel; +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JComponent; import javax.swing.JFrame; +import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; @@ -93,40 +97,67 @@ public class TestTiledPrintingGearsSwingAWT extends TiledPrintingAWTBase { public static void releaseClass() { } - protected void runTestGL(GLCapabilities caps) throws InterruptedException, InvocationTargetException { - final Dimension glc_sz = new Dimension(width/2, height); + protected void runTestGL(GLCapabilities caps, boolean layered) throws InterruptedException, InvocationTargetException { + final int layerStepX = width/6, layerStepY = height/6; + final Dimension glc_sz = new Dimension(layered ? width - 2*layerStepX : width/2, layered ? height - 2*layerStepY : height); final GLJPanel glJPanel1 = new GLJPanel(caps); Assert.assertNotNull(glJPanel1); glJPanel1.setMinimumSize(glc_sz); glJPanel1.setPreferredSize(glc_sz); - glJPanel1.setSize(glc_sz); + if( layered ) { + glJPanel1.setBounds(layerStepX/2, layerStepY/2, glc_sz.width, glc_sz.height); + } else { + glJPanel1.setBounds(0, 0, glc_sz.width, glc_sz.height); + } glJPanel1.addGLEventListener(new Gears()); final GLJPanel glJPanel2 = new GLJPanel(caps); Assert.assertNotNull(glJPanel2); glJPanel2.setMinimumSize(glc_sz); glJPanel2.setPreferredSize(glc_sz); - glJPanel2.setSize(glc_sz); + if( layered ) { + glJPanel2.setBounds(3*layerStepY, 2*layerStepY, glc_sz.width, glc_sz.height); + } else { + glJPanel2.setBounds(0, 0, glc_sz.width, glc_sz.height); + } glJPanel2.addGLEventListener(new RedSquareES2()); + // glJPanel2.addGLEventListener(new Gears()); - final JPanel demoPanel = new JPanel(); - demoPanel.add(glJPanel1); - demoPanel.add(glJPanel2); + final JComponent demoPanel; + if( layered ) { + glJPanel1.setOpaque(true); + glJPanel2.setOpaque(false); + final Dimension lsz = new Dimension(width, height); + demoPanel = new JLayeredPane(); + demoPanel.setMinimumSize(lsz); + demoPanel.setPreferredSize(lsz); + demoPanel.setBounds(0, 0, lsz.width, lsz.height); + demoPanel.setBorder(BorderFactory.createTitledBorder("Layered Pane")); + demoPanel.add(glJPanel1, JLayeredPane.DEFAULT_LAYER); + demoPanel.add(glJPanel2, Integer.valueOf(1)); + final JButton tb = new JButton("On Top"); + tb.setBounds(4*layerStepY, 3*layerStepY, 100, 50); + demoPanel.add(tb, Integer.valueOf(2)); + } else { + demoPanel = new JPanel(); + demoPanel.add(glJPanel1); + demoPanel.add(glJPanel2); + } final JFrame frame = new JFrame("Swing Print"); Assert.assertNotNull(frame); final ActionListener print72DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 72, false); + doPrintManual(frame, 72, 0); } }; final ActionListener print300DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 300, false); + doPrintManual(frame, 300, -1); } }; final ActionListener print600DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 600, false); + doPrintManual(frame, 600, -1); } }; final Button print72DPIButton = new Button("72dpi"); print72DPIButton.addActionListener(print72DPIAction); @@ -182,20 +213,19 @@ public class TestTiledPrintingGearsSwingAWT extends TiledPrintingAWTBase { Thread.sleep(200); if( !printDone ) { printDone = true; - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, false); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, 0); waitUntilPrintJobsIdle(); - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, true); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 72, 8); waitUntilPrintJobsIdle(); // No AA needed for 300 dpi and greater :) - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 300, false); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 300, -1); waitUntilPrintJobsIdle(); if( allow600dpi ) { - doPrintAuto(frame, PageFormat.LANDSCAPE, null, 600, false); + doPrintAuto(frame, PageFormat.LANDSCAPE, null, 600, -1); waitUntilPrintJobsIdle(); } } } - // try { Thread.sleep(4000); } catch (InterruptedException e) { } // time to finish print jobs .. FIXME ?? Assert.assertNotNull(frame); Assert.assertNotNull(glJPanel1); @@ -220,15 +250,22 @@ public class TestTiledPrintingGearsSwingAWT extends TiledPrintingAWTBase { @Test public void test01_Onscreen_aa0() throws InterruptedException, InvocationTargetException { GLCapabilities caps = new GLCapabilities(glp); - runTestGL(caps); + runTestGL(caps, false); + } + + @Test + public void test01_Onscreen_aa0_layered() throws InterruptedException, InvocationTargetException { + GLCapabilities caps = new GLCapabilities(glp); + caps.setAlphaBits(8); + runTestGL(caps, true); } @Test public void test02_Onscreen_aa8() throws InterruptedException, InvocationTargetException { GLCapabilities caps = new GLCapabilities(glp); caps.setSampleBuffers(true); - caps.setNumSamples(8); // FIXME - runTestGL(caps); + caps.setNumSamples(8); + runTestGL(caps, false); } static long duration = 500; // ms diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java index ec216a95e..c23d51c51 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java @@ -28,11 +28,10 @@ package com.jogamp.opengl.test.junit.jogl.tile; -import java.awt.Frame; +import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; -import java.awt.RenderingHints; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.Printable; @@ -41,7 +40,6 @@ import java.awt.print.PrinterJob; import java.io.FileNotFoundException; import java.io.FileOutputStream; -import javax.media.opengl.awt.AWTPrintLifecycle; import javax.print.StreamPrintService; import javax.print.StreamPrintServiceFactory; import javax.print.attribute.HashPrintRequestAttributeSet; @@ -53,6 +51,7 @@ import org.junit.Assert; import com.jogamp.common.util.awt.AWTEDTExecutor; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; +import com.jogamp.nativewindow.awt.AWTPrintLifecycle; import com.jogamp.opengl.test.junit.util.UITestCase; /** @@ -97,11 +96,7 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab public static final double A0_HEIGHT_INCH = A0_WIDTH_MM / MM_PER_INCH; */ /** Helper to pass desired Frame to print! **/ - private Frame frame; - /** Helper to pass desired DPI value ! **/ - private int glDPI = 72; - /** Helper to pass desired AA hint ! **/ - private boolean printAA = false; + private Container printContainer; private RecursiveLock lockPrinting = LockFactory.createRecursiveLock(); @@ -155,9 +150,9 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab /** * See: 'Scaling of Frame and GL content' in Class description! */ - final Insets frameInsets = frame.getInsets(); - final int frameWidth = frame.getWidth(); - final int frameHeight= frame.getHeight(); + final Insets frameInsets = printContainer.getInsets(); + final int frameWidth = printContainer.getWidth(); + final int frameHeight= printContainer.getHeight(); final double scaleComp72; { final int frameBorderW = frameInsets.left + frameInsets.right; @@ -166,32 +161,21 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab final double sy = pf.getImageableHeight() / ( frameHeight + frameBorderH ); scaleComp72 = Math.min(sx, sy); } - final double scaleGLMatXY = 72.0 / glDPI; System.err.println("PRINT thread "+Thread.currentThread().getName()); - System.err.println("PRINT DPI: "+glDPI+", AA "+printAA+", scaleGL "+scaleGLMatXY+", scaleComp72 "+scaleComp72+ + System.err.println("PRINT DPI: scaleComp72 "+scaleComp72+ ", frame: border "+frameInsets+", size "+frameWidth+"x"+frameHeight); - final Graphics2D printG2D = (Graphics2D)g; - final Graphics2D g2d = printG2D; - + final Graphics2D g2d = (Graphics2D)g; + System.err.println("PRINT at.pre: "+g2d.getTransform()); g2d.translate(pf.getImageableX(), pf.getImageableY()); g2d.scale(scaleComp72, scaleComp72); - - if( printAA ) { - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - } - final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(frame, g2d, scaleGLMatXY, scaleGLMatXY); - try { - System.err.println("PRINT AWTPrintLifecycle.setup.count "+ctx.getCount()); - AWTEDTExecutor.singleton.invoke(true, new Runnable() { - public void run() { - frame.printAll(g2d); - } - }); - } finally { - ctx.releasePrint(); - System.err.println("PRINT AWTPrintLifecycle.release.count "+ctx.getCount()); - } + System.err.println("PRINT at.post: "+g2d.getTransform()); + + AWTEDTExecutor.singleton.invoke(true, new Runnable() { + public void run() { + printContainer.printAll(g2d); + } + }); /* tell the caller that this page is part of the printed document */ return PAGE_EXISTS; @@ -207,7 +191,15 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab super(); } - public void doPrintAuto(Frame frame, int pOrientation, Paper paper, int dpi, boolean antialiasing) { + /** + * + * @param cont + * @param pOrientation + * @param paper + * @param dpi + * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + */ + public void doPrintAuto(Container cont, int pOrientation, Paper paper, int dpi, int numSamples) { lock.lock(); try { final PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); @@ -224,12 +216,12 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab StreamPrintServiceFactory[] factories = PrinterJob.lookupStreamPrintServices(pdfMimeType); if (factories.length > 0) { - final String fname = getPrintFilename(dpi, antialiasing, "pdf"); + final String fname = getPrintFilename(dpi, numSamples, "pdf"); System.err.println("doPrint: dpi "+dpi+", "+fname); FileOutputStream outstream; try { outstream = new FileOutputStream(fname); - Assert.assertTrue(doPrintAutoImpl(frame, pj, factories[0].getPrintService(outstream), pOrientation, paper, dpi, antialiasing)); + Assert.assertTrue(doPrintAutoImpl(cont, pj, factories[0].getPrintService(outstream), pOrientation, paper, dpi, numSamples)); } catch (FileNotFoundException e) { Assert.assertNull("Unexpected exception", e); } @@ -239,12 +231,12 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab factories = PrinterJob.lookupStreamPrintServices(psMimeType); if (factories.length > 0) { - final String fname = getPrintFilename(dpi, antialiasing, "ps"); + final String fname = getPrintFilename(dpi, numSamples, "ps"); System.err.println("doPrint: dpi "+dpi+", "+fname); FileOutputStream outstream; try { outstream = new FileOutputStream(fname); - Assert.assertTrue(doPrintAutoImpl(frame, pj, factories[0].getPrintService(outstream), pOrientation, paper, dpi, antialiasing)); + Assert.assertTrue(doPrintAutoImpl(cont, pj, factories[0].getPrintService(outstream), pOrientation, paper, dpi, numSamples)); } catch (FileNotFoundException e) { Assert.assertNull("Unexpected exception", e); } @@ -255,18 +247,14 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab lock.unlock(); } } - private String getPrintFilename(int dpi, boolean antialiasing, String suffix) { + private String getPrintFilename(int dpi, int numSamples, String suffix) { final int maxSimpleTestNameLen = getMaxTestNameLen()+getClass().getSimpleName().length()+1; final String simpleTestName = getSimpleTestName("."); - final String sAA = antialiasing ? "aa_" : "raw"; - return String.format("%-"+maxSimpleTestNameLen+"s-n%04d-dpi%03d-%s.%s", simpleTestName, printCount, dpi, sAA, suffix).replace(' ', '_'); + return String.format("%-"+maxSimpleTestNameLen+"s-n%04d-dpi%03d-aa%d.%s", simpleTestName, printCount, dpi, numSamples, suffix).replace(' ', '_'); } - private boolean doPrintAutoImpl(Frame frame, PrinterJob job, + private boolean doPrintAutoImpl(Container cont, PrinterJob job, StreamPrintService ps, int pOrientation, Paper paper, int dpi, - boolean antialiasing) { - this.frame = frame; - glDPI = dpi; - printAA = antialiasing; + int numSamples) { boolean ok = true; try { PageFormat pageFormat = job.defaultPage(); @@ -280,7 +268,7 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab pageFormat.setOrientation(pOrientation); // PageFormat.LANDSCAPE or PageFormat.PORTRAIT job.setPrintService(ps); job.setPrintable(this, pageFormat); - job.print(); + doPrintImpl(cont, job, dpi, numSamples); } catch (PrinterException pe) { pe.printStackTrace(); ok = false; @@ -288,25 +276,52 @@ public abstract class TiledPrintingAWTBase extends UITestCase implements Printab return ok; } - public void doPrintManual(Frame frame, int dpi, boolean antialiasing) { + /** + * + * @param cont + * @param dpi + * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + */ + public void doPrintManual(Container cont, int dpi, int numSamples) { lock.lock(); try { - this.frame = frame; - glDPI = dpi; - printAA = antialiasing; PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(this); boolean ok = job.printDialog(); if (ok) { + doPrintImpl(cont, job, dpi, numSamples); + } + } finally { + lock.unlock(); + } + } + + /** + * + * @param cont + * @param job + * @param dpi + * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + */ + private void doPrintImpl(final Container cont, final PrinterJob job, final int dpi, final int numSamples) { + printContainer = cont; + final double scaleGLMatXY = 72.0 / dpi; + System.err.println("PRINT DPI: "+dpi+", AA "+numSamples+", scaleGL "+scaleGLMatXY); + final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(printContainer, scaleGLMatXY, scaleGLMatXY, numSamples); + System.err.println("PRINT AWTPrintLifecycle.setup.count "+ctx.getCount()); + try { + AWTEDTExecutor.singleton.invoke(true, new Runnable() { + public void run() { try { job.print(); } catch (PrinterException ex) { ex.printStackTrace(); } - } - } finally { - lock.unlock(); - } + } }); + } finally { + ctx.releasePrint(); + System.err.println("PRINT AWTPrintLifecycle.release.count "+ctx.getCount()); + } } /** Wait for idle .. simply acquiring all locks and releasing them. */ -- cgit v1.2.3 From efa8a7927eb8c69e45787d15306e172e440c6150 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 15 Sep 2013 23:46:35 +0200 Subject: Updating doc AWTPrinting.txt --- doc/Implementation/AWTPrinting.txt | 20 ++++++++++++++------ .../jogamp/nativewindow/awt/AWTPrintLifecycle.java | 1 - 2 files changed, 14 insertions(+), 7 deletions(-) (limited to 'src/nativewindow') diff --git a/doc/Implementation/AWTPrinting.txt b/doc/Implementation/AWTPrinting.txt index 97353266e..f2fcbbdd9 100644 --- a/doc/Implementation/AWTPrinting.txt +++ b/doc/Implementation/AWTPrinting.txt @@ -11,7 +11,7 @@ Unit test producing the results: Print code: AWTPrintLifecycle: - + GLCanvas: ... @@ -41,20 +41,28 @@ Impl. in GLCanvas, etc. After printing, AWTPrintLifecycle.releasePrint() shall be called. Impl. in GLCanvas .. etc. -To perform AWTPrintLifecycle on all component in one container, +To perform AWTPrintLifecycle on all components in one container decorating PrinterJob.job(), one may use: - final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(frame, g2d, scaleGLMatXY, scaleGLMatXY); + Container cont; + double scaleGLMatXY = 72.0/glDPI; + int numSamples = 0; // leave multisampling as-is + PrinterJob job; + ... + final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(cont, scaleGLMatXY, scaleGLMatXY, numSamples); try { AWTEDTExecutor.singleton.invoke(true, new Runnable() { public void run() { - frame.printAll(g2d); + try { + job.print(); + } catch (PrinterException ex) { + ex.printStackTrace(); + } } }); } finally { ctx.releasePrint(); } - +++ Tiled rendering is used, i.e. at print(Graphics g), @@ -75,7 +83,7 @@ TileRendererBase.TileRendererNotify interface! Bugs: - None in results - - GLCanvas: Workaround bug where onscreen MSAA cannot switch to offscreen FBO, + - GLCanvas: Workaround Bug 830 where onscreen MSAA cannot switch to offscreen FBO, i.e. stay 'onscreen' +++ diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java index a54f6bac6..65e5ab3f0 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java @@ -51,7 +51,6 @@ import jogamp.nativewindow.awt.AWTMisc; * on all {@link AWTPrintLifecycle} elements in the {@link Container}.
          * To minimize this burden, a user can use {@link Context#setupPrint(Container, double, double, int) Context.setupPrint(..)}: *
          - *  Graphics2D g2d;
            *  Container cont;
            *  double scaleGLMatXY = 72.0/glDPI;
            *  int numSamples = 0; // leave multisampling as-is
          -- 
          cgit v1.2.3
          
          
          From 06b47d1f738c94ca28c0959a12b05d880bc8a78b Mon Sep 17 00:00:00 2001
          From: Sven Gothel 
          Date: Mon, 16 Sep 2013 02:59:30 +0200
          Subject: Add 'DirectDataBufferInt' supporting NIO based BufferedImages
          
          - Contains convenient method to create an NIO backed BufferedImage
            'BufferedImage createBufferedImage(int width, int height, int numComponents, Point location)'
          
          Standalone test TestTiledPrintingNIOImageSwingAWT 'prints', i.e. renders offscreen,
          the Frame into
            - a traditional array-backed BufferedImage
            - an NIO-backed backed BufferedImage
          ---
           make/scripts/tests.sh                              |   3 +-
           .../nativewindow/awt/DirectDataBufferInt.java      | 238 +++++++++++++++++
           .../tile/TestTiledPrintingNIOImageSwingAWT.java    | 296 +++++++++++++++++++++
           .../test/junit/jogl/tile/TiledPrintingAWTBase.java |   4 +-
           4 files changed, 538 insertions(+), 3 deletions(-)
           create mode 100644 src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java
           create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java
          
          (limited to 'src/nativewindow')
          
          diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh
          index db267816e..9e2a06dac 100644
          --- a/make/scripts/tests.sh
          +++ b/make/scripts/tests.sh
          @@ -330,8 +330,9 @@ function testawtswt() {
           #testnoawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering2GL2NEWT $*
           #testawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering3GL2AWT $*
           #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsAWT $*
          -testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $*
          +#testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $*
           #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsNewtAWT $*
          +testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingNIOImageSwingAWT $*
           
           #
           # core/newt (testnoawt and testawt)
          diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java
          new file mode 100644
          index 000000000..d9c3c3791
          --- /dev/null
          +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java
          @@ -0,0 +1,238 @@
          +/**
          + * Copyright 2013 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:
          + * 
          + *    1. Redistributions of source code must retain the above copyright notice, this list of
          + *       conditions and the following disclaimer.
          + * 
          + *    2. 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.
          + * 
          + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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.
          + * 
          + * The views and conclusions contained in the software and documentation are those of the
          + * authors and should not be interpreted as representing official policies, either expressed
          + * or implied, of JogAmp Community.
          + */
          +package com.jogamp.nativewindow.awt;
          +
          +import java.awt.Point;
          +import java.awt.image.BufferedImage;
          +import java.awt.image.ColorModel;
          +import java.awt.image.DataBuffer;
          +import java.awt.image.DirectColorModel;
          +import java.awt.image.SampleModel;
          +import java.awt.image.SinglePixelPackedSampleModel;
          +import java.awt.image.WritableRaster;
          +import java.nio.IntBuffer;
          +
          +import com.jogamp.common.nio.Buffers;
          +
          +/**
          + * {@link DataBuffer} specialization using NIO direct buffer of type {@link DataBuffer#TYPE_INT} as storage.
          + */
          +public final class DirectDataBufferInt extends DataBuffer {
          +    
          +    public static class DirectWritableRaster extends WritableRaster {
          +        protected DirectWritableRaster(SampleModel sampleModel, DirectDataBufferInt dataBuffer, Point origin) {
          +            super(sampleModel, dataBuffer, origin);
          +        }
          +    }
          +    
          +    /**
          +     * Creates a {@link BufferedImage} using an RGB[A] {@link DirectColorModel} 
          +     * with an {@link DirectWritableRaster} utilizing a {@link DirectDataBufferInt} as storage.
          +     *  
          +     * @param width
          +     * @param height
          +     * @param numComponents 3 or 4 components, i.e. {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_RGBA}.
          +     * @param location origin, if null 0/0 is assumed.
          +     * @return
          +     */
          +    public static BufferedImage createBufferedImage(int width, int height, int numComponents, Point location) {
          +        final int[] bandOffsets = new int[numComponents];
          +        for (int i=0; i < numComponents; i++) {
          +            bandOffsets[i] = i;
          +        }
          +        final int bpp, rmask, gmask, bmask, amask;
          +        final ColorModel cm;
          +        if( 4 == numComponents ) {
          +            bpp = 32;
          +            rmask = 0x00ff0000;
          +            gmask = 0x0000ff00;
          +            bmask = 0x000000ff;
          +            amask = 0xff000000;
          +            cm = ColorModel.getRGBdefault();
          +        } else if( 3 == numComponents ) {
          +            bpp = 24;
          +            rmask = 0x00ff0000;
          +            gmask = 0x0000ff00;
          +            bmask = 0x000000ff;
          +            amask = 0x0;
          +            cm = new DirectColorModel(bpp, rmask, gmask, bmask, amask);
          +        } else {
          +            throw new IllegalArgumentException("numComponents must be [3..4], has "+numComponents);
          +        }
          +        final int[] bandMasks;
          +        if ( 0 != amask ) {
          +            bandMasks = new int[4];
          +            bandMasks[3] = amask;
          +        }
          +        else {
          +            bandMasks = new int[3];
          +        }
          +        bandMasks[0] = rmask;
          +        bandMasks[1] = gmask;
          +        bandMasks[2] = bmask;
          +        
          +        final DirectDataBufferInt dataBuffer = new DirectDataBufferInt(width*height);
          +        if( null == location ) {
          +            location = new Point(0,0);
          +        }
          +        final SinglePixelPackedSampleModel sppsm = new SinglePixelPackedSampleModel(dataBuffer.getDataType(), 
          +                    width, height, width /* scanLineStride */, bandMasks);
          +        // IntegerComponentRasters must haveinteger DataBuffers:
          +        //    final WritableRaster raster = new IntegerInterleavedRaster(sppsm, dataBuffer, location);
          +        // Not public:
          +        //    final WritableRaster raster = new SunWritableRaster(sppsm, dataBuffer, location);
          +        final WritableRaster raster = new DirectWritableRaster(sppsm, dataBuffer, location);
          +        
          +        return new BufferedImage (cm, raster, false /* isRasterPremultiplied */, null /* properties */);
          +    }
          +    
          +    /** Default data bank. */
          +    private IntBuffer data;
          +
          +    /** All data banks */
          +    private IntBuffer bankdata[];
          +    
          +    /**
          +     * Constructs an nio integer-based {@link DataBuffer} with a single bank 
          +     * and the specified size.
          +     *
          +     * @param size The size of the {@link DataBuffer}.
          +     */
          +    public DirectDataBufferInt(int size) {
          +        super(TYPE_INT, size);
          +        data = Buffers.newDirectIntBuffer(size);
          +        bankdata = new IntBuffer[1];
          +        bankdata[0] = data;
          +    }
          +
          +    /**
          +     * Constructs an nio integer-based {@link DataBuffer} with the specified number of
          +     * banks, all of which are the specified size.
          +     *
          +     * @param size The size of the banks in the {@link DataBuffer}.
          +     * @param numBanks The number of banks in the a{@link DataBuffer}.
          +     */
          +    public DirectDataBufferInt(int size, int numBanks) {
          +        super(TYPE_INT,size,numBanks);
          +        bankdata = new IntBuffer[numBanks];
          +        for (int i= 0; i < numBanks; i++) {
          +            bankdata[i] = Buffers.newDirectIntBuffer(size);
          +        }
          +        data = bankdata[0];
          +    }
          +
          +    /**
          +     * Constructs an nio integer-based {@link DataBuffer} with a single bank using the
          +     * specified array.
          +     * 

          + * Only the first size elements should be used by accessors of + * this {@link DataBuffer}. dataArray must be large enough to + * hold size elements. + *

          + * + * @param dataArray The integer array for the {@link DataBuffer}. + * @param size The size of the {@link DataBuffer} bank. + */ + public DirectDataBufferInt(IntBuffer dataArray, int size) { + super(TYPE_INT,size); + data = dataArray; + bankdata = new IntBuffer[1]; + bankdata[0] = data; + } + + /** + * Returns the default (first) int data array in {@link DataBuffer}. + * + * @return The first integer data array. + */ + public IntBuffer getData() { + return data; + } + + /** + * Returns the data array for the specified bank. + * + * @param bank The bank whose data array you want to get. + * @return The data array for the specified bank. + */ + public IntBuffer getData(int bank) { + return bankdata[bank]; + } + + /** + * Returns the requested data array element from the first (default) bank. + * + * @param i The data array element you want to get. + * @return The requested data array element as an integer. + * @see #setElem(int, int) + * @see #setElem(int, int, int) + */ + public int getElem(int i) { + return data.get(i+offset); + } + + /** + * Returns the requested data array element from the specified bank. + * + * @param bank The bank from which you want to get a data array element. + * @param i The data array element you want to get. + * @return The requested data array element as an integer. + * @see #setElem(int, int) + * @see #setElem(int, int, int) + */ + public int getElem(int bank, int i) { + return bankdata[bank].get(i+offsets[bank]); + } + + /** + * Sets the requested data array element in the first (default) bank + * to the specified value. + * + * @param i The data array element you want to set. + * @param val The integer value to which you want to set the data array element. + * @see #getElem(int) + * @see #getElem(int, int) + */ + public void setElem(int i, int val) { + data.put(i+offset, val); + } + + /** + * Sets the requested data array element in the specified bank + * to the integer value i. + * @param bank The bank in which you want to set the data array element. + * @param i The data array element you want to set. + * @param val The integer value to which you want to set the specified data array element. + * @see #getElem(int) + * @see #getElem(int, int) + */ + public void setElem(int bank, int i, int val) { + bankdata[bank].put(i+offsets[bank], val); + } +} + diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java new file mode 100644 index 000000000..ad699c0f5 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java @@ -0,0 +1,296 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.tile; + +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Graphics2D; +import java.awt.Insets; +import java.awt.Label; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.InvocationTargetException; + +import javax.imageio.ImageIO; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLProfile; +import javax.media.opengl.awt.GLJPanel; +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLayeredPane; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +import com.jogamp.common.util.awt.AWTEDTExecutor; +import com.jogamp.nativewindow.awt.AWTPrintLifecycle; +import com.jogamp.nativewindow.awt.DirectDataBufferInt; +import com.jogamp.opengl.test.junit.jogl.demos.es2.RedSquareES2; +import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.util.texture.TextureIO; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestTiledPrintingNIOImageSwingAWT extends UITestCase { + + static boolean waitForKey = false; + /** only when run manually .. */ + static boolean allow600dpi = false; + static GLProfile glp; + static int width, height; + + @BeforeClass + public static void initClass() { + if(GLProfile.isAvailable(GLProfile.GL2)) { + glp = GLProfile.get(GLProfile.GL2); + Assert.assertNotNull(glp); + width = 640; + height = 480; + } else { + setTestSupported(false); + } + // Runtime.getRuntime().traceInstructions(true); + // Runtime.getRuntime().traceMethodCalls(true); + } + + @AfterClass + public static void releaseClass() { + } + + protected void printOffscreenToFile(final BufferedImage image, final Frame frame, final GLCapabilities caps, final int num, final String detail) { + final Insets frameInsets = frame.getInsets(); + final int frameWidth = frame.getWidth(); + final int frameHeight= frame.getHeight(); + final int imageWidth = image.getWidth(); + final int imageHeight= image.getHeight(); + final double scaleComp72; + { + final double frameBorderW = frameInsets.left + frameInsets.right; + final double frameBorderH = frameInsets.top + frameInsets.bottom; + final double sx = (double)imageWidth / ( frameWidth + frameBorderW ); + final double sy = (double)imageHeight / ( frameHeight + frameBorderH ); + scaleComp72 = Math.min(sx, sy); + } + System.err.println("PRINT DPI: scaleComp72 "+scaleComp72+", image-size "+imageWidth+"x"+imageHeight+", frame[border "+frameInsets+", size "+frameWidth+"x"+frameHeight+"]"); + + System.err.println("XXX: image "+image); + System.err.println("XXX: cm "+image.getColorModel()); + System.err.println("XXX: raster "+image.getRaster()); + System.err.println("XXX: dataBuffer "+image.getRaster().getDataBuffer()); + + AWTEDTExecutor.singleton.invoke(true, new Runnable() { + public void run() { + final Graphics2D g2d = (Graphics2D) image.getGraphics(); + g2d.setClip(0, 0, image.getWidth(), image.getHeight()); + g2d.scale(scaleComp72, scaleComp72); + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + + // frame.paintAll(g2d); + final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(frame, 1.0/scaleComp72, 1.0/scaleComp72, 0); + try { + frame.printAll(g2d); + } finally { + ctx.releasePrint(); + } + // to file + final String fname = getSnapshotFilename(num, detail, caps, image.getWidth(), image.getHeight(), false, TextureIO.PNG, null); + System.err.println("XXX file "+fname); + final File fout = new File(fname); + try { + ImageIO.write(image, "png", fout); + } catch (IOException e) { + e.printStackTrace(); + } + } }); + } + + protected void runTestGL(final GLCapabilities caps, final boolean layered) throws InterruptedException, InvocationTargetException { + final int layerStepX = width/6, layerStepY = height/6; + final Dimension glc_sz = new Dimension(layered ? width - 2*layerStepX : width/2, layered ? height - 2*layerStepY : height); + final GLJPanel glJPanel1 = new GLJPanel(caps); + Assert.assertNotNull(glJPanel1); + glJPanel1.setMinimumSize(glc_sz); + glJPanel1.setPreferredSize(glc_sz); + if( layered ) { + glJPanel1.setBounds(layerStepX/2, layerStepY/2, glc_sz.width, glc_sz.height); + } else { + glJPanel1.setBounds(0, 0, glc_sz.width, glc_sz.height); + } + glJPanel1.addGLEventListener(new Gears()); + + final GLJPanel glJPanel2 = new GLJPanel(caps); + Assert.assertNotNull(glJPanel2); + glJPanel2.setMinimumSize(glc_sz); + glJPanel2.setPreferredSize(glc_sz); + if( layered ) { + glJPanel2.setBounds(3*layerStepY, 2*layerStepY, glc_sz.width, glc_sz.height); + } else { + glJPanel2.setBounds(0, 0, glc_sz.width, glc_sz.height); + } + glJPanel2.addGLEventListener(new RedSquareES2()); + // glJPanel2.addGLEventListener(new Gears()); + + final JComponent demoPanel; + if( layered ) { + glJPanel1.setOpaque(true); + glJPanel2.setOpaque(false); + final Dimension lsz = new Dimension(width, height); + demoPanel = new JLayeredPane(); + demoPanel.setMinimumSize(lsz); + demoPanel.setPreferredSize(lsz); + demoPanel.setBounds(0, 0, lsz.width, lsz.height); + demoPanel.setBorder(BorderFactory.createTitledBorder("Layered Pane")); + demoPanel.add(glJPanel1, JLayeredPane.DEFAULT_LAYER); + demoPanel.add(glJPanel2, Integer.valueOf(1)); + final JButton tb = new JButton("On Top"); + tb.setBounds(4*layerStepY, 3*layerStepY, 100, 50); + demoPanel.add(tb, Integer.valueOf(2)); + } else { + demoPanel = new JPanel(); + demoPanel.add(glJPanel1); + demoPanel.add(glJPanel2); + } + + final JFrame frame = new JFrame("Swing Print"); + Assert.assertNotNull(frame); + + final Button print72DPIButton = new Button("72dpi"); // dummy + final Button print300DPIButton = new Button("300dpi"); // dummy + final Button print600DPIButton = new Button("600dpi"); // dummy + + final JPanel printPanel = new JPanel(); + printPanel.add(print72DPIButton); + printPanel.add(print300DPIButton); + printPanel.add(print600DPIButton); + final JPanel southPanel = new JPanel(); + southPanel.add(new Label("South")); + final JPanel eastPanel = new JPanel(); + eastPanel.add(new Label("East")); + final JPanel westPanel = new JPanel(); + westPanel.add(new Label("West")); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + final Container fcont = frame.getContentPane(); + fcont.setLayout(new BorderLayout()); + fcont.add(printPanel, BorderLayout.NORTH); + fcont.add(demoPanel, BorderLayout.CENTER); + fcont.add(southPanel, BorderLayout.SOUTH); + fcont.add(eastPanel, BorderLayout.EAST); + fcont.add(westPanel, BorderLayout.WEST); + fcont.validate(); + frame.pack(); + frame.setVisible(true); + } } ) ; + + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame, true)); + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glJPanel1, true)); + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glJPanel2, true)); + + // paint offscreen: array 72dpi + { + final BufferedImage image = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_INT_ARGB); + printOffscreenToFile(image, frame, caps, 0, "array_072dpi"); + } + // paint offscreen: NIO 72dpi + { + final BufferedImage image = DirectDataBufferInt.createBufferedImage(frame.getWidth(), frame.getHeight(), 4, null /* location */); + printOffscreenToFile(image, frame, caps, 1, "newio_072dpi"); + } + // paint offscreen: NIO 600dpi + { + final int scale = (int) ( 600.0 / 72.0 + 0.5 ); + final BufferedImage image = DirectDataBufferInt.createBufferedImage(frame.getWidth()*scale, frame.getHeight()*scale, 4, null /* location */); + printOffscreenToFile(image, frame, caps, 2, "newio_600dpi"); + } + + Assert.assertNotNull(frame); + Assert.assertNotNull(glJPanel1); + Assert.assertNotNull(glJPanel2); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setVisible(false); + }}); + Assert.assertEquals(false, frame.isVisible()); + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + final Frame _frame = frame; + _frame.remove(demoPanel); + _frame.dispose(); + }}); + } + + @Test + public void test01_Offscreen_aa0() throws InterruptedException, InvocationTargetException { + GLCapabilities caps = new GLCapabilities(glp); + runTestGL(caps, false); + } + + static long duration = 500; // ms + + public static void main(String args[]) { + allow600dpi = true; + for(int i=0; i Date: Tue, 24 Sep 2013 23:13:16 +0200 Subject: Bug 816: Fix OSX CALayer 'quirks' for AWT 1.7.0_40 - See JAWTUtil JAWT_OSX_CALAYER_QUIRK_SIZE and JAWT_OSX_CALAYER_QUIRK_POSITION. - Provide quirk bits for OSX CALayer depending on used JVM/AWT and act accordingly. - TestBug816OSXCALayerPosAWT: Add resize by frame --- .../macosx/MacOSXWindowSystemInterface-calayer.m | 76 ++++++----- .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 76 ++++++++++- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 14 +- .../jogamp/nativewindow/macosx/OSXUtil.java | 26 ++-- .../native/macosx/NativeWindowProtocols.h | 21 ++- src/nativewindow/native/macosx/OSXmisc.m | 143 +++++++++++++-------- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 5 +- .../jogamp/newt/awt/applet/JOGLNewtApplet1Run.java | 7 +- .../junit/jogl/awt/TestBug816OSXCALayerPosAWT.java | 120 +++++++++++++---- 9 files changed, 355 insertions(+), 133 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index 046171efc..d15c8e038 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -150,7 +150,7 @@ extern GLboolean glIsVertexArray (GLuint array); @end -@interface MyNSOpenGLLayer: NSOpenGLLayer +@interface MyNSOpenGLLayer: NSOpenGLLayer { @private GLfloat gl_texCoords[8]; @@ -166,8 +166,8 @@ extern GLboolean glIsVertexArray (GLuint array); NSOpenGLPixelFormat* parentPixelFmt; int texWidth; int texHeight; - volatile int dedicatedWidth; - volatile int dedicatedHeight; + volatile Bool dedicatedFrameSet; + volatile CGRect dedicatedFrame; volatile NSOpenGLPixelBuffer* pbuffer; volatile GLuint textureID; volatile NSOpenGLPixelBuffer* newPBuffer; @@ -206,14 +206,14 @@ extern GLboolean glIsVertexArray (GLuint array); - (Bool)isGLSourceValid; - (void) setGLEnabled: (Bool) enable; -- (Bool) validateTexSizeWithDedicatedSize; +- (Bool) validateTexSize: (CGRect) lRect; - (void) setTextureID: (int) _texID; - (Bool) isSamePBuffer: (NSOpenGLPixelBuffer*) p; - (void) setNewPBuffer: (NSOpenGLPixelBuffer*)p; - (void) applyNewPBuffer; -- (void)setDedicatedSize:(CGSize)size; // @NWDedicatedSize +- (void)setDedicatedFrame:(CGRect)frame quirks:(int)quirks; // @NWDedicatedFrame - (void) setFrame:(CGRect) frame; - (id)actionForKey:(NSString *)key ; - (NSOpenGLPixelFormat *)openGLPixelFormatForDisplayMask:(uint32_t)mask; @@ -300,9 +300,9 @@ static const GLfloat gl_verts[] = { timespec_now(&lastWaitTime); shallDraw = NO; isGLEnabled = YES; - dedicatedWidth = _texWidth; - dedicatedHeight = _texHeight; - [self validateTexSizeWithDedicatedSize]; + dedicatedFrameSet = NO; + dedicatedFrame = CGRectMake(0, 0, _texWidth, _texHeight); + [self validateTexSize: dedicatedFrame]; [self setTextureID: texID]; newPBuffer = NULL; @@ -383,11 +383,16 @@ static const GLfloat gl_verts[] = { isGLEnabled = enable; } -- (Bool) validateTexSizeWithDedicatedSize +- (Bool) validateTexSize: (CGRect) lRect { - if( dedicatedHeight != texHeight || dedicatedWidth != texWidth ) { - texWidth = dedicatedWidth; - texHeight = dedicatedHeight; + const int lRectW = (int) (lRect.size.width + 0.5f); + const int lRectH = (int) (lRect.size.height + 0.5f); + Bool changed; + + if( lRectH != texHeight || lRectW != texWidth ) { + texWidth = lRectW; + texHeight = lRectH; + changed = YES; GLfloat texCoordWidth, texCoordHeight; if(NULL != pbuffer) { @@ -409,16 +414,16 @@ static const GLfloat gl_verts[] = { gl_texCoords[5] = texCoordHeight; gl_texCoords[4] = texCoordWidth; gl_texCoords[6] = texCoordWidth; -#ifdef VERBOSE_ON - CGRect lRect = [self bounds]; - DBG_PRINT("MyNSOpenGLLayer::validateTexSize %p -> tex %dx%d, bounds: %lf/%lf %lfx%lf\n", + #ifdef VERBOSE_ON + DBG_PRINT("MyNSOpenGLLayer::validateTexSize %p -> tex %dx%d, bounds: %lf/%lf %lfx%lf (%dx%d), dedicatedFrame set:%d %lf/%lf %lfx%lf\n", self, texWidth, texHeight, - lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); -#endif - return YES; + lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, lRectW, lRectH, + dedicatedFrameSet, dedicatedFrame.origin.x, dedicatedFrame.origin.y, dedicatedFrame.size.width, dedicatedFrame.size.height); + #endif } else { - return NO; + changed = NO; } + return changed; } - (void) setTextureID: (int) _texID @@ -560,21 +565,30 @@ static const GLfloat gl_verts[] = { return NULL != pbuffer || NULL != newPBuffer || 0 != textureID ; } -// @NWDedicatedSize -- (void)setDedicatedSize:(CGSize)size { - DBG_PRINT("MyNSOpenGLLayer::setDedicatedSize: %p, texSize %dx%d <- %lfx%lf\n", - self, texWidth, texHeight, size.width, size.height); - - dedicatedWidth = size.width; - dedicatedHeight = size.height; +// @NWDedicatedFrame +- (void)setDedicatedFrame:(CGRect)dFrame quirks:(int)quirks { + CGRect lRect = [self frame]; + Bool dedicatedFramePosSet = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & quirks ); + Bool dedicatedFrameSizeSet = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & quirks ); + dedicatedFrameSet = dedicatedFramePosSet || dedicatedFrameSizeSet; + dedicatedFrame = dFrame; - CGRect rect = CGRectMake(0, 0, dedicatedWidth, dedicatedHeight); - [super setFrame: rect]; + DBG_PRINT("MyNSOpenGLLayer::setDedicatedFrame: Quirks [%d, pos %d, size %d], %p, texSize %dx%d, %lf/%lf %lfx%lf -> %lf/%lf %lfx%lf\n", + quirks, dedicatedFramePosSet, dedicatedFrameSizeSet, self, texWidth, texHeight, + lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, + dFrame.origin.x, dFrame.origin.y, dFrame.size.width, dFrame.size.height); + + if( dedicatedFrameSet ) { + [super setFrame: dedicatedFrame]; + } } - (void) setFrame:(CGRect) frame { - CGRect rect = CGRectMake(0, 0, dedicatedWidth, dedicatedHeight); - [super setFrame: rect]; + if( dedicatedFrameSet ) { + [super setFrame: dedicatedFrame]; + } else { + [super setFrame: frame]; + } } - (id)actionForKey:(NSString *)key @@ -622,7 +636,7 @@ static const GLfloat gl_verts[] = { GLenum textureTarget; - Bool texSizeChanged = [self validateTexSizeWithDedicatedSize]; + Bool texSizeChanged = [self validateTexSize: ( dedicatedFrameSet ? dedicatedFrame : [self bounds] ) ]; if( texSizeChanged ) { [context update]; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index 1f5d33746..b663f90b7 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -68,7 +68,7 @@ public class JAWTUtil { public static final VersionNumber JAWT_MacOSXCALayerMinVersion = new VersionNumber(10,6,4); /** OSX JAWT CALayer required with Java >= 1.7.0 (implies OS X >= 10.7 */ - public static final VersionNumber JAWT_MacOSXCALayerRequiredForJavaVersion = new VersionNumber(1,7,0); + public static final VersionNumber JAWT_MacOSXCALayerRequiredForJavaVersion = Platform.Version17; // See whether we're running in headless mode private static final boolean headlessMode; @@ -98,18 +98,84 @@ public class JAWTUtil { * Returns true if this platform's JAWT implementation supports offscreen layer. */ public static boolean isOffscreenLayerSupported() { - return Platform.OS_TYPE == Platform.OSType.MACOS && - Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0; + return Platform.OS_TYPE == Platform.OSType.MACOS && + Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0; } /** * Returns true if this platform's JAWT implementation requires using offscreen layer. */ public static boolean isOffscreenLayerRequired() { - return Platform.OS_TYPE == Platform.OSType.MACOS && - Platform.JAVA_VERSION_NUMBER.compareTo(JAWT_MacOSXCALayerRequiredForJavaVersion)>=0; + return Platform.OS_TYPE == Platform.OSType.MACOS && + Platform.JAVA_VERSION_NUMBER.compareTo(JAWT_MacOSXCALayerRequiredForJavaVersion)>=0; } + /** + * CALayer size needs to be set using the AWT component size. + *

          + * As of today, we have to overwrite the CALayer size + * w/ the AWT component one since programmatic resize leads to differences. + *

          + *

          + * Hence this flag is always enabled. + *

          + *

          + * Sync w/ NativeWindowProtocols.h + *

          + */ + public static final int JAWT_OSX_CALAYER_QUIRK_SIZE = 1 << 0; + + /** + * CALayer position needs to be set to zero. + *

          + * Normally we have to set the root-calayer's position to 0/0 + * and leave client-calayer's position in it's desired place. + * With pre AWT 1.7.0_40, the client-calayer's position has to + * be set to zero as well. + *

          + *

          + * Further more a re-layout seems to be required in this case, + * i.e. a programmatic forced resize +1 and it's inverted resize -1. + *

          + *

          + * Hence this flag is enabled w/ AWT < 1.7.0_40. + *

          + *

          + * Sync w/ NativeWindowProtocols.h + *

          + */ + public static final int JAWT_OSX_CALAYER_QUIRK_POSITION = 1 << 1; + + /** + * Returns bitfield of required JAWT OSX CALayer quirks to mediate AWT impl. bugs. + *

          + * Returns zero, if platform is not {@link Platform.OSType#MACOS} + * or not supporting CALayer, i.e. OSX < 10.6.4. + *

          + *

          + * Otherwise includes + *

            + *
          • {@link #JAWT_OSX_CALAYER_QUIRK_SIZE} (always)
          • + *
          • {@link #JAWT_OSX_CALAYER_QUIRK_POSITION} if JVM < 1.7.0_40
          • + *
          + *

          + */ + public static int getOSXCALayerQuirks() { + int res = 0; + if( Platform.OS_TYPE == Platform.OSType.MACOS && + Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0 ) { + + /** Knowing impl. all expose the SIZE bug */ + res |= JAWT_OSX_CALAYER_QUIRK_SIZE; + + final int c = Platform.JAVA_VERSION_NUMBER.compareTo(Platform.Version17); + if( c < 0 || c == 0 && Platform.JAVA_VERSION_UPDATE < 40 ) { + res |= JAWT_OSX_CALAYER_QUIRK_POSITION; + } + } + return res; + } + /** * @param useOffscreenLayerIfAvailable * @return diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 080504a5c..666f895f4 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -49,6 +49,7 @@ import javax.media.nativewindow.Capabilities; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.MutableSurface; +import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.util.Point; import com.jogamp.nativewindow.awt.JAWTWindow; @@ -105,16 +106,19 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { protected void attachSurfaceLayerImpl(final long layerHandle) { OSXUtil.RunOnMainThread(false, new Runnable() { public void run() { - OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, getWidth(), getHeight()); + OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, getWidth(), getHeight(), JAWTUtil.getOSXCALayerQuirks()); } } ); } @Override protected void layoutSurfaceLayerImpl(long layerHandle, int width, int height) { - if(DEBUG) { - System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", "+width+"x"+height+"; "+this); + final int caLayerQuirks = JAWTUtil.getOSXCALayerQuirks(); + if( 0 != caLayerQuirks ) { + if(DEBUG) { + System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", "+width+"x"+height+", caLayerQuirks "+caLayerQuirks+"; "+this); + } + OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, width, height, caLayerQuirks); } - OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, width, height); } @Override @@ -240,7 +244,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { public void run() { String errMsg = null; if(0 == rootSurfaceLayer && 0 != jawtSurfaceLayersHandle) { - rootSurfaceLayer = OSXUtil.CreateCALayer(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); + rootSurfaceLayer = OSXUtil.CreateCALayer(bounds.getWidth(), bounds.getHeight()); if(0 == rootSurfaceLayer) { errMsg = "Could not create root CALayer"; } else { diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 1a90c095d..de24a76db 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -141,8 +141,8 @@ public class OSXUtil implements ToolkitProperties { * @see #DestroyCALayer(long) * @see #AddCASublayer(long, long) */ - public static long CreateCALayer(final int x, final int y, final int width, final int height) { - final long l = CreateCALayer0(x, y, width, height); + public static long CreateCALayer(final int width, final int height) { + final long l = CreateCALayer0(width, height); if(DEBUG) { System.err.println("OSXUtil.CreateCALayer: 0x"+Long.toHexString(l)+" - "+Thread.currentThread().getName()); } @@ -159,17 +159,18 @@ public class OSXUtil implements ToolkitProperties { * Hence it is important that related resources are not locked if * they will be used for creation. *

          - * @see #CreateCALayer(int, int, int, int) + * @param caLayerQuirks TODO + * @see #CreateCALayer(int, int) * @see #RemoveCASublayer(long, long, boolean) */ - public static void AddCASublayer(final long rootCALayer, final long subCALayer, final int width, final int height) { + public static void AddCASublayer(final long rootCALayer, final long subCALayer, final int width, final int height, final int caLayerQuirks) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } if(DEBUG) { - System.err.println("OSXUtil.AttachCALayer: 0x"+Long.toHexString(subCALayer)+" - "+Thread.currentThread().getName()); + System.err.println("OSXUtil.AttachCALayer: caLayerQuirks "+caLayerQuirks+", 0x"+Long.toHexString(subCALayer)+" - "+Thread.currentThread().getName()); } - AddCASublayer0(rootCALayer, subCALayer, width, height); + AddCASublayer0(rootCALayer, subCALayer, width, height, caLayerQuirks); } /** @@ -187,12 +188,13 @@ public class OSXUtil implements ToolkitProperties { * @param subCALayer the client surface layer, maybe null. * @param width the expected width * @param height the expected height + * @param caLayerQuirks TODO */ - public static void FixCALayerLayout(final long rootCALayer, final long subCALayer, final int width, final int height) { + public static void FixCALayerLayout(final long rootCALayer, final long subCALayer, final int width, final int height, final int caLayerQuirks) { if( 0==rootCALayer && 0==subCALayer ) { return; } - FixCALayerLayout0(rootCALayer, subCALayer, width, height); + FixCALayerLayout0(rootCALayer, subCALayer, width, height, caLayerQuirks); } /** @@ -210,7 +212,7 @@ public class OSXUtil implements ToolkitProperties { /** * Destroy a CALayer. - * @see #CreateCALayer(int, int, int, int) + * @see #CreateCALayer(int, int) */ public static void DestroyCALayer(final long caLayer) { if(0==caLayer) { @@ -354,9 +356,9 @@ public class OSXUtil implements ToolkitProperties { private static native void DestroyNSWindow0(long nsWindow); private static native long GetNSView0(long nsWindow); private static native long GetNSWindow0(long nsView); - private static native long CreateCALayer0(int x, int y, int width, int height); - private static native void AddCASublayer0(long rootCALayer, long subCALayer, int width, int height); - private static native void FixCALayerLayout0(long rootCALayer, long subCALayer, int width, int height); + private static native long CreateCALayer0(int width, int height); + private static native void AddCASublayer0(long rootCALayer, long subCALayer, int width, int height, int caLayerQuirks); + private static native void FixCALayerLayout0(long rootCALayer, long subCALayer, int width, int height, int caLayerQuirks); private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); private static native void RunOnMainThread0(Runnable runnable); diff --git a/src/nativewindow/native/macosx/NativeWindowProtocols.h b/src/nativewindow/native/macosx/NativeWindowProtocols.h index b91a50dfd..73c8e65c5 100644 --- a/src/nativewindow/native/macosx/NativeWindowProtocols.h +++ b/src/nativewindow/native/macosx/NativeWindowProtocols.h @@ -25,10 +25,27 @@ * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ + +#ifndef NATIVEWINDOWPROTOCOLS_H +#define NATIVEWINDOWPROTOCOLS_H 1 +/** + * CALayer size needs to be set using the AWT component size. + * See detailed description in JAWTUtil.java and sync w/ changed. + */ +#define NW_DEDICATEDFRAME_QUIRK_SIZE ( 1 << 0 ) + +/** + * CALayer position needs to be set to zero. + * See detailed description in JAWTUtil.java and sync w/ changed. + */ +#define NW_DEDICATEDFRAME_QUIRK_POSITION ( 1 << 1 ) + #import -@protocol NWDedicatedSize -- (void)setDedicatedSize:(CGSize)size; +@protocol NWDedicatedFrame +- (void)setDedicatedFrame:(CGRect)dFrame quirks:(int)quirks; @end +#endif /* NATIVEWINDOWPROTOCOLS_H_ */ + diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 688ef79b8..afe3b3868 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -395,23 +395,23 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: CreateCALayer0 - * Signature: (IIII)J + * Signature: (II)J */ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 - (JNIEnv *env, jclass unused, jint x, jint y, jint width, jint height) + (JNIEnv *env, jclass unused, jint width, jint height) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; MyCALayer* layer = [[MyCALayer alloc] init]; - DBG_PRINT("CALayer::CreateCALayer.0: root %p %d/%d %dx%d (refcnt %d)\n", layer, (int)x, (int)y, (int)width, (int)height, (int)[layer retainCount]); + DBG_PRINT("CALayer::CreateCALayer.0: root %p 0/0 %dx%d (refcnt %d)\n", layer, (int)width, (int)height, (int)[layer retainCount]); // avoid zero size if(0 == width) { width = 32; } if(0 == height) { height = 32; } // initial dummy size ! CGRect lRect = [layer frame]; - lRect.origin.x = x; - lRect.origin.y = y; + lRect.origin.x = 0; + lRect.origin.y = 0; lRect.size.width = width; lRect.size.height = height; [layer setFrame: lRect]; @@ -428,45 +428,79 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 return (jlong) ((intptr_t) layer); } -static void FixCALayerLayout0(MyCALayer* rootLayer, CALayer* subLayer, jint width, jint height) { +static void FixCALayerLayout0(MyCALayer* rootLayer, CALayer* subLayer, jint width, jint height, jint caLayerQuirks, jboolean force) { if( NULL != rootLayer ) { CGRect lRect = [rootLayer frame]; - if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { - DBG_PRINT("CALayer::FixCALayerLayout0.0: Root %p frame %lf/%lf %lfx%lf -> 0/0 %dx%d\n", - rootLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, (int)width, (int)height); - lRect.origin.x = 0; - lRect.origin.y = 0; - lRect.size.width = width; - lRect.size.height = height; + int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lRect.origin.x!=0 || lRect.origin.y!=0 ); + int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lRect.size.width!=width || lRect.size.height!=height ); + CGFloat _x, _y, _w, _h; + // force root -> 0/0 + _x = 0; + _y = 0; + posQuirk |= 8; + if( sizeQuirk ) { + _w = width; + _h = height; + } else { + _w = lRect.size.width; + _h = lRect.size.height; + } + DBG_PRINT("CALayer::FixCALayerLayout0.0: Quirks [%d, pos %d, size %d], Root %p frame %lf/%lf %lfx%lf, usr %dx%d -> %lf/%lf %lfx%lf\n", + caLayerQuirks, posQuirk, sizeQuirk, rootLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, + width, height, _x, _y, _w, _h); + if( posQuirk || sizeQuirk ) { + lRect.origin.x = _x; + lRect.origin.y = _y; + lRect.size.width = _w; + lRect.size.height = _h; [rootLayer setFrame: lRect]; } } if( NULL != subLayer ) { CGRect lRect = [subLayer frame]; - if(lRect.origin.x!=0 || lRect.origin.y!=0 || lRect.size.width!=width || lRect.size.height!=height) { - DBG_PRINT("CALayer::FixCALayerLayout0.0: SubL %p frame %lf/%lf %lfx%lf -> 0/0 %dx%d\n", - subLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, (int)width, (int)height); - lRect.origin.x = 0; - lRect.origin.y = 0; - lRect.size.width = width; - lRect.size.height = height; - if( [subLayer conformsToProtocol:@protocol(NWDedicatedSize)] ) { - CALayer * subLayerDS = (CALayer *) subLayer; - [subLayerDS setDedicatedSize: lRect.size]; + int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lRect.size.width!=width || lRect.size.height!=height ); + CGFloat _x, _y, _w, _h; + int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lRect.origin.x!=0 || lRect.origin.y!=0 ); + if( posQuirk ) { + _x = 0; + _y = 0; + } else { + // sub always rel to root + _x = lRect.origin.x; + _y = lRect.origin.y; + } + if( sizeQuirk ) { + _w = width; + _h = height; + } else { + _w = lRect.size.width; + _h = lRect.size.height; + } + DBG_PRINT("CALayer::FixCALayerLayout1.0: Quirks [%d, pos %d, size %d], SubL %p frame %lf/%lf %lfx%lf, usr %dx%d -> %lf/%lf %lfx%lf\n", + caLayerQuirks, posQuirk, sizeQuirk, subLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, + width, height, _x, _y, _w, _h); + if( force || posQuirk || sizeQuirk ) { + lRect.origin.x = _x; + lRect.origin.y = _y; + lRect.size.width = _w; + lRect.size.height = _h; + if( [subLayer conformsToProtocol:@protocol(NWDedicatedFrame)] ) { + CALayer * subLayerDS = (CALayer *) subLayer; + [subLayerDS setDedicatedFrame: lRect quirks: caLayerQuirks]; } else { [subLayer setFrame: lRect]; } - } + } } } /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: AddCASublayer0 - * Signature: (JJII)V + * Signature: (JJIIIII)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 - (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint width, jint height) + (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint width, jint height, jint caLayerQuirks) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); @@ -479,20 +513,23 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 [subLayer retain]; // Pairs w/ RemoveCASublayer CGRect lRectRoot = [rootLayer frame]; - DBG_PRINT("CALayer::AddCASublayer0.0: Origin %p frame0: %lf/%lf %lfx%lf\n", - rootLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height); - if(lRectRoot.origin.x!=0 || lRectRoot.origin.y!=0) { - lRectRoot.origin.x = 0; - lRectRoot.origin.y = 0; - [rootLayer setFrame: lRectRoot]; - DBG_PRINT("CALayer::AddCASublayer0.1: Origin %p frame*: %lf/%lf %lfx%lf\n", - rootLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height); + int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ); + int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ); + + DBG_PRINT("CALayer::AddCASublayer0.0: Quirks [%d, pos %d, size %d], Root %p (refcnt %d), Sub %p (refcnt %d), frame0: %lf/%lf %lfx%lf\n", + caLayerQuirks, posQuirk, sizeQuirk, rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount], + lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height); + + CGPoint origin = lRectRoot.origin; // save + // force root to 0/0 + lRectRoot.origin.x = 0; + lRectRoot.origin.y = 0; + [rootLayer setFrame: lRectRoot]; + + // simple 1:1 layout rel. to root-layer ! + if( !posQuirk ) { + lRectRoot.origin = origin; } - DBG_PRINT("CALayer::AddCASublayer0.2: root %p (refcnt %d) .sub %p %lf/%lf %lfx%lf (refcnt %d)\n", - rootLayer, (int)[rootLayer retainCount], - subLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height, (int)[subLayer retainCount]); - - // simple 1:1 layout ! [subLayer setFrame:lRectRoot]; [rootLayer addSublayer:subLayer]; @@ -507,7 +544,9 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 [subLayer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; [subLayer setNeedsDisplayOnBoundsChange: YES]; - FixCALayerLayout0(rootLayer, subLayer, width, height); + if( 0 != caLayerQuirks ) { + FixCALayerLayout0(rootLayer, subLayer, width, height, caLayerQuirks, JNI_TRUE); + } [CATransaction commit]; @@ -519,23 +558,25 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: FixCALayerLayout0 - * Signature: (JJII)V + * Signature: (JJIIIII)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_FixCALayerLayout0 - (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint width, jint height) + (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint width, jint height, int caLayerQuirks) { - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); - CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); + if( 0 != caLayerQuirks ) { + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); + CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); - [CATransaction begin]; - [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; + [CATransaction begin]; + [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; - FixCALayerLayout0(rootLayer, subLayer, width, height); + FixCALayerLayout0(rootLayer, subLayer, width, height, caLayerQuirks, JNI_FALSE); - [CATransaction commit]; + [CATransaction commit]; - [pool release]; + [pool release]; + } } /* @@ -807,7 +848,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunLater0 /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: IsMainThread0 - * Signature: (V)V + * Signature: (V)Z */ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_IsMainThread0 (JNIEnv *env, jclass unused) diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 374a80325..eadb69ec2 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -56,6 +56,7 @@ import javax.media.opengl.GLDrawableFactory; import javax.swing.MenuSelectionManager; import jogamp.nativewindow.awt.AWTMisc; +import jogamp.nativewindow.jawt.JAWTUtil; import jogamp.newt.Debug; import jogamp.newt.WindowImpl; import jogamp.newt.awt.NewtFactoryAWT; @@ -63,7 +64,6 @@ import jogamp.newt.awt.event.AWTParentWindowAdapter; import jogamp.newt.driver.DriverClearFocus; import jogamp.opengl.awt.AWTTilePainter; -import com.jogamp.common.os.Platform; import com.jogamp.common.util.awt.AWTEDTExecutor; import com.jogamp.nativewindow.awt.AWTPrintLifecycle; import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol; @@ -741,7 +741,8 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto newtChild.setSize(w, h); newtChild.reparentWindow(jawtWindow); newtChild.addSurfaceUpdatedListener(jawtWindow); - if( Platform.OSType.MACOS == Platform.getOSType() && jawtWindow.isOffscreenLayerSurfaceEnabled() ) { + if( jawtWindow.isOffscreenLayerSurfaceEnabled() && + 0 != ( JAWTUtil.JAWT_OSX_CALAYER_QUIRK_POSITION & JAWTUtil.getOSXCALayerQuirks() ) ) { AWTEDTExecutor.singleton.invoke(false, forceRelayout); } newtChild.setVisible(true); diff --git a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java index e8cd71514..83a129455 100644 --- a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java +++ b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java @@ -42,7 +42,8 @@ import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; -import com.jogamp.common.os.Platform; +import jogamp.nativewindow.jawt.JAWTUtil; + import com.jogamp.newt.awt.NewtCanvasAWT; import com.jogamp.newt.opengl.GLWindow; @@ -251,7 +252,9 @@ public class JOGLNewtApplet1Run extends Applet { System.err.println("GLWindow: "+glWindow); } base.start(); - if( null != newtCanvasAWT && Platform.OSType.MACOS == Platform.getOSType() && newtCanvasAWT.isOffscreenLayerSurfaceEnabled() ) { + if( null != newtCanvasAWT && + newtCanvasAWT.isOffscreenLayerSurfaceEnabled() && + 0 != ( JAWTUtil.JAWT_OSX_CALAYER_QUIRK_POSITION & JAWTUtil.getOSXCALayerQuirks() ) ) { // force relayout final int cW = newtCanvasAWT.getWidth(); final int cH = newtCanvasAWT.getHeight(); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPosAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPosAWT.java index f929b4d14..48340aa75 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPosAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPosAWT.java @@ -36,6 +36,7 @@ import javax.media.opengl.awt.GLCanvas; import javax.swing.BoxLayout; import javax.swing.JFrame; +import com.jogamp.common.util.awt.AWTEDTExecutor; import com.jogamp.newt.event.awt.AWTWindowAdapter; import com.jogamp.newt.event.TraceWindowAdapter; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; @@ -71,7 +72,7 @@ import org.junit.runners.MethodSorters; public class TestBug816OSXCALayerPosAWT extends UITestCase { public enum FrameLayout { None, Flow, DoubleBorderCenterSurrounded, Box }; - static long duration = 500; // ms + static long duration = 1600; // ms static int width, height; static boolean forceES2 = false; @@ -102,7 +103,7 @@ public class TestBug816OSXCALayerPosAWT extends UITestCase { static void setComponentSize(final Frame frame, final Component comp1, final java.awt.Dimension new_sz1, final Component comp2, final java.awt.Dimension new_sz2) { try { - javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + AWTEDTExecutor.singleton.invoke(true /* wait */, new Runnable() { public void run() { comp1.setMinimumSize(new_sz1); comp1.setPreferredSize(new_sz1); @@ -121,9 +122,23 @@ public class TestBug816OSXCALayerPosAWT extends UITestCase { Assume.assumeNoException( throwable ); } } + static void setFrameSize(final Frame frame, final boolean frameLayout, final java.awt.Dimension new_sz) { + try { + AWTEDTExecutor.singleton.invoke(true /* wait */, new Runnable() { + public void run() { + frame.setSize(new_sz); + if( frameLayout ) { + frame.validate(); + } + } } ); + } catch( Throwable throwable ) { + throwable.printStackTrace(); + Assume.assumeNoException( throwable ); + } + } - protected void runTestGL(GLCapabilities caps, FrameLayout frameLayout, final boolean twoCanvas) throws InterruptedException, InvocationTargetException { - final JFrame frame = new JFrame("Bug861 AWT Test"); + protected void runTestGL(GLCapabilities caps, FrameLayout frameLayout, final boolean twoCanvas, final boolean resizeByComp) throws InterruptedException, InvocationTargetException { + final JFrame frame = new JFrame("Bug861: "+this.getTestMethodName()); Assert.assertNotNull(frame); final Container framePane = frame.getContentPane(); @@ -138,6 +153,7 @@ public class TestBug816OSXCALayerPosAWT extends UITestCase { } final Dimension glcDim = new Dimension(width/2, height); + final Dimension frameDim = new Dimension(twoCanvas ? width + 64: width/2 + 64, height + 64); setComponentSize(null, glCanvas1, glcDim, glCanvas2, glcDim); @@ -148,7 +164,7 @@ public class TestBug816OSXCALayerPosAWT extends UITestCase { break; case Flow: { final Container c = new Container(); - c.setLayout(new FlowLayout()); + c.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); c.add(glCanvas1); if( twoCanvas ) { c.add(glCanvas2); @@ -209,8 +225,12 @@ public class TestBug816OSXCALayerPosAWT extends UITestCase { javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { - frame.pack(); - frame.setVisible(true); + if( resizeByComp ) { + frame.pack(); + } else { + setFrameSize(frame, true, frameDim); + } + frame.setVisible(true); }}); Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame, true)); Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glCanvas1, true)); @@ -229,8 +249,13 @@ public class TestBug816OSXCALayerPosAWT extends UITestCase { } Thread.sleep(Math.max(1000, duration/2)); - final Dimension rwsizeHalf = new Dimension(rwsize.width/2, rwsize.height); - setComponentSize(frame, glCanvas1, rwsizeHalf, glCanvas2, rwsizeHalf); + final Dimension compRSizeHalf = new Dimension(rwsize.width/2, rwsize.height); + final Dimension frameRSizeHalf = new Dimension(twoCanvas ? rwsize.width + 64: rwsize.width/2 + 64, rwsize.height + 64); + if( resizeByComp ) { + setComponentSize(frame, glCanvas1, compRSizeHalf, glCanvas2, compRSizeHalf); + } else { + setFrameSize(frame, true, frameRSizeHalf); + } System.err.println("resize canvas1 pos/siz: "+glCanvas1.getX()+"/"+glCanvas1.getY()+" "+glCanvas1.getWidth()+"x"+glCanvas1.getHeight()); if( twoCanvas ) { System.err.println("resize canvas2 pos/siz: "+glCanvas2.getX()+"/"+glCanvas2.getY()+" "+glCanvas2.getWidth()+"x"+glCanvas2.getHeight()); @@ -276,52 +301,101 @@ public class TestBug816OSXCALayerPosAWT extends UITestCase { } @Test - public void test00_None_One() throws InterruptedException, InvocationTargetException { + public void test00_Compo_None_One() throws InterruptedException, InvocationTargetException { if( testNum != -1 && testNum != 0 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); - runTestGL(caps, FrameLayout.None, false); + runTestGL(caps, FrameLayout.None, false /* twoCanvas */, true /* resizeByComp */); } @Test - public void test01_Flow_One() throws InterruptedException, InvocationTargetException { + public void test01_Compo_Flow_One() throws InterruptedException, InvocationTargetException { if( testNum != -1 && testNum != 1 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); - runTestGL(caps, FrameLayout.Flow, false); + runTestGL(caps, FrameLayout.Flow, false /* twoCanvas */, true /* resizeByComp */); } @Test - public void test02_DblBrd_One() throws InterruptedException, InvocationTargetException { + public void test02_Compo_DblBrd_One() throws InterruptedException, InvocationTargetException { if( testNum != -1 && testNum != 2 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); - runTestGL(caps, FrameLayout.DoubleBorderCenterSurrounded, false); + runTestGL(caps, FrameLayout.DoubleBorderCenterSurrounded, false /* twoCanvas */, true /* resizeByComp */); } @Test - public void test03_Box_One() throws InterruptedException, InvocationTargetException { + public void test03_Compo_Box_One() throws InterruptedException, InvocationTargetException { if( testNum != -1 && testNum != 3 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); - runTestGL(caps, FrameLayout.Box, false); + runTestGL(caps, FrameLayout.Box, false /* twoCanvas */, true /* resizeByComp */); } @Test - public void test04_Flow_Two() throws InterruptedException, InvocationTargetException { + public void test04_Compo_Flow_Two() throws InterruptedException, InvocationTargetException { if( testNum != -1 && testNum != 4 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); - runTestGL(caps, FrameLayout.Flow, true); + runTestGL(caps, FrameLayout.Flow, true/* twoCanvas */, true /* resizeByComp */); } @Test - public void test05_DblBrd_Two() throws InterruptedException, InvocationTargetException { + public void test05_Compo_DblBrd_Two() throws InterruptedException, InvocationTargetException { if( testNum != -1 && testNum != 5 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); - runTestGL(caps, FrameLayout.DoubleBorderCenterSurrounded, true); + runTestGL(caps, FrameLayout.DoubleBorderCenterSurrounded, true/* twoCanvas */, true /* resizeByComp */); } @Test - public void test06_Box_Two() throws InterruptedException, InvocationTargetException { + public void test06_Compo_Box_Two() throws InterruptedException, InvocationTargetException { if( testNum != -1 && testNum != 6 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); - runTestGL(caps, FrameLayout.Box, true); + runTestGL(caps, FrameLayout.Box, true/* twoCanvas */, true /* resizeByComp */); + } + + @Test + public void test10_Frame_None_One() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 10 ) { return ; } + final GLCapabilities caps = new GLCapabilities(getGLP()); + runTestGL(caps, FrameLayout.None, false /* twoCanvas */, false /* resizeByComp */); + } + + @Test + public void test11_Frame_Flow_One() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 11 ) { return ; } + final GLCapabilities caps = new GLCapabilities(getGLP()); + runTestGL(caps, FrameLayout.Flow, false /* twoCanvas */, false /* resizeByComp */); + } + + @Test + public void test12_Frame_DblBrd_One() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 12 ) { return ; } + final GLCapabilities caps = new GLCapabilities(getGLP()); + runTestGL(caps, FrameLayout.DoubleBorderCenterSurrounded, false /* twoCanvas */, false /* resizeByComp */); + } + + @Test + public void test13_Frame_Box_One() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 13 ) { return ; } + final GLCapabilities caps = new GLCapabilities(getGLP()); + runTestGL(caps, FrameLayout.Box, false /* twoCanvas */, false /* resizeByComp */); + } + + @Test + public void test14_Frame_Flow_Two() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 14 ) { return ; } + final GLCapabilities caps = new GLCapabilities(getGLP()); + runTestGL(caps, FrameLayout.Flow, true/* twoCanvas */, false /* resizeByComp */); + } + + @Test + public void test15_Frame_DblBrd_Two() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 15 ) { return ; } + final GLCapabilities caps = new GLCapabilities(getGLP()); + runTestGL(caps, FrameLayout.DoubleBorderCenterSurrounded, true/* twoCanvas */, false /* resizeByComp */); + } + + @Test + public void test16_Frame_Box_Two() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 16 ) { return ; } + final GLCapabilities caps = new GLCapabilities(getGLP()); + runTestGL(caps, FrameLayout.Box, true/* twoCanvas */, false /* resizeByComp */); } static int testNum = -1; -- cgit v1.2.3 From 7231fa94ce228b1ea31acba5582e95b0c9f40778 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 25 Sep 2013 02:08:42 +0200 Subject: OSXMisc.c: Fix compilation error w/ java6's jint definition (probably clang as well) Regression of commit 4b5435c68c3f12d62dadb395957362eceacfb25c --- src/nativewindow/native/macosx/OSXmisc.m | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index afe3b3868..fbe37be7d 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -558,10 +558,10 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: FixCALayerLayout0 - * Signature: (JJIIIII)V + * Signature: (JJIII)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_FixCALayerLayout0 - (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint width, jint height, int caLayerQuirks) + (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint width, jint height, jint caLayerQuirks) { if( 0 != caLayerQuirks ) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; -- cgit v1.2.3 From 7ec812589190c0fbc6916cc22d9b74f009244f5c Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 27 Sep 2013 01:53:18 +0200 Subject: DirectDataBufferInt: createBufferedImage(..) use BufferedImage type value instead of component-count, support all int types ; Add type 'BufferedImageInt' preserving the custom image-type, add note about TYPE_CUSTOM - createBufferedImage(..) use BufferedImage type value instead of component-count, support all int types - Support all integer data image-type, hence we need to pass image-type instead of component count (collision). - Also pass 'properties' to allow configuring all BufferedImage parameters (just in case) - Return BufferedImageInt to allow user to query the used image-type, see below. - Add type 'BufferedImageInt' preserving the custom image-type, add note about TYPE_CUSTOM - Simply extends BufferedImage w/ custom image-type, since BufferedImage's type is TYPE_CUSTOM due to our custom storage type (see API doc comment). Unit tests: - Testing all integer image-type's in - TestTiledPrintingGearsSwingAWT - TestTiledPrintingNIOImageSwingAWT - Disable all AA print-hints, all AWT text visible on X11. Probably has a regression on Windows / OSX .. TBD. --- make/scripts/tests.sh | 4 +- .../nativewindow/awt/DirectDataBufferInt.java | 107 ++++++++++++++++----- .../test/junit/jogl/tile/OffscreenPrintable.java | 15 +-- .../test/junit/jogl/tile/OnscreenPrintable.java | 4 +- .../junit/jogl/tile/TestTiledPrintingGearsAWT.java | 11 ++- .../jogl/tile/TestTiledPrintingGearsNewtAWT.java | 11 ++- .../jogl/tile/TestTiledPrintingGearsSwingAWT.java | 30 ++++-- .../jogl/tile/TestTiledPrintingGearsSwingAWT2.java | 2 +- .../tile/TestTiledPrintingNIOImageSwingAWT.java | 41 +++++--- .../test/junit/jogl/tile/TiledPrintingAWTBase.java | 28 +++--- 10 files changed, 176 insertions(+), 77 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 8c58efb3f..442b12672 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -332,7 +332,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering2GL2NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering3GL2AWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* +testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT2 $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsNewtAWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingNIOImageSwingAWT $* @@ -454,7 +454,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.acore.TestPBufferDeadlockAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.x11.TestGLXCallsOnAWT $* -testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPosAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPosAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug675BeansInDesignTimeAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug551AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug572AWT $* diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java index d9c3c3791..1d66d67e7 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java @@ -28,6 +28,7 @@ package com.jogamp.nativewindow.awt; import java.awt.Point; +import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.DataBuffer; @@ -36,6 +37,7 @@ import java.awt.image.SampleModel; import java.awt.image.SinglePixelPackedSampleModel; import java.awt.image.WritableRaster; import java.nio.IntBuffer; +import java.util.Hashtable; import com.jogamp.common.nio.Buffers; @@ -50,40 +52,97 @@ public final class DirectDataBufferInt extends DataBuffer { } } + public static class BufferedImageInt extends BufferedImage { + final int customImageType; + public BufferedImageInt (int customImageType, ColorModel cm, WritableRaster raster, Hashtable properties) { + super(cm, raster, false /* isRasterPremultiplied */, properties); + this.customImageType = customImageType; + } + + /** + * @return one of the custom image-type values {@link BufferedImage#TYPE_INT_ARGB TYPE_INT_ARGB}, + * {@link BufferedImage#TYPE_INT_ARGB_PRE TYPE_INT_ARGB_PRE}, + * {@link BufferedImage#TYPE_INT_RGB TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_BGR TYPE_INT_BGR}. + */ + public int getCustomType() { + return customImageType; + } + + @Override + public String toString() { + return new String("BufferedImageInt@"+Integer.toHexString(hashCode()) + +": custum/internal type = "+customImageType+"/"+getType() + +" "+getColorModel()+" "+getRaster()); + } + } + /** - * Creates a {@link BufferedImage} using an RGB[A] {@link DirectColorModel} - * with an {@link DirectWritableRaster} utilizing a {@link DirectDataBufferInt} as storage. + * Creates a {@link BufferedImageInt} using a {@link DirectColorModel direct color model} in {@link ColorSpace#CS_sRGB sRGB color space}.
          + * It uses a {@link DirectWritableRaster} utilizing {@link DirectDataBufferInt} storage. + *

          + * Note that due to using the custom storage type {@link DirectDataBufferInt}, the resulting + * {@link BufferedImage}'s {@link BufferedImage#getType() image-type} is of {@link BufferedImage#TYPE_CUSTOM TYPE_CUSTOM}. + * We are not able to change this detail, since the AWT image implementation associates the {@link BufferedImage#getType() image-type} + * with a build-in storage-type. + * Use {@link BufferedImageInt#getCustomType()} to retrieve the custom image-type, which will return the imageType + * value passed here. + *

          * * @param width * @param height - * @param numComponents 3 or 4 components, i.e. {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_RGBA}. + * @param imageType one of {@link BufferedImage#TYPE_INT_ARGB TYPE_INT_ARGB}, {@link BufferedImage#TYPE_INT_ARGB_PRE TYPE_INT_ARGB_PRE}, + * {@link BufferedImage#TYPE_INT_RGB TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_BGR TYPE_INT_BGR}. * @param location origin, if null 0/0 is assumed. + * @param properties Hashtable of + * String/Object pairs. Used for {@link BufferedImage#getProperty(String)} etc. * @return */ - public static BufferedImage createBufferedImage(int width, int height, int numComponents, Point location) { - final int[] bandOffsets = new int[numComponents]; - for (int i=0; i < numComponents; i++) { + public static BufferedImageInt createBufferedImage(int width, int height, int imageType, Point location, Hashtable properties) { + final int[] bandOffsets = new int[imageType]; + for (int i=0; i < imageType; i++) { bandOffsets[i] = i; } + final ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB); + final int transferType = DataBuffer.TYPE_INT; final int bpp, rmask, gmask, bmask, amask; - final ColorModel cm; - if( 4 == numComponents ) { - bpp = 32; - rmask = 0x00ff0000; - gmask = 0x0000ff00; - bmask = 0x000000ff; - amask = 0xff000000; - cm = ColorModel.getRGBdefault(); - } else if( 3 == numComponents ) { - bpp = 24; - rmask = 0x00ff0000; - gmask = 0x0000ff00; - bmask = 0x000000ff; - amask = 0x0; - cm = new DirectColorModel(bpp, rmask, gmask, bmask, amask); - } else { - throw new IllegalArgumentException("numComponents must be [3..4], has "+numComponents); + final boolean alphaPreMul; + switch( imageType ) { + case BufferedImage.TYPE_INT_ARGB: + bpp = 32; + rmask = 0x00ff0000; + gmask = 0x0000ff00; + bmask = 0x000000ff; + amask = 0xff000000; + alphaPreMul = false; + break; + case BufferedImage.TYPE_INT_ARGB_PRE: + bpp = 32; + rmask = 0x00ff0000; + gmask = 0x0000ff00; + bmask = 0x000000ff; + amask = 0xff000000; + alphaPreMul = true; + break; + case BufferedImage.TYPE_INT_RGB: + bpp = 24; + rmask = 0x00ff0000; + gmask = 0x0000ff00; + bmask = 0x000000ff; + amask = 0x0; + alphaPreMul = false; + break; + case BufferedImage.TYPE_INT_BGR: + bpp = 24; + rmask = 0x000000ff; + gmask = 0x0000ff00; + bmask = 0x00ff0000; + amask = 0x0; + alphaPreMul = false; + break; + default: + throw new IllegalArgumentException("Unsupported imageType, must be [INT_ARGB, INT_ARGB_PRE, INT_RGB, INT_BGR], has "+imageType); } + final ColorModel colorModel = new DirectColorModel(colorSpace, bpp, rmask, gmask, bmask, amask, alphaPreMul, transferType); final int[] bandMasks; if ( 0 != amask ) { bandMasks = new int[4]; @@ -108,7 +167,7 @@ public final class DirectDataBufferInt extends DataBuffer { // final WritableRaster raster = new SunWritableRaster(sppsm, dataBuffer, location); final WritableRaster raster = new DirectWritableRaster(sppsm, dataBuffer, location); - return new BufferedImage (cm, raster, false /* isRasterPremultiplied */, null /* properties */); + return new BufferedImageInt(imageType, colorModel, raster, properties); } /** Default data bank. */ diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/OffscreenPrintable.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/OffscreenPrintable.java index 1517e0bd1..37ad8c361 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/OffscreenPrintable.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/OffscreenPrintable.java @@ -31,7 +31,6 @@ import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; -import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.awt.print.Paper; @@ -55,6 +54,7 @@ import com.jogamp.nativewindow.awt.DirectDataBufferInt; */ public class OffscreenPrintable extends PrintableBase implements Printable { + public final int imageType; public final String pngFilename; /** @@ -62,11 +62,13 @@ public class OffscreenPrintable extends PrintableBase implements Printable { * @param job * @param printContainer * @param printDPI - * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param imageType AWT BufferedImage type (must be one of the integer types) * @param pngFilename TODO */ - public OffscreenPrintable(PrinterJob job, Container printContainer, int printDPI, int numSamples, String pngFilename) { + public OffscreenPrintable(PrinterJob job, Container printContainer, int printDPI, int numSamples, int imageType, String pngFilename) { super(job, printContainer, printDPI, numSamples); + this.imageType = imageType; this.pngFilename = pngFilename; } @@ -141,13 +143,14 @@ public class OffscreenPrintable extends PrintableBase implements Printable { " -> total "+frameWidthT+ "x" + frameHeightT+ " -> scaled "+frameSWidthT+ "x" + frameSHeightT); - final BufferedImage image = DirectDataBufferInt.createBufferedImage(frameSWidthT, frameSHeightT, 4, null /* location */); + final BufferedImage image = DirectDataBufferInt.createBufferedImage(frameSWidthT, frameSHeightT, imageType, null /* location */, null /* properties */); { + System.err.println("PRINT.offscrn image "+image); final Graphics2D g2d = (Graphics2D) image.getGraphics(); g2d.setClip(0, 0, frameSWidthT, frameSHeightT); g2d.scale(scaleGraphics, scaleGraphics); - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + // g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + // g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); AWTEDTExecutor.singleton.invoke(true, new Runnable() { public void run() { cont.printAll(g2d); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/OnscreenPrintable.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/OnscreenPrintable.java index 273da5c76..a23f7f8c3 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/OnscreenPrintable.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/OnscreenPrintable.java @@ -145,8 +145,8 @@ public class OnscreenPrintable extends PrintableBase implements Printable { System.err.println("PRINT at.pre: "+g2d.getTransform()); g2d.translate(pf.getImageableX(), pf.getImageableY()); g2d.scale(scaleComp72, scaleComp72); // WARNING: Produces rounding artifacts due to diff scale-factor of AWT/GL comps !!! - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + // g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + // g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); AWTEDTExecutor.singleton.invoke(true, new Runnable() { public void run() { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java index 5c200a076..af4b41af2 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java @@ -36,6 +36,7 @@ import java.awt.Label; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.io.BufferedReader; import java.io.IOException; @@ -177,26 +178,26 @@ public class TestTiledPrintingGearsAWT extends TiledPrintingAWTBase { if( !printDone ) { printDone = true; { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 72, 0); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 0); waitUntilPrintJobsIdle(p); } { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 72, 8); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 8); waitUntilPrintJobsIdle(p); } { // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 300, -1); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 300, -1); waitUntilPrintJobsIdle(p); } { // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, true, 300, -1); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 300, -1); waitUntilPrintJobsIdle(p); } if( allow600dpi ) { // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 600, -1); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 600, -1); waitUntilPrintJobsIdle(p); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java index 1a5f8b922..d600c95a8 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java @@ -36,6 +36,7 @@ import java.awt.Label; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.io.BufferedReader; import java.io.IOException; @@ -182,26 +183,26 @@ public class TestTiledPrintingGearsNewtAWT extends TiledPrintingAWTBase { if( !printDone ) { printDone = true; { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 72, 0); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 0); waitUntilPrintJobsIdle(p); } { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 72, 8); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 8); waitUntilPrintJobsIdle(p); } { // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 300, -1); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 300, -1); waitUntilPrintJobsIdle(p); } { // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, true, 300, -1); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 300, -1); waitUntilPrintJobsIdle(p); } if( allow600dpi ) { // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 600, -1); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 600, -1); waitUntilPrintJobsIdle(p); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java index b4f5ad988..cd1ae8657 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java @@ -36,6 +36,7 @@ import java.awt.Frame; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.io.BufferedReader; import java.io.IOException; @@ -216,26 +217,41 @@ public class TestTiledPrintingGearsSwingAWT extends TiledPrintingAWTBase { if( !printDone ) { printDone = true; { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 72, 0); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 0); waitUntilPrintJobsIdle(p); } { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 72, 8); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 8); waitUntilPrintJobsIdle(p); } { - // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 300, -1); + // No AA needed for 150 dpi and greater :) + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1); waitUntilPrintJobsIdle(p); } { - // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, true, 300, -1); + // No AA needed for 150 dpi and greater :) + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1); + waitUntilPrintJobsIdle(p); + } + { + // No AA needed for 150 dpi and greater :) + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB /* offscreen-type */, 150, -1); + waitUntilPrintJobsIdle(p); + } + { + // No AA needed for 150 dpi and greater :) + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_RGB /* offscreen-type */, 150, -1); + waitUntilPrintJobsIdle(p); + } + { + // No AA needed for 150 dpi and greater :) + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_BGR /* offscreen-type */, 150, -1); waitUntilPrintJobsIdle(p); } if( allow600dpi ) { // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, false, 600, -1); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 600, -1); waitUntilPrintJobsIdle(p); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT2.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT2.java index f619ec9a1..a89f4dd6e 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT2.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT2.java @@ -220,7 +220,7 @@ public class TestTiledPrintingGearsSwingAWT2 extends TiledPrintingAWTBase { printDone = true; { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.PORTRAIT, null, false, 150, -1); + final PrintableBase p = doPrintAuto(frame, PageFormat.PORTRAIT, null, -1 /* offscreen-type */, 150, -1); waitUntilPrintJobsIdle(p); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java index a0c50ac4b..3198212b5 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java @@ -36,7 +36,6 @@ import java.awt.Frame; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Label; -import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; @@ -125,8 +124,8 @@ public class TestTiledPrintingNIOImageSwingAWT extends UITestCase { final Graphics2D g2d = (Graphics2D) image.getGraphics(); g2d.setClip(0, 0, image.getWidth(), image.getHeight()); g2d.scale(scaleComp72, scaleComp72); - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + // g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + // g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // frame.paintAll(g2d); final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(frame, 1.0/scaleComp72, 1.0/scaleComp72, 0); @@ -230,21 +229,39 @@ public class TestTiledPrintingNIOImageSwingAWT extends UITestCase { Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glJPanel1, true)); Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glJPanel2, true)); - // paint offscreen: array 72dpi + // paint offscreen: array 72dpi ARGB { final BufferedImage image = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_INT_ARGB); - printOffscreenToFile(image, frame, caps, 0, "array_072dpi"); + printOffscreenToFile(image, frame, caps, 0, "array_072dpi_argb"); } - // paint offscreen: NIO 72dpi + // paint offscreen: NIO 72dpi ARGB { - final BufferedImage image = DirectDataBufferInt.createBufferedImage(frame.getWidth(), frame.getHeight(), 4, null /* location */); - printOffscreenToFile(image, frame, caps, 1, "newio_072dpi"); + final BufferedImage image = DirectDataBufferInt.createBufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_INT_ARGB, null /* location */, null /* properties */); + printOffscreenToFile(image, frame, caps, 1, "newio_072dpi_argb"); } - // paint offscreen: NIO 300dpi + // paint offscreen: NIO 150dpi ARGB { - final int scale = (int) ( 300.0 / 72.0 + 0.5 ); - final BufferedImage image = DirectDataBufferInt.createBufferedImage(frame.getWidth()*scale, frame.getHeight()*scale, 4, null /* location */); - printOffscreenToFile(image, frame, caps, 2, "newio_300dpi"); + final int scale = (int) ( 150.0 / 72.0 + 0.5 ); + final BufferedImage image = DirectDataBufferInt.createBufferedImage(frame.getWidth()*scale, frame.getHeight()*scale, BufferedImage.TYPE_INT_ARGB, null /* location */, null /* properties */); + printOffscreenToFile(image, frame, caps, 2, "newio_150dpi_argb"); + } + // paint offscreen: NIO 150dpi ARGB_PRE + { + final int scale = (int) ( 150.0 / 72.0 + 0.5 ); + final BufferedImage image = DirectDataBufferInt.createBufferedImage(frame.getWidth()*scale, frame.getHeight()*scale, BufferedImage.TYPE_INT_ARGB_PRE, null /* location */, null /* properties */); + printOffscreenToFile(image, frame, caps, 2, "newio_150dpi_argbp"); + } + // paint offscreen: NIO 150dpi RGB + { + final int scale = (int) ( 150.0 / 72.0 + 0.5 ); + final BufferedImage image = DirectDataBufferInt.createBufferedImage(frame.getWidth()*scale, frame.getHeight()*scale, BufferedImage.TYPE_INT_RGB, null /* location */, null /* properties */); + printOffscreenToFile(image, frame, caps, 2, "newio_150dpi_rgb"); + } + // paint offscreen: NIO 150dpi BGR + { + final int scale = (int) ( 150.0 / 72.0 + 0.5 ); + final BufferedImage image = DirectDataBufferInt.createBufferedImage(frame.getWidth()*scale, frame.getHeight()*scale, BufferedImage.TYPE_INT_BGR, null /* location */, null /* properties */); + printOffscreenToFile(image, frame, caps, 2, "newio_150dpi_bgr"); } Assert.assertNotNull(frame); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java index 199a667a1..8393cf978 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java @@ -70,11 +70,11 @@ public abstract class TiledPrintingAWTBase extends UITestCase { * @param cont * @param pOrientation * @param paper - * @param offscrn TODO + * @param offscrnImageType if < 0 onscreen, otherwise integer BufferedImage type * @param dpi * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples */ - public PrintableBase doPrintAuto(Container cont, int pOrientation, Paper paper, boolean offscrn, int dpi, int numSamples) { + public PrintableBase doPrintAuto(Container cont, int pOrientation, Paper paper, int offscrnImageType, int dpi, int numSamples) { lock.lock(); try { final PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); @@ -91,31 +91,29 @@ public abstract class TiledPrintingAWTBase extends UITestCase { StreamPrintServiceFactory[] factories = PrinterJob.lookupStreamPrintServices(pdfMimeType); if (factories.length > 0) { - final String fname = getPrintFilename(offscrn, dpi, numSamples, "pdf"); + final String fname = getPrintFilename(offscrnImageType, dpi, numSamples, "pdf"); System.err.println("doPrint: dpi "+dpi+", "+fname); FileOutputStream outstream; try { outstream = new FileOutputStream(fname); - return doPrintAutoImpl(cont, pj, factories[0].getPrintService(outstream), pOrientation, paper, offscrn, dpi, numSamples); + return doPrintAutoImpl(cont, pj, factories[0].getPrintService(outstream), pOrientation, paper, offscrnImageType, dpi, numSamples); } catch (FileNotFoundException e) { Assert.assertNull("Unexpected exception", e); } - return null; } System.err.println("No PDF"); factories = PrinterJob.lookupStreamPrintServices(psMimeType); if (factories.length > 0) { - final String fname = getPrintFilename(offscrn, dpi, numSamples, "ps"); + final String fname = getPrintFilename(offscrnImageType, dpi, numSamples, "ps"); System.err.println("doPrint: dpi "+dpi+", "+fname); FileOutputStream outstream; try { outstream = new FileOutputStream(fname); - return doPrintAutoImpl(cont, pj, factories[0].getPrintService(outstream), pOrientation, paper, offscrn, dpi, numSamples); + return doPrintAutoImpl(cont, pj, factories[0].getPrintService(outstream), pOrientation, paper, offscrnImageType, dpi, numSamples); } catch (FileNotFoundException e) { Assert.assertNull("Unexpected exception", e); } - return null; } System.err.println("No PS"); return null; @@ -123,15 +121,15 @@ public abstract class TiledPrintingAWTBase extends UITestCase { lock.unlock(); } } - private String getPrintFilename(boolean offscrn, int dpi, int numSamples, String suffix) { + private String getPrintFilename(int offscrnImageType, int dpi, int numSamples, String suffix) { final int maxSimpleTestNameLen = getMaxTestNameLen()+getClass().getSimpleName().length()+1; final String simpleTestName = getSimpleTestName("."); - final String onoffscrn = offscrn ? "offscrn" : "on_scrn"; + final String onoffscrn = 0 > offscrnImageType ? "on_screen" : "offscrn_"+offscrnImageType; return String.format("%-"+maxSimpleTestNameLen+"s-n%04d-%s-dpi%03d-aa%d.%s", simpleTestName, printCount, onoffscrn, dpi, numSamples, suffix).replace(' ', '_'); } private PrintableBase doPrintAutoImpl(Container cont, PrinterJob job, StreamPrintService ps, int pOrientation, Paper paper, - boolean offscrn, int dpi, int numSamples) { + int offscrnImageType, int dpi, int numSamples) { try { PageFormat pageFormat = job.defaultPage(); if( null != paper ) { @@ -143,8 +141,12 @@ public abstract class TiledPrintingAWTBase extends UITestCase { } pageFormat.setOrientation(pOrientation); // PageFormat.LANDSCAPE or PageFormat.PORTRAIT job.setPrintService(ps); - final PrintableBase printable = offscrn ? new OffscreenPrintable(job, cont, dpi, numSamples, getPrintFilename(offscrn, dpi, numSamples, "png")) : - new OnscreenPrintable(job, cont, dpi, numSamples); + final PrintableBase printable; + if( 0 < offscrnImageType ) { + printable = new OffscreenPrintable(job, cont, dpi, numSamples, offscrnImageType, getPrintFilename(offscrnImageType, dpi, numSamples, "png")); + } else { + printable = new OnscreenPrintable(job, cont, dpi, numSamples); + } printable.job.setPrintable(printable, pageFormat); doPrintImpl(printable); return printable; -- cgit v1.2.3 From 9a8f9b9f7e6148b60b6f0f4326df8d213774284c Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 27 Sep 2013 13:23:39 +0200 Subject: Bug 816: Fix JAWTWindow's getLocationOnScreenNonBlocking(); Derive CALayer position from AWT component's location on screen. Track fixedFrame size of root CALayer; Add Split layout to unit test, add [manual] Applet tests. - Fix JAWTWindow's getLocationOnScreenNonBlocking() Skip JRootPane while traversing up to root Container. JRootPane would duplicate the top-level container's offset (Window insets). - Derive CALayer position from AWT component's location on screen. Add Split layout to unit test, add [manual] Applet tests. AWT >= 7u40: - AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. - Use getLocationOnScreenNonBlocking() to get location-on-screen w/o insets. - Native code: flip origin AWT < 7u40 still uses fixed position 0/0 for root and sub layer. - Track fixedFrame size of root CALayer - MyCALayer: - Override layoutSublayers to validate root and sub-layer pos/size - Override setFrame to use fixedFrame, if set (similar to MyNSOpenGLLayer) - Add Split layout to unit test, add [manual] Applet tests. - Thx to 'jimthev' and 'Manu' for providing Applet unit tests --- jnlp-files/jogl-applet-bug816_glcanvas01.html | 32 +++ jnlp-files/jogl-applet-bug816_glcanvas02.html | 32 +++ jnlp-files/jogl-test-applets.html | 11 + make/scripts/tests.sh | 4 +- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 46 ++-- .../classes/jogamp/nativewindow/awt/AWTMisc.java | 15 +- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 46 +++- .../jogamp/nativewindow/macosx/OSXUtil.java | 12 +- src/nativewindow/native/macosx/OSXmisc.m | 237 +++++++++++++-------- .../junit/jogl/awt/TestBug816OSXCALayerPosAWT.java | 98 +++++++-- .../jogl/demos/es2/awt/Bug816AppletGLCanvas01.java | 134 ++++++++++++ .../jogl/demos/es2/awt/Bug816AppletGLCanvas02.java | 85 ++++++++ 12 files changed, 611 insertions(+), 141 deletions(-) create mode 100644 jnlp-files/jogl-applet-bug816_glcanvas01.html create mode 100644 jnlp-files/jogl-applet-bug816_glcanvas02.html create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/Bug816AppletGLCanvas01.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/Bug816AppletGLCanvas02.java (limited to 'src/nativewindow') diff --git a/jnlp-files/jogl-applet-bug816_glcanvas01.html b/jnlp-files/jogl-applet-bug816_glcanvas01.html new file mode 100644 index 000000000..c460ff12c --- /dev/null +++ b/jnlp-files/jogl-applet-bug816_glcanvas01.html @@ -0,0 +1,32 @@ + + + +Bug816 OSX CALayer Pos - Custom Bounds + + + +

          +Bug816 OSX CALayer Pos - Custom Bounds +

          + +

          + + + + + + Sorry, no Java support detected. + + + +

          + + diff --git a/jnlp-files/jogl-applet-bug816_glcanvas02.html b/jnlp-files/jogl-applet-bug816_glcanvas02.html new file mode 100644 index 000000000..850b9752a --- /dev/null +++ b/jnlp-files/jogl-applet-bug816_glcanvas02.html @@ -0,0 +1,32 @@ + + + +Bug816 OSX CALayer Pos - Box Layout + + + +

          +Bug816 OSX CALayer Pos - Box Layout +

          + +

          + + + + + + Sorry, no Java support detected. + + + +

          + + diff --git a/jnlp-files/jogl-test-applets.html b/jnlp-files/jogl-test-applets.html index 132945e4e..69fb70eca 100644 --- a/jnlp-files/jogl-test-applets.html +++ b/jnlp-files/jogl-test-applets.html @@ -198,6 +198,17 @@ Click on the Launch link to actually launch the demo.
          +

          +Misc tests: +

          +

          + diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 442b12672..8c58efb3f 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -332,7 +332,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering2GL2NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering3GL2AWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsAWT $* -testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT2 $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsNewtAWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingNIOImageSwingAWT $* @@ -454,7 +454,7 @@ testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestPBufferDeadlockAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.x11.TestGLXCallsOnAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPosAWT $* +testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPosAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug675BeansInDesignTimeAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug551AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug572AWT $* diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index a71356b1c..576fcf4ed 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -46,6 +46,7 @@ import java.awt.Container; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.applet.Applet; + import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.CapabilitiesImmutable; @@ -60,6 +61,7 @@ import javax.media.nativewindow.util.InsetsImmutable; import javax.media.nativewindow.util.Point; import javax.media.nativewindow.util.Rectangle; import javax.media.nativewindow.util.RectangleImmutable; +import javax.swing.JRootPane; import jogamp.nativewindow.SurfaceUpdatedHelper; import jogamp.nativewindow.jawt.JAWT; @@ -227,9 +229,6 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if( !isOffscreenLayerSurfaceEnabled() ) { throw new NativeWindowException("Not an offscreen layer surface"); } - if(DEBUG) { - System.err.println("JAWTWindow.attachSurfaceHandle: "+toHexString(layerHandle) + ", bounds "+bounds); - } attachSurfaceLayerImpl(layerHandle); offscreenSurfaceLayer = layerHandle; component.repaint(); @@ -248,14 +247,14 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, * Call this method if any parent or ancestor's layout has been changed, * which could affects the layout of this surface. *

          - * @see #isOffscreenLayerSurfaceEnabled() + * @see #isOffscreenLayerSurfaceEnabled() * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false */ - protected void layoutSurfaceLayerImpl(long layerHandle, int width, int height) {} + protected void layoutSurfaceLayerImpl(long layerHandle) {} private final void layoutSurfaceLayerIfEnabled() throws NativeWindowException { if( isOffscreenLayerSurfaceEnabled() && 0 != offscreenSurfaceLayer ) { - layoutSurfaceLayerImpl(offscreenSurfaceLayer, getWidth(), getHeight()); + layoutSurfaceLayerImpl(offscreenSurfaceLayer); } } @@ -533,7 +532,11 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, System.err.println("Warning: JAWT Lock hold, but not the AWT tree lock: "+this); Thread.dumpStack(); } - return getLocationOnScreenNonBlocking(storage, component); + if( null == storage ) { + storage = new Point(); + } + getLocationOnScreenNonBlocking(storage, component); + return storage; } java.awt.Point awtLOS = component.getLocationOnScreen(); if(null!=storage) { @@ -569,21 +572,28 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } protected abstract Point getLocationOnScreenNativeImpl(int x, int y); - protected static Point getLocationOnScreenNonBlocking(Point storage, Component comp) { - int x = 0; - int y = 0; + protected static Component getLocationOnScreenNonBlocking(Point storage, Component comp) { + Component last = null; while(null != comp) { - x += comp.getX(); - y += comp.getY(); + final int dx = comp.getX(); + final int dy = comp.getY(); + if( ! ( comp instanceof JRootPane ) ) { + if( DEBUG ) { + System.err.print("LOS: "+storage+" + "+comp.getClass().getSimpleName()+"["+dx+"/"+dy+"] -> "); + } + storage.translate(dx, dy); + if( DEBUG ) { + System.err.println(storage); + } + last = comp; + } else if( DEBUG ) { + System.err.println("LOS: ignore "+comp.getClass().getSimpleName()+"["+dx+"/"+dy+"]"); + } comp = comp.getParent(); } - if(null!=storage) { - storage.translate(x, y); - return storage; - } - return new Point(x, y); + return last; } - + @Override public boolean hasFocus() { return component.hasFocus(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java index f38e7ea2b..e326b65bd 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java +++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java @@ -28,13 +28,16 @@ package jogamp.nativewindow.awt; import java.awt.FocusTraversalPolicy; +import java.awt.Insets; import java.awt.Window; import java.awt.Component; import java.awt.Container; import java.awt.Frame; + +import javax.swing.JComponent; import javax.swing.JFrame; +import javax.swing.JRootPane; import javax.swing.WindowConstants; - import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.WindowClosingProtocol; import javax.swing.MenuSelectionManager; @@ -68,6 +71,16 @@ public class AWTMisc { } return (Container) c; } + + public static Insets getInsets(Component c) { + if( c instanceof Window ) { + return ((Window)c).getInsets(); + } + if( c instanceof JComponent ) { + return ((JComponent)c).getInsets(); + } + return null; + } public static interface ComponentAction { /** diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 666f895f4..6d08078b6 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -40,6 +40,7 @@ package jogamp.nativewindow.jawt.macosx; +import java.awt.Component; import java.nio.Buffer; import java.security.AccessController; import java.security.PrivilegedAction; @@ -49,11 +50,11 @@ import javax.media.nativewindow.Capabilities; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.MutableSurface; -import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.util.Point; import com.jogamp.nativewindow.awt.JAWTWindow; +import jogamp.nativewindow.awt.AWTMisc; import jogamp.nativewindow.jawt.JAWT; import jogamp.nativewindow.jawt.JAWTFactory; import jogamp.nativewindow.jawt.JAWTUtil; @@ -105,19 +106,42 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { @Override protected void attachSurfaceLayerImpl(final long layerHandle) { OSXUtil.RunOnMainThread(false, new Runnable() { - public void run() { - OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, getWidth(), getHeight(), JAWTUtil.getOSXCALayerQuirks()); + public void run() { + // AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. + // Determine p0: components location on screen w/o insets. + // CALayer position will be determined in native code. + final Point p0 = new Point(); + final Component outterComp = getLocationOnScreenNonBlocking(p0, component); + final java.awt.Insets ins = AWTMisc.getInsets(outterComp); + if(null != ins) { + p0.translate(-ins.left, -ins.top); + } + if( DEBUG ) { + final java.awt.Point wP0 = outterComp.getLocationOnScreen(); + System.err.println("JAWTWindow.attachSurfaceHandleImpl: "+toHexString(layerHandle) + ", wP0 "+wP0+"[ins "+ins+"], p0 "+p0+", bounds "+bounds); + } + OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, p0.getX(), p0.getY(), getWidth(), getHeight(), JAWTUtil.getOSXCALayerQuirks()); } } ); } @Override - protected void layoutSurfaceLayerImpl(long layerHandle, int width, int height) { + protected void layoutSurfaceLayerImpl(long layerHandle) { final int caLayerQuirks = JAWTUtil.getOSXCALayerQuirks(); if( 0 != caLayerQuirks ) { - if(DEBUG) { - System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", "+width+"x"+height+", caLayerQuirks "+caLayerQuirks+"; "+this); + // AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. + // Determine p0: components location on screen w/o insets. + // CALayer position will be determined in native code. + final Point p0 = new Point(); + final Component outterComp = getLocationOnScreenNonBlocking(p0, component); + final java.awt.Insets ins = AWTMisc.getInsets(outterComp); + if( null != ins ) { + p0.translate(-ins.left, -ins.top); } - OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, width, height, caLayerQuirks); + if( DEBUG ) { + final java.awt.Point wP0 = outterComp.getLocationOnScreen(); + System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", wP0 "+wP0+"[ins "+ins+"], p0 "+p0+", bounds "+bounds); + } + OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, p0.getX(), p0.getY(), getWidth(), getHeight(), caLayerQuirks); } } @@ -312,8 +336,12 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { *

          */ @Override - public Point getLocationOnScreen(Point storage) { - return getLocationOnScreenNonBlocking(storage, component); + public Point getLocationOnScreen(Point storage) { + if( null == storage ) { + storage = new Point(); + } + getLocationOnScreenNonBlocking(storage, component); + return storage; } protected Point getLocationOnScreenNativeImpl(final int x0, final int y0) { return null; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index de24a76db..2112131ed 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -163,14 +163,14 @@ public class OSXUtil implements ToolkitProperties { * @see #CreateCALayer(int, int) * @see #RemoveCASublayer(long, long, boolean) */ - public static void AddCASublayer(final long rootCALayer, final long subCALayer, final int width, final int height, final int caLayerQuirks) { + public static void AddCASublayer(final long rootCALayer, final long subCALayer, final int x, final int y, final int width, final int height, final int caLayerQuirks) { if(0==rootCALayer || 0==subCALayer) { throw new IllegalArgumentException("rootCALayer 0x"+Long.toHexString(rootCALayer)+", subCALayer 0x"+Long.toHexString(subCALayer)); } if(DEBUG) { System.err.println("OSXUtil.AttachCALayer: caLayerQuirks "+caLayerQuirks+", 0x"+Long.toHexString(subCALayer)+" - "+Thread.currentThread().getName()); } - AddCASublayer0(rootCALayer, subCALayer, width, height, caLayerQuirks); + AddCASublayer0(rootCALayer, subCALayer, x, y, width, height, caLayerQuirks); } /** @@ -190,11 +190,11 @@ public class OSXUtil implements ToolkitProperties { * @param height the expected height * @param caLayerQuirks TODO */ - public static void FixCALayerLayout(final long rootCALayer, final long subCALayer, final int width, final int height, final int caLayerQuirks) { + public static void FixCALayerLayout(final long rootCALayer, final long subCALayer, final int x, final int y, final int width, final int height, final int caLayerQuirks) { if( 0==rootCALayer && 0==subCALayer ) { return; } - FixCALayerLayout0(rootCALayer, subCALayer, width, height, caLayerQuirks); + FixCALayerLayout0(rootCALayer, subCALayer, x, y, width, height, caLayerQuirks); } /** @@ -357,8 +357,8 @@ public class OSXUtil implements ToolkitProperties { private static native long GetNSView0(long nsWindow); private static native long GetNSWindow0(long nsView); private static native long CreateCALayer0(int width, int height); - private static native void AddCASublayer0(long rootCALayer, long subCALayer, int width, int height, int caLayerQuirks); - private static native void FixCALayerLayout0(long rootCALayer, long subCALayer, int width, int height, int caLayerQuirks); + private static native void AddCASublayer0(long rootCALayer, long subCALayer, int x, int y, int width, int height, int caLayerQuirks); + private static native void FixCALayerLayout0(long rootCALayer, long subCALayer, int x, int y, int width, int height, int caLayerQuirks); private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); private static native void RunOnMainThread0(Runnable runnable); diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index fbe37be7d..fa40c871f 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -333,6 +333,9 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 */ @interface MyCALayer: CALayer { +@private + BOOL fixedFrameSet; + CGRect fixedFrame; } - (id)init; #ifdef DBG_LIFECYCLE @@ -341,6 +344,9 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 - (void)dealloc; #endif - (id)actionForKey:(NSString *)key ; +- (void)layoutSublayers; +- (void)setFrame:(CGRect) frame; +- (void)fixCALayerLayout: (CALayer*) subLayer x:(jint)x y:(jint)y width:(jint)width height:(jint)height caLayerQuirks:(jint)caLayerQuirks force:(jboolean) force; @end @@ -350,6 +356,8 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 { DBG_PRINT("MyCALayer::init.0\n"); MyCALayer * o = [super init]; + o->fixedFrameSet = 0; + o->fixedFrame = CGRectMake(0, 0, 0, 0); DBG_PRINT("MyCALayer::init.X: new %p\n", o); return o; } @@ -390,6 +398,127 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 // return [super actionForKey: key]; } +- (void)layoutSublayers +{ + if( fixedFrameSet ) { + NSArray* subs = [self sublayers]; + if( NULL != subs ) { + CGRect rFrame = [self frame]; + if( !CGRectEqualToRect(fixedFrame, rFrame) ) { + #ifdef VERBOSE + DBG_PRINT("CALayer::layoutSublayers.0: Root %p frame %lf/%lf %lfx%lf -> %lf/%lf %lfx%lf\n", + self, + rFrame.origin.x, rFrame.origin.y, rFrame.size.width, rFrame.size.height, + fixedFrame.origin.x, fixedFrame.origin.y, fixedFrame.size.width, fixedFrame.size.height); + #endif + [super setFrame: fixedFrame]; + } + NSUInteger i = 0; + for(i=0; i<[subs count]; i++) { + CALayer* sub = [subs objectAtIndex: i]; + CGRect sFrame = [sub frame]; + CGRect sFrame2 = CGRectMake(0, 0, fixedFrame.size.width, fixedFrame.size.height); + if( !CGRectEqualToRect(sFrame2, sFrame) ) { + #ifdef VERBOSE + DBG_PRINT("CALayer::layoutSublayers.1: Sub[%d] %p frame %lf/%lf %lfx%lf -> %lf/%lf %lfx%lf\n", + (int)i, sub, + sFrame.origin.x, sFrame.origin.y, sFrame.size.width, sFrame.size.height, + sFrame2.origin.x, sFrame2.origin.y, sFrame2.size.width, sFrame2.size.height); + #endif + [sub setFrame: sFrame2]; + } + #ifdef VERBOSE + DBG_PRINT("CALayer::layoutSublayers.X: Root %p . Sub[%d] %p : frame r: %lf/%lf %lfx%lf . s: %lf/%lf %lfx%lf\n", + self, (int)i, sub, + rFrame.origin.x, rFrame.origin.y, rFrame.size.width, rFrame.size.height, + sFrame.origin.x, sFrame.origin.y, sFrame.size.width, sFrame.size.height); + #endif + } + } + } else { + [super layoutSublayers]; + } +} + +- (void) setFrame:(CGRect) frame +{ + if( fixedFrameSet ) { + [super setFrame: fixedFrame]; + } else { + [super setFrame: frame]; + } +} + +- (void)fixCALayerLayout: (CALayer*) subLayer x:(jint)x y:(jint)y width:(jint)width height:(jint)height caLayerQuirks:(jint)caLayerQuirks force:(jboolean) force +{ + { + CALayer* superLayer = [self superlayer]; + CGRect superFrame = [superLayer frame]; + CGRect lFrame = [self frame]; + int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lFrame.origin.x!=0 || lFrame.origin.y!=0 ); + int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lFrame.size.width!=width || lFrame.size.height!=height ); + if( !posQuirk ) { + // Use root layer position, sub-layer will be on 0/0, + // Given AWT position is location on screen w/o insets and top/left origin! + fixedFrame.origin.x = x; + fixedFrame.origin.y = superFrame.size.height - height - y; // AWT's position top/left -> bottom/left + posQuirk |= 8; + } else { + // Buggy super layer position, always use 0/0 + fixedFrame.origin.x = 0; + fixedFrame.origin.y = 0; + } + if( !sizeQuirk ) { + fixedFrame.size.width = lFrame.size.width; + fixedFrame.size.height = lFrame.size.height; + } else { + fixedFrame.size.width = width; + fixedFrame.size.height = height; + } + DBG_PRINT("CALayer::FixCALayerLayout0.0: Quirks [%d, pos %d, size %d], Super %p frame %lf/%lf %lfx%lf, Root %p frame %lf/%lf %lfx%lf, usr %d/%d %dx%d -> %lf/%lf %lfx%lf\n", + caLayerQuirks, posQuirk, sizeQuirk, + superLayer, superFrame.origin.x, superFrame.origin.y, superFrame.size.width, superFrame.size.height, + self, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height, + x, y, width, height, fixedFrame.origin.x, fixedFrame.origin.y, fixedFrame.size.width, fixedFrame.size.height); + if( posQuirk || sizeQuirk ) { + fixedFrameSet = 1; + [super setFrame: fixedFrame]; + } + } + if( NULL != subLayer ) { + CGRect lFrame = [subLayer frame]; + int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lFrame.size.width!=width || lFrame.size.height!=height ); + CGFloat _x, _y, _w, _h; + int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lFrame.origin.x!=0 || lFrame.origin.y!=0 ); + // Sub rel. to used root layer + _x = 0; + _y = 0; + posQuirk |= 8; + if( !sizeQuirk ) { + _w = lFrame.size.width; + _h = lFrame.size.height; + } else { + _w = width; + _h = height; + } + DBG_PRINT("CALayer::FixCALayerLayout1.0: Quirks [%d, pos %d, size %d], SubL %p frame %lf/%lf %lfx%lf, usr %dx%d -> %lf/%lf %lfx%lf\n", + caLayerQuirks, posQuirk, sizeQuirk, subLayer, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height, + width, height, _x, _y, _w, _h); + if( force || posQuirk || sizeQuirk ) { + lFrame.origin.x = _x; + lFrame.origin.y = _y; + lFrame.size.width = _w; + lFrame.size.height = _h; + if( [subLayer conformsToProtocol:@protocol(NWDedicatedFrame)] ) { + CALayer * subLayerDS = (CALayer *) subLayer; + [subLayerDS setDedicatedFrame: lFrame quirks: caLayerQuirks]; + } else { + [subLayer setFrame: lFrame]; + } + } + } +} + @end /* @@ -409,98 +538,32 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0 if(0 == height) { height = 32; } // initial dummy size ! - CGRect lRect = [layer frame]; - lRect.origin.x = 0; - lRect.origin.y = 0; - lRect.size.width = width; - lRect.size.height = height; - [layer setFrame: lRect]; + CGRect lFrame = [layer frame]; + lFrame.origin.x = 0; + lFrame.origin.y = 0; + lFrame.size.width = width; + lFrame.size.height = height; + [layer setFrame: lFrame]; // no animations for add/remove/swap sublayers etc // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition] [layer removeAllAnimations]; // [layer addAnimation:nil forKey:kCATransition]; [layer setAutoresizingMask: (kCALayerWidthSizable|kCALayerHeightSizable)]; [layer setNeedsDisplayOnBoundsChange: YES]; - DBG_PRINT("CALayer::CreateCALayer.1: root %p %lf/%lf %lfx%lf\n", layer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height); + DBG_PRINT("CALayer::CreateCALayer.1: root %p %lf/%lf %lfx%lf\n", layer, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height); [pool release]; DBG_PRINT("CALayer::CreateCALayer.X: root %p (refcnt %d)\n", layer, (int)[layer retainCount]); return (jlong) ((intptr_t) layer); } -static void FixCALayerLayout0(MyCALayer* rootLayer, CALayer* subLayer, jint width, jint height, jint caLayerQuirks, jboolean force) { - if( NULL != rootLayer ) { - CGRect lRect = [rootLayer frame]; - int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lRect.origin.x!=0 || lRect.origin.y!=0 ); - int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lRect.size.width!=width || lRect.size.height!=height ); - CGFloat _x, _y, _w, _h; - // force root -> 0/0 - _x = 0; - _y = 0; - posQuirk |= 8; - if( sizeQuirk ) { - _w = width; - _h = height; - } else { - _w = lRect.size.width; - _h = lRect.size.height; - } - DBG_PRINT("CALayer::FixCALayerLayout0.0: Quirks [%d, pos %d, size %d], Root %p frame %lf/%lf %lfx%lf, usr %dx%d -> %lf/%lf %lfx%lf\n", - caLayerQuirks, posQuirk, sizeQuirk, rootLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, - width, height, _x, _y, _w, _h); - if( posQuirk || sizeQuirk ) { - lRect.origin.x = _x; - lRect.origin.y = _y; - lRect.size.width = _w; - lRect.size.height = _h; - [rootLayer setFrame: lRect]; - } - } - if( NULL != subLayer ) { - CGRect lRect = [subLayer frame]; - int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lRect.size.width!=width || lRect.size.height!=height ); - CGFloat _x, _y, _w, _h; - int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lRect.origin.x!=0 || lRect.origin.y!=0 ); - if( posQuirk ) { - _x = 0; - _y = 0; - } else { - // sub always rel to root - _x = lRect.origin.x; - _y = lRect.origin.y; - } - if( sizeQuirk ) { - _w = width; - _h = height; - } else { - _w = lRect.size.width; - _h = lRect.size.height; - } - DBG_PRINT("CALayer::FixCALayerLayout1.0: Quirks [%d, pos %d, size %d], SubL %p frame %lf/%lf %lfx%lf, usr %dx%d -> %lf/%lf %lfx%lf\n", - caLayerQuirks, posQuirk, sizeQuirk, subLayer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, - width, height, _x, _y, _w, _h); - if( force || posQuirk || sizeQuirk ) { - lRect.origin.x = _x; - lRect.origin.y = _y; - lRect.size.width = _w; - lRect.size.height = _h; - if( [subLayer conformsToProtocol:@protocol(NWDedicatedFrame)] ) { - CALayer * subLayerDS = (CALayer *) subLayer; - [subLayerDS setDedicatedFrame: lRect quirks: caLayerQuirks]; - } else { - [subLayer setFrame: lRect]; - } - } - } -} - /* * Class: Java_jogamp_nativewindow_macosx_OSXUtil * Method: AddCASublayer0 * Signature: (JJIIIII)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 - (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint width, jint height, jint caLayerQuirks) + (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint x, jint y, jint width, jint height, jint caLayerQuirks) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); @@ -513,23 +576,10 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 [subLayer retain]; // Pairs w/ RemoveCASublayer CGRect lRectRoot = [rootLayer frame]; - int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ); - int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ); - - DBG_PRINT("CALayer::AddCASublayer0.0: Quirks [%d, pos %d, size %d], Root %p (refcnt %d), Sub %p (refcnt %d), frame0: %lf/%lf %lfx%lf\n", - caLayerQuirks, posQuirk, sizeQuirk, rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount], + DBG_PRINT("CALayer::AddCASublayer0.0: Quirks %d, Root %p (refcnt %d), Sub %p (refcnt %d), frame0: %lf/%lf %lfx%lf\n", + caLayerQuirks, rootLayer, (int)[rootLayer retainCount], subLayer, (int)[subLayer retainCount], lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height); - CGPoint origin = lRectRoot.origin; // save - // force root to 0/0 - lRectRoot.origin.x = 0; - lRectRoot.origin.y = 0; - [rootLayer setFrame: lRectRoot]; - - // simple 1:1 layout rel. to root-layer ! - if( !posQuirk ) { - lRectRoot.origin = origin; - } [subLayer setFrame:lRectRoot]; [rootLayer addSublayer:subLayer]; @@ -545,7 +595,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 [subLayer setNeedsDisplayOnBoundsChange: YES]; if( 0 != caLayerQuirks ) { - FixCALayerLayout0(rootLayer, subLayer, width, height, caLayerQuirks, JNI_TRUE); + [rootLayer fixCALayerLayout: subLayer x:x y:y width:width height:height caLayerQuirks:caLayerQuirks force:JNI_TRUE]; } [CATransaction commit]; @@ -561,17 +611,20 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 * Signature: (JJIII)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_FixCALayerLayout0 - (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint width, jint height, jint caLayerQuirks) + (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint x, jint y, jint width, jint height, jint caLayerQuirks) { if( 0 != caLayerQuirks ) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; MyCALayer* rootLayer = (MyCALayer*) ((intptr_t) rootCALayer); + if( NULL == rootLayer ) { + NativewindowCommon_throwNewRuntimeException(env, "Argument \"rootLayer\" is null"); + } CALayer* subLayer = (CALayer*) ((intptr_t) subCALayer); [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; - FixCALayerLayout0(rootLayer, subLayer, width, height, caLayerQuirks, JNI_FALSE); + [rootLayer fixCALayerLayout: subLayer x:x y:y width:width height:height caLayerQuirks:caLayerQuirks force:JNI_FALSE]; [CATransaction commit]; diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPosAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPosAWT.java index 48340aa75..358e97622 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPosAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPosAWT.java @@ -33,8 +33,13 @@ import javax.media.opengl.*; import com.jogamp.opengl.util.Animator; import javax.media.opengl.awt.GLCanvas; +import javax.swing.BoundedRangeModel; import javax.swing.BoxLayout; import javax.swing.JFrame; +import javax.swing.JScrollBar; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.ScrollPaneConstants; import com.jogamp.common.util.awt.AWTEDTExecutor; import com.jogamp.newt.event.awt.AWTWindowAdapter; @@ -68,9 +73,15 @@ import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; +/** + * Bug 816: OSX CALayer Positioning Bug. + *

          + * Diff. OSX CALayer positioning w/ java6, [7uxx..7u40[, and >= 7u40 + *

          + */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestBug816OSXCALayerPosAWT extends UITestCase { - public enum FrameLayout { None, Flow, DoubleBorderCenterSurrounded, Box }; + public enum FrameLayout { None, Flow, DoubleBorderCenterSurrounded, Box, Split }; static long duration = 1600; // ms static int width, height; @@ -113,7 +124,7 @@ public class TestBug816OSXCALayerPosAWT extends UITestCase { comp2.setPreferredSize(new_sz2); comp2.setSize(new_sz2); } - if( null != frame ) { + if( null != frame ) { frame.pack(); } } } ); @@ -206,6 +217,39 @@ public class TestBug816OSXCALayerPosAWT extends UITestCase { framePane.add(c); } break; + case Split: { + Dimension sbDim = new Dimension(16, 16); + JScrollPane vsp = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + { + JScrollBar vsb = vsp.getVerticalScrollBar(); + vsb.setPreferredSize(sbDim); + BoundedRangeModel model = vsb.getModel(); + model.setMinimum(0); + model.setMaximum(100); + model.setValue(50); + model.setExtent(1); + vsb.setEnabled(true); + } + JScrollPane hsp = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); + { + JScrollBar hsb = hsp.getHorizontalScrollBar(); + hsb.setPreferredSize(sbDim); + BoundedRangeModel model = hsb.getModel(); + model.setMinimum(0); + model.setMaximum(100); + model.setValue(50); + model.setExtent(1); + hsb.setEnabled(true); + } + JSplitPane horizontalSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, + twoCanvas ? glCanvas2 : vsp, glCanvas1 ); + horizontalSplitPane.setResizeWeight(0.5); + JSplitPane verticalSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, + true, horizontalSplitPane, hsp); + verticalSplitPane.setResizeWeight(0.5); + framePane.add(verticalSplitPane); + } + break; } final GearsES2 demo1 = new GearsES2(swapInterval); glCanvas1.addGLEventListener(demo1); @@ -329,26 +373,40 @@ public class TestBug816OSXCALayerPosAWT extends UITestCase { } @Test - public void test04_Compo_Flow_Two() throws InterruptedException, InvocationTargetException { + public void test04_Compo_Split_One() throws InterruptedException, InvocationTargetException { if( testNum != -1 && testNum != 4 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); + runTestGL(caps, FrameLayout.Split, false /* twoCanvas */, true /* resizeByComp */); + } + + @Test + public void test05_Compo_Flow_Two() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 5 ) { return ; } + final GLCapabilities caps = new GLCapabilities(getGLP()); runTestGL(caps, FrameLayout.Flow, true/* twoCanvas */, true /* resizeByComp */); } @Test - public void test05_Compo_DblBrd_Two() throws InterruptedException, InvocationTargetException { - if( testNum != -1 && testNum != 5 ) { return ; } + public void test06_Compo_DblBrd_Two() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 6 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); runTestGL(caps, FrameLayout.DoubleBorderCenterSurrounded, true/* twoCanvas */, true /* resizeByComp */); } @Test - public void test06_Compo_Box_Two() throws InterruptedException, InvocationTargetException { - if( testNum != -1 && testNum != 6 ) { return ; } + public void test07_Compo_Box_Two() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 7 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); runTestGL(caps, FrameLayout.Box, true/* twoCanvas */, true /* resizeByComp */); } + @Test + public void test08_Compo_Split_Two() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 8 ) { return ; } + final GLCapabilities caps = new GLCapabilities(getGLP()); + runTestGL(caps, FrameLayout.Split, true/* twoCanvas */, true /* resizeByComp */); + } + @Test public void test10_Frame_None_One() throws InterruptedException, InvocationTargetException { if( testNum != -1 && testNum != 10 ) { return ; } @@ -378,26 +436,40 @@ public class TestBug816OSXCALayerPosAWT extends UITestCase { } @Test - public void test14_Frame_Flow_Two() throws InterruptedException, InvocationTargetException { - if( testNum != -1 && testNum != 14 ) { return ; } + public void test14_Frame_Split_One() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 14) { return ; } + final GLCapabilities caps = new GLCapabilities(getGLP()); + runTestGL(caps, FrameLayout.Split, false /* twoCanvas */, false /* resizeByComp */); + } + + @Test + public void test15_Frame_Flow_Two() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 15 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); runTestGL(caps, FrameLayout.Flow, true/* twoCanvas */, false /* resizeByComp */); } @Test - public void test15_Frame_DblBrd_Two() throws InterruptedException, InvocationTargetException { - if( testNum != -1 && testNum != 15 ) { return ; } + public void test16_Frame_DblBrd_Two() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 16 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); runTestGL(caps, FrameLayout.DoubleBorderCenterSurrounded, true/* twoCanvas */, false /* resizeByComp */); } @Test - public void test16_Frame_Box_Two() throws InterruptedException, InvocationTargetException { - if( testNum != -1 && testNum != 16 ) { return ; } + public void test17_Frame_Box_Two() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 17 ) { return ; } final GLCapabilities caps = new GLCapabilities(getGLP()); runTestGL(caps, FrameLayout.Box, true/* twoCanvas */, false /* resizeByComp */); } + @Test + public void test18_Frame_Split_Two() throws InterruptedException, InvocationTargetException { + if( testNum != -1 && testNum != 18 ) { return ; } + final GLCapabilities caps = new GLCapabilities(getGLP()); + runTestGL(caps, FrameLayout.Split, true/* twoCanvas */, false /* resizeByComp */); + } + static int testNum = -1; public static void main(String args[]) { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/Bug816AppletGLCanvas01.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/Bug816AppletGLCanvas01.java new file mode 100644 index 000000000..175b053d1 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/Bug816AppletGLCanvas01.java @@ -0,0 +1,134 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.test.junit.jogl.demos.es2.awt; + +import java.applet.Applet; +import java.awt.Color; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.media.opengl.GL; +import javax.media.opengl.GLAutoDrawable; +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLCapabilitiesImmutable; +import javax.media.opengl.GLEventListener; +import javax.media.opengl.GLProfile; +import javax.media.opengl.awt.GLCanvas; +import javax.swing.JFrame; +import javax.swing.JPanel; + +/** + * Bug 816: OSX CALayer Positioning Bug. + *

          + * Diff. OSX CALayer positioning w/ java6, [7uxx..7u40[, and >= 7u40 + *

          + *

          + * Test simply positions a GLCanvas via setBounds(..) within it's Applet. + *

          + */ +@SuppressWarnings("serial") +public class Bug816AppletGLCanvas01 extends Applet implements GLEventListener { + + public Bug816AppletGLCanvas01() { + } + + public static JFrame frame; + public static JPanel appletHolder; + public static boolean isApplet = true; + + static public void main(String args[]) { + Applet myApplet = null; + isApplet = false; + + myApplet = new Bug816AppletGLCanvas01(); + appletStarter(myApplet, "Bug861AppletGLCanvasTest01", 800, 600); + } + + static public void appletStarter(final Applet des, String frameName, int width, int height) { + appletHolder = new JPanel(); + if (frame != null) { + frame.dispose(); + frame = null; + } + frame = new JFrame(frameName); + frame.setVisible(false); + frame.getContentPane().add(appletHolder); + + appletHolder.setLayout(null); + des.setBounds(0, 0, width, height); + appletHolder.add(des); + + frame.setVisible(true); + int frameBorderSize = appletHolder.getLocationOnScreen().x - frame.getLocationOnScreen().x; + int titleBarHeight = appletHolder.getLocationOnScreen().y - frame.getLocationOnScreen().y; + int frameWidth = width + 2 * frameBorderSize; + int frameHeight = height + titleBarHeight + frameBorderSize; + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setSize(frameWidth, frameHeight); + frame.setVisible(true); + des.init(); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); + } + + public void init() { + initOpenGLAWT(); + } + + public void initOpenGLAWT() { + setBackground(Color.gray); + setLayout(null); + + GLProfile glp = GLProfile.getDefault(); + GLCapabilities caps = new GLCapabilities(glp); + GLCanvas canvas = new GLCanvas((GLCapabilitiesImmutable) caps); + canvas.setBounds(50, 50, 200, 450); + canvas.addGLEventListener(this); + add(canvas); + } + + public void init(GLAutoDrawable gLAutoDrawable) { + GL gl = gLAutoDrawable.getGL(); + gl.glClearColor(1.0f, 0.0f, 0.0f, 1.0f); + gl.glClear(GL.GL_COLOR_BUFFER_BIT); + gLAutoDrawable.swapBuffers(); + } + + public void dispose(GLAutoDrawable glad) { + } + + public void display(GLAutoDrawable glad) { + } + + public void reshape(GLAutoDrawable glad, int i, int i1, int i2, int i3) { + } + +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/Bug816AppletGLCanvas02.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/Bug816AppletGLCanvas02.java new file mode 100644 index 000000000..9ae0a2bbd --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/Bug816AppletGLCanvas02.java @@ -0,0 +1,85 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.test.junit.jogl.demos.es2.awt; + +import java.applet.Applet; +import java.util.ArrayList; +import java.util.List; + +import javax.media.opengl.GLAnimatorControl; +import javax.media.opengl.awt.GLCanvas; +import javax.swing.BoxLayout; + +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.util.Animator; + +/** + * Bug 816: OSX CALayer Positioning Bug. + *

          + * Diff. OSX CALayer positioning w/ java6, [7uxx..7u40[, and >= 7u40 + *

          + *

          + * Test uses a box layout within the Applet. + *

          + */ +@SuppressWarnings("serial") +public class Bug816AppletGLCanvas02 extends Applet { + private List animators = new ArrayList(2); + + @Override + public void init() { + System.err.println("GearsApplet: init() - begin"); + new BoxLayout(this, BoxLayout.X_AXIS); + setSize(600, 300); + add(createCanvas()); + add(createCanvas()); + System.err.println("GearsApplet: init() - end"); + } + + private GLCanvas createCanvas() { + GLCanvas canvas = new GLCanvas(); + canvas.addGLEventListener(new GearsES2(1)); + canvas.setSize(300, 300); + animators.add(new Animator(canvas)); + return canvas; + } + + @Override + public void start() { + for (GLAnimatorControl control : animators) { + control.start(); + } + } + + @Override + public void stop() { + for (GLAnimatorControl control : animators) { + control.stop(); + } + } +} -- cgit v1.2.3 From 3abff83dbc0a99c8d227788c9dddbe59cd15b9ba Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 27 Sep 2013 15:31:17 +0200 Subject: Fix Bug 816: JAWTWindow.getLocationOnScreenNonBlocking(..) shall use JRootPane for last position offset; AWTMisc.getInsets(..) add special JRootPane case. Please note that we use JAWTWindow.getLocationOnScreenNonBlocking(..) to determine the location on the screen 'only' b/c we cannot allow AWT to aquire the tree-lock! The latter would be the case if using AWT's 'getLocationOnScreen()'. If anybody has a more reliable implementation to achieve the same .. please provide your patch! The following fix has been performed to fix the last issue w/ vZome. - JAWTWindow.getLocationOnScreenNonBlocking(..) shall use JRootPane for last position offset - w/ vZome, the frame's position was 0/0 (invalid), instead JRootPane's position is good. Use JRootPane's position and stop traversing here (LW top-level). - AWTMisc.getInsets(..) add special JRootPane case. + * Exception is JRootPane. + * Return it's parent's Window component's insets if available, + * otherwise return JRootPane's insets.
          + * This is due to experience that some JRootPane's + * do not expose valid insets value. - --- make/scripts/tests.sh | 4 ++-- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 24 ++++++++++++---------- .../classes/jogamp/nativewindow/awt/AWTMisc.java | 18 ++++++++++++++++ 3 files changed, 33 insertions(+), 13 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 442b12672..8c58efb3f 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -332,7 +332,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering2GL2NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering3GL2AWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsAWT $* -testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT2 $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsNewtAWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingNIOImageSwingAWT $* @@ -454,7 +454,7 @@ testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestPBufferDeadlockAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.x11.TestGLXCallsOnAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPosAWT $* +testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPosAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug675BeansInDesignTimeAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug551AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug572AWT $* diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 576fcf4ed..5b5df7f68 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -64,6 +64,7 @@ import javax.media.nativewindow.util.RectangleImmutable; import javax.swing.JRootPane; import jogamp.nativewindow.SurfaceUpdatedHelper; +import jogamp.nativewindow.awt.AWTMisc; import jogamp.nativewindow.jawt.JAWT; import jogamp.nativewindow.jawt.JAWTUtil; import jogamp.nativewindow.jawt.JAWT_Rectangle; @@ -577,17 +578,18 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, while(null != comp) { final int dx = comp.getX(); final int dy = comp.getY(); - if( ! ( comp instanceof JRootPane ) ) { - if( DEBUG ) { - System.err.print("LOS: "+storage+" + "+comp.getClass().getSimpleName()+"["+dx+"/"+dy+"] -> "); - } - storage.translate(dx, dy); - if( DEBUG ) { - System.err.println(storage); - } - last = comp; - } else if( DEBUG ) { - System.err.println("LOS: ignore "+comp.getClass().getSimpleName()+"["+dx+"/"+dy+"]"); + if( DEBUG ) { + final java.awt.Insets ins = AWTMisc.getInsets(comp); + System.err.print("LOS: "+storage+" + "+comp.getClass().getName()+"["+dx+"/"+dy+", vis "+comp.isVisible()+", ins "+ins+"] -> "); + } + storage.translate(dx, dy); + if( DEBUG ) { + System.err.println(storage); + } + last = comp; + if( comp instanceof JRootPane ) { + // LW JRootPane is considered a top-level component! + break; } comp = comp.getParent(); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java index e326b65bd..611c13a22 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java +++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java @@ -72,10 +72,28 @@ public class AWTMisc { return (Container) c; } + /** + * Return insets of the component w/o traversing up to parent, + * i.e. trying Window and JComponent. + *

          + * Exception is JRootPane. + * Return it's parent's Window component's insets if available, + * otherwise return JRootPane's insets.
          + * This is due to experience that some JRootPane's + * do not expose valid insets value. + *

          + */ public static Insets getInsets(Component c) { if( c instanceof Window ) { return ((Window)c).getInsets(); } + if( c instanceof JRootPane ) { + final Window w = getWindow(c); + if( null != w ) { + return w.getInsets(); + } + return ((JRootPane)c).getInsets(); + } if( c instanceof JComponent ) { return ((JComponent)c).getInsets(); } -- cgit v1.2.3 From a2a057406ff5d21499860e8fef6ba88f07d9bf95 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 28 Sep 2013 00:20:50 +0200 Subject: Bug 816: Clarify JAWT_OSX_CALAYER_QUIRK_* semantics, add JAWT_OSX_CALAYER_QUIRK_LAYOUT --- .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 49 ++++++++++++++++++---- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 2 + .../native/macosx/NativeWindowProtocols.h | 7 ++++ src/nativewindow/native/macosx/OSXmisc.m | 15 +++---- 4 files changed, 58 insertions(+), 15 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index b663f90b7..b20007d53 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -113,11 +113,12 @@ public class JAWTUtil { /** * CALayer size needs to be set using the AWT component size. *

          - * As of today, we have to overwrite the CALayer size - * w/ the AWT component one since programmatic resize leads to differences. + * AWT's super-calayer, i.e. the AWT's own component CALayer, + * does not layout our root-calayer in respect to this component's + * position and size, at least when resizing programmatically. *

          *

          - * Hence this flag is always enabled. + * As of today, this flag is enabled for all known AWT versions. *

          *

          * Sync w/ NativeWindowProtocols.h @@ -128,17 +129,18 @@ public class JAWTUtil { /** * CALayer position needs to be set to zero. *

          - * Normally we have to set the root-calayer's position to 0/0 - * and leave client-calayer's position in it's desired place. - * With pre AWT 1.7.0_40, the client-calayer's position has to - * be set to zero as well. + * AWT's super-calayer, i.e. the AWT's own component CALayer, + * has a broken layout and needs it's sub-layers to be located at position 0/0. + *

          + *

          + * See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7172187. *

          *

          * Further more a re-layout seems to be required in this case, * i.e. a programmatic forced resize +1 and it's inverted resize -1. *

          *

          - * Hence this flag is enabled w/ AWT < 1.7.0_40. + * This flag is enabled w/ AWT < 1.7.0_40. *

          *

          * Sync w/ NativeWindowProtocols.h @@ -146,6 +148,34 @@ public class JAWTUtil { */ public static final int JAWT_OSX_CALAYER_QUIRK_POSITION = 1 << 1; + /** + * CALayer position needs to be derived from AWT position + * in relation to super CALayer. + *

          + * AWT's super-calayer, i.e. the AWT's own component CALayer, + * does not layout our root-calayer in respect to this component's + * position and size, at least when resizing programmatically. + *

          + *

          + * CALayer position has origin 0/0 at bottom/left, + * where AWT component has origin 0/0 at top/left. + *

          + *

          + * The super-calayer bounds exclude the frame's heavyweight border/insets. + *

          + *

          + * This flags also sets {@link #JAWT_OSX_CALAYER_QUIRK_SIZE}, + * i.e. they are related. + *

          + *

          + * As of today, this flag is enabled for w/ AWT >= 1.7.0_40. + *

          + *

          + * Sync w/ NativeWindowProtocols.h + *

          + */ + public static final int JAWT_OSX_CALAYER_QUIRK_LAYOUT = 1 << 2; + /** * Returns bitfield of required JAWT OSX CALayer quirks to mediate AWT impl. bugs. *

          @@ -157,6 +187,7 @@ public class JAWTUtil { *

            *
          • {@link #JAWT_OSX_CALAYER_QUIRK_SIZE} (always)
          • *
          • {@link #JAWT_OSX_CALAYER_QUIRK_POSITION} if JVM < 1.7.0_40
          • + *
          • {@link #JAWT_OSX_CALAYER_QUIRK_LAYOUT} if JVM >= 1.7.0_40
          • *
          *

          */ @@ -171,6 +202,8 @@ public class JAWTUtil { final int c = Platform.JAVA_VERSION_NUMBER.compareTo(Platform.Version17); if( c < 0 || c == 0 && Platform.JAVA_VERSION_UPDATE < 40 ) { res |= JAWT_OSX_CALAYER_QUIRK_POSITION; + } else { + res |= JAWT_OSX_CALAYER_QUIRK_LAYOUT; } } return res; diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 6d08078b6..0d81274ca 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -110,6 +110,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { // AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. // Determine p0: components location on screen w/o insets. // CALayer position will be determined in native code. + // See: {@link JAWTWindow#JAWT_OSX_CALAYER_QUIRK_LAYOUT} final Point p0 = new Point(); final Component outterComp = getLocationOnScreenNonBlocking(p0, component); final java.awt.Insets ins = AWTMisc.getInsets(outterComp); @@ -131,6 +132,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { // AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. // Determine p0: components location on screen w/o insets. // CALayer position will be determined in native code. + // See: {@link JAWTWindow#JAWT_OSX_CALAYER_QUIRK_LAYOUT} final Point p0 = new Point(); final Component outterComp = getLocationOnScreenNonBlocking(p0, component); final java.awt.Insets ins = AWTMisc.getInsets(outterComp); diff --git a/src/nativewindow/native/macosx/NativeWindowProtocols.h b/src/nativewindow/native/macosx/NativeWindowProtocols.h index 73c8e65c5..98e864f8b 100644 --- a/src/nativewindow/native/macosx/NativeWindowProtocols.h +++ b/src/nativewindow/native/macosx/NativeWindowProtocols.h @@ -41,6 +41,13 @@ */ #define NW_DEDICATEDFRAME_QUIRK_POSITION ( 1 << 1 ) +/** + * CALayer position needs to be derived from AWT position. + * in relation to super CALayer. + * See detailed description in JAWTUtil.java and sync w/ changed. + */ +#define NW_DEDICATEDFRAME_QUIRK_LAYOUT ( 1 << 2 ) + #import @protocol NWDedicatedFrame diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index fa40c871f..e3844455a 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -451,13 +451,14 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 - (void)fixCALayerLayout: (CALayer*) subLayer x:(jint)x y:(jint)y width:(jint)width height:(jint)height caLayerQuirks:(jint)caLayerQuirks force:(jboolean) force { + int loutQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_LAYOUT & caLayerQuirks ); { CALayer* superLayer = [self superlayer]; CGRect superFrame = [superLayer frame]; CGRect lFrame = [self frame]; int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lFrame.origin.x!=0 || lFrame.origin.y!=0 ); int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lFrame.size.width!=width || lFrame.size.height!=height ); - if( !posQuirk ) { + if( !posQuirk || loutQuirk ) { // Use root layer position, sub-layer will be on 0/0, // Given AWT position is location on screen w/o insets and top/left origin! fixedFrame.origin.x = x; @@ -475,12 +476,12 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 fixedFrame.size.width = width; fixedFrame.size.height = height; } - DBG_PRINT("CALayer::FixCALayerLayout0.0: Quirks [%d, pos %d, size %d], Super %p frame %lf/%lf %lfx%lf, Root %p frame %lf/%lf %lfx%lf, usr %d/%d %dx%d -> %lf/%lf %lfx%lf\n", - caLayerQuirks, posQuirk, sizeQuirk, + DBG_PRINT("CALayer::FixCALayerLayout0.0: Quirks [%d, pos %d, size %d, lout %d], Super %p frame %lf/%lf %lfx%lf, Root %p frame %lf/%lf %lfx%lf, usr %d/%d %dx%d -> %lf/%lf %lfx%lf\n", + caLayerQuirks, posQuirk, sizeQuirk, loutQuirk, superLayer, superFrame.origin.x, superFrame.origin.y, superFrame.size.width, superFrame.size.height, self, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height, x, y, width, height, fixedFrame.origin.x, fixedFrame.origin.y, fixedFrame.size.width, fixedFrame.size.height); - if( posQuirk || sizeQuirk ) { + if( posQuirk || sizeQuirk || loutQuirk ) { fixedFrameSet = 1; [super setFrame: fixedFrame]; } @@ -501,10 +502,10 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 _w = width; _h = height; } - DBG_PRINT("CALayer::FixCALayerLayout1.0: Quirks [%d, pos %d, size %d], SubL %p frame %lf/%lf %lfx%lf, usr %dx%d -> %lf/%lf %lfx%lf\n", - caLayerQuirks, posQuirk, sizeQuirk, subLayer, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height, + DBG_PRINT("CALayer::FixCALayerLayout1.0: Quirks [%d, pos %d, size %d, lout %d], SubL %p frame %lf/%lf %lfx%lf, usr %dx%d -> %lf/%lf %lfx%lf\n", + caLayerQuirks, posQuirk, sizeQuirk, loutQuirk, subLayer, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height, width, height, _x, _y, _w, _h); - if( force || posQuirk || sizeQuirk ) { + if( force || posQuirk || sizeQuirk || loutQuirk ) { lFrame.origin.x = _x; lFrame.origin.y = _y; lFrame.size.width = _w; -- cgit v1.2.3 From 7f7275834922b9c30aec6520dc5c5f20939a49d8 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 3 Oct 2013 15:19:29 +0200 Subject: Bug 816 (OSX CALayer pos): Fix location on 'inner CALayer' calculation 'inner CALayer' is the outter AWT Window client space (content). +++ Pseudo-Code: p0 = c.locationOnScreen(); p0 -= c.getOutterComp.getPos(); p0 -= c.getOutterComp.getInsets(); Where 'locationOnScreen()' is: p0 = 0/0; while( null != c ) { p0 += c.getPos(); } +++ JAWTWindow.getLocationOnScreenNonBlocking(..) validated against AWT's Component.getLocationOnScreen() - OK for all use-cases. (Validation enabled w/ DEBUG) All unit tests manually validated on OSX 10.7 w/ jdk7u40. --- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 16 +++++---- .../classes/jogamp/nativewindow/awt/AWTMisc.java | 6 ++-- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 42 +++++++++++++++------- 3 files changed, 43 insertions(+), 21 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 5b5df7f68..53eb985b2 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -61,7 +61,6 @@ import javax.media.nativewindow.util.InsetsImmutable; import javax.media.nativewindow.util.Point; import javax.media.nativewindow.util.Rectangle; import javax.media.nativewindow.util.RectangleImmutable; -import javax.swing.JRootPane; import jogamp.nativewindow.SurfaceUpdatedHelper; import jogamp.nativewindow.awt.AWTMisc; @@ -574,23 +573,26 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected abstract Point getLocationOnScreenNativeImpl(int x, int y); protected static Component getLocationOnScreenNonBlocking(Point storage, Component comp) { + final java.awt.Insets insets = new java.awt.Insets(0, 0, 0, 0); // DEBUG Component last = null; while(null != comp) { final int dx = comp.getX(); final int dy = comp.getY(); if( DEBUG ) { - final java.awt.Insets ins = AWTMisc.getInsets(comp); - System.err.print("LOS: "+storage+" + "+comp.getClass().getName()+"["+dx+"/"+dy+", vis "+comp.isVisible()+", ins "+ins+"] -> "); + final java.awt.Insets ins = AWTMisc.getInsets(comp, false); + if( null != ins ) { + insets.bottom += ins.bottom; + insets.top += ins.top; + insets.left += ins.left; + insets.right += ins.right; + } + System.err.print("LOS: "+storage+" + "+comp.getClass().getName()+"["+dx+"/"+dy+", vis "+comp.isVisible()+", ins "+ins+" -> "+insets+"] -> "); } storage.translate(dx, dy); if( DEBUG ) { System.err.println(storage); } last = comp; - if( comp instanceof JRootPane ) { - // LW JRootPane is considered a top-level component! - break; - } comp = comp.getParent(); } return last; diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java index 611c13a22..23c48d20e 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java +++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java @@ -82,8 +82,10 @@ public class AWTMisc { * This is due to experience that some JRootPane's * do not expose valid insets value. *

          + * @param topLevelOnly if true only returns insets of top-level components, i.e. Window and JRootPanel, + * otherwise for JComponent as well. */ - public static Insets getInsets(Component c) { + public static Insets getInsets(Component c, boolean topLevelOnly) { if( c instanceof Window ) { return ((Window)c).getInsets(); } @@ -94,7 +96,7 @@ public class AWTMisc { } return ((JRootPane)c).getInsets(); } - if( c instanceof JComponent ) { + if( !topLevelOnly && c instanceof JComponent ) { return ((JComponent)c).getInsets(); } return null; diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 0d81274ca..833e6cd24 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -113,15 +113,24 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { // See: {@link JAWTWindow#JAWT_OSX_CALAYER_QUIRK_LAYOUT} final Point p0 = new Point(); final Component outterComp = getLocationOnScreenNonBlocking(p0, component); - final java.awt.Insets ins = AWTMisc.getInsets(outterComp); - if(null != ins) { - p0.translate(-ins.left, -ins.top); + final java.awt.Insets outterInsets = AWTMisc.getInsets(outterComp, true); + final Point p1 = (Point)p0.cloneMutable(); + p1.translate(-outterComp.getX(), -outterComp.getY()); + if( null != outterInsets ) { + p1.translate(-outterInsets.left, -outterInsets.top); } + if( DEBUG ) { - final java.awt.Point wP0 = outterComp.getLocationOnScreen(); - System.err.println("JAWTWindow.attachSurfaceHandleImpl: "+toHexString(layerHandle) + ", wP0 "+wP0+"[ins "+ins+"], p0 "+p0+", bounds "+bounds); + final java.awt.Point pA0 = component.getLocationOnScreen(); + final Point pA1 = new Point(pA0.x, pA0.y); + pA1.translate(-outterComp.getX(), -outterComp.getY()); + if( null != outterInsets ) { + pA1.translate(-outterInsets.left, -outterInsets.top); + } + System.err.println("JAWTWindow.attachSurfaceLayerImpl: "+toHexString(layerHandle) + ", [ins "+outterInsets+"], pA "+pA0+" -> "+pA1+ + ", p0 "+p0+" -> "+p1+", bounds "+bounds); } - OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, p0.getX(), p0.getY(), getWidth(), getHeight(), JAWTUtil.getOSXCALayerQuirks()); + OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, p1.getX(), p1.getY(), getWidth(), getHeight(), JAWTUtil.getOSXCALayerQuirks()); } } ); } @@ -135,15 +144,24 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { // See: {@link JAWTWindow#JAWT_OSX_CALAYER_QUIRK_LAYOUT} final Point p0 = new Point(); final Component outterComp = getLocationOnScreenNonBlocking(p0, component); - final java.awt.Insets ins = AWTMisc.getInsets(outterComp); - if( null != ins ) { - p0.translate(-ins.left, -ins.top); + final java.awt.Insets outterInsets = AWTMisc.getInsets(outterComp, true); + final Point p1 = (Point)p0.cloneMutable(); + p1.translate(-outterComp.getX(), -outterComp.getY()); + if( null != outterInsets ) { + p1.translate(-outterInsets.left, -outterInsets.top); } + if( DEBUG ) { - final java.awt.Point wP0 = outterComp.getLocationOnScreen(); - System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", wP0 "+wP0+"[ins "+ins+"], p0 "+p0+", bounds "+bounds); + final java.awt.Point pA0 = component.getLocationOnScreen(); + final Point pA1 = new Point(pA0.x, pA0.y); + pA1.translate(-outterComp.getX(), -outterComp.getY()); + if( null != outterInsets ) { + pA1.translate(-outterInsets.left, -outterInsets.top); + } + System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", [ins "+outterInsets+"], pA "+pA0+" -> "+pA1+ + ", p0 "+p0+" -> "+p1+", bounds "+bounds); } - OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, p0.getX(), p0.getY(), getWidth(), getHeight(), caLayerQuirks); + OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, p1.getX(), p1.getY(), getWidth(), getHeight(), caLayerQuirks); } } -- cgit v1.2.3 From e9ce2246c947cc357fef993003008fe4c6a0495f Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 3 Oct 2013 15:35:09 +0200 Subject: Bug 816 (OSX CALayer pos): Add detailed description (pseudo code) to JAWTUtil.JAWT_OSX_CALAYER_QUIRK_LAYOUT --- .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 20 +++++++++++++++++++- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 4 ++-- 2 files changed, 21 insertions(+), 3 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index b20007d53..844b17469 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -152,7 +152,7 @@ public class JAWTUtil { * CALayer position needs to be derived from AWT position * in relation to super CALayer. *

          - * AWT's super-calayer, i.e. the AWT's own component CALayer, + * AWT's super-calayer, i.e. the AWT top-container's CALayer, * does not layout our root-calayer in respect to this component's * position and size, at least when resizing programmatically. *

          @@ -164,6 +164,24 @@ public class JAWTUtil { * The super-calayer bounds exclude the frame's heavyweight border/insets. *

          *

          + * The super-calayer lies within the AWT top-container client space (content). + *

          + *

          + * Component's location in super-calayer: + *

          +      p0 = c.locationOnScreen();
          +      p0 -= c.getOutterComp.getPos();
          +      p0 -= c.getOutterComp.getInsets();
          +   * 
          + * Where 'locationOnScreen()' is: + *
          +     p0 = 0/0;
          +     while( null != c ) {
          +       p0 += c.getPos();
          +     }
          +   * 
          + *

          + *

          * This flags also sets {@link #JAWT_OSX_CALAYER_QUIRK_SIZE}, * i.e. they are related. *

          diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 833e6cd24..2eff1bc09 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -110,7 +110,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { // AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. // Determine p0: components location on screen w/o insets. // CALayer position will be determined in native code. - // See: {@link JAWTWindow#JAWT_OSX_CALAYER_QUIRK_LAYOUT} + // See detailed description in {@link JAWTUtil#JAWT_OSX_CALAYER_QUIRK_LAYOUT} final Point p0 = new Point(); final Component outterComp = getLocationOnScreenNonBlocking(p0, component); final java.awt.Insets outterInsets = AWTMisc.getInsets(outterComp, true); @@ -141,7 +141,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { // AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. // Determine p0: components location on screen w/o insets. // CALayer position will be determined in native code. - // See: {@link JAWTWindow#JAWT_OSX_CALAYER_QUIRK_LAYOUT} + // See detailed description in {@link JAWTUtil#JAWT_OSX_CALAYER_QUIRK_LAYOUT} final Point p0 = new Point(); final Component outterComp = getLocationOnScreenNonBlocking(p0, component); final java.awt.Insets outterInsets = AWTMisc.getInsets(outterComp, true); -- cgit v1.2.3 From 3b02a219b1b9e446e87df1beb7da4266f74824fa Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 5 Oct 2013 13:44:43 +0200 Subject: Bug 729: OSX CALayer shall honor the Component's visibility state A once visible CALayer (GLCanvas) must be able to become invisible w/o destruction, e.g. as required by CardLayout's switching cards. See unit test for Bug 532: 'TestAWTCardLayoutAnimatorStartStopBug532' Out native 'fixCALayerLayout(..)' takes the visible state as tracked by JAWTWindow's ComponentListener and sets our CALayer (root and sub) hidden state accordingly. Now MacOSXJAWTWindow's layoutSurfaceLayerImpl(..) always calls down to 'fixCALayerLayout(..)' due to update the visibility state. --- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 21 ++++++---- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 47 +++++++++++----------- .../jogamp/nativewindow/macosx/OSXUtil.java | 7 ++-- src/nativewindow/native/macosx/OSXmisc.m | 22 +++++++--- 4 files changed, 57 insertions(+), 40 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 53eb985b2..d9f36901b 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -115,23 +115,28 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, this.isApplet = false; this.offscreenSurfaceLayer = 0; this.component.addComponentListener(new ComponentListener() { + private boolean visible = component.isVisible(); @Override public void componentResized(ComponentEvent e) { - layoutSurfaceLayerIfEnabled(); + layoutSurfaceLayerIfEnabled(visible); } @Override public void componentMoved(ComponentEvent e) { - layoutSurfaceLayerIfEnabled(); + layoutSurfaceLayerIfEnabled(visible); } @Override public void componentShown(ComponentEvent e) { - layoutSurfaceLayerIfEnabled(); + visible = true; + layoutSurfaceLayerIfEnabled(visible); } @Override - public void componentHidden(ComponentEvent e) { } + public void componentHidden(ComponentEvent e) { + visible = false; + layoutSurfaceLayerIfEnabled(visible); + } }); } @@ -247,14 +252,14 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, * Call this method if any parent or ancestor's layout has been changed, * which could affects the layout of this surface. *

          - * @see #isOffscreenLayerSurfaceEnabled() + * @see #isOffscreenLayerSurfaceEnabled() * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false */ - protected void layoutSurfaceLayerImpl(long layerHandle) {} + protected void layoutSurfaceLayerImpl(long layerHandle, boolean visible) {} - private final void layoutSurfaceLayerIfEnabled() throws NativeWindowException { + private final void layoutSurfaceLayerIfEnabled(boolean visible) throws NativeWindowException { if( isOffscreenLayerSurfaceEnabled() && 0 != offscreenSurfaceLayer ) { - layoutSurfaceLayerImpl(offscreenSurfaceLayer); + layoutSurfaceLayerImpl(offscreenSurfaceLayer, visible); } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 2eff1bc09..b712f6a1a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -135,34 +135,33 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } @Override - protected void layoutSurfaceLayerImpl(long layerHandle) { + protected void layoutSurfaceLayerImpl(long layerHandle, boolean visible) { final int caLayerQuirks = JAWTUtil.getOSXCALayerQuirks(); - if( 0 != caLayerQuirks ) { - // AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. - // Determine p0: components location on screen w/o insets. - // CALayer position will be determined in native code. - // See detailed description in {@link JAWTUtil#JAWT_OSX_CALAYER_QUIRK_LAYOUT} - final Point p0 = new Point(); - final Component outterComp = getLocationOnScreenNonBlocking(p0, component); - final java.awt.Insets outterInsets = AWTMisc.getInsets(outterComp, true); - final Point p1 = (Point)p0.cloneMutable(); - p1.translate(-outterComp.getX(), -outterComp.getY()); + // AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. + // Determine p0: components location on screen w/o insets. + // CALayer position will be determined in native code. + // See detailed description in {@link JAWTUtil#JAWT_OSX_CALAYER_QUIRK_LAYOUT} + final Point p0 = new Point(); + final Component outterComp = getLocationOnScreenNonBlocking(p0, component); + final java.awt.Insets outterInsets = AWTMisc.getInsets(outterComp, true); + final Point p1 = (Point)p0.cloneMutable(); + p1.translate(-outterComp.getX(), -outterComp.getY()); + if( null != outterInsets ) { + p1.translate(-outterInsets.left, -outterInsets.top); + } + + if( DEBUG ) { + final java.awt.Point pA0 = component.getLocationOnScreen(); + final Point pA1 = new Point(pA0.x, pA0.y); + pA1.translate(-outterComp.getX(), -outterComp.getY()); if( null != outterInsets ) { - p1.translate(-outterInsets.left, -outterInsets.top); - } - - if( DEBUG ) { - final java.awt.Point pA0 = component.getLocationOnScreen(); - final Point pA1 = new Point(pA0.x, pA0.y); - pA1.translate(-outterComp.getX(), -outterComp.getY()); - if( null != outterInsets ) { - pA1.translate(-outterInsets.left, -outterInsets.top); - } - System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", [ins "+outterInsets+"], pA "+pA0+" -> "+pA1+ - ", p0 "+p0+" -> "+p1+", bounds "+bounds); + pA1.translate(-outterInsets.left, -outterInsets.top); } - OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, p1.getX(), p1.getY(), getWidth(), getHeight(), caLayerQuirks); + System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", quirks "+caLayerQuirks+", visible "+visible+ + ", [ins "+outterInsets+"], pA "+pA0+" -> "+pA1+ + ", p0 "+p0+" -> "+p1+", bounds "+bounds); } + OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, visible, p1.getX(), p1.getY(), getWidth(), getHeight(), caLayerQuirks); } @Override diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 2112131ed..b27affa7e 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -186,15 +186,16 @@ public class OSXUtil implements ToolkitProperties { * * @param rootCALayer the root surface layer, maybe null. * @param subCALayer the client surface layer, maybe null. + * @param visible TODO * @param width the expected width * @param height the expected height * @param caLayerQuirks TODO */ - public static void FixCALayerLayout(final long rootCALayer, final long subCALayer, final int x, final int y, final int width, final int height, final int caLayerQuirks) { + public static void FixCALayerLayout(final long rootCALayer, final long subCALayer, final boolean visible, final int x, final int y, final int width, final int height, final int caLayerQuirks) { if( 0==rootCALayer && 0==subCALayer ) { return; } - FixCALayerLayout0(rootCALayer, subCALayer, x, y, width, height, caLayerQuirks); + FixCALayerLayout0(rootCALayer, subCALayer, visible, x, y, width, height, caLayerQuirks); } /** @@ -358,7 +359,7 @@ public class OSXUtil implements ToolkitProperties { private static native long GetNSWindow0(long nsView); private static native long CreateCALayer0(int width, int height); private static native void AddCASublayer0(long rootCALayer, long subCALayer, int x, int y, int width, int height, int caLayerQuirks); - private static native void FixCALayerLayout0(long rootCALayer, long subCALayer, int x, int y, int width, int height, int caLayerQuirks); + private static native void FixCALayerLayout0(long rootCALayer, long subCALayer, boolean visible, int x, int y, int width, int height, int caLayerQuirks); private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); private static native void RunOnMainThread0(Runnable runnable); diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index e3844455a..889e1efd3 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -346,7 +346,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 - (id)actionForKey:(NSString *)key ; - (void)layoutSublayers; - (void)setFrame:(CGRect) frame; -- (void)fixCALayerLayout: (CALayer*) subLayer x:(jint)x y:(jint)y width:(jint)width height:(jint)height caLayerQuirks:(jint)caLayerQuirks force:(jboolean) force; +- (void)fixCALayerLayout: (CALayer*) subLayer visible:(BOOL)visible x:(jint)x y:(jint)y width:(jint)width height:(jint)height caLayerQuirks:(jint)caLayerQuirks force:(jboolean) force; @end @@ -449,13 +449,25 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 } } -- (void)fixCALayerLayout: (CALayer*) subLayer x:(jint)x y:(jint)y width:(jint)width height:(jint)height caLayerQuirks:(jint)caLayerQuirks force:(jboolean) force +- (void)fixCALayerLayout: (CALayer*) subLayer visible:(BOOL)visible x:(jint)x y:(jint)y width:(jint)width height:(jint)height caLayerQuirks:(jint)caLayerQuirks force:(jboolean) force { int loutQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_LAYOUT & caLayerQuirks ); { CALayer* superLayer = [self superlayer]; CGRect superFrame = [superLayer frame]; CGRect lFrame = [self frame]; + if( visible ) { + // Setting opacity should not be required, otherwise we should save the opacity value. + // [subLayer setOpacity: 1.0]; + // [self setOpacity: 1.0]; + [self setHidden: NO]; + [subLayer setHidden: NO]; + } else { + [subLayer setHidden: YES]; + [self setHidden: YES]; + // [subLayer setOpacity: 0.0]; + // [self setOpacity: 0.0]; + } int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lFrame.origin.x!=0 || lFrame.origin.y!=0 ); int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lFrame.size.width!=width || lFrame.size.height!=height ); if( !posQuirk || loutQuirk ) { @@ -596,7 +608,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 [subLayer setNeedsDisplayOnBoundsChange: YES]; if( 0 != caLayerQuirks ) { - [rootLayer fixCALayerLayout: subLayer x:x y:y width:width height:height caLayerQuirks:caLayerQuirks force:JNI_TRUE]; + [rootLayer fixCALayerLayout: subLayer visible:1 x:x y:y width:width height:height caLayerQuirks:caLayerQuirks force:JNI_TRUE]; } [CATransaction commit]; @@ -612,7 +624,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0 * Signature: (JJIII)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_FixCALayerLayout0 - (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jint x, jint y, jint width, jint height, jint caLayerQuirks) + (JNIEnv *env, jclass unused, jlong rootCALayer, jlong subCALayer, jboolean visible, jint x, jint y, jint width, jint height, jint caLayerQuirks) { if( 0 != caLayerQuirks ) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -625,7 +637,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_FixCALayerLayout0 [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; - [rootLayer fixCALayerLayout: subLayer x:x y:y width:width height:height caLayerQuirks:caLayerQuirks force:JNI_FALSE]; + [rootLayer fixCALayerLayout: subLayer visible:(BOOL)visible x:x y:y width:width height:height caLayerQuirks:caLayerQuirks force:JNI_FALSE]; [CATransaction commit]; -- cgit v1.2.3 From ae103ba597464ca25071950af7afe012e2b86c13 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 5 Oct 2013 16:13:56 +0200 Subject: Bug816 OSX CALayer: getLocationOnScreenNonBlocking(..) stop traversing at top-level heavyweight Window, fixes [J]Dialog use case. Top-level heavyweight Window's position is it's position on screen, hence stop traversing. Thx to Emmanuel Puybaret for pointing this out. Adding Dialog and JDialog unit tests as inspired by Emmanuel Puybaret. --- make/scripts/tests.sh | 4 +- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 4 + .../jogl/awt/TestBug816OSXCALayerPos01AWT.java | 2 +- .../jogl/awt/TestBug816OSXCALayerPos02AWT.java | 2 +- .../jogl/awt/TestBug816OSXCALayerPos03AWT.java | 2 +- .../jogl/awt/TestBug816OSXCALayerPos04aAWT.java | 152 +++++++++++++++++++++ .../jogl/awt/TestBug816OSXCALayerPos04bAWT.java | 152 +++++++++++++++++++++ 7 files changed, 314 insertions(+), 4 deletions(-) create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos04aAWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos04bAWT.java (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 92730fa8d..2789c9ea1 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -457,6 +457,8 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos01AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos02AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03AWT $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04aAWT $* +testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04bAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug675BeansInDesignTimeAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug551AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug572AWT $* @@ -474,7 +476,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461PBufferSupersamplingSwingAWT #testawt com.jogamp.opengl.test.junit.jogl.glu.TestBug463ScaleImageMemoryAWT $* #testawt com.jogamp.opengl.test.junit.jogl.glu.TestBug694ScaleImageUnpackBufferSizeAWT $* -testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWTCardLayoutAnimatorStartStopBug532 $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWTCardLayoutAnimatorStartStopBug532 $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAWTActionDeadlock00AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAWTActionDeadlock01AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAWTActionDeadlock02AWT $* diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index d9f36901b..069147d26 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -43,6 +43,7 @@ import com.jogamp.nativewindow.MutableGraphicsConfiguration; import java.awt.Component; import java.awt.Container; +import java.awt.Window; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.applet.Applet; @@ -598,6 +599,9 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, System.err.println(storage); } last = comp; + if( comp instanceof Window ) { // top-level heavy-weight ? + break; + } comp = comp.getParent(); } return last; diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos01AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos01AWT.java index c103b4b86..fade6c33a 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos01AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos01AWT.java @@ -135,7 +135,7 @@ public class TestBug816OSXCALayerPos01AWT extends UITestCase { } protected void runTestGL(GLCapabilities caps, FrameLayout frameLayout, final boolean twoCanvas, final boolean resizeByComp) throws InterruptedException, InvocationTargetException { - final JFrame frame = new JFrame("Bug861: "+this.getTestMethodName()); + final JFrame frame = new JFrame("Bug816: "+this.getTestMethodName()); Assert.assertNotNull(frame); final Container framePane = frame.getContentPane(); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos02AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos02AWT.java index f82983050..43d536afa 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos02AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos02AWT.java @@ -68,7 +68,7 @@ public class TestBug816OSXCALayerPos02AWT extends UITestCase { public void test() throws InterruptedException, InvocationTargetException { final GLCapabilities caps = new GLCapabilities(getGLP()); - final JFrame frame = new JFrame("Bug861: "+this.getTestMethodName()); + final JFrame frame = new JFrame("TestBug816OSXCALayerPos02AWT"); Assert.assertNotNull(frame); final GLCanvas glCanvas1 = new GLCanvas(caps); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java index 09c7669d9..6589cac1e 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java @@ -68,7 +68,7 @@ public class TestBug816OSXCALayerPos03AWT extends UITestCase { public void test() throws InterruptedException, InvocationTargetException { final GLCapabilities caps = new GLCapabilities(getGLP()); - final Frame frame = new Frame("Bug861: "+this.getTestMethodName()); + final Frame frame = new Frame("TestBug816OSXCALayerPos03AWT"); Assert.assertNotNull(frame); final GLCanvas glCanvas1 = new GLCanvas(caps); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos04aAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos04aAWT.java new file mode 100644 index 000000000..b558b1680 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos04aAWT.java @@ -0,0 +1,152 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package com.jogamp.opengl.test.junit.jogl.awt; + +import java.awt.BorderLayout; +import java.awt.Dialog; +import java.awt.Frame; +import java.lang.reflect.InvocationTargetException; + +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLProfile; +import javax.media.opengl.awt.GLCanvas; + +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +import com.jogamp.newt.event.TraceWindowAdapter; +import com.jogamp.newt.event.awt.AWTWindowAdapter; +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.MiscUtils; +import com.jogamp.opengl.test.junit.util.QuitAdapter; +import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.util.Animator; + +/** + * Bug 816: OSX CALayer Positioning Bug - AWT Frame w/ (top-level) Dialog child containing the GLCanvas + *

          + * Diff. OSX CALayer positioning w/ java6, [7uxx..7u40[, and >= 7u40 + *

          + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestBug816OSXCALayerPos04aAWT extends UITestCase { + static long duration = 1600; // ms + static int width=640, height=480; + + @Test + public void test() throws InterruptedException, InvocationTargetException { + final GLCapabilities caps = new GLCapabilities(getGLP()); + + final Frame frame = new Frame("TestBug816OSXCALayerPos04aAWT"); + Assert.assertNotNull(frame); + + final GLCanvas glCanvas1 = new GLCanvas(caps); + Assert.assertNotNull(glCanvas1); + glCanvas1.addGLEventListener(new GearsES2(1)); + + final Animator animator = new Animator(); + animator.add(glCanvas1); + QuitAdapter quitAdapter = new QuitAdapter(); + + new AWTWindowAdapter(new TraceWindowAdapter(quitAdapter)).addTo(frame); + + // Display the canvas 3D in a dialog child of a frame + frame.setSize(400, 400); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setLocation(100, 100); + frame.setSize(width, height); + frame.setVisible(true); + }}); + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame, true)); + + final Dialog dialog = new Dialog(frame, "Bug 816 AWT Top-Level Dialog"); + dialog.setLayout(new BorderLayout()); + dialog.add(glCanvas1, BorderLayout.CENTER); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + dialog.setLocation(200, 200); + dialog.setSize(width/2, height/2); + dialog.setVisible(true); + }}); + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(dialog, true)); + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glCanvas1, true)); + + animator.start(); + Assert.assertTrue(animator.isStarted()); + Assert.assertTrue(animator.isAnimating()); + animator.setUpdateFPSFrames(60, System.err); + + final long t0 = System.currentTimeMillis(); + long t1 = t0; + while(!quitAdapter.shouldQuit() && t1 - t0 < duration) { + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + Assert.assertNotNull(frame); + Assert.assertNotNull(glCanvas1); + + Assert.assertNotNull(animator); + animator.stop(); + Assert.assertFalse(animator.isAnimating()); + Assert.assertFalse(animator.isStarted()); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setVisible(false); + }}); + Assert.assertEquals(false, frame.isVisible()); + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.remove(glCanvas1); + frame.dispose(); + }}); + } + + static GLProfile getGLP() { + return GLProfile.getMaxProgrammableCore(true); + } + + public static void main(String args[]) { + for(int i=0; i + * Diff. OSX CALayer positioning w/ java6, [7uxx..7u40[, and >= 7u40 + *

          + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestBug816OSXCALayerPos04bAWT extends UITestCase { + static long duration = 1600; // ms + static int width=640, height=480; + + @Test + public void test() throws InterruptedException, InvocationTargetException { + final GLCapabilities caps = new GLCapabilities(getGLP()); + + final JFrame frame = new JFrame("TestBug816OSXCALayerPos04bAWT"); + Assert.assertNotNull(frame); + + final GLCanvas glCanvas1 = new GLCanvas(caps); + Assert.assertNotNull(glCanvas1); + glCanvas1.addGLEventListener(new GearsES2(1)); + + final Animator animator = new Animator(); + animator.add(glCanvas1); + QuitAdapter quitAdapter = new QuitAdapter(); + + new AWTWindowAdapter(new TraceWindowAdapter(quitAdapter)).addTo(frame); + + // Display the canvas 3D in a dialog child of a frame + frame.setSize(400, 400); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setLocation(100, 100); + frame.setSize(width, height); + frame.setVisible(true); + }}); + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame, true)); + + final JDialog dialog = new JDialog(frame, "Bug 816 AWT Top-Level JDialog"); + dialog.setLayout(new BorderLayout()); + dialog.add(glCanvas1, BorderLayout.CENTER); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + dialog.setLocation(200, 200); + dialog.setSize(width/2, height/2); + dialog.setVisible(true); + }}); + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(dialog, true)); + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glCanvas1, true)); + + animator.start(); + Assert.assertTrue(animator.isStarted()); + Assert.assertTrue(animator.isAnimating()); + animator.setUpdateFPSFrames(60, System.err); + + final long t0 = System.currentTimeMillis(); + long t1 = t0; + while(!quitAdapter.shouldQuit() && t1 - t0 < duration) { + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + Assert.assertNotNull(frame); + Assert.assertNotNull(glCanvas1); + + Assert.assertNotNull(animator); + animator.stop(); + Assert.assertFalse(animator.isAnimating()); + Assert.assertFalse(animator.isStarted()); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setVisible(false); + }}); + Assert.assertEquals(false, frame.isVisible()); + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.remove(glCanvas1); + frame.dispose(); + }}); + } + + static GLProfile getGLP() { + return GLProfile.getMaxProgrammableCore(true); + } + + public static void main(String args[]) { + for(int i=0; i Date: Sun, 6 Oct 2013 02:28:14 +0200 Subject: Bug 729: OSX CALayer invisible needs to have opacity 0 to not show hidden component. Completes commit 3b02a219b1b9e446e87df1beb7da4266f74824fa See unit test: TestBug816OSXCALayerPos03AWT --- make/scripts/tests.sh | 4 ++-- src/nativewindow/native/macosx/OSXmisc.m | 13 ++++++++----- .../test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java | 5 ++++- 3 files changed, 14 insertions(+), 8 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 2789c9ea1..f3b535058 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -456,9 +456,9 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.acore.x11.TestGLXCallsOnAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos01AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos02AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03AWT $* +testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04aAWT $* -testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04bAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04bAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug675BeansInDesignTimeAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug551AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug572AWT $* diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 889e1efd3..3b19440d7 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -336,6 +336,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 @private BOOL fixedFrameSet; CGRect fixedFrame; + float visibleOpacity; } - (id)init; #ifdef DBG_LIFECYCLE @@ -358,6 +359,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 MyCALayer * o = [super init]; o->fixedFrameSet = 0; o->fixedFrame = CGRectMake(0, 0, 0, 0); + o->visibleOpacity = 1.0; DBG_PRINT("MyCALayer::init.X: new %p\n", o); return o; } @@ -457,16 +459,17 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 CGRect superFrame = [superLayer frame]; CGRect lFrame = [self frame]; if( visible ) { - // Setting opacity should not be required, otherwise we should save the opacity value. - // [subLayer setOpacity: 1.0]; - // [self setOpacity: 1.0]; + // Opacity must be 0 to see through the disabled CALayer + [subLayer setOpacity: visibleOpacity]; + [self setOpacity: visibleOpacity]; [self setHidden: NO]; [subLayer setHidden: NO]; } else { [subLayer setHidden: YES]; [self setHidden: YES]; - // [subLayer setOpacity: 0.0]; - // [self setOpacity: 0.0]; + visibleOpacity = [self opacity]; + [subLayer setOpacity: 0.0]; + [self setOpacity: 0.0]; } int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lFrame.origin.x!=0 || lFrame.origin.y!=0 ); int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lFrame.size.width!=width || lFrame.size.height!=height ); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java index 6589cac1e..92d24e417 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java @@ -86,7 +86,10 @@ public class TestBug816OSXCALayerPos03AWT extends UITestCase { checkbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { glCanvas1.setVisible(checkbox.getState()); - System.out.println(glCanvas1.isVisible()); + System.out.println("Canvas visible: "+glCanvas1.isVisible()); + if( glCanvas1.isVisible() ) { + frame.validate(); // take care of resized frame while hidden + } } }); -- cgit v1.2.3 From e33e6374e0be0454f7e9732b5f897f84dbc3c4dc Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 6 Oct 2013 21:25:42 +0200 Subject: Bug 729, Bug 849: Honor JAWTWindow's [parent] visibility state JAWTWindow snoops HierarchyEvents for SHOWING_CHANGED to track local component's visibility state as well as it's global visibility state. The later is determined by it's parent's visibility change. If 'removeNotify()' is called, component's visibility is reset to it's local visibility state. Fixes OSX CALayer component's visibility if parent's visibility changes (Bug 729). Fixes continuous GL rendering if parent is invisible (Bug 849). --- make/scripts/tests.sh | 4 +- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 122 +++++++++++---- .../jogl/awt/TestBug816OSXCALayerPos03AWT.java | 155 ------------------ .../jogl/awt/TestBug816OSXCALayerPos03aAWT.java | 165 ++++++++++++++++++++ .../jogl/awt/TestBug816OSXCALayerPos03bAWT.java | 171 ++++++++++++++++++++ .../jogl/awt/TestBug816OSXCALayerPos03cAWT.java | 173 +++++++++++++++++++++ 6 files changed, 608 insertions(+), 182 deletions(-) delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03aAWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03bAWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03cAWT.java (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index f3b535058..81f89d531 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -456,7 +456,9 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.acore.x11.TestGLXCallsOnAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos01AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos02AWT $* -testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03AWT $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03aAWT $* +testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03bAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03cAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04aAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04bAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug675BeansInDesignTimeAWT $* diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 069147d26..6e198d961 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -37,6 +37,7 @@ package com.jogamp.nativewindow.awt; +import com.jogamp.common.os.Platform; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.nativewindow.MutableGraphicsConfiguration; @@ -46,6 +47,8 @@ import java.awt.Container; import java.awt.Window; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; +import java.awt.event.HierarchyEvent; +import java.awt.event.HierarchyListener; import java.applet.Applet; import javax.media.nativewindow.AbstractGraphicsConfiguration; @@ -76,10 +79,11 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected boolean shallUseOffscreenLayer = false; // lifetime: forever - protected Component component; - private AWTGraphicsConfiguration config; // control access due to delegation - private SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); - private RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); + protected final Component component; + private final AWTGraphicsConfiguration config; // control access due to delegation + private final SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); + private final RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); + private final JAWTComponentListener jawtComponentListener; // lifetime: valid after lock but may change with each 1st lock, purges after invalidate private boolean isApplet; @@ -106,39 +110,110 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if(! ( config instanceof AWTGraphicsConfiguration ) ) { throw new NativeWindowException("Error: AbstractGraphicsConfiguration is not an AWTGraphicsConfiguration: "+config); } + this.component = (Component)comp; this.config = (AWTGraphicsConfiguration) config; - init((Component)comp); - } - - private void init(Component windowObject) throws NativeWindowException { + this.jawtComponentListener = new JAWTComponentListener(); + this.component.addComponentListener(jawtComponentListener); + this.component.addHierarchyListener(jawtComponentListener); invalidate(); - this.component = windowObject; this.isApplet = false; this.offscreenSurfaceLayer = 0; - this.component.addComponentListener(new ComponentListener() { - private boolean visible = component.isVisible(); + } + private class JAWTComponentListener implements ComponentListener, HierarchyListener { + private boolean localVisibility = component.isVisible(); + private boolean globalVisibility = localVisibility; + private boolean visibilityPropagation = false; + + private String s(ComponentEvent e) { + return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"],"+Platform.getNewline()+ + " ** COMP "+e.getComponent()+Platform.getNewline()+ + " ** SOURCE "+e.getSource()+Platform.getNewline()+ + " ** THIS "+component; + } + private String s(HierarchyEvent e) { + return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"], changeBits 0x"+Long.toHexString(e.getChangeFlags())+Platform.getNewline()+ + " ** COMP "+e.getComponent()+Platform.getNewline()+ + " ** SOURCE "+e.getSource()+Platform.getNewline()+ + " ** CHANGED "+e.getChanged()+Platform.getNewline()+ + " ** CHANGEDPARENT "+e.getChangedParent()+Platform.getNewline()+ + " ** THIS "+component; + } + @Override public void componentResized(ComponentEvent e) { - layoutSurfaceLayerIfEnabled(visible); + if(DEBUG) { + System.err.println("JAWTWindow.componentResized: "+s(e)); + } + layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); } @Override public void componentMoved(ComponentEvent e) { - layoutSurfaceLayerIfEnabled(visible); + if(DEBUG) { + System.err.println("JAWTWindow.componentMoved: "+s(e)); + } + layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); } @Override public void componentShown(ComponentEvent e) { - visible = true; - layoutSurfaceLayerIfEnabled(visible); + if(DEBUG) { + System.err.println("JAWTWindow.componentShown: "+s(e)); + } + layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); } @Override public void componentHidden(ComponentEvent e) { - visible = false; - layoutSurfaceLayerIfEnabled(visible); - } - }); + if(DEBUG) { + System.err.println("JAWTWindow.componentHidden: "+s(e)); + } + layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); + } + + @Override + public void hierarchyChanged(HierarchyEvent e) { + final long bits = e.getChangeFlags(); + final java.awt.Component changed = e.getChanged(); + if( 0 != ( java.awt.event.HierarchyEvent.DISPLAYABILITY_CHANGED & bits ) ) { + final boolean displayable = changed.isDisplayable(); + final boolean resetLocalVisibility = changed == component && !displayable && localVisibility != component.isVisible(); + if( resetLocalVisibility ) { + // Reset components local state if detached from parent, i.e. 'removeNotify()' + visibilityPropagation = true; + if(DEBUG) { + System.err.println("JAWTWindow.hierarchyChanged DISPLAYABILITY_CHANGED (1): displayable "+displayable+", "+s(e)); + } + component.setVisible(localVisibility); + } else if(DEBUG) { + System.err.println("JAWTWindow.hierarchyChanged DISPLAYABILITY_CHANGED (x): displayable "+displayable+", "+s(e)); + } + } else if( 0 != ( java.awt.event.HierarchyEvent.SHOWING_CHANGED & bits ) ) { + final boolean showing = changed.isShowing(); + final boolean propagateVisibility = changed != component && ( showing && localVisibility ) != component.isVisible(); + if( propagateVisibility ) { + // Propagate parent's visibility + final boolean _visible = showing && localVisibility; + visibilityPropagation = true; + globalVisibility = showing; + if(DEBUG) { + System.err.println("JAWTWindow.hierarchyChanged SHOWING_CHANGED (1): showing "+showing+" -> visible "+_visible+", "+s(e)); + } + component.setVisible(_visible); + } else if( changed == component ) { + // Update component's local visibility state + if(!visibilityPropagation) { + localVisibility = showing; + } + visibilityPropagation = false; + if(DEBUG) { + System.err.println("JAWTWindow.hierarchyChanged SHOWING_CHANGED (0): showing "+showing+" -> visible "+(showing && localVisibility)+", "+s(e)); + } + } else if(DEBUG) { + System.err.println("JAWTWindow.hierarchyChanged SHOWING_CHANGED (x): showing "+showing+" -> visible "+(showing && localVisibility)+", "+s(e)); + } + } + } } protected synchronized void invalidate() { @@ -488,7 +563,6 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, surfaceLock.lock(); try { invalidate(); - component = null; // don't dispose the AWT component, since we are merely an immutable uplink } finally { surfaceLock.unlock(); } @@ -638,12 +712,8 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, ", surfaceHandle "+toHexString(getSurfaceHandle())+ ", bounds "+bounds+", insets "+insets ); - if(null!=component) { - sb.append(", pos "+getX()+"/"+getY()+", size "+getWidth()+"x"+getHeight()+ - ", visible "+component.isVisible()); - } else { - sb.append(", component NULL"); - } + sb.append(", pos "+getX()+"/"+getY()+", size "+getWidth()+"x"+getHeight()+ + ", visible "+component.isVisible()); sb.append(", lockedExt "+isSurfaceLockedByOtherThread()+ ",\n\tconfig "+getPrivateGraphicsConfiguration()+ ",\n\tawtComponent "+getAWTComponent()+ diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java deleted file mode 100644 index 92d24e417..000000000 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03AWT.java +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Copyright 2013 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ - -package com.jogamp.opengl.test.junit.jogl.awt; - -import java.awt.BorderLayout; -import java.awt.Checkbox; -import java.awt.Frame; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.lang.reflect.InvocationTargetException; - -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLProfile; -import javax.media.opengl.awt.GLCanvas; - -import org.junit.Assert; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; - -import com.jogamp.newt.event.TraceWindowAdapter; -import com.jogamp.newt.event.awt.AWTWindowAdapter; -import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; -import com.jogamp.opengl.test.junit.util.AWTRobotUtil; -import com.jogamp.opengl.test.junit.util.MiscUtils; -import com.jogamp.opengl.test.junit.util.QuitAdapter; -import com.jogamp.opengl.test.junit.util.UITestCase; -import com.jogamp.opengl.util.Animator; - -/** - * Bug 816: OSX CALayer Positioning Bug - AWT Frame BorderLayout w/ Checkbox North, GLCanvas Center - *

          - * Diff. OSX CALayer positioning w/ java6, [7uxx..7u40[, and >= 7u40 - *

          - */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class TestBug816OSXCALayerPos03AWT extends UITestCase { - static long duration = 1600; // ms - static int width=640, height=480; - - @Test - public void test() throws InterruptedException, InvocationTargetException { - final GLCapabilities caps = new GLCapabilities(getGLP()); - - final Frame frame = new Frame("TestBug816OSXCALayerPos03AWT"); - Assert.assertNotNull(frame); - - final GLCanvas glCanvas1 = new GLCanvas(caps); - Assert.assertNotNull(glCanvas1); - glCanvas1.addGLEventListener(new GearsES2(1)); - - final Animator animator = new Animator(); - animator.add(glCanvas1); - QuitAdapter quitAdapter = new QuitAdapter(); - - new AWTWindowAdapter(new TraceWindowAdapter(quitAdapter)).addTo(frame); - - // Create a check box that hides / shows canvas - final Checkbox checkbox = new Checkbox("Visible canvas", true); - checkbox.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent ev) { - glCanvas1.setVisible(checkbox.getState()); - System.out.println("Canvas visible: "+glCanvas1.isVisible()); - if( glCanvas1.isVisible() ) { - frame.validate(); // take care of resized frame while hidden - } - } - }); - - // Build a GUI that displays canvas and check box - frame.setLayout(new BorderLayout()); - frame.add(glCanvas1, BorderLayout.CENTER); - frame.add(checkbox, BorderLayout.NORTH); - - javax.swing.SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - frame.setSize(width, height); - frame.setVisible(true); - }}); - Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame, true)); - Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glCanvas1, true)); - - animator.start(); - Assert.assertTrue(animator.isStarted()); - Assert.assertTrue(animator.isAnimating()); - animator.setUpdateFPSFrames(60, System.err); - - final long t0 = System.currentTimeMillis(); - long t1 = t0; - while(!quitAdapter.shouldQuit() && t1 - t0 < duration) { - Thread.sleep(100); - t1 = System.currentTimeMillis(); - } - - Assert.assertNotNull(frame); - Assert.assertNotNull(glCanvas1); - - Assert.assertNotNull(animator); - animator.stop(); - Assert.assertFalse(animator.isAnimating()); - Assert.assertFalse(animator.isStarted()); - - javax.swing.SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - frame.setVisible(false); - }}); - Assert.assertEquals(false, frame.isVisible()); - javax.swing.SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - frame.remove(glCanvas1); - frame.dispose(); - }}); - } - - static GLProfile getGLP() { - return GLProfile.getMaxProgrammableCore(true); - } - - public static void main(String args[]) { - for(int i=0; i + * Checkbox toggles GLCanvas visibility state. + *

          + *

          + * Validates bugs: + *

            + *
          • Bug 816: OSX CALayer Positioning Bug
          • + *
          • Bug 729: OSX CALayer shall honor the Component's visibility state
          • + *
          + *

          + *

          + * Diff. OSX CALayer positioning w/ java6, [7uxx..7u40[, and >= 7u40 + *

          + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestBug816OSXCALayerPos03aAWT extends UITestCase { + static long duration = 1600; // ms + static int width=640, height=480; + + @Test + public void test() throws InterruptedException, InvocationTargetException { + final GLCapabilities caps = new GLCapabilities(getGLP()); + + final Frame frame = new Frame("TestBug816OSXCALayerPos03aAWT"); + Assert.assertNotNull(frame); + + final GLCanvas glCanvas1 = new GLCanvas(caps); + Assert.assertNotNull(glCanvas1); + glCanvas1.addGLEventListener(new GearsES2(1)); + + final Animator animator = new Animator(); + animator.add(glCanvas1); + QuitAdapter quitAdapter = new QuitAdapter(); + + new AWTWindowAdapter(new TraceWindowAdapter(quitAdapter)).addTo(frame); + + // Create a check box that hides / shows canvas + final Checkbox checkbox = new Checkbox("Visible canvas", true); + checkbox.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent ev) { + glCanvas1.setVisible(checkbox.getState()); + System.out.println("Canvas visible: "+glCanvas1.isVisible()); + if( glCanvas1.isVisible() ) { + frame.validate(); // take care of resized frame while hidden + } + } + }); + + // Build a GUI that displays canvas and check box + frame.setLayout(new BorderLayout()); + frame.add(glCanvas1, BorderLayout.CENTER); + frame.add(checkbox, BorderLayout.NORTH); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setSize(width, height); + frame.setVisible(true); + }}); + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame, true)); + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glCanvas1, true)); + + animator.start(); + Assert.assertTrue(animator.isStarted()); + Assert.assertTrue(animator.isAnimating()); + animator.setUpdateFPSFrames(60, System.err); + + final long t0 = System.currentTimeMillis(); + long t1 = t0; + while(!quitAdapter.shouldQuit() && t1 - t0 < duration) { + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + Assert.assertNotNull(frame); + Assert.assertNotNull(glCanvas1); + + Assert.assertNotNull(animator); + animator.stop(); + Assert.assertFalse(animator.isAnimating()); + Assert.assertFalse(animator.isStarted()); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setVisible(false); + }}); + Assert.assertEquals(false, frame.isVisible()); + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.remove(glCanvas1); + frame.dispose(); + }}); + } + + static GLProfile getGLP() { + return GLProfile.getMaxProgrammableCore(true); + } + + public static void main(String args[]) { + for(int i=0; i + * Checkbox toggles GLCanvas's parent panel's visibility state. + *

          + *

          + * Validates bugs: + *

            + *
          • Bug 816: OSX CALayer Positioning Bug
          • + *
          • Bug 729: OSX CALayer shall honor the Component's visibility state
          • + *
          • Bug 849: AWT GLAutoDrawables (JAWTWindow) shall honor it's parent visibility state
          • + *
          + *

          + *

          + * Diff. OSX CALayer positioning w/ java6, [7uxx..7u40[, and >= 7u40 + *

          + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestBug816OSXCALayerPos03bAWT extends UITestCase { + static long duration = 1600; // ms + static int width=640, height=480; + + @Test + public void test() throws InterruptedException, InvocationTargetException { + final GLCapabilities caps = new GLCapabilities(getGLP()); + + final Frame frame = new Frame("TestBug816OSXCALayerPos03bAWT"); + Assert.assertNotNull(frame); + + final GLCanvas glCanvas1 = new GLCanvas(caps); + Assert.assertNotNull(glCanvas1); + glCanvas1.addGLEventListener(new GearsES2(1)); + // Put it in a panel + final Panel panel = new Panel(new GridLayout(1, 1)); + panel.add(glCanvas1); + + final Animator animator = new Animator(); + animator.add(glCanvas1); + QuitAdapter quitAdapter = new QuitAdapter(); + + new AWTWindowAdapter(new TraceWindowAdapter(quitAdapter)).addTo(frame); + + // Create a check box that hides / shows canvas + final Checkbox checkbox = new Checkbox("Visible canvas", true); + checkbox.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent ev) { + panel.setVisible(checkbox.getState()); + System.out.println("Visible: [panel "+panel.isVisible()+", canvas "+glCanvas1.isVisible()+"]; Displayable: [panel "+panel.isDisplayable()+", canvas "+glCanvas1.isDisplayable()+"]"); + if( panel.isVisible() ) { + frame.validate(); // take care of resized frame while hidden + } + } + }); + + // Build a GUI that displays canvas and check box + frame.setLayout(new BorderLayout()); + frame.add(panel, BorderLayout.CENTER); + frame.add(checkbox, BorderLayout.NORTH); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setSize(width, height); + frame.setVisible(true); + }}); + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame, true)); + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glCanvas1, true)); + + animator.start(); + Assert.assertTrue(animator.isStarted()); + Assert.assertTrue(animator.isAnimating()); + animator.setUpdateFPSFrames(60, System.err); + + final long t0 = System.currentTimeMillis(); + long t1 = t0; + while(!quitAdapter.shouldQuit() && t1 - t0 < duration) { + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + Assert.assertNotNull(frame); + Assert.assertNotNull(glCanvas1); + + Assert.assertNotNull(animator); + animator.stop(); + Assert.assertFalse(animator.isAnimating()); + Assert.assertFalse(animator.isStarted()); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setVisible(false); + }}); + Assert.assertEquals(false, frame.isVisible()); + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.remove(panel); + frame.dispose(); + }}); + } + + static GLProfile getGLP() { + return GLProfile.getMaxProgrammableCore(true); + } + + public static void main(String args[]) { + for(int i=0; i + * Checkbox toggles GLCanvas's parent jpanel's visibility state. + *

          + *

          + * Validates bugs: + *

            + *
          • Bug 816: OSX CALayer Positioning Bug
          • + *
          • Bug 729: OSX CALayer shall honor the Component's visibility state
          • + *
          • Bug 849: AWT GLAutoDrawables (JAWTWindow) shall honor it's parent visibility state
          • + *
          + *

          + *

          + * Diff. OSX CALayer positioning w/ java6, [7uxx..7u40[, and >= 7u40 + *

          + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestBug816OSXCALayerPos03cAWT extends UITestCase { + static long duration = 1600; // ms + static int width=640, height=480; + + @Test + public void test() throws InterruptedException, InvocationTargetException { + final GLCapabilities caps = new GLCapabilities(getGLP()); + + final JFrame frame = new JFrame("TestBug816OSXCALayerPos03cAWT"); + Assert.assertNotNull(frame); + final Container framePane = frame.getContentPane(); + + final GLCanvas glCanvas1 = new GLCanvas(caps); + Assert.assertNotNull(glCanvas1); + glCanvas1.addGLEventListener(new GearsES2(1)); + // Put it in a panel + final JPanel panel = new JPanel(new GridLayout(1, 1)); + panel.add(glCanvas1); + + final Animator animator = new Animator(); + animator.add(glCanvas1); + QuitAdapter quitAdapter = new QuitAdapter(); + + new AWTWindowAdapter(new TraceWindowAdapter(quitAdapter)).addTo(frame); + + // Create a check box that hides / shows canvas + final JCheckBox checkbox = new JCheckBox("Visible canvas", true); + checkbox.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent ev) { + panel.setVisible(checkbox.getSelectedObjects()!=null); + System.out.println("Visible: [panel "+panel.isVisible()+", canvas "+glCanvas1.isVisible()+"]; Displayable: [panel "+panel.isDisplayable()+", canvas "+glCanvas1.isDisplayable()+"]"); + if( panel.isVisible() ) { + frame.validate(); // take care of resized frame while hidden + } + } + }); + + // Build a GUI that displays canvas and check box + framePane.setLayout(new BorderLayout()); + framePane.add(panel, BorderLayout.CENTER); + framePane.add(checkbox, BorderLayout.NORTH); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setSize(width, height); + frame.setVisible(true); + }}); + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame, true)); + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glCanvas1, true)); + + animator.start(); + Assert.assertTrue(animator.isStarted()); + Assert.assertTrue(animator.isAnimating()); + animator.setUpdateFPSFrames(60, System.err); + + final long t0 = System.currentTimeMillis(); + long t1 = t0; + while(!quitAdapter.shouldQuit() && t1 - t0 < duration) { + Thread.sleep(100); + t1 = System.currentTimeMillis(); + } + + Assert.assertNotNull(frame); + Assert.assertNotNull(glCanvas1); + + Assert.assertNotNull(animator); + animator.stop(); + Assert.assertFalse(animator.isAnimating()); + Assert.assertFalse(animator.isStarted()); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.setVisible(false); + }}); + Assert.assertEquals(false, frame.isVisible()); + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + framePane.remove(panel); + frame.dispose(); + }}); + } + + static GLProfile getGLP() { + return GLProfile.getMaxProgrammableCore(true); + } + + public static void main(String args[]) { + for(int i=0; i Date: Mon, 7 Oct 2013 07:36:17 +0200 Subject: NativeWindow/OSX: Fix RunOnThread/RunLater - Properly determine 'forkOnMain' via onMain && ( isOnMain || 0 < delay ) --- .../classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 2 +- .../classes/jogamp/nativewindow/macosx/OSXUtil.java | 10 +++++----- src/nativewindow/native/macosx/OSXmisc.m | 13 ++++++++----- 3 files changed, 14 insertions(+), 11 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index e6334150b..0828d1dc3 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -745,7 +745,7 @@ public class MacOSXCGLContext extends GLContextImpl if (DEBUG) { System.err.println("NSOpenGLLayer.Attach: Re-Queue, drawableHandle "+toHexString(drawable.getHandle())+" - "+getThreadName()); } - OSXUtil.RunLater(this, 1); + OSXUtil.RunLater(true /* onMain */, this, 1); } } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index b27affa7e..dc32bd58c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -263,13 +263,13 @@ public class OSXUtil implements ToolkitProperties { } /** - * Run later on current OSX thread. - * + * Run later on .. + * @param onMain if true, run on main-thread, otherwise on the current OSX thread. * @param runnable * @param delay delay to run the runnable in milliseconds */ - public static void RunLater(Runnable runnable, int delay) { - RunLater0(new RunnableTask( runnable, null, true, System.err ), delay); + public static void RunLater(boolean onMain, Runnable runnable, int delay) { + RunLater0(onMain, new RunnableTask( runnable, null, true, System.err ), delay); } private static Runnable _nop = new Runnable() { public void run() {}; }; @@ -363,7 +363,7 @@ public class OSXUtil implements ToolkitProperties { private static native void RemoveCASublayer0(long rootCALayer, long subCALayer); private static native void DestroyCALayer0(long caLayer); private static native void RunOnMainThread0(Runnable runnable); - private static native void RunLater0(Runnable runnable, int delay); + private static native void RunLater0(boolean onMain, Runnable runnable, int delay); private static native boolean IsMainThread0(); private static native int GetScreenRefreshRate0(int scrn_idx); } diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 3b19440d7..6a7952eaf 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -852,10 +852,13 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Uns static void RunOnThread (JNIEnv *env, jobject runnable, BOOL onMain, jint delayInMS) { - DBG_PRINT2( "RunOnThread0: isMainThread %d, NSApp %d, NSApp-isRunning %d, onMain %d, delay %dms\n", - (int)([NSThread isMainThread]), (int)(NULL!=NSApp), (int)([NSApp isRunning]), (int)onMain, (int)delayInMS); + BOOL isMainThread = [NSThread isMainThread]; + BOOL forkOnMain = onMain && ( NO == isMainThread || 0 < delayInMS ); - if ( !onMain || NO == [NSThread isMainThread] ) { + DBG_PRINT2( "RunOnThread0: forkOnMain %d [onMain %d, delay %dms, isMainThread %d], NSApp %d, NSApp-isRunning %d\n", + (int)forkOnMain, (int)onMain, (int)delayInMS, (int)isMainThread, (int)(NULL!=NSApp), (int)([NSApp isRunning])); + + if ( forkOnMain ) { jobject runnableObj = (*env)->NewGlobalRef(env, runnable); JavaVM *jvmHandle = NULL; @@ -907,10 +910,10 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunOnMainThread0 * Signature: (ZLjava/lang/Runnable;I)V */ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RunLater0 - (JNIEnv *env, jclass unused, jobject runnable, jint delay) + (JNIEnv *env, jclass unused, jboolean onMain, jobject runnable, jint delay) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - RunOnThread (env, runnable, NO, delay); + RunOnThread (env, runnable, onMain ? YES : NO, delay); [pool release]; } -- cgit v1.2.3 From b74f849c1864984e0be08fa18c9e555db701a971 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 15 Oct 2013 03:55:57 +0200 Subject: Cleanup DirectDataBufferInt: Fix type ; Remove unsused local vars --- .../classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java index 1d66d67e7..7a7a771d6 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java @@ -71,7 +71,7 @@ public final class DirectDataBufferInt extends DataBuffer { @Override public String toString() { return new String("BufferedImageInt@"+Integer.toHexString(hashCode()) - +": custum/internal type = "+customImageType+"/"+getType() + +": custom/internal type = "+customImageType+"/"+getType() +" "+getColorModel()+" "+getRaster()); } } @@ -98,10 +98,6 @@ public final class DirectDataBufferInt extends DataBuffer { * @return */ public static BufferedImageInt createBufferedImage(int width, int height, int imageType, Point location, Hashtable properties) { - final int[] bandOffsets = new int[imageType]; - for (int i=0; i < imageType; i++) { - bandOffsets[i] = i; - } final ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB); final int transferType = DataBuffer.TYPE_INT; final int bpp, rmask, gmask, bmask, amask; -- cgit v1.2.3 From a05b87a369441d9ef38f97929f866b3d4ced0e57 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 15 Oct 2013 17:04:35 +0200 Subject: AWTPrintLifecycle.setupPrint(..): Add optional tileWidth and tileHeight, allowing user to set custom tile size for performance evaluation/tweak --- make/scripts/tests.sh | 4 +-- .../classes/javax/media/opengl/awt/GLCanvas.java | 27 +++++++++----- .../classes/javax/media/opengl/awt/GLJPanel.java | 29 +++++++++------ .../classes/jogamp/opengl/awt/AWTTilePainter.java | 21 ++++++----- .../jogamp/nativewindow/awt/AWTPrintLifecycle.java | 30 ++++++++++------ .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 27 +++++++++----- .../test/junit/jogl/tile/OffscreenPrintable.java | 7 ++-- .../test/junit/jogl/tile/OnscreenPrintable.java | 8 +++-- .../opengl/test/junit/jogl/tile/PrintableBase.java | 8 ++++- .../junit/jogl/tile/TestTiledPrintingGearsAWT.java | 25 +++++++------ .../jogl/tile/TestTiledPrintingGearsNewtAWT.java | 25 +++++++------ .../jogl/tile/TestTiledPrintingGearsSwingAWT.java | 31 +++++++++------- .../jogl/tile/TestTiledPrintingGearsSwingAWT2.java | 8 ++--- .../tile/TestTiledPrintingNIOImageSwingAWT.java | 2 +- .../test/junit/jogl/tile/TiledPrintingAWTBase.java | 42 ++++++++++++++-------- 15 files changed, 187 insertions(+), 107 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 84f487c38..a302666f7 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -299,7 +299,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelsAWT $* -testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* +#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NewtCanvasAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NEWT $* @@ -333,7 +333,7 @@ testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasA #testnoawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering2GL2NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestRandomTiledRendering3GL2AWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsAWT $* -#testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* +testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsSwingAWT2 $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingGearsNewtAWT $* #testawt com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintingNIOImageSwingAWT $* diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 20dd802fb..b9576b8d6 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -723,18 +723,16 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } private volatile boolean printActive = false; - private int printNumSamples = 0; private GLAnimatorControl printAnimator = null; private GLAutoDrawable printGLAD = null; private AWTTilePainter printAWTTiles = null; @Override - public void setupPrint(double scaleMatX, double scaleMatY, int numSamples) { + public void setupPrint(double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight) { printActive = true; - printNumSamples = numSamples; final int componentCount = isOpaque() ? 3 : 4; final TileRenderer printRenderer = new TileRenderer(); - printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, DEBUG); + printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, numSamples, tileWidth, tileHeight, DEBUG); AWTEDTExecutor.singleton.invoke(getTreeLock(), true /* allowOnNonEDT */, true /* wait */, setupPrintOnEDT); } private final Runnable setupPrintOnEDT = new Runnable() { @@ -760,10 +758,18 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing printAnimator.remove(GLCanvas.this); } final GLCapabilities caps = (GLCapabilities)getChosenGLCapabilities().cloneMutable(); - final int reqNumSamples = printNumSamples; - printNumSamples = AWTTilePainter.getNumSamples(reqNumSamples, caps); + final int printNumSamples = printAWTTiles.getNumSamples(caps); + GLDrawable printDrawable = printGLAD.getDelegatedDrawable(); + final boolean reqNewGLADSamples = printNumSamples != caps.getNumSamples(); + final boolean reqNewGLADSize = printAWTTiles.customTileWidth != -1 && printAWTTiles.customTileWidth != printDrawable.getWidth() || + printAWTTiles.customTileHeight != -1 && printAWTTiles.customTileHeight != printDrawable.getHeight(); + final boolean reqNewGLAD = !caps.getSampleBuffers(); // reqNewGLADSamples || reqNewGLADSize ; if( DEBUG ) { - System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", scaleMat "+printAWTTiles.scaleMatX+" x "+printAWTTiles.scaleMatY+", numSamples "+reqNumSamples+" -> "+printNumSamples+", printAnimator "+printAnimator); + System.err.println("AWT print.setup: reqNewGLAD "+reqNewGLAD+"[ samples "+reqNewGLADSamples+", size "+reqNewGLADSize+"], "+ + ", drawableSize "+printDrawable.getWidth()+"x"+printDrawable.getHeight()+ + ", customTileSize "+printAWTTiles.customTileWidth+"x"+printAWTTiles.customTileHeight+ + ", scaleMat "+printAWTTiles.scaleMatX+" x "+printAWTTiles.scaleMatY+ + ", numSamples "+printAWTTiles.customNumSamples+" -> "+printNumSamples+", printAnimator "+printAnimator); } if( caps.getSampleBuffers() ) { // Bug 830: swapGLContextAndAllGLEventListener and onscreen MSAA w/ NV/GLX @@ -776,10 +782,13 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing caps.setNumSamples(printNumSamples); } final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); - printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, DEFAULT_PRINT_TILE_SIZE, DEFAULT_PRINT_TILE_SIZE, null); + printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, + printAWTTiles.customTileWidth != -1 ? printAWTTiles.customTileWidth : DEFAULT_PRINT_TILE_SIZE, + printAWTTiles.customTileHeight != -1 ? printAWTTiles.customTileHeight : DEFAULT_PRINT_TILE_SIZE, + null); GLDrawableUtil.swapGLContextAndAllGLEventListener(GLCanvas.this, printGLAD); + printDrawable = printGLAD.getDelegatedDrawable(); } - final GLDrawable printDrawable = printGLAD.getDelegatedDrawable(); printAWTTiles.setIsGLOriented(printGLAD.isGLOriented()); printAWTTiles.renderer.setTileSize(printDrawable.getWidth(), printDrawable.getHeight(), 0); printAWTTiles.renderer.attachAutoDrawable(printGLAD); diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java index 673f22aff..1ec0ad7bc 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java @@ -510,18 +510,16 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } private volatile boolean printActive = false; - private int printNumSamples = 0; private GLAnimatorControl printAnimator = null; private GLAutoDrawable printGLAD = null; private AWTTilePainter printAWTTiles = null; @Override - public void setupPrint(double scaleMatX, double scaleMatY, int numSamples) { + public void setupPrint(double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight) { printActive = true; - printNumSamples = numSamples; final int componentCount = isOpaque() ? 3 : 4; final TileRenderer printRenderer = new TileRenderer(); - printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, DEBUG); + printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, numSamples, tileWidth, tileHeight, DEBUG); AWTEDTExecutor.singleton.invoke(getTreeLock(), true /* allowOnNonEDT */, true /* wait */, setupPrintOnEDT); } private final Runnable setupPrintOnEDT = new Runnable() { @@ -553,21 +551,32 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing printGLAD = GLJPanel.this; // default: re-use final GLCapabilities caps = (GLCapabilities)getChosenGLCapabilities().cloneMutable(); - final int reqNumSamples = printNumSamples; - printNumSamples = AWTTilePainter.getNumSamples(reqNumSamples, caps); + final int printNumSamples = printAWTTiles.getNumSamples(caps); + GLDrawable printDrawable = printGLAD.getDelegatedDrawable(); + final boolean reqNewGLADSamples = printNumSamples != caps.getNumSamples(); + final boolean reqNewGLADSize = printAWTTiles.customTileWidth != -1 && printAWTTiles.customTileWidth != printDrawable.getWidth() || + printAWTTiles.customTileHeight != -1 && printAWTTiles.customTileHeight != printDrawable.getHeight(); + final boolean reqNewGLAD = reqNewGLADSamples || reqNewGLADSize ; if( DEBUG ) { - System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", scaleMat "+printAWTTiles.scaleMatX+" x "+printAWTTiles.scaleMatY+", numSamples "+reqNumSamples+" -> "+printNumSamples+", printAnimator "+printAnimator); + System.err.println("AWT print.setup: reqNewGLAD "+reqNewGLAD+"[ samples "+reqNewGLADSamples+", size "+reqNewGLADSize+"], "+ + ", drawableSize "+printDrawable.getWidth()+"x"+printDrawable.getHeight()+ + ", customTileSize "+printAWTTiles.customTileWidth+"x"+printAWTTiles.customTileHeight+ + ", scaleMat "+printAWTTiles.scaleMatX+" x "+printAWTTiles.scaleMatY+ + ", numSamples "+printAWTTiles.customNumSamples+" -> "+printNumSamples+", printAnimator "+printAnimator); } - if( printNumSamples != caps.getNumSamples() ) { + if( reqNewGLAD ) { caps.setDoubleBuffered(false); caps.setOnscreen(false); caps.setSampleBuffers(0 < printNumSamples); caps.setNumSamples(printNumSamples); final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); - printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, DEFAULT_PRINT_TILE_SIZE, DEFAULT_PRINT_TILE_SIZE, null); + printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, + printAWTTiles.customTileWidth != -1 ? printAWTTiles.customTileWidth : DEFAULT_PRINT_TILE_SIZE, + printAWTTiles.customTileHeight != -1 ? printAWTTiles.customTileHeight : DEFAULT_PRINT_TILE_SIZE, + null); GLDrawableUtil.swapGLContextAndAllGLEventListener(GLJPanel.this, printGLAD); + printDrawable = printGLAD.getDelegatedDrawable(); } - final GLDrawable printDrawable = printGLAD.getDelegatedDrawable(); printAWTTiles.setIsGLOriented(printGLAD.isGLOriented()); printAWTTiles.renderer.setTileSize(printDrawable.getWidth(), printDrawable.getHeight(), 0); printAWTTiles.renderer.attachAutoDrawable(printGLAD); diff --git a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java index 0600d99f5..9bdceff48 100644 --- a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java +++ b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java @@ -71,6 +71,7 @@ public class AWTTilePainter { public final TileRenderer renderer; public final int componentCount; public final double scaleMatX, scaleMatY; + public final int customTileWidth, customTileHeight, customNumSamples; public final boolean verbose; public boolean flipVertical; @@ -99,18 +100,16 @@ public class AWTTilePainter { } /** - * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples - * @param caps used capabilties - * @return resulting number of samples, 0 if disabled + * @return resulting number of samples by comparing w/ {@link #customNumSamples} and the caps-config, 0 if disabled */ - public static int getNumSamples(int numSamples, GLCapabilitiesImmutable caps) { - if( 0 > numSamples ) { + public int getNumSamples(GLCapabilitiesImmutable caps) { + if( 0 > customNumSamples ) { return 0; - } else if( 0 < numSamples ) { + } else if( 0 < customNumSamples ) { if ( !caps.getGLProfile().isGL2ES3() ) { return 0; } - return Math.max(caps.getNumSamples(), numSamples); + return Math.max(caps.getNumSamples(), customNumSamples); } else { return caps.getNumSamples(); } @@ -130,14 +129,20 @@ public class AWTTilePainter { * @param componentCount * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels + * @param numSamples custom multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param tileWidth custom tile width for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. + * @param tileHeight custom tile height for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. * @param verbose */ - public AWTTilePainter(TileRenderer renderer, int componentCount, double scaleMatX, double scaleMatY, boolean verbose) { + public AWTTilePainter(TileRenderer renderer, int componentCount, double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight, boolean verbose) { this.renderer = renderer; this.renderer.setGLEventListener(preTileGLEL, postTileGLEL); this.componentCount = componentCount; this.scaleMatX = scaleMatX; this.scaleMatY = scaleMatY; + this.customNumSamples = numSamples; + this.customTileWidth= tileWidth; + this.customTileHeight = tileHeight; this.verbose = verbose; this.flipVertical = true; } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java index 65e5ab3f0..e5290aee1 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java @@ -47,9 +47,9 @@ import jogamp.nativewindow.awt.AWTMisc; *

          * Users attempting to print an AWT {@link Container} containing {@link AWTPrintLifecycle} elements * shall consider decorating the {@link Container#printAll(Graphics)} call with
          - * {@link #setupPrint(double, double, int) setupPrint(..)} and {@link #releasePrint()} + * {@link #setupPrint(double, double, int, int, int) setupPrint(..)} and {@link #releasePrint()} * on all {@link AWTPrintLifecycle} elements in the {@link Container}.
          - * To minimize this burden, a user can use {@link Context#setupPrint(Container, double, double, int) Context.setupPrint(..)}: + * To minimize this burden, a user can use {@link Context#setupPrint(Container, double, double, int, int, int) Context.setupPrint(..)}: *

            *  Container cont;
            *  double scaleGLMatXY = 72.0/glDPI;
          @@ -75,7 +75,7 @@ import jogamp.nativewindow.awt.AWTMisc;
            */
           public interface AWTPrintLifecycle {
           
          -    public static final int DEFAULT_PRINT_TILE_SIZE = 512;
          +    public static final int DEFAULT_PRINT_TILE_SIZE = 1024;
               
               
               /**
          @@ -86,8 +86,10 @@ public interface AWTPrintLifecycle {
                * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels
                * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels
                * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples 
          +     * @param tileWidth custom tile width for {@link com.jogamp.opengl.util.TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default.
          +     * @param tileHeight custom tile height for {@link com.jogamp.opengl.util.TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default.
                */
          -    void setupPrint(double scaleMatX, double scaleMatY, int numSamples);
          +    void setupPrint(double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight);
               
               /**
                * Shall be called after {@link PrinterJob#print()}.
          @@ -98,7 +100,7 @@ public interface AWTPrintLifecycle {
               void releasePrint();
           
               /**
          -     * Convenient {@link AWTPrintLifecycle} context simplifying calling {@link AWTPrintLifecycle#setupPrint(double, double, int) setupPrint(..)}
          +     * Convenient {@link AWTPrintLifecycle} context simplifying calling {@link AWTPrintLifecycle#setupPrint(double, double, int, int, int) setupPrint(..)}
                * and {@link AWTPrintLifecycle#releasePrint()} on all {@link AWTPrintLifecycle} elements of a {@link Container}.
                * 

          * See Usage. @@ -110,14 +112,16 @@ public interface AWTPrintLifecycle { * See Usage. *

          * - * @param c container to be traversed through to perform {@link AWTPrintLifecycle#setupPrint(double, double, int) setupPrint(..)} on all {@link AWTPrintLifecycle} elements. + * @param c container to be traversed through to perform {@link AWTPrintLifecycle#setupPrint(double, double, int, int, int) setupPrint(..)} on all {@link AWTPrintLifecycle} elements. * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param tileWidth custom tile width for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. + * @param tileHeight custom tile height for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. * @return the context */ - public static Context setupPrint(Container c, double scaleMatX, double scaleMatY, int numSamples) { - final Context t = new Context(c, scaleMatX, scaleMatY, numSamples); + public static Context setupPrint(Container c, double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight) { + final Context t = new Context(c, scaleMatX, scaleMatY, numSamples, tileWidth, tileHeight); t.setupPrint(c); return t; } @@ -132,7 +136,7 @@ public interface AWTPrintLifecycle { } /** - * @return count of performed actions of last {@link #setupPrint(Container, double, double, int) setupPrint(..)} or {@link #releasePrint()}. + * @return count of performed actions of last {@link #setupPrint(Container, double, double, int, int, int) setupPrint(..)} or {@link #releasePrint()}. */ public int getCount() { return count; } @@ -140,12 +144,14 @@ public interface AWTPrintLifecycle { private final double scaleMatX; private final double scaleMatY; private final int numSamples; + private final int tileWidth; + private final int tileHeight; private int count; private final AWTMisc.ComponentAction setupAction = new AWTMisc.ComponentAction() { @Override public void run(Component c) { - ((AWTPrintLifecycle)c).setupPrint(scaleMatX, scaleMatY, numSamples); + ((AWTPrintLifecycle)c).setupPrint(scaleMatX, scaleMatY, numSamples, tileWidth, tileHeight); } }; private final AWTMisc.ComponentAction releaseAction = new AWTMisc.ComponentAction() { @Override @@ -153,11 +159,13 @@ public interface AWTPrintLifecycle { ((AWTPrintLifecycle)c).releasePrint(); } }; - private Context(Container c, double scaleMatX, double scaleMatY, int numSamples) { + private Context(Container c, double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight) { this.cont = c; this.scaleMatX = scaleMatX; this.scaleMatY = scaleMatY; this.numSamples = numSamples; + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; this.count = 0; } private void setupPrint(Container c) { diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 73b3bc368..767533d40 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -471,7 +471,6 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } private volatile boolean printActive = false; - private int printNumSamples = 0; private GLAnimatorControl printAnimator = null; private GLAutoDrawable printGLAD = null; private AWTTilePainter printAWTTiles = null; @@ -484,12 +483,11 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } @Override - public void setupPrint(double scaleMatX, double scaleMatY, int numSamples) { + public void setupPrint(double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight) { printActive = true; - printNumSamples = numSamples; final int componentCount = isOpaque() ? 3 : 4; final TileRenderer printRenderer = new TileRenderer(); - printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, DEBUG); + printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, numSamples, tileWidth, tileHeight, DEBUG); AWTEDTExecutor.singleton.invoke(getTreeLock(), true /* allowOnNonEDT */, true /* wait */, setupPrintOnEDT); } private final Runnable setupPrintOnEDT = new Runnable() { @@ -522,10 +520,18 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto printAnimator.remove(glad); } final GLCapabilities caps = (GLCapabilities)glad.getChosenGLCapabilities().cloneMutable(); - final int reqNumSamples = printNumSamples; - printNumSamples = AWTTilePainter.getNumSamples(reqNumSamples, caps); + final int printNumSamples = printAWTTiles.getNumSamples(caps); + GLDrawable printDrawable = printGLAD.getDelegatedDrawable(); + final boolean reqNewGLADSamples = printNumSamples != caps.getNumSamples(); + final boolean reqNewGLADSize = printAWTTiles.customTileWidth != -1 && printAWTTiles.customTileWidth != printDrawable.getWidth() || + printAWTTiles.customTileHeight != -1 && printAWTTiles.customTileHeight != printDrawable.getHeight(); + final boolean reqNewGLAD = !caps.getSampleBuffers(); // reqNewGLADSamples || reqNewGLADSize ; if( DEBUG ) { - System.err.println("AWT print.setup: canvasSize "+getWidth()+"x"+getWidth()+", scaleMat "+printAWTTiles.scaleMatX+" x "+printAWTTiles.scaleMatY+", numSamples "+reqNumSamples+" -> "+printNumSamples+", printAnimator "+printAnimator); + System.err.println("AWT print.setup: reqNewGLAD "+reqNewGLAD+"[ samples "+reqNewGLADSamples+", size "+reqNewGLADSize+"], "+ + ", drawableSize "+printDrawable.getWidth()+"x"+printDrawable.getHeight()+ + ", customTileSize "+printAWTTiles.customTileWidth+"x"+printAWTTiles.customTileHeight+ + ", scaleMat "+printAWTTiles.scaleMatX+" x "+printAWTTiles.scaleMatY+ + ", numSamples "+printAWTTiles.customNumSamples+" -> "+printNumSamples+", printAnimator "+printAnimator); } if( caps.getSampleBuffers() ) { // Bug 830: swapGLContextAndAllGLEventListener and onscreen MSAA w/ NV/GLX @@ -538,10 +544,13 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto caps.setNumSamples(printNumSamples); } final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); - printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, DEFAULT_PRINT_TILE_SIZE, DEFAULT_PRINT_TILE_SIZE, null); + printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, + printAWTTiles.customTileWidth != -1 ? printAWTTiles.customTileWidth : DEFAULT_PRINT_TILE_SIZE, + printAWTTiles.customTileHeight != -1 ? printAWTTiles.customTileHeight : DEFAULT_PRINT_TILE_SIZE, + null); GLDrawableUtil.swapGLContextAndAllGLEventListener(glad, printGLAD); + printDrawable = printGLAD.getDelegatedDrawable(); } - final GLDrawable printDrawable = printGLAD.getDelegatedDrawable(); printAWTTiles.setIsGLOriented(printGLAD.isGLOriented()); printAWTTiles.renderer.setTileSize(printDrawable.getWidth(), printDrawable.getHeight(), 0); printAWTTiles.renderer.attachAutoDrawable(printGLAD); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/OffscreenPrintable.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/OffscreenPrintable.java index bd526419c..78fdde3ee 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/OffscreenPrintable.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/OffscreenPrintable.java @@ -45,6 +45,7 @@ import javax.imageio.ImageIO; import com.jogamp.common.util.awt.AWTEDTExecutor; import com.jogamp.nativewindow.awt.DirectDataBufferInt; +import com.jogamp.opengl.util.TileRenderer; /** * {@link Printable} implementation using NIO {@link DirectDataBufferInt} {@link BufferedImage} @@ -64,11 +65,13 @@ public class OffscreenPrintable extends PrintableBase implements Printable { * @param printContainer * @param printDPI * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param tileWidth custom tile width for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. + * @param tileHeight custom tile height for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. * @param imageType AWT BufferedImage type (must be one of the integer types) * @param pngFilename TODO */ - public OffscreenPrintable(PrinterJob job, Container printContainer, int printDPI, int numSamples, int imageType, String pngFilename) { - super(job, printContainer, printDPI, numSamples); + public OffscreenPrintable(PrinterJob job, Container printContainer, int printDPI, int numSamples, int tileWidth, int tileHeight, int imageType, String pngFilename) { + super(job, printContainer, printDPI, numSamples, tileWidth, tileHeight); this.imageType = imageType; this.pngFilename = pngFilename; } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/OnscreenPrintable.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/OnscreenPrintable.java index 7e8bac295..6f73ef2b4 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/OnscreenPrintable.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/OnscreenPrintable.java @@ -39,6 +39,7 @@ import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import com.jogamp.common.util.awt.AWTEDTExecutor; +import com.jogamp.opengl.util.TileRenderer; /** *
          Scaling of Frame and GL content
          @@ -66,11 +67,14 @@ public class OnscreenPrintable extends PrintableBase implements Printable { * @param printContainer * @param printDPI * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param tileWidth custom tile width for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. + * @param tileHeight custom tile height for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. */ - public OnscreenPrintable(PrinterJob job, Container printContainer, int printDPI, int numSamples) { - super(job, printContainer, printDPI, numSamples); + public OnscreenPrintable(PrinterJob job, Container printContainer, int printDPI, int numSamples, int tileWidth, int tileHeight) { + super(job, printContainer, printDPI, numSamples, tileWidth, tileHeight); } + @Override public int print(Graphics g, PageFormat pf, int page) throws PrinterException { if (page > 0) { // We have only one page, and 'page' is zero-based diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/PrintableBase.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/PrintableBase.java index 830ded960..dd9de60c3 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/PrintableBase.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/PrintableBase.java @@ -33,6 +33,7 @@ import java.awt.print.PrinterJob; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; +import com.jogamp.opengl.util.TileRenderer; /** * Base {@link Printable} implementation class. @@ -58,6 +59,7 @@ public abstract class PrintableBase implements Printable { public final Container cont; public final int dpi; public final int numSamples; + public final int tileWidth, tileHeight; protected final RecursiveLock lockPrinting = LockFactory.createRecursiveLock(); /** @@ -66,12 +68,16 @@ public abstract class PrintableBase implements Printable { * @param printContainer * @param printDPI * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param tileWidth custom tile width for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. + * @param tileHeight custom tile height for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. */ - public PrintableBase(PrinterJob job, Container printContainer, int printDPI, int numSamples) { + public PrintableBase(PrinterJob job, Container printContainer, int printDPI, int numSamples, int tileWidth, int tileHeight) { this.job = job; this.cont = printContainer; this.dpi = printDPI; this.numSamples = numSamples; + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; } /** Wait for idle .. simply acquiring all locks and releasing them. */ diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java index 4883df501..30e0ba4e6 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsAWT.java @@ -116,15 +116,15 @@ public class TestTiledPrintingGearsAWT extends TiledPrintingAWTBase { final ActionListener print72DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 72, 0); + doPrintManual(frame, 72, 0, -1, -1); } }; final ActionListener print300DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 300, -1); + doPrintManual(frame, 300, -1, -1, -1); } }; final ActionListener print600DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 600, -1); + doPrintManual(frame, 600, -1, -1, -1); } }; final Button print72DPIButton = new Button("72dpi"); print72DPIButton.addActionListener(print72DPIAction); @@ -178,36 +178,41 @@ public class TestTiledPrintingGearsAWT extends TiledPrintingAWTBase { if( !printDone ) { printDone = true; { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 0, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 0, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 8, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 8, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, true /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, 2048, 2048, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, -1, -1, true /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, true/* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, -1, -1, false /* resizeWithinPrint */); + waitUntilPrintJobsIdle(p); + } + { + // No AA needed for 150 dpi and greater :) + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, -1, -1, true/* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } if( allow600dpi ) { // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 600, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 600, -1, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java index a256d964f..ec1d7b1d6 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsNewtAWT.java @@ -121,15 +121,15 @@ public class TestTiledPrintingGearsNewtAWT extends TiledPrintingAWTBase { final ActionListener print72DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 72, 0); + doPrintManual(frame, 72, 0, -1, -1); } }; final ActionListener print300DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 300, -1); + doPrintManual(frame, 300, -1, -1, -1); } }; final ActionListener print600DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 600, -1); + doPrintManual(frame, 600, -1, -1, -1); } }; final Button print72DPIButton = new Button("72dpi"); print72DPIButton.addActionListener(print72DPIAction); @@ -183,36 +183,41 @@ public class TestTiledPrintingGearsNewtAWT extends TiledPrintingAWTBase { if( !printDone ) { printDone = true; { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 0, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 0, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 8, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 8, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, true /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, 2048, 2048, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, -1, -1, true /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, true /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, -1, -1, false /* resizeWithinPrint */); + waitUntilPrintJobsIdle(p); + } + { + // No AA needed for 150 dpi and greater :) + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, -1, -1, true /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } if( allow600dpi ) { // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 600, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 600, -1, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java index f1759798b..72cb219ab 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT.java @@ -152,15 +152,15 @@ public class TestTiledPrintingGearsSwingAWT extends TiledPrintingAWTBase { final ActionListener print72DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 72, 0); + doPrintManual(frame, 72, 0, -1, -1); } }; final ActionListener print300DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 300, -1); + doPrintManual(frame, 300, -1, -1, -1); } }; final ActionListener print600DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 600, -1); + doPrintManual(frame, 600, -1, -1, -1); } }; final Button print72DPIButton = new Button("72dpi"); print72DPIButton.addActionListener(print72DPIAction); @@ -217,51 +217,56 @@ public class TestTiledPrintingGearsSwingAWT extends TiledPrintingAWTBase { if( !printDone ) { printDone = true; { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 0, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 0, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 8, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 72, 8, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, true /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, 2048, 2048, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 150, -1, -1, -1, true /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB /* offscreen-type */, 150, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_RGB /* offscreen-type */, 150, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB /* offscreen-type */, 150, -1, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_BGR /* offscreen-type */, 150, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_RGB /* offscreen-type */, 150, -1, -1, -1, false /* resizeWithinPrint */); + waitUntilPrintJobsIdle(p); + } + { + // No AA needed for 150 dpi and greater :) + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_BGR /* offscreen-type */, 150, -1, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, true /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, BufferedImage.TYPE_INT_ARGB_PRE /* offscreen-type */, 150, -1, -1, -1, true /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } if( allow600dpi ) { // No AA needed for 300 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 600, -1, false /* resizeWithinPrint */); + final PrintableBase p = doPrintAuto(frame, PageFormat.LANDSCAPE, null, -1 /* offscreen-type */, 600, -1, -1, -1, false /* resizeWithinPrint */); waitUntilPrintJobsIdle(p); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT2.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT2.java index d18def075..2d4973d6b 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT2.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingGearsSwingAWT2.java @@ -142,15 +142,15 @@ public class TestTiledPrintingGearsSwingAWT2 extends TiledPrintingAWTBase { final ActionListener print72DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 72, 0); + doPrintManual(frame, 72, 0, -1, -1); } }; final ActionListener print150DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 150, -1); + doPrintManual(frame, 150, -1, -1, -1); } }; final ActionListener print300DPIAction = new ActionListener() { public void actionPerformed(ActionEvent e) { - doPrintManual(frame, 300, -1); + doPrintManual(frame, 300, -1, -1, -1); } }; final Button print72DPIButton = new Button("72dpi"); print72DPIButton.addActionListener(print72DPIAction); @@ -220,7 +220,7 @@ public class TestTiledPrintingGearsSwingAWT2 extends TiledPrintingAWTBase { printDone = true; { // No AA needed for 150 dpi and greater :) - final PrintableBase p = doPrintAuto(frame, PageFormat.PORTRAIT, null, -1 /* offscreen-type */, 150, -1, false); + final PrintableBase p = doPrintAuto(frame, PageFormat.PORTRAIT, null, -1 /* offscreen-type */, 150, -1, -1, -1, false); waitUntilPrintJobsIdle(p); } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java index 0fe08ebc2..b51bfae87 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TestTiledPrintingNIOImageSwingAWT.java @@ -128,7 +128,7 @@ public class TestTiledPrintingNIOImageSwingAWT extends UITestCase { g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // frame.paintAll(g2d); - final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(frame, 1.0/scaleComp72, 1.0/scaleComp72, 0); + final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(frame, 1.0/scaleComp72, 1.0/scaleComp72, 0, -1, -1); try { frame.printAll(g2d); } finally { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java index e6179aa95..4e9d4bdbe 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/tile/TiledPrintingAWTBase.java @@ -51,11 +51,13 @@ import jogamp.nativewindow.awt.AWTMisc; import org.junit.Assert; +import com.jogamp.common.os.Platform; import com.jogamp.common.util.awt.AWTEDTExecutor; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.nativewindow.awt.AWTPrintLifecycle; import com.jogamp.opengl.test.junit.util.UITestCase; +import com.jogamp.opengl.util.TileRenderer; /** * Base unit test class implementing @@ -79,9 +81,12 @@ public abstract class TiledPrintingAWTBase extends UITestCase { * @param offscrnImageType if < 0 onscreen, otherwise integer BufferedImage type * @param dpi * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param tileWidth custom tile width for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. + * @param tileHeight custom tile height for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. * @param resizeWithinPrintTest TODO */ - public PrintableBase doPrintAuto(Container cont, int pOrientation, Paper paper, int offscrnImageType, int dpi, int numSamples, boolean resizeWithinPrintTest) { + public PrintableBase doPrintAuto(Container cont, int pOrientation, Paper paper, + int offscrnImageType, int dpi, int numSamples, int tileWidth, int tileHeight, boolean resizeWithinPrintTest) { lock.lock(); try { final PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); @@ -98,12 +103,13 @@ public abstract class TiledPrintingAWTBase extends UITestCase { StreamPrintServiceFactory[] factories = PrinterJob.lookupStreamPrintServices(pdfMimeType); if (factories.length > 0) { - final String fname = getPrintFilename(offscrnImageType, dpi, numSamples, "pdf", resizeWithinPrintTest); + final String fname = getPrintFilename(offscrnImageType, dpi, numSamples, tileWidth, tileHeight, "pdf", resizeWithinPrintTest); System.err.println("doPrint: dpi "+dpi+", "+fname); FileOutputStream outstream; try { outstream = new FileOutputStream(fname); - return doPrintAutoImpl(cont, pj, factories[0].getPrintService(outstream), pOrientation, paper, offscrnImageType, dpi, numSamples, resizeWithinPrintTest); + return doPrintAutoImpl(cont, pj, factories[0].getPrintService(outstream), pOrientation, paper, + offscrnImageType, dpi, numSamples, tileWidth, tileHeight, resizeWithinPrintTest); } catch (FileNotFoundException e) { Assert.assertNull("Unexpected exception", e); } @@ -112,12 +118,12 @@ public abstract class TiledPrintingAWTBase extends UITestCase { factories = PrinterJob.lookupStreamPrintServices(psMimeType); if (factories.length > 0) { - final String fname = getPrintFilename(offscrnImageType, dpi, numSamples, "ps", resizeWithinPrintTest); + final String fname = getPrintFilename(offscrnImageType, dpi, numSamples, tileWidth, tileHeight, "ps", resizeWithinPrintTest); System.err.println("doPrint: dpi "+dpi+", "+fname); FileOutputStream outstream; try { outstream = new FileOutputStream(fname); - return doPrintAutoImpl(cont, pj, factories[0].getPrintService(outstream), pOrientation, paper, offscrnImageType, dpi, numSamples, resizeWithinPrintTest); + return doPrintAutoImpl(cont, pj, factories[0].getPrintService(outstream), pOrientation, paper, offscrnImageType, dpi, numSamples, tileWidth, tileHeight, resizeWithinPrintTest); } catch (FileNotFoundException e) { Assert.assertNull("Unexpected exception", e); } @@ -128,17 +134,17 @@ public abstract class TiledPrintingAWTBase extends UITestCase { lock.unlock(); } } - private String getPrintFilename(int offscrnImageType, int dpi, int numSamples, String suffix, boolean resizeWithinPrintTest) { + private String getPrintFilename(int offscrnImageType, int dpi, int numSamples, int tileWidth, int tileHeight, String suffix, boolean resizeWithinPrintTest) { final int maxSimpleTestNameLen = getMaxTestNameLen()+getClass().getSimpleName().length()+1; final String simpleTestName = getSimpleTestName("."); final String onoffscrn = 0 > offscrnImageType ? "on_screen" : "offscrn_"+offscrnImageType; final String aa = 0 <= numSamples ? "aa"+numSamples : "aaN"; - return String.format("%-"+maxSimpleTestNameLen+"s-n%04d-%s-dpi%03d-%s-resize%d.%s", - simpleTestName, printCount, onoffscrn, dpi, aa, resizeWithinPrintTest?1:0, suffix).replace(' ', '_'); + return String.format("%-"+maxSimpleTestNameLen+"s-n%04d-%s-dpi%03d-%s-tSz%04dx%04d-resize%d.%s", + simpleTestName, printCount, onoffscrn, dpi, aa, tileWidth, tileHeight, resizeWithinPrintTest?1:0, suffix).replace(' ', '_'); } private PrintableBase doPrintAutoImpl(Container cont, PrinterJob job, StreamPrintService ps, int pOrientation, Paper paper, - int offscrnImageType, int dpi, int numSamples, boolean resizeWithinPrintTest) { + int offscrnImageType, int dpi, int numSamples, int tileWidth, int tileHeight, boolean resizeWithinPrintTest) { try { PageFormat pageFormat = job.defaultPage(); if( null != paper ) { @@ -152,9 +158,9 @@ public abstract class TiledPrintingAWTBase extends UITestCase { job.setPrintService(ps); final PrintableBase printable; if( 0 < offscrnImageType ) { - printable = new OffscreenPrintable(job, cont, dpi, numSamples, offscrnImageType, getPrintFilename(offscrnImageType, dpi, numSamples, "png", resizeWithinPrintTest)); + printable = new OffscreenPrintable(job, cont, dpi, numSamples, tileWidth, tileHeight, offscrnImageType, getPrintFilename(offscrnImageType, dpi, numSamples, tileWidth, tileHeight, "png", resizeWithinPrintTest)); } else { - printable = new OnscreenPrintable(job, cont, dpi, numSamples); + printable = new OnscreenPrintable(job, cont, dpi, numSamples, tileWidth, tileHeight); } printable.job.setPrintable(printable, pageFormat); doPrintImpl(printable, resizeWithinPrintTest); @@ -166,15 +172,16 @@ public abstract class TiledPrintingAWTBase extends UITestCase { } /** - * * @param cont * @param dpi * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param tileWidth custom tile width for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. + * @param tileHeight custom tile height for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. */ - public PrintableBase doPrintManual(Container cont, int dpi, int numSamples) { + public PrintableBase doPrintManual(Container cont, int dpi, int numSamples, int tileWidth, int tileHeight) { lock.lock(); try { - final OnscreenPrintable printable = new OnscreenPrintable(PrinterJob.getPrinterJob(), cont, dpi, numSamples); + final OnscreenPrintable printable = new OnscreenPrintable(PrinterJob.getPrinterJob(), cont, dpi, numSamples, tileWidth, tileHeight); printable.job.setPrintable(printable); boolean ok = printable.job.printDialog(); if (ok) { @@ -207,10 +214,13 @@ public abstract class TiledPrintingAWTBase extends UITestCase { final double scaleGLMatXY = 72.0 / printable.dpi; System.err.println("PRINTable: "+printable.getClass().getSimpleName()); System.err.println("PRINT DPI: "+printable.dpi+", AA "+printable.numSamples+", scaleGL "+scaleGLMatXY); - final AWTPrintLifecycle.Context ctx = AWTPrintLifecycle.Context.setupPrint(printable.cont, scaleGLMatXY, scaleGLMatXY, printable.numSamples); + final AWTPrintLifecycle.Context ctx = + AWTPrintLifecycle.Context.setupPrint(printable.cont, scaleGLMatXY, scaleGLMatXY, + printable.numSamples, printable.tileWidth, printable.tileHeight); System.err.println("PRINT AWTPrintLifecycle.setup.count "+ctx.getCount()); final int w = printable.cont.getWidth(); final int h = printable.cont.getHeight(); + final long t0 = Platform.currentTimeMillis(); try { AWTEDTExecutor.singleton.invoke(true, new Runnable() { public void run() { @@ -230,6 +240,8 @@ public abstract class TiledPrintingAWTBase extends UITestCase { } }); } finally { ctx.releasePrint(); + final long td = Platform.currentTimeMillis() - t0; + System.err.println("PRINT Duration "+td+" ms"); if( resizeWithinPrintTest ) { AWTEDTExecutor.singleton.invoke(true, new Runnable() { public void run() { -- cgit v1.2.3 From b831ebadcaea1eea7370f7ec0bffc59eaba7a5ba Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 16 Oct 2013 14:28:27 +0200 Subject: Add efficient set(..all..) to Dimension, Insets, Point and Rectangle of NativeWindow's util types. --- .../classes/com/jogamp/opengl/util/TileRenderer.java | 9 +++------ .../classes/com/jogamp/opengl/util/TileRendererBase.java | 3 +-- .../classes/com/jogamp/nativewindow/awt/JAWTWindow.java | 12 +++--------- .../classes/javax/media/nativewindow/util/Dimension.java | 16 ++++++++++------ .../classes/javax/media/nativewindow/util/Insets.java | 11 +++++++---- .../classes/javax/media/nativewindow/util/Point.java | 11 ++++++----- .../classes/javax/media/nativewindow/util/Rectangle.java | 11 +++++++---- .../classes/jogamp/nativewindow/macosx/OSXUtil.java | 3 +-- src/newt/classes/com/jogamp/newt/MonitorDevice.java | 5 +---- src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java | 3 +-- src/newt/classes/jogamp/newt/OffscreenWindow.java | 3 +-- src/newt/classes/jogamp/newt/ScreenImpl.java | 5 +---- .../classes/jogamp/newt/driver/awt/WindowDriver.java | 7 ++----- .../classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java | 5 +---- .../jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java | 5 +---- .../jogamp/newt/driver/intel/gdl/ScreenDriver.java | 5 +---- src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java | 5 +---- .../classes/jogamp/newt/driver/windows/ScreenDriver.java | 5 +---- .../classes/jogamp/newt/driver/x11/ScreenDriver.java | 5 +---- 19 files changed, 50 insertions(+), 79 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/opengl/util/TileRenderer.java b/src/jogl/classes/com/jogamp/opengl/util/TileRenderer.java index deab8bc3e..999db77a9 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/TileRenderer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/TileRenderer.java @@ -188,8 +188,7 @@ public class TileRenderer extends TileRendererBase { if( null == imageClippingDim ) { imageClippingDim = new Dimension(width, height); } else { - imageClippingDim.setWidth(width); - imageClippingDim.setHeight(height); + imageClippingDim.set(width, height); } reset(); } @@ -245,10 +244,8 @@ public class TileRenderer extends TileRendererBase { throw new IllegalArgumentException("Tile size must be > 0x0 minus 2*border"); } tileBorder = border; - tileSize.setWidth( width ); - tileSize.setHeight( height ); - tileSizeNB.setWidth( width - 2 * border ); - tileSizeNB.setHeight( height - 2 * border ); + tileSize.set( width, height ); + tileSizeNB.set( width - 2 * border, height - 2 * border ); reset(); } diff --git a/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java b/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java index d6c36aa14..0553d5673 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java +++ b/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java @@ -286,8 +286,7 @@ public abstract class TileRendererBase { * @param height The height of the final image */ public void setImageSize(int width, int height) { - imageSize.setWidth(width); - imageSize.setHeight(height); + imageSize.set(width, height); } /** @see #setImageSize(int, int) */ diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 6e198d961..38a46f214 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -243,17 +243,11 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, System.err.println("JAWTWindow.updateBounds: "+bounds+" -> "+jb); // Thread.dumpStack(); } - bounds.setX(jawtBounds.getX()); - bounds.setY(jawtBounds.getY()); - bounds.setWidth(jawtBounds.getWidth()); - bounds.setHeight(jawtBounds.getHeight()); + bounds.set(jawtBounds.getX(), jawtBounds.getY(), jawtBounds.getWidth(), jawtBounds.getHeight()); if(component instanceof Container) { - java.awt.Insets contInsets = ((Container)component).getInsets(); - insets.setLeftWidth(contInsets.left); - insets.setRightWidth(contInsets.right); - insets.setTopHeight(contInsets.top); - insets.setBottomHeight(contInsets.bottom); + final java.awt.Insets contInsets = ((Container)component).getInsets(); + insets.set(contInsets.left, contInsets.right, contInsets.top, contInsets.bottom); } } return changed; diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java index b52414146..17b4930c5 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java @@ -58,22 +58,26 @@ public class Dimension implements Cloneable, DimensionImmutable { } @Override - public int getWidth() { return width; } + public final int getWidth() { return width; } @Override - public int getHeight() { return height; } + public final int getHeight() { return height; } - public void setWidth(int width) { + public final void set(int width, int height) { + this.width = width; + this.height = height; + } + public final void setWidth(int width) { this.width = width; } - public void setHeight(int height) { + public final void setHeight(int height) { this.height = height; } - public Dimension scale(int s) { + public final Dimension scale(int s) { width *= s; height *= s; return this; } - public Dimension add(Dimension pd) { + public final Dimension add(Dimension pd) { width += pd.width ; height += pd.height ; return this; diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java index f22668f55..942c12c2b 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java @@ -70,10 +70,13 @@ public class Insets implements Cloneable, InsetsImmutable { @Override public final int getTotalHeight() { return t + b; } - public void setLeftWidth(int left) { l = left; } - public void setRightWidth(int right) { r = right; } - public void setTopHeight(int top) { t = top; } - public void setBottomHeight(int bottom) { b = bottom; } + public final void set(int left, int right, int top, int bottom) { + l = left; r = right; t = top; b = bottom; + } + public final void setLeftWidth(int left) { l = left; } + public final void setRightWidth(int right) { r = right; } + public final void setTopHeight(int top) { t = top; } + public final void setBottomHeight(int bottom) { b = bottom; } @Override public boolean equals(Object obj) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java index a30d3030e..4c233bb16 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java @@ -99,22 +99,23 @@ public class Point implements Cloneable, PointImmutable { return new String( x + " / " + y ); } - public void setX(int x) { this.x = x; } - public void setY(int y) { this.y = y; } + public final void set(int x, int y) { this.x = x; this.y = y; } + public final void setX(int x) { this.x = x; } + public final void setY(int y) { this.y = y; } - public Point translate(Point pd) { + public final Point translate(Point pd) { x += pd.x ; y += pd.y ; return this; } - public Point translate(int dx, int dy) { + public final Point translate(int dx, int dy) { x += dx ; y += dy ; return this; } - public Point scale(int sx, int sy) { + public final Point scale(int sx, int sy) { x *= sx ; y *= sy ; return this; diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java index 7576f4ec7..bbbfa2932 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java @@ -68,6 +68,12 @@ public class Rectangle implements Cloneable, RectangleImmutable { @Override public final int getHeight() { return height; } + public final void set(int x, int y, int width, int height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } public final void setX(int x) { this.x = x; } public final void setY(int y) { this.y = y; } public final void setWidth(int width) { this.width = width; } @@ -100,10 +106,7 @@ public class Rectangle implements Cloneable, RectangleImmutable { y1 = Math.min(y1, vp.getY()); y2 = Math.max(y2, vp.getY() + vp.getHeight()); } - setX(x1); - setY(y1); - setWidth(x2 - x1); - setHeight(y2 - y1); + set(x1, y1, x2 - x1, y2 - y1); return this; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index dc32bd58c..0d498fa54 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -113,8 +113,7 @@ public class OSXUtil implements ToolkitProperties { if(topLevel) { // top-level position -> client window position final Insets insets = GetInsets(windowOrView); - los.setX(los.getX() + insets.getLeftWidth()); - los.setY(los.getY() + insets.getTopHeight()); + los.set(los.getX() + insets.getLeftWidth(), los.getY() + insets.getTopHeight()); } return los; } diff --git a/src/newt/classes/com/jogamp/newt/MonitorDevice.java b/src/newt/classes/com/jogamp/newt/MonitorDevice.java index 8bc7f40e3..42ac34240 100644 --- a/src/newt/classes/com/jogamp/newt/MonitorDevice.java +++ b/src/newt/classes/com/jogamp/newt/MonitorDevice.java @@ -183,10 +183,7 @@ public abstract class MonitorDevice { y1 = Math.min(y1, vp.getY()); y2 = Math.max(y2, vp.getY() + vp.getHeight()); } - result.setX(x1); - result.setY(y1); - result.setWidth(x2 - x1); - result.setHeight(y2 - y1); + result.set(x1, y1, x2 - x1, y2 - y1); return result; } diff --git a/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java index 2fa83e0e2..a2135273b 100644 --- a/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java +++ b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java @@ -497,8 +497,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { if( isOSX ) { final Point los = OSXUtil.GetLocationOnScreen(nativeWindowHandle, false, 0, 0); // top-level position -> client window position - los.setX(los.getX() + insets.getLeftWidth()); - los.setY(los.getY() + insets.getTopHeight()); + los.set(los.getX() + insets.getLeftWidth(), los.getY() + insets.getTopHeight()); if(null!=point) { return point.translate(los); } else { diff --git a/src/newt/classes/jogamp/newt/OffscreenWindow.java b/src/newt/classes/jogamp/newt/OffscreenWindow.java index 911d371d5..0a302d76b 100644 --- a/src/newt/classes/jogamp/newt/OffscreenWindow.java +++ b/src/newt/classes/jogamp/newt/OffscreenWindow.java @@ -132,8 +132,7 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { @Override public Point getLocationOnScreen(Point storage) { if(null!=storage) { - storage.setX(0); - storage.setY(0); + storage.set(0, 0); return storage; } return new Point(0,0); diff --git a/src/newt/classes/jogamp/newt/ScreenImpl.java b/src/newt/classes/jogamp/newt/ScreenImpl.java index 5ffa2ebbf..7068d7464 100644 --- a/src/newt/classes/jogamp/newt/ScreenImpl.java +++ b/src/newt/classes/jogamp/newt/ScreenImpl.java @@ -285,10 +285,7 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { */ protected void updateVirtualScreenOriginAndSize() { if(null != usrSize ) { - vOriginSize.setX(0); - vOriginSize.setY(0); - vOriginSize.setWidth(usrSize.getWidth()); - vOriginSize.setHeight(usrSize.getHeight()); + vOriginSize.set(0, 0, usrSize.getWidth(), usrSize.getHeight()); if(DEBUG) { System.err.println("Update user virtual screen viewport @ "+Thread.currentThread().getName()+": "+vOriginSize); } diff --git a/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java index c45a5ae3b..77daa556f 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java @@ -177,11 +177,8 @@ public class WindowDriver extends WindowImpl { } protected void updateInsetsImpl(javax.media.nativewindow.util.Insets insets) { - Insets contInsets = awtContainer.getInsets(); - insets.setLeftWidth(contInsets.left); - insets.setRightWidth(contInsets.right); - insets.setTopHeight(contInsets.top); - insets.setBottomHeight(contInsets.bottom); + final Insets contInsets = awtContainer.getInsets(); + insets.set(contInsets.left, contInsets.right, contInsets.top, contInsets.bottom); } private void setCanvasSizeImpl(int width, int height) { diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java index afaedffe3..abe2908b0 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java @@ -101,10 +101,7 @@ public class ScreenDriver extends jogamp.newt.ScreenImpl { } protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { - vOriginSize.setX(0); - vOriginSize.setY(0); - vOriginSize.setWidth(fixedWidth); // FIXME - vOriginSize.setHeight(fixedHeight); // FIXME + vOriginSize.set(0, 0, fixedWidth, fixedHeight); // FIXME } //---------------------------------------------------------------------- diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java index f7973def8..be99052d7 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java @@ -95,10 +95,7 @@ public class ScreenDriver extends ScreenImpl { @Override protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { - vOriginSize.setX(0); - vOriginSize.setY(0); - vOriginSize.setWidth(cachedWidth); - vOriginSize.setHeight(cachedHeight); + vOriginSize.set(0, 0, cachedWidth, cachedHeight); } /** Called from {@link #initNative()}. */ diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java index 4c47eb0d8..27b776562 100644 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java @@ -103,10 +103,7 @@ public class ScreenDriver extends jogamp.newt.ScreenImpl { } protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { - vOriginSize.setX(0); - vOriginSize.setY(0); - vOriginSize.setWidth(cachedWidth); - vOriginSize.setHeight(cachedHeight); + vOriginSize.set(0, 0, cachedWidth, cachedHeight); } //---------------------------------------------------------------------- diff --git a/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java index dc87c3c08..f893275ca 100644 --- a/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java @@ -99,10 +99,7 @@ public class ScreenDriver extends ScreenImpl { } protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { - vOriginSize.setX(0); - vOriginSize.setY(0); - vOriginSize.setWidth(cachedWidth); - vOriginSize.setHeight(cachedHeight); + vOriginSize.set(0, 0, cachedWidth, cachedHeight); } protected void sizeChanged(int w, int h) { diff --git a/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java index 342829691..621091320 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java @@ -155,10 +155,7 @@ public class ScreenDriver extends ScreenImpl { @Override protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { - vOriginSize.setX(getVirtualOriginX0()); - vOriginSize.setY(getVirtualOriginY0()); - vOriginSize.setWidth(getVirtualWidthImpl0()); - vOriginSize.setHeight(getVirtualHeightImpl0()); + vOriginSize.set(getVirtualOriginX0(), getVirtualOriginY0(), getVirtualWidthImpl0(), getVirtualHeightImpl0()); } // Native calls diff --git a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java index f37556dd7..c01d899f8 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java @@ -237,10 +237,7 @@ public class ScreenDriver extends ScreenImpl { } else */ { runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public Object run(long dpy) { - vOriginSize.setX(0); - vOriginSize.setY(0); - vOriginSize.setWidth(getWidth0(dpy, screen_idx)); - vOriginSize.setHeight(getHeight0(dpy, screen_idx)); + vOriginSize.set(0, 0, getWidth0(dpy, screen_idx), getHeight0(dpy, screen_idx)); return null; } } ); if( DEBUG ) { -- cgit v1.2.3 From 5e9c02bce7b241a0bf95c8abca9a91cd25e51ed3 Mon Sep 17 00:00:00 2001 From: Harvey Harrison Date: Thu, 17 Oct 2013 22:27:27 -0700 Subject: jogl: remove all trailing whitespace Signed-off-by: Harvey Harrison --- .../com/jogamp/audio/windows/waveout/Audio.java | 10 +- .../com/jogamp/audio/windows/waveout/Mixer.java | 12 +- .../jogamp/audio/windows/waveout/SoundBuffer.java | 10 +- .../com/jogamp/audio/windows/waveout/Track.java | 12 +- .../com/jogamp/audio/windows/waveout/Vec3f.java | 10 +- .../gluegen/opengl/BuildComposablePipeline.java | 18 +- .../jogamp/gluegen/opengl/BuildStaticGLInfo.java | 38 +- .../com/jogamp/gluegen/opengl/GLConfiguration.java | 28 +- .../com/jogamp/gluegen/opengl/GLEmitter.java | 34 +- .../gluegen/opengl/GLJavaMethodBindingEmitter.java | 16 +- .../jogamp/gluegen/opengl/ant/StaticGLGenTask.java | 72 +- .../opengl/nativesig/NativeSignatureEmitter.java | 18 +- .../NativeSignatureJavaMethodBindingEmitter.java | 26 +- .../gluegen/runtime/opengl/GLNameResolver.java | 20 +- .../runtime/opengl/GLProcAddressResolver.java | 10 +- .../com/jogamp/graph/curve/OutlineShape.java | 124 ++-- .../classes/com/jogamp/graph/curve/Region.java | 68 +- .../com/jogamp/graph/curve/opengl/GLRegion.java | 42 +- .../jogamp/graph/curve/opengl/RegionRenderer.java | 24 +- .../com/jogamp/graph/curve/opengl/RenderState.java | 32 +- .../com/jogamp/graph/curve/opengl/Renderer.java | 84 +-- .../jogamp/graph/curve/opengl/TextRenderer.java | 60 +- .../com/jogamp/graph/curve/tess/Triangulation.java | 2 +- .../com/jogamp/graph/curve/tess/Triangulator.java | 12 +- src/jogl/classes/com/jogamp/graph/font/Font.java | 34 +- .../classes/com/jogamp/graph/font/FontFactory.java | 20 +- .../classes/com/jogamp/graph/font/FontSet.java | 16 +- .../classes/com/jogamp/graph/geom/Outline.java | 36 +- .../classes/com/jogamp/graph/geom/Triangle.java | 10 +- src/jogl/classes/com/jogamp/graph/geom/Vertex.java | 22 +- .../com/jogamp/graph/geom/opengl/SVertex.java | 40 +- src/jogl/classes/com/jogamp/opengl/FBObject.java | 786 ++++++++++----------- .../com/jogamp/opengl/GLAutoDrawableDelegate.java | 56 +- .../com/jogamp/opengl/GLEventListenerState.java | 118 ++-- .../classes/com/jogamp/opengl/GLExtensions.java | 22 +- .../com/jogamp/opengl/GLRendererQuirks.java | 64 +- .../classes/com/jogamp/opengl/GLStateKeeper.java | 38 +- .../opengl/GenericGLCapabilitiesChooser.java | 10 +- .../classes/com/jogamp/opengl/JoglVersion.java | 40 +- .../opengl/cg/CgDynamicLibraryBundleInfo.java | 24 +- .../classes/com/jogamp/opengl/cg/CgException.java | 14 +- .../classes/com/jogamp/opengl/math/FixedPoint.java | 12 +- .../classes/com/jogamp/opengl/math/FloatUtil.java | 88 +-- .../classes/com/jogamp/opengl/math/Quaternion.java | 38 +- .../classes/com/jogamp/opengl/math/VectorUtil.java | 46 +- .../com/jogamp/opengl/math/Vert2fImmutable.java | 4 +- .../com/jogamp/opengl/math/geom/AABBox.java | 84 +-- .../com/jogamp/opengl/math/geom/Frustum.java | 82 +-- .../classes/com/jogamp/opengl/swt/GLCanvas.java | 134 ++-- .../com/jogamp/opengl/util/AWTAnimatorImpl.java | 10 +- .../classes/com/jogamp/opengl/util/Animator.java | 34 +- .../com/jogamp/opengl/util/AnimatorBase.java | 106 +-- .../jogamp/opengl/util/DefaultAnimatorImpl.java | 10 +- .../com/jogamp/opengl/util/FPSAnimator.java | 66 +- .../com/jogamp/opengl/util/GLArrayDataClient.java | 80 +-- .../jogamp/opengl/util/GLArrayDataEditable.java | 28 +- .../com/jogamp/opengl/util/GLArrayDataServer.java | 122 ++-- .../com/jogamp/opengl/util/GLArrayDataWrapper.java | 112 +-- .../classes/com/jogamp/opengl/util/GLBuffers.java | 388 +++++----- .../com/jogamp/opengl/util/GLDrawableUtil.java | 50 +- .../com/jogamp/opengl/util/GLPixelBuffer.java | 126 ++-- .../jogamp/opengl/util/GLPixelStorageModes.java | 48 +- .../com/jogamp/opengl/util/GLReadBufferUtil.java | 62 +- src/jogl/classes/com/jogamp/opengl/util/Gamma.java | 14 +- .../com/jogamp/opengl/util/ImmModeSink.java | 382 +++++----- .../classes/com/jogamp/opengl/util/PMVMatrix.java | 276 ++++---- .../com/jogamp/opengl/util/RandomTileRenderer.java | 56 +- .../classes/com/jogamp/opengl/util/TGAWriter.java | 16 +- .../com/jogamp/opengl/util/TileRenderer.java | 78 +- .../com/jogamp/opengl/util/TileRendererBase.java | 148 ++-- .../classes/com/jogamp/opengl/util/TimeFrameI.java | 30 +- .../com/jogamp/opengl/util/av/AudioSink.java | 188 ++--- .../jogamp/opengl/util/av/AudioSinkFactory.java | 10 +- .../com/jogamp/opengl/util/av/GLMediaPlayer.java | 192 ++--- .../opengl/util/av/GLMediaPlayerFactory.java | 12 +- .../jogamp/opengl/util/awt/AWTGLPixelBuffer.java | 78 +- .../opengl/util/awt/AWTGLReadBufferUtil.java | 12 +- .../com/jogamp/opengl/util/awt/ImageUtil.java | 26 +- .../com/jogamp/opengl/util/awt/Overlay.java | 14 +- .../com/jogamp/opengl/util/awt/Screenshot.java | 28 +- .../com/jogamp/opengl/util/awt/TextRenderer.java | 12 +- .../jogamp/opengl/util/awt/TextureRenderer.java | 28 +- .../com/jogamp/opengl/util/gl2/BitmapCharRec.java | 18 +- .../com/jogamp/opengl/util/gl2/BitmapFontRec.java | 18 +- .../com/jogamp/opengl/util/gl2/CoordRec.java | 18 +- .../classes/com/jogamp/opengl/util/gl2/GLUT.java | 52 +- .../com/jogamp/opengl/util/gl2/GLUTBitmap8x13.java | 14 +- .../com/jogamp/opengl/util/gl2/GLUTBitmap9x15.java | 14 +- .../opengl/util/gl2/GLUTBitmapHelvetica10.java | 14 +- .../opengl/util/gl2/GLUTBitmapHelvetica12.java | 14 +- .../opengl/util/gl2/GLUTBitmapHelvetica18.java | 14 +- .../opengl/util/gl2/GLUTBitmapTimesRoman10.java | 14 +- .../opengl/util/gl2/GLUTBitmapTimesRoman24.java | 14 +- .../opengl/util/gl2/GLUTStrokeMonoRoman.java | 14 +- .../jogamp/opengl/util/gl2/GLUTStrokeRoman.java | 14 +- .../com/jogamp/opengl/util/gl2/StrokeCharRec.java | 18 +- .../com/jogamp/opengl/util/gl2/StrokeFontRec.java | 18 +- .../com/jogamp/opengl/util/gl2/StrokeRec.java | 20 +- .../com/jogamp/opengl/util/glsl/ShaderCode.java | 208 +++--- .../com/jogamp/opengl/util/glsl/ShaderProgram.java | 42 +- .../com/jogamp/opengl/util/glsl/ShaderState.java | 232 +++--- .../com/jogamp/opengl/util/glsl/ShaderUtil.java | 54 +- .../opengl/util/glsl/fixedfunc/FixedFuncUtil.java | 12 +- .../util/glsl/fixedfunc/ShaderSelectionMode.java | 18 +- .../jogamp/opengl/util/glsl/sdk/CompileShader.java | 4 +- .../opengl/util/packrect/BackingStoreManager.java | 14 +- .../com/jogamp/opengl/util/packrect/Level.java | 16 +- .../com/jogamp/opengl/util/packrect/LevelSet.java | 16 +- .../com/jogamp/opengl/util/packrect/Rect.java | 16 +- .../jogamp/opengl/util/packrect/RectVisitor.java | 14 +- .../opengl/util/packrect/RectanglePacker.java | 16 +- .../com/jogamp/opengl/util/texture/Texture.java | 86 +-- .../jogamp/opengl/util/texture/TextureCoords.java | 16 +- .../jogamp/opengl/util/texture/TextureData.java | 94 +-- .../com/jogamp/opengl/util/texture/TextureIO.java | 74 +- .../opengl/util/texture/TextureSequence.java | 120 ++-- .../jogamp/opengl/util/texture/TextureState.java | 52 +- .../opengl/util/texture/awt/AWTTextureData.java | 28 +- .../opengl/util/texture/awt/AWTTextureIO.java | 18 +- .../jogamp/opengl/util/texture/spi/DDSImage.java | 22 +- .../jogamp/opengl/util/texture/spi/JPEGImage.java | 40 +- .../opengl/util/texture/spi/LEDataInputStream.java | 22 +- .../util/texture/spi/LEDataOutputStream.java | 14 +- .../util/texture/spi/NetPbmTextureWriter.java | 36 +- .../jogamp/opengl/util/texture/spi/PNGImage.java | 66 +- .../jogamp/opengl/util/texture/spi/SGIImage.java | 38 +- .../jogamp/opengl/util/texture/spi/TGAImage.java | 34 +- .../opengl/util/texture/spi/TextureProvider.java | 14 +- .../opengl/util/texture/spi/TextureWriter.java | 14 +- .../util/texture/spi/awt/IIOTextureProvider.java | 14 +- .../util/texture/spi/awt/IIOTextureWriter.java | 16 +- src/jogl/classes/javax/media/opengl/DebugGL2.java | 2 +- src/jogl/classes/javax/media/opengl/DebugGL3.java | 2 +- .../classes/javax/media/opengl/DebugGL3bc.java | 2 +- src/jogl/classes/javax/media/opengl/DebugGL4.java | 2 +- .../classes/javax/media/opengl/DebugGLES2.java | 2 +- .../media/opengl/DefaultGLCapabilitiesChooser.java | 32 +- .../classes/javax/media/opengl/FPSCounter.java | 32 +- .../javax/media/opengl/GLAnimatorControl.java | 16 +- .../classes/javax/media/opengl/GLArrayData.java | 20 +- .../classes/javax/media/opengl/GLAutoDrawable.java | 120 ++-- src/jogl/classes/javax/media/opengl/GLBase.java | 108 +-- .../classes/javax/media/opengl/GLCapabilities.java | 16 +- .../javax/media/opengl/GLCapabilitiesChooser.java | 16 +- .../media/opengl/GLCapabilitiesImmutable.java | 10 +- src/jogl/classes/javax/media/opengl/GLContext.java | 320 ++++----- .../javax/media/opengl/GLDebugListener.java | 8 +- .../classes/javax/media/opengl/GLDebugMessage.java | 114 +-- .../classes/javax/media/opengl/GLDrawable.java | 22 +- .../javax/media/opengl/GLDrawableFactory.java | 152 ++-- .../javax/media/opengl/GLEventListener.java | 22 +- .../classes/javax/media/opengl/GLException.java | 14 +- .../classes/javax/media/opengl/GLFBODrawable.java | 76 +- .../media/opengl/GLOffscreenAutoDrawable.java | 20 +- src/jogl/classes/javax/media/opengl/GLPbuffer.java | 4 +- .../javax/media/opengl/GLPipelineFactory.java | 22 +- src/jogl/classes/javax/media/opengl/GLProfile.java | 282 ++++---- .../classes/javax/media/opengl/GLRunnable.java | 20 +- .../classes/javax/media/opengl/GLRunnable2.java | 14 +- .../classes/javax/media/opengl/GLUniformData.java | 14 +- src/jogl/classes/javax/media/opengl/Threading.java | 52 +- src/jogl/classes/javax/media/opengl/TraceGL2.java | 2 +- src/jogl/classes/javax/media/opengl/TraceGL3.java | 2 +- .../classes/javax/media/opengl/TraceGL3bc.java | 2 +- src/jogl/classes/javax/media/opengl/TraceGL4.java | 2 +- .../classes/javax/media/opengl/TraceGLES2.java | 2 +- .../javax/media/opengl/awt/ComponentEvents.java | 14 +- .../classes/javax/media/opengl/awt/GLCanvas.java | 104 +-- .../classes/javax/media/opengl/awt/GLJPanel.java | 192 ++--- .../javax/media/opengl/fixedfunc/GLMatrixFunc.java | 18 +- .../media/opengl/fixedfunc/GLPointerFunc.java | 2 +- .../media/opengl/fixedfunc/GLPointerFuncUtil.java | 10 +- .../jogamp/graph/curve/opengl/RegionFactory.java | 20 +- .../graph/curve/opengl/RegionRendererImpl01.java | 24 +- .../jogamp/graph/curve/opengl/RenderStateImpl.java | 14 +- .../graph/curve/opengl/TextRendererImpl01.java | 26 +- .../jogamp/graph/curve/opengl/VBORegion2PES2.java | 178 ++--- .../jogamp/graph/curve/opengl/VBORegionSPES2.java | 34 +- .../graph/curve/opengl/shader/AttributeNames.java | 12 +- .../graph/curve/opengl/shader/UniformNames.java | 2 +- .../jogamp/graph/curve/tess/CDTriangulator2D.java | 30 +- .../jogamp/graph/curve/tess/GraphOutline.java | 10 +- .../jogamp/graph/curve/tess/GraphVertex.java | 12 +- .../classes/jogamp/graph/curve/tess/HEdge.java | 12 +- src/jogl/classes/jogamp/graph/curve/tess/Loop.java | 30 +- .../jogamp/graph/curve/text/GlyphShape.java | 20 +- .../jogamp/graph/curve/text/GlyphString.java | 58 +- src/jogl/classes/jogamp/graph/font/FontInt.java | 2 +- .../classes/jogamp/graph/font/JavaFontLoader.java | 46 +- .../jogamp/graph/font/UbuntuFontLoader.java | 36 +- .../jogamp/graph/font/typecast/TypecastFont.java | 56 +- .../font/typecast/TypecastFontConstructor.java | 10 +- .../jogamp/graph/font/typecast/TypecastGlyph.java | 88 +-- .../graph/font/typecast/TypecastHMetrics.java | 14 +- .../graph/font/typecast/TypecastRenderer.java | 26 +- .../graph/font/typecast/ot/Disassembler.java | 8 +- .../jogamp/graph/font/typecast/ot/Fixed.java | 4 +- .../jogamp/graph/font/typecast/ot/Mnemonic.java | 8 +- .../jogamp/graph/font/typecast/ot/OTFont.java | 36 +- .../graph/font/typecast/ot/OTFontCollection.java | 4 +- .../jogamp/graph/font/typecast/ot/OTGlyph.java | 8 +- .../graph/font/typecast/ot/mac/ResourceData.java | 2 +- .../graph/font/typecast/ot/mac/ResourceFile.java | 10 +- .../graph/font/typecast/ot/mac/ResourceHeader.java | 6 +- .../graph/font/typecast/ot/mac/ResourceMap.java | 10 +- .../font/typecast/ot/mac/ResourceReference.java | 12 +- .../graph/font/typecast/ot/mac/ResourceType.java | 10 +- .../graph/font/typecast/ot/table/BaseTable.java | 98 +-- .../graph/font/typecast/ot/table/CffTable.java | 122 ++-- .../graph/font/typecast/ot/table/Charstring.java | 2 +- .../font/typecast/ot/table/CharstringType2.java | 18 +- .../graph/font/typecast/ot/table/ClassDef.java | 8 +- .../font/typecast/ot/table/ClassDefFormat1.java | 8 +- .../font/typecast/ot/table/ClassDefFormat2.java | 8 +- .../graph/font/typecast/ot/table/CmapFormat.java | 14 +- .../graph/font/typecast/ot/table/CmapFormat0.java | 2 +- .../graph/font/typecast/ot/table/CmapFormat2.java | 28 +- .../graph/font/typecast/ot/table/CmapFormat4.java | 4 +- .../graph/font/typecast/ot/table/CmapFormat6.java | 4 +- .../font/typecast/ot/table/CmapFormatUnknown.java | 6 +- .../font/typecast/ot/table/CmapIndexEntry.java | 2 +- .../graph/font/typecast/ot/table/CmapTable.java | 10 +- .../graph/font/typecast/ot/table/Coverage.java | 2 +- .../graph/font/typecast/ot/table/CvtTable.java | 12 +- .../graph/font/typecast/ot/table/Device.java | 8 +- .../font/typecast/ot/table/DirectoryEntry.java | 4 +- .../graph/font/typecast/ot/table/DsigEntry.java | 14 +- .../graph/font/typecast/ot/table/DsigTable.java | 12 +- .../graph/font/typecast/ot/table/FeatureList.java | 8 +- .../font/typecast/ot/table/FeatureRecord.java | 2 +- .../graph/font/typecast/ot/table/FpgmTable.java | 12 +- .../graph/font/typecast/ot/table/GaspRange.java | 12 +- .../graph/font/typecast/ot/table/GaspTable.java | 14 +- .../typecast/ot/table/GlyfCompositeDescript.java | 2 +- .../graph/font/typecast/ot/table/GlyfDescript.java | 2 +- .../font/typecast/ot/table/GlyfSimpleDescript.java | 4 +- .../graph/font/typecast/ot/table/GlyfTable.java | 6 +- .../font/typecast/ot/table/GlyphDescription.java | 24 +- .../graph/font/typecast/ot/table/GposTable.java | 4 +- .../graph/font/typecast/ot/table/GsubTable.java | 20 +- .../graph/font/typecast/ot/table/HdmxTable.java | 20 +- .../graph/font/typecast/ot/table/HeadTable.java | 4 +- .../graph/font/typecast/ot/table/HheaTable.java | 12 +- .../jogamp/graph/font/typecast/ot/table/ID.java | 4 +- .../graph/font/typecast/ot/table/KernSubtable.java | 12 +- .../typecast/ot/table/KernSubtableFormat0.java | 10 +- .../typecast/ot/table/KernSubtableFormat2.java | 8 +- .../graph/font/typecast/ot/table/KernTable.java | 14 +- .../graph/font/typecast/ot/table/KerningPair.java | 8 +- .../graph/font/typecast/ot/table/LangSys.java | 10 +- .../font/typecast/ot/table/LangSysRecord.java | 2 +- .../graph/font/typecast/ot/table/Ligature.java | 4 +- .../typecast/ot/table/LigatureSubstFormat1.java | 2 +- .../graph/font/typecast/ot/table/LocaTable.java | 10 +- .../graph/font/typecast/ot/table/Lookup.java | 2 +- .../graph/font/typecast/ot/table/LookupList.java | 8 +- .../typecast/ot/table/LookupSubtableFactory.java | 4 +- .../graph/font/typecast/ot/table/LtshTable.java | 16 +- .../graph/font/typecast/ot/table/MaxpTable.java | 14 +- .../graph/font/typecast/ot/table/NameRecord.java | 18 +- .../graph/font/typecast/ot/table/NameTable.java | 14 +- .../graph/font/typecast/ot/table/Os2Table.java | 14 +- .../graph/font/typecast/ot/table/Panose.java | 26 +- .../graph/font/typecast/ot/table/PcltTable.java | 14 +- .../graph/font/typecast/ot/table/PostTable.java | 18 +- .../graph/font/typecast/ot/table/PrepTable.java | 12 +- .../graph/font/typecast/ot/table/Program.java | 8 +- .../graph/font/typecast/ot/table/RangeRecord.java | 2 +- .../graph/font/typecast/ot/table/Script.java | 6 +- .../graph/font/typecast/ot/table/ScriptList.java | 12 +- .../graph/font/typecast/ot/table/ScriptRecord.java | 4 +- .../font/typecast/ot/table/SignatureBlock.java | 10 +- .../graph/font/typecast/ot/table/SingleSubst.java | 2 +- .../font/typecast/ot/table/SingleSubstFormat1.java | 2 +- .../font/typecast/ot/table/SingleSubstFormat2.java | 2 +- .../graph/font/typecast/ot/table/TTCHeader.java | 12 +- .../jogamp/graph/font/typecast/ot/table/Table.java | 12 +- .../font/typecast/ot/table/TableDirectory.java | 2 +- .../font/typecast/ot/table/TableException.java | 6 +- .../graph/font/typecast/ot/table/TableFactory.java | 10 +- .../graph/font/typecast/ot/table/VdmxTable.java | 40 +- .../graph/font/typecast/ot/table/VheaTable.java | 2 +- .../graph/font/typecast/t2/T2Interpreter.java | 146 ++-- .../graph/font/typecast/tt/engine/Interpreter.java | 4 +- .../jogamp/graph/geom/plane/AffineTransform.java | 50 +- .../classes/jogamp/graph/geom/plane/Crossing.java | 26 +- .../classes/jogamp/graph/geom/plane/Path2D.java | 42 +- src/jogl/classes/jogamp/opengl/Debug.java | 20 +- .../opengl/DesktopGLDynamicLibraryBundleInfo.java | 14 +- .../opengl/DesktopGLDynamicLookupHelper.java | 10 +- .../jogamp/opengl/ExtensionAvailabilityCache.java | 38 +- src/jogl/classes/jogamp/opengl/FPSCounterImpl.java | 50 +- .../classes/jogamp/opengl/GLAutoDrawableBase.java | 144 ++-- .../classes/jogamp/opengl/GLBufferSizeTracker.java | 18 +- .../jogamp/opengl/GLBufferStateTracker.java | 30 +- src/jogl/classes/jogamp/opengl/GLContextImpl.java | 296 ++++---- .../classes/jogamp/opengl/GLContextShareSet.java | 50 +- .../jogamp/opengl/GLDebugMessageHandler.java | 126 ++-- .../jogamp/opengl/GLDrawableFactoryImpl.java | 58 +- .../classes/jogamp/opengl/GLDrawableHelper.java | 198 +++--- src/jogl/classes/jogamp/opengl/GLDrawableImpl.java | 64 +- .../jogamp/opengl/GLDynamicLibraryBundleInfo.java | 18 +- .../jogamp/opengl/GLDynamicLookupHelper.java | 10 +- .../classes/jogamp/opengl/GLFBODrawableImpl.java | 142 ++-- .../jogamp/opengl/GLGraphicsConfigurationUtil.java | 60 +- .../jogamp/opengl/GLOffscreenAutoDrawableImpl.java | 42 +- src/jogl/classes/jogamp/opengl/GLPbufferImpl.java | 16 +- src/jogl/classes/jogamp/opengl/GLRunnableTask.java | 28 +- src/jogl/classes/jogamp/opengl/GLStateTracker.java | 52 +- .../classes/jogamp/opengl/GLVersionNumber.java | 20 +- src/jogl/classes/jogamp/opengl/GLWorkerThread.java | 24 +- src/jogl/classes/jogamp/opengl/GLXExtensions.java | 4 +- .../jogamp/opengl/ListenerSyncedImplStub.java | 12 +- src/jogl/classes/jogamp/opengl/ProjectFloat.java | 120 ++-- .../jogamp/opengl/SharedResourceRunner.java | 44 +- src/jogl/classes/jogamp/opengl/ThreadingImpl.java | 38 +- .../jogamp/opengl/ToolkitThreadingPlugin.java | 16 +- .../jogamp/opengl/awt/AWTThreadingPlugin.java | 16 +- .../classes/jogamp/opengl/awt/AWTTilePainter.java | 74 +- src/jogl/classes/jogamp/opengl/awt/AWTUtil.java | 16 +- src/jogl/classes/jogamp/opengl/awt/Java2D.java | 46 +- .../classes/jogamp/opengl/awt/VersionApplet.java | 6 +- .../egl/DesktopES2DynamicLibraryBundleInfo.java | 26 +- src/jogl/classes/jogamp/opengl/egl/EGLContext.java | 20 +- .../classes/jogamp/opengl/egl/EGLDisplayUtil.java | 62 +- .../classes/jogamp/opengl/egl/EGLDrawable.java | 20 +- .../jogamp/opengl/egl/EGLDrawableFactory.java | 136 ++-- .../opengl/egl/EGLDummyUpstreamSurfaceHook.java | 12 +- .../opengl/egl/EGLDynamicLibraryBundleInfo.java | 30 +- .../opengl/egl/EGLES1DynamicLibraryBundleInfo.java | 28 +- .../opengl/egl/EGLES2DynamicLibraryBundleInfo.java | 38 +- .../opengl/egl/EGLGraphicsConfiguration.java | 58 +- .../egl/EGLGraphicsConfigurationFactory.java | 68 +- .../jogamp/opengl/egl/EGLOnscreenDrawable.java | 4 +- .../jogamp/opengl/egl/EGLUpstreamSurfaceHook.java | 50 +- .../jogamp/opengl/egl/EGLWrappedSurface.java | 10 +- .../classes/jogamp/opengl/gl2/ProjectDouble.java | 92 +-- .../classes/jogamp/opengl/glu/GLUquadricImpl.java | 82 +-- src/jogl/classes/jogamp/opengl/glu/Glue.java | 16 +- .../classes/jogamp/opengl/glu/error/Error.java | 16 +- .../opengl/glu/gl2/nurbs/GL2CurveEvaluator.java | 2 +- .../opengl/glu/gl2/nurbs/GLUgl2nurbsImpl.java | 38 +- .../jogamp/opengl/glu/mipmap/BuildMipmap.java | 198 +++--- .../classes/jogamp/opengl/glu/mipmap/Extract.java | 8 +- .../jogamp/opengl/glu/mipmap/Extract1010102.java | 24 +- .../jogamp/opengl/glu/mipmap/Extract1555rev.java | 24 +- .../opengl/glu/mipmap/Extract2101010rev.java | 24 +- .../jogamp/opengl/glu/mipmap/Extract233rev.java | 18 +- .../jogamp/opengl/glu/mipmap/Extract332.java | 18 +- .../jogamp/opengl/glu/mipmap/Extract4444.java | 24 +- .../jogamp/opengl/glu/mipmap/Extract4444rev.java | 24 +- .../jogamp/opengl/glu/mipmap/Extract5551.java | 24 +- .../jogamp/opengl/glu/mipmap/Extract565.java | 24 +- .../jogamp/opengl/glu/mipmap/Extract565rev.java | 24 +- .../jogamp/opengl/glu/mipmap/Extract8888.java | 24 +- .../jogamp/opengl/glu/mipmap/Extract8888rev.java | 24 +- .../jogamp/opengl/glu/mipmap/ExtractFloat.java | 14 +- .../jogamp/opengl/glu/mipmap/ExtractPrimitive.java | 8 +- .../jogamp/opengl/glu/mipmap/ExtractSByte.java | 14 +- .../jogamp/opengl/glu/mipmap/ExtractSInt.java | 14 +- .../jogamp/opengl/glu/mipmap/ExtractSShort.java | 14 +- .../jogamp/opengl/glu/mipmap/ExtractUByte.java | 14 +- .../jogamp/opengl/glu/mipmap/ExtractUInt.java | 14 +- .../jogamp/opengl/glu/mipmap/ExtractUShort.java | 14 +- .../jogamp/opengl/glu/mipmap/HalveImage.java | 276 ++++---- .../classes/jogamp/opengl/glu/mipmap/Image.java | 120 ++-- .../classes/jogamp/opengl/glu/mipmap/Mipmap.java | 200 +++--- .../opengl/glu/mipmap/PixelStorageModes.java | 14 +- .../jogamp/opengl/glu/mipmap/ScaleInternal.java | 364 +++++----- .../jogamp/opengl/glu/mipmap/Type_Widget.java | 80 +-- src/jogl/classes/jogamp/opengl/glu/nurbs/Arc.java | 18 +- .../jogamp/opengl/glu/nurbs/ArcSdirSorter.java | 2 +- .../jogamp/opengl/glu/nurbs/ArcTdirSorter.java | 2 +- .../classes/jogamp/opengl/glu/nurbs/Backend.java | 2 +- src/jogl/classes/jogamp/opengl/glu/nurbs/Bin.java | 2 +- .../classes/jogamp/opengl/glu/nurbs/Breakpt.java | 4 +- .../jogamp/opengl/glu/nurbs/CArrayOfArcs.java | 32 +- .../jogamp/opengl/glu/nurbs/CArrayOfBreakpts.java | 22 +- .../jogamp/opengl/glu/nurbs/CArrayOfFloats.java | 32 +- .../opengl/glu/nurbs/CArrayOfQuiltspecs.java | 28 +- .../classes/jogamp/opengl/glu/nurbs/Curve.java | 6 +- .../classes/jogamp/opengl/glu/nurbs/Flist.java | 6 +- .../classes/jogamp/opengl/glu/nurbs/Knotspec.java | 20 +- .../jogamp/opengl/glu/nurbs/Knotvector.java | 14 +- .../classes/jogamp/opengl/glu/nurbs/Mapdesc.java | 12 +- .../jogamp/opengl/glu/nurbs/O_nurbscurve.java | 2 +- .../classes/jogamp/opengl/glu/nurbs/Patchlist.java | 2 +- .../classes/jogamp/opengl/glu/nurbs/Property.java | 6 +- .../jogamp/opengl/glu/nurbs/Renderhints.java | 2 +- .../jogamp/opengl/glu/nurbs/Subdivider.java | 6 +- .../jogamp/opengl/glu/nurbs/TrimVertex.java | 4 +- .../jogamp/opengl/glu/registry/Registry.java | 14 +- .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 144 ++-- .../opengl/macosx/cgl/MacOSXCGLDrawable.java | 10 +- .../macosx/cgl/MacOSXCGLDrawableFactory.java | 28 +- .../cgl/MacOSXCGLDynamicLibraryBundleInfo.java | 18 +- .../macosx/cgl/MacOSXCGLGraphicsConfiguration.java | 44 +- .../cgl/MacOSXCGLGraphicsConfigurationFactory.java | 18 +- .../macosx/cgl/MacOSXPbufferCGLDrawable.java | 4 +- .../MacOSXAWTCGLGraphicsConfigurationFactory.java | 12 +- .../classes/jogamp/opengl/util/GLArrayHandler.java | 24 +- .../jogamp/opengl/util/GLArrayHandlerFlat.java | 14 +- .../opengl/util/GLArrayHandlerInterleaved.java | 20 +- .../jogamp/opengl/util/GLDataArrayHandler.java | 10 +- .../jogamp/opengl/util/GLFixedArrayHandler.java | 16 +- .../opengl/util/GLFixedArrayHandlerFlat.java | 8 +- .../jogamp/opengl/util/GLVBOArrayHandler.java | 10 +- .../jogamp/opengl/util/av/EGLMediaPlayerImpl.java | 46 +- .../jogamp/opengl/util/av/GLMediaPlayerImpl.java | 284 ++++---- .../jogamp/opengl/util/av/JavaSoundAudioSink.java | 70 +- .../jogamp/opengl/util/av/NullAudioSink.java | 54 +- .../jogamp/opengl/util/av/NullGLMediaPlayer.java | 44 +- .../av/impl/FFMPEGDynamicLibraryBundleInfo.java | 118 ++-- .../opengl/util/av/impl/FFMPEGMediaPlayer.java | 174 ++--- .../jogamp/opengl/util/av/impl/FFMPEGNatives.java | 92 +-- .../opengl/util/av/impl/FFMPEGStaticNatives.java | 10 +- .../opengl/util/av/impl/FFMPEGv08Natives.java | 10 +- .../opengl/util/av/impl/FFMPEGv09Natives.java | 10 +- .../opengl/util/av/impl/FFMPEGv10Natives.java | 10 +- .../opengl/util/av/impl/OMXGLMediaPlayer.java | 48 +- .../jogamp/opengl/util/glsl/GLSLArrayHandler.java | 24 +- .../opengl/util/glsl/GLSLArrayHandlerFlat.java | 10 +- .../util/glsl/GLSLArrayHandlerInterleaved.java | 18 +- .../jogamp/opengl/util/glsl/GLSLTextureRaster.java | 70 +- .../opengl/util/glsl/fixedfunc/FixedFuncHook.java | 60 +- .../util/glsl/fixedfunc/FixedFuncPipeline.java | 236 +++---- .../jogamp/opengl/util/jpeg/JPEGDecoder.java | 132 ++-- .../jogamp/opengl/util/pngj/FilterType.java | 2 +- .../classes/jogamp/opengl/util/pngj/ImageInfo.java | 2 +- .../classes/jogamp/opengl/util/pngj/ImageLine.java | 30 +- .../jogamp/opengl/util/pngj/ImageLineHelper.java | 8 +- .../jogamp/opengl/util/pngj/ImageLines.java | 8 +- .../jogamp/opengl/util/pngj/PngHelperInternal.java | 2 +- .../classes/jogamp/opengl/util/pngj/PngReader.java | 56 +- .../classes/jogamp/opengl/util/pngj/PngWriter.java | 28 +- .../jogamp/opengl/util/pngj/PngjException.java | 4 +- .../opengl/util/pngj/PngjExceptionInternal.java | 4 +- .../opengl/util/pngj/chunks/ChunkHelper.java | 14 +- .../util/pngj/chunks/ChunkLoadBehaviour.java | 2 +- .../opengl/util/pngj/chunks/ChunkPredicate.java | 2 +- .../jogamp/opengl/util/pngj/chunks/ChunksList.java | 12 +- .../util/pngj/chunks/ChunksListForWrite.java | 6 +- .../jogamp/opengl/util/pngj/chunks/PngChunk.java | 2 +- .../opengl/util/pngj/chunks/PngChunkBKGD.java | 6 +- .../opengl/util/pngj/chunks/PngChunkMultiple.java | 4 +- .../opengl/util/pngj/chunks/PngChunkSBIT.java | 2 +- .../opengl/util/pngj/chunks/PngChunkTRNS.java | 2 +- .../opengl/util/pngj/chunks/PngMetadata.java | 10 +- .../opengl/windows/wgl/WGLGLCapabilities.java | 8 +- .../classes/jogamp/opengl/windows/wgl/WGLUtil.java | 22 +- .../windows/wgl/WindowsBitmapWGLDrawable.java | 4 +- .../windows/wgl/WindowsExternalWGLContext.java | 2 +- .../windows/wgl/WindowsPbufferWGLDrawable.java | 6 +- .../opengl/windows/wgl/WindowsWGLContext.java | 10 +- .../opengl/windows/wgl/WindowsWGLDrawable.java | 8 +- .../windows/wgl/WindowsWGLDrawableFactory.java | 30 +- .../wgl/WindowsWGLDynamicLibraryBundleInfo.java | 14 +- .../wgl/WindowsWGLGraphicsConfiguration.java | 72 +- .../WindowsWGLGraphicsConfigurationFactory.java | 42 +- .../WindowsAWTWGLGraphicsConfigurationFactory.java | 22 +- .../classes/jogamp/opengl/x11/glx/GLXUtil.java | 44 +- .../opengl/x11/glx/X11ExternalGLXContext.java | 6 +- .../opengl/x11/glx/X11ExternalGLXDrawable.java | 2 +- .../jogamp/opengl/x11/glx/X11GLXContext.java | 18 +- .../opengl/x11/glx/X11GLXDrawableFactory.java | 30 +- .../x11/glx/X11GLXDynamicLibraryBundleInfo.java | 22 +- .../x11/glx/X11GLXGraphicsConfiguration.java | 60 +- .../glx/X11GLXGraphicsConfigurationFactory.java | 46 +- .../DelegatedUpstreamSurfaceHookMutableSize.java | 6 +- ...elegatedUpstreamSurfaceHookWithSurfaceSize.java | 8 +- .../nativewindow/MutableGraphicsConfiguration.java | 4 +- .../jogamp/nativewindow/NativeWindowVersion.java | 10 +- .../UpstreamSurfaceHookMutableSize.java | 10 +- .../nativewindow/awt/AWTGraphicsConfiguration.java | 26 +- .../jogamp/nativewindow/awt/AWTGraphicsDevice.java | 14 +- .../jogamp/nativewindow/awt/AWTGraphicsScreen.java | 14 +- .../jogamp/nativewindow/awt/AWTPrintLifecycle.java | 26 +- .../nativewindow/awt/AWTWindowClosingProtocol.java | 2 +- .../nativewindow/awt/DirectDataBufferInt.java | 62 +- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 52 +- .../jogamp/nativewindow/egl/EGLGraphicsDevice.java | 30 +- .../nativewindow/macosx/MacOSXGraphicsDevice.java | 10 +- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 164 ++--- .../windows/WindowsGraphicsDevice.java | 12 +- .../nativewindow/x11/X11GraphicsConfiguration.java | 16 +- .../jogamp/nativewindow/x11/X11GraphicsDevice.java | 30 +- .../jogamp/nativewindow/x11/X11GraphicsScreen.java | 12 +- .../AbstractGraphicsConfiguration.java | 16 +- .../media/nativewindow/AbstractGraphicsDevice.java | 46 +- .../media/nativewindow/AbstractGraphicsScreen.java | 16 +- .../javax/media/nativewindow/Capabilities.java | 46 +- .../media/nativewindow/CapabilitiesChooser.java | 16 +- .../media/nativewindow/CapabilitiesImmutable.java | 8 +- .../nativewindow/DefaultCapabilitiesChooser.java | 24 +- .../nativewindow/DefaultGraphicsConfiguration.java | 18 +- .../media/nativewindow/DefaultGraphicsDevice.java | 34 +- .../media/nativewindow/DefaultGraphicsScreen.java | 12 +- .../nativewindow/GraphicsConfigurationFactory.java | 84 +-- .../javax/media/nativewindow/MutableSurface.java | 4 +- .../javax/media/nativewindow/NativeSurface.java | 40 +- .../media/nativewindow/NativeWindowException.java | 14 +- .../media/nativewindow/NativeWindowFactory.java | 134 ++-- .../media/nativewindow/OffscreenLayerOption.java | 12 +- .../media/nativewindow/OffscreenLayerSurface.java | 22 +- .../javax/media/nativewindow/ProxySurface.java | 60 +- .../media/nativewindow/SurfaceUpdatedListener.java | 12 +- .../javax/media/nativewindow/ToolkitLock.java | 14 +- .../media/nativewindow/UpstreamSurfaceHook.java | 18 +- .../javax/media/nativewindow/VisualIDHolder.java | 36 +- .../media/nativewindow/WindowClosingProtocol.java | 4 +- .../javax/media/nativewindow/util/Dimension.java | 18 +- .../nativewindow/util/DimensionImmutable.java | 4 +- .../javax/media/nativewindow/util/Insets.java | 18 +- .../media/nativewindow/util/InsetsImmutable.java | 4 +- .../javax/media/nativewindow/util/Point.java | 8 +- .../media/nativewindow/util/PointImmutable.java | 6 +- .../javax/media/nativewindow/util/Rectangle.java | 28 +- .../nativewindow/util/RectangleImmutable.java | 10 +- .../javax/media/nativewindow/util/SurfaceSize.java | 18 +- .../classes/jogamp/nativewindow/Debug.java | 16 +- .../DefaultGraphicsConfigurationFactoryImpl.java | 10 +- .../jogamp/nativewindow/GlobalToolkitLock.java | 14 +- .../jogamp/nativewindow/NWJNILibLoader.java | 12 +- .../nativewindow/NativeWindowFactoryImpl.java | 16 +- .../jogamp/nativewindow/NullToolkitLock.java | 10 +- .../jogamp/nativewindow/ProxySurfaceImpl.java | 42 +- .../jogamp/nativewindow/ResourceToolkitLock.java | 8 +- .../nativewindow/SharedResourceToolkitLock.java | 18 +- .../jogamp/nativewindow/SurfaceUpdatedHelper.java | 22 +- .../jogamp/nativewindow/ToolkitProperties.java | 20 +- .../jogamp/nativewindow/WrappedSurface.java | 10 +- .../classes/jogamp/nativewindow/awt/AWTMisc.java | 20 +- .../jogamp/nativewindow/jawt/JAWTJNILibLoader.java | 24 +- .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 112 +-- .../nativewindow/jawt/JAWT_PlatformInfo.java | 14 +- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 82 +-- .../jawt/windows/Win32SunJDKReflection.java | 14 +- .../jawt/windows/WindowsJAWTWindow.java | 16 +- .../nativewindow/jawt/x11/X11JAWTWindow.java | 18 +- .../nativewindow/jawt/x11/X11SunJDKReflection.java | 14 +- .../macosx/OSXDummyUpstreamSurfaceHook.java | 14 +- .../jogamp/nativewindow/macosx/OSXUtil.java | 94 +-- .../windows/GDIDummyUpstreamSurfaceHook.java | 18 +- .../jogamp/nativewindow/windows/GDISurface.java | 14 +- .../jogamp/nativewindow/windows/GDIUtil.java | 36 +- .../nativewindow/windows/RegisteredClass.java | 2 +- .../windows/RegisteredClassFactory.java | 16 +- .../x11/X11DummyUpstreamSurfaceHook.java | 14 +- .../x11/X11GraphicsConfigurationFactory.java | 16 +- .../classes/jogamp/nativewindow/x11/X11Util.java | 94 +-- .../awt/X11AWTGraphicsConfigurationFactory.java | 36 +- src/newt/classes/com/jogamp/newt/Display.java | 32 +- .../classes/com/jogamp/newt/MonitorDevice.java | 46 +- src/newt/classes/com/jogamp/newt/MonitorMode.java | 84 +-- src/newt/classes/com/jogamp/newt/NewtFactory.java | 24 +- src/newt/classes/com/jogamp/newt/NewtVersion.java | 10 +- src/newt/classes/com/jogamp/newt/Screen.java | 34 +- src/newt/classes/com/jogamp/newt/Window.java | 32 +- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 158 ++--- .../jogamp/newt/awt/applet/JOGLNewtApplet1Run.java | 24 +- .../jogamp/newt/awt/applet/JOGLNewtAppletBase.java | 22 +- .../jogamp/newt/event/DoubleTapScrollGesture.java | 66 +- .../com/jogamp/newt/event/GestureHandler.java | 60 +- .../classes/com/jogamp/newt/event/InputEvent.java | 56 +- .../classes/com/jogamp/newt/event/KeyAdapter.java | 10 +- .../classes/com/jogamp/newt/event/KeyEvent.java | 256 +++---- .../classes/com/jogamp/newt/event/KeyListener.java | 22 +- .../com/jogamp/newt/event/MonitorEvent.java | 12 +- .../com/jogamp/newt/event/MouseAdapter.java | 10 +- .../classes/com/jogamp/newt/event/MouseEvent.java | 164 ++--- .../com/jogamp/newt/event/MouseListener.java | 20 +- .../classes/com/jogamp/newt/event/NEWTEvent.java | 30 +- .../com/jogamp/newt/event/NEWTEventConsumer.java | 14 +- .../com/jogamp/newt/event/NEWTEventFiFo.java | 10 +- .../com/jogamp/newt/event/NEWTEventListener.java | 12 +- .../classes/com/jogamp/newt/event/OutputEvent.java | 2 +- .../com/jogamp/newt/event/PinchToZoomGesture.java | 48 +- .../com/jogamp/newt/event/TraceKeyAdapter.java | 10 +- .../com/jogamp/newt/event/TraceMouseAdapter.java | 10 +- .../com/jogamp/newt/event/TraceWindowAdapter.java | 10 +- .../com/jogamp/newt/event/WindowAdapter.java | 10 +- .../classes/com/jogamp/newt/event/WindowEvent.java | 16 +- .../com/jogamp/newt/event/WindowListener.java | 18 +- .../com/jogamp/newt/event/WindowUpdateEvent.java | 10 +- .../com/jogamp/newt/event/awt/AWTAdapter.java | 36 +- .../com/jogamp/newt/event/awt/AWTKeyAdapter.java | 12 +- .../com/jogamp/newt/event/awt/AWTMouseAdapter.java | 12 +- .../jogamp/newt/event/awt/AWTWindowAdapter.java | 24 +- .../classes/com/jogamp/newt/opengl/GLWindow.java | 38 +- .../classes/com/jogamp/newt/swt/NewtCanvasSWT.java | 130 ++-- src/newt/classes/com/jogamp/newt/util/EDTUtil.java | 30 +- .../classes/com/jogamp/newt/util/MainThread.java | 90 +-- .../com/jogamp/newt/util/MonitorModeUtil.java | 18 +- src/newt/classes/jogamp/newt/Debug.java | 18 +- src/newt/classes/jogamp/newt/DefaultEDTUtil.java | 36 +- src/newt/classes/jogamp/newt/DisplayImpl.java | 66 +- .../classes/jogamp/newt/MonitorDeviceImpl.java | 28 +- src/newt/classes/jogamp/newt/MonitorModeProps.java | 44 +- src/newt/classes/jogamp/newt/NEWTJNILibLoader.java | 16 +- src/newt/classes/jogamp/newt/OffscreenWindow.java | 28 +- src/newt/classes/jogamp/newt/ScreenImpl.java | 98 +-- .../classes/jogamp/newt/ScreenMonitorState.java | 18 +- src/newt/classes/jogamp/newt/WindowImpl.java | 554 +++++++-------- .../classes/jogamp/newt/awt/NewtFactoryAWT.java | 16 +- .../jogamp/newt/awt/event/AWTNewtEventFactory.java | 74 +- .../newt/awt/event/AWTParentWindowAdapter.java | 20 +- .../jogamp/newt/driver/DriverClearFocus.java | 6 +- .../jogamp/newt/driver/DriverUpdatePosition.java | 8 +- .../classes/jogamp/newt/driver/awt/AWTCanvas.java | 40 +- .../classes/jogamp/newt/driver/awt/AWTEDTUtil.java | 32 +- .../jogamp/newt/driver/awt/DisplayDriver.java | 16 +- .../jogamp/newt/driver/awt/ScreenDriver.java | 28 +- .../jogamp/newt/driver/awt/WindowDriver.java | 50 +- .../jogamp/newt/driver/bcm/egl/DisplayDriver.java | 12 +- .../jogamp/newt/driver/bcm/egl/ScreenDriver.java | 20 +- .../jogamp/newt/driver/bcm/egl/WindowDriver.java | 22 +- .../newt/driver/bcm/vc/iv/DisplayDriver.java | 10 +- .../jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java | 22 +- .../jogamp/newt/driver/bcm/vc/iv/WindowDriver.java | 30 +- .../newt/driver/intel/gdl/DisplayDriver.java | 12 +- .../jogamp/newt/driver/intel/gdl/ScreenDriver.java | 22 +- .../jogamp/newt/driver/intel/gdl/WindowDriver.java | 18 +- .../jogamp/newt/driver/kd/DisplayDriver.java | 12 +- .../jogamp/newt/driver/kd/ScreenDriver.java | 26 +- .../jogamp/newt/driver/kd/WindowDriver.java | 22 +- .../newt/driver/linux/LinuxEventDeviceTracker.java | 16 +- .../newt/driver/linux/LinuxMouseTracker.java | 46 +- .../jogamp/newt/driver/macosx/DisplayDriver.java | 18 +- .../jogamp/newt/driver/macosx/MacKeyUtil.java | 38 +- .../jogamp/newt/driver/macosx/ScreenDriver.java | 32 +- .../jogamp/newt/driver/macosx/WindowDriver.java | 126 ++-- .../jogamp/newt/driver/windows/DisplayDriver.java | 18 +- .../jogamp/newt/driver/windows/ScreenDriver.java | 28 +- .../jogamp/newt/driver/windows/WindowDriver.java | 90 +-- .../jogamp/newt/driver/x11/DisplayDriver.java | 28 +- src/newt/classes/jogamp/newt/driver/x11/RandR.java | 22 +- .../classes/jogamp/newt/driver/x11/RandR11.java | 66 +- .../classes/jogamp/newt/driver/x11/RandR13.java | 60 +- .../jogamp/newt/driver/x11/ScreenDriver.java | 68 +- .../jogamp/newt/driver/x11/WindowDriver.java | 92 +-- .../classes/jogamp/newt/event/NEWTEventTask.java | 10 +- src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java | 46 +- .../jogamp/newt/swt/event/SWTNewtEventFactory.java | 48 +- 643 files changed, 12269 insertions(+), 12269 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/audio/windows/waveout/Audio.java b/src/jogl/classes/com/jogamp/audio/windows/waveout/Audio.java index 2b51be164..83f5e4ebd 100644 --- a/src/jogl/classes/com/jogamp/audio/windows/waveout/Audio.java +++ b/src/jogl/classes/com/jogamp/audio/windows/waveout/Audio.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 diff --git a/src/jogl/classes/com/jogamp/audio/windows/waveout/Mixer.java b/src/jogl/classes/com/jogamp/audio/windows/waveout/Mixer.java index 60972873e..0a502c123 100644 --- a/src/jogl/classes/com/jogamp/audio/windows/waveout/Mixer.java +++ b/src/jogl/classes/com/jogamp/audio/windows/waveout/Mixer.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 @@ -344,7 +344,7 @@ public class Mixer { e.printStackTrace(); } } - + if (directByteBufferConstructor != null) { try { return (ByteBuffer) diff --git a/src/jogl/classes/com/jogamp/audio/windows/waveout/SoundBuffer.java b/src/jogl/classes/com/jogamp/audio/windows/waveout/SoundBuffer.java index c45430d23..01346553c 100644 --- a/src/jogl/classes/com/jogamp/audio/windows/waveout/SoundBuffer.java +++ b/src/jogl/classes/com/jogamp/audio/windows/waveout/SoundBuffer.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 diff --git a/src/jogl/classes/com/jogamp/audio/windows/waveout/Track.java b/src/jogl/classes/com/jogamp/audio/windows/waveout/Track.java index b57bf1dc6..98a787478 100644 --- a/src/jogl/classes/com/jogamp/audio/windows/waveout/Track.java +++ b/src/jogl/classes/com/jogamp/audio/windows/waveout/Track.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 @@ -151,7 +151,7 @@ public class Track { // These are only for use by the Mixer private float leftGain; private float rightGain; - + void setLeftGain(float leftGain) { this.leftGain = leftGain; } diff --git a/src/jogl/classes/com/jogamp/audio/windows/waveout/Vec3f.java b/src/jogl/classes/com/jogamp/audio/windows/waveout/Vec3f.java index 1afdaf081..0726e5762 100644 --- a/src/jogl/classes/com/jogamp/audio/windows/waveout/Vec3f.java +++ b/src/jogl/classes/com/jogamp/audio/windows/waveout/Vec3f.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java index b04f35230..8429fbcfd 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -67,7 +67,7 @@ public class BuildComposablePipeline { * By extra command-line argument: prolog_xor_downstream. *

          * If true, either prolog (if exist) is called or downstream's method, but not both. - * By default, both methods would be called. + * By default, both methods would be called. *

          *

          Default: false

          */ @@ -81,7 +81,7 @@ public class BuildComposablePipeline { *

          Default: false

          */ public static final int GEN_GL_IDENTITY_BY_ASSIGNABLE_CLASS = 1 << 4; - + int mode; private String outputDir; private String outputPackage; diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java index 5298cc357..a5a26d18f 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -68,7 +68,7 @@ import java.util.regex.Pattern; *
          * *
          -   * 
          +   *
              * #ifndef GL_XXXX
              * GLAPI   glFuncName()
              * #endif GL_XXXX
          @@ -78,7 +78,7 @@ import java.util.regex.Pattern;
              * For example, if it parses the following data:
              *
              * 
          -   * 
          +   *
              * #ifndef GL_VERSION_1_3
              * GLAPI void APIENTRY glActiveTexture (GLenum);
              * GLAPI void APIENTRY glMultiTexCoord1dv (GLenum, const GLdouble *);
          @@ -89,7 +89,7 @@ import java.util.regex.Pattern;
              * GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
              * GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
              * #endif
          -   * 
          +   *
              * 
          * * It will associate @@ -105,7 +105,7 @@ import java.util.regex.Pattern; * */ public class BuildStaticGLInfo { - // Handles function pointer + // Handles function pointer protected static final int funcIdentifierGroup = 9; protected static Pattern funcPattern = Pattern.compile("^(GLAPI|GL_API|GL_APICALL|EGLAPI|extern)?(\\s*)((unsigned|const)\\s+)?(\\w+)(\\s+\\*\\s*|\\s*\\*\\s+|\\s+)?(GLAPIENTRY|GL_APIENTRY|APIENTRY|EGLAPIENTRY|WINAPI)?(\\s*)([ew]?gl\\w+)\\s?(\\(.*)"); @@ -119,7 +119,7 @@ public class BuildStaticGLInfo { Pattern.compile("\\#(elif|else)(.*)"); protected static Pattern endifPattern = Pattern.compile("\\#endif(.*)"); - + protected static final int defineIdentifierGroup = 1; protected static Pattern definePattern = Pattern.compile("\\#define ([CEW]?GL[XU]?_[A-Za-z0-9_]+)\\s*([A-Za-z0-9_]+)(.*)"); @@ -203,7 +203,7 @@ public class BuildStaticGLInfo { Matcher m = null; int block = 0; while ((line = reader.readLine()) != null) { - int type = 0; // 1-define, 2-function + int type = 0; // 1-define, 2-function if ( 0 < block ) { // inside a #ifndef GL_XXX block and matching a function, if block > 0 String identifier = null; if( 2 >= block ) { // not within sub-blocks > 2, i.e. further typedefs @@ -216,9 +216,9 @@ public class BuildStaticGLInfo { } } if ( identifier != null && - activeAssociation != null && - !identifier.equals(activeAssociation) // Handles #ifndef GL_... #define GL_... - ) + activeAssociation != null && + !identifier.equals(activeAssociation) // Handles #ifndef GL_... #define GL_... + ) { addAssociation(identifier, activeAssociation); if (DEBUG) { @@ -243,7 +243,7 @@ public class BuildStaticGLInfo { if (DEBUG) { System.err.println("<"+block+"> END ASSOCIATION BLOCK: <" + activeAssociation + " <-> " + comment + ">"); } - activeAssociation = null; + activeAssociation = null; } else { if (DEBUG) { System.err.println("<"+block+"> END IF BLOCK: <" + comment + ">"); @@ -251,7 +251,7 @@ public class BuildStaticGLInfo { } } } - } else if ((m = associationPattern.matcher(line)).matches()) { + } else if ((m = associationPattern.matcher(line)).matches()) { // found a new #ifndef GL_XXX block activeAssociation = m.group(1).trim(); block++; @@ -387,7 +387,7 @@ public class BuildStaticGLInfo { declarationToExtensionMap.put(identifier, extensions); } extensions.add(association); - + Set identifiers = extensionToDeclarationMap.get(association); if (identifiers == null) { identifiers = new HashSet(); diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java b/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java index a00b19abc..f1a32fa9c 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003-2005 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 @@ -29,11 +29,11 @@ * 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. */ @@ -241,7 +241,7 @@ public class GLConfiguration extends ProcAddressConfiguration { } } if( ignoredExtension ) { - ignoredExtension = !shouldForceExtension( symbol, true, symbol ); + ignoredExtension = !shouldForceExtension( symbol, true, symbol ); if( ignoredExtension ) { final Set origSymbols = getRenamedJavaSymbols( symbol ); if(null != origSymbols) { @@ -251,7 +251,7 @@ public class GLConfiguration extends ProcAddressConfiguration { break; } } - } + } } } if( ignoredExtension ) { @@ -274,7 +274,7 @@ public class GLConfiguration extends ProcAddressConfiguration { } return false; } - + public boolean shouldForceExtension(final String symbol, final boolean criteria, final String renamedSymbol) { if (criteria && glInfo != null) { final Set extensionNames = glInfo.getExtension(symbol); @@ -292,7 +292,7 @@ public class GLConfiguration extends ProcAddressConfiguration { } return true; } - } + } } } return false; @@ -343,9 +343,9 @@ public class GLConfiguration extends ProcAddressConfiguration { public boolean isBufferObjectFunction(String name) { return (getBufferObjectKind(name) != null); } - - public boolean isBufferObjectOnly(String name) { - return bufferObjectOnly.contains(name); + + public boolean isBufferObjectOnly(String name) { + return bufferObjectOnly.contains(name); } /** Parses any GL headers specified in the configuration file for diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java b/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java index fa95049cc..1af632682 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003-2005 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 @@ -29,11 +29,11 @@ * 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. */ @@ -125,7 +125,7 @@ public class GLEmitter extends ProcAddressEmitter { } if(JavaConfiguration.DEBUG_RENAMES) { System.err.println("RenameExtensionIntoCore: "+extension+" END>"); - } + } } } @@ -279,7 +279,7 @@ public class GLEmitter extends ProcAddressEmitter { int j=0; while( j < bindings.size() ) { final MethodBinding cur = bindings.get(j); - + // Some of these routines (glBitmap) take strongly-typed // primitive pointers as arguments which are expanded into // non-void* arguments @@ -306,7 +306,7 @@ public class GLEmitter extends ProcAddressEmitter { // Now need to flag this MethodBinding so that we generate the // correct flags in the emitters later bufferObjectMethodBindings.put(result, result); - + if( bufferObjectOnly ) { bindings.remove(j); } else { @@ -397,7 +397,7 @@ public class GLEmitter extends ProcAddressEmitter { } private int addExtensionListOfAliasedSymbols2Buffer(BuildStaticGLInfo glInfo, StringBuilder buf, String sep1, String sep2, String name, Collection exclude) { int num = 0; - if(null != name) { + if(null != name) { num += addExtensionListOfSymbol2Buffer(glInfo, buf, sep1, name); // extensions of given name boolean needsSep2 = 0 origNames = cfg.getRenamedJavaSymbols(name); @@ -406,7 +406,7 @@ public class GLEmitter extends ProcAddressEmitter { if(!exclude.contains(origName)) { if (needsSep2) { buf.append(sep2); // diff-name seperator - } + } int num2 = addExtensionListOfSymbol2Buffer(glInfo, buf, sep1, origName); // extensions of orig-name needsSep2 = num col) { BuildStaticGLInfo glInfo = getGLConfig().getGLInfo(); if (null == glInfo) { @@ -469,16 +469,16 @@ public class GLEmitter extends ProcAddressEmitter { /** * {@inheritDoc} - */ + */ @Override protected void endProcAddressTable() throws Exception { PrintWriter w = tableWriter; - + w.println(" @Override"); w.println(" protected boolean isFunctionAvailableImpl(String functionNameUsr) throws IllegalArgumentException {"); w.println(" final String functionNameBase = "+GLNameResolver.class.getName()+".normalizeVEN(com.jogamp.gluegen.runtime.opengl.GLNameResolver.normalizeARB(functionNameUsr, true), true);"); w.println(" final String addressFieldNameBase = \"" + PROCADDRESS_VAR_PREFIX + "\" + functionNameBase;"); - w.println(" final int funcNamePermNum = "+GLNameResolver.class.getName()+".getFuncNamePermutationNumber(functionNameBase);"); + w.println(" final int funcNamePermNum = "+GLNameResolver.class.getName()+".getFuncNamePermutationNumber(functionNameBase);"); w.println(" final java.lang.reflect.Field addressField = java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {"); w.println(" public final java.lang.reflect.Field run() {"); w.println(" java.lang.reflect.Field addressField = null;"); @@ -510,7 +510,7 @@ public class GLEmitter extends ProcAddressEmitter { w.println(" \"function\", e);"); w.println(" }"); w.println(" }"); - + w.println(" @Override"); w.println(" public long getAddressFor(String functionNameUsr) throws SecurityException, IllegalArgumentException {"); w.println(" SecurityUtil.checkAllLinkPermission();"); diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/GLJavaMethodBindingEmitter.java b/src/jogl/classes/com/jogamp/gluegen/opengl/GLJavaMethodBindingEmitter.java index fdfaee8a6..389d35f99 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/GLJavaMethodBindingEmitter.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/GLJavaMethodBindingEmitter.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003-2005 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 @@ -29,11 +29,11 @@ * 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. */ @@ -111,7 +111,7 @@ public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmit writer.print(" "); writer.print(funcSym.getType().toString(symbolRenamed, tagNativeBinding)); writer.print(" "); - + newComment.append("
          Part of "); if (0 == glEmitter.addExtensionsOfSymbols2Buffer(newComment, ", ", "; ", symbolRenamed, binding.getAliasedNames())) { if (glEmitter.getGLConfig().getAllowNonGLExtensions()) { diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/ant/StaticGLGenTask.java b/src/jogl/classes/com/jogamp/gluegen/opengl/ant/StaticGLGenTask.java index e3e7cb970..b98f17117 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/ant/StaticGLGenTask.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/ant/StaticGLGenTask.java @@ -55,13 +55,13 @@ import org.apache.tools.ant.util.JavaEnvUtils; /** *

          An ANT {@link org.apache.tools.ant.Task} * for using {@link com.jogamp.gluegen.opengl.BuildStaticGLInfo}.

          - * + * *

          Usage:

          *
          -    <staticglgen package="[generated files package]" 
          +    <staticglgen package="[generated files package]"
                               headers="[file pattern of GL headers]"
                               outputdir="[directory to output the generated files]" />
          - * 
          + *
          * * @author Rob Grzywinski rgrzywinski@yahoo.com */ @@ -72,7 +72,7 @@ public class StaticGLGenTask extends Task *

          The {@link com.jogamp.gluegen.opengl.BuildStaticGLInfo} classname.

          */ private static final String GL_GEN = "com.jogamp.gluegen.opengl.BuildStaticGLInfo"; - + // ========================================================================= /** *

          The {@link org.apache.tools.ant.types.CommandlineJava} that is used @@ -90,12 +90,12 @@ public class StaticGLGenTask extends Task *

          The output directory.

          */ private String outputDirectory; - + /** *

          The {@link org.apache.tools.ant.types.FileSet} of GL headers.

          */ private FileSet headerSet = new FileSet(); - + // ========================================================================= /** *

          Create and add the VM and classname to {@link org.apache.tools.ant.types.CommandlineJava}.

          @@ -104,7 +104,7 @@ public class StaticGLGenTask extends Task { // create the CommandlineJava that will be used to call BuildStaticGLInfo glgenCommandline = new CommandlineJava(); - + // set the VM and classname in the commandline glgenCommandline.setVm(JavaEnvUtils.getJreExecutable("java")); glgenCommandline.setClassname(GL_GEN); @@ -114,7 +114,7 @@ public class StaticGLGenTask extends Task // ANT getters and setters /** *

          Set the package name for the generated files. This is called by ANT.

          - * + * * @param packageName the name of the package for the generated files */ public void setPackage(String packageName) @@ -125,12 +125,12 @@ public class StaticGLGenTask extends Task /** *

          Set the output directory. This is called by ANT.

          - * + * * @param directory the output directory */ public void setOutputDir(String directory) { - log( ("Setting output directory to: " + directory), + log( ("Setting output directory to: " + directory), Project.MSG_VERBOSE); this.outputDirectory = directory; } @@ -138,7 +138,7 @@ public class StaticGLGenTask extends Task /** *

          Add a header file to the list. This is called by ANT for a nested * element.

          - * + * * @return {@link org.apache.tools.ant.types.PatternSet.NameEntry} */ public PatternSet.NameEntry createHeader() @@ -149,7 +149,7 @@ public class StaticGLGenTask extends Task /** *

          Add a header file to the list. This is called by ANT for a nested * element.

          - * + * * @return {@link org.apache.tools.ant.types.PatternSet.NameEntry} */ public PatternSet.NameEntry createHeadersFile() @@ -171,7 +171,7 @@ public class StaticGLGenTask extends Task /** *

          Add an optional classpath that defines the location of {@link com.jogamp.gluegen.opengl.BuildStaticGLInfo} * and BuildStaticGLInfo's dependencies.

          - * + * * @returns {@link org.apache.tools.ant.types.Path} */ public Path createClasspath() @@ -183,23 +183,23 @@ public class StaticGLGenTask extends Task /** *

          Run the task. This involves validating the set attributes, creating * the command line to be executed and finally executing the command.

          - * + * * @see org.apache.tools.ant.Task#execute() */ - public void execute() - throws BuildException + public void execute() + throws BuildException { // validate that all of the required attributes have been set validateAttributes(); - + // TODO: add logic to determine if the generated file needs to be // regenerated - + // add the attributes to the CommandlineJava addAttributes(); log(glgenCommandline.describeCommand(), Project.MSG_VERBOSE); - + // execute the command and throw on error final int error = execute(glgenCommandline.getCommandline()); if(error == 1) @@ -208,11 +208,11 @@ public class StaticGLGenTask extends Task /** *

          Ensure that the user specified all required arguments.

          - * - * @throws BuildException if there are required arguments that are not + * + * @throws BuildException if there are required arguments that are not * present or not valid */ - private void validateAttributes() + private void validateAttributes() throws BuildException { // validate that the package name is set @@ -223,29 +223,29 @@ public class StaticGLGenTask extends Task // TODO: switch to file and ensure that it exists if(!isValid(outputDirectory)) throw new BuildException("Invalid output directory name: " + outputDirectory); - + // TODO: validate that there are headers set } /** *

          Is the specified string valid? A valid string is non-null * and has a non-zero length.

          - * + * * @param string the string to be tested for validity * @return true if the string is valid. false - * otherwise. + * otherwise. */ private boolean isValid(String string) { // check for null if(string == null) return false; - + // ensure that the string has a non-zero length // NOTE: must trim() to remove leading and trailing whitespace if(string.trim().length() < 1) return false; - + // the string is valid return true; } @@ -258,10 +258,10 @@ public class StaticGLGenTask extends Task { // add the package name glgenCommandline.createArgument().setValue(packageName); - + // add the output directory name glgenCommandline.createArgument().setValue(outputDirectory); - + // add the header -files- from the FileSet headerSet.setDir(getProject().getBaseDir()); DirectoryScanner directoryScanner = headerSet.getDirectoryScanner(getProject()); @@ -272,25 +272,25 @@ public class StaticGLGenTask extends Task } } - /** - *

          Execute {@link com.jogamp.gluegen.opengl.BuildStaticGLInfo} in a + /** + *

          Execute {@link com.jogamp.gluegen.opengl.BuildStaticGLInfo} in a * forked JVM.

          - * + * * @throws BuildException */ - private int execute(String[] command) + private int execute(String[] command) throws BuildException { // create the object that will perform the command execution Execute execute = new Execute(new LogStreamHandler(this, Project.MSG_INFO, - Project.MSG_WARN), + Project.MSG_WARN), null); - + // set the project and command line execute.setAntRun(project); execute.setCommandline(command); execute.setWorkingDirectory( project.getBaseDir() ); - + // execute the command try { diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureEmitter.java b/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureEmitter.java index adb1c2ae0..4ac9ae3f3 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureEmitter.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureEmitter.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2006 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 @@ -29,11 +29,11 @@ * 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. */ @@ -55,8 +55,8 @@ import java.util.Set; /** * Emitter producing NativeSignature attributes. - * - * Review: This Package/Class is not used and subject to be deleted. + * + * Review: This Package/Class is not used and subject to be deleted. */ public class NativeSignatureEmitter extends GLEmitter { diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java b/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java index e98478b6e..a17657382 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2006 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 @@ -29,11 +29,11 @@ * 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. */ @@ -182,14 +182,14 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding // Always emit outgoing "this" argument writer.print("long "); - writer.print(javaThisArgumentName()); + writer.print(javaThisArgumentName()); ++numEmitted; needComma = true; } for (int i = 0; i < binding.getNumArguments(); i++) { JavaType type = binding.getJavaArgumentType(i); - if (type.isVoid()) { + if (type.isVoid()) { // Make sure this is the only param to the method; if it isn't, // there's something wrong with our parsing of the headers. if (binding.getNumArguments() != 1) { @@ -198,7 +198,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding "multi-argument function \"" + binding + "\""); } continue; - } + } if (type.isJNIEnv() || binding.isArgumentThisPointer(i)) { // Don't need to expose these at the Java level @@ -229,7 +229,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding if (type.isNIOBuffer()) { writer.print(", int " + byteOffsetArgName(i)); } else if (type.isNIOBufferArray()) { - writer.print(", int[] " + + writer.print(", int[] " + byteOffsetArrayArgName(i)); } } @@ -246,7 +246,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding writer.print(" "); JavaType returnType = binding.getJavaReturnType(); boolean needsResultAssignment = false; - + if (!returnType.isVoid()) { if (returnType.isCompoundTypeWrapper() || returnType.isNIOByteBuffer()) { @@ -375,7 +375,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding // there's something wrong with our parsing of the headers. assert(binding.getNumArguments() == 1); continue; - } + } if (needComma) { writer.print(", "); diff --git a/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLNameResolver.java b/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLNameResolver.java index 92554776a..9b57a2f2d 100644 --- a/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLNameResolver.java +++ b/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLNameResolver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003-2005 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 @@ -29,11 +29,11 @@ * 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. - * + * */ package com.jogamp.gluegen.runtime.opengl; @@ -43,12 +43,12 @@ public class GLNameResolver { //GL_XYZ : GL_XYZ, GL_GL2_XYZ, GL_ARB_XYZ, GL_OES_XYZ, GL_OML_XYZ // // Pass-1 Unify ARB extensions with the same value - // Pass-2 Unify vendor extensions, + // Pass-2 Unify vendor extensions, // if exist as an ARB extension with the same value. // Pass-3 Emit public static final String[] extensionsARB = { "ARB", "GL2", "OES", "KHR", "OML" }; - public static final String[] extensionsVEN = { "3DFX", + public static final String[] extensionsVEN = { "3DFX", "AMD", "ANGLE", "ARM", @@ -158,7 +158,7 @@ public class GLNameResolver { return str; } public static final boolean isExtension(String str, boolean isGLFunc) { - return isExtension(extensionsARB, str, isGLFunc) || + return isExtension(extensionsARB, str, isGLFunc) || isExtension(extensionsVEN, str, isGLFunc); } diff --git a/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLProcAddressResolver.java b/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLProcAddressResolver.java index 9775de491..f8406075c 100644 --- a/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLProcAddressResolver.java +++ b/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLProcAddressResolver.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + /* * Created on Saturday, April 24 2010 16:44 */ diff --git a/src/jogl/classes/com/jogamp/graph/curve/OutlineShape.java b/src/jogl/classes/com/jogamp/graph/curve/OutlineShape.java index a3749788b..cb2885e0f 100644 --- a/src/jogl/classes/com/jogamp/graph/curve/OutlineShape.java +++ b/src/jogl/classes/com/jogamp/graph/curve/OutlineShape.java @@ -42,13 +42,13 @@ import com.jogamp.opengl.math.geom.AABBox; /** A Generic shape objects which is defined by a list of Outlines. * This Shape can be transformed to Triangulations. * The list of triangles generated are render-able by a Region object. - * The triangulation produced by this Shape will define the + * The triangulation produced by this Shape will define the * closed region defined by the outlines. - * + * * One or more OutlineShape Object can be associated to a region * this is left as a high-level representation of the Objects. For * optimizations, flexibility requirements for future features. - * + * *

          * Example to creating an Outline Shape: *
          @@ -60,18 +60,18 @@ import com.jogamp.opengl.math.geom.AABBox;
                 addVertex(...)
                 addVertex(...)
            * 
          - * - * The above will create two outlines each with three vertices. By adding these two outlines to + * + * The above will create two outlines each with three vertices. By adding these two outlines to * the OutlineShape, we are stating that the combination of the two outlines represent the shape. *
          - * - * To specify that the shape is curved at a region, the on-curve flag should be set to false + * + * To specify that the shape is curved at a region, the on-curve flag should be set to false * for the vertex that is in the middle of the curved region (if the curved region is defined by 3 * vertices (quadratic curve). *
          - * In case the curved region is defined by 4 or more vertices the middle vertices should both have + * In case the curved region is defined by 4 or more vertices the middle vertices should both have * the on-curve flag set to false. - * + * *
          Example:
          *
                 addVertex(0,0, true);
          @@ -79,16 +79,16 @@ import com.jogamp.opengl.math.geom.AABBox;
                 addVertex(1,1, false);
                 addVertex(1,0, true);
            * 
          - * - * The above snippet defines a cubic nurbs curve where (0,1 and 1,1) + * + * The above snippet defines a cubic nurbs curve where (0,1 and 1,1) * do not belong to the final rendered shape. - * + * * Implementation Notes:
          *
            *
          • The first vertex of any outline belonging to the shape should be on-curve
          • *
          • Intersections between off-curved parts of the outline is not handled
          • *
          - * + * * @see Outline * @see Region */ @@ -104,21 +104,21 @@ public class OutlineShape implements Comparable { VerticesState(int state){ this.state = state; } - } + } public static final int DIRTY_BOUNDS = 1 << 0; private final Vertex.Factory vertexFactory; private VerticesState outlineState; - /** The list of {@link Outline}s that are part of this + /** The list of {@link Outline}s that are part of this * outline shape. */ private ArrayList outlines; private AABBox bbox; /** dirty bits DIRTY_BOUNDS */ - private int dirtyBits; + private int dirtyBits; /** Create a new Outline based Shape */ @@ -128,7 +128,7 @@ public class OutlineShape implements Comparable { this.outlines.add(new Outline()); this.outlineState = VerticesState.UNDEFINED; this.bbox = new AABBox(); - this.dirtyBits = 0; + this.dirtyBits = 0; } /** Clears all data and reset all states as if this instance was newly created */ @@ -137,7 +137,7 @@ public class OutlineShape implements Comparable { outlines.add(new Outline()); outlineState = VerticesState.UNDEFINED; bbox.reset(); - dirtyBits = 0; + dirtyBits = 0; } /** Returns the associated vertex factory of this outline shape @@ -149,10 +149,10 @@ public class OutlineShape implements Comparable { return outlines.size(); } - /** Add a new empty {@link Outline} + /** Add a new empty {@link Outline} * to the end of this shape's outline list. *

          If the {@link #getLastOutline()} is empty already, no new one will be added.

          - * + * * After a call to this function all new vertices added * will belong to the new outline */ @@ -164,26 +164,26 @@ public class OutlineShape implements Comparable { /** Appends the {@link Outline} element to the end, * ensuring a clean tail. - * + * *

          A clean tail is ensured, no double empty Outlines are produced * and a pre-existing empty outline will be replaced with the given one.

          - * + * * @param outline Outline object to be added - * @throws NullPointerException if the {@link Outline} element is null + * @throws NullPointerException if the {@link Outline} element is null */ public void addOutline(Outline outline) throws NullPointerException { addOutline(outlines.size(), outline); } /** Insert the {@link Outline} element at the given {@code position}. - * + * *

          If the {@code position} indicates the end of this list, * a clean tail is ensured, no double empty Outlines are produced * and a pre-existing empty outline will be replaced with the given one.

          - * + * * @param position of the added Outline * @param outline Outline object to be added - * @throws NullPointerException if the {@link Outline} element is null + * @throws NullPointerException if the {@link Outline} element is null * @throws IndexOutOfBoundsException if position is out of range (position < 0 || position > getOutlineNumber()) */ public void addOutline(int position, Outline outline) throws NullPointerException, IndexOutOfBoundsException { @@ -213,7 +213,7 @@ public class OutlineShape implements Comparable { * using {@link #addOutline(Outline)} for each element. *

          Closes the current last outline via {@link #closeLastOutline()} before adding the new ones.

          * @param outlineShape OutlineShape elements to be added. - * @throws NullPointerException if the {@link OutlineShape} is null + * @throws NullPointerException if the {@link OutlineShape} is null * @throws IndexOutOfBoundsException if position is out of range (position < 0 || position > getOutlineNumber()) */ public void addOutlineShape(OutlineShape outlineShape) throws NullPointerException { @@ -228,10 +228,10 @@ public class OutlineShape implements Comparable { /** Replaces the {@link Outline} element at the given {@code position}. *

          Sets the bounding box dirty, hence a next call to {@link #getBounds()} will validate it.

          - * + * * @param position of the replaced Outline - * @param outline replacement Outline object - * @throws NullPointerException if the {@link Outline} element is null + * @param outline replacement Outline object + * @throws NullPointerException if the {@link Outline} element is null * @throws IndexOutOfBoundsException if position is out of range (position < 0 || position >= getOutlineNumber()) */ public void setOutline(int position, Outline outline) throws NullPointerException, IndexOutOfBoundsException { @@ -244,7 +244,7 @@ public class OutlineShape implements Comparable { /** Removes the {@link Outline} element at the given {@code position}. *

          Sets the bounding box dirty, hence a next call to {@link #getBounds()} will validate it.

          - * + * * @param position of the to be removed Outline * @throws IndexOutOfBoundsException if position is out of range (position < 0 || position >= getOutlineNumber()) */ @@ -261,15 +261,15 @@ public class OutlineShape implements Comparable { return outlines.get(outlines.size()-1); } - /** @return the {@code Outline} at {@code position} + /** @return the {@code Outline} at {@code position} * @throws IndexOutOfBoundsException if position is out of range (position < 0 || position >= getOutlineNumber()) */ public Outline getOutline(int position) throws IndexOutOfBoundsException { return outlines.get(position); - } + } /** Adds a vertex to the last open outline in the - * shape. + * shape. * @param v the vertex to be added to the OutlineShape */ public final void addVertex(Vertex v) { @@ -280,9 +280,9 @@ public class OutlineShape implements Comparable { } } - /** Adds a vertex to the last open outline in the shape. - * at {@code position} - * @param position indx at which the vertex will be added + /** Adds a vertex to the last open outline in the shape. + * at {@code position} + * @param position indx at which the vertex will be added * @param v the vertex to be added to the OutlineShape */ public final void addVertex(int position, Vertex v) { @@ -295,7 +295,7 @@ public class OutlineShape implements Comparable { /** Add a 2D {@link Vertex} to the last outline by defining the coordniate attribute * of the vertex. The 2D vertex will be represented as Z=0. - * + * * @param x the x coordinate * @param y the y coordniate * @param onCurve flag if this vertex is on the final curve or defines a curved region @@ -317,10 +317,10 @@ public class OutlineShape implements Comparable { addVertex(vertexFactory.create(x, y, z, onCurve)); } - /** Add a vertex to the last outline by passing a float array and specifying the - * offset and length in which. The attributes of the vertex are located. + /** Add a vertex to the last outline by passing a float array and specifying the + * offset and length in which. The attributes of the vertex are located. * The attributes should be continuous (stride = 0). - * Attributes which value are not set (when length less than 3) + * Attributes which value are not set (when length less than 3) * are set implicitly to zero. * @param coordsBuffer the coordinate array where the vertex attributes are to be picked from * @param offset the offset in the buffer to the x coordinate @@ -330,11 +330,11 @@ public class OutlineShape implements Comparable { */ public final void addVertex(float[] coordsBuffer, int offset, int length, boolean onCurve) { addVertex(vertexFactory.create(coordsBuffer, offset, length, onCurve)); - } + } /** Closes the last outline in the shape. *

          If last vertex is not equal to first vertex. - * A new temp vertex is added at the end which + * A new temp vertex is added at the end which * is equal to the first.

          */ public void closeLastOutline() { @@ -351,7 +351,7 @@ public class OutlineShape implements Comparable { /** Ensure the outlines represent * the specified destinationType. * and removes all overlaps in boundary triangles - * @param destinationType the target outline's vertices state. Currently only + * @param destinationType the target outline's vertices state. Currently only * {@link OutlineShape.VerticesState#QUADRATIC_NURBS} are supported. */ public void transformOutlines(VerticesState destinationType) { @@ -371,7 +371,7 @@ public class OutlineShape implements Comparable { float[] v2 = VectorUtil.mid(v1, v3); //drop off-curve vertex to image on the curve - b.setCoord(v2, 0, 3); + b.setCoord(v2, 0, 3); b.setOnCurve(true); outline.addVertex(index, vertexFactory.create(v1, 0, 3, false)); @@ -379,19 +379,19 @@ public class OutlineShape implements Comparable { } /** Check overlaps between curved triangles - * first check if any vertex in triangle a is in triangle b + * first check if any vertex in triangle a is in triangle b * second check if edges of triangle a intersect segments of triangle b * if any of the two tests is true we divide current triangle * and add the other to the list of overlaps - * + * * Loop until overlap array is empty. (check only in first pass) */ - private void checkOverlaps() { + private void checkOverlaps() { ArrayList overlaps = new ArrayList(3); int count = getOutlineNumber(); boolean firstpass = true; do { - for (int cc = 0; cc < count; cc++) { + for (int cc = 0; cc < count; cc++) { final Outline outline = getOutline(cc); int vertexCount = outline.getVertexCount(); for(int i=0; i < outline.getVertexCount(); i++) { @@ -429,7 +429,7 @@ public class OutlineShape implements Comparable { private Vertex checkTriOverlaps(Vertex a, Vertex b, Vertex c) { int count = getOutlineNumber(); - for (int cc = 0; cc < count; cc++) { + for (int cc = 0; cc < count; cc++) { final Outline outline = getOutline(cc); int vertexCount = outline.getVertexCount(); for(int i=0; i < vertexCount; i++) { @@ -451,7 +451,7 @@ public class OutlineShape implements Comparable { return current; } - if(VectorUtil.tri2SegIntersection(a, b, c, prevV, current) + if(VectorUtil.tri2SegIntersection(a, b, c, prevV, current) || VectorUtil.tri2SegIntersection(a, b, c, current, nextV) || VectorUtil.tri2SegIntersection(a, b, c, prevV, nextV)) { return current; @@ -463,7 +463,7 @@ public class OutlineShape implements Comparable { private void transformOutlines2Quadratic() { int count = getOutlineNumber(); - for (int cc = 0; cc < count; cc++) { + for (int cc = 0; cc < count; cc++) { final Outline outline = getOutline(cc); int vertexCount = outline.getVertexCount(); @@ -471,13 +471,13 @@ public class OutlineShape implements Comparable { final Vertex currentVertex = outline.getVertex(i); final Vertex nextVertex = outline.getVertex((i+1)%vertexCount); if ( !currentVertex.isOnCurve() && !nextVertex.isOnCurve() ) { - final float[] newCoords = VectorUtil.mid(currentVertex.getCoord(), + final float[] newCoords = VectorUtil.mid(currentVertex.getCoord(), nextVertex.getCoord()); final Vertex v = vertexFactory.create(newCoords, 0, 3, true); i++; vertexCount++; outline.addVertex(i, v); - } + } } if(vertexCount <= 0) { outlines.remove(outline); @@ -487,7 +487,7 @@ public class OutlineShape implements Comparable { } if( vertexCount > 0 ) { - if(VectorUtil.checkEquality(outline.getVertex(0).getCoord(), + if(VectorUtil.checkEquality(outline.getVertex(0).getCoord(), outline.getLastVertex().getCoord())) { outline.removeVertex(vertexCount-1); } @@ -508,7 +508,7 @@ public class OutlineShape implements Comparable { } } - /** @return the list of concatenated vertices associated with all + /** @return the list of concatenated vertices associated with all * {@code Outline}s of this object */ public ArrayList getVertices() { @@ -551,7 +551,7 @@ public class OutlineShape implements Comparable { } /** Compare two outline shapes with Bounding Box area - * as criteria. + * as criteria. * @see java.lang.Comparable#compareTo(java.lang.Object) */ public final int compareTo(OutlineShape outline) { @@ -579,12 +579,12 @@ public class OutlineShape implements Comparable { validateBoundingBox(); } return bbox; - } + } /** * @param obj the Object to compare this OutlineShape with - * @return true if {@code obj} is an OutlineShape, not null, - * same outlineState, equal bounds and equal outlines in the same order + * @return true if {@code obj} is an OutlineShape, not null, + * same outlineState, equal bounds and equal outlines in the same order */ public boolean equals(Object obj) { if( obj == this) { @@ -592,7 +592,7 @@ public class OutlineShape implements Comparable { } if( null == obj || !(obj instanceof OutlineShape) ) { return false; - } + } final OutlineShape o = (OutlineShape) obj; if(getOutlineState() != o.getOutlineState()) { return false; @@ -625,5 +625,5 @@ public class OutlineShape implements Comparable { o.outlines.add(outlines.get(i).clone()); } return o; - } + } } diff --git a/src/jogl/classes/com/jogamp/graph/curve/Region.java b/src/jogl/classes/com/jogamp/graph/curve/Region.java index 8b6d000fa..a9779523a 100644 --- a/src/jogl/classes/com/jogamp/graph/curve/Region.java +++ b/src/jogl/classes/com/jogamp/graph/curve/Region.java @@ -38,48 +38,48 @@ import com.jogamp.opengl.math.geom.AABBox; /** Abstract Outline shape GL representation * define the method an OutlineShape(s) is * binded rendered. - * + * * @see GLRegion */ public abstract class Region { - + /** Debug flag for region impl (graph.curve) */ public static final boolean DEBUG = Debug.debug("graph.curve"); - + public static final boolean DEBUG_INSTANCE = false; - /** View based Anti-Aliasing, A Two pass region rendering, slower - * and more resource hungry (FBO), but AA is perfect. - * Otherwise the default fast one pass MSAA region rendering is being used. + /** View based Anti-Aliasing, A Two pass region rendering, slower + * and more resource hungry (FBO), but AA is perfect. + * Otherwise the default fast one pass MSAA region rendering is being used. */ public static final int VBAA_RENDERING_BIT = 1 << 0; /** Use non uniform weights [0.0 .. 1.9] for curve region rendering. - * Otherwise the default weight 1.0 for uniform curve region rendering is being applied. + * Otherwise the default weight 1.0 for uniform curve region rendering is being applied. */ public static final int VARIABLE_CURVE_WEIGHT_BIT = 1 << 1; public static final int TWO_PASS_DEFAULT_TEXTURE_UNIT = 0; private final int renderModes; - private boolean dirty = true; - protected int numVertices = 0; + private boolean dirty = true; + protected int numVertices = 0; protected final AABBox box = new AABBox(); protected ArrayList triangles = new ArrayList(); protected ArrayList vertices = new ArrayList(); - public static boolean isVBAA(int renderModes) { - return 0 != ( renderModes & Region.VBAA_RENDERING_BIT ); + public static boolean isVBAA(int renderModes) { + return 0 != ( renderModes & Region.VBAA_RENDERING_BIT ); } /** Check if render mode capable of non uniform weights - * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, - * {@link Region#VBAA_RENDERING_BIT} + * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, + * {@link Region#VBAA_RENDERING_BIT} * @return true of capable of non uniform weights */ - public static boolean isNonUniformWeight(int renderModes) { - return 0 != ( renderModes & Region.VARIABLE_CURVE_WEIGHT_BIT ); + public static boolean isNonUniformWeight(int renderModes) { + return 0 != ( renderModes & Region.VARIABLE_CURVE_WEIGHT_BIT ); } protected Region(int regionRenderModes) { @@ -87,28 +87,28 @@ public abstract class Region { } /** Get current Models - * @return bit-field of render modes + * @return bit-field of render modes */ - public final int getRenderModes() { - return renderModes; + public final int getRenderModes() { + return renderModes; } /** Check if current Region is using VBAA * @return true if capable of two pass rendering - VBAA */ - public boolean isVBAA() { - return Region.isVBAA(renderModes); + public boolean isVBAA() { + return Region.isVBAA(renderModes); } - /** Check if current instance uses non uniform weights + /** Check if current instance uses non uniform weights * @return true if capable of nonuniform weights */ - public boolean isNonUniformWeight() { - return Region.isNonUniformWeight(renderModes); + public boolean isNonUniformWeight() { + return Region.isNonUniformWeight(renderModes); } /** Get the current number of vertices associated - * with this region. This number is not necessary equal to + * with this region. This number is not necessary equal to * the OGL bound number of vertices. * @return vertices count */ @@ -117,10 +117,10 @@ public abstract class Region { } /** Adds a {@link Triangle} object to the Region - * This triangle will be bound to OGL objects + * This triangle will be bound to OGL objects * on the next call to {@code update} * @param tri a triangle object - * + * * @see update(GL2ES2) */ public void addTriangle(Triangle tri) { @@ -129,10 +129,10 @@ public abstract class Region { } /** Adds a list of {@link Triangle} objects to the Region - * These triangles are to be binded to OGL objects + * These triangles are to be binded to OGL objects * on the next call to {@code update} * @param tris an arraylist of triangle objects - * + * * @see update(GL2ES2) */ public void addTriangles(ArrayList tris) { @@ -141,10 +141,10 @@ public abstract class Region { } /** Adds a {@link Vertex} object to the Region - * This vertex will be bound to OGL objects + * This vertex will be bound to OGL objects * on the next call to {@code update} * @param vert a vertex objects - * + * * @see update(GL2ES2) */ public void addVertex(Vertex vert) { @@ -154,10 +154,10 @@ public abstract class Region { } /** Adds a list of {@link Vertex} objects to the Region - * These vertices are to be binded to OGL objects + * These vertices are to be binded to OGL objects * on the next call to {@code update} * @param verts an arraylist of vertex objects - * + * * @see update(GL2ES2) */ public void addVertices(ArrayList verts) { @@ -175,10 +175,10 @@ public abstract class Region { } /** Check if this region is dirty. A region is marked dirty - * when new Vertices, Triangles, and or Lines are added after a + * when new Vertices, Triangles, and or Lines are added after a * call to update() * @return true if region is Dirty, false otherwise - * + * * @see update(GL2ES2) */ public final boolean isDirty() { diff --git a/src/jogl/classes/com/jogamp/graph/curve/opengl/GLRegion.java b/src/jogl/classes/com/jogamp/graph/curve/opengl/GLRegion.java index 63713887b..dfb7a95b3 100644 --- a/src/jogl/classes/com/jogamp/graph/curve/opengl/GLRegion.java +++ b/src/jogl/classes/com/jogamp/graph/curve/opengl/GLRegion.java @@ -41,32 +41,32 @@ import jogamp.graph.curve.opengl.RegionFactory; /** A GLRegion is the OGL binding of one or more OutlineShapes * Defined by its vertices and generated triangles. The Region - * defines the final shape of the OutlineShape(s), which shall produced a shaded + * defines the final shape of the OutlineShape(s), which shall produced a shaded * region on the screen. - * - * Implementations of the GLRegion shall take care of the OGL + * + * Implementations of the GLRegion shall take care of the OGL * binding of the depending on its context, profile. - * + * * @see Region, RegionFactory, OutlineShape */ -public abstract class GLRegion extends Region { - +public abstract class GLRegion extends Region { + /** Create an ogl {@link GLRegion} defining the list of {@link OutlineShape}. * Combining the Shapes into single buffers. * @return the resulting Region inclusive the generated region */ public static GLRegion create(OutlineShape[] outlineShapes, int renderModes) { final GLRegion region = RegionFactory.create(renderModes); - + int numVertices = region.getNumVertices(); - + for(int index=0; index triangles = outlineShape.triangulate(); region.addTriangles(triangles); - + ArrayList vertices = outlineShape.getVertices(); for(int pos=0; pos < vertices.size(); pos++){ Vertex vert = vertices.get(pos); @@ -74,42 +74,42 @@ public abstract class GLRegion extends Region { } region.addVertices(vertices); } - + return region; } - /** + /** * Create an ogl {@link GLRegion} defining this {@link OutlineShape} * @return the resulting Region. */ public static GLRegion create(OutlineShape outlineShape, int renderModes) { final GLRegion region = RegionFactory.create(renderModes); - + outlineShape.transformOutlines(OutlineShape.VerticesState.QUADRATIC_NURBS); ArrayList triangles = (ArrayList) outlineShape.triangulate(); ArrayList vertices = (ArrayList) outlineShape.getVertices(); region.addVertices(vertices); region.addTriangles(triangles); return region; - } - + } + protected GLRegion(int renderModes) { super(renderModes); } - + /** Updates a graph region by updating the ogl related * objects for use in rendering if {@link #isDirty()}. - *

          Allocates the ogl related data and initializes it the 1st time.

          + *

          Allocates the ogl related data and initializes it the 1st time.

          *

          Called by {@link #draw(GL2ES2, RenderState, int, int, int)}.

          * @param rs TODO */ protected abstract void update(GL2ES2 gl, RenderState rs); - + /** Delete and clean the associated OGL * objects */ public abstract void destroy(GL2ES2 gl, RenderState rs); - + /** Renders the associated OGL objects specifying * current width/hight of window for multi pass rendering * of the region. @@ -117,13 +117,13 @@ public abstract class GLRegion extends Region { * @param rs the RenderState to be used * @param vp_width current screen width * @param vp_height current screen height - * @param texWidth desired texture width for multipass-rendering. + * @param texWidth desired texture width for multipass-rendering. * The actual used texture-width is written back when mp rendering is enabled, otherwise the store is untouched. */ public final void draw(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int[/*1*/] texWidth) { update(gl, rs); drawImpl(gl, rs, vp_width, vp_height, texWidth); } - + protected abstract void drawImpl(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int[/*1*/] texWidth); } diff --git a/src/jogl/classes/com/jogamp/graph/curve/opengl/RegionRenderer.java b/src/jogl/classes/com/jogamp/graph/curve/opengl/RegionRenderer.java index 2f078d7bb..f7d4bfd2f 100644 --- a/src/jogl/classes/com/jogamp/graph/curve/opengl/RegionRenderer.java +++ b/src/jogl/classes/com/jogamp/graph/curve/opengl/RegionRenderer.java @@ -35,26 +35,26 @@ import com.jogamp.graph.curve.Region; public abstract class RegionRenderer extends Renderer { - /** + /** * Create a Hardware accelerated Region Renderer. - * @param rs the used {@link RenderState} - * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, {@link Region#VBAA_RENDERING_BIT} + * @param rs the used {@link RenderState} + * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, {@link Region#VBAA_RENDERING_BIT} * @return an instance of Region Renderer */ public static RegionRenderer create(RenderState rs, int renderModes) { return new jogamp.graph.curve.opengl.RegionRendererImpl01(rs, renderModes); } - + protected RegionRenderer(RenderState rs, int renderModes) { super(rs, renderModes); } - - + + /** Render an {@link OutlineShape} in 3D space at the position provided * the triangles of the shapes will be generated, if not yet generated * @param region the OutlineShape to Render. - * @param position the initial translation of the outlineShape. - * @param texWidth desired texture width for multipass-rendering. + * @param position the initial translation of the outlineShape. + * @param texWidth desired texture width for multipass-rendering. * The actual used texture-width is written back when mp rendering is enabled, otherwise the store is untouched. * @throws Exception if HwRegionRenderer not initialized */ @@ -65,10 +65,10 @@ public abstract class RegionRenderer extends Renderer { if( !areRenderModesCompatible(region) ) { throw new GLException("Incompatible render modes, : region modes "+region.getRenderModes()+ " doesn't contain renderer modes "+this.getRenderModes()); - } + } drawImpl(gl, region, position, texWidth); } - + /** * Usually just dispatched the draw call to the Region's draw implementation, * e.g. {@link com.jogamp.graph.curve.opengl.GLRegion#draw(GL2ES2, RenderState, int, int, int[]) GLRegion#draw(GL2ES2, RenderState, int, int, int[])}. @@ -79,6 +79,6 @@ public abstract class RegionRenderer extends Renderer { protected void destroyImpl(GL2ES2 gl) { // nop } - - + + } diff --git a/src/jogl/classes/com/jogamp/graph/curve/opengl/RenderState.java b/src/jogl/classes/com/jogamp/graph/curve/opengl/RenderState.java index 5e305d664..9c833fd24 100644 --- a/src/jogl/classes/com/jogamp/graph/curve/opengl/RenderState.java +++ b/src/jogl/classes/com/jogamp/graph/curve/opengl/RenderState.java @@ -40,7 +40,7 @@ import com.jogamp.opengl.util.glsl.ShaderState; public abstract class RenderState { private static final String thisKey = "jogamp.graph.curve.RenderState" ; - + public static RenderState createRenderState(ShaderState st, Vertex.Factory pointFactory) { return new RenderStateImpl(st, pointFactory); } @@ -48,42 +48,42 @@ public abstract class RenderState { public static RenderState createRenderState(ShaderState st, Vertex.Factory pointFactory, PMVMatrix pmvMatrix) { return new RenderStateImpl(st, pointFactory, pmvMatrix); } - + public static final RenderState getRenderState(GL2ES2 gl) { return (RenderState) gl.getContext().getAttachedObject(thisKey); } - + protected final ShaderState st; protected final Vertex.Factory vertexFactory; protected final PMVMatrix pmvMatrix; - protected final GLUniformData gcu_PMVMatrix; - + protected final GLUniformData gcu_PMVMatrix; + protected RenderState(ShaderState st, Vertex.Factory vertexFactory, PMVMatrix pmvMatrix) { this.st = st; this.vertexFactory = vertexFactory; - this.pmvMatrix = pmvMatrix; + this.pmvMatrix = pmvMatrix; this.gcu_PMVMatrix = new GLUniformData(UniformNames.gcu_PMVMatrix, 4, 4, pmvMatrix.glGetPMvMatrixf()); - st.ownUniform(gcu_PMVMatrix); + st.ownUniform(gcu_PMVMatrix); } - + public final ShaderState getShaderState() { return st; } public final Vertex.Factory getVertexFactory() { return vertexFactory; } public final PMVMatrix pmvMatrix() { return pmvMatrix; } public final GLUniformData getPMVMatrix() { return gcu_PMVMatrix; } - + public void destroy(GL2ES2 gl) { st.destroy(gl); } - + public abstract GLUniformData getWeight(); public abstract GLUniformData getAlpha(); public abstract GLUniformData getColorStatic(); // public abstract GLUniformData getStrength(); - + public final RenderState attachTo(GL2ES2 gl) { return (RenderState) gl.getContext().attachObject(thisKey, this); } - + public final boolean detachFrom(GL2ES2 gl) { RenderState _rs = (RenderState) gl.getContext().getAttachedObject(thisKey); if(_rs == this) { @@ -91,8 +91,8 @@ public abstract class RenderState { return true; } return false; - } - + } + public StringBuilder toString(StringBuilder sb, boolean alsoUnlocated) { if(null==sb) { sb = new StringBuilder(); @@ -104,8 +104,8 @@ public abstract class RenderState { return sb; } - + public String toString() { return toString(null, false).toString(); - } + } } diff --git a/src/jogl/classes/com/jogamp/graph/curve/opengl/Renderer.java b/src/jogl/classes/com/jogamp/graph/curve/opengl/Renderer.java index 998129551..c642fb652 100644 --- a/src/jogl/classes/com/jogamp/graph/curve/opengl/Renderer.java +++ b/src/jogl/classes/com/jogamp/graph/curve/opengl/Renderer.java @@ -52,8 +52,8 @@ public abstract class Renderer { protected int vp_height; protected boolean initialized; protected final RenderState rs; - private boolean vboSupported = false; - + private boolean vboSupported = false; + public final boolean isInitialized() { return initialized; } public final int getWidth() { return vp_width; } @@ -62,29 +62,29 @@ public abstract class Renderer { public float getWeight() { return rs.getWeight().floatValue(); } public float getAlpha() { return rs.getAlpha().floatValue(); } public final PMVMatrix getMatrix() { return rs.pmvMatrix(); } - + /** * Implementation shall load, compile and link the shader program and leave it active. * @param gl referencing the current GLContext to which the ShaderState is bound to * @return */ protected abstract boolean initShaderProgram(GL2ES2 gl); - + protected abstract void destroyImpl(GL2ES2 gl); - + /** - * @param rs the used {@link RenderState} + * @param rs the used {@link RenderState} * @param renderModes bit-field of modes */ protected Renderer(RenderState rs, int renderModes) { this.rs = rs; this.renderModes = renderModes; } - + public final int getRenderModes() { return renderModes; } - + public boolean usesVariableCurveWeight() { return Region.isNonUniformWeight(renderModes); } /** @@ -93,17 +93,17 @@ public abstract class Renderer { */ public final boolean areRenderModesCompatible(Region region) { final int cleanRenderModes = getRenderModes() & ( Region.VARIABLE_CURVE_WEIGHT_BIT ); - return cleanRenderModes == ( region.getRenderModes() & cleanRenderModes ); + return cleanRenderModes == ( region.getRenderModes() & cleanRenderModes ); } - + public final boolean isVBOSupported() { return vboSupported; } - - /** + + /** * Initialize shader and bindings for GPU based rendering bound to the given GL object's GLContext * if not initialized yet. *

          Leaves the renderer enabled, ie ShaderState.

          *

          Shall be called by a {@code draw()} method, e.g. {@link RegionRenderer#draw(GL2ES2, Region, float[], int)}

          - * + * * @param gl referencing the current GLContext to which the ShaderState is bound to * @throws GLException if initialization failed */ @@ -117,48 +117,48 @@ public abstract class Renderer { gl.isFunctionAvailable("glDrawElements") && gl.isFunctionAvailable("glVertexAttribPointer") && gl.isFunctionAvailable("glDeleteBuffers"); - + if(DEBUG) { System.err.println("TextRendererImpl01: VBO Supported = " + isVBOSupported()); } - + if(!vboSupported){ throw new GLException("VBO not supported"); } - + rs.attachTo(gl); - + gl.glEnable(GL2ES2.GL_BLEND); gl.glBlendFunc(GL2ES2.GL_SRC_ALPHA, GL2ES2.GL_ONE_MINUS_SRC_ALPHA); // FIXME: alpha blending stage ? - + initialized = initShaderProgram(gl); if(!initialized) { throw new GLException("Shader initialization failed"); } - + if(!rs.getShaderState().uniform(gl, rs.getPMVMatrix())) { throw new GLException("Error setting PMVMatrix in shader: "+rs.getShaderState()); } - + if( Region.isNonUniformWeight( getRenderModes() ) ) { if(!rs.getShaderState().uniform(gl, rs.getWeight())) { throw new GLException("Error setting weight in shader: "+rs.getShaderState()); } } - + if(!rs.getShaderState().uniform(gl, rs.getAlpha())) { throw new GLException("Error setting global alpha in shader: "+rs.getShaderState()); - } - + } + if(!rs.getShaderState().uniform(gl, rs.getColorStatic())) { throw new GLException("Error setting global color in shader: "+rs.getShaderState()); - } + } } - public final void flushCache(GL2ES2 gl) { + public final void flushCache(GL2ES2 gl) { // FIXME: REMOVE ! } - + public void destroy(GL2ES2 gl) { if(!initialized){ if(DEBUG_INSTANCE) { @@ -169,13 +169,13 @@ public abstract class Renderer { rs.getShaderState().useProgram(gl, false); destroyImpl(gl); rs.destroy(gl); - initialized = false; + initialized = false; } - + public final RenderState getRenderState() { return rs; } public final ShaderState getShaderState() { return rs.getShaderState(); } - - public final void enable(GL2ES2 gl, boolean enable) { + + public final void enable(GL2ES2 gl, boolean enable) { rs.getShaderState().useProgram(gl, enable); } @@ -188,7 +188,7 @@ public abstract class Renderer { rs.getShaderState().uniform(gl, rs.getWeight()); } } - + public void setAlpha(GL2ES2 gl, float alpha_t) { rs.getAlpha().setData(alpha_t); if(null != gl && rs.getShaderState().inUse()) { @@ -199,11 +199,11 @@ public abstract class Renderer { public void getColorStatic(GL2ES2 gl, float[] rgb) { FloatBuffer fb = (FloatBuffer) rs.getColorStatic().getBuffer(); - rgb[0] = fb.get(0); - rgb[1] = fb.get(1); - rgb[2] = fb.get(2); + rgb[0] = fb.get(0); + rgb[1] = fb.get(1); + rgb[2] = fb.get(2); } - + public void setColorStatic(GL2ES2 gl, float r, float g, float b){ FloatBuffer fb = (FloatBuffer) rs.getColorStatic().getBuffer(); fb.put(0, r); @@ -213,7 +213,7 @@ public abstract class Renderer { rs.getShaderState().uniform(gl, rs.getColorStatic()); } } - + public void rotate(GL2ES2 gl, float angle, float x, float y, float z) { rs.pmvMatrix().glRotatef(angle, x, y, z); updateMatrix(gl); @@ -223,7 +223,7 @@ public abstract class Renderer { rs.pmvMatrix().glTranslatef(x, y, z); updateMatrix(gl); } - + public void scale(GL2ES2 gl, float x, float y, float z) { rs.pmvMatrix().glScalef(x, y, z); updateMatrix(gl); @@ -261,15 +261,15 @@ public abstract class Renderer { p.glLoadIdentity(); p.glOrthof(0, width, 0, height, near, far); updateMatrix(gl); - return true; + return true; } protected String getVertexShaderName() { return "curverenderer" + getImplVersion(); } - + protected String getFragmentShaderName() { - final String version = getImplVersion(); + final String version = getImplVersion(); final String pass = Region.isVBAA(renderModes) ? "-2pass" : "-1pass" ; final String weight = Region.isNonUniformWeight(renderModes) ? "-weight" : "" ; return "curverenderer" + version + pass + weight; @@ -277,7 +277,7 @@ public abstract class Renderer { // FIXME: Really required to have sampler2D def. precision ? If not, we can drop getFragmentShaderPrecision(..) and use default ShaderCode .. public static final String es2_precision_fp = "\nprecision mediump float;\nprecision mediump int;\nprecision mediump sampler2D;\n"; - + protected String getFragmentShaderPrecision(GL2ES2 gl) { if( gl.isGLES2() ) { return es2_precision_fp; @@ -287,7 +287,7 @@ public abstract class Renderer { } return null; } - + protected String getImplVersion() { return "01"; } diff --git a/src/jogl/classes/com/jogamp/graph/curve/opengl/TextRenderer.java b/src/jogl/classes/com/jogamp/graph/curve/opengl/TextRenderer.java index 8dc41b0c0..f6ce852d8 100644 --- a/src/jogl/classes/com/jogamp/graph/curve/opengl/TextRenderer.java +++ b/src/jogl/classes/com/jogamp/graph/curve/opengl/TextRenderer.java @@ -38,28 +38,28 @@ import jogamp.graph.curve.text.GlyphString; import com.jogamp.graph.font.Font; public abstract class TextRenderer extends Renderer { - /** + /** * Create a Hardware accelerated Text Renderer. - * @param rs the used {@link RenderState} + * @param rs the used {@link RenderState} * @param renderModes either {@link com.jogamp.graph.curve.opengl.GLRegion#SINGLE_PASS} or {@link com.jogamp.graph.curve.Region#VBAA_RENDERING_BIT} */ public static TextRenderer create(RenderState rs, int renderModes) { return new jogamp.graph.curve.opengl.TextRendererImpl01(rs, renderModes); } - + protected TextRenderer(RenderState rs, int type) { super(rs, type); } - + /** Render the String in 3D space wrt to the font provided at the position provided * the outlines will be generated, if not yet generated * @param gl the current GL state * @param font {@link Font} to be used - * @param str text to be rendered - * @param position the lower left corner of the string + * @param str text to be rendered + * @param position the lower left corner of the string * @param fontSize font size - * @param texWidth desired texture width for multipass-rendering. + * @param texWidth desired texture width for multipass-rendering. * The actual used texture-width is written back when mp rendering is enabled, otherwise the store is untouched. * @throws Exception if TextRenderer not initialized */ @@ -77,11 +77,11 @@ public abstract class TextRenderer extends Renderer { if(DEBUG_INSTANCE) { System.err.println("createString: "+getCacheSize()+"/"+getCacheLimit()+" - "+Font.NAME_UNIQUNAME + " - " + str + " - " + size); } - final GlyphString glyphString = GlyphString.createString(null, rs.getVertexFactory(), font, size, str); - glyphString.createRegion(gl, renderModes); + final GlyphString glyphString = GlyphString.createString(null, rs.getVertexFactory(), font, size, str); + glyphString.createRegion(gl, renderModes); return glyphString; } - + /** FIXME public void flushCache(GL2ES2 gl) { Iterator iterator = stringCacheMap.values().iterator(); @@ -89,10 +89,10 @@ public abstract class TextRenderer extends Renderer { GlyphString glyphString = iterator.next(); glyphString.destroy(gl, rs); } - stringCacheMap.clear(); + stringCacheMap.clear(); stringCacheArray.clear(); } */ - + @Override protected void destroyImpl(GL2ES2 gl) { // fluchCache(gl) already called @@ -101,42 +101,42 @@ public abstract class TextRenderer extends Renderer { GlyphString glyphString = iterator.next(); glyphString.destroy(gl, rs); } - stringCacheMap.clear(); + stringCacheMap.clear(); stringCacheArray.clear(); } - + /** *

          Sets the cache limit for reusing GlyphString's and their Region. * Default is {@link #DEFAULT_CACHE_LIMIT}, -1 unlimited, 0 turns cache off, >0 limited

          - * + * *

          The cache will be validate when the next string rendering happens.

          - * + * * @param newLimit new cache size - * + * * @see #DEFAULT_CACHE_LIMIT */ public final void setCacheLimit(int newLimit ) { stringCacheLimit = newLimit; } - + /** * Sets the cache limit, see {@link #setCacheLimit(int)} and validates the cache. - * + * * @see #setCacheLimit(int) - * + * * @param gl current GL used to remove cached objects if required * @param newLimit new cache size */ public final void setCacheLimit(GL2ES2 gl, int newLimit ) { stringCacheLimit = newLimit; validateCache(gl, 0); } - + /** * @return the current cache limit */ public final int getCacheLimit() { return stringCacheLimit; } - - /** + + /** * @return the current utilized cache size, <= {@link #getCacheLimit()} */ public final int getCacheSize() { return stringCacheArray.size(); } - + protected final void validateCache(GL2ES2 gl, int space) { if ( getCacheLimit() > 0 ) { while ( getCacheSize() + space > getCacheLimit() ) { @@ -144,7 +144,7 @@ public abstract class TextRenderer extends Renderer { } } } - + protected final GlyphString getCachedGlyphString(Font font, String str, int fontSize) { return stringCacheMap.get(getKey(font, str, fontSize)); } @@ -160,13 +160,13 @@ public abstract class TextRenderer extends Renderer { } /// else overwrite is nop .. } } - + protected final void removeCachedGlyphString(GL2ES2 gl, Font font, String str, int fontSize) { final String key = getKey(font, str, fontSize); GlyphString glyphString = stringCacheMap.remove(key); if(null != glyphString) { glyphString.destroy(gl, rs); - } + } stringCacheArray.remove(key); } @@ -177,7 +177,7 @@ public abstract class TextRenderer extends Renderer { glyphString.destroy(gl, rs); } } - + protected final String getKey(Font font, String str, int fontSize) { final StringBuilder sb = new StringBuilder(); return font.getName(sb, Font.NAME_UNIQUNAME) @@ -186,8 +186,8 @@ public abstract class TextRenderer extends Renderer { /** Default cache limit, see {@link #setCacheLimit(int)} */ public static final int DEFAULT_CACHE_LIMIT = 256; - + private HashMap stringCacheMap = new HashMap(DEFAULT_CACHE_LIMIT); private ArrayList stringCacheArray = new ArrayList(DEFAULT_CACHE_LIMIT); - private int stringCacheLimit = DEFAULT_CACHE_LIMIT; + private int stringCacheLimit = DEFAULT_CACHE_LIMIT; } \ No newline at end of file diff --git a/src/jogl/classes/com/jogamp/graph/curve/tess/Triangulation.java b/src/jogl/classes/com/jogamp/graph/curve/tess/Triangulation.java index 7728efcaf..ae2849536 100644 --- a/src/jogl/classes/com/jogamp/graph/curve/tess/Triangulation.java +++ b/src/jogl/classes/com/jogamp/graph/curve/tess/Triangulation.java @@ -33,7 +33,7 @@ import jogamp.graph.curve.tess.CDTriangulator2D; public class Triangulation { /** Create a new instance of a triangulation. - * Currently only a modified version of Constraint Delaunay + * Currently only a modified version of Constraint Delaunay * is implemented. * @return instance of a triangulator * @see Triangulator diff --git a/src/jogl/classes/com/jogamp/graph/curve/tess/Triangulator.java b/src/jogl/classes/com/jogamp/graph/curve/tess/Triangulator.java index 1ffaccebc..4e8c400e0 100644 --- a/src/jogl/classes/com/jogamp/graph/curve/tess/Triangulator.java +++ b/src/jogl/classes/com/jogamp/graph/curve/tess/Triangulator.java @@ -36,32 +36,32 @@ import com.jogamp.graph.geom.Triangle; /** Interface to the triangulation algorithms provided * A triangulation of 2D outlines where you can * provides an easy one or more outlines to be triangulated - * + * * example usage: * addCurve(o1); * addCurve(o2); * addCurve(o3); * generate(); * reset(); - * + * * @see Outline * @see Triangulation */ public interface Triangulator { - + /** Add a curve to the list of Outlines * describing the shape * @param outline a bounding {@link Outline} */ public void addCurve(Outline outline); - - /** Generate the triangulation of the provided + + /** Generate the triangulation of the provided * List of {@link Outline}s * @return an arraylist of {@link Triangle}s resembling the * final shape. */ public ArrayList generate(); - + /** Reset the triangulation to initial state * Clearing cached data */ diff --git a/src/jogl/classes/com/jogamp/graph/font/Font.java b/src/jogl/classes/com/jogamp/graph/font/Font.java index 64a3a3e6c..82211da92 100644 --- a/src/jogl/classes/com/jogamp/graph/font/Font.java +++ b/src/jogl/classes/com/jogamp/graph/font/Font.java @@ -31,10 +31,10 @@ import com.jogamp.opengl.math.geom.AABBox; /** * Interface wrapper for font implementation. - * + * * TrueType Font Specification: * http://developer.apple.com/fonts/ttrefman/rm06/Chap6.html - * + * * TrueType Font Table Introduction: * http://scripts.sil.org/cms/scripts/page.php?item_id=IWS-Chapter08 */ @@ -50,22 +50,22 @@ public interface Font { public static final int NAME_VERSION = 5; public static final int NAME_MANUFACTURER = 8; public static final int NAME_DESIGNER = 9; - - + + /** * Metrics for font - * + * * Depending on the font's direction, horizontal or vertical, * the following tables shall be used: - * + * * Vertical http://developer.apple.com/fonts/TTRefMan/RM06/Chap6vhea.html * Horizontal http://developer.apple.com/fonts/TTRefMan/RM06/Chap6hhea.html */ - public interface Metrics { + public interface Metrics { float getAscent(float pixelSize); float getDescent(float pixelSize); float getLineGap(float pixelSize); - float getMaxExtend(float pixelSize); + float getMaxExtend(float pixelSize); float getScale(float pixelSize); AABBox getBBox(float pixelSize); } @@ -74,12 +74,12 @@ public interface Font { * Glyph for font */ public interface Glyph { - // reserved special glyph IDs + // reserved special glyph IDs // http://scripts.sil.org/cms/scripts/page.php?item_id=IWS-Chapter08#ba57949e public static final int ID_UNKNOWN = 0; public static final int ID_CR = 2; public static final int ID_SPACE = 3; - + public Font getFont(); public char getSymbol(); public AABBox getBBox(float pixelSize); @@ -89,25 +89,25 @@ public interface Font { public String getName(int nameIndex); public StringBuilder getName(StringBuilder string, int nameIndex); - + /** Shall return the family and subfamily name, separated a dash. *

          {@link #getName(StringBuilder, int)} w/ {@link #NAME_FAMILY} and {@link #NAME_SUBFAMILY}

          *

          Example: "{@code Ubuntu-Regular}"

          */ public StringBuilder getFullFamilyName(StringBuilder buffer); - + public StringBuilder getAllNames(StringBuilder string, String separator); - + public float getAdvanceWidth(int i, float pixelSize); public Metrics getMetrics(); public Glyph getGlyph(char symbol); public int getNumGlyphs(); - + public float getStringWidth(CharSequence string, float pixelSize); public float getStringHeight(CharSequence string, float pixelSize); public AABBox getStringBounds(CharSequence string, float pixelSize); - - public boolean isPrintableChar( char c ); - + + public boolean isPrintableChar( char c ); + /** Shall return {@link #getFullFamilyName()} */ public String toString(); } \ No newline at end of file diff --git a/src/jogl/classes/com/jogamp/graph/font/FontFactory.java b/src/jogl/classes/com/jogamp/graph/font/FontFactory.java index d2824b9dc..884662e6e 100644 --- a/src/jogl/classes/com/jogamp/graph/font/FontFactory.java +++ b/src/jogl/classes/com/jogamp/graph/font/FontFactory.java @@ -49,13 +49,13 @@ import jogamp.graph.font.UbuntuFontLoader; public class FontFactory { private static final String FontConstructorPropKey = "jogamp.graph.font.ctor"; private static final String DefaultFontConstructor = "jogamp.graph.font.typecast.TypecastFontConstructor"; - + /** Ubuntu is the default font family */ public static final int UBUNTU = 0; - + /** Java fonts are optional */ public static final int JAVA = 1; - + private static final FontConstructor fontConstr; static { @@ -63,18 +63,18 @@ public class FontFactory { * For example: * "jogamp.graph.font.typecast.TypecastFontFactory" (default) * "jogamp.graph.font.ttf.TTFFontImpl" - */ + */ String fontImplName = PropertyAccess.getProperty(FontConstructorPropKey, true); if(null == fontImplName) { fontImplName = DefaultFontConstructor; } fontConstr = (FontConstructor) ReflectionUtil.createInstance(fontImplName, FontFactory.class.getClassLoader()); } - + public static final FontSet getDefault() { return get(UBUNTU); } - + public static final FontSet get(int font) { switch (font) { case JAVA: @@ -83,15 +83,15 @@ public class FontFactory { return UbuntuFontLoader.get(); } } - + public static final Font get(File file) throws IOException { return fontConstr.create(file); } public static final Font get(final URLConnection conn) throws IOException { return fontConstr.create(conn); - } - + } + public static boolean isPrintableChar( char c ) { if( Character.isWhitespace(c) ) { return true; @@ -101,5 +101,5 @@ public class FontFactory { } final Character.UnicodeBlock block = Character.UnicodeBlock.of( c ); return block != null && block != Character.UnicodeBlock.SPECIALS; - } + } } diff --git a/src/jogl/classes/com/jogamp/graph/font/FontSet.java b/src/jogl/classes/com/jogamp/graph/font/FontSet.java index d376922ab..17b8b2136 100644 --- a/src/jogl/classes/com/jogamp/graph/font/FontSet.java +++ b/src/jogl/classes/com/jogamp/graph/font/FontSet.java @@ -34,29 +34,29 @@ public interface FontSet { /** Font family REGULAR **/ public static final int FAMILY_REGULAR = 0; - + /** Font family LIGHT **/ public static final int FAMILY_LIGHT = 1; - + /** Font family MEDIUM **/ public static final int FAMILY_MEDIUM = 2; - + /** Font family CONDENSED **/ public static final int FAMILY_CONDENSED = 3; - + /** Font family MONO **/ public static final int FAMILY_MONOSPACED = 4; - + /** SERIF style/family bit flag. Fallback to Sans Serif. */ public static final int STYLE_SERIF = 1 << 1; - + /** BOLD style bit flag */ public static final int STYLE_BOLD = 1 << 2; - + /** ITALIC style bit flag */ public static final int STYLE_ITALIC = 1 << 3; Font getDefault() throws IOException ; - + Font get(int family, int stylebits) throws IOException ; } diff --git a/src/jogl/classes/com/jogamp/graph/geom/Outline.java b/src/jogl/classes/com/jogamp/graph/geom/Outline.java index 12c45860b..dfa6a8635 100644 --- a/src/jogl/classes/com/jogamp/graph/geom/Outline.java +++ b/src/jogl/classes/com/jogamp/graph/geom/Outline.java @@ -36,12 +36,12 @@ import com.jogamp.opengl.math.geom.AABBox; /** Define a single continuous stroke by control vertices. - * The vertices define the shape of the region defined by this + * The vertices define the shape of the region defined by this * outline. The Outline can contain a list of off-curve and on-curve * vertices which define curved regions. - * + * * Note: An outline should be closed to be rendered as a region. - * + * * @see OutlineShape, Region */ public class Outline implements Cloneable, Comparable { @@ -55,7 +55,7 @@ public class Outline implements Cloneable, Comparable { * An outline can contain off Curve vertices which define curved * regions in the outline. */ - public Outline() { + public Outline() { } public final int getVertexCount() { @@ -64,7 +64,7 @@ public class Outline implements Cloneable, Comparable { /** Appends a vertex to the outline loop/strip. * @param vertex Vertex to be added - * @throws NullPointerException if the {@link Vertex} element is null + * @throws NullPointerException if the {@link Vertex} element is null */ public final void addVertex(Vertex vertex) throws NullPointerException { addVertex(vertices.size(), vertex); @@ -73,7 +73,7 @@ public class Outline implements Cloneable, Comparable { /** Insert the {@link Vertex} element at the given {@code position} to the outline loop/strip. * @param position of the added Vertex * @param vertex Vertex object to be added - * @throws NullPointerException if the {@link Vertex} element is null + * @throws NullPointerException if the {@link Vertex} element is null * @throws IndexOutOfBoundsException if position is out of range (position < 0 || position > getVertexNumber()) */ public final void addVertex(int position, Vertex vertex) throws NullPointerException, IndexOutOfBoundsException { @@ -88,10 +88,10 @@ public class Outline implements Cloneable, Comparable { /** Replaces the {@link Vertex} element at the given {@code position}. *

          Sets the bounding box dirty, hence a next call to {@link #getBounds()} will validate it.

          - * + * * @param position of the replaced Vertex - * @param vertex replacement Vertex object - * @throws NullPointerException if the {@link Outline} element is null + * @param vertex replacement Vertex object + * @throws NullPointerException if the {@link Outline} element is null * @throws IndexOutOfBoundsException if position is out of range (position < 0 || position >= getVertexNumber()) */ public final void setVertex(int position, Vertex vertex) throws NullPointerException, IndexOutOfBoundsException { @@ -112,12 +112,12 @@ public class Outline implements Cloneable, Comparable { /** Removes the {@link Vertex} element at the given {@code position}. *

          Sets the bounding box dirty, hence a next call to {@link #getBounds()} will validate it.

          - * + * * @param position of the to be removed Vertex * @throws IndexOutOfBoundsException if position is out of range (position < 0 || position >= getVertexNumber()) */ public final Vertex removeVertex(int position) throws IndexOutOfBoundsException { - dirtyBBox = true; + dirtyBBox = true; return vertices.remove(position); } @@ -139,7 +139,7 @@ public class Outline implements Cloneable, Comparable { /** * Use the given outline loop/strip. *

          Validates the bounding box.

          - * + * * @param vertices the new outline loop/strip */ public final void setVertices(ArrayList vertices) { @@ -152,7 +152,7 @@ public class Outline implements Cloneable, Comparable { } /** define if this outline is closed or not. - * if set to closed, checks if the last vertex is + * if set to closed, checks if the last vertex is * equal to the first vertex. If not Equal adds a * vertex at the end to the list. * @param closed @@ -170,7 +170,7 @@ public class Outline implements Cloneable, Comparable { } /** Compare two outlines with Bounding Box area - * as criteria. + * as criteria. * @see java.lang.Comparable#compareTo(java.lang.Object) */ public final int compareTo(Outline outline) { @@ -198,11 +198,11 @@ public class Outline implements Cloneable, Comparable { validateBoundingBox(); } return bbox; - } + } /** * @param obj the Object to compare this Outline with - * @return true if {@code obj} is an Outline, not null, equals bounds and equal vertices in the same order + * @return true if {@code obj} is an Outline, not null, equals bounds and equal vertices in the same order */ public boolean equals(Object obj) { if( obj == this) { @@ -210,7 +210,7 @@ public class Outline implements Cloneable, Comparable { } if( null == obj || !(obj instanceof Outline) ) { return false; - } + } final Outline o = (Outline) obj; if(getVertexCount() != o.getVertexCount()) { return false; @@ -240,5 +240,5 @@ public class Outline implements Cloneable, Comparable { o.vertices.add(vertices.get(i).clone()); } return o; - } + } } diff --git a/src/jogl/classes/com/jogamp/graph/geom/Triangle.java b/src/jogl/classes/com/jogamp/graph/geom/Triangle.java index fb34de221..bd0900495 100644 --- a/src/jogl/classes/com/jogamp/graph/geom/Triangle.java +++ b/src/jogl/classes/com/jogamp/graph/geom/Triangle.java @@ -48,11 +48,11 @@ public class Triangle { public Vertex[] getVertices() { return vertices; } - + public boolean isEdgesBoundary() { return boundaryEdges[0] || boundaryEdges[1] || boundaryEdges[2]; } - + public boolean isVerticesBoundary() { return boundaryVertices[0] || boundaryVertices[1] || boundaryVertices[2]; } @@ -60,11 +60,11 @@ public class Triangle { public void setEdgesBoundary(boolean[] boundary) { this.boundaryEdges = boundary; } - + public boolean[] getEdgeBoundary() { return boundaryEdges; } - + public boolean[] getVerticesBoundary() { return boundaryVertices; } @@ -72,7 +72,7 @@ public class Triangle { public void setVerticesBoundary(boolean[] boundaryVertices) { this.boundaryVertices = boundaryVertices; } - + public String toString() { return "Tri ID: " + id + "\n" + vertices[0] + "\n" + vertices[1] + "\n" + vertices[2]; } diff --git a/src/jogl/classes/com/jogamp/graph/geom/Vertex.java b/src/jogl/classes/com/jogamp/graph/geom/Vertex.java index e3df86de1..40048235e 100644 --- a/src/jogl/classes/com/jogamp/graph/geom/Vertex.java +++ b/src/jogl/classes/com/jogamp/graph/geom/Vertex.java @@ -30,7 +30,7 @@ package com.jogamp.graph.geom; import com.jogamp.opengl.math.Vert3fImmutable; /** - * A Vertex with custom memory layout using custom factory. + * A Vertex with custom memory layout using custom factory. */ public interface Vertex extends Vert3fImmutable, Cloneable { @@ -39,16 +39,16 @@ public interface Vertex extends Vert3fImmutable, Cloneable { T create(float x, float y, float z, boolean onCurve); - T create(float[] coordsBuffer, int offset, int length, boolean onCurve); + T create(float[] coordsBuffer, int offset, int length, boolean onCurve); } - + void setCoord(float x, float y, float z); /** * @see System#arraycopy(Object, int, Object, int, int) for thrown IndexOutOfBoundsException */ void setCoord(float[] coordsBuffer, int offset, int length); - + void setX(float x); void setY(float y); @@ -60,24 +60,24 @@ public interface Vertex extends Vert3fImmutable, Cloneable { void setOnCurve(boolean onCurve); int getId(); - + void setId(int id); - + float[] getTexCoord(); - + void setTexCoord(float s, float t); - + /** * @see System#arraycopy(Object, int, Object, int, int) for thrown IndexOutOfBoundsException */ void setTexCoord(float[] texCoordsBuffer, int offset, int length); - + /** * @param obj the Object to compare this Vertex with - * @return true if {@code obj} is a Vertex and not null, on-curve flag is equal and has same vertex- and tex-coords. + * @return true if {@code obj} is a Vertex and not null, on-curve flag is equal and has same vertex- and tex-coords. */ boolean equals(Object obj); - + /** * @return deep clone of this Vertex */ diff --git a/src/jogl/classes/com/jogamp/graph/geom/opengl/SVertex.java b/src/jogl/classes/com/jogamp/graph/geom/opengl/SVertex.java index 97e438b63..6b07688a7 100644 --- a/src/jogl/classes/com/jogamp/graph/geom/opengl/SVertex.java +++ b/src/jogl/classes/com/jogamp/graph/geom/opengl/SVertex.java @@ -39,11 +39,11 @@ public class SVertex implements Vertex { protected float[] coord = new float[3]; protected boolean onCurve; private float[] texCoord = new float[2]; - + static final Factory factory = new Factory(); - - public static Factory factory() { return factory; } - + + public static Factory factory() { return factory; } + public static class Factory implements Vertex.Factory { public SVertex create() { return new SVertex(); @@ -55,9 +55,9 @@ public class SVertex implements Vertex { public SVertex create(float[] coordsBuffer, int offset, int length, boolean onCurve) { return new SVertex(coordsBuffer, offset, length, onCurve); - } + } } - + public SVertex() { } @@ -65,19 +65,19 @@ public class SVertex implements Vertex { setCoord(x, y, z); setOnCurve(onCurve); } - + public SVertex(float[] coordsBuffer, int offset, int length, boolean onCurve) { setCoord(coordsBuffer, offset, length); setOnCurve(onCurve); } - - public SVertex(float[] coordsBuffer, int offset, int length, + + public SVertex(float[] coordsBuffer, int offset, int length, float[] texCoordsBuffer, int offsetTC, int lengthTC, boolean onCurve) { setCoord(coordsBuffer, offset, length); setTexCoord(texCoordsBuffer, offsetTC, lengthTC); setOnCurve(onCurve); } - + public final void setCoord(float x, float y, float z) { this.coord[0] = x; this.coord[1] = y; @@ -87,12 +87,12 @@ public class SVertex implements Vertex { public final void setCoord(float[] coordsBuffer, int offset, int length) { System.arraycopy(coordsBuffer, offset, coord, 0, length); } - + @Override public int getCoordCount() { return 3; } - + @Override public final float[] getCoord() { return coord; @@ -133,11 +133,11 @@ public class SVertex implements Vertex { public final int getId(){ return id; } - + public final void setId(int id){ this.id = id; } - + public boolean equals(Object obj) { if( obj == this) { return true; @@ -146,12 +146,12 @@ public class SVertex implements Vertex { return false; } final Vertex v = (Vertex) obj; - return this == v || - isOnCurve() == v.isOnCurve() && + return this == v || + isOnCurve() == v.isOnCurve() && VectorUtil.checkEqualityVec2(getTexCoord(), v.getTexCoord()) && VectorUtil.checkEquality(getCoord(), v.getCoord()) ; } - + public final float[] getTexCoord() { return texCoord; } @@ -164,16 +164,16 @@ public class SVertex implements Vertex { public final void setTexCoord(float[] texCoordsBuffer, int offset, int length) { System.arraycopy(texCoordsBuffer, offset, texCoord, 0, length); } - + /** * @return deep clone of this Vertex, but keeping the id blank */ public SVertex clone(){ return new SVertex(this.coord, 0, 3, this.texCoord, 0, 2, this.onCurve); } - + public String toString() { - return "[ID: " + id + ", onCurve: " + onCurve + + return "[ID: " + id + ", onCurve: " + onCurve + ": p " + coord[0] + ", " + coord[1] + ", " + coord[2] + ", t " + texCoord[0] + ", " + texCoord[1] + "]"; } diff --git a/src/jogl/classes/com/jogamp/opengl/FBObject.java b/src/jogl/classes/com/jogamp/opengl/FBObject.java index 7060bb7d1..c78b2b83d 100644 --- a/src/jogl/classes/com/jogamp/opengl/FBObject.java +++ b/src/jogl/classes/com/jogamp/opengl/FBObject.java @@ -46,7 +46,7 @@ import com.jogamp.opengl.FBObject.Attachment.Type; /** * Core utility class simplifying usage of framebuffer objects (FBO) - * with all {@link GLProfile}s. + * with all {@link GLProfile}s. *

          * Supports on-the-fly reconfiguration of dimension and multisample buffers via {@link #reset(GL, int, int, int, boolean)} * while preserving the {@link Attachment} references. @@ -55,50 +55,50 @@ import com.jogamp.opengl.FBObject.Attachment.Type; * Integrates default read/write framebuffers via {@link GLContext#getDefaultReadFramebuffer()} and {@link GLContext#getDefaultReadFramebuffer()}, * which is being hooked at {@link GL#glBindFramebuffer(int, int)} when the default (zero) framebuffer is selected. *

          - * + * *

          FIXME: Implement support for {@link Type#DEPTH_TEXTURE}, {@link Type#STENCIL_TEXTURE} .

          */ public class FBObject { protected static final boolean DEBUG = Debug.debug("FBObject"); private static final boolean FBOResizeQuirk = false; - + private static enum DetachAction { NONE, DISPOSE, RECREATE }; - - /** + + /** * Marker interface, denotes a color buffer attachment. *

          Always an instance of {@link Attachment}.

          - *

          Either an instance of {@link ColorAttachment} or {@link TextureAttachment}. + *

          Either an instance of {@link ColorAttachment} or {@link TextureAttachment}. */ - public static interface Colorbuffer { - /** + public static interface Colorbuffer { + /** * Initializes the color buffer and set it's parameter, if uninitialized, i.e. name is zero. * @return true if newly initialized, otherwise false. - * @throws GLException if buffer generation or setup fails. The just created buffer name will be deleted in this case. + * @throws GLException if buffer generation or setup fails. The just created buffer name will be deleted in this case. */ public boolean initialize(GL gl) throws GLException; - - /** + + /** * Releases the color buffer if initialized, i.e. name is not zero. - * @throws GLException if buffer release fails. + * @throws GLException if buffer release fails. */ public void free(GL gl) throws GLException; - + /** * Writes the internal format to the given GLCapabilities object. * @param caps the destination for format bits * @param rgba8Avail whether rgba8 is available */ - public void formatToGLCapabilities(GLCapabilities caps, boolean rgba8Avail); + public void formatToGLCapabilities(GLCapabilities caps, boolean rgba8Avail); } - + /** Common super class of all attachments */ public static abstract class Attachment { - public enum Type { + public enum Type { NONE, DEPTH, STENCIL, DEPTH_STENCIL, COLOR, COLOR_TEXTURE, DEPTH_TEXTURE, STENCIL_TEXTURE; - - /** + + /** * Returns {@link #COLOR}, {@link #DEPTH}, {@link #STENCIL} or {@link #DEPTH_STENCIL} - * @throws IllegalArgumentException if format cannot be handled. + * @throws IllegalArgumentException if format cannot be handled. */ public static Type determine(int format) throws IllegalArgumentException { switch(format) { @@ -120,20 +120,20 @@ public class FBObject { return Type.DEPTH_STENCIL; default: throw new IllegalArgumentException("format invalid: "+toHexString(format)); - } + } } }; - + /** immutable type [{@link #COLOR}, {@link #DEPTH}, {@link #STENCIL}, {@link #COLOR_TEXTURE}, {@link #DEPTH_TEXTURE}, {@link #STENCIL_TEXTURE} ] */ public final Type type; - + /** immutable the internal format */ public final int format; - + private int width, height; - + private int name; - + protected Attachment(Type type, int iFormat, int width, int height, int name) { this.type = type; this.format = iFormat; @@ -141,18 +141,18 @@ public class FBObject { this.height = height; this.name = name; } - + /** * Writes the internal format to the given GLCapabilities object. * @param caps the destination for format bits * @param rgba8Avail whether rgba8 is available */ - public final void formatToGLCapabilities(GLCapabilities caps, boolean rgba8Avail) { + public final void formatToGLCapabilities(GLCapabilities caps, boolean rgba8Avail) { final int _format; switch(format) { case GL.GL_RGBA: case 4: - _format = rgba8Avail ? GL.GL_RGBA8 : GL.GL_RGBA4; + _format = rgba8Avail ? GL.GL_RGBA8 : GL.GL_RGBA4; break; case GL.GL_RGB: case 3: @@ -191,7 +191,7 @@ public class FBObject { caps.setGreenBits(8); caps.setBlueBits(8); caps.setAlphaBits(8); - break; + break; case GL.GL_DEPTH_COMPONENT16: caps.setDepthBits(16); break; @@ -218,18 +218,18 @@ public class FBObject { throw new IllegalArgumentException("format invalid: "+toHexString(format)); } } - + /** width of attachment */ public final int getWidth() { return width; } /** height of attachment */ public final int getHeight() { return height; } /* pp */ final void setSize(int w, int h) { width = w; height = h; } - + /** buffer name [1..max], maybe a texture or renderbuffer name, depending on type. */ - public final int getName() { return name; } + public final int getName() { return name; } /* pp */ final void setName(int n) { name = n; } - - /** + + /** * Initializes the attachment and set it's parameter, if uninitialized, i.e. name is zero. *

                       final boolean init = 0 == name;
          @@ -239,11 +239,11 @@ public class FBObject {
                       return init;
                    * 
          * @return true if newly initialized, otherwise false. - * @throws GLException if buffer generation or setup fails. The just created buffer name will be deleted in this case. + * @throws GLException if buffer generation or setup fails. The just created buffer name will be deleted in this case. */ public abstract boolean initialize(GL gl) throws GLException; - - /** + + /** * Releases the attachment if initialized, i.e. name is not zero. *
                       if(0 != name) {
          @@ -251,10 +251,10 @@ public class FBObject {
                           name = 0;
                       }
                    * 
          - * @throws GLException if buffer release fails. + * @throws GLException if buffer release fails. */ public abstract void free(GL gl) throws GLException; - + /** *

          * Comparison by {@link #type}, {@link #format}, {@link #width}, {@link #height} and {@link #name}. @@ -272,7 +272,7 @@ public class FBObject { height== a.height && name == a.name ; } - + /** *

          * Hashed by {@link #type}, {@link #format}, {@link #width}, {@link #height} and {@link #name}. @@ -289,14 +289,14 @@ public class FBObject { hash = ((hash << 5) - hash) + name; return hash; } - + int objectHashCode() { return super.hashCode(); } - + public String toString() { return getClass().getSimpleName()+"[type "+type+", format "+toHexString(format)+", "+width+"x"+height+ "; name "+toHexString(name)+", obj "+toHexString(objectHashCode())+"]"; } - + public static Type getType(int attachmentPoint, int maxColorAttachments) { if( GL.GL_COLOR_ATTACHMENT0 <= attachmentPoint && attachmentPoint < GL.GL_COLOR_ATTACHMENT0+maxColorAttachments ) { return Type.COLOR; @@ -304,9 +304,9 @@ public class FBObject { switch(attachmentPoint) { case GL.GL_DEPTH_ATTACHMENT: return Type.DEPTH; - case GL.GL_STENCIL_ATTACHMENT: + case GL.GL_STENCIL_ATTACHMENT: return Type.STENCIL; - default: + default: throw new IllegalArgumentException("Invalid attachment point "+toHexString(attachmentPoint)); } } @@ -315,7 +315,7 @@ public class FBObject { /** Other renderbuffer attachment which maybe a colorbuffer, depth or stencil. */ public static class RenderAttachment extends Attachment { private int samples; - + /** * @param type allowed types are {@link Type#DEPTH_STENCIL} {@link Type#DEPTH}, {@link Type#STENCIL} or {@link Type#COLOR} * @param iFormat @@ -328,11 +328,11 @@ public class FBObject { super(validateType(type), iFormat, width, height, name); this.samples = samples; } - + /** number of samples, or zero for no multisampling */ public final int getSamples() { return samples; } /* pp */ final void setSamples(int s) { samples = s; } - + private static Type validateType(Type type) { switch(type) { case DEPTH_STENCIL: @@ -340,11 +340,11 @@ public class FBObject { case STENCIL: case COLOR: return type; - default: + default: throw new IllegalArgumentException("Invalid type: "+type); } } - + /** *

          * Comparison by {@link #type}, {@link #format}, {@link #samples}, {@link #width}, {@link #height} and {@link #name}. @@ -358,7 +358,7 @@ public class FBObject { return super.equals(o) && samples == ((RenderAttachment)o).samples; } - + /** *

          * Hashed by {@link #type}, {@link #format}, {@link #samples}, {@link #width}, {@link #height} and {@link #name}. @@ -378,14 +378,14 @@ public class FBObject { final boolean init = 0 == getName(); if( init ) { checkPreGLError(gl); - + final int[] name = new int[] { -1 }; gl.glGenRenderbuffers(1, name, 0); setName(name[0]); - + gl.glBindRenderbuffer(GL.GL_RENDERBUFFER, getName()); if( samples > 0 ) { - ((GL2GL3)gl).glRenderbufferStorageMultisample(GL.GL_RENDERBUFFER, samples, format, getWidth(), getHeight()); + ((GL2GL3)gl).glRenderbufferStorageMultisample(GL.GL_RENDERBUFFER, samples, format, getWidth(), getHeight()); } else { gl.glRenderbufferStorage(GL.GL_RENDERBUFFER, format, getWidth(), getHeight()); } @@ -401,7 +401,7 @@ public class FBObject { } return init; } - + @Override public void free(GL gl) { final int[] name = new int[] { getName() }; @@ -413,20 +413,20 @@ public class FBObject { setName(0); } } - + public String toString() { return getClass().getSimpleName()+"[type "+type+", format "+toHexString(format)+", samples "+samples+", "+getWidth()+"x"+getHeight()+ ", name "+toHexString(getName())+", obj "+toHexString(objectHashCode())+"]"; } } - + /** Color render buffer attachment */ public static class ColorAttachment extends RenderAttachment implements Colorbuffer { public ColorAttachment(int iFormat, int samples, int width, int height, int name) { super(Type.COLOR, iFormat, samples, width, height, name); - } + } } - + /** Texture attachment */ public static class TextureAttachment extends Attachment implements Colorbuffer { /** details of the texture setup */ @@ -445,7 +445,7 @@ public class FBObject { * @param wrapT * @param name */ - public TextureAttachment(Type type, int iFormat, int width, int height, int dataFormat, int dataType, + public TextureAttachment(Type type, int iFormat, int width, int height, int dataFormat, int dataType, int magFilter, int minFilter, int wrapS, int wrapT, int name) { super(validateType(type), iFormat, width, height, name); this.dataFormat = dataFormat; @@ -455,35 +455,35 @@ public class FBObject { this.wrapS = wrapS; this.wrapT = wrapT; } - + private static Type validateType(Type type) { switch(type) { case COLOR_TEXTURE: case DEPTH_TEXTURE: case STENCIL_TEXTURE: return type; - default: + default: throw new IllegalArgumentException("Invalid type: "+type); } } - - /** + + /** * Initializes the texture and set it's parameter, if uninitialized, i.e. name is zero. - * @throws GLException if texture generation and setup fails. The just created texture name will be deleted in this case. + * @throws GLException if texture generation and setup fails. The just created texture name will be deleted in this case. */ @Override public boolean initialize(GL gl) throws GLException { final boolean init = 0 == getName(); if( init ) { checkPreGLError(gl); - - final int[] name = new int[] { -1 }; + + final int[] name = new int[] { -1 }; gl.glGenTextures(1, name, 0); if(0 == name[0]) { throw new GLException("null texture, "+this); } setName(name[0]); - + gl.glBindTexture(GL.GL_TEXTURE_2D, name[0]); if( 0 < magFilter ) { gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, magFilter); @@ -495,7 +495,7 @@ public class FBObject { gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, wrapS); } if( 0 < wrapT ) { - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, wrapT); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, wrapT); } boolean preTexImage2D = true; int glerr = gl.glGetError(); @@ -534,50 +534,50 @@ public class FBObject { "; min/mag "+toHexString(minFilter)+"/"+toHexString(magFilter)+ ", wrap S/T "+toHexString(wrapS)+"/"+toHexString(wrapT)+ "; name "+toHexString(getName())+", obj "+toHexString(objectHashCode())+"]"; - } + } } static String toHexString(int v) { return "0x"+Integer.toHexString(v); } - + /** - * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE}, + * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE}, * selecting the texture data type and format automatically. - * + * *

          Using default min/mag filter {@link GL#GL_NEAREST} and default wrapS/wrapT {@link GL#GL_CLAMP_TO_EDGE}.

          - * + * * @param glp the chosen {@link GLProfile} * @param alpha set to true if you request alpha channel, otherwise false; - * @param width texture width + * @param width texture width * @param height texture height * @return the created and uninitialized color {@link TextureAttachment} */ public static final TextureAttachment createColorTextureAttachment(GLProfile glp, boolean alpha, int width, int height) { return createColorTextureAttachment(glp, alpha, width, height, GL.GL_NEAREST, GL.GL_NEAREST, GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE); } - + /** - * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE}, + * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE}, * selecting the texture data type and format automatically. - * + * * @param glp the chosen {@link GLProfile} * @param alpha set to true if you request alpha channel, otherwise false; - * @param width texture width + * @param width texture width * @param height texture height * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER} - * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} + * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S} * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} * @return the created and uninitialized color {@link TextureAttachment} */ - public static final TextureAttachment createColorTextureAttachment(GLProfile glp, boolean alpha, int width, int height, + public static final TextureAttachment createColorTextureAttachment(GLProfile glp, boolean alpha, int width, int height, int magFilter, int minFilter, int wrapS, int wrapT) { final int textureInternalFormat, textureDataFormat, textureDataType; - if(glp.isGLES()) { + if(glp.isGLES()) { textureInternalFormat = alpha ? GL.GL_RGBA : GL.GL_RGB; textureDataFormat = alpha ? GL.GL_RGBA : GL.GL_RGB; textureDataType = GL.GL_UNSIGNED_BYTE; - } else { + } else { textureInternalFormat = alpha ? GL.GL_RGBA8 : GL.GL_RGB8; // textureInternalFormat = alpha ? GL.GL_RGBA : GL.GL_RGB; // textureInternalFormat = alpha ? 4 : 3; @@ -586,27 +586,27 @@ public class FBObject { } return createColorTextureAttachment(textureInternalFormat, width, height, textureDataFormat, textureDataType, magFilter, minFilter, wrapS, wrapT); } - + /** - * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE}. + * Creates a color {@link TextureAttachment}, i.e. type {@link Type#COLOR_TEXTURE}. * * @param internalFormat internalFormat parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} - * @param width texture width + * @param width texture width * @param height texture height * @param dataFormat format parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} * @param dataType type parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER} - * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} + * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S} * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} * @return the created and uninitialized color {@link TextureAttachment} */ public static final TextureAttachment createColorTextureAttachment(int internalFormat, int width, int height, int dataFormat, int dataType, int magFilter, int minFilter, int wrapS, int wrapT) { - return new TextureAttachment(Type.COLOR_TEXTURE, internalFormat, width, height, dataFormat, dataType, + return new TextureAttachment(Type.COLOR_TEXTURE, internalFormat, width, height, dataFormat, dataType, magFilter, minFilter, wrapS, wrapT, 0 /* name */); } - + private static boolean hasAlpha(int format) { switch(format) { case GL.GL_RGBA8: @@ -619,7 +619,7 @@ public class FBObject { return false; } } - + private boolean initialized; private boolean fullFBOSupport; private boolean rgba8Avail; @@ -629,7 +629,7 @@ public class FBObject { private boolean stencil04Avail; private boolean stencil08Avail; private boolean stencil16Avail; - private boolean packedDepthStencilAvail; + private boolean packedDepthStencilAvail; private int maxColorAttachments, maxSamples, maxTextureSize, maxRenderbufferSize; private int width, height, samples; @@ -639,21 +639,21 @@ public class FBObject { private boolean bound; private int colorAttachmentCount; - private Colorbuffer[] colorAttachmentPoints; // colorbuffer attachment points + private Colorbuffer[] colorAttachmentPoints; // colorbuffer attachment points private RenderAttachment depth, stencil; // depth and stencil maybe equal in case of packed-depth-stencil private FBObject samplingSink; // MSAA sink - private TextureAttachment samplingSinkTexture; + private TextureAttachment samplingSinkTexture; private boolean samplingSinkDirty; // // ColorAttachment helper .. // - + private final void validateColorAttachmentPointRange(int point) { if(!initialized) { throw new GLException("FBO not initialized"); - } + } if(maxColorAttachments != colorAttachmentPoints.length) { throw new InternalError("maxColorAttachments "+maxColorAttachments+", array.lenght "+colorAttachmentPoints); } @@ -661,14 +661,14 @@ public class FBObject { throw new IllegalArgumentException("attachment point out of range: "+point+", should be within [0.."+(maxColorAttachments-1)+"], "+this); } } - + private final void validateAddColorAttachment(int point, Colorbuffer ca) { validateColorAttachmentPointRange(point); if( null != colorAttachmentPoints[point] ) { throw new IllegalArgumentException("Cannot attach "+ca+", attachment point already in use by "+colorAttachmentPoints[point]+", "+this); - } + } } - + private final void addColorAttachment(int point, Colorbuffer ca) { validateColorAttachmentPointRange(point); final Colorbuffer c = colorAttachmentPoints[point]; @@ -678,7 +678,7 @@ public class FBObject { colorAttachmentPoints[point] = ca; colorAttachmentCount++; } - + private final void removeColorAttachment(int point, Colorbuffer ca) { validateColorAttachmentPointRange(point); final Colorbuffer c = colorAttachmentPoints[point]; @@ -688,20 +688,20 @@ public class FBObject { colorAttachmentPoints[point] = null; colorAttachmentCount--; } - + /** * Return the {@link Colorbuffer} attachment at attachmentPoint if it is attached to this FBO, otherwise null. - * + * * @see #attachColorbuffer(GL, boolean) * @see #attachColorbuffer(GL, boolean) * @see #attachTexture2D(GL, int, boolean, int, int, int, int) - * @see #attachTexture2D(GL, int, int, int, int, int, int, int, int) + * @see #attachTexture2D(GL, int, int, int, int, int, int, int, int) */ public final Colorbuffer getColorbuffer(int attachmentPoint) { - validateColorAttachmentPointRange(attachmentPoint); + validateColorAttachmentPointRange(attachmentPoint); return colorAttachmentPoints[attachmentPoint]; } - + /** * Finds the passed {@link Colorbuffer} within the valid range of attachment points * using reference comparison only. @@ -709,36 +709,36 @@ public class FBObject { * Note: Slow. Implementation uses a logN array search to save resources, i.e. not using a HashMap. *

          * @param ca the {@link Colorbuffer} to look for. - * @return -1 if the {@link Colorbuffer} could not be found, otherwise [0..{@link #getMaxColorAttachments()}-1] + * @return -1 if the {@link Colorbuffer} could not be found, otherwise [0..{@link #getMaxColorAttachments()}-1] */ public final int getColorbufferAttachmentPoint(Colorbuffer ca) { for(int i=0; ireference only. - * + * *

          * Note: Slow. Uses {@link #getColorbufferAttachmentPoint(Colorbuffer)} to determine it's attachment point * to be used for {@link #getColorbuffer(int)} *

          - * + * * @see #attachColorbuffer(GL, boolean) * @see #attachColorbuffer(GL, boolean) * @see #attachTexture2D(GL, int, boolean, int, int, int, int) - * @see #attachTexture2D(GL, int, int, int, int, int, int, int, int) + * @see #attachTexture2D(GL, int, int, int, int, int, int, int, int) */ public final Colorbuffer getColorbuffer(Colorbuffer ca) { final int p = getColorbufferAttachmentPoint(ca); return p>=0 ? getColorbuffer(p) : null; } - + /** * Creates an uninitialized FBObject instance. *

          @@ -747,7 +747,7 @@ public class FBObject { */ public FBObject() { this.initialized = false; - + // TBD @ init this.fullFBOSupport = false; this.rgba8Avail = false; @@ -762,7 +762,7 @@ public class FBObject { this.maxSamples=-1; this.maxTextureSize = 0; this.maxRenderbufferSize = 0; - + this.width = 0; this.height = 0; this.samples = 0; @@ -770,17 +770,17 @@ public class FBObject { this.ignoreStatus = false; this.fbName = 0; this.bound = false; - + this.colorAttachmentPoints = null; // at init .. this.colorAttachmentCount = 0; this.depth = null; - this.stencil = null; - + this.stencil = null; + this.samplingSink = null; this.samplingSinkTexture = null; this.samplingSinkDirty = true; } - + private void init(GL gl, int width, int height, int samples) throws GLException { if(initialized) { throw new GLException("FBO already initialized"); @@ -788,8 +788,8 @@ public class FBObject { if( !gl.hasBasicFBOSupport() ) { throw new GLException("FBO not supported w/ context: "+gl.getContext()+", "+this); } - fullFBOSupport = gl.hasFullFBOSupport(); - + fullFBOSupport = gl.hasFullFBOSupport(); + rgba8Avail = gl.isGL2GL3() || gl.isExtensionAvailable(GLExtensions.OES_rgb8_rgba8); depth24Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_depth24); depth32Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_depth32); @@ -797,15 +797,15 @@ public class FBObject { stencil04Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_stencil4); stencil08Avail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_stencil8); stencil16Avail = fullFBOSupport; - + packedDepthStencilAvail = fullFBOSupport || gl.isExtensionAvailable(GLExtensions.OES_packed_depth_stencil) || gl.isExtensionAvailable(GLExtensions.EXT_packed_depth_stencil) ; - + final boolean NV_fbo_color_attachments = gl.isExtensionAvailable(GLExtensions.NV_fbo_color_attachments); - + int val[] = new int[1]; - + checkPreGLError(gl); int realMaxColorAttachments = 1; @@ -818,24 +818,24 @@ public class FBObject { } catch (GLException gle) { gle.printStackTrace(); } } maxColorAttachments = realMaxColorAttachments <= 8 ? realMaxColorAttachments : 8; // cap to limit array size - + colorAttachmentPoints = new Colorbuffer[maxColorAttachments]; colorAttachmentCount = 0; - + maxSamples = gl.getMaxRenderbufferSamples(); gl.glGetIntegerv(GL.GL_MAX_TEXTURE_SIZE, val, 0); maxTextureSize = val[0]; gl.glGetIntegerv(GL.GL_MAX_RENDERBUFFER_SIZE, val, 0); maxRenderbufferSize = val[0]; - + checkPreGLError(gl); - + if( 0 >= width ) { width = 1; } if( 0 >= height ) { height = 1; } this.width = width; this.height = height; this.samples = samples <= maxSamples ? samples : maxSamples; - + if(DEBUG) { System.err.println("FBObject "+width+"x"+height+", "+samples+" -> "+this.samples+" samples"); System.err.println("fullFBOSupport: "+fullFBOSupport); @@ -856,16 +856,16 @@ public class FBObject { System.err.println(JoglVersion.getGLStrings(gl, null).toString()); System.err.println(gl.getContext()); } - + checkNoError(null, gl.glGetError(), "FBObject Init.pre"); // throws GLException if error - + if(width > 2 + maxTextureSize || height> 2 + maxTextureSize || width > maxRenderbufferSize || height> maxRenderbufferSize ) { throw new GLException("size "+width+"x"+height+" exceeds on of the maxima [texture "+maxTextureSize+", renderbuffer "+maxRenderbufferSize+"]"); } resetSamplingSink(gl); - + // generate fbo .. gl.glGenFramebuffers(1, val, 0); fbName = val[0]; @@ -874,15 +874,15 @@ public class FBObject { } // bind fbo .. - gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, fbName); - checkNoError(gl, gl.glGetError(), "FBObject Init.bindFB"); // throws GLException if error + gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, fbName); + checkNoError(gl, gl.glGetError(), "FBObject Init.bindFB"); // throws GLException if error if(!gl.glIsFramebuffer(fbName)) { checkNoError(gl, GL.GL_INVALID_VALUE, "FBObject Init.isFB"); // throws GLException } bound = true; samplingSinkDirty = true; initialized = true; - + vStatus = GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT; // always incomplete w/o attachments! if(DEBUG) { System.err.println("FBObject.init(): "+this); @@ -900,9 +900,9 @@ public class FBObject { * Incompatibility and hence recreation is forced if * the size or sample count doesn't match for subsequent calls. *

          - * + * *

          Leaves the FBO bound state untouched

          - * + * * @param gl the current GL context * @param newWidth * @param newHeight @@ -911,7 +911,7 @@ public class FBObject { public final void reset(GL gl, int newWidth, int newHeight) { reset(gl, newWidth, newHeight, 0, false); } - + /** * Initializes or resets this FBO's instance. *

          @@ -920,21 +920,21 @@ public class FBObject { * to match the new given parameters. *

          *

          - * Currently incompatibility and hence recreation of the attachments will be performed + * Currently incompatibility and hence recreation of the attachments will be performed * if the size or sample count doesn't match for subsequent calls. *

          - * + * *

          Leaves the FBO bound state untouched

          - * + * * @param gl the current GL context * @param newWidth the new width, it's minimum is capped to 1 * @param newHeight the new height, it's minimum is capped to 1 * @param newSamples if > 0, MSAA will be used, otherwise no multisampling. Will be capped to {@link #getMaxSamples()}. - * @param resetSamplingSink true calls {@link #resetSamplingSink(GL)} immediatly. + * @param resetSamplingSink true calls {@link #resetSamplingSink(GL)} immediatly. * false postpones resetting the sampling sink until {@link #use(GL, TextureAttachment)} or {@link #syncSamplingSink(GL)}, - * allowing to use the samples sink's FBO and texture until then. The latter is useful to benefit - * from implicit double buffering while resetting the sink just before it's being used, eg. at swap-buffer. - * + * allowing to use the samples sink's FBO and texture until then. The latter is useful to benefit + * from implicit double buffering while resetting the sink just before it's being used, eg. at swap-buffer. + * * @throws GLException in case of an error, i.e. size too big, etc .. */ public final void reset(GL gl, int newWidth, int newHeight, int newSamples, boolean resetSamplingSink) { @@ -942,9 +942,9 @@ public class FBObject { init(gl, newWidth, newHeight, newSamples); return; } - + newSamples = newSamples <= maxSamples ? newSamples : maxSamples; // clamp - + if( newWidth != width || newHeight != height || newSamples != samples ) { if( 0 >= newWidth ) { newWidth = 1; } if( 0 >= newHeight ) { newHeight = 1; } @@ -952,39 +952,39 @@ public class FBObject { newWidth > maxRenderbufferSize || newHeight > maxRenderbufferSize ) { throw new GLException("size "+width+"x"+height+" exceeds on of the maxima [texture "+maxTextureSize+", renderbuffer "+maxRenderbufferSize+"]"); } - + if(DEBUG) { System.err.println("FBObject.reset - START - "+width+"x"+height+", "+samples+" -> "+newWidth+"x"+newHeight+", "+newSamples+"; "+this); - } - + } + final boolean wasBound = isBound(); - + width = newWidth; height = newHeight; samples = newSamples; - + if(0 < samples && null == samplingSink ) { // needs valid samplingSink for detach*() -> bind() samplingSink = new FBObject(); samplingSink.init(gl, width, height, 0); } - detachAllImpl(gl, true , true); + detachAllImpl(gl, true , true); if(resetSamplingSink) { resetSamplingSink(gl); } - + samplingSinkDirty = true; if(!wasBound) { unbind(gl); } - + if(DEBUG) { System.err.println("FBObject.reset - END - "+this); } - } + } } - + /** * Writes the internal format of the attachments to the given GLCapabilities object. * @param caps the destination for format bits @@ -994,11 +994,11 @@ public class FBObject { caps.setNumSamples(samples); caps.setDepthBits(0); caps.setStencilBits(0); - + final Colorbuffer cb = samples > 0 ? getSamplingSink() : getColorbuffer(0); if(null != cb) { cb.formatToGLCapabilities(caps, rgba8Avail); - } + } if(null != depth) { depth.formatToGLCapabilities(caps, rgba8Avail); } @@ -1006,11 +1006,11 @@ public class FBObject { stencil.formatToGLCapabilities(caps, rgba8Avail); } } - - /** + + /** * Note that the status may reflect an incomplete state during transition of attachments. * @return The FB status. {@link GL.GL_FRAMEBUFFER_COMPLETE} if ok, otherwise return GL FBO error state or -1 - * @see #validateStatus() + * @see #validateStatus() */ public final int getStatus() { return vStatus; @@ -1020,15 +1020,15 @@ public class FBObject { public final String getStatusString() { return getStatusString(vStatus); } - + public static final String getStatusString(int fbStatus) { switch(fbStatus) { case -1: return "NOT A FBO"; - + case GL.GL_FRAMEBUFFER_COMPLETE: return "OK"; - + case GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: return("FBO incomplete attachment\n"); case GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: @@ -1043,21 +1043,21 @@ public class FBObject { return("FBO missing read buffer"); case GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: return("FBO missing multisample buffer"); - case GL3.GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: + case GL3.GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: return("FBO missing layer targets"); - + case GL.GL_FRAMEBUFFER_UNSUPPORTED: return("Unsupported FBO format"); case GL2GL3.GL_FRAMEBUFFER_UNDEFINED: return("FBO undefined"); - + case 0: return("FBO implementation fault"); default: return("FBO incomplete, implementation ERROR "+toHexString(fbStatus)); } } - + /** * The status may even be valid if incomplete during transition of attachments. * @see #getStatus() @@ -1066,7 +1066,7 @@ public class FBObject { switch(vStatus) { case GL.GL_FRAMEBUFFER_COMPLETE: return true; - + case GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: case GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: case GL.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: @@ -1079,29 +1079,29 @@ public class FBObject { // we are in transition return true; } - + case GL.GL_FRAMEBUFFER_UNSUPPORTED: case GL2GL3.GL_FRAMEBUFFER_UNDEFINED: - - case 0: + + case 0: default: if(DEBUG) { - System.err.println("Framebuffer " + fbName + " is incomplete, status = " + toHexString(vStatus) + + System.err.println("Framebuffer " + fbName + " is incomplete, status = " + toHexString(vStatus) + " : " + getStatusString(vStatus)); } return false; } } - + private static int checkPreGLError(GL gl) { int glerr = gl.glGetError(); if(DEBUG && GL.GL_NO_ERROR != glerr) { System.err.println("Pre-existing GL error: "+toHexString(glerr)); Thread.dumpStack(); } - return glerr; + return glerr; } - + private final boolean checkNoError(GL gl, int err, String exceptionMessage) throws GLException { if(GL.GL_NO_ERROR != err) { if(null != gl) { @@ -1118,17 +1118,17 @@ public class FBObject { private final void checkInitialized() throws GLException { if(!initialized) { throw new GLException("FBO not initialized, call init(GL) first."); - } + } } - + /** * Attaches a {@link Colorbuffer}, i.e. {@link TextureAttachment}, to this FBO's instance at the given attachment point, * selecting the texture data type and format automatically. - * + * *

          Using default min/mag filter {@link GL#GL_NEAREST} and default wrapS/wrapT {@link GL#GL_CLAMP_TO_EDGE}.

          - * + * *

          Leaves the FBO bound.

          - * + * * @param gl the current GL context * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] * @param alpha set to true if you request alpha channel, otherwise false; @@ -1140,18 +1140,18 @@ public class FBObject { return (TextureAttachment)attachColorbuffer(gl, attachmentPoint, createColorTextureAttachment(gl.getGLProfile(), alpha, width, height)); } - + /** * Attaches a {@link Colorbuffer}, i.e. {@link TextureAttachment}, to this FBO's instance at the given attachment point, * selecting the texture data type and format automatically. - * + * *

          Leaves the FBO bound.

          - * + * * @param gl the current GL context * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] * @param alpha set to true if you request alpha channel, otherwise false; * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER} - * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} + * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S} * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} * @return TextureAttachment instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown @@ -1162,19 +1162,19 @@ public class FBObject { return (TextureAttachment)attachColorbuffer(gl, attachmentPoint, createColorTextureAttachment(gl.getGLProfile(), alpha, width, height, magFilter, minFilter, wrapS, wrapT)); } - + /** * Attaches a {@link Colorbuffer}, i.e. {@link TextureAttachment}, to this FBO's instance at the given attachment point. - * + * *

          Leaves the FBO bound.

          - * + * * @param gl the current GL context * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] * @param internalFormat internalFormat parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} * @param dataFormat format parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} * @param dataType type parameter to {@link GL#glTexImage2D(int, int, int, int, int, int, int, int, long)} * @param magFilter if > 0 value for {@link GL#GL_TEXTURE_MAG_FILTER} - * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} + * @param minFilter if > 0 value for {@link GL#GL_TEXTURE_MIN_FILTER} * @param wrapS if > 0 value for {@link GL#GL_TEXTURE_WRAP_S} * @param wrapT if > 0 value for {@link GL#GL_TEXTURE_WRAP_T} * @return TextureAttachment instance describing the new attached texture colorbuffer if bound and configured successfully, otherwise GLException is thrown @@ -1187,10 +1187,10 @@ public class FBObject { return (TextureAttachment)attachColorbuffer(gl, attachmentPoint, createColorTextureAttachment(internalFormat, width, height, dataFormat, dataType, magFilter, minFilter, wrapS, wrapT)); } - + /** * Creates a {@link ColorAttachment}, selecting the format automatically. - * + * * @param alpha set to true if you request alpha channel, otherwise false; * @return uninitialized ColorAttachment instance describing the new attached colorbuffer */ @@ -1203,13 +1203,13 @@ public class FBObject { } return new ColorAttachment(internalFormat, samples, width, height, 0); } - + /** * Attaches a {@link Colorbuffer}, i.e. {@link ColorAttachment}, to this FBO's instance at the given attachment point, * selecting the format automatically. - * + * *

          Leaves the FBO bound.

          - * + * * @param gl the current GL context * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] * @param alpha set to true if you request alpha channel, otherwise false; @@ -1220,15 +1220,15 @@ public class FBObject { public final ColorAttachment attachColorbuffer(GL gl, int attachmentPoint, boolean alpha) throws GLException { return (ColorAttachment) attachColorbuffer(gl, attachmentPoint, createColorAttachment(alpha)); } - + /** * Attaches a {@link Colorbuffer}, i.e. {@link ColorAttachment}, to this FBO's instance at the given attachment point. - * + * *

          Leaves the FBO bound.

          - * + * * @param gl the current GL context * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] - * @param internalFormat usually {@link GL#GL_RGBA4}, {@link GL#GL_RGB5_A1}, {@link GL#GL_RGB565}, {@link GL#GL_RGB8} or {@link GL#GL_RGBA8} + * @param internalFormat usually {@link GL#GL_RGBA4}, {@link GL#GL_RGB5_A1}, {@link GL#GL_RGB565}, {@link GL#GL_RGB8} or {@link GL#GL_RGBA8} * @return ColorAttachment instance describing the new attached colorbuffer if bound and configured successfully, otherwise GLException is thrown * @throws GLException in case the colorbuffer couldn't be allocated * @throws IllegalArgumentException if internalFormat doesn't reflect a colorbuffer @@ -1238,28 +1238,28 @@ public class FBObject { if( Attachment.Type.COLOR != atype ) { throw new IllegalArgumentException("colorformat invalid: "+toHexString(internalFormat)+", "+this); } - + return (ColorAttachment) attachColorbuffer(gl, attachmentPoint, new ColorAttachment(internalFormat, samples, width, height, 0)); } - + /** - * Attaches a {@link Colorbuffer}, i.e. {@link ColorAttachment} or {@link TextureAttachment}, + * Attaches a {@link Colorbuffer}, i.e. {@link ColorAttachment} or {@link TextureAttachment}, * to this FBO's instance at the given attachment point. - * + * *

          * If {@link Colorbuffer} is a {@link TextureAttachment} and is uninitialized, i.e. it's texture name is zero, * a new texture name is generated and setup w/ the texture parameter.
          * Otherwise, i.e. texture name is not zero, the passed TextureAttachment texA is - * considered complete and assumed matching this FBO requirement. A GL error may occur is the latter is untrue. + * considered complete and assumed matching this FBO requirement. A GL error may occur is the latter is untrue. *

          - * + * *

          Leaves the FBO bound.

          - * + * * @param gl * @param attachmentPoint the color attachment point ranging from [0..{@link #getMaxColorAttachments()}-1] - * @param colbuf the to be attached {@link Colorbuffer} + * @param colbuf the to be attached {@link Colorbuffer} * @return newly attached {@link Colorbuffer} instance if bound and configured successfully, otherwise GLException is thrown - * @throws GLException in case the colorbuffer couldn't be allocated or MSAA has been chosen in case of a {@link TextureAttachment} + * @throws GLException in case the colorbuffer couldn't be allocated or MSAA has been chosen in case of a {@link TextureAttachment} */ public final Colorbuffer attachColorbuffer(GL gl, int attachmentPoint, Colorbuffer colbuf) throws GLException { bind(gl); @@ -1268,13 +1268,13 @@ public class FBObject { private final Colorbuffer attachColorbufferImpl(GL gl, int attachmentPoint, Colorbuffer colbuf) throws GLException { validateAddColorAttachment(attachmentPoint, colbuf); - + final boolean initializedColorbuf = colbuf.initialize(gl); addColorAttachment(attachmentPoint, colbuf); - + if(colbuf instanceof TextureAttachment) { final TextureAttachment texA = (TextureAttachment) colbuf; - + if(samples>0) { removeColorAttachment(attachmentPoint, texA); if(initializedColorbuf) { @@ -1282,14 +1282,14 @@ public class FBObject { } throw new GLException("Texture2D not supported w/ MSAA. If you have enabled MSAA with exisiting texture attachments, you may want to detach them via detachAllTexturebuffer(gl)."); } - + // Set up the color buffer for use as a renderable texture: gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0 + attachmentPoint, GL.GL_TEXTURE_2D, texA.getName(), 0); - + if(!ignoreStatus) { - updateStatus(gl); + updateStatus(gl); if(!isStatusValid()) { detachColorbuffer(gl, attachmentPoint, true); throw new GLException("attachTexture2D "+texA+" at "+attachmentPoint+" failed "+getStatusString()+", "+this); @@ -1297,12 +1297,12 @@ public class FBObject { } } else if(colbuf instanceof ColorAttachment) { final ColorAttachment colA = (ColorAttachment) colbuf; - + // Attach the color buffer - gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, - GL.GL_COLOR_ATTACHMENT0 + attachmentPoint, + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, + GL.GL_COLOR_ATTACHMENT0 + attachmentPoint, GL.GL_RENDERBUFFER, colA.getName()); - + if(!ignoreStatus) { updateStatus(gl); if(!isStatusValid()) { @@ -1316,7 +1316,7 @@ public class FBObject { } return colbuf; } - + /** * Attaches one depth, stencil or packed-depth-stencil buffer to this FBO's instance, * selecting the internalFormat automatically. @@ -1325,30 +1325,30 @@ public class FBObject { *

          *

          * In case the desired type or bit-number is not supported, the next available one is chosen. - *

          + *

          *

          * Use {@link #getDepthAttachment()} and/or {@link #getStencilAttachment()} to retrieve details * about the attached buffer. The details cannot be returned, since it's possible 2 buffers * are being created, depth and stencil. *

          - * + * *

          Leaves the FBO bound.

          - * + * * @param gl - * @param atype either {@link Type#DEPTH}, {@link Type#STENCIL} or {@link Type#DEPTH_STENCIL} + * @param atype either {@link Type#DEPTH}, {@link Type#STENCIL} or {@link Type#DEPTH_STENCIL} * @param reqBits desired bits for depth or -1 for default (24 bits) * @throws GLException in case the renderbuffer couldn't be allocated or one is already attached. * @throws IllegalArgumentException * @see #getDepthAttachment() * @see #getStencilAttachment() */ - public final void attachRenderbuffer(GL gl, Attachment.Type atype, int reqBits) throws GLException, IllegalArgumentException { + public final void attachRenderbuffer(GL gl, Attachment.Type atype, int reqBits) throws GLException, IllegalArgumentException { if( 0 > reqBits ) { reqBits = 24; - } + } final int internalFormat; int internalStencilFormat = -1; - + switch ( atype ) { case DEPTH: if( 32 <= reqBits && depth32Avail ) { @@ -1356,10 +1356,10 @@ public class FBObject { } else if( 24 <= reqBits && depth24Avail ) { internalFormat = GL.GL_DEPTH_COMPONENT24; } else { - internalFormat = GL.GL_DEPTH_COMPONENT16; + internalFormat = GL.GL_DEPTH_COMPONENT16; } break; - + case STENCIL: if( 16 <= reqBits && stencil16Avail ) { internalFormat = GL2GL3.GL_STENCIL_INDEX16; @@ -1370,10 +1370,10 @@ public class FBObject { } else if( 1 <= reqBits && stencil01Avail ) { internalFormat = GL.GL_STENCIL_INDEX1; } else { - throw new GLException("stencil buffer n/a"); + throw new GLException("stencil buffer n/a"); } break; - + case DEPTH_STENCIL: if( packedDepthStencilAvail ) { internalFormat = GL.GL_DEPTH24_STENCIL8; @@ -1381,7 +1381,7 @@ public class FBObject { if( 24 <= reqBits && depth24Avail ) { internalFormat = GL.GL_DEPTH_COMPONENT24; } else { - internalFormat = GL.GL_DEPTH_COMPONENT16; + internalFormat = GL.GL_DEPTH_COMPONENT16; } if( stencil08Avail ) { internalStencilFormat = GL.GL_STENCIL_INDEX8; @@ -1397,17 +1397,17 @@ public class FBObject { default: throw new IllegalArgumentException("only depth/stencil types allowed, was "+atype+", "+this); } - + attachRenderbufferImpl(gl, atype, internalFormat); - + if(0<=internalStencilFormat) { attachRenderbufferImpl(gl, Attachment.Type.STENCIL, internalStencilFormat); } } - + /** * Attaches one depth, stencil or packed-depth-stencil buffer to this FBO's instance, - * depending on the internalFormat. + * depending on the internalFormat. *

          * Stencil and depth buffer can be attached only once. *

          @@ -1416,9 +1416,9 @@ public class FBObject { * about the attached buffer. The details cannot be returned, since it's possible 2 buffers * are being created, depth and stencil. *

          - * + * *

          Leaves the FBO bound.

          - * + * * @param gl the current GL context * @param internalFormat {@link GL#GL_DEPTH_COMPONENT16}, {@link GL#GL_DEPTH_COMPONENT24}, {@link GL#GL_DEPTH_COMPONENT32}, * {@link GL#GL_STENCIL_INDEX1}, {@link GL#GL_STENCIL_INDEX4}, {@link GL#GL_STENCIL_INDEX8} @@ -1435,19 +1435,19 @@ public class FBObject { } attachRenderbufferImpl(gl, atype, internalFormat); } - + protected final void attachRenderbufferImpl(GL gl, Attachment.Type atype, int internalFormat) throws GLException { if( null != depth && ( Attachment.Type.DEPTH == atype || Attachment.Type.DEPTH_STENCIL == atype ) ) { throw new GLException("FBO depth buffer already attached (rb "+depth+"), type is "+atype+", "+toHexString(internalFormat)+", "+this); - } + } if( null != stencil && ( Attachment.Type.STENCIL== atype || Attachment.Type.DEPTH_STENCIL == atype ) ) { throw new GLException("FBO stencil buffer already attached (rb "+stencil+"), type is "+atype+", "+toHexString(internalFormat)+", "+this); } bind(gl); - + attachRenderbufferImpl2(gl, atype, internalFormat); } - + private final void attachRenderbufferImpl2(GL gl, Attachment.Type atype, int internalFormat) throws GLException { if( Attachment.Type.DEPTH == atype ) { if(null == depth) { @@ -1486,10 +1486,10 @@ public class FBObject { } else if( Attachment.Type.STENCIL == atype ) { gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, stencil.getName()); } else if( Attachment.Type.DEPTH_STENCIL == atype ) { - gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, depth.getName()); + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER, depth.getName()); gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT, GL.GL_RENDERBUFFER, stencil.getName()); } - + if(!ignoreStatus) { updateStatus(gl); if( !isStatusValid() ) { @@ -1500,13 +1500,13 @@ public class FBObject { if(DEBUG) { System.err.println("FBObject.attachRenderbuffer.X: [attachmentType "+atype+", iformat "+toHexString(internalFormat)+"]: "+this); - } + } } - + /** - * Detaches a {@link Colorbuffer}, i.e. {@link ColorAttachment} or {@link TextureAttachment}. + * Detaches a {@link Colorbuffer}, i.e. {@link ColorAttachment} or {@link TextureAttachment}. *

          Leaves the FBO bound!

          - * + * * @param gl * @param attachmentPoint * @param dispose true if the Colorbuffer shall be disposed @@ -1515,26 +1515,26 @@ public class FBObject { */ public final Colorbuffer detachColorbuffer(GL gl, int attachmentPoint, boolean dispose) throws IllegalArgumentException { bind(gl); - + final Colorbuffer res = detachColorbufferImpl(gl, attachmentPoint, dispose ? DetachAction.DISPOSE : DetachAction.NONE); if(null == res) { - throw new IllegalArgumentException("ColorAttachment at "+attachmentPoint+", not attached, "+this); + throw new IllegalArgumentException("ColorAttachment at "+attachmentPoint+", not attached, "+this); } if(DEBUG) { System.err.println("FBObject.detachColorbuffer.X: [attachmentPoint "+attachmentPoint+", dispose "+dispose+"]: "+res+", "+this); } return res; } - + private final Colorbuffer detachColorbufferImpl(GL gl, int attachmentPoint, DetachAction detachAction) { Colorbuffer colbuf = colorAttachmentPoints[attachmentPoint]; // shortcut, don't validate here - + if(null == colbuf) { return null; } - + removeColorAttachment(attachmentPoint, colbuf); - + if(colbuf instanceof TextureAttachment) { final TextureAttachment texA = (TextureAttachment) colbuf; if( 0 != texA.getName() ) { @@ -1553,7 +1553,7 @@ public class FBObject { if(DetachAction.RECREATE == detachAction) { if(samples == 0) { // stay non MSAA - texA.setSize(width, height); + texA.setSize(width, height); } else { // switch to MSAA colbuf = createColorAttachment(hasAlpha(texA.format)); @@ -1563,8 +1563,8 @@ public class FBObject { } else if(colbuf instanceof ColorAttachment) { final ColorAttachment colA = (ColorAttachment) colbuf; if( 0 != colA.getName() ) { - gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, - GL.GL_COLOR_ATTACHMENT0+attachmentPoint, + gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, + GL.GL_COLOR_ATTACHMENT0+attachmentPoint, GL.GL_RENDERBUFFER, 0); switch(detachAction) { case DISPOSE: @@ -1582,9 +1582,9 @@ public class FBObject { } else { // switch to non MSAA if(null != samplingSinkTexture) { - colbuf = createColorTextureAttachment(samplingSinkTexture.format, width, height, - samplingSinkTexture.dataFormat, samplingSinkTexture.dataType, - samplingSinkTexture.magFilter, samplingSinkTexture.minFilter, + colbuf = createColorTextureAttachment(samplingSinkTexture.format, width, height, + samplingSinkTexture.dataFormat, samplingSinkTexture.dataType, + samplingSinkTexture.magFilter, samplingSinkTexture.minFilter, samplingSinkTexture.wrapS, samplingSinkTexture.wrapT); } else { colbuf = createColorTextureAttachment(gl.getGLProfile(), true, width, height); @@ -1595,15 +1595,15 @@ public class FBObject { } return colbuf; } - + private final void freeAllColorbufferImpl(GL gl) { for(int i=0; iLeaves the FBO bound, if initialized!

          *

          * An attached sampling sink texture will be detached as well, see {@link #getSamplingSink()}. - *

          + *

          * @param gl the current GL context */ public final void detachAll(GL gl) { if(null != samplingSink) { samplingSink.detachAll(gl); - } + } detachAllImpl(gl, true/* detachNonColorbuffer */, false /* recreate */); } - - /** - * Detaches all {@link ColorAttachment}s and {@link TextureAttachment}s + + /** + * Detaches all {@link ColorAttachment}s and {@link TextureAttachment}s * and disposes them. *

          Leaves the FBO bound, if initialized!

          *

          * An attached sampling sink texture will be detached as well, see {@link #getSamplingSink()}. - *

          + *

          * @param gl the current GL context */ public final void detachAllColorbuffer(GL gl) { if(null != samplingSink) { samplingSink.detachAllColorbuffer(gl); - } + } detachAllImpl(gl, false/* detachNonColorbuffer */, false /* recreate */); } - - /** + + /** * Detaches all {@link TextureAttachment}s and disposes them. *

          Leaves the FBO bound, if initialized!

          *

          * An attached sampling sink texture will be detached as well, see {@link #getSamplingSink()}. - *

          + *

          * @param gl the current GL context */ public final void detachAllTexturebuffer(GL gl) { @@ -1826,7 +1826,7 @@ public class FBObject { if(null != samplingSink) { samplingSink.detachAllTexturebuffer(gl); } - bind(gl); + bind(gl); for(int i=0; i0 ) { throw new InternalError("Non zero ColorAttachments "+this); } - + if(detachNonColorbuffer) { detachRenderbufferImpl(gl, Attachment.Type.DEPTH_STENCIL, recreate ? DetachAction.RECREATE : DetachAction.DISPOSE); } @@ -1888,7 +1888,7 @@ public class FBObject { System.err.println("FBObject.detachAll.X: [resetNonColorbuffer "+detachNonColorbuffer+", recreate "+recreate+"]: "+this); } } - + /** * @param gl the current GL context */ @@ -1903,9 +1903,9 @@ public class FBObject { if( null != samplingSink && samplingSink.isInitialized() ) { samplingSink.destroy(gl); } - + detachAllImpl(gl, true /* detachNonColorbuffer */, false /* recreate */); - + // cache FB names, preset exposed to zero, // braking ties w/ GL/GLContext link to getReadFramebuffer()/getWriteFramebuffer() final int fb_cache = fbName; @@ -1915,7 +1915,7 @@ public class FBObject { if(0!=fb_cache) { name[0] = fb_cache; gl.glDeleteFramebuffers(1, name, 0); - } + } initialized = false; bound = false; if(DEBUG) { @@ -1933,14 +1933,14 @@ public class FBObject { final boolean depthMismatch = ( null != depth && null == samplingSink.depth ) || ( null != depth && null != samplingSink.depth && depth.format != samplingSink.depth.format ); - + final boolean stencilMismatch = ( null != stencil && null == samplingSink.stencil ) || ( null != stencil && null != samplingSink.stencil && - stencil.format != samplingSink.stencil.format ); - - return depthMismatch || stencilMismatch; + stencil.format != samplingSink.stencil.format ); + + return depthMismatch || stencilMismatch; } - + /** * Manually reset the MSAA sampling sink, if used. *

          @@ -1948,7 +1948,7 @@ public class FBObject { * a new sampling sink is being created. *

          *

          - * Automatically called by {@link #reset(GL, int, int, int, boolean)} + * Automatically called by {@link #reset(GL, int, int, int, boolean)} * and {@link #syncSamplingSink(GL)}. *

          *

          @@ -1967,58 +1967,58 @@ public class FBObject { } return; } - + if(null == samplingSink ) { samplingSink = new FBObject(); } - + if(!samplingSink.initialized) { samplingSink.init(gl, width, height, 0); } - + boolean sampleSinkSizeMismatch = sampleSinkSizeMismatch(); boolean sampleSinkTexMismatch = sampleSinkTexMismatch(); boolean sampleSinkDepthStencilMismatch = sampleSinkDepthStencilMismatch(); - + /** if(DEBUG) { System.err.println("FBObject.resetSamplingSink.0: \n\tTHIS "+this+",\n\tSINK "+samplesSink+ "\n\t size "+sampleSinkSizeMismatch +", tex "+sampleSinkTexMismatch +", depthStencil "+sampleSinkDepthStencilMismatch); } */ - + if(!sampleSinkSizeMismatch && !sampleSinkTexMismatch && !sampleSinkDepthStencilMismatch) { - // all properties match .. - return; + // all properties match .. + return; } - + unbind(gl); - + if(DEBUG) { System.err.println("FBObject.resetSamplingSink: BEGIN\n\tTHIS "+this+",\n\tSINK "+samplingSink+ "\n\t size "+sampleSinkSizeMismatch +", tex "+sampleSinkTexMismatch +", depthStencil "+sampleSinkDepthStencilMismatch); } - + if( sampleSinkDepthStencilMismatch ) { samplingSink.detachAllRenderbuffer(gl); } - + if( sampleSinkSizeMismatch ) { samplingSink.reset(gl, width, height); } - + if(null == samplingSinkTexture) { samplingSinkTexture = samplingSink.attachTexture2D(gl, 0, true); } else if( 0 == samplingSinkTexture.getName() ) { samplingSinkTexture.setSize(width, height); samplingSink.attachColorbuffer(gl, 0, samplingSinkTexture); } - + if( sampleSinkDepthStencilMismatch ) { samplingSink.attachRenderbuffer(gl, depth.format); if( null != stencil && !isDepthStencilPackedFormat() ) { samplingSink.attachRenderbuffer(gl, stencil.format); } - } - + } + sampleSinkSizeMismatch = sampleSinkSizeMismatch(); sampleSinkTexMismatch = sampleSinkTexMismatch(); sampleSinkDepthStencilMismatch = sampleSinkDepthStencilMismatch(); @@ -2026,21 +2026,21 @@ public class FBObject { throw new InternalError("Samples sink mismatch after reset: \n\tTHIS "+this+",\n\t SINK "+samplingSink+ "\n\t size "+sampleSinkSizeMismatch +", tex "+sampleSinkTexMismatch +", depthStencil "+sampleSinkDepthStencilMismatch); } - + if(DEBUG) { System.err.println("FBObject.resetSamplingSink: END\n\tTHIS "+this+",\n\tSINK "+samplingSink+ "\n\t size "+sampleSinkSizeMismatch +", tex "+sampleSinkTexMismatch +", depthStencil "+sampleSinkDepthStencilMismatch); } } - + /** * Setting this FBO sampling sink. * @param newSamplingSink the new FBO sampling sink to use, or null to remove current sampling sink - * @return the previous sampling sink or null if none was attached + * @return the previous sampling sink or null if none was attached * @throws GLException if this FBO doesn't use MSAA or the given sink uses MSAA itself */ public FBObject setSamplingSink(FBObject newSamplingSink) throws GLException { - final FBObject prev = samplingSink; + final FBObject prev = samplingSink; if( null == newSamplingSink) { samplingSink = null; samplingSinkTexture = null; @@ -2056,14 +2056,14 @@ public class FBObject { samplingSinkDirty = true; return prev; } - - /** + + /** * Bind this FBO, i.e. bind write framebuffer to {@link #getWriteFramebuffer()}. - * - *

          If multisampling is used, it sets the read framebuffer to the sampling sink {@link #getWriteFramebuffer()}, + * + *

          If multisampling is used, it sets the read framebuffer to the sampling sink {@link #getWriteFramebuffer()}, * if full FBO is supported.

          - * - *

          + * + *

          * In case you have attached more than one color buffer, * you may want to setup {@link GL2GL3#glDrawBuffers(int, int[], int)}. *

          @@ -2079,7 +2079,7 @@ public class FBObject { gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, getReadFramebuffer()); } else { // one for all - gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, getWriteFramebuffer()); + gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, getWriteFramebuffer()); } bound = true; @@ -2087,29 +2087,29 @@ public class FBObject { } } - /** + /** * Unbind this FBO, i.e. bind read and write framebuffer to default, see {@link GLBase#getDefaultDrawFramebuffer()}. - * - *

          If full FBO is supported, sets the read and write framebuffer individually to default, hence not disturbing + * + *

          If full FBO is supported, sets the read and write framebuffer individually to default, hence not disturbing * an optional operating MSAA FBO, see {@link GLBase#getDefaultReadFramebuffer()} and {@link GLBase#getDefaultDrawFramebuffer()}

          - * + * * @param gl the current GL context * @throws GLException */ public final void unbind(GL gl) throws GLException { if(bound) { if(fullFBOSupport) { - // default read/draw buffers, may utilize GLContext/GLDrawable override of + // default read/draw buffers, may utilize GLContext/GLDrawable override of // GLContext.getDefaultDrawFramebuffer() and GLContext.getDefaultReadFramebuffer() gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, 0); gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, 0); } else { - gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); // default draw buffer + gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); // default draw buffer } bound = false; } } - + /** * Method simply marks this FBO unbound w/o interfering w/ the bound framebuffer as perfomed by {@link #unbind(GL)}. *

          @@ -2121,22 +2121,22 @@ public class FBObject { bound = false; } - /** + /** * Returns true if framebuffer object is bound via {@link #bind(GL)}, otherwise false. *

          * Method verifies the bound state via {@link GL#getBoundFramebuffer(int)}. *

          * @param gl the current GL context */ - public final boolean isBound(GL gl) { + public final boolean isBound(GL gl) { bound = bound && fbName != gl.getBoundFramebuffer(GL.GL_FRAMEBUFFER) ; return bound; } - + /** Returns true if framebuffer object is bound via {@link #bind(GL)}, otherwise false. */ public final boolean isBound() { return bound; } - - /** + + /** * If multisampling is being used and flagged dirty by a previous call of {@link #bind(GL)} or after initialization, * the msaa-buffers are sampled to it's sink {@link #getSamplingSink()}. *

          @@ -2147,7 +2147,7 @@ public class FBObject { *

          *

          * Method always resets the framebuffer binding to default in the end. - * If full FBO is supported, sets the read and write framebuffer individually to default after sampling, hence not disturbing + * If full FBO is supported, sets the read and write framebuffer individually to default after sampling, hence not disturbing * an optional operating MSAA FBO, see {@link GLBase#getDefaultReadFramebuffer()} and {@link GLBase#getDefaultDrawFramebuffer()} *

          *

          @@ -2155,10 +2155,10 @@ public class FBObject { * you may want to call {@link GL#glBindFramebuffer(int, int) glBindFramebuffer}({@link GL2GL3#GL_READ_FRAMEBUFFER}, {@link #getReadFramebuffer()}); *

          *

          Leaves the FBO unbound.

          - * + * * @param gl the current GL context * @param ta {@link TextureAttachment} to use, prev. attached w/ {@link #attachTexture2D(GL, int, boolean, int, int, int, int) attachTexture2D(..)} - * @throws IllegalArgumentException + * @throws IllegalArgumentException */ public final void syncSamplingSink(GL gl) { markUnbound(); @@ -2170,30 +2170,30 @@ public class FBObject { gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, samplingSink.getWriteFramebuffer()); ((GL2GL3)gl).glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, // since MSAA is supported, casting to GL2GL3 is OK GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST); - checkNoError(null, gl.glGetError(), "FBObject syncSampleSink"); // throws GLException if error + checkNoError(null, gl.glGetError(), "FBObject syncSampleSink"); // throws GLException if error } if(fullFBOSupport) { - // default read/draw buffers, may utilize GLContext/GLDrawable override of + // default read/draw buffers, may utilize GLContext/GLDrawable override of // GLContext.getDefaultDrawFramebuffer() and GLContext.getDefaultReadFramebuffer() gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, 0); gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, 0); } else { - gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); // default draw buffer + gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); // default draw buffer } } - - /** + + /** * Bind the given texture colorbuffer. - * + * *

          If using multiple texture units, ensure you call {@link GL#glActiveTexture(int)} first!

          - * + * *

          {@link #syncSamplingSink(GL)} is being called

          - * + * *

          Leaves the FBO unbound!

          - * + * * @param gl the current GL context * @param ta {@link TextureAttachment} to use, prev. attached w/ {@link #attachTexture2D(GL, int, boolean, int, int, int, int) attachTexture2D(..)} - * @throws IllegalArgumentException + * @throws IllegalArgumentException */ public final void use(GL gl, TextureAttachment ta) throws IllegalArgumentException { if(null == ta) { throw new IllegalArgumentException("Null TextureAttachment, this: "+toString()); } @@ -2201,26 +2201,26 @@ public class FBObject { gl.glBindTexture(GL.GL_TEXTURE_2D, ta.getName()); // use it .. } - /** + /** * Unbind texture, ie bind 'non' texture 0 - * + * *

          Leaves the FBO unbound.

          - */ + */ public final void unuse(GL gl) { unbind(gl); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); // don't use it } - /** @see GL#hasFullFBOSupport() */ + /** @see GL#hasFullFBOSupport() */ public final boolean hasFullFBOSupport() throws GLException { checkInitialized(); return this.fullFBOSupport; } - - /** + + /** * Returns true if renderbuffer accepts internal format {@link GL#GL_RGB8} and {@link GL#GL_RGBA8}, otherwise false. * @throws GLException if {@link #init(GL)} hasn't been called. */ public final boolean supportsRGBA8() throws GLException { checkInitialized(); return rgba8Avail; } - - /** + + /** * Returns true if {@link GL#GL_DEPTH_COMPONENT16}, {@link GL#GL_DEPTH_COMPONENT24} or {@link GL#GL_DEPTH_COMPONENT32} is supported, otherwise false. * @param bits 16, 24 or 32 bits * @throws GLException if {@link #init(GL)} hasn't been called. @@ -2228,14 +2228,14 @@ public class FBObject { public final boolean supportsDepth(int bits) throws GLException { checkInitialized(); switch(bits) { - case 16: return true; + case 16: return true; case 24: return depth24Avail; case 32: return depth32Avail; - default: return false; + default: return false; } } - - /** + + /** * Returns true if {@link GL#GL_STENCIL_INDEX1}, {@link GL#GL_STENCIL_INDEX4}, {@link GL#GL_STENCIL_INDEX8} or {@link GL2GL3#GL_STENCIL_INDEX16} is supported, otherwise false. * @param bits 1, 4, 8 or 16 bits * @throws GLException if {@link #init(GL)} hasn't been called. @@ -2243,34 +2243,34 @@ public class FBObject { public final boolean supportsStencil(int bits) throws GLException { checkInitialized(); switch(bits) { - case 1: return stencil01Avail; + case 1: return stencil01Avail; case 4: return stencil04Avail; case 8: return stencil08Avail; case 16: return stencil16Avail; - default: return false; + default: return false; } } - - /** + + /** * Returns true if {@link GL#GL_DEPTH24_STENCIL8} is supported, otherwise false. * @throws GLException if {@link #init(GL)} hasn't been called. */ public final boolean supportsPackedDepthStencil() throws GLException { checkInitialized(); return packedDepthStencilAvail; } - + /** * Returns the maximum number of colorbuffer attachments. * @throws GLException if {@link #init(GL)} hasn't been called. */ public final int getMaxColorAttachments() throws GLException { checkInitialized(); return maxColorAttachments; } - + public final int getMaxTextureSize() throws GLException { checkInitialized(); return this.maxTextureSize; } public final int getMaxRenderbufferSize() throws GLException { checkInitialized(); return this.maxRenderbufferSize; } - + /** @see GL#getMaxRenderbufferSamples() */ public final int getMaxSamples() throws GLException { checkInitialized(); return this.maxSamples; } - + /** - * Returns true if this instance has been initialized with {@link #reset(GL, int, int)} + * Returns true if this instance has been initialized with {@link #reset(GL, int, int)} * or {@link #reset(GL, int, int, int, boolean)}, otherwise false */ public final boolean isInitialized() { return initialized; } @@ -2283,43 +2283,43 @@ public class FBObject { /** Returns the framebuffer name to render to. */ public final int getWriteFramebuffer() { return fbName; } /** Returns the framebuffer name to read from. Depending on multisampling, this may be a different framebuffer. */ - public final int getReadFramebuffer() { return ( samples > 0 ) ? samplingSink.getReadFramebuffer() : fbName; } - public final int getDefaultReadBuffer() { return GL.GL_COLOR_ATTACHMENT0; } + public final int getReadFramebuffer() { return ( samples > 0 ) ? samplingSink.getReadFramebuffer() : fbName; } + public final int getDefaultReadBuffer() { return GL.GL_COLOR_ATTACHMENT0; } /** Return the number of color/texture attachments */ public final int getColorAttachmentCount() { return colorAttachmentCount; } - /** Return the stencil {@link RenderAttachment} attachment, if exist. Maybe share the same {@link Attachment#getName()} as {@link #getDepthAttachment()}, if packed depth-stencil is being used. */ + /** Return the stencil {@link RenderAttachment} attachment, if exist. Maybe share the same {@link Attachment#getName()} as {@link #getDepthAttachment()}, if packed depth-stencil is being used. */ public final RenderAttachment getStencilAttachment() { return stencil; } - /** Return the depth {@link RenderAttachment} attachment. Maybe share the same {@link Attachment#getName()} as {@link #getStencilAttachment()}, if packed depth-stencil is being used. */ + /** Return the depth {@link RenderAttachment} attachment. Maybe share the same {@link Attachment#getName()} as {@link #getStencilAttachment()}, if packed depth-stencil is being used. */ public final RenderAttachment getDepthAttachment() { return depth; } - - /** Return the complete multisampling {@link FBObject} sink, if using multisampling. */ + + /** Return the complete multisampling {@link FBObject} sink, if using multisampling. */ public final FBObject getSamplingSinkFBO() { return samplingSink; } - - /** Return the multisampling {@link TextureAttachment} sink, if using multisampling. */ + + /** Return the multisampling {@link TextureAttachment} sink, if using multisampling. */ public final TextureAttachment getSamplingSink() { return samplingSinkTexture; } - /** - * Returns true if the multisampling colorbuffer (msaa-buffer) + /** + * Returns true if the multisampling colorbuffer (msaa-buffer) * has been flagged dirty by a previous call of {@link #bind(GL)}, * otherwise false. */ public final boolean isSamplingBufferDirty() { return samplingSinkDirty; } - + int objectHashCode() { return super.hashCode(); } - + public final String toString() { - final String caps = null != colorAttachmentPoints ? Arrays.asList(colorAttachmentPoints).toString() : null ; + final String caps = null != colorAttachmentPoints ? Arrays.asList(colorAttachmentPoints).toString() : null ; return "FBO[name r/w "+fbName+"/"+getReadFramebuffer()+", init "+initialized+", bound "+bound+", size "+width+"x"+height+ ", samples "+samples+"/"+maxSamples+", depth "+depth+", stencil "+stencil+ ", color attachments: "+colorAttachmentCount+"/"+maxColorAttachments+ ": "+caps+", msaa-sink "+samplingSinkTexture+", hasSamplesSink "+(null != samplingSink)+ ", state "+getStatusString()+", obj "+toHexString(objectHashCode())+"]"; } - + private final void updateStatus(GL gl) { if( 0 == fbName ) { vStatus = -1; } else { vStatus = gl.glCheckFramebufferStatus(GL.GL_FRAMEBUFFER); } - } + } } diff --git a/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java index bec05a0bd..ce58d29c1 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java +++ b/src/jogl/classes/com/jogamp/opengl/GLAutoDrawableDelegate.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.opengl; import javax.media.nativewindow.AbstractGraphicsDevice; @@ -58,14 +58,14 @@ import jogamp.opengl.GLDrawableImpl; * * and setup a {@link com.jogamp.newt.Window#setWindowDestroyNotifyAction(Runnable) custom toolkit destruction} issuing {@link #windowDestroyNotifyOp()}. *

          - *

          + *

          * See example {@link com.jogamp.opengl.test.junit.jogl.acore.TestGLAutoDrawableDelegateNEWT TestGLAutoDrawableDelegateNEWT}. *

          */ public class GLAutoDrawableDelegate extends GLAutoDrawableBase implements GLAutoDrawable { /** * @param drawable a valid {@link GLDrawable}, may not be {@link GLDrawable#isRealized() realized} yet. - * @param context a valid {@link GLContext}, + * @param context a valid {@link GLContext}, * may not have been made current (created) yet, * may not be associated w/ drawable yet, * may be null for lazy initialization @@ -84,7 +84,7 @@ public class GLAutoDrawableDelegate extends GLAutoDrawableBase implements GLAuto this.upstreamWidget = upstreamWidget; this.lock = ( null != lock ) ? lock : LockFactory.createRecursiveLock() ; } - + // // expose default methods // @@ -93,40 +93,40 @@ public class GLAutoDrawableDelegate extends GLAutoDrawableBase implements GLAuto public final void windowRepaintOp() { super.defaultWindowRepaintOp(); } - + /** Implementation to handle resize events from the windowing system. All required locks are being claimed. */ public final void windowResizedOp(int newWidth, int newHeight) { super.defaultWindowResizedOp(newWidth, newHeight); } - - /** + + /** * Implementation to handle destroy notifications from the windowing system. - * + * *

          - * If the {@link NativeSurface} does not implement {@link WindowClosingProtocol} + * If the {@link NativeSurface} does not implement {@link WindowClosingProtocol} * or {@link WindowClosingMode#DISPOSE_ON_CLOSE} is enabled (default), * a thread safe destruction is being induced. - *

          + *

          */ public final void windowDestroyNotifyOp() { super.defaultWindowDestroyNotifyOp(); } - + // // Complete GLAutoDrawable // - + private Object upstreamWidget; private final RecursiveLock lock; - + @Override protected final RecursiveLock getLock() { return lock; } - + @Override public final Object getUpstreamWidget() { return upstreamWidget; } - + /** * Set the upstream UI toolkit object. * @see #getUpstreamWidget() @@ -134,7 +134,7 @@ public class GLAutoDrawableDelegate extends GLAutoDrawableBase implements GLAuto public final void setUpstreamWidget(Object newUpstreamWidget) { upstreamWidget = newUpstreamWidget; } - + /** * {@inheritDoc} *

          @@ -142,7 +142,7 @@ public class GLAutoDrawableDelegate extends GLAutoDrawableBase implements GLAuto *

          *

          * User still needs to destroy the upstream window, which details are hidden from this aspect. - * This can be performed by overriding {@link #destroyImplInLock()}. + * This can be performed by overriding {@link #destroyImplInLock()}. *

          */ @Override @@ -154,29 +154,29 @@ public class GLAutoDrawableDelegate extends GLAutoDrawableBase implements GLAuto protected void destroyImplInLock() { super.destroyImplInLock(); } - + @Override - public void display() { + public void display() { defaultDisplay(); } - + // // GLDrawable delegation // - + @Override public final GLDrawableFactory getFactory() { return drawable.getFactory(); } - + @Override public final void swapBuffers() throws GLException { defaultSwapBuffers(); } - + @Override public String toString() { return getClass().getSimpleName()+"[ \n\tHelper: " + helper + ", \n\tDrawable: " + drawable + ", \n\tContext: " + context + ", \n\tUpstreamWidget: "+upstreamWidget+ /** ", \n\tFactory: "+factory+ */ "]"; - } + } } diff --git a/src/jogl/classes/com/jogamp/opengl/GLEventListenerState.java b/src/jogl/classes/com/jogamp/opengl/GLEventListenerState.java index 21dafecb1..1b4187668 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLEventListenerState.java +++ b/src/jogl/classes/com/jogamp/opengl/GLEventListenerState.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -48,7 +48,7 @@ import jogamp.opengl.Debug; import com.jogamp.nativewindow.MutableGraphicsConfiguration; /** - * GLEventListenerState is holding {@link GLAutoDrawable} components crucial + * GLEventListenerState is holding {@link GLAutoDrawable} components crucial * to relocating all its {@link GLEventListener} w/ their operating {@link GLContext}, etc. * The components are: *
            @@ -69,8 +69,8 @@ import com.jogamp.nativewindow.MutableGraphicsConfiguration; */ public class GLEventListenerState { private static final boolean DEBUG = Debug.debug("GLDrawable") || Debug.debug("GLEventListenerState"); - - private GLEventListenerState(AbstractGraphicsDevice upstreamDevice, boolean proxyOwnsUpstreamDevice, AbstractGraphicsDevice device, + + private GLEventListenerState(AbstractGraphicsDevice upstreamDevice, boolean proxyOwnsUpstreamDevice, AbstractGraphicsDevice device, GLCapabilitiesImmutable caps, GLContext context, int count, GLAnimatorControl anim, boolean animStarted) { this.upstreamDevice = upstreamDevice; @@ -82,19 +82,19 @@ public class GLEventListenerState { this.listenersInit = new boolean[count]; this.anim = anim; this.animStarted = animStarted; - + this.owner = true; } /** - * Returns true, if this instance is the current owner of the components, + * Returns true, if this instance is the current owner of the components, * otherwise false. *

            * Ownership is lost if {@link #moveTo(GLAutoDrawable)} is being called successfully - * and all components are transferred to the new {@link GLAutoDrawable}. + * and all components are transferred to the new {@link GLAutoDrawable}. *

            */ public final boolean isOwner() { return owner; } - + public final int listenerCount() { return listeners.length; } public final AbstractGraphicsDevice upstreamDevice; @@ -103,10 +103,10 @@ public class GLEventListenerState { public final GLCapabilitiesImmutable caps; public final GLContext context; public final GLEventListener[] listeners; - public final boolean[] listenersInit; + public final boolean[] listenersInit; public final GLAnimatorControl anim; public final boolean animStarted; - + private boolean owner; /** @@ -127,25 +127,25 @@ public class GLEventListenerState { private static AbstractGraphicsDevice cloneDevice(AbstractGraphicsDevice aDevice) { return (AbstractGraphicsDevice) aDevice.clone(); } - + /** - * Moves all GLEventListenerState components from the given {@link GLAutoDrawable} + * Moves all GLEventListenerState components from the given {@link GLAutoDrawable} * to a newly created instance. *

            * Note that all components are removed from the {@link GLAutoDrawable}, * i.e. the {@link GLContext}, all {@link GLEventListener}. *

            - *

            + *

            * If the {@link GLAutoDrawable} was added to a {@link GLAnimatorControl}, it is removed * and the {@link GLAnimatorControl} added to the GLEventListenerState. *

            *

            - * The returned GLEventListenerState instance is the {@link #isOwner() owner of the components}. + * The returned GLEventListenerState instance is the {@link #isOwner() owner of the components}. *

            - * + * * @param a {@link GLAutoDrawable} source to move components from * @return new GLEventListenerState instance {@link #isOwner() owning} moved components. - * + * * @see #moveTo(GLAutoDrawable) */ public static GLEventListenerState moveFrom(GLAutoDrawable a) { @@ -154,16 +154,16 @@ public class GLEventListenerState { if( null != aAnim ) { aAnimStarted = aAnim.isStarted(); aAnim.remove(a); // also handles ECT - } else { + } else { aAnimStarted = false; } - + final GLEventListenerState glls; final NativeSurface aSurface = a.getNativeSurface(); final boolean surfaceLocked = false; // NativeSurface.LOCK_SURFACE_NOT_READY < aSurface.lockSurface(); try { final int aSz = a.getGLEventListenerCount(); - + // Create new AbstractGraphicsScreen w/ cloned AbstractGraphicsDevice for future GLAutoDrawable // allowing this AbstractGraphicsDevice to loose ownership -> not closing display/device! final AbstractGraphicsConfiguration aCfg = aSurface.getGraphicsConfiguration(); @@ -171,7 +171,7 @@ public class GLEventListenerState { final AbstractGraphicsDevice aDevice1 = aCfg.getScreen().getDevice(); final AbstractGraphicsDevice aDevice2 = cloneDevice(aDevice1); aDevice1.clearHandleOwner(); // don't close device handle - if( DEBUG ) { + if( DEBUG ) { System.err.println("GLEventListenerState.moveFrom.0a: orig 0x"+Integer.toHexString(aDevice1.hashCode())+", "+aDevice1); System.err.println("GLEventListenerState.moveFrom.0b: pres 0x"+Integer.toHexString(aDevice2.hashCode())+", "+aDevice2); System.err.println("GLEventListenerState.moveFrom.1: "+aSurface.getClass().getName()/*+", "+aSurface*/); @@ -203,9 +203,9 @@ public class GLEventListenerState { } aUpDevice2 = _aUpDevice2; } - - glls = new GLEventListenerState(aUpDevice2, proxyOwnsUpstreamDevice, aDevice2, caps, a.getContext(), aSz, aAnim, aAnimStarted); - + + glls = new GLEventListenerState(aUpDevice2, proxyOwnsUpstreamDevice, aDevice2, caps, a.getContext(), aSz, aAnim, aAnimStarted); + // // remove and cache all GLEventListener and their init-state // @@ -213,41 +213,41 @@ public class GLEventListenerState { final GLEventListener l = a.getGLEventListener(0); glls.listenersInit[i] = a.getGLEventListenerInitState(l); glls.listeners[i] = a.removeGLEventListener( l ); - } - + } + // // trigger glFinish to sync GL ctx // a.invoke(true, glFinish); - + a.setContext( null, false ); - + } finally { if( surfaceLocked ) { aSurface.unlockSurface(); } - } - + } + return glls; } /** - * Moves all GLEventListenerState components to the given {@link GLAutoDrawable} + * Moves all GLEventListenerState components to the given {@link GLAutoDrawable} * from this instance, while loosing {@link #isOwner() ownership}. - *

            + *

            * If the previous {@link GLAutoDrawable} was removed from a {@link GLAnimatorControl} by previous {@link #moveFrom(GLAutoDrawable)}, * the given {@link GLAutoDrawable} is added to the cached {@link GLAnimatorControl}. - * This operation is skipped, if the given {@link GLAutoDrawable} is already added to a {@link GLAnimatorControl} instance. + * This operation is skipped, if the given {@link GLAutoDrawable} is already added to a {@link GLAnimatorControl} instance. *

            *

            - * Note: After this operation, the GLEventListenerState reference should be released. + * Note: After this operation, the GLEventListenerState reference should be released. *

            - * + * * @param a {@link GLAutoDrawable} destination to move GLEventListenerState components to - * + * * * @throws GLException if this preserved {@link AbstractGraphicsDevice} is incompatible w/ the given destination one. - * + * * @see #moveFrom(GLAutoDrawable) * @see #isOwner() */ @@ -261,22 +261,22 @@ public class GLEventListenerState { if( aPaused ) { aAnim.resume(); } - } else { + } else { aPaused = false; } - + final List aGLCmds = new ArrayList(); final int aSz = listenerCount(); - + final NativeSurface aSurface = a.getNativeSurface(); final boolean surfaceLocked = false; // NativeSurface.LOCK_SURFACE_NOT_READY < aSurface.lockSurface(); final boolean aRealized; try { - + final MutableGraphicsConfiguration aCfg = (MutableGraphicsConfiguration) aSurface.getGraphicsConfiguration(); /** final GLCapabilitiesImmutable aCaps = (GLCapabilitiesImmutable) aCfg.getChosenCapabilities(); - if( caps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) != aCaps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) || + if( caps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) != aCaps.getVisualID(VisualIDHolder.VIDType.INTRINSIC) || caps.getVisualID(VisualIDHolder.VIDType.NATIVE) != aCaps.getVisualID(VisualIDHolder.VIDType.NATIVE) ) { throw new GLException("Incompatible Capabilities - Prev-Holder: "+caps+", New-Holder "+caps); } */ @@ -285,8 +285,8 @@ public class GLEventListenerState { if( !aDevice1.getUniqueID().equals( aDevice2.getUniqueID() ) ) { throw new GLException("Incompatible devices: Preserved <"+aDevice2.getUniqueID()+">, target <"+aDevice1.getUniqueID()+">"); } - - // collect optional upstream surface info + + // collect optional upstream surface info final ProxySurface aProxy; final NativeSurface aUpSurface; if(aSurface instanceof ProxySurface) { @@ -302,8 +302,8 @@ public class GLEventListenerState { } if( null==aUpSurface && null != upstreamDevice ) { throw new GLException("Incompatible Surface config - Has Upstream-Surface: Prev-Holder = true, New-Holder = false"); - } - + } + // Destroy and remove currently associated GLContext, if any (will be replaced) a.setContext( null, true ); aRealized = a.isRealized(); @@ -311,7 +311,7 @@ public class GLEventListenerState { // Unrealize due to device dependencies of an upstream surface, e.g. EGLUpstreamSurfaceHook a.getDelegatedDrawable().setRealized(false); } - + // Set new Screen and close previous one { if( DEBUG ) { @@ -319,13 +319,13 @@ public class GLEventListenerState { System.err.println("GLEventListenerState.moveTo.0b: pres 0x"+Integer.toHexString(aDevice2.hashCode())+", "+aDevice2); } DefaultGraphicsDevice.swapDeviceHandleAndOwnership(aDevice1, aDevice2); - aDevice2.close(); + aDevice2.close(); if( DEBUG ) { System.err.println("GLEventListenerState.moveTo.1a: orig 0x"+Integer.toHexString(aDevice1.hashCode())+", "+aDevice1); System.err.println("GLEventListenerState.moveTo.1b: pres 0x"+Integer.toHexString(aDevice2.hashCode())+", "+aDevice2); } } - + // If using a ProxySurface w/ an upstream surface, set new Screen and close previous one on it if( null != aUpSurface ) { final MutableGraphicsConfiguration aUpCfg = (MutableGraphicsConfiguration) aUpSurface.getGraphicsConfiguration(); @@ -339,9 +339,9 @@ public class GLEventListenerState { System.err.println("GLEventListenerState.moveTo.2a: up-orig 0x"+Integer.toHexString(aUpDevice1.hashCode())+", "+aUpDevice1); System.err.println("GLEventListenerState.moveTo.2b: up-pres 0x"+Integer.toHexString(aUpDevice2.hashCode())+", "+aUpDevice2); System.err.println("GLEventListenerState.moveTo.2c: "+aUpSurface.getClass().getName()/*+", "+aUpSurface+", "*/+aProxy.getUpstreamOptionBits(null).toString()); - } + } DefaultGraphicsDevice.swapDeviceHandleAndOwnership(aUpDevice1, aUpDevice2); - aUpDevice2.close(); + aUpDevice2.close(); if( proxyOwnsUpstreamDevice ) { aProxy.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); } @@ -354,7 +354,7 @@ public class GLEventListenerState { throw new GLException("Incompatible Surface config - Has Upstream-Surface: Prev-Holder = false, New-Holder = true"); } } - + if( aRealized && null != aUpSurface ) { a.getDelegatedDrawable().setRealized(true); } @@ -369,7 +369,7 @@ public class GLEventListenerState { } } owner = false; - + // // Trigger GL-Viewport reset and reshape of all initialized GLEventListeners // @@ -389,7 +389,7 @@ public class GLEventListenerState { a.setGLEventListenerInitState(l, listenersInit[i]); listeners[i] = null; } - + if( hasAnimator ) { // prefer already bound animator aAnim.add(a); @@ -410,7 +410,7 @@ public class GLEventListenerState { public boolean run(GLAutoDrawable drawable) { drawable.getGL().glViewport(0, 0, drawable.getWidth(), drawable.getHeight()); return true; - } + } }; public static GLRunnable glFinish = new GLRunnable() { @@ -418,7 +418,7 @@ public class GLEventListenerState { public boolean run(GLAutoDrawable drawable) { drawable.getGL().glFinish(); return true; - } + } }; public static class ReshapeGLEventListener implements GLRunnable { @@ -430,6 +430,6 @@ public class GLEventListenerState { public boolean run(GLAutoDrawable drawable) { listener.reshape(drawable, 0, 0, drawable.getWidth(), drawable.getHeight()); return true; - } + } } } diff --git a/src/jogl/classes/com/jogamp/opengl/GLExtensions.java b/src/jogl/classes/com/jogamp/opengl/GLExtensions.java index 14f4be96a..c7aadcd14 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLExtensions.java +++ b/src/jogl/classes/com/jogamp/opengl/GLExtensions.java @@ -28,17 +28,17 @@ package com.jogamp.opengl; /** - * Class holding OpenGL extension strings, commonly used by JOGL's implementation. + * Class holding OpenGL extension strings, commonly used by JOGL's implementation. */ public class GLExtensions { public static final String VERSION_1_2 = "GL_VERSION_1_2"; public static final String VERSION_1_4 = "GL_VERSION_1_4"; public static final String VERSION_1_5 = "GL_VERSION_1_5"; public static final String VERSION_2_0 = "GL_VERSION_2_0"; - + public static final String ARB_debug_output = "GL_ARB_debug_output"; public static final String AMD_debug_output = "GL_AMD_debug_output"; - + public static final String ARB_framebuffer_object = "GL_ARB_framebuffer_object"; public static final String OES_framebuffer_object = "GL_OES_framebuffer_object"; public static final String EXT_framebuffer_object = "GL_EXT_framebuffer_object"; @@ -49,17 +49,17 @@ public class GLExtensions { public static final String OES_depth32 = "GL_OES_depth32"; public static final String OES_packed_depth_stencil = "GL_OES_packed_depth_stencil"; public static final String NV_fbo_color_attachments = "GL_NV_fbo_color_attachments"; - + public static final String ARB_ES2_compatibility = "GL_ARB_ES2_compatibility"; public static final String ARB_ES3_compatibility = "GL_ARB_ES3_compatibility"; - + public static final String EXT_abgr = "GL_EXT_abgr"; public static final String OES_rgb8_rgba8 = "GL_OES_rgb8_rgba8"; public static final String OES_stencil1 = "GL_OES_stencil1"; public static final String OES_stencil4 = "GL_OES_stencil4"; public static final String OES_stencil8 = "GL_OES_stencil8"; public static final String APPLE_float_pixels = "GL_APPLE_float_pixels"; - + public static final String ARB_texture_non_power_of_two = "GL_ARB_texture_non_power_of_two"; public static final String ARB_texture_rectangle = "GL_ARB_texture_rectangle"; public static final String EXT_texture_rectangle = "GL_EXT_texture_rectangle"; @@ -72,15 +72,15 @@ public class GLExtensions { public static final String OES_read_format = "GL_OES_read_format"; public static final String OES_single_precision = "GL_OES_single_precision"; public static final String OES_EGL_image_external = "GL_OES_EGL_image_external"; - + public static final String ARB_gpu_shader_fp64 = "GL_ARB_gpu_shader_fp64"; - public static final String ARB_shader_objects = "GL_ARB_shader_objects"; + public static final String ARB_shader_objects = "GL_ARB_shader_objects"; public static final String ARB_geometry_shader4 = "GL_ARB_geometry_shader4"; - + // // Aliased GLX/WGL/.. extensions // - - public static final String ARB_pixel_format = "GL_ARB_pixel_format"; + + public static final String ARB_pixel_format = "GL_ARB_pixel_format"; public static final String ARB_pbuffer = "GL_ARB_pbuffer"; } diff --git a/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java b/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java index 6ef1e0805..ee77f8d2d 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java +++ b/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java @@ -29,20 +29,20 @@ package com.jogamp.opengl; import java.util.List; -/** - * GLRendererQuirks contains information of known bugs of various GL renderer. +/** + * GLRendererQuirks contains information of known bugs of various GL renderer. * This information allows us to workaround them. *

            * Using centralized quirk identifier enables us to - * locate code dealing w/ it and hence eases it's maintenance. + * locate code dealing w/ it and hence eases it's maintenance. *

            *

            * Some GL_VENDOR and GL_RENDERER strings are - * listed here . + * listed here . *

            */ public class GLRendererQuirks { - /** + /** * Crashes XServer when using double buffered PBuffer with GL_RENDERER: *
              *
            • Mesa DRI Intel(R) Sandybridge Desktop
            • @@ -52,23 +52,23 @@ public class GLRendererQuirks { * For now, it is safe to disable it w/ hw-acceleration. */ public static final int NoDoubleBufferedPBuffer = 0; - + /** On Windows no double buffered bitmaps are guaranteed to be available. */ public static final int NoDoubleBufferedBitmap = 1; /** Crashes application when trying to set EGL swap interval on Android 4.0.3 / Pandaboard ES / PowerVR SGX 540 */ public static final int NoSetSwapInterval = 2; - + /** No offscreen bitmap available, currently true for JOGL's OSX implementation. */ public static final int NoOffscreenBitmap = 3; - + /** SIGSEGV on setSwapInterval() after changing the context's drawable w/ 'Mesa 8.0.4' dri2SetSwapInterval/DRI2 (soft & intel) */ public static final int NoSetSwapIntervalPostRetarget = 4; /** GLSL discard command leads to undefined behavior or won't get compiled if being used. Appears to have happened on Nvidia Tegra2, but seems to be fine now. FIXME: Constrain version. */ public static final int GLSLBuggyDiscard = 5; - - /** + + /** * Non compliant GL context due to a buggy implementation not suitable for use. *

              * Currently, Mesa >= 9.1.3 (may extend back as far as 9.0) OpenGL 3.1 compatibility @@ -82,19 +82,19 @@ public class GLRendererQuirks { *

            *

            *

            - * It still has to be verified whether the AMD OpenGL 3.1 core driver is compliant enought. + * It still has to be verified whether the AMD OpenGL 3.1 core driver is compliant enought. */ public static final int GLNonCompliant = 6; - + /** * The OpenGL Context needs a glFlush() before releasing it, otherwise driver may freeze: *

              *
            • OSX < 10.7.3 - NVidia Driver. Bug 533 and Bug 548 @ https://jogamp.org/bugzilla/.
            • - *
            + *
          */ public static final int GLFlushBeforeRelease = 7; - - /** + + /** * Closing X11 displays may cause JVM crashes or X11 errors with some buggy drivers * while being used in concert w/ OpenGL. *

          @@ -123,14 +123,14 @@ public class GLRendererQuirks { *

          */ public static final int DontCloseX11Display = 8; - + /** - * Need current GL Context when calling new ARB pixel format query functions, + * Need current GL Context when calling new ARB pixel format query functions, * otherwise driver crashes the VM. *

          * Drivers known exposing such bug: *

            - *
          • ATI proprietary Catalyst driver on Windows version ≤ XP. + *
          • ATI proprietary Catalyst driver on Windows version ≤ XP. * TODO: Validate if bug actually relates to 'old' ATI Windows drivers for old GPU's like X300 * regardless of the Windows version.
          • *
          @@ -139,7 +139,7 @@ public class GLRendererQuirks { *

          */ public static final int NeedCurrCtx4ARBPixFmtQueries = 9; - + /** * Need current GL Context when calling new ARB CreateContext function, * otherwise driver crashes the VM. @@ -159,14 +159,14 @@ public class GLRendererQuirks { *

          */ public static final int NeedCurrCtx4ARBCreateContext = 10; - + /** * No full FBO support, i.e. not compliant w/ - *
            + *
              *
            • GL_ARB_framebuffer_object
            • - *
            • EXT_framebuffer_object
            • - *
            • EXT_framebuffer_multisample
            • - *
            • EXT_framebuffer_blit
            • + *
            • EXT_framebuffer_object
            • + *
            • EXT_framebuffer_multisample
            • + *
            • EXT_framebuffer_blit
            • *
            • EXT_packed_depth_stencil
            • *
            . * Drivers known exposing such bug: @@ -180,18 +180,18 @@ public class GLRendererQuirks { * Quirk can also be enabled via property: jogl.fbo.force.min. */ public static final int NoFullFBOSupport = 11; - + /** * GLSL is not compliant or even not stable (crash) *
              *
            • OSX < 10.7.0 (?) - NVidia Driver. Bug 818 @ https://jogamp.org/bugzilla/.
            • - *
            + *
          */ public static final int GLSLNonCompliant = 12; - + /** Number of quirks known. */ public static final int COUNT = 13; - + private static final String[] _names = new String[] { "NoDoubleBufferedPBuffer", "NoDoubleBufferedBitmap", "NoSetSwapInterval", "NoOffscreenBitmap", "NoSetSwapIntervalPostRetarget", "GLSLBuggyDiscard", "GLNonCompliant", "GLFlushBeforeRelease", "DontCloseX11Display", @@ -218,7 +218,7 @@ public class GLRendererQuirks { bitmask |= 1 << quirk; } _bitmask = bitmask; - } + } /** * @param quirks a list of valid quirks @@ -233,7 +233,7 @@ public class GLRendererQuirks { } _bitmask = bitmask; } - + /** * @param quirk the quirk to be tested * @return true if quirk exist, otherwise false @@ -261,7 +261,7 @@ public class GLRendererQuirks { sb.append("]"); return sb; } - + public final String toString() { return toString(null).toString(); } @@ -273,7 +273,7 @@ public class GLRendererQuirks { public static void validateQuirk(int quirk) throws IllegalArgumentException { if( !( 0 <= quirk && quirk < COUNT ) ) { throw new IllegalArgumentException("Quirks must be in range [0.."+COUNT+"[, but quirk: "+quirk); - } + } } /** diff --git a/src/jogl/classes/com/jogamp/opengl/GLStateKeeper.java b/src/jogl/classes/com/jogamp/opengl/GLStateKeeper.java index 321d4ee57..b98c4431d 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLStateKeeper.java +++ b/src/jogl/classes/com/jogamp/opengl/GLStateKeeper.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -31,12 +31,12 @@ package com.jogamp.opengl; * Interface adding a {@link GLEventListenerState} protocol to {@link GLAutoDrawable}s * or other self-contained compound types combining {@link GLDrawable}, {@link GLContext} and {@link GLEventListener}. *

          - * Implementing classes {@link #isGLStatePreservationSupported() may support} preservation - * of the {@link GLContext} state and it's associated {@link GLEventListener}. - *

          + * Implementing classes {@link #isGLStatePreservationSupported() may support} preservation + * of the {@link GLContext} state and it's associated {@link GLEventListener}. + *

          */ public interface GLStateKeeper { - + /** Listener for preserve and restore notifications. */ public static interface Listener { /** Invoked before preservation. */ @@ -44,14 +44,14 @@ public interface GLStateKeeper { /** Invoked after restoration. */ void glStateRestored(GLStateKeeper glsk); } - - /** + + /** * Sets a {@link Listener}, overriding the old one. * @param l the new {@link Listener}. * @return the previous {@link Listener}. */ public Listener setGLStateKeeperListener(Listener l); - + /** * @return true if GL state preservation is supported in implementation and on current platform, false otherwise. * @see #preserveGLStateAtDestroy(boolean) @@ -59,7 +59,7 @@ public interface GLStateKeeper { * @see #clearPreservedGLState() */ public boolean isGLStatePreservationSupported(); - + /** * If set to true, the next {@link GLAutoDrawable#destroy()} operation will * {@link #pullGLEventListenerState() pull} to preserve the {@link GLEventListenerState}. @@ -68,8 +68,8 @@ public interface GLStateKeeper { * the flag is cleared. *

          *

          - * A preserved {@link GLEventListenerState} will be {@link #pushGLEventListenerState() pushed} - * if realized again. + * A preserved {@link GLEventListenerState} will be {@link #pushGLEventListenerState() pushed} + * if realized again. *

          * @return true if supported and successful, false otherwise. * @see #isGLStatePreservationSupported() @@ -77,21 +77,21 @@ public interface GLStateKeeper { * @see #clearPreservedGLState() */ public boolean preserveGLStateAtDestroy(boolean value); - + /** * Returns the preserved {@link GLEventListenerState} if preservation was performed, - * otherwise null. + * otherwise null. * @see #isGLStatePreservationSupported() * @see #preserveGLStateAtDestroy(boolean) * @see #clearPreservedGLState() */ public GLEventListenerState getPreservedGLState(); - + /** * Clears the preserved {@link GLEventListenerState} from this {@link GLStateKeeper}, without destroying it. - * + * * @return the preserved and cleared {@link GLEventListenerState} if preservation was performed, - * otherwise null. + * otherwise null. * @see #isGLStatePreservationSupported() * @see #preserveGLStateAtDestroy(boolean) * @see #getPreservedGLState() diff --git a/src/jogl/classes/com/jogamp/opengl/GenericGLCapabilitiesChooser.java b/src/jogl/classes/com/jogamp/opengl/GenericGLCapabilitiesChooser.java index 73ec10886..3693f647a 100644 --- a/src/jogl/classes/com/jogamp/opengl/GenericGLCapabilitiesChooser.java +++ b/src/jogl/classes/com/jogamp/opengl/GenericGLCapabilitiesChooser.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -37,7 +37,7 @@ import javax.media.opengl.DefaultGLCapabilitiesChooser; * otherwise uses {@link DefaultGLCapabilitiesChooser} implementation. */ public class GenericGLCapabilitiesChooser extends DefaultGLCapabilitiesChooser { - + @Override public int chooseCapabilities(final CapabilitiesImmutable desired, final List available, diff --git a/src/jogl/classes/com/jogamp/opengl/JoglVersion.java b/src/jogl/classes/com/jogamp/opengl/JoglVersion.java index 1f0189aa3..1f715c21a 100644 --- a/src/jogl/classes/com/jogamp/opengl/JoglVersion.java +++ b/src/jogl/classes/com/jogamp/opengl/JoglVersion.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.opengl; import com.jogamp.common.GlueGenVersion; @@ -90,16 +90,16 @@ public class JoglVersion extends JogampVersion { sb.append("\tnone").append(Platform.getNewline()); } sb.append(Platform.getNewline()); - return sb; + return sb; } - + public static StringBuilder getAllAvailableCapabilitiesInfo(AbstractGraphicsDevice device, StringBuilder sb) { if(null==sb) { sb = new StringBuilder(); } if(null == device) { device = GLProfile.getDefaultDevice(); - } + } sb.append(Platform.getNewline()).append(Platform.getNewline()); sb.append("Desktop Capabilities: ").append(Platform.getNewline()); getAvailableCapabilitiesInfo(GLDrawableFactory.getDesktopFactory(), device, sb); @@ -107,7 +107,7 @@ public class JoglVersion extends JogampVersion { getAvailableCapabilitiesInfo(GLDrawableFactory.getEGLFactory(), device, sb); return sb; } - + public static StringBuilder getDefaultOpenGLInfo(AbstractGraphicsDevice device, StringBuilder sb, boolean withCapabilitiesInfo) { if(null==sb) { sb = new StringBuilder(); @@ -126,7 +126,7 @@ public class JoglVersion extends JogampVersion { } return sb; } - + public static StringBuilder getGLInfo(GL gl, StringBuilder sb) { return getGLInfo(gl, sb, false); } @@ -136,26 +136,26 @@ public class JoglVersion extends JogampVersion { if(null==sb) { sb = new StringBuilder(); } - + sb.append(VersionUtil.SEPERATOR).append(Platform.getNewline()); sb.append(device.getClass().getSimpleName()).append("[type ") .append(device.getType()).append(", connection ").append(device.getConnection()).append("]: ").append(Platform.getNewline()); - GLProfile.glAvailabilityToString(device, sb, "\t", 1); + GLProfile.glAvailabilityToString(device, sb, "\t", 1); sb.append(Platform.getNewline()); sb = getGLStrings(gl, sb, withCapabilitiesAndExtensionInfo); - + if( withCapabilitiesAndExtensionInfo ) { - sb = getAllAvailableCapabilitiesInfo(device, sb); + sb = getAllAvailableCapabilitiesInfo(device, sb); } return sb; } - + public static StringBuilder getGLStrings(GL gl, StringBuilder sb) { return getGLStrings(gl, sb, true); } - - public static StringBuilder getGLStrings(GL gl, StringBuilder sb, boolean withExtensions) { + + public static StringBuilder getGLStrings(GL gl, StringBuilder sb, boolean withExtensions) { if(null==sb) { sb = new StringBuilder(); } @@ -175,7 +175,7 @@ public class JoglVersion extends JogampVersion { sb.append("GL_RENDERER ").append(gl.glGetString(GL.GL_RENDERER)); sb.append(Platform.getNewline()); sb.append("GL_VERSION ").append(gl.glGetString(GL.GL_VERSION)); - sb.append(Platform.getNewline()); + sb.append(Platform.getNewline()); sb.append("GLSL ").append(gl.hasGLSL()).append(", has-compiler-func: ").append(gl.isFunctionAvailable("glCompileShader")); if(gl.hasGLSL()) { sb.append(", version: ").append(gl.glGetString(GL2ES2.GL_SHADING_LANGUAGE_VERSION)).append(" / ").append(ctx.getGLSLVersionNumber()); @@ -200,7 +200,7 @@ public class JoglVersion extends JogampVersion { return sb; } - public StringBuilder getBriefOSGLBuildInfo(GL gl, StringBuilder sb) { + public StringBuilder getBriefOSGLBuildInfo(GL gl, StringBuilder sb) { if(null==sb) { sb = new StringBuilder(); } @@ -216,7 +216,7 @@ public class JoglVersion extends JogampVersion { sb.append(Platform.getNewline()); return sb; } - + public static void main(String args[]) { System.err.println(VersionUtil.getPlatformInfo()); System.err.println(GlueGenVersion.getInstance()); diff --git a/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java b/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java index ca4846939..8d2d07d58 100644 --- a/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.opengl.cg; import com.jogamp.common.jvm.JNILibLoaderBase; @@ -45,15 +45,15 @@ public final class CgDynamicLibraryBundleInfo implements DynamicLibraryBundleInf AccessController.doPrivileged(new PrivilegedAction() { public Object run() { Platform.initSingleton(); - + if(TempJarCache.isInitialized()) { // only: jogl-cg.jar -> jogl-cg-natives-.jar [atomic JAR files only] - JNILibLoaderBase.addNativeJarLibs(new Class[] { CgDynamicLibraryBundleInfo.class }, null, null ); + JNILibLoaderBase.addNativeJarLibs(new Class[] { CgDynamicLibraryBundleInfo.class }, null, null ); } return null; } }); - + glueLibNames = new ArrayList(); // glueLibNames.addAll(getGlueLibNamesPreload()); glueLibNames.add("jogl_cg"); @@ -76,7 +76,7 @@ public final class CgDynamicLibraryBundleInfo implements DynamicLibraryBundleInf *

          * Returns false. *

          - */ + */ @Override public final boolean shallLookupGlobal() { return false; } @@ -91,7 +91,7 @@ public final class CgDynamicLibraryBundleInfo implements DynamicLibraryBundleInf public final long toolGetProcAddress(long toolGetProcAddressHandle, String funcName) { return 0; } - + @Override public final boolean useToolGetProcAdressFirst(String funcName) { return false; @@ -103,7 +103,7 @@ public final class CgDynamicLibraryBundleInfo implements DynamicLibraryBundleInf final List libsCg = new ArrayList(); libsCg.add("Cg"); libsList.add(libsCg); - + final List libsCgGL = new ArrayList(); libsCgGL.add("CgGL"); libsList.add(libsCgGL); @@ -119,7 +119,7 @@ public final class CgDynamicLibraryBundleInfo implements DynamicLibraryBundleInf @Override public final RunnableExecutor getLibLoaderExecutor() { return DynamicLibraryBundle.getDefaultRunnableExecutor(); - } + } } diff --git a/src/jogl/classes/com/jogamp/opengl/cg/CgException.java b/src/jogl/classes/com/jogamp/opengl/cg/CgException.java index 8bfd9e23e..3e42f4d70 100644 --- a/src/jogl/classes/com/jogamp/opengl/cg/CgException.java +++ b/src/jogl/classes/com/jogamp/opengl/cg/CgException.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/math/FixedPoint.java b/src/jogl/classes/com/jogamp/opengl/math/FixedPoint.java index e0acfec28..b7dbf183f 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/FixedPoint.java +++ b/src/jogl/classes/com/jogamp/opengl/math/FixedPoint.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2009 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 @@ -28,7 +28,7 @@ * 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. - * + * */ package com.jogamp.opengl.math; diff --git a/src/jogl/classes/com/jogamp/opengl/math/FloatUtil.java b/src/jogl/classes/com/jogamp/opengl/math/FloatUtil.java index f3f44f15a..191a83241 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/FloatUtil.java +++ b/src/jogl/classes/com/jogamp/opengl/math/FloatUtil.java @@ -40,7 +40,7 @@ import com.jogamp.common.os.Platform; *

          * Derived from ProjectFloat.java - Created 11-jan-2004 *

          - * + * * @author Erik Duijs * @author Kenneth Russell * @author Sven Gothel @@ -95,7 +95,7 @@ public class FloatUtil { m.put(ZERO_MATRIX); m.position(oldPos); } - + /** * @param a 4x4 matrix in column-major order * @param b 4x4 matrix in column-major order @@ -111,7 +111,7 @@ public class FloatUtil { d[d_off+i+3*4] = ai0 * b[b_off+0+3*4] + ai1 * b[b_off+1+3*4] + ai2 * b[b_off+2+3*4] + ai3 * b[b_off+3+3*4] ; } } - + /** * @param a 4x4 matrix in column-major order (also result) * @param b 4x4 matrix in column-major order @@ -127,7 +127,7 @@ public class FloatUtil { a[a_off_i+3*4] = ai0 * b[b_off+0+3*4] + ai1 * b[b_off+1+3*4] + ai2 * b[b_off+2+3*4] + ai3 * b[b_off+3+3*4] ; } } - + /** * @param a 4x4 matrix in column-major order * @param b 4x4 matrix in column-major order @@ -151,7 +151,7 @@ public class FloatUtil { * @param d result a*b in column-major order */ public static final void multMatrixf(final FloatBuffer a, final float[] b, int b_off, FloatBuffer d) { - final int aP = a.position(); + final int aP = a.position(); final int dP = d.position(); for (int i = 0; i < 4; i++) { // one row in column-major order @@ -162,13 +162,13 @@ public class FloatUtil { d.put(dP+i+3*4 , ai0 * b[b_off+0+3*4] + ai1 * b[b_off+1+3*4] + ai2 * b[b_off+2+3*4] + ai3 * b[b_off+3+3*4] ); } } - + /** * @param a 4x4 matrix in column-major order (also result) * @param b 4x4 matrix in column-major order */ public static final void multMatrixf(final FloatBuffer a, final float[] b, int b_off) { - final int aP = a.position(); + final int aP = a.position(); for (int i = 0; i < 4; i++) { // one row in column-major order final int aP_i = aP+i; @@ -186,7 +186,7 @@ public class FloatUtil { * @param d result a*b in column-major order */ public static final void multMatrixf(final FloatBuffer a, final FloatBuffer b, FloatBuffer d) { - final int aP = a.position(); + final int aP = a.position(); final int bP = b.position(); final int dP = d.position(); for (int i = 0; i < 4; i++) { @@ -198,13 +198,13 @@ public class FloatUtil { d.put(dP+i+3*4 , ai0 * b.get(bP+0+3*4) + ai1 * b.get(bP+1+3*4) + ai2 * b.get(bP+2+3*4) + ai3 * b.get(bP+3+3*4) ); } } - + /** * @param a 4x4 matrix in column-major order (also result) * @param b 4x4 matrix in column-major order */ public static final void multMatrixf(final FloatBuffer a, final FloatBuffer b) { - final int aP = a.position(); + final int aP = a.position(); final int bP = b.position(); for (int i = 0; i < 4; i++) { // one row in column-major order @@ -216,14 +216,14 @@ public class FloatUtil { a.put(aP_i+3*4 , ai0 * b.get(bP+0+3*4) + ai1 * b.get(bP+1+3*4) + ai2 * b.get(bP+2+3*4) + ai3 * b.get(bP+3+3*4) ); } } - + /** * @param a 4x4 matrix in column-major order * @param b 4x4 matrix in column-major order * @param d result a*b in column-major order */ public static final void multMatrixf(final FloatBuffer a, final FloatBuffer b, float[] d, int d_off) { - final int aP = a.position(); + final int aP = a.position(); final int bP = b.position(); for (int i = 0; i < 4; i++) { // one row in column-major order @@ -234,7 +234,7 @@ public class FloatUtil { d[d_off+i+3*4] = ai0 * b.get(bP+0+3*4) + ai1 * b.get(bP+1+3*4) + ai2 * b.get(bP+2+3*4) + ai3 * b.get(bP+3+3*4) ; } } - + /** * Normalize vector * @@ -242,7 +242,7 @@ public class FloatUtil { */ public static final void normalize(float[] v) { float r = (float) Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); - + if ( r == 0.0 || r == 1.0) { return; } @@ -265,7 +265,7 @@ public class FloatUtil { float r = (float) Math.sqrt(v.get(0+vPos) * v.get(0+vPos) + v.get(1+vPos) * v.get(1+vPos) + v.get(2+vPos) * v.get(2+vPos)); - + if ( r == 0.0 || r == 1.0) { return; } @@ -341,7 +341,7 @@ public class FloatUtil { v_in[3] * m_in[3*4+i]; } } - + /** * @param m_in 4x4 matrix in column-major order * @param v_in 4-component column-vector @@ -355,10 +355,10 @@ public class FloatUtil { v_in[0+v_in_off] * m_in.get(0*4+i+matrixPos) + v_in[1+v_in_off] * m_in.get(1*4+i+matrixPos) + v_in[2+v_in_off] * m_in.get(2*4+i+matrixPos) + - v_in[3+v_in_off] * m_in.get(3*4+i+matrixPos); + v_in[3+v_in_off] * m_in.get(3*4+i+matrixPos); } } - + /** * @param m_in 4x4 matrix in column-major order * @param v_in 4-component column-vector @@ -372,10 +372,10 @@ public class FloatUtil { v_in[0] * m_in.get(0*4+i+matrixPos) + v_in[1] * m_in.get(1*4+i+matrixPos) + v_in[2] * m_in.get(2*4+i+matrixPos) + - v_in[3] * m_in.get(3*4+i+matrixPos); + v_in[3] * m_in.get(3*4+i+matrixPos); } } - + /** * @param m_in 4x4 matrix in column-major order * @param v_in 4-component column-vector @@ -395,7 +395,7 @@ public class FloatUtil { } } - /** + /** * @param sb optional passed StringBuilder instance to be used * @param f the format string of one floating point, i.e. "%10.5f", see {@link java.util.Formatter} * @param a mxn matrix (rows x columns) @@ -403,7 +403,7 @@ public class FloatUtil { * @param rows * @param columns * @param rowMajorOrder if true floats are layed out in row-major-order, otherwise column-major-order (OpenGL) - * @param row row number to print + * @param row row number to print * @return matrix row string representation */ public static StringBuilder matrixRowToString(StringBuilder sb, String f, FloatBuffer a, int aOffset, int rows, int columns, boolean rowMajorOrder, int row) { @@ -413,17 +413,17 @@ public class FloatUtil { final int a0 = aOffset + a.position(); if(rowMajorOrder) { for(int c=0; ca's current position @@ -469,14 +469,14 @@ public class FloatUtil { for(int i=0; ia's current position @@ -493,14 +493,14 @@ public class FloatUtil { for(int i=0; ia's current position @@ -521,14 +521,14 @@ public class FloatUtil { matrixRowToString(sb, f, a, aOffset, rows, columns, rowMajorOrder, i); sb.append("=?= "); matrixRowToString(sb, f, b, bOffset, rows, columns, rowMajorOrder, i); - sb.append("]").append(Platform.getNewline()); + sb.append("]").append(Platform.getNewline()); } return sb; } - /** + /** * @param sb optional passed StringBuilder instance to be used - * @param rowPrefix optional prefix for each row + * @param rowPrefix optional prefix for each row * @param f the format string of one floating point, i.e. "%10.5f", see {@link java.util.Formatter} * @param a 4x4 matrix in column major order (OpenGL) * @param aOffset offset to a's current position @@ -549,11 +549,11 @@ public class FloatUtil { matrixRowToString(sb, f, a, aOffset, rows, columns, rowMajorOrder, i); sb.append("=?= "); matrixRowToString(sb, f, b, bOffset, rows, columns, rowMajorOrder, i); - sb.append("]").append(Platform.getNewline()); + sb.append("]").append(Platform.getNewline()); } return sb; } - + public static final float E = 2.7182818284590452354f; public static final float PI = 3.14159265358979323846f; @@ -569,5 +569,5 @@ public class FloatUtil { public static float acos(float a) { return (float) java.lang.Math.acos(a); } public static float sqrt(float a) { return (float) java.lang.Math.sqrt(a); } - + } \ No newline at end of file diff --git a/src/jogl/classes/com/jogamp/opengl/math/Quaternion.java b/src/jogl/classes/com/jogamp/opengl/math/Quaternion.java index c6bf44f6d..78cbb18cf 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/Quaternion.java +++ b/src/jogl/classes/com/jogamp/opengl/math/Quaternion.java @@ -33,7 +33,7 @@ public class Quaternion { public Quaternion() { setIdentity(); } - + public Quaternion(Quaternion q) { x = q.x; y = q.y; @@ -50,7 +50,7 @@ public class Quaternion { /** * Constructor to create a rotation based quaternion from two vectors - * + * * @param vector1 * @param vector2 */ @@ -59,7 +59,7 @@ public class Quaternion { final float[] cross = VectorUtil.cross(vector1, vector2); fromAxis(cross, theta); } - + /*** * Constructor to create a rotation based quaternion from axis vector and angle * @param vector axis vector @@ -69,10 +69,10 @@ public class Quaternion { public Quaternion(float[] vector, float angle) { fromAxis(vector, angle); } - + /*** * Initialize this quaternion with given axis vector and rotation angle - * + * * @param vector axis vector * @param angle rotation angle (rads) */ @@ -88,7 +88,7 @@ public class Quaternion { /** * Transform the rotational quaternion to axis based rotation angles - * + * * @return new float[4] with ,theta,Rx,Ry,Rz */ public float[] toAxis() { @@ -135,7 +135,7 @@ public class Quaternion { /** * Add a quaternion - * + * * @param q quaternion */ public void add(Quaternion q) { @@ -146,7 +146,7 @@ public class Quaternion { /** * Subtract a quaternion - * + * * @param q quaternion */ public void subtract(Quaternion q) { @@ -157,7 +157,7 @@ public class Quaternion { /** * Divide a quaternion by a constant - * + * * @param n a float to divide by */ public void divide(float n) { @@ -168,7 +168,7 @@ public class Quaternion { /** * Multiply this quaternion by the param quaternion - * + * * @param q a quaternion to multiply with */ public void mult(Quaternion q) { @@ -186,7 +186,7 @@ public class Quaternion { /** * Multiply a quaternion by a constant - * + * * @param n a float constant */ public void mult(float n) { @@ -194,10 +194,10 @@ public class Quaternion { y *= n; z *= n; } - + /*** * Rotate given vector by this quaternion - * + * * @param vector input vector * @return rotated vector */ @@ -250,7 +250,7 @@ public class Quaternion { /** * Transform this quaternion to a 4x4 column matrix representing the * rotation - * + * * @return new float[16] column matrix 4x4 */ public float[] toMatrix() { @@ -287,7 +287,7 @@ public class Quaternion { * See http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/ * quaternions/slerp/ *

          - * + * * @param a initial quaternion * @param b target quaternion * @param t float between 0 and 1 representing interp. @@ -332,13 +332,13 @@ public class Quaternion { /** * Check if this quaternion represents an identity matrix for rotation, * , ie (0,0,0,1). - * + * * @return true if it is an identity rep., false otherwise */ public boolean isIdentity() { return w == 1 && x == 0 && y == 0 && z == 0; } - + /*** * Set this quaternion to identity (x=0,y=0,z=0,w=1) */ @@ -349,7 +349,7 @@ public class Quaternion { /** * compute the quaternion from a 3x3 column matrix - * + * * @param m 3x3 column matrix */ public void setFromMatrix(float[] m) { @@ -386,7 +386,7 @@ public class Quaternion { /** * Check if the the 3x3 matrix (param) is in fact an affine rotational * matrix - * + * * @param m 3x3 column matrix * @return true if representing a rotational matrix, false otherwise */ diff --git a/src/jogl/classes/com/jogamp/opengl/math/VectorUtil.java b/src/jogl/classes/com/jogamp/opengl/math/VectorUtil.java index 0033afeaa..508f1aafd 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/VectorUtil.java +++ b/src/jogl/classes/com/jogamp/opengl/math/VectorUtil.java @@ -39,7 +39,7 @@ public class VectorUtil { Winding(int dir) { this.dir = dir; } - } + } public static final int COLLINEAR = 0; @@ -119,15 +119,15 @@ public class VectorUtil { /** Column Matrix Vector multiplication * @param colMatrix column matrix (4x4) * @param vec vector(x,y,z) - * @return result new float[3] + * @return result new float[3] */ public static float[] colMatrixVectorMult(float[] colMatrix, float[] vec) { final float[] out = new float[3]; - out[0] = vec[0]*colMatrix[0] + vec[1]*colMatrix[4] + vec[2]*colMatrix[8] + colMatrix[12]; - out[1] = vec[0]*colMatrix[1] + vec[1]*colMatrix[5] + vec[2]*colMatrix[9] + colMatrix[13]; - out[2] = vec[0]*colMatrix[2] + vec[1]*colMatrix[6] + vec[2]*colMatrix[10] + colMatrix[14]; + out[0] = vec[0]*colMatrix[0] + vec[1]*colMatrix[4] + vec[2]*colMatrix[8] + colMatrix[12]; + out[1] = vec[0]*colMatrix[1] + vec[1]*colMatrix[5] + vec[2]*colMatrix[9] + colMatrix[13]; + out[2] = vec[0]*colMatrix[2] + vec[1]*colMatrix[6] + vec[2]*colMatrix[10] + colMatrix[14]; return out; } @@ -135,15 +135,15 @@ public class VectorUtil { /** Matrix Vector multiplication * @param rawMatrix column matrix (4x4) * @param vec vector(x,y,z) - * @return result new float[3] + * @return result new float[3] */ public static float[] rowMatrixVectorMult(float[] rawMatrix, float[] vec) { final float[] out = new float[3]; - out[0] = vec[0]*rawMatrix[0] + vec[1]*rawMatrix[1] + vec[2]*rawMatrix[2] + rawMatrix[3]; - out[1] = vec[0]*rawMatrix[4] + vec[1]*rawMatrix[5] + vec[2]*rawMatrix[6] + rawMatrix[7]; - out[2] = vec[0]*rawMatrix[8] + vec[1]*rawMatrix[9] + vec[2]*rawMatrix[10] + rawMatrix[11]; + out[0] = vec[0]*rawMatrix[0] + vec[1]*rawMatrix[1] + vec[2]*rawMatrix[2] + rawMatrix[3]; + out[1] = vec[0]*rawMatrix[4] + vec[1]*rawMatrix[5] + vec[2]*rawMatrix[6] + rawMatrix[7]; + out[2] = vec[0]*rawMatrix[8] + vec[1]*rawMatrix[9] + vec[2]*rawMatrix[10] + rawMatrix[11]; return out; } @@ -157,7 +157,7 @@ public class VectorUtil { { return (p1+p2)/2.0f; } - + /** Calculate the midpoint of two points * @param p1 first point * @param p2 second point @@ -172,7 +172,7 @@ public class VectorUtil { return midPoint; } - + /** Compute the norm of a vector * @param vec vector * @return vorm @@ -181,7 +181,7 @@ public class VectorUtil { { return FloatUtil.sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]); } - + /** Compute distance between 2 points * @param p0 a ref point on the line * @param vec vector representing the direction of the line @@ -216,7 +216,7 @@ public class VectorUtil { */ public static boolean checkEqualityVec2(float[] v1, float[] v2) { - return Float.compare(v1[0], v2[0]) == 0 && + return Float.compare(v1[0], v2[0]) == 0 && Float.compare(v1[1], v2[1]) == 0 ; } @@ -261,7 +261,7 @@ public class VectorUtil { * @param b triangle vertex 2 * @param c triangle vertex 3 * @param d vertex in question - * @return true if the vertex d is inside the circle defined by the + * @return true if the vertex d is inside the circle defined by the * vertices a, b, c. from paper by Guibas and Stolfi (1985). */ public static boolean inCircle(Vert2fImmutable a, Vert2fImmutable b, Vert2fImmutable c, Vert2fImmutable d){ @@ -282,8 +282,8 @@ public class VectorUtil { return (b.getX() - a.getX()) * (c.getY() - a.getY()) - (b.getY() - a.getY())*(c.getX() - a.getX()); } - /** Check if a vertex is in triangle using - * barycentric coordinates computation. + /** Check if a vertex is in triangle using + * barycentric coordinates computation. * @param a first triangle vertex * @param b second triangle vertex * @param c third triangle vertex @@ -291,7 +291,7 @@ public class VectorUtil { * @return true if p is in triangle (a, b, c), false otherwise. */ public static boolean vertexInTriangle(float[] a, float[] b, float[] c, float[] p){ - // Compute vectors + // Compute vectors final float[] ac = computeVector(a, c); //v0 final float[] ab = computeVector(a, b); //v1 final float[] ap = computeVector(a, p); //v2 @@ -362,13 +362,13 @@ public class VectorUtil { * @param b vertex 2 of first segment * @param c vertex 1 of second segment * @param d vertex 2 of second segment - * @return the intersection coordinates if the segments intersect, otherwise - * returns null + * @return the intersection coordinates if the segments intersect, otherwise + * returns null */ public static float[] seg2SegIntersection(Vert2fImmutable a, Vert2fImmutable b, Vert2fImmutable c, Vert2fImmutable d) { final float determinant = (a.getX()-b.getX())*(c.getY()-d.getY()) - (a.getY()-b.getY())*(c.getX()-d.getX()); - if (determinant == 0) + if (determinant == 0) return null; final float alpha = (a.getX()*b.getY()-a.getY()*b.getX()); @@ -389,13 +389,13 @@ public class VectorUtil { * @param b vertex 2 of first line * @param c vertex 1 of second line * @param d vertex 2 of second line - * @return the intersection coordinates if the lines intersect, otherwise - * returns null + * @return the intersection coordinates if the lines intersect, otherwise + * returns null */ public static float[] line2lineIntersection(Vert2fImmutable a, Vert2fImmutable b, Vert2fImmutable c, Vert2fImmutable d) { final float determinant = (a.getX()-b.getX())*(c.getY()-d.getY()) - (a.getY()-b.getY())*(c.getX()-d.getX()); - if (determinant == 0) + if (determinant == 0) return null; final float alpha = (a.getX()*b.getY()-a.getY()*b.getX()); diff --git a/src/jogl/classes/com/jogamp/opengl/math/Vert2fImmutable.java b/src/jogl/classes/com/jogamp/opengl/math/Vert2fImmutable.java index 13349884c..ec90b401f 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/Vert2fImmutable.java +++ b/src/jogl/classes/com/jogamp/opengl/math/Vert2fImmutable.java @@ -33,7 +33,7 @@ public interface Vert2fImmutable { float getY(); int getCoordCount(); - + float[] getCoord(); - + } diff --git a/src/jogl/classes/com/jogamp/opengl/math/geom/AABBox.java b/src/jogl/classes/com/jogamp/opengl/math/geom/AABBox.java index b6e8ede2e..f1880a61b 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/geom/AABBox.java +++ b/src/jogl/classes/com/jogamp/opengl/math/geom/AABBox.java @@ -32,23 +32,23 @@ import com.jogamp.opengl.math.VectorUtil; /** * Axis Aligned Bounding Box. Defined by two 3D coordinates (low and high) - * The low being the the lower left corner of the box, and the high being the upper + * The low being the the lower left corner of the box, and the high being the upper * right corner of the box. - * + * */ public class AABBox implements Cloneable { private float[] low = new float[3]; private float[] high = new float[3]; private float[] center = new float[3]; - /** Create a Axis Aligned bounding box (AABBox) + /** Create a Axis Aligned bounding box (AABBox) * where the low and and high MAX float Values. */ public AABBox() { reset(); } - /** Create an AABBox specifying the coordinates + /** Create an AABBox specifying the coordinates * of the low and high * @param lx min x-coordinate * @param ly min y-coordnate @@ -61,7 +61,7 @@ public class AABBox implements Cloneable { float hx, float hy, float hz) { setSize(lx, ly, lz, hx, hy, hz); } - + /** Create a AABBox defining the low and high * @param low min xyz-coordinates * @param high max xyz-coordinates @@ -78,27 +78,27 @@ public class AABBox implements Cloneable { center[1] = 0f; center[2] = 0f; } - + /** Get the max xyz-coordinates * @return a float array containing the max xyz coordinates */ public final float[] getHigh() { return high; } - + private final void setHigh(float hx, float hy, float hz) { this.high[0] = hx; this.high[1] = hy; this.high[2] = hz; } - + /** Get the min xyz-coordinates * @return a float array containing the min xyz coordinates */ public final float[] getLow() { return low; } - + private final void setLow(float lx, float ly, float lz) { this.low[0] = lx; this.low[1] = ly; @@ -111,10 +111,10 @@ public class AABBox implements Cloneable { center[2] = (high[2] + low[2])/2; } - /** - * Set size of the AABBox specifying the coordinates + /** + * Set size of the AABBox specifying the coordinates * of the low and high. - * + * * @param lx min x-coordinate * @param ly min y-coordnate * @param lz min z-coordinate @@ -123,7 +123,7 @@ public class AABBox implements Cloneable { * @param hz max z-coordinate */ public final void setSize(float lx, float ly, float lz, - float hx, float hy, float hz) { + float hx, float hy, float hz) { this.low[0] = lx; this.low[1] = ly; this.low[2] = lz; @@ -132,7 +132,7 @@ public class AABBox implements Cloneable { this.high[2] = hz; computeCenter(); } - + /** Resize the AABBox to encapsulate another AABox * @param newBox AABBox to be encapsulated in */ @@ -160,12 +160,12 @@ public class AABBox implements Cloneable { } /** Resize the AABBox to encapsulate the passed - * xyz-coordinates. + * xyz-coordinates. * @param x x-axis coordinate value * @param y y-axis coordinate value * @param z z-axis coordinate value */ - public final void resize(float x, float y, float z) { + public final void resize(float x, float y, float z) { /** test low */ if (x < low[0]) low[0] = x; @@ -181,12 +181,12 @@ public class AABBox implements Cloneable { high[1] = y; if (z > high[2]) high[2] = z; - + computeCenter(); } /** Resize the AABBox to encapsulate the passed - * xyz-coordinates. + * xyz-coordinates. * @param xyz xyz-axis coordinate values * @param offset of the array */ @@ -210,7 +210,7 @@ public class AABBox implements Cloneable { } return true; } - + /** Check if the xyz coordinates are bounded/contained * by this AABBox. * @param x x-axis coordinate value @@ -231,7 +231,7 @@ public class AABBox implements Cloneable { } return true; } - + /** Check if there is a common region between this AABBox and the passed * 2D region irrespective of z range * @param x lower left x-coord @@ -244,13 +244,13 @@ public class AABBox implements Cloneable { if (w <= 0 || h <= 0) { return false; } - + final float _w = getWidth(); - final float _h = getHeight(); + final float _h = getHeight(); if (_w <= 0 || _h <= 0) { return false; } - + final float x0 = getMinX(); final float y0 = getMinY(); return (x + w > x0 && @@ -259,8 +259,8 @@ public class AABBox implements Cloneable { y < y0 + _h); } - - /** Get the size of the Box where the size is represented by the + + /** Get the size of the Box where the size is represented by the * length of the vector between low and high. * @return a float representing the size of the AABBox */ @@ -283,16 +283,16 @@ public class AABBox implements Cloneable { diffH[0] = high[0] - center[0]; diffH[1] = high[1] - center[1]; diffH[2] = high[2] - center[2]; - + diffH = VectorUtil.scale(diffH, size); - + float[] diffL = new float[3]; diffL[0] = low[0] - center[0]; diffL[1] = low[1] - center[1]; diffL[2] = low[2] - center[2]; - + diffL = VectorUtil.scale(diffL, size); - + high = VectorUtil.vectorAdd(center, diffH); low = VectorUtil.vectorAdd(center, diffL); } @@ -300,43 +300,43 @@ public class AABBox implements Cloneable { public final float getMinX() { return low[0]; } - + public final float getMinY() { return low[1]; } - + public final float getMinZ() { return low[2]; } - + public final float getMaxX() { return high[0]; } - + public final float getMaxY() { return high[1]; } - + public final float getMaxZ() { return high[2]; } - + public final float getWidth(){ return high[0] - low[0]; } - + public final float getHeight() { return high[1] - low[1]; } - + public final float getDepth() { return high[2] - low[2]; } - + public final AABBox clone() { return new AABBox(this.low, this.high); } - + public final boolean equals(Object obj) { if( obj == this ) { return true; @@ -344,11 +344,11 @@ public class AABBox implements Cloneable { if( null == obj || !(obj instanceof AABBox) ) { return false; } - final AABBox other = (AABBox) obj; - return VectorUtil.checkEquality(low, other.low) && + final AABBox other = (AABBox) obj; + return VectorUtil.checkEquality(low, other.low) && VectorUtil.checkEquality(high, other.high) ; } - + public final String toString() { return "[ "+low[0]+"/"+low[1]+"/"+low[1]+" .. "+high[0]+"/"+high[0]+"/"+high[0]+", ctr "+ center[0]+"/"+center[1]+"/"+center[1]+" ]"; diff --git a/src/jogl/classes/com/jogamp/opengl/math/geom/Frustum.java b/src/jogl/classes/com/jogamp/opengl/math/geom/Frustum.java index 93e68a1d6..fb311083f 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/geom/Frustum.java +++ b/src/jogl/classes/com/jogamp/opengl/math/geom/Frustum.java @@ -30,11 +30,11 @@ package com.jogamp.opengl.math.geom; import com.jogamp.common.os.Platform; /** - * Providing frustum {@link #getPlanes() planes} derived by different inputs + * Providing frustum {@link #getPlanes() planes} derived by different inputs * ({@link #updateByPMV(float[], int) P*MV}, ..) - * used to {@link #classifySphere(float[], float) classify objects} and to test + * used to {@link #classifySphere(float[], float) classify objects} and to test * whether they are {@link #isOutside(AABBox) outside}. - * + * *

          * Extracting the world-frustum planes from the P*Mv: *

          @@ -54,7 +54,7 @@ import com.jogamp.common.os.Platform;
            * Lighthouse3d.com
            * http://www.lighthouse3d.com/tutorials/view-frustum-culling/
            * 
          - * + * * Fundamentals about Planes, Half-Spaces and Frustum-Culling:
          *
            * Planes and Half-Spaces,  Max Wagner 
          @@ -69,7 +69,7 @@ import com.jogamp.common.os.Platform;
           public class Frustum {
               /** Normalized planes[l, r, b, t, n, f] */
           	protected Plane[] planes = new Plane[6];
          -	
          +
           	/**
           	 * Creates an undefined instance w/o calculating the frustum.
           	 * 

          @@ -83,35 +83,35 @@ public class Frustum { planes[i] = new Plane(); } } - - /** + + /** * Plane equation := dot(n, x - p) = 0 -> ax + bc + cx + d == 0 *

          * In order to work w/ {@link Frustum#isOutside(AABBox) isOutside(..)} methods, * the normals have to point to the inside of the frustum. - *

          + *

          */ public static class Plane { /** Normal of the plane */ public final float[] n = new float[3]; - + /** Distance to origin */ public float d; - /** + /** * Return signed distance of plane to given point. *
            *
          • If dist < 0 , then the point p lies in the negative halfspace.
          • *
          • If dist = 0 , then the point p lies in the plane.
          • *
          • If dist > 0 , then the point p lies in the positive halfspace.
          • - *
          + * * A plane cuts 3D space into 2 half spaces. *

          * Positive halfspace is where the plane’s normals vector points into. - *

          + *

          *

          * Negative halfspace is the other side of the plane, i.e. *-1 - *

          + *

          **/ public final float distanceTo(float x, float y, float z) { return n[0] * x + n[1] * y + n[2] * z + d; @@ -121,13 +121,13 @@ public class Frustum { public final float distanceTo(float[] p) { return n[0] * p[0] + n[1] * p[1] + n[2] * p[2] + d; } - + @Override public String toString() { return "Plane[ [ " + n[0] + ", " + n[1] + ", " + n[2] + " ], " + d + "]"; } } - + /** Index for left plane: {@value} */ public static final int LEFT = 0; /** Index for right plane: {@value} */ @@ -140,7 +140,7 @@ public class Frustum { public static final int NEAR = 4; /** Index for far plane: {@value} */ public static final int FAR = 5; - + /** * {@link Plane}s are ordered in the returned array as follows: *
            @@ -154,17 +154,17 @@ public class Frustum { *

            * {@link Plane}'s normals are pointing to the inside of the frustum * in order to work w/ {@link #isOutside(AABBox) isOutside(..)} methods. - *

            - * - * @return array of normalized {@link Plane}s, order see above. + *

            + * + * @return array of normalized {@link Plane}s, order see above. */ public final Plane[] getPlanes() { return planes; } - + /** * Copy the given src planes into this this instance's planes. * @param src the 6 source planes */ - public final void updateByPlanes(Plane[] src) { + public final void updateByPlanes(Plane[] src) { for (int i = 0; i < 6; ++i) { final Plane p0 = planes[i]; final float[] p0_n = p0.n; @@ -176,7 +176,7 @@ public class Frustum { p0.d = p1.d; } } - + /** * Calculate the frustum planes in world coordinates * using the passed float[16] as premultiplied P*MV (column major order). @@ -185,7 +185,7 @@ public class Frustum { * as required by this class. *

            */ - public void updateByPMV(float[] pmv, int pmv_off) { + public void updateByPMV(float[] pmv, int pmv_off) { // Left: a = m41 + m11, b = m42 + m12, c = m43 + m13, d = m44 + m14 - [1..4] row-major // Left: a = m30 + m00, b = m31 + m01, c = m32 + m02, d = m33 + m03 - [0..3] row-major { @@ -264,11 +264,11 @@ public class Frustum { p.d /= invl; } } - + private static final boolean isOutsideImpl(Plane p, AABBox box) { final float[] low = box.getLow(); final float[] high = box.getHigh(); - + if ( p.distanceTo(low[0], low[1], low[2]) > 0.0f || p.distanceTo(high[0], low[1], low[2]) > 0.0f || p.distanceTo(low[0], high[1], low[2]) > 0.0f || @@ -298,19 +298,19 @@ public class Frustum { // We make no attempt to determine whether it's fully inside or not. return false; } - - + + public static enum Location { OUTSIDE, INSIDE, INTERSECT }; - + /** * Check to see if a point is outside, inside or on a plane of the frustum. - * + * * @param p the point * @return {@link Location} of point related to frustum planes */ public final Location classifyPoint(float[] p) { Location res = Location.INSIDE; - + for (int i = 0; i < 6; ++i) { final float d = planes[i].distanceTo(p); if ( d < 0.0f ) { @@ -321,43 +321,43 @@ public class Frustum { } return res; } - + /** * Check to see if a point is outside of the frustum. - * + * * @param p the point * @return true if outside of the frustum, otherwise inside or on a plane */ public final boolean isPointOutside(float[] p) { return Location.OUTSIDE == classifyPoint(p); } - + /** * Check to see if a sphere is outside, intersecting or inside of the frustum. - * + * * @param p center of the sphere * @param radius radius of the sphere * @return {@link Location} of point related to frustum planes */ public final Location classifySphere(float[] p, float radius) { Location res = Location.INSIDE; // fully inside - + for (int i = 0; i < 6; ++i) { final float d = planes[i].distanceTo(p); - if ( d < -radius ) { + if ( d < -radius ) { // fully outside return Location.OUTSIDE; } else if (d < radius ) { // intersecting res = Location.INTERSECT; } - } + } return res; } - + /** * Check to see if a sphere is outside of the frustum. - * + * * @param p center of the sphere * @param radius radius of the sphere * @return true if outside of the frustum, otherwise inside or intersecting @@ -365,7 +365,7 @@ public class Frustum { public final boolean isSphereOutside(float[] p, float radius) { return Location.OUTSIDE == classifySphere(p, radius); } - + public StringBuilder toString(StringBuilder sb) { if( null == sb ) { sb = new StringBuilder(); @@ -380,7 +380,7 @@ public class Frustum { .append("]"); return sb; } - + @Override public String toString() { return toString(null).toString(); diff --git a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java index ff764d849..33941a407 100644 --- a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java +++ b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java @@ -102,11 +102,11 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { /* GL Stuff */ private final RecursiveLock lock = LockFactory.createRecursiveLock(); private final GLDrawableHelper helper = new GLDrawableHelper(); - + private final GLContext shareWith; private final GLCapabilitiesImmutable capsRequested; - private final GLCapabilitiesChooser capsChooser; - + private final GLCapabilitiesChooser capsChooser; + private volatile Rectangle clientArea; private volatile GLDrawableImpl drawable; // volatile: avoid locking for read-only access private volatile GLContextImpl context; @@ -156,7 +156,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { public void run() { final RecursiveLock _lock = lock; _lock.lock(); - try { + try { if( !GLCanvas.this.isDisposed() ) { helper.invokeGL(drawable, context, displayAction, initAction); } @@ -215,7 +215,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { gle.printStackTrace(); } } - context = null; + context = null; } if ( null != drawable ) { drawable.setRealized(false); @@ -261,11 +261,11 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { } } }; - - /** - * Creates an instance using {@link #GLCanvas(Composite, int, GLCapabilitiesImmutable, GLCapabilitiesChooser, GLContext)} + + /** + * Creates an instance using {@link #GLCanvas(Composite, int, GLCapabilitiesImmutable, GLCapabilitiesChooser, GLContext)} * on the SWT thread. - * + * * @param parent * Required (non-null) parent Composite. * @param style @@ -284,7 +284,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { */ public static GLCanvas create(final Composite parent, final int style, final GLCapabilitiesImmutable caps, final GLCapabilitiesChooser chooser, final GLContext shareWith) { - final GLCanvas[] res = new GLCanvas[] { null }; + final GLCanvas[] res = new GLCanvas[] { null }; parent.getDisplay().syncExec(new Runnable() { public void run() { res[0] = new GLCanvas( parent, style, caps, chooser, shareWith ); @@ -319,22 +319,22 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { GLProfile.initSingleton(); // ensure JOGL is completly initialized SWTAccessor.setRealized(this, true); - + clientArea = GLCanvas.this.getClientArea(); - /* Get the nativewindow-Graphics Device associated with this control (which is determined by the parent Composite). + /* Get the nativewindow-Graphics Device associated with this control (which is determined by the parent Composite). * Note: SWT is owner of the native handle, hence closing operation will be a NOP. */ final AbstractGraphicsDevice swtDevice = SWTAccessor.getDevice(this); - + useX11GTK = SWTAccessor.useX11GTK(); if(useX11GTK) { - // Decoupled X11 Device/Screen allowing X11 display lock-free off-thread rendering + // Decoupled X11 Device/Screen allowing X11 display lock-free off-thread rendering final long x11DeviceHandle = X11Util.openDisplay(swtDevice.getConnection()); if( 0 == x11DeviceHandle ) { throw new RuntimeException("Error creating display(EDT): "+swtDevice.getConnection()); } final AbstractGraphicsDevice x11Device = new X11GraphicsDevice(x11DeviceHandle, AbstractGraphicsDevice.DEFAULT_UNIT, true /* owner */); - screen = SWTAccessor.getScreen(x11Device, -1 /* default */); + screen = SWTAccessor.getScreen(x11Device, -1 /* default */); } else { screen = SWTAccessor.getScreen(swtDevice, -1 /* default */); } @@ -343,7 +343,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { if(null == capsReqUser) { capsReqUser = new GLCapabilities(GLProfile.getDefault(screen.getDevice())); } - + this.capsRequested = capsReqUser; this.capsChooser = capsChooser; this.shareWith = shareWith; @@ -353,7 +353,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { x11Window = 0; drawable = null; context = null; - + final Listener listener = new Listener () { @Override public void handleEvent (Event event) { @@ -374,7 +374,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { addListener (SWT.Paint, listener); addListener (SWT.Dispose, listener); } - + private final UpstreamSurfaceHook swtCanvasUpStreamHook = new UpstreamSurfaceHook() { @Override public final void create(ProxySurface s) { /* nop */ } @@ -401,11 +401,11 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { protected final void updateSizeCheck() { final Rectangle oClientArea = clientArea; final Rectangle nClientArea = GLCanvas.this.getClientArea(); - if ( nClientArea != null && + if ( nClientArea != null && ( nClientArea.width != oClientArea.width || nClientArea.height != oClientArea.height ) ) { clientArea = nClientArea; // write back new value - + final GLDrawableImpl _drawable = drawable; final boolean drawableOK = null != _drawable && _drawable.isRealized(); if(DEBUG) { @@ -419,14 +419,14 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { try { final GLDrawableImpl _drawableNew = GLDrawableHelper.resizeOffscreenDrawable(_drawable, context, nClientArea.width, nClientArea.height); if(_drawable != _drawableNew) { - // write back + // write back drawable = _drawableNew; } } finally { _lock.unlock(); } - } - } + } + } if(0 != x11Window) { SWTAccessor.resizeX11Window(screen.getDevice(), clientArea, x11Window); } else if(0 != gdkWindow) { @@ -435,36 +435,36 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { sendReshape = true; // async if display() doesn't get called below, but avoiding deadlock } } - + private boolean isValidAndVisibleOnEDTActionResult; private final Runnable isValidAndVisibleOnEDTAction = new Runnable() { @Override - public void run() { + public void run() { isValidAndVisibleOnEDTActionResult = !GLCanvas.this.isDisposed() && GLCanvas.this.isVisible(); } }; - + private final boolean isValidAndVisibleOnEDT() { synchronized(isValidAndVisibleOnEDTAction) { runOnEDTIfAvail(true, isValidAndVisibleOnEDTAction); return isValidAndVisibleOnEDTActionResult; } } - + /** assumes drawable == null || !drawable.isRealized() ! Checks of !isDispose() and isVisible() */ protected final boolean validateDrawableAndContextWithCheck() { if( !isValidAndVisibleOnEDT() ) { return false; } - return validateDrawableAndContextPostCheck(); + return validateDrawableAndContextPostCheck(); } - + /** assumes drawable == null || !drawable.isRealized() ! No check of !isDispose() and isVisible() */ protected final boolean validateDrawableAndContextPostCheck() { final Rectangle nClientArea = clientArea; if(0 >= nClientArea.width || 0 >= nClientArea.height) { return false; } - + final boolean res; final RecursiveLock _lock = lock; _lock.lock(); @@ -480,18 +480,18 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { } } finally { _lock.unlock(); - } - + } + if(res) { sendReshape = true; if(DEBUG) { System.err.println("SWT GLCanvas realized! "+this+", "+drawable); // Thread.dumpStack(); - } + } } - return res; + return res; } - + private final void createDrawableAndContext() { final AbstractGraphicsDevice device = screen.getDevice(); device.open(); @@ -503,14 +503,14 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { capsRequested, capsRequested, capsChooser, screen, VisualIDHolder.VID_UNDEFINED); if(DEBUG) { System.err.println("SWT.GLCanvas.X11 factory: "+factory+", chosen config: "+cfg); - } + } if (null == cfg) { throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); } final int visualID = cfg.getVisualID(VIDType.NATIVE); if( VisualIDHolder.VID_UNDEFINED != visualID ) { // gdkWindow = SWTAccessor.createCompatibleGDKChildWindow(this, visualID, clientArea.width, clientArea.height); - // nativeWindowHandle = SWTAccessor.gdk_window_get_xwindow(gdkWindow); + // nativeWindowHandle = SWTAccessor.gdk_window_get_xwindow(gdkWindow); x11Window = SWTAccessor.createCompatibleX11ChildWindow(screen, this, visualID, clientArea.width, clientArea.height); nativeWindowHandle = x11Window; } else { @@ -520,16 +520,16 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { nativeWindowHandle = SWTAccessor.getWindowHandle(this); } final GLDrawableFactory glFactory = GLDrawableFactory.getFactory(capsRequested.getGLProfile()); - + // Create a NativeWindow proxy for the SWT canvas - ProxySurface proxySurface = glFactory.createProxySurface(device, screen.getIndex(), nativeWindowHandle, + ProxySurface proxySurface = glFactory.createProxySurface(device, screen.getIndex(), nativeWindowHandle, capsRequested, capsChooser, swtCanvasUpStreamHook); // Associate a GL surface with the proxy drawable = (GLDrawableImpl) glFactory.createGLDrawable(proxySurface); context = (GLContextImpl) drawable.createContext(shareWith); - context.setContextCreationFlags(additionalCtxCreationFlags); + context.setContextCreationFlags(additionalCtxCreationFlags); } - + @Override public void update() { // don't paint background etc .. nop avoids flickering @@ -543,13 +543,13 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { if(r && 0 != gdkWindow) { SWTGTKUtil.focusGDKWindow(gdkWindow); } - return r; + return r; } */ - + @Override public void dispose() { runInGLThread(disposeOnEDTGLAction); - super.dispose(); + super.dispose(); } private final void displayIfNoAnimatorNoCheck() { @@ -557,14 +557,14 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { final boolean drawableOK = null != drawable && drawable.isRealized(); if( drawableOK || validateDrawableAndContextPostCheck() ) { runInGLThread(makeCurrentAndDisplayOnGLAction); - } + } } } - + // // GL[Auto]Drawable // - + @Override public void display() { final boolean drawableOK = null != drawable && drawable.isRealized(); @@ -577,7 +577,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { public final Object getUpstreamWidget() { return this; } - + @Override public int getWidth() { return clientArea.width; @@ -593,7 +593,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { final GLDrawable _drawable = drawable; return null != _drawable ? _drawable.isGLOriented() : true; } - + @Override public void addGLEventListener(final GLEventListener listener) { helper.addGLEventListener(listener); @@ -608,29 +608,29 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { public int getGLEventListenerCount() { return helper.getGLEventListenerCount(); } - + @Override public GLEventListener getGLEventListener(int index) throws IndexOutOfBoundsException { return helper.getGLEventListener(index); } - + @Override public boolean getGLEventListenerInitState(GLEventListener listener) { return helper.getGLEventListenerInitState(listener); } - + @Override public void setGLEventListenerInitState(GLEventListener listener, boolean initialized) { helper.setGLEventListenerInitState(listener, initialized); } - + @Override public GLEventListener disposeGLEventListener(GLEventListener listener, boolean remove) { final DisposeGLEventListenerAction r = new DisposeGLEventListenerAction(listener, remove); runInGLThread(r); return r.listener; } - + @Override public GLEventListener removeGLEventListener(final GLEventListener listener) { return helper.removeGLEventListener(listener); @@ -673,7 +673,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { public final GLDrawable getDelegatedDrawable() { return drawable; } - + @Override public GLContext getContext() { return null != drawable ? context : null; @@ -694,12 +694,12 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { public boolean invoke(final boolean wait, final GLRunnable runnable) { return helper.invoke(this, wait, runnable); } - + @Override public boolean invoke(final boolean wait, final List runnables) { return helper.invoke(this, wait, runnables); } - + @Override public void setAnimator(final GLAnimatorControl arg0) throws GLException { helper.setAnimator(arg0); @@ -714,7 +714,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { public GLContext setContext(GLContext newCtx, boolean destroyPrevCtx) { final RecursiveLock _lock = lock; _lock.lock(); - try { + try { final GLContext oldCtx = context; GLDrawableHelper.switchContext(drawable, oldCtx, destroyPrevCtx, newCtx, additionalCtxCreationFlags); context=(GLContextImpl)newCtx; @@ -761,7 +761,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { @Override public GLCapabilitiesImmutable getChosenGLCapabilities() { - final GLDrawable _drawable = drawable; + final GLDrawable _drawable = drawable; return null != _drawable ? (GLCapabilitiesImmutable)_drawable.getChosenGLCapabilities() : null; } @@ -771,7 +771,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { * @return Non-null GLCapabilities. */ public GLCapabilitiesImmutable getRequestedGLCapabilities() { - final GLDrawable _drawable = drawable; + final GLDrawable _drawable = drawable; return null != _drawable ? (GLCapabilitiesImmutable)_drawable.getNativeSurface().getGraphicsConfiguration().getRequestedCapabilities() : null; } @@ -788,7 +788,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { @Override public long getHandle() { - final GLDrawable _drawable = drawable; + final GLDrawable _drawable = drawable; return (_drawable != null) ? _drawable.getHandle() : 0; } @@ -827,12 +827,12 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { *
              * *
            • Current thread
            • - *
            + *
          * - * The current thread seems to be valid for all platforms, + * The current thread seems to be valid for all platforms, * since no SWT lifecycle tasks are being performed w/ this call. * Only GL task, which are independent from the SWT threading model. - * + * * @see Platform#AWT_AVAILABLE * @see Platform#getOSType() */ @@ -854,8 +854,8 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { } */ action.run(); } - - private void runOnEDTIfAvail(boolean wait, final Runnable action) { + + private void runOnEDTIfAvail(boolean wait, final Runnable action) { final Display d = isDisposed() ? null : getDisplay(); if( null == d || d.isDisposed() || d.getThread() == Thread.currentThread() ) { action.run(); @@ -879,7 +879,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { ",\n\tDrawable size "+dw+"x"+dh+ ",\n\tSWT size "+getWidth()+"x"+getHeight()+"]"; } - + public static void main(final String[] args) { System.err.println(VersionUtil.getPlatformInfo()); System.err.println(GlueGenVersion.getInstance()); diff --git a/src/jogl/classes/com/jogamp/opengl/util/AWTAnimatorImpl.java b/src/jogl/classes/com/jogamp/opengl/util/AWTAnimatorImpl.java index 8de178e49..80289acf3 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/AWTAnimatorImpl.java +++ b/src/jogl/classes/com/jogamp/opengl/util/AWTAnimatorImpl.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 diff --git a/src/jogl/classes/com/jogamp/opengl/util/Animator.java b/src/jogl/classes/com/jogamp/opengl/util/Animator.java index 80d980492..cdfb73b21 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/Animator.java +++ b/src/jogl/classes/com/jogamp/opengl/util/Animator.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -57,7 +57,7 @@ import javax.media.opengl.GLException; * Call {@link #stop() } to terminate the animation and it's execution thread. *

          */ -public class Animator extends AnimatorBase { +public class Animator extends AnimatorBase { protected ThreadGroup threadGroup; private Runnable runnable; private boolean runAsFastAsPossible; @@ -75,7 +75,7 @@ public class Animator extends AnimatorBase { } } - /** + /** * Creates a new Animator w/ an associated ThreadGroup. */ public Animator(ThreadGroup tg) { @@ -86,7 +86,7 @@ public class Animator extends AnimatorBase { } } - /** + /** * Creates a new Animator for a particular drawable. */ public Animator(GLAutoDrawable drawable) { @@ -97,7 +97,7 @@ public class Animator extends AnimatorBase { } } - /** + /** * Creates a new Animator w/ an associated ThreadGroup for a particular drawable. */ public Animator(ThreadGroup tg, GLAutoDrawable drawable) { @@ -127,7 +127,7 @@ public class Animator extends AnimatorBase { stateSync.unlock(); } } - + private final void setIsAnimatingSynced(boolean v) { stateSync.lock(); try { @@ -185,7 +185,7 @@ public class Animator extends AnimatorBase { } if (!stopIssued && !isAnimating) { // Wakes up 'waitForStartedCondition' sync - // - and - + // - and - // Resume from pause or drawablesEmpty, // implies !pauseIssued and !drawablesEmpty setIsAnimatingSynced(true); // barrier @@ -251,7 +251,7 @@ public class Animator extends AnimatorBase { /** * Set a {@link ThreadGroup} for the {@link #getThread() animation thread}. - * + * * @param tg the {@link ThreadGroup} * @throws GLException if the animator has already been started */ @@ -261,7 +261,7 @@ public class Animator extends AnimatorBase { } threadGroup = tg; } - + public synchronized boolean start() { if ( isStartedImpl() ) { return false; @@ -277,7 +277,7 @@ public class Animator extends AnimatorBase { } else { thread = new Thread(threadGroup, runnable, threadName); } - thread.setDaemon(false); // force to be non daemon, regardless of parent thread + thread.setDaemon(false); // force to be non daemon, regardless of parent thread if(DEBUG) { final Thread ct = Thread.currentThread(); System.err.println("Animator "+ct.getName()+"[daemon "+ct.isDaemon()+"]: starting "+thread.getName()+"[daemon "+thread.isDaemon()+"]"); @@ -288,7 +288,7 @@ public class Animator extends AnimatorBase { private final Condition waitForStartedCondition = new Condition() { public boolean eval() { return !isStartedImpl() || (!drawablesEmpty && !isAnimating) ; - } }; + } }; public synchronized boolean stop() { if ( !isStartedImpl() ) { diff --git a/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java b/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java index ef92100ad..b447a339b 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java +++ b/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java @@ -52,14 +52,14 @@ import javax.media.opengl.GLProfile; */ public abstract class AnimatorBase implements GLAnimatorControl { protected static final boolean DEBUG = Debug.debug("Animator"); - + /** A 1s timeout while waiting for a native action response, limiting {@link #finishLifecycleAction(Condition, long)} */ protected static final long TO_WAIT_FOR_FINISH_LIFECYCLE_ACTION = 1000; - + protected static final long POLLP_WAIT_FOR_FINISH_LIFECYCLE_ACTION = 32; // 2 frames @ 60Hz - + /** - * If present in modeBits field and + * If present in modeBits field and * {@link GLProfile#isAWTAvailable() AWT is available}, * implementation is aware of the AWT EDT, otherwise not. *

          @@ -67,8 +67,8 @@ public abstract class AnimatorBase implements GLAnimatorControl { *

          * @see #setModeBits(boolean, int) */ - public static final int MODE_EXPECT_AWT_RENDERING_THREAD = 1 << 0; - + public static final int MODE_EXPECT_AWT_RENDERING_THREAD = 1 << 0; + public interface AnimatorImpl { void display(ArrayList drawables, boolean ignoreExceptions, boolean printExceptions); boolean blockUntilDone(Thread thread); @@ -77,7 +77,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { protected int modeBits; protected AnimatorImpl impl; protected String baseName; - + protected ArrayList drawables = new ArrayList(); protected boolean drawablesEmpty; protected Thread animThread; @@ -85,10 +85,10 @@ public abstract class AnimatorBase implements GLAnimatorControl { protected boolean printExceptions; protected boolean exclusiveContext; protected Thread userExclusiveContextThread; - protected FPSCounterImpl fpsCounter = new FPSCounterImpl(); + protected FPSCounterImpl fpsCounter = new FPSCounterImpl(); protected RecursiveLock stateSync = LockFactory.createRecursiveLock(); - - private final static Class awtAnimatorImplClazz; + + private final static Class awtAnimatorImplClazz; static { GLProfile.initSingleton(); if( GLProfile.isAWTAvailable() ) { @@ -96,7 +96,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { try { clazz = Class.forName("com.jogamp.opengl.util.AWTAnimatorImpl"); } catch (Exception e) { - clazz = null; + clazz = null; } awtAnimatorImplClazz = clazz; } else { @@ -105,29 +105,29 @@ public abstract class AnimatorBase implements GLAnimatorControl { } /** - * Creates a new, empty Animator instance + * Creates a new, empty Animator instance * while expecting an AWT rendering thread if AWT is available. - * + * * @see GLProfile#isAWTAvailable() */ public AnimatorBase() { - modeBits = MODE_EXPECT_AWT_RENDERING_THREAD; // default! + modeBits = MODE_EXPECT_AWT_RENDERING_THREAD; // default! drawablesEmpty = true; } - + private static final boolean useAWTAnimatorImpl(int modeBits) { return 0 != ( MODE_EXPECT_AWT_RENDERING_THREAD & modeBits ) && null != awtAnimatorImplClazz; } - + /** * Initializes implementation details post setup, * invoked at {@link #add(GLAutoDrawable)}, {@link #start()}, .. *

          - * Operation is a NOP if force is false + * Operation is a NOP if force is false * and this instance is already initialized. - *

          - * - * @throws GLException if Animator is {@link #isStarted()} + *

          + * + * @throws GLException if Animator is {@link #isStarted()} */ protected synchronized void initImpl(boolean force) { if( force || null == impl ) { @@ -153,8 +153,8 @@ public abstract class AnimatorBase implements GLAnimatorControl { * in this Animators modeBits. * @param enable * @param bitValues - * - * @throws GLException if Animator is {@link #isStarted()} and {@link #MODE_EXPECT_AWT_RENDERING_THREAD} about to change + * + * @throws GLException if Animator is {@link #isStarted()} and {@link #MODE_EXPECT_AWT_RENDERING_THREAD} about to change * @see AnimatorBase#MODE_EXPECT_AWT_RENDERING_THREAD */ public synchronized void setModeBits(boolean enable, int bitValues) throws GLException { @@ -172,8 +172,8 @@ public abstract class AnimatorBase implements GLAnimatorControl { } } public synchronized int getModeBits() { return modeBits; } - - + + @Override public synchronized void add(final GLAutoDrawable drawable) { if(DEBUG) { @@ -190,7 +190,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { drawables.add(drawable); drawablesEmpty = drawables.size() == 0; drawable.setAnimator(this); - if( isPaused() ) { // either paused by pause() above, or if previously drawablesEmpty==true + if( isPaused() ) { // either paused by pause() above, or if previously drawablesEmpty==true resume(); } final Condition waitForAnimatingAndECTCondition = new Condition() { @@ -213,7 +213,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { if( !drawables.contains(drawable) ) { throw new IllegalArgumentException("Drawable not added to animator: "+this+", "+drawable); } - + if( exclusiveContext && isAnimating() ) { drawable.setExclusiveContextThread( null ); final Condition waitForNullECTCondition = new Condition() { @@ -244,7 +244,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { return isStarted() && drawablesEmpty && isAnimating(); } }; - + /** * Dedicate all {@link GLAutoDrawable}'s context to the given exclusive context thread. *

          @@ -252,14 +252,14 @@ public abstract class AnimatorBase implements GLAnimatorControl { *

          *

          * If already started and disabling, method waits - * until change is propagated to all {@link GLAutoDrawable} if not + * until change is propagated to all {@link GLAutoDrawable} if not * called from the animator thread or {@link #getExclusiveContextThread() exclusive context thread}. *

          *

          * Note: Utilizing this feature w/ AWT could lead to an AWT-EDT deadlock, depending on the AWT implementation. * Hence it is advised not to use it with native AWT GLAutoDrawable like GLCanvas. *

          - * + * * @param enable * @return previous value * @see #setExclusiveContext(boolean) @@ -272,7 +272,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { final boolean enable = null != t; stateSync.lock(); try { - old = userExclusiveContextThread; + old = userExclusiveContextThread; if( enable && t != animThread ) { // disable: will be cleared at end after propagation && filter out own animThread usae userExclusiveContextThread=t; } @@ -282,7 +282,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { setExclusiveContext(enable); return old; } - + /** * Dedicate all {@link GLAutoDrawable}'s context to this animator thread. *

          @@ -290,14 +290,14 @@ public abstract class AnimatorBase implements GLAnimatorControl { *

          *

          * If already started and disabling, method waits - * until change is propagated to all {@link GLAutoDrawable} if not + * until change is propagated to all {@link GLAutoDrawable} if not * called from the animator thread or {@link #getExclusiveContextThread() exclusive context thread}. *

          *

          * Note: Utilizing this feature w/ AWT could lead to an AWT-EDT deadlock, depending on the AWT implementation. * Hence it is advised not to use it with native AWT GLAutoDrawable like GLCanvas. *

          - * + * * @param enable * @return previous value * @see #setExclusiveContext(Thread) @@ -349,24 +349,24 @@ public abstract class AnimatorBase implements GLAnimatorControl { System.err.println("AnimatorBase.setExclusiveContextThread: all-GLAD Ok: "+validateDrawablesExclCtxState(dECT)+", "+this); } return oldExclusiveContext; - } - + } + /** * Returns true, if the exclusive context thread is enabled, otherwise false. - * + * * @see #setExclusiveContext(boolean) * @see #setExclusiveContext(Thread) */ // @Override - public final boolean isExclusiveContextEnabled() { + public final boolean isExclusiveContextEnabled() { stateSync.lock(); try { - return exclusiveContext; + return exclusiveContext; } finally { stateSync.unlock(); } } - + /** * Returns the exclusive context thread if {@link #isExclusiveContextEnabled()} and {@link #isStarted()}, otherwise null. *

          @@ -381,7 +381,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { * @see #setExclusiveContext(Thread) */ // @Override - public final Thread getExclusiveContextThread() { + public final Thread getExclusiveContextThread() { stateSync.lock(); try { return ( isStartedImpl() && exclusiveContext ) ? ( null != userExclusiveContextThread ? userExclusiveContextThread : animThread ) : null ; @@ -389,7 +389,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { stateSync.unlock(); } } - + /** * Should be called at {@link #start()} and {@link #stop()} * from within the animator thread. @@ -407,7 +407,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { for (int i=0; ifalse. - * @param pollPeriod if 0, method will wait until TO is reached or being notified. + * @param pollPeriod if 0, method will wait until TO is reached or being notified. * if > 0, method will wait for the given pollPeriod in milliseconds. * @return true if {@link Condition#eval() waitCondition.eval()} returned false, otherwise false. */ @@ -545,11 +545,11 @@ public abstract class AnimatorBase implements GLAnimatorControl { if( remaining<=0 && nok ) { System.err.println("finishLifecycleAction(" + waitCondition.getClass().getName() + "): ++++++ timeout reached ++++++ " + getThreadName()); } - stateSync.lock(); // avoid too many lock/unlock ops + stateSync.lock(); // avoid too many lock/unlock ops try { System.err.println("finishLifecycleAction(" + waitCondition.getClass().getName() + "): OK "+(!nok)+ "- pollPeriod "+pollPeriod+", blocking "+blocking+ - ", waited " + (blocking ? ( TO_WAIT_FOR_FINISH_LIFECYCLE_ACTION - remaining ) : 0 ) + "/" + TO_WAIT_FOR_FINISH_LIFECYCLE_ACTION + + ", waited " + (blocking ? ( TO_WAIT_FOR_FINISH_LIFECYCLE_ACTION - remaining ) : 0 ) + "/" + TO_WAIT_FOR_FINISH_LIFECYCLE_ACTION + " - " + getThreadName()); System.err.println(" - "+toString()); } finally { diff --git a/src/jogl/classes/com/jogamp/opengl/util/DefaultAnimatorImpl.java b/src/jogl/classes/com/jogamp/opengl/util/DefaultAnimatorImpl.java index bbd2951b9..0477e1903 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/DefaultAnimatorImpl.java +++ b/src/jogl/classes/com/jogamp/opengl/util/DefaultAnimatorImpl.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 diff --git a/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java b/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java index 7613efec6..b48169c27 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java +++ b/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -45,10 +45,10 @@ import java.util.TimerTask; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLException; -/** +/** * An Animator subclass which attempts to achieve a target * frames-per-second rate to avoid using all CPU time. The target FPS - * is only an estimate and is not guaranteed. + * is only an estimate and is not guaranteed. *

          * The Animator execution thread does not run as a daemon thread, * so it is able to keep an application from terminating.
          @@ -105,45 +105,45 @@ public class FPSAnimator extends AnimatorBase { * @param fps * @throws GLException if the animator has already been started */ - public final synchronized void setFPS(int fps) throws GLException { + public final synchronized void setFPS(int fps) throws GLException { if ( isStartedImpl() ) { throw new GLException("Animator already started."); } - this.fps = fps; + this.fps = fps; } public final int getFPS() { return fps; } - + class MainTask extends TimerTask { private boolean justStarted; private boolean alreadyStopped; private boolean alreadyPaused; - + public MainTask() { } - + public void start(Timer timer) { fpsCounter.resetFPSCounter(); shouldRun = true; shouldStop = false; - + justStarted = true; alreadyStopped = false; alreadyPaused = false; - final long period = 0 < fps ? (long) (1000.0f / (float) fps) : 1; // 0 -> 1: IllegalArgumentException: Non-positive period + final long period = 0 < fps ? (long) (1000.0f / (float) fps) : 1; // 0 -> 1: IllegalArgumentException: Non-positive period if (scheduleAtFixedRate) { timer.scheduleAtFixedRate(this, 0, period); } else { timer.schedule(this, 0, period); } } - + public boolean isActive() { return !alreadyStopped && !alreadyPaused; } - + public String toString() { return "Task[thread "+animThread+", stopped "+alreadyStopped+", paused "+alreadyPaused+" shouldRun "+shouldRun+", shouldStop "+shouldStop+" -- started "+isStartedImpl()+", animating "+isAnimatingImpl()+", paused "+isPausedImpl()+", drawable "+drawables.size()+", drawablesEmpty "+drawablesEmpty+"]"; } - + public void run() { if( justStarted ) { justStarted = false; @@ -167,8 +167,8 @@ public class FPSAnimator extends AnimatorBase { display(); } else if( shouldStop ) { // STOP System.err.println("FPSAnimator P4: "+alreadyStopped+", "+ Thread.currentThread() + ": " + toString()); - this.cancel(); - + this.cancel(); + if( !alreadyStopped ) { alreadyStopped = true; if( exclusiveContext && !drawablesEmpty ) { @@ -184,23 +184,23 @@ public class FPSAnimator extends AnimatorBase { FPSAnimator.this.notifyAll(); } } - } else { + } else { System.err.println("FPSAnimator P5: "+alreadyPaused+", "+ Thread.currentThread() + ": " + toString()); this.cancel(); - + if( !alreadyPaused ) { // PAUSE alreadyPaused = true; if( exclusiveContext && !drawablesEmpty ) { setDrawablesExclCtxState(false); display(); // propagate exclusive change! } - synchronized (FPSAnimator.this) { + synchronized (FPSAnimator.this) { if(DEBUG) { System.err.println("FPSAnimator pause " + Thread.currentThread() + ": " + toString()); } isAnimating = false; FPSAnimator.this.notifyAll(); - } + } } } } @@ -230,7 +230,7 @@ public class FPSAnimator extends AnimatorBase { } static int timerNo = 0; - + public synchronized boolean start() { if ( null != timer || null != task || isStartedImpl() ) { return false; @@ -241,8 +241,8 @@ public class FPSAnimator extends AnimatorBase { System.err.println("FPSAnimator.start() START: "+task+", "+ Thread.currentThread() + ": " + toString()); } task.start(timer); - - final boolean res = finishLifecycleAction( drawablesEmpty ? waitForStartedEmptyCondition : waitForStartedAddedCondition, + + final boolean res = finishLifecycleAction( drawablesEmpty ? waitForStartedEmptyCondition : waitForStartedAddedCondition, POLLP_WAIT_FOR_FINISH_LIFECYCLE_ACTION); if(DEBUG) { System.err.println("FPSAnimator.start() END: "+task+", "+ Thread.currentThread() + ": " + toString()); @@ -256,11 +256,11 @@ public class FPSAnimator extends AnimatorBase { private final Condition waitForStartedAddedCondition = new Condition() { public boolean eval() { return !isStartedImpl() || !isAnimating ; - } }; + } }; private final Condition waitForStartedEmptyCondition = new Condition() { public boolean eval() { return !isStartedImpl() || isAnimating ; - } }; + } }; /** Stops this FPSAnimator. Due to the implementation of the FPSAnimator it is not guaranteed that the FPSAnimator will be @@ -268,7 +268,7 @@ public class FPSAnimator extends AnimatorBase { public synchronized boolean stop() { if ( null == timer || !isStartedImpl() ) { return false; - } + } if(DEBUG) { System.err.println("FPSAnimator.stop() START: "+task+", "+ Thread.currentThread() + ": " + toString()); } @@ -281,7 +281,7 @@ public class FPSAnimator extends AnimatorBase { shouldStop = true; res = finishLifecycleAction(waitForStoppedCondition, POLLP_WAIT_FOR_FINISH_LIFECYCLE_ACTION); } - + if(DEBUG) { System.err.println("FPSAnimator.stop() END: "+task+", "+ Thread.currentThread() + ": " + toString()); } @@ -316,7 +316,7 @@ public class FPSAnimator extends AnimatorBase { shouldRun = false; res = finishLifecycleAction(waitForPausedCondition, POLLP_WAIT_FOR_FINISH_LIFECYCLE_ACTION); } - + if(DEBUG) { System.err.println("FPSAnimator.pause() END: "+task+", "+ Thread.currentThread() + ": " + toString()); } diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java index e0bbbc33c..2d685a1a8 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java @@ -53,13 +53,13 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData * and starting with a new created Buffer object with initialElementCount size * * On profiles GL2 and ES1 the fixed function pipeline behavior is as expected. - * On profile ES2 the fixed function emulation will transform these calls to + * On profile ES2 the fixed function emulation will transform these calls to * EnableVertexAttribArray and VertexAttribPointer calls, * and a predefined vertex attribute variable name will be chosen. - * - * The default name mapping will be used, + * + * The default name mapping will be used, * see {@link GLPointerFuncUtil#getPredefinedArrayIndexName(int)}. - * + * * @param index The GL array index * @param comps The array component number * @param dataType The array index GL data type @@ -67,7 +67,7 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData * @param initialElementCount * * @see javax.media.opengl.GLContext#getPredefinedArrayIndexName(int) - */ + */ public static GLArrayDataClient createFixed(int index, int comps, int dataType, boolean normalized, int initialElementCount) throws GLException { @@ -82,13 +82,13 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData * and starting with a given Buffer object incl it's stride * * On profiles GL2 and ES1 the fixed function pipeline behavior is as expected. - * On profile ES2 the fixed function emulation will transform these calls to + * On profile ES2 the fixed function emulation will transform these calls to * EnableVertexAttribArray and VertexAttribPointer calls, * and a predefined vertex attribute variable name will be chosen. - * - * The default name mapping will be used, + * + * The default name mapping will be used, * see {@link GLPointerFuncUtil#getPredefinedArrayIndexName(int)}. - * + * * @param index The GL array index * @param comps The array component number * @param dataType The array index GL data type @@ -97,8 +97,8 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData * @param buffer the user define data * * @see javax.media.opengl.GLContext#getPredefinedArrayIndexName(int) - */ - public static GLArrayDataClient createFixed(int index, int comps, int dataType, boolean normalized, int stride, + */ + public static GLArrayDataClient createFixed(int index, int comps, int dataType, boolean normalized, int stride, Buffer buffer) throws GLException { @@ -111,13 +111,13 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData /** * Create a client side buffer object, using a custom GLSL array attribute name * and starting with a new created Buffer object with initialElementCount size - * @param name The custom name for the GL attribute. + * @param name The custom name for the GL attribute. * @param comps The array component number * @param dataType The array index GL data type * @param normalized Whether the data shall be normalized * @param initialElementCount */ - public static GLArrayDataClient createGLSL(String name, int comps, + public static GLArrayDataClient createGLSL(String name, int comps, int dataType, boolean normalized, int initialElementCount) throws GLException { @@ -130,7 +130,7 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData /** * Create a client side buffer object, using a custom GLSL array attribute name * and starting with a given Buffer object incl it's stride - * @param name The custom name for the GL attribute. + * @param name The custom name for the GL attribute. * @param comps The array component number * @param dataType The array index GL data type * @param normalized Whether the data shall be normalized @@ -157,8 +157,8 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData } } } - - // + + // // Data read access // @@ -167,7 +167,7 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData @Override public final boolean sealed() { return sealed; } - + @Override public final boolean enabled() { return bufferEnabled; } @@ -195,10 +195,10 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData seal(seal); enableBuffer(gl, seal); } - + @Override public void enableBuffer(GL gl, boolean enable) { - if( enableBufferAlways || bufferEnabled != enable ) { + if( enableBufferAlways || bufferEnabled != enable ) { if(enable) { checkSeal(true); // init/generate VBO name if not done yet @@ -208,7 +208,7 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData bufferEnabled = enable; } } - + @Override public boolean bindBuffer(GL gl, boolean bind) { if(bind) { @@ -218,7 +218,7 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData } return glArrayHandler.bindBuffer(gl, bind); } - + @Override public void setEnableAlways(boolean always) { enableBufferAlways = always; @@ -328,15 +328,15 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData ", isVertexAttribute "+isVertexAttribute+ ", usesGLSL "+usesGLSL+ ", usesShaderState "+(null!=shaderState)+ - ", dataType 0x"+Integer.toHexString(componentType)+ - ", bufferClazz "+componentClazz+ + ", dataType 0x"+Integer.toHexString(componentType)+ + ", bufferClazz "+componentClazz+ ", elements "+getElementCount()+ - ", components "+components+ + ", components "+components+ ", stride "+strideB+"b "+strideL+"c"+ - ", initialElementCount "+initialElementCount+ - ", sealed "+sealed+ - ", bufferEnabled "+bufferEnabled+ - ", bufferWritten "+bufferWritten+ + ", initialElementCount "+initialElementCount+ + ", sealed "+sealed+ + ", bufferEnabled "+bufferEnabled+ + ", bufferWritten "+bufferWritten+ ", buffer "+buffer+ ", alive "+alive+ "]"; @@ -345,16 +345,16 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData // non public matters protected final boolean growBufferIfNecessary(int spare) { - if(buffer==null || buffer.remaining()enable is true, + * Enables the buffer if enable is true, * and transfers the data if required. * In case {@link #isVBO() VBO is used}, it is bound accordingly for the data transfer and association, * i.e. it issued {@link #bindBuffer(GL, boolean)}. - * The VBO buffer is unbound when the method returns. + * The VBO buffer is unbound when the method returns. *

          - * Disables the buffer if enable is false. + * Disables the buffer if enable is false. *

          - * + * *

          The action will only be executed, - * if the internal enable state differs, + * if the internal enable state differs, * or 'setEnableAlways' was called with 'true'. - * + * *

          It is up to the user to enable/disable the array properly, * ie in case of multiple data sets for the same vertex attribute (VA). * Meaning in such case usage of one set while expecting another one @@ -68,7 +68,7 @@ public interface GLArrayDataEditable extends GLArrayData { public void enableBuffer(GL gl, boolean enable); /** - * if bind is true and the data uses {@link #isVBO() VBO}, + * if bind is true and the data uses {@link #isVBO() VBO}, * the latter will be bound and data written to the GPU if required. *

          * If bind is false and the data uses {@link #isVBO() VBO}, @@ -79,11 +79,11 @@ public interface GLArrayDataEditable extends GLArrayData { * to be bounded and written while keeping the VBO bound. The latter is in contrast to {@link #enableBuffer(GL, boolean)}, * which leaves the VBO unbound, since it's not required for vertex attributes or pointers. *

          - * + * * @param gl current GL object - * @param bind true if VBO shall be bound and data written, - * otherwise clear VBO binding. - * @return true if data uses VBO and action was performed, otherwise false + * @param bind true if VBO shall be bound and data written, + * otherwise clear VBO binding. + * @return true if data uses VBO and action was performed, otherwise false */ public boolean bindBuffer(GL gl, boolean bind); @@ -92,7 +92,7 @@ public interface GLArrayDataEditable extends GLArrayData { * * The default is 'false' * - * This is useful when you mix up + * This is useful when you mix up * GLArrayData usage with conventional GL array calls * or in case of a buggy GL VBO implementation. * @@ -117,7 +117,7 @@ public interface GLArrayDataEditable extends GLArrayData { * ie position:=limit and limit:=capacity.

          * * @see #seal(boolean) - */ + */ public void seal(boolean seal); public void rewind(); diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java index 7e7d27b36..80639c5c7 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java @@ -57,13 +57,13 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE * and starting with a given Buffer object incl it's stride * * On profiles GL2 and ES1 the fixed function pipeline behavior is as expected. - * On profile ES2 the fixed function emulation will transform these calls to + * On profile ES2 the fixed function emulation will transform these calls to * EnableVertexAttribArray and VertexAttribPointer calls, * and a predefined vertex attribute variable name will be chosen. - * - * The default name mapping will be used, + * + * The default name mapping will be used, * see {@link GLPointerFuncUtil#getPredefinedArrayIndexName(int)}. - * + * * @param index The GL array index * @param comps The array component number * @param dataType The array index GL data type @@ -90,13 +90,13 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE * and starting with a new created Buffer object with initialElementCount size * * On profiles GL2 and ES1 the fixed function pipeline behavior is as expected. - * On profile ES2 the fixed function emulation will transform these calls to + * On profile ES2 the fixed function emulation will transform these calls to * EnableVertexAttribArray and VertexAttribPointer calls, * and a predefined vertex attribute variable name will be chosen. - * - * The default name mapping will be used, + * + * The default name mapping will be used, * see {@link GLPointerFuncUtil#getPredefinedArrayIndexName(int)}. - * + * * @param index The GL array index * @param comps The array component number * @param dataType The array index GL data type @@ -106,7 +106,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE * * @see javax.media.opengl.GLContext#getPredefinedArrayIndexName(int) */ - public static GLArrayDataServer createFixed(int index, int comps, int dataType, boolean normalized, int initialElementCount, + public static GLArrayDataServer createFixed(int index, int comps, int dataType, boolean normalized, int initialElementCount, int vboUsage) throws GLException { @@ -120,7 +120,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE /** * Create a VBO, using a custom GLSL array attribute name * and starting with a new created Buffer object with initialElementCount size - * @param name The custom name for the GL attribute + * @param name The custom name for the GL attribute * @param comps The array component number * @param dataType The array index GL data type * @param normalized Whether the data shall be normalized @@ -128,20 +128,20 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW} */ public static GLArrayDataServer createGLSL(String name, int comps, - int dataType, boolean normalized, int initialElementCount, int vboUsage) - throws GLException + int dataType, boolean normalized, int initialElementCount, int vboUsage) + throws GLException { GLArrayDataServer ads = new GLArrayDataServer(); GLArrayHandler glArrayHandler = new GLSLArrayHandler(ads); ads.init(name, -1, comps, dataType, normalized, 0, null, initialElementCount, true, glArrayHandler, 0, 0, vboUsage, GL.GL_ARRAY_BUFFER, true); return ads; - } - + } + /** * Create a VBO, using a custom GLSL array attribute name * and starting with a given Buffer object incl it's stride - * @param name The custom name for the GL attribute + * @param name The custom name for the GL attribute * @param comps The array component number * @param dataType The array index GL data type * @param normalized Whether the data shall be normalized @@ -151,7 +151,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE */ public static GLArrayDataServer createGLSL(String name, int comps, int dataType, boolean normalized, int stride, Buffer buffer, - int vboUsage) + int vboUsage) throws GLException { GLArrayDataServer ads = new GLArrayDataServer(); @@ -160,12 +160,12 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE 0, 0, vboUsage, GL.GL_ARRAY_BUFFER, true); return ads; } - + /** * Create a VBO data object for any target w/o render pipeline association, ie {@link GL#GL_ELEMENT_ARRAY_BUFFER}. - * + * * Hence no index, name for a fixed function pipeline nor vertex attribute is given. - * + * * @param comps The array component number * @param dataType The array index GL data type * @param stride @@ -187,16 +187,16 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE /** * Create a VBO data object for any target w/o render pipeline association, ie {@link GL#GL_ELEMENT_ARRAY_BUFFER}. - * + * * Hence no index, name for a fixed function pipeline nor vertex attribute is given. - * + * * @param comps The array component number * @param dataType The array index GL data type * @param initialElementCount * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW} * @param vboTarget {@link GL#GL_ELEMENT_ARRAY_BUFFER}, .. */ - public static GLArrayDataServer createData(int comps, int dataType, int initialElementCount, + public static GLArrayDataServer createData(int comps, int dataType, int initialElementCount, int vboUsage, int vboTarget) throws GLException { @@ -207,19 +207,19 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE return ads; } - + /** * Create a VBO for fixed function interleaved array data * starting with a new created Buffer object with initialElementCount size. *

          User needs to configure the interleaved segments via {@link #addFixedSubArray(int, int, int)}.

          - * + * * @param comps The total number of all interleaved components. * @param dataType The array index GL data type * @param normalized Whether the data shall be normalized - * @param initialElementCount + * @param initialElementCount * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW} */ - public static GLArrayDataServer createFixedInterleaved(int comps, int dataType, boolean normalized, int initialElementCount, + public static GLArrayDataServer createFixedInterleaved(int comps, int dataType, boolean normalized, int initialElementCount, int vboUsage) throws GLException { @@ -239,7 +239,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE * The memory of the the interleaved array is being used.

          *

          * Must be called before using the array, eg: {@link #seal(boolean)}, {@link #putf(float)}, ..

          - * + * * @param index The GL array index, maybe -1 if vboTarget is {@link GL#GL_ELEMENT_ARRAY_BUFFER} * @param comps This interleaved array segment's component number * @param vboTarget {@link GL#GL_ARRAY_BUFFER} or {@link GL#GL_ELEMENT_ARRAY_BUFFER} @@ -250,32 +250,32 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE throw new GLException("Interleaved offset > total components ("+iOffC+" > "+getComponentCount()+")"); } if(usesGLSL) { - throw new GLException("buffer uses GLSL"); + throw new GLException("buffer uses GLSL"); } final GLArrayDataWrapper ad = GLArrayDataWrapper.createFixed( - index, comps, getComponentType(), - getNormalized(), getStride(), getBuffer(), + index, comps, getComponentType(), + getNormalized(), getStride(), getBuffer(), getVBOName(), interleavedOffset, getVBOUsage(), vboTarget); ad.setVBOEnabled(isVBO()); interleavedOffset += comps * getComponentSizeInBytes(); - if(GL.GL_ARRAY_BUFFER == vboTarget) { + if(GL.GL_ARRAY_BUFFER == vboTarget) { glArrayHandler.addSubHandler(new GLFixedArrayHandlerFlat(ad)); } return ad; } - + /** * Create a VBO for GLSL interleaved array data * starting with a new created Buffer object with initialElementCount size. *

          User needs to configure the interleaved segments via {@link #addGLSLSubArray(int, int, int)}.

          - * + * * @param comps The total number of all interleaved components. * @param dataType The array index GL data type * @param normalized Whether the data shall be normalized - * @param initialElementCount + * @param initialElementCount * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW} */ - public static GLArrayDataServer createGLSLInterleaved(int comps, int dataType, boolean normalized, int initialElementCount, + public static GLArrayDataServer createGLSLInterleaved(int comps, int dataType, boolean normalized, int initialElementCount, int vboUsage) throws GLException { @@ -285,7 +285,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE 0, 0, vboUsage, GL.GL_ARRAY_BUFFER, true); return ads; } - + /** * Configure a segment of this GLSL interleaved array (see {@link #createGLSLInterleaved(int, int, boolean, int, int)}). *

          @@ -305,20 +305,20 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE throw new GLException("Interleaved offset > total components ("+iOffC+" > "+getComponentCount()+")"); } if(!usesGLSL) { - throw new GLException("buffer uses fixed function"); + throw new GLException("buffer uses fixed function"); } final GLArrayDataWrapper ad = GLArrayDataWrapper.createGLSL( - name, comps, getComponentType(), - getNormalized(), getStride(), getBuffer(), - getVBOName(), interleavedOffset, getVBOUsage(), vboTarget); + name, comps, getComponentType(), + getNormalized(), getStride(), getBuffer(), + getVBOName(), interleavedOffset, getVBOUsage(), vboTarget); ad.setVBOEnabled(isVBO()); interleavedOffset += comps * getComponentSizeInBytes(); - if(GL.GL_ARRAY_BUFFER == vboTarget) { + if(GL.GL_ARRAY_BUFFER == vboTarget) { glArrayHandler.addSubHandler(new GLSLArrayHandlerFlat(ad)); } return ad; } - + // // Data matters GLArrayData // @@ -341,15 +341,15 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE } // - // data matters + // data matters // /** - * Convenient way do disable the VBO behavior and + * Convenient way do disable the VBO behavior and * switch to client side data one * Only possible if buffer is defined. */ - public void setVBOEnabled(boolean vboUsage) { + public void setVBOEnabled(boolean vboUsage) { checkSeal(false); super.setVBOEnabled(vboUsage); } @@ -361,22 +361,22 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE ", isVertexAttribute "+isVertexAttribute+ ", usesGLSL "+usesGLSL+ ", usesShaderState "+(null!=shaderState)+ - ", dataType 0x"+Integer.toHexString(componentType)+ - ", bufferClazz "+componentClazz+ + ", dataType 0x"+Integer.toHexString(componentType)+ + ", bufferClazz "+componentClazz+ ", elements "+getElementCount()+ - ", components "+components+ + ", components "+components+ ", stride "+strideB+"b "+strideL+"c"+ ", initialElementCount "+initialElementCount+ - ", vboEnabled "+vboEnabled+ - ", vboName "+vboName+ - ", vboUsage 0x"+Integer.toHexString(vboUsage)+ - ", vboTarget 0x"+Integer.toHexString(vboTarget)+ - ", vboOffset "+vboOffset+ - ", sealed "+sealed+ - ", bufferEnabled "+bufferEnabled+ - ", bufferWritten "+bufferWritten+ - ", buffer "+buffer+ - ", alive "+alive+ + ", vboEnabled "+vboEnabled+ + ", vboName "+vboName+ + ", vboUsage 0x"+Integer.toHexString(vboUsage)+ + ", vboTarget 0x"+Integer.toHexString(vboTarget)+ + ", vboOffset "+vboOffset+ + ", sealed "+sealed+ + ", bufferEnabled "+bufferEnabled+ + ", bufferWritten "+bufferWritten+ + ", buffer "+buffer+ + ", alive "+alive+ "]"; } @@ -384,7 +384,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE // non public matters .. // - protected void init(String name, int index, int comps, int dataType, boolean normalized, + protected void init(String name, int index, int comps, int dataType, boolean normalized, int stride, Buffer data, int initialElementCount, boolean isVertexAttribute, GLArrayHandler glArrayHandler, int vboName, long vboOffset, int vboUsage, int vboTarget, boolean usesGLSL) @@ -407,7 +407,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE } } } - - private int interleavedOffset = 0; + + private int interleavedOffset = 0; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java index f8b17501e..290f47a6d 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java @@ -49,7 +49,7 @@ public class GLArrayDataWrapper implements GLArrayData { /** * Create a VBO, using a predefined fixed function array index, wrapping the given data. - * + * * @param index The GL array index * @param comps The array component number * @param dataType The array index GL data type @@ -61,23 +61,23 @@ public class GLArrayDataWrapper implements GLArrayData { * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW} * @param vboTarget {@link GL#GL_ARRAY_BUFFER} or {@link GL#GL_ELEMENT_ARRAY_BUFFER} * @return the new create instance - * + * * @throws GLException */ - public static GLArrayDataWrapper createFixed(int index, int comps, int dataType, boolean normalized, int stride, + public static GLArrayDataWrapper createFixed(int index, int comps, int dataType, boolean normalized, int stride, Buffer buffer, int vboName, long vboOffset, int vboUsage, int vboTarget) throws GLException { GLArrayDataWrapper adc = new GLArrayDataWrapper(); - adc.init(null, index, comps, dataType, normalized, stride, buffer, false, + adc.init(null, index, comps, dataType, normalized, stride, buffer, false, vboName, vboOffset, vboUsage, vboTarget); return adc; } /** * Create a VBO, using a custom GLSL array attribute name, wrapping the given data. - * - * @param name The custom name for the GL attribute, maybe null if gpuBufferTarget is {@link GL#GL_ELEMENT_ARRAY_BUFFER} + * + * @param name The custom name for the GL attribute, maybe null if gpuBufferTarget is {@link GL#GL_ELEMENT_ARRAY_BUFFER} * @param comps The array component number * @param dataType The array index GL data type * @param normalized Whether the data shall be normalized @@ -90,7 +90,7 @@ public class GLArrayDataWrapper implements GLArrayData { * @return the new create instance * @throws GLException */ - public static GLArrayDataWrapper createGLSL(String name, int comps, int dataType, boolean normalized, int stride, + public static GLArrayDataWrapper createGLSL(String name, int comps, int dataType, boolean normalized, int stride, Buffer buffer, int vboName, long vboOffset, int vboUsage, int vboTarget) throws GLException { @@ -102,8 +102,8 @@ public class GLArrayDataWrapper implements GLArrayData { /** * Validates this instance's parameter. Called automatically by {@link GLArrayDataClient} and {@link GLArrayDataServer}. - * {@link GLArrayDataWrapper} does not validate it's instance by itself. - * + * {@link GLArrayDataWrapper} does not validate it's instance by itself. + * * @param glp the GLProfile to use * @param throwException whether to throw an exception if this instance has invalid parameter or not * @return true if this instance has invalid parameter, otherwise false @@ -113,7 +113,7 @@ public class GLArrayDataWrapper implements GLArrayData { if(throwException) { throw new GLException("Instance !alive "+this); } - return false; + return false; } if(this.isVertexAttribute() && !glp.hasGLSL()) { if(throwException) { @@ -123,13 +123,13 @@ public class GLArrayDataWrapper implements GLArrayData { } return glp.isValidArrayDataType(getIndex(), getComponentCount(), getComponentType(), isVertexAttribute(), throwException); } - + @Override public void associate(Object obj, boolean enable) { // nop } - - // + + // // Data read access // @@ -150,14 +150,14 @@ public class GLArrayDataWrapper implements GLArrayData { location = gl.glGetAttribLocation(program, name); return location; } - + @Override public final int setLocation(GL2ES2 gl, int program, int location) { this.location = location; gl.glBindAttribLocation(program, location, name); return location; } - + @Override public final String getName() { return name; } @@ -172,10 +172,10 @@ public class GLArrayDataWrapper implements GLArrayData { @Override public final int getVBOUsage() { return vboEnabled?vboUsage:0; } - + @Override public final int getVBOTarget() { return vboEnabled?vboTarget:0; } - + @Override public final Buffer getBuffer() { return buffer; } @@ -187,19 +187,19 @@ public class GLArrayDataWrapper implements GLArrayData { @Override public final int getComponentSizeInBytes() { return componentByteSize; } - + @Override public final int getElementCount() { if(null==buffer) return 0; return ( buffer.position()==0 ) ? ( buffer.limit() / components ) : ( buffer.position() / components ) ; } - + @Override public final int getSizeInBytes() { if(null==buffer) return 0; - return ( buffer.position()==0 ) ? ( buffer.limit() * componentByteSize ) : ( buffer.position() * componentByteSize ) ; + return ( buffer.position()==0 ) ? ( buffer.limit() * componentByteSize ) : ( buffer.position() * componentByteSize ) ; } - + @Override public final boolean getNormalized() { return normalized; } @@ -223,18 +223,18 @@ public class GLArrayDataWrapper implements GLArrayData { ", index "+index+ ", location "+location+ ", isVertexAttribute "+isVertexAttribute+ - ", dataType 0x"+Integer.toHexString(componentType)+ - ", bufferClazz "+componentClazz+ + ", dataType 0x"+Integer.toHexString(componentType)+ + ", bufferClazz "+componentClazz+ ", elements "+getElementCount()+ - ", components "+components+ + ", components "+components+ ", stride "+strideB+"b "+strideL+"c"+ - ", buffer "+buffer+ - ", vboEnabled "+vboEnabled+ - ", vboName "+vboName+ - ", vboUsage 0x"+Integer.toHexString(vboUsage)+ - ", vboTarget 0x"+Integer.toHexString(vboTarget)+ - ", vboOffset "+vboOffset+ - ", alive "+alive+ + ", buffer "+buffer+ + ", vboEnabled "+vboEnabled+ + ", vboName "+vboName+ + ", vboUsage 0x"+Integer.toHexString(vboUsage)+ + ", vboTarget 0x"+Integer.toHexString(vboTarget)+ + ", vboOffset "+vboOffset+ + ", alive "+alive+ "]"; } @@ -252,12 +252,12 @@ public class GLArrayDataWrapper implements GLArrayData { return IntBuffer.class; case GL.GL_FLOAT: return FloatBuffer.class; - default: + default: throw new GLException("Given OpenGL data type not supported: "+dataType); } } - @Override + @Override public void setName(String newName) { location = -1; name = newName; @@ -267,7 +267,7 @@ public class GLArrayDataWrapper implements GLArrayData { * Enable or disable use of VBO. * Only possible if a VBO buffer name is defined. * @see #setVBOName(int) - */ + */ public void setVBOEnabled(boolean vboEnabled) { this.vboEnabled=vboEnabled; } @@ -275,31 +275,31 @@ public class GLArrayDataWrapper implements GLArrayData { /** * Set the VBO buffer name, if valid (!= 0) enable use of VBO, * otherwise (==0) disable VBO usage. - * + * * @see #setVBOEnabled(boolean) - */ + */ public void setVBOName(int vboName) { this.vboName=vboName; setVBOEnabled(0!=vboName); } - /** + /** * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW} - */ - public void setVBOUsage(int vboUsage) { - this.vboUsage = vboUsage; + */ + public void setVBOUsage(int vboUsage) { + this.vboUsage = vboUsage; } - - /** + + /** * @param vboTarget either {@link GL#GL_ARRAY_BUFFER} or {@link GL#GL_ELEMENT_ARRAY_BUFFER} - */ + */ public void setVBOTarget(int vboTarget) { this.vboTarget = vboTarget; - } + } - protected void init(String name, int index, int components, int componentType, - boolean normalized, int stride, Buffer data, - boolean isVertexAttribute, + protected void init(String name, int index, int components, int componentType, + boolean normalized, int stride, Buffer data, + boolean isVertexAttribute, int vboName, long vboOffset, int vboUsage, int vboTarget) throws GLException { @@ -307,19 +307,19 @@ public class GLArrayDataWrapper implements GLArrayData { this.index = index; this.location = -1; // We can't have any dependence on the FixedFuncUtil class here for build bootstrapping reasons - + if( GL.GL_ELEMENT_ARRAY_BUFFER == vboTarget ) { // OK .. } else if( ( 0 == vboUsage && 0 == vboTarget ) || GL.GL_ARRAY_BUFFER == vboTarget ) { - // Set/Check name .. - Required for GLSL case. Validation and debug-name for FFP. + // Set/Check name .. - Required for GLSL case. Validation and debug-name for FFP. this.name = ( null == name ) ? GLPointerFuncUtil.getPredefinedArrayIndexName(index) : name ; if(null == this.name ) { throw new GLException("Not a valid array buffer index: "+index); - } + } } else if( 0 < vboTarget ) { throw new GLException("Invalid GPUBuffer target: 0x"+Integer.toHexString(vboTarget)); } - + this.componentType = componentType; componentClazz = getBufferClass(componentType); if( GLBuffers.isGLTypeFixedPoint(componentType) ) { @@ -329,7 +329,7 @@ public class GLArrayDataWrapper implements GLArrayData { } componentByteSize = GLBuffers.sizeOfGLType(componentType); if(0 > componentByteSize) { - throw new GLException("Given componentType not supported: "+componentType+":\n\t"+this); + throw new GLException("Given componentType not supported: "+componentType+":\n\t"+this); } if(0 >= components) { throw new GLException("Invalid number of components: " + components); @@ -348,7 +348,7 @@ public class GLArrayDataWrapper implements GLArrayData { this.vboName= vboName; this.vboEnabled= 0 != vboName ; this.vboOffset=vboOffset; - + switch(vboUsage) { case 0: // nop case GL.GL_STATIC_DRAW: @@ -356,7 +356,7 @@ public class GLArrayDataWrapper implements GLArrayData { case GL2ES2.GL_STREAM_DRAW: break; default: - throw new GLException("invalid gpuBufferUsage: "+vboUsage+":\n\t"+this); + throw new GLException("invalid gpuBufferUsage: "+vboUsage+":\n\t"+this); } switch(vboTarget) { case 0: // nop @@ -367,7 +367,7 @@ public class GLArrayDataWrapper implements GLArrayData { throw new GLException("invalid gpuBufferTarget: "+vboTarget+":\n\t"+this); } this.vboUsage=vboUsage; - this.vboTarget=vboTarget; + this.vboTarget=vboTarget; this.alive=true; } @@ -390,6 +390,6 @@ public class GLArrayDataWrapper implements GLArrayData { protected int vboName; protected boolean vboEnabled; protected int vboUsage; - protected int vboTarget; + protected int vboTarget; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java b/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java index 6bdea4518..418d7fa81 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 @@ -28,11 +28,11 @@ * 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. */ @@ -52,7 +52,7 @@ import com.jogamp.common.nio.Buffers; /** * Utility routines for dealing with direct buffers. - * + * * @author Kenneth Russel, et.al. */ public class GLBuffers extends Buffers { @@ -72,11 +72,11 @@ public class GLBuffers extends Buffers { case GL.GL_UNSIGNED_INT: case GL2.GL_HILO16_NV: return false; - + } return true; } - + /** * @param glType GL primitive type * @return false if one of GL primitive floating point types, otherwise true @@ -92,19 +92,19 @@ public class GLBuffers extends Buffers { case GLES2.GL_HALF_FLOAT_OES: case GL2GL3.GL_DOUBLE: return false; - + default: return true; - } + } } - + /** * @param glType shall be one of (31)
          * GL_BYTE, GL_UNSIGNED_BYTE,
          * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV,
          *
          * GL_SHORT, GL_UNSIGNED_SHORT,
          - * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
          + * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
          * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV,
          * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV,
          * GL_UNSIGNED_SHORT_8_8_APPLE, GL_UNSIGNED_SHORT_8_8_REV_APPLE,
          @@ -112,16 +112,16 @@ public class GLBuffers extends Buffers { *
          * GL_FIXED, GL_INT
          * GL_UNSIGNED_INT, GL_UNSIGNED_INT_8_8_8_8,
          - * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
          + * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
          * GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_24_8,
          - * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
          + * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
          * GL_HILO16_NV, GL_SIGNED_HILO16_NV
          *
          * GL2GL3.GL_FLOAT_32_UNSIGNED_INT_24_8_REV
          *
          - * GL_FLOAT, GL_DOUBLE
          - * - * @return -1 if glType is unhandled, otherwise the actual value > 0 + * GL_FLOAT, GL_DOUBLE
          + * + * @return -1 if glType is unhandled, otherwise the actual value > 0 */ public static final int sizeOfGLType(int glType) { switch (glType) { // 29 @@ -131,7 +131,7 @@ public class GLBuffers extends Buffers { case GL2GL3.GL_UNSIGNED_BYTE_3_3_2: case GL2GL3.GL_UNSIGNED_BYTE_2_3_3_REV: return SIZEOF_BYTE; - + case GL.GL_SHORT: case GL.GL_UNSIGNED_SHORT: case GL.GL_UNSIGNED_SHORT_5_6_5: @@ -145,40 +145,40 @@ public class GLBuffers extends Buffers { case GL.GL_HALF_FLOAT: case GLES2.GL_HALF_FLOAT_OES: return SIZEOF_SHORT; - + case GL.GL_FIXED: case GL2ES2.GL_INT: case GL.GL_UNSIGNED_INT: case GL2GL3.GL_UNSIGNED_INT_8_8_8_8: case GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV: case GL2GL3.GL_UNSIGNED_INT_10_10_10_2: - case GL2GL3.GL_UNSIGNED_INT_2_10_10_10_REV: + case GL2GL3.GL_UNSIGNED_INT_2_10_10_10_REV: case GL2GL3.GL_UNSIGNED_INT_24_8: case GL2GL3.GL_UNSIGNED_INT_10F_11F_11F_REV: case GL2GL3.GL_UNSIGNED_INT_5_9_9_9_REV: case GL2.GL_HILO16_NV: case GL2.GL_SIGNED_HILO16_NV: return SIZEOF_INT; - + case GL2GL3.GL_FLOAT_32_UNSIGNED_INT_24_8_REV: return SIZEOF_LONG; - + case GL.GL_FLOAT: return SIZEOF_FLOAT; - + case GL2GL3.GL_DOUBLE: return SIZEOF_DOUBLE; } return -1; } - + /** * @param glType shall be one of (31)
          * GL_BYTE, GL_UNSIGNED_BYTE,
          * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV,
          *
          * GL_SHORT, GL_UNSIGNED_SHORT,
          - * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
          + * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
          * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV,
          * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV,
          * GL_UNSIGNED_SHORT_8_8_APPLE, GL_UNSIGNED_SHORT_8_8_REV_APPLE,
          @@ -186,16 +186,16 @@ public class GLBuffers extends Buffers { *
          * GL_FIXED, GL_INT
          * GL_UNSIGNED_INT, GL_UNSIGNED_INT_8_8_8_8,
          - * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
          + * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
          * GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_24_8,
          - * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
          + * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
          * GL_HILO16_NV, GL_SIGNED_HILO16_NV
          *
          * GL_FLOAT_32_UNSIGNED_INT_24_8_REV
          *
          - * GL_FLOAT, GL_DOUBLE
          - * - * @return null if glType is unhandled, otherwise the new Buffer object + * GL_FLOAT, GL_DOUBLE
          + * + * @return null if glType is unhandled, otherwise the new Buffer object */ public static final Buffer newDirectGLBuffer(int glType, int numElements) { switch (glType) { // 29 @@ -204,7 +204,7 @@ public class GLBuffers extends Buffers { case GL2GL3.GL_UNSIGNED_BYTE_3_3_2: case GL2GL3.GL_UNSIGNED_BYTE_2_3_3_REV: return newDirectByteBuffer(numElements); - + case GL.GL_SHORT: case GL.GL_UNSIGNED_SHORT: case GL.GL_UNSIGNED_SHORT_5_6_5: @@ -218,7 +218,7 @@ public class GLBuffers extends Buffers { case GL.GL_HALF_FLOAT: case GLES2.GL_HALF_FLOAT_OES: return newDirectShortBuffer(numElements); - + case GL.GL_FIXED: case GL2ES2.GL_INT: case GL.GL_UNSIGNED_INT: @@ -232,13 +232,13 @@ public class GLBuffers extends Buffers { case GL2.GL_HILO16_NV: case GL2.GL_SIGNED_HILO16_NV: return newDirectIntBuffer(numElements); - + case GL2GL3.GL_FLOAT_32_UNSIGNED_INT_24_8_REV: return newDirectLongBuffer(numElements); - + case GL.GL_FLOAT: return newDirectFloatBuffer(numElements); - + case GL2.GL_DOUBLE: return newDirectDoubleBuffer(numElements); } @@ -251,7 +251,7 @@ public class GLBuffers extends Buffers { * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV,
          *
          * GL_SHORT, GL_UNSIGNED_SHORT,
          - * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
          + * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
          * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV,
          * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV,
          * GL_UNSIGNED_SHORT_8_8_APPLE, GL_UNSIGNED_SHORT_8_8_REV_APPLE,
          @@ -259,15 +259,15 @@ public class GLBuffers extends Buffers { *
          * GL_FIXED, GL_INT
          * GL_UNSIGNED_INT, GL_UNSIGNED_INT_8_8_8_8,
          - * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
          + * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
          * GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_24_8,
          - * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
          + * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
          * GL_HILO16_NV, GL_SIGNED_HILO16_NV
          *
          * GL_FLOAT_32_UNSIGNED_INT_24_8_REV
          *
          - * GL_FLOAT, GL_DOUBLE
          - * @return null if glType is unhandled or parent is null or bufLen is 0, otherwise the new Buffer object + * GL_FLOAT, GL_DOUBLE
          + * @return null if glType is unhandled or parent is null or bufLen is 0, otherwise the new Buffer object */ public static final Buffer sliceGLBuffer(ByteBuffer parent, int bytePos, int byteLen, int glType) { if (parent == null || byteLen == 0) { @@ -275,11 +275,11 @@ public class GLBuffers extends Buffers { } final int parentPos = parent.position(); final int parentLimit = parent.limit(); - + parent.position(bytePos); parent.limit(bytePos + byteLen); Buffer res = null; - + switch (glType) { // 29 case GL.GL_BYTE: case GL.GL_UNSIGNED_BYTE: @@ -287,7 +287,7 @@ public class GLBuffers extends Buffers { case GL2GL3.GL_UNSIGNED_BYTE_2_3_3_REV: res = parent.slice().order(parent.order()); // slice and duplicate may change byte order break; - + case GL.GL_SHORT: case GL.GL_UNSIGNED_SHORT: case GL.GL_UNSIGNED_SHORT_5_6_5: @@ -302,7 +302,7 @@ public class GLBuffers extends Buffers { case GLES2.GL_HALF_FLOAT_OES: res = parent.slice().order(parent.order()).asShortBuffer(); // slice and duplicate may change byte order break; - + case GL.GL_FIXED: case GL2GL3.GL_INT: case GL2ES2.GL_UNSIGNED_INT: @@ -317,15 +317,15 @@ public class GLBuffers extends Buffers { case GL2.GL_SIGNED_HILO16_NV: res = parent.slice().order(parent.order()).asIntBuffer(); // slice and duplicate may change byte order break; - + case GL2GL3.GL_FLOAT_32_UNSIGNED_INT_24_8_REV: res = parent.slice().order(parent.order()).asLongBuffer(); // slice and duplicate may change byte order break; - + case GL.GL_FLOAT: res = parent.slice().order(parent.order()).asFloatBuffer(); // slice and duplicate may change byte order break; - + case GL2.GL_DOUBLE: res = parent.slice().order(parent.order()).asDoubleBuffer(); // slice and duplicate may change byte order break; @@ -338,29 +338,29 @@ public class GLBuffers extends Buffers { gl.glGetIntegerv(pname, tmp, 0); return tmp[0]; } - - /** + + /** * Returns the number of bytes required to read/write a memory buffer via OpenGL * using the current GL pixel storage state and the given parameters. - * + * *

          This method is security critical, hence it throws an exception (fail-fast) - * in case of an invalid alignment. In case we forgot to handle - * proper values, please contact the maintainer.

          - * + * in case of an invalid alignment. In case we forgot to handle + * proper values, please contact the maintainer.

          + * * @param gl the current GL object - * + * * @param tmp a pass through integer array of size >= 1 used to store temp data (performance) - * + * * @param bytesPerPixel bytes per pixel, i.e. via {@link #bytesPerPixel(int, int)}. * @param width in pixels * @param height in pixels * @param depth in pixels - * @param pack true for read mode GPU -> CPU (pack), otherwise false for write mode CPU -> GPU (unpack) + * @param pack true for read mode GPU -> CPU (pack), otherwise false for write mode CPU -> GPU (unpack) * @return required minimum size of the buffer in bytes * @throws GLException if alignment is invalid. Please contact the maintainer if this is our bug. */ - public static final int sizeof(GL gl, int tmp[], - int bytesPerPixel, int width, int height, int depth, + public static final int sizeof(GL gl, int tmp[], + int bytesPerPixel, int width, int height, int depth, boolean pack) { int rowLength = 0; int skipRows = 0; @@ -368,31 +368,31 @@ public class GLBuffers extends Buffers { int alignment = 1; int imageHeight = 0; int skipImages = 0; - - if (pack) { + + if (pack) { alignment = glGetInteger(gl, GL.GL_PACK_ALIGNMENT, tmp); if(gl.isGL2GL3()) { rowLength = glGetInteger(gl, GL2GL3.GL_PACK_ROW_LENGTH, tmp); - skipRows = glGetInteger(gl, GL2GL3.GL_PACK_SKIP_ROWS, tmp); + skipRows = glGetInteger(gl, GL2GL3.GL_PACK_SKIP_ROWS, tmp); skipPixels = glGetInteger(gl, GL2GL3.GL_PACK_SKIP_PIXELS, tmp); - if (depth > 1) { - imageHeight = glGetInteger(gl, GL2GL3.GL_PACK_IMAGE_HEIGHT, tmp); + if (depth > 1) { + imageHeight = glGetInteger(gl, GL2GL3.GL_PACK_IMAGE_HEIGHT, tmp); skipImages = glGetInteger(gl, GL2GL3.GL_PACK_SKIP_IMAGES, tmp); } } - } else { + } else { alignment = glGetInteger(gl, GL.GL_UNPACK_ALIGNMENT, tmp); - if(gl.isGL2GL3 ()) { - rowLength = glGetInteger(gl, GL2GL3.GL_UNPACK_ROW_LENGTH, tmp); - skipRows = glGetInteger(gl, GL2GL3.GL_UNPACK_SKIP_ROWS, tmp); + if(gl.isGL2GL3 ()) { + rowLength = glGetInteger(gl, GL2GL3.GL_UNPACK_ROW_LENGTH, tmp); + skipRows = glGetInteger(gl, GL2GL3.GL_UNPACK_SKIP_ROWS, tmp); skipPixels = glGetInteger(gl, GL2GL3.GL_UNPACK_SKIP_PIXELS, tmp); - if (depth > 1) { - imageHeight = glGetInteger(gl, GL2GL3.GL_UNPACK_IMAGE_HEIGHT, tmp); + if (depth > 1) { + imageHeight = glGetInteger(gl, GL2GL3.GL_UNPACK_IMAGE_HEIGHT, tmp); skipImages = glGetInteger(gl, GL2GL3.GL_UNPACK_SKIP_IMAGES, tmp); } } } - + // Try to deal somewhat correctly with potentially invalid values width = Math.max(0, width ); height = Math.max(1, height); // min 1D @@ -401,13 +401,13 @@ public class GLBuffers extends Buffers { skipPixels = Math.max(0, skipPixels); alignment = Math.max(1, alignment); skipImages = Math.max(0, skipImages); - + imageHeight = ( imageHeight > 0 ) ? imageHeight : height; rowLength = ( rowLength > 0 ) ? rowLength : width; - + int rowLengthInBytes = rowLength * bytesPerPixel; int skipBytes = skipPixels * bytesPerPixel; - + switch(alignment) { case 1: break; @@ -423,71 +423,71 @@ public class GLBuffers extends Buffers { if (remainder > 0) { skipBytes += alignment - remainder; } - } + } break; default: - throw new GLException("Invalid alignment "+alignment+", must be 2**n (1,2,4,8). Pls notify the maintainer in case this is our bug."); + throw new GLException("Invalid alignment "+alignment+", must be 2**n (1,2,4,8). Pls notify the maintainer in case this is our bug."); } - + /** * skipImages, depth, skipPixels and skipRows are static offsets. * * skipImages and depth are in multiples of image size. * * skipBytes and rowLengthInBytes are aligned - * - * rowLengthInBytes is the aligned byte offset + * + * rowLengthInBytes is the aligned byte offset * from line n to line n+1 at the same x-axis position. */ return skipBytes + // aligned skipPixels * bpp - ( skipImages + depth - 1 ) * imageHeight * rowLengthInBytes + // aligned whole images + ( skipImages + depth - 1 ) * imageHeight * rowLengthInBytes + // aligned whole images ( skipRows + height - 1 ) * rowLengthInBytes + // aligned lines - width * bytesPerPixel; // last line + width * bytesPerPixel; // last line } - - /** + + /** * Returns the number of bytes required to read/write a memory buffer via OpenGL * using the current GL pixel storage state and the given parameters. - * + * *

          This method is security critical, hence it throws an exception (fail-fast) - * in case either the format, type or alignment is unhandled. In case we forgot to handle - * proper values, please contact the maintainer.

          - * + * in case either the format, type or alignment is unhandled. In case we forgot to handle + * proper values, please contact the maintainer.

          + * *

          See {@link #bytesPerPixel(int, int)}.

          - * + * * @param gl the current GL object - * + * * @param tmp a pass through integer array of size >= 1 used to store temp data (performance) - * - * @param format must be one of (27)
          - * GL_COLOR_INDEX GL_STENCIL_INDEX
          - * GL_DEPTH_COMPONENT GL_DEPTH_STENCIL
          - * GL_RED GL_RED_INTEGER
          - * GL_GREEN GL_GREEN_INTEGER
          - * GL_BLUE GL_BLUE_INTEGER
          - * GL_ALPHA GL_LUMINANCE (12)
          - *
          + * + * @param format must be one of (27)
          + * GL_COLOR_INDEX GL_STENCIL_INDEX
          + * GL_DEPTH_COMPONENT GL_DEPTH_STENCIL
          + * GL_RED GL_RED_INTEGER
          + * GL_GREEN GL_GREEN_INTEGER
          + * GL_BLUE GL_BLUE_INTEGER
          + * GL_ALPHA GL_LUMINANCE (12)
          + *
          * GL_LUMINANCE_ALPHA GL_RG
          - * GL_RG_INTEGER GL_HILO_NV
          - * GL_SIGNED_HILO_NV (5)
          - *
          - * GL_YCBCR_422_APPLE
          - *
          - * GL_RGB GL_RGB_INTEGER
          - * GL_BGR GL_BGR_INTEGER (4)
          - *
          - * GL_RGBA GL_RGBA_INTEGER
          + * GL_RG_INTEGER GL_HILO_NV
          + * GL_SIGNED_HILO_NV (5)
          + *
          + * GL_YCBCR_422_APPLE
          + *
          + * GL_RGB GL_RGB_INTEGER
          + * GL_BGR GL_BGR_INTEGER (4)
          + *
          + * GL_RGBA GL_RGBA_INTEGER
          * GL_BGRA GL_BGRA_INTEGER
          - * GL_ABGR_EXT (5)
          - * - * @param type must be one of (32)
          - * GL_BITMAP,
          + * GL_ABGR_EXT (5)
          + * + * @param type must be one of (32)
          + * GL_BITMAP,
          * GL_BYTE, GL_UNSIGNED_BYTE,
          * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV,
          *
          * GL_SHORT, GL_UNSIGNED_SHORT,
          - * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
          + * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
          * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV,
          * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV,
          * GL_UNSIGNED_SHORT_8_8_APPLE, GL_UNSIGNED_SHORT_8_8_REV_APPLE,
          @@ -495,70 +495,70 @@ public class GLBuffers extends Buffers { *
          * GL_FIXED, GL_INT
          * GL_UNSIGNED_INT, GL_UNSIGNED_INT_8_8_8_8,
          - * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
          + * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
          * GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_24_8,
          - * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
          + * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
          * GL_HILO16_NV, GL_SIGNED_HILO16_NV
          *
          * GL_FLOAT_32_UNSIGNED_INT_24_8_REV
          *
          - * GL_FLOAT, GL_DOUBLE
          - * + * GL_FLOAT, GL_DOUBLE
          + * * @param width in pixels * @param height in pixels * @param depth in pixels - * @param pack true for read mode GPU -> CPU, otherwise false for write mode CPU -> GPU + * @param pack true for read mode GPU -> CPU, otherwise false for write mode CPU -> GPU * @return required minimum size of the buffer in bytes * @throws GLException if format, type or alignment is not handled. Please contact the maintainer if this is our bug. */ - public static final int sizeof(GL gl, int tmp[], + public static final int sizeof(GL gl, int tmp[], int format, int type, int width, int height, int depth, boolean pack) throws GLException { if (width < 0) return 0; if (height < 0) return 0; if (depth < 0) return 0; - + final int bytesPerPixel = bytesPerPixel(format, type); return sizeof(gl, tmp, bytesPerPixel, width, height, depth, pack); } - - /** + + /** * Returns the number of bytes required for one pixel with the the given OpenGL format and type. - * + * *

          This method is security critical, hence it throws an exception (fail-fast) - * in case either the format, type or alignment is unhandled. In case we forgot to handle - * proper values, please contact the maintainer.

          - * + * in case either the format, type or alignment is unhandled. In case we forgot to handle + * proper values, please contact the maintainer.

          + * *

          See {@link #componentCount(int)}.

          - * - * @param format must be one of (27)
          - * GL_COLOR_INDEX GL_STENCIL_INDEX
          - * GL_DEPTH_COMPONENT GL_DEPTH_STENCIL
          - * GL_RED GL_RED_INTEGER
          - * GL_GREEN GL_GREEN_INTEGER
          - * GL_BLUE GL_BLUE_INTEGER
          - * GL_ALPHA GL_LUMINANCE (12)
          - *
          + * + * @param format must be one of (27)
          + * GL_COLOR_INDEX GL_STENCIL_INDEX
          + * GL_DEPTH_COMPONENT GL_DEPTH_STENCIL
          + * GL_RED GL_RED_INTEGER
          + * GL_GREEN GL_GREEN_INTEGER
          + * GL_BLUE GL_BLUE_INTEGER
          + * GL_ALPHA GL_LUMINANCE (12)
          + *
          * GL_LUMINANCE_ALPHA GL_RG
          - * GL_RG_INTEGER GL_HILO_NV
          - * GL_SIGNED_HILO_NV (5)
          - *
          - * GL_YCBCR_422_APPLE
          - *
          - * GL_RGB GL_RGB_INTEGER
          - * GL_BGR GL_BGR_INTEGER (4)
          - *
          - * GL_RGBA GL_RGBA_INTEGER
          + * GL_RG_INTEGER GL_HILO_NV
          + * GL_SIGNED_HILO_NV (5)
          + *
          + * GL_YCBCR_422_APPLE
          + *
          + * GL_RGB GL_RGB_INTEGER
          + * GL_BGR GL_BGR_INTEGER (4)
          + *
          + * GL_RGBA GL_RGBA_INTEGER
          * GL_BGRA GL_BGRA_INTEGER
          - * GL_ABGR_EXT (5)
          - * - * @param type must be one of (32)
          - * GL_BITMAP,
          + * GL_ABGR_EXT (5)
          + * + * @param type must be one of (32)
          + * GL_BITMAP,
          * GL_BYTE, GL_UNSIGNED_BYTE,
          * GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV,
          *
          * GL_SHORT, GL_UNSIGNED_SHORT,
          - * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
          + * GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV,
          * GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV,
          * GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV,
          * GL_UNSIGNED_SHORT_8_8_APPLE, GL_UNSIGNED_SHORT_8_8_REV_APPLE,
          @@ -566,15 +566,15 @@ public class GLBuffers extends Buffers { *
          * GL_FIXED, GL_INT
          * GL_UNSIGNED_INT, GL_UNSIGNED_INT_8_8_8_8,
          - * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
          + * GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2,
          * GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_24_8,
          - * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
          + * GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV
          * GL_HILO16_NV, GL_SIGNED_HILO16_NV
          *
          * GL_FLOAT_32_UNSIGNED_INT_24_8_REV
          *
          - * GL_FLOAT, GL_DOUBLE
          - * + * GL_FLOAT, GL_DOUBLE
          + * * @return required size of one pixel in bytes * @throws GLException if format or type alignment is not handled. Please contact the maintainer if this is our bug. */ @@ -582,14 +582,14 @@ public class GLBuffers extends Buffers { int compSize = 0; int compCount = componentCount(format); - + switch (type) /* 30 */ { case GL2.GL_BITMAP: if (GL2.GL_COLOR_INDEX == format || GL2GL3.GL_STENCIL_INDEX == format) { compSize = 1; } case GL.GL_BYTE: - case GL.GL_UNSIGNED_BYTE: + case GL.GL_UNSIGNED_BYTE: compSize = 1; break; case GL.GL_SHORT: @@ -607,7 +607,7 @@ public class GLBuffers extends Buffers { case GL2GL3.GL_DOUBLE: compSize = 8; break; - + case GL2GL3.GL_UNSIGNED_BYTE_3_3_2: case GL2GL3.GL_UNSIGNED_BYTE_2_3_3_REV: compSize = 1; @@ -630,7 +630,7 @@ public class GLBuffers extends Buffers { case GL2.GL_SIGNED_HILO16_NV: compSize = 2; compCount = 2; - break; + break; case GL2GL3.GL_UNSIGNED_INT_8_8_8_8: case GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV: case GL2GL3.GL_UNSIGNED_INT_10_10_10_2: @@ -640,52 +640,52 @@ public class GLBuffers extends Buffers { case GL2GL3.GL_UNSIGNED_INT_5_9_9_9_REV: compSize = 4; compCount = 1; - break; + break; case GL2GL3.GL_FLOAT_32_UNSIGNED_INT_24_8_REV: compSize = 8; compCount = 1; - break; - + break; + default: throw new GLException("type 0x"+Integer.toHexString(type)+"/"+"format 0x"+Integer.toHexString(format)+" not supported [yet], pls notify the maintainer in case this is our bug."); - } + } return compCount * compSize; } - - /** + + /** * Returns the number of components required for the given OpenGL format. - * + * *

          This method is security critical, hence it throws an exception (fail-fast) - * in case either the format, type or alignment is unhandled. In case we forgot to handle - * proper values, please contact the maintainer.

          - * - * @param format must be one of (27)
          - * GL_COLOR_INDEX GL_STENCIL_INDEX
          - * GL_DEPTH_COMPONENT GL_DEPTH_STENCIL
          - * GL_RED GL_RED_INTEGER
          - * GL_GREEN GL_GREEN_INTEGER
          - * GL_BLUE GL_BLUE_INTEGER
          - * GL_ALPHA GL_LUMINANCE (12)
          - *
          + * in case either the format, type or alignment is unhandled. In case we forgot to handle + * proper values, please contact the maintainer.

          + * + * @param format must be one of (27)
          + * GL_COLOR_INDEX GL_STENCIL_INDEX
          + * GL_DEPTH_COMPONENT GL_DEPTH_STENCIL
          + * GL_RED GL_RED_INTEGER
          + * GL_GREEN GL_GREEN_INTEGER
          + * GL_BLUE GL_BLUE_INTEGER
          + * GL_ALPHA GL_LUMINANCE (12)
          + *
          * GL_LUMINANCE_ALPHA GL_RG
          - * GL_RG_INTEGER GL_HILO_NV
          - * GL_SIGNED_HILO_NV (5)
          - *
          - * GL_YCBCR_422_APPLE
          - *
          - * GL_RGB GL_RGB_INTEGER
          - * GL_BGR GL_BGR_INTEGER (4)
          - *
          - * GL_RGBA GL_RGBA_INTEGER
          + * GL_RG_INTEGER GL_HILO_NV
          + * GL_SIGNED_HILO_NV (5)
          + *
          + * GL_YCBCR_422_APPLE
          + *
          + * GL_RGB GL_RGB_INTEGER
          + * GL_BGR GL_BGR_INTEGER (4)
          + *
          + * GL_RGBA GL_RGBA_INTEGER
          * GL_BGRA GL_BGRA_INTEGER
          - * GL_ABGR_EXT (5)
          - * + * GL_ABGR_EXT (5)
          + * * @return number of components required for the given OpenGL format * @throws GLException if format is not handled. Please contact the maintainer if this is our bug. */ public static final int componentCount(int format) throws GLException { final int compCount; - + switch (format) /* 26 */ { case GL2.GL_COLOR_INDEX: case GL2GL3.GL_STENCIL_INDEX: @@ -711,10 +711,10 @@ public class GLBuffers extends Buffers { case GL.GL_RGB: case GL2GL3.GL_RGB_INTEGER: case GL2GL3.GL_BGR: - case GL2GL3.GL_BGR_INTEGER: + case GL2GL3.GL_BGR_INTEGER: compCount = 3; break; - case GL2.GL_YCBCR_422_APPLE: + case GL2.GL_YCBCR_422_APPLE: compCount = 3; break; case GL.GL_RGBA: @@ -724,16 +724,16 @@ public class GLBuffers extends Buffers { case GL2.GL_ABGR_EXT: compCount = 4; break; - /* FIXME ?? + /* FIXME ?? case GL.GL_HILO_NV: elements = 2; - break; */ + break; */ default: throw new GLException("format 0x"+Integer.toHexString(format)+" not supported [yet], pls notify the maintainer in case this is our bug."); } return compCount; } - + public static final int getNextPowerOf2(int number) { if (((number-1) & number) == 0) { //ex: 8 -> 0b1000; 8-1=7 -> 0b0111; 0b1000&0b0111 == 0 @@ -745,8 +745,8 @@ public class GLBuffers extends Buffers { power++; } return (1<src to dest. * If preserveInitState is true, it's initialized state is preserved @@ -86,7 +86,7 @@ public class GLDrawableUtil { dest.invoke(false, new GLEventListenerState.ReshapeGLEventListener(listener)); } // else .. !init state is default } - + /** * Moves all {@link GLEventListener} from {@link GLAutoDrawable} src to dest. * If preserveInitState is true, it's initialized state is preserved @@ -113,12 +113,12 @@ public class GLDrawableUtil { /** * Swaps the {@link GLContext} and all {@link GLEventListener} between {@link GLAutoDrawable} a and b, * while preserving it's initialized state, resets the GL-Viewport and issuing {@link GLEventListener#reshape(GLAutoDrawable, int, int, int, int) reshape(..)}. - *

          - * The {@link GLAutoDrawable} to {@link GLAnimatorControl} association - * is also swapped. + *

          + * The {@link GLAutoDrawable} to {@link GLAnimatorControl} association + * is also swapped. *

          *

          - * If an {@link GLAnimatorControl} is being attached to {@link GLAutoDrawable} a or b + * If an {@link GLAnimatorControl} is being attached to {@link GLAutoDrawable} a or b * and the current thread is different than {@link GLAnimatorControl#getThread() the animator's thread}, it is paused during the operation. *

          * @param a @@ -128,31 +128,31 @@ public class GLDrawableUtil { public static final void swapGLContextAndAllGLEventListener(GLAutoDrawable a, GLAutoDrawable b) { final GLEventListenerState gllsA = GLEventListenerState.moveFrom(a); final GLEventListenerState gllsB = GLEventListenerState.moveFrom(b); - + gllsA.moveTo(b); gllsB.moveTo(a); } - - /** - * Swaps the {@link GLContext} of given {@link GLAutoDrawable} - * and {@link GLAutoDrawable#disposeGLEventListener(GLEventListener, boolean) disposes} + + /** + * Swaps the {@link GLContext} of given {@link GLAutoDrawable} + * and {@link GLAutoDrawable#disposeGLEventListener(GLEventListener, boolean) disposes} * each {@link GLEventListener} w/o removing it. *

          * The GL-Viewport is reset and {@link GLEventListener#reshape(GLAutoDrawable, int, int, int, int) reshape(..)} issued implicit. - *

          + *

          *

          - * If an {@link GLAnimatorControl} is being attached to GLAutoDrawable src or dest and the current thread is different + * If an {@link GLAnimatorControl} is being attached to GLAutoDrawable src or dest and the current thread is different * than {@link GLAnimatorControl#getThread() the animator's thread}, it is paused during the operation. *

          * @param src * @param dest */ - public static final void swapGLContext(GLAutoDrawable src, GLAutoDrawable dest) { + public static final void swapGLContext(GLAutoDrawable src, GLAutoDrawable dest) { final GLAnimatorControl aAnim = src.getAnimator(); - final GLAnimatorControl bAnim = dest.getAnimator(); + final GLAnimatorControl bAnim = dest.getAnimator(); final boolean aIsPaused = isAnimatorAnimatingOnOtherThread(aAnim) && aAnim.pause(); final boolean bIsPaused = isAnimatorAnimatingOnOtherThread(bAnim) && bAnim.pause(); - + for(int i = src.getGLEventListenerCount() - 1; 0 <= i; i--) { src.disposeGLEventListener(src.getGLEventListener(i), false); } @@ -160,12 +160,12 @@ public class GLDrawableUtil { dest.disposeGLEventListener(dest.getGLEventListener(i), false); } dest.setContext( src.setContext( dest.getContext(), false ), false ); - + src.invoke(true, GLEventListenerState.setViewport); dest.invoke(true, GLEventListenerState.setViewport); - + if(aIsPaused) { aAnim.resume(); } if(bIsPaused) { bAnim.resume(); } } - + } diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java b/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java index 71e284101..f0c6be44f 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -39,78 +39,78 @@ import javax.media.opengl.GLException; import com.jogamp.common.nio.Buffers; import com.jogamp.opengl.util.texture.TextureData; -/** +/** * OpenGL pixel data buffer, allowing user to provide buffers via their {@link GLPixelBufferProvider} implementation. *

          * {@link GLPixelBufferProvider} produces a {@link GLPixelBuffer}. - *

          + *

          *

          * You may use {@link #defaultProviderNoRowStride}. *

          */ public class GLPixelBuffer { - - /** Allows user to interface with another toolkit to define {@link GLPixelAttributes} and memory buffer to produce {@link TextureData}. */ + + /** Allows user to interface with another toolkit to define {@link GLPixelAttributes} and memory buffer to produce {@link TextureData}. */ public static interface GLPixelBufferProvider { /** Allow {@link GL2ES3#GL_PACK_ROW_LENGTH}, or {@link GL2ES2#GL_UNPACK_ROW_LENGTH}. */ boolean getAllowRowStride(); - + /** Called first to determine {@link GLPixelAttributes}. */ GLPixelAttributes getAttributes(GL gl, int componentCount); - - /** + + /** * Allocates a new {@link GLPixelBuffer} object. *

          * Being called to gather the initial {@link GLPixelBuffer}, * or a new replacement {@link GLPixelBuffer} if {@link GLPixelBuffer#requiresNewBuffer(GL, int, int, int)}. *

          *

          - * The minimum required {@link Buffer#remaining() remaining} byte size equals to minByteSize, if > 0, + * The minimum required {@link Buffer#remaining() remaining} byte size equals to minByteSize, if > 0, * otherwise utilize {@link GLBuffers#sizeof(GL, int[], int, int, int, int, int, boolean)} * to calculate it. *

          - * + * * @param gl the corresponding current GL context object * @param pixelAttributes the desired {@link GLPixelAttributes} * @param width in pixels * @param height in pixels * @param depth in pixels * @param pack true for read mode GPU -> CPU, otherwise false for write mode CPU -> GPU - * @param minByteSize if > 0, the pre-calculated minimum byte-size for the resulting buffer, otherwise ignore. + * @param minByteSize if > 0, the pre-calculated minimum byte-size for the resulting buffer, otherwise ignore. */ GLPixelBuffer allocate(GL gl, GLPixelAttributes pixelAttributes, int width, int height, int depth, boolean pack, int minByteSize); } - /** Single {@link GLPixelBuffer} provider. */ + /** Single {@link GLPixelBuffer} provider. */ public static interface SingletonGLPixelBufferProvider extends GLPixelBufferProvider { - /** Return the last {@link #allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocated} {@link GLPixelBuffer} w/ {@link GLPixelAttributes#componentCount}. */ + /** Return the last {@link #allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocated} {@link GLPixelBuffer} w/ {@link GLPixelAttributes#componentCount}. */ GLPixelBuffer getSingleBuffer(GLPixelAttributes pixelAttributes); - /** + /** * Initializes the single {@link GLPixelBuffer} w/ a given size, if not yet {@link #allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocated}. * @return the newly initialized single {@link GLPixelBuffer}, or null if already allocated. */ - GLPixelBuffer initSingleton(int componentCount, int width, int height, int depth, boolean pack); + GLPixelBuffer initSingleton(int componentCount, int width, int height, int depth, boolean pack); } public static class DefaultGLPixelBufferProvider implements GLPixelBufferProvider { private final boolean allowRowStride; - + /** - * @param allowRowStride If true, allow row-stride, otherwise not. + * @param allowRowStride If true, allow row-stride, otherwise not. * See {@link #getAllowRowStride()} and {@link GLPixelBuffer#requiresNewBuffer(GL, int, int, int)}. */ public DefaultGLPixelBufferProvider(boolean allowRowStride) { - this.allowRowStride = allowRowStride; + this.allowRowStride = allowRowStride; } - + @Override public boolean getAllowRowStride() { return allowRowStride; } - + @Override public GLPixelAttributes getAttributes(GL gl, int componentCount) { final GLContext ctx = gl.getContext(); final int dFormat, dType; - + if( 1 == componentCount ) { if( gl.isGL3ES3() ) { // RED is supported on ES3 and >= GL3 [core]; ALPHA is deprecated on core @@ -122,7 +122,7 @@ public class GLPixelBuffer { dType = GL.GL_UNSIGNED_BYTE; } else if( 3 == componentCount ) { dFormat = GL.GL_RGB; - dType = GL.GL_UNSIGNED_BYTE; + dType = GL.GL_UNSIGNED_BYTE; } else if( 4 == componentCount ) { int _dFormat = ctx.getDefaultPixelDataFormat(); final int dComps = GLBuffers.componentCount(_dFormat); @@ -131,14 +131,14 @@ public class GLPixelBuffer { dType = ctx.getDefaultPixelDataType(); } else { dFormat = GL.GL_RGBA; - dType = GL.GL_UNSIGNED_BYTE; + dType = GL.GL_UNSIGNED_BYTE; } } else { throw new GLException("Unsupported componentCount "+componentCount+", contact maintainer to enhance"); } return new GLPixelAttributes(componentCount, dFormat, dType); } - + /** * {@inheritDoc} *

          @@ -148,7 +148,7 @@ public class GLPixelBuffer { @Override public GLPixelBuffer allocate(GL gl, GLPixelAttributes pixelAttributes, int width, int height, int depth, boolean pack, int minByteSize) { if( minByteSize > 0 ) { - return new GLPixelBuffer(pixelAttributes, width, height, depth, pack, Buffers.newDirectByteBuffer(minByteSize), getAllowRowStride()); + return new GLPixelBuffer(pixelAttributes, width, height, depth, pack, Buffers.newDirectByteBuffer(minByteSize), getAllowRowStride()); } else { int[] tmp = { 0 }; final int byteSize = GLBuffers.sizeof(gl, tmp, pixelAttributes.bytesPerPixel, width, height, depth, pack); @@ -156,26 +156,26 @@ public class GLPixelBuffer { } } } - - /** + + /** * Default {@link GLPixelBufferProvider} with {@link GLPixelBufferProvider#getAllowRowStride()} == false, * utilizing best match for {@link GLPixelAttributes} * and {@link GLPixelBufferProvider#allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocating} a {@link ByteBuffer}. */ public static GLPixelBufferProvider defaultProviderNoRowStride = new DefaultGLPixelBufferProvider(false); - - /** + + /** * Default {@link GLPixelBufferProvider} with {@link GLPixelBufferProvider#getAllowRowStride()} == true, * utilizing best match for {@link GLPixelAttributes} * and {@link GLPixelBufferProvider#allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocating} a {@link ByteBuffer}. */ public static GLPixelBufferProvider defaultProviderWithRowStride = new DefaultGLPixelBufferProvider(true); - - /** Pixel attributes. */ + + /** Pixel attributes. */ public static class GLPixelAttributes { - /** Undefined instance of {@link GLPixelAttributes}, having componentCount:=0, format:=0 and type:= 0. */ + /** Undefined instance of {@link GLPixelAttributes}, having componentCount:=0, format:=0 and type:= 0. */ public static final GLPixelAttributes UNDEF = new GLPixelAttributes(0, 0, 0, false); - + /** Pixel source component count, i.e. number of meaningful components. */ public final int componentCount; /** The OpenGL pixel data format */ @@ -184,7 +184,7 @@ public class GLPixelBuffer { public final int type; /** The OpenGL pixel size in bytes */ public final int bytesPerPixel; - + /** * Deriving {@link #componentCount} via GL dataFormat, i.e. {@link GLBuffers#componentCount(int)} if > 0. * @param dataFormat GL data format @@ -194,7 +194,7 @@ public class GLPixelBuffer { this(0 < dataFormat ? GLBuffers.componentCount(dataFormat) : 0, dataFormat, dataType); } /** - * Using user specified source {@link #componentCount}. + * Using user specified source {@link #componentCount}. * @param componentCount source component count * @param dataFormat GL data format * @param dataType GL data type @@ -220,7 +220,7 @@ public class GLPixelBuffer { return "PixelAttributes[comp "+componentCount+", fmt 0x"+Integer.toHexString(format)+", type 0x"+Integer.toHexString(type)+", bytesPerPixel "+bytesPerPixel+"]"; } } - + /** The {@link GLPixelAttributes}. */ public final GLPixelAttributes pixelAttributes; /** Width in pixels. */ @@ -233,22 +233,22 @@ public class GLPixelBuffer { public final boolean pack; /** Byte size of the buffer. Actually the number of {@link Buffer#remaining()} bytes when passed in ctor. */ public final int byteSize; - /** - * Buffer holding the pixel data. If {@link #rewind()}, it holds byteSize {@link Buffer#remaining()} bytes. + /** + * Buffer holding the pixel data. If {@link #rewind()}, it holds byteSize {@link Buffer#remaining()} bytes. *

          * By default the {@link Buffer} is a {@link ByteBuffer}, due to {@link DefProvider#allocate(GL, GLPixelAttributes, int, int, int, boolean, int)}. * However, other {@link GLPixelBufferProvider} may utilize different {@link Buffer} types. *

          - */ + */ public final Buffer buffer; /** Buffer element size in bytes. */ public final int bufferElemSize; - + /** Allow {@link GL2ES3#GL_PACK_ROW_LENGTH}, or {@link GL2ES2#GL_UNPACK_ROW_LENGTH}. See {@link #requiresNewBuffer(GL, int, int, int)}. */ public final boolean allowRowStride; - + private boolean disposed = false; - + public StringBuilder toString(StringBuilder sb) { if(null == sb) { sb = new StringBuilder(); @@ -272,7 +272,7 @@ public class GLPixelBuffer { * @param allowRowStride If true, allow row-stride, otherwise not. See {@link #requiresNewBuffer(GL, int, int, int)}. */ public GLPixelBuffer(GLPixelAttributes pixelAttributes, int width, int height, int depth, boolean pack, Buffer buffer, boolean allowRowStride) { - this.pixelAttributes = pixelAttributes; + this.pixelAttributes = pixelAttributes; this.width = width; this.height = height; this.depth = depth; @@ -282,15 +282,15 @@ public class GLPixelBuffer { this.bufferElemSize = Buffers.sizeOfBufferElem(buffer); this.allowRowStride = allowRowStride; } - + /** Allow {@link GL2ES3#GL_PACK_ROW_LENGTH}, or {@link GL2ES2#GL_UNPACK_ROW_LENGTH}. */ public final boolean getAllowRowStride() { return allowRowStride; } - + /** Is not {@link #dispose() disposed} and has {@link #byteSize} > 0. */ public boolean isValid() { return !disposed && 0 < byteSize; } - + /** See {@link Buffer#rewind()}. */ public Buffer rewind() { return buffer.rewind(); @@ -300,40 +300,40 @@ public class GLPixelBuffer { public int position() { return buffer.position() * bufferElemSize; } - + /** Sets the byte position of the {@link #buffer}. */ public Buffer position(int bytePos) { return buffer.position( bytePos / bufferElemSize ); } - + /** Returns the byte capacity of the {@link #buffer}. */ public int capacity() { return buffer.capacity() * bufferElemSize; } - + /** Returns the byte limit of the {@link #buffer}. */ public int limit() { return buffer.limit() * bufferElemSize; } - + /** See {@link Buffer#flip()}. */ public Buffer flip() { - return buffer.flip(); + return buffer.flip(); } - + /** See {@link Buffer#clear()}. */ public Buffer clear() { - return buffer.clear(); + return buffer.clear(); } - - /** + + /** * Returns true, if {@link #isValid() invalid} or implementation requires a new buffer based on the new size * due to pixel alignment or byte size, otherwise false. *

          * It is assumed that pixelAttributes, depth and pack stays the same! *

          *

          - * The minimum required byte size equals to minByteSize, if > 0, + * The minimum required byte size equals to minByteSize, if > 0, * otherwise {@link GLBuffers#sizeof(GL, int[], int, int, int, int, int, boolean) GLBuffers.sizeof(..)} * is being used to calculate it. This value is referred to newByteSize. *

          @@ -341,16 +341,16 @@ public class GLPixelBuffer { * If {@link #allowRowStride} = false, * method returns true if the newByteSize > currentByteSize * or the newWidth != currentWidth. - *

          + *

          *

          * If {@link #allowRowStride} = true, see {@link GLPixelBufferProvider#getAllowRowStride()}, - * method returns true only if the newByteSize > currentByteSize. + * method returns true only if the newByteSize > currentByteSize. * Assuming user utilizes the row-stride when dealing w/ the data, i.e. {@link GL2ES3#GL_PACK_ROW_LENGTH}. *

          * @param gl the corresponding current GL context object * @param newWidth new width in pixels * @param newHeight new height in pixels - * @param newByteSize if > 0, the pre-calculated minimum byte-size for the resulting buffer, otherwise ignore. + * @param newByteSize if > 0, the pre-calculated minimum byte-size for the resulting buffer, otherwise ignore. * @see GLPixelBufferProvider#allocate(GL, GLPixelAttributes, int, int, int, boolean, int) */ public boolean requiresNewBuffer(GL gl, int newWidth, int newHeight, int newByteSize) { @@ -366,7 +366,7 @@ public class GLPixelBuffer { } return byteSize < newByteSize || width != newWidth; } - + /** Dispose resources. See {@link #isValid()}. */ public void dispose() { disposed = true; diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLPixelStorageModes.java b/src/jogl/classes/com/jogamp/opengl/util/GLPixelStorageModes.java index f512a3aae..1c6e97450 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLPixelStorageModes.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLPixelStorageModes.java @@ -46,35 +46,35 @@ public class GLPixelStorageModes { /** Create instance w/o {@link #save(GL)} */ public GLPixelStorageModes() {} - + /** Create instance w/ {@link #save(GL)} */ public GLPixelStorageModes(GL gl) { save(gl); } - + /** * Sets the {@link GL#GL_PACK_ALIGNMENT}. - *

          + *

          * Saves the pixel storage modes if not saved yet. *

          */ public final void setPackAlignment(GL gl, int packAlignment) { save(gl); - gl.glPixelStorei(GL.GL_PACK_ALIGNMENT, packAlignment); + gl.glPixelStorei(GL.GL_PACK_ALIGNMENT, packAlignment); } /** * Sets the {@link GL#GL_UNPACK_ALIGNMENT}. - *

          + *

          * Saves the pixel storage modes if not saved yet. *

          */ public final void setUnpackAlignment(GL gl, int unpackAlignment) { save(gl); - gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, unpackAlignment); + gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, unpackAlignment); } - + /** - * Sets the {@link GL#GL_PACK_ALIGNMENT} and {@link GL#GL_UNPACK_ALIGNMENT}. - *

          + * Sets the {@link GL#GL_PACK_ALIGNMENT} and {@link GL#GL_UNPACK_ALIGNMENT}. + *

          * Saves the pixel storage modes if not saved yet. *

          */ @@ -82,32 +82,32 @@ public class GLPixelStorageModes { setPackAlignment(gl, packAlignment); setUnpackAlignment(gl, unpackAlignment); } - + /** * Sets the {@link GL2ES3#GL_PACK_ROW_LENGTH}. - *

          + *

          * Saves the pixel storage modes if not saved yet. *

          */ public final void setPackRowLength(GL2ES3 gl, int packRowLength) { save(gl); - gl.glPixelStorei(GL2ES3.GL_PACK_ROW_LENGTH, packRowLength); + gl.glPixelStorei(GL2ES3.GL_PACK_ROW_LENGTH, packRowLength); } /** * Sets the {@link GL2ES2#GL_UNPACK_ROW_LENGTH}. - *

          + *

          * Saves the pixel storage modes if not saved yet. *

          */ public final void setUnpackRowLength(GL2ES2 gl, int unpackRowLength) { save(gl); - gl.glPixelStorei(GL2ES2.GL_UNPACK_ROW_LENGTH, unpackRowLength); + gl.glPixelStorei(GL2ES2.GL_UNPACK_ROW_LENGTH, unpackRowLength); } - + /** * Sets the {@link GL2ES3#GL_PACK_ROW_LENGTH} and {@link GL2ES2#GL_UNPACK_ROW_LENGTH}. - *

          + *

          * Saves the pixel storage modes if not saved yet. *

          */ @@ -115,7 +115,7 @@ public class GLPixelStorageModes { setPackRowLength(gl, packRowLength); setUnpackRowLength(gl, unpackRowLength); } - + /** * Save the pixel storage mode, if not saved yet. *

          @@ -126,8 +126,8 @@ public class GLPixelStorageModes { if(saved) { return; } - - if(gl.isGL2GL3()) { + + if(gl.isGL2GL3()) { if(gl.isGL2()) { gl.getGL2().glPushClientAttrib(GL2.GL_CLIENT_PIXEL_STORE_BIT); } else { @@ -154,7 +154,7 @@ public class GLPixelStorageModes { // embedded deals with pack/unpack alignment only gl.glGetIntegerv(GL2ES2.GL_PACK_ALIGNMENT, savedAlignment, 0); gl.glGetIntegerv(GL2ES2.GL_UNPACK_ALIGNMENT, savedAlignment, 1); - } + } saved = true; } @@ -166,8 +166,8 @@ public class GLPixelStorageModes { if(!saved) { throw new GLException("pixel storage modes not saved"); } - - if(gl.isGL2GL3()) { + + if(gl.isGL2GL3()) { if(gl.isGL2()) { gl.getGL2().glPopClientAttrib(); } else { @@ -186,9 +186,9 @@ public class GLPixelStorageModes { // embedded deals with pack/unpack alignment only gl.glPixelStorei(GL2ES2.GL_PACK_ALIGNMENT, savedAlignment[0]); gl.glPixelStorei(GL2ES2.GL_UNPACK_ALIGNMENT, savedAlignment[1]); - } + } saved = false; - } + } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java b/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java index 65d1b6906..b942c9ab2 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.opengl.util; import java.io.File; @@ -51,45 +51,45 @@ import com.jogamp.opengl.util.texture.TextureIO; */ public class GLReadBufferUtil { protected final GLPixelBufferProvider pixelBufferProvider; - protected final int componentCount, alignment; + protected final int componentCount, alignment; protected final Texture readTexture; - protected final GLPixelStorageModes psm; - + protected final GLPixelStorageModes psm; + protected GLPixelBuffer readPixelBuffer = null; protected TextureData readTextureData = null; /** - * @param alpha true for RGBA readPixels, otherwise RGB readPixels. Disclaimer: Alpha maybe forced on ES platforms! + * @param alpha true for RGBA readPixels, otherwise RGB readPixels. Disclaimer: Alpha maybe forced on ES platforms! * @param write2Texture true if readPixel's TextureData shall be written to a 2d Texture */ public GLReadBufferUtil(boolean alpha, boolean write2Texture) { this(GLPixelBuffer.defaultProviderNoRowStride, alpha, write2Texture); } - + public GLReadBufferUtil(GLPixelBufferProvider pixelBufferProvider, boolean alpha, boolean write2Texture) { this.pixelBufferProvider = pixelBufferProvider; this.componentCount = alpha ? 4 : 3 ; - this.alignment = alpha ? 4 : 1 ; + this.alignment = alpha ? 4 : 1 ; this.readTexture = write2Texture ? new Texture(GL.GL_TEXTURE_2D) : null ; this.psm = new GLPixelStorageModes(); } - + /** Returns the {@link GLPixelBufferProvider} used by this instance. */ public GLPixelBufferProvider getPixelBufferProvider() { return pixelBufferProvider; } - + public boolean isValid() { return null!=readTextureData && null!=readPixelBuffer && readPixelBuffer.isValid(); } - + public boolean hasAlpha() { return 4 == componentCount ? true : false ; } - + public GLPixelStorageModes getGLPixelStorageModes() { return psm; } - + /** * Returns the {@link GLPixelBuffer}, created and filled by {@link #readPixels(GLAutoDrawable, boolean)}. */ public GLPixelBuffer getPixelBuffer() { return readPixelBuffer; } - + /** * rewind the raw pixel ByteBuffer */ @@ -99,7 +99,7 @@ public class GLReadBufferUtil { * @return the resulting TextureData, filled by {@link #readPixels(GLAutoDrawable, boolean)} */ public TextureData getTextureData() { return readTextureData; } - + /** * @return the Texture object filled by {@link #readPixels(GLAutoDrawable, boolean)}, * if this instance writes to a 2d Texture, otherwise null. @@ -121,27 +121,27 @@ public class GLReadBufferUtil { /** * Read the drawable's pixels to TextureData and Texture, if requested at construction. - * + * * @param gl the current GL context object. It's read drawable is being used as the pixel source. * @param mustFlipVertically indicates whether to flip the data vertically or not. * The context's drawable {@link GLDrawable#isGLOriented()} state * is taken into account. * Vertical flipping is propagated to TextureData * and handled in a efficient manner there (TextureCoordinates and TextureIO writer). - * + * * @see #GLReadBufferUtil(boolean, boolean) */ public boolean readPixels(GL gl, boolean mustFlipVertically) { return readPixels(gl, 0, 0, 0, 0, mustFlipVertically); } - + /** * Read the drawable's pixels to TextureData and Texture, if requested at construction. - * + * * @param gl the current GL context object. It's read drawable is being used as the pixel source. * @param inX readPixel x offset * @param inY readPixel y offset - * @param inWidth optional readPixel width value, used if [1 .. drawable.width], otherwise using drawable.width + * @param inWidth optional readPixel width value, used if [1 .. drawable.width], otherwise using drawable.width * @param inHeight optional readPixel height, used if [1 .. drawable.height], otherwise using drawable.height * @param mustFlipVertically indicates whether to flip the data vertically or not. * The context's drawable {@link GLDrawable#isGLOriented()} state @@ -174,17 +174,17 @@ public class GLReadBufferUtil { } else { height= inHeight; } - + final boolean flipVertically; if( drawable.isGLOriented() ) { flipVertically = mustFlipVertically; } else { flipVertically = !mustFlipVertically; } - + final int tmp[] = new int[1]; final int readPixelSize = GLBuffers.sizeof(gl, tmp, pixelAttribs.bytesPerPixel, width, height, 1, true); - + boolean newData = false; if( null == readPixelBuffer || readPixelBuffer.requiresNewBuffer(gl, width, height, readPixelSize) ) { readPixelBuffer = pixelBufferProvider.allocate(gl, pixelAttribs, width, height, 1, true, readPixelSize); @@ -194,9 +194,9 @@ public class GLReadBufferUtil { gl.getGLProfile(), internalFormat, width, height, - 0, + 0, pixelAttribs, - false, false, + false, false, flipVertically, readPixelBuffer.buffer, null /* Flusher */); @@ -230,13 +230,13 @@ public class GLReadBufferUtil { " "+width+"x"+height+ ", "+pixelAttribs+ ", "+readPixelBuffer+", sz "+readPixelSize); - res = false; + res = false; } if(res && null != readTexture) { if(newData) { readTexture.updateImage(gl, readTextureData); } else { - readTexture.updateSubImage(gl, readTextureData, 0, + readTexture.updateSubImage(gl, readTextureData, 0, 0, 0, // src offset 0, 0, // dst offset width, height); @@ -248,7 +248,7 @@ public class GLReadBufferUtil { return res; } - public void dispose(GL gl) { + public void dispose(GL gl) { if(null != readTexture) { readTexture.destroy(gl); readTextureData = null; diff --git a/src/jogl/classes/com/jogamp/opengl/util/Gamma.java b/src/jogl/classes/com/jogamp/opengl/util/Gamma.java index c649d1c6a..966781906 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/Gamma.java +++ b/src/jogl/classes/com/jogamp/opengl/util/Gamma.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java b/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java index 111e2509e..697b7cca0 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java +++ b/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java @@ -34,28 +34,28 @@ import com.jogamp.opengl.util.glsl.ShaderState; * to be either rendered directly via {@link #glEnd(GL)} or to be added to an internal display list * via {@link #glEnd(GL, boolean) glEnd(gl, false)} for deferred rendering via {@link #draw(GL, boolean)}. *

          - *
          Buffer storage and it's creation via {@link #createFixed(int, int, int, int, int, int, int, int, int, int) createFixed(..)} - * and {@link #createGLSL(int, int, int, int, int, int, int, int, int, int, ShaderState) createGLSL(..)}
          + *
          Buffer storage and it's creation via {@link #createFixed(int, int, int, int, int, int, int, int, int, int) createFixed(..)} + * and {@link #createGLSL(int, int, int, int, int, int, int, int, int, int, ShaderState) createGLSL(..)}
          *

          - * If unsure whether colors, normals and textures will be used, + * If unsure whether colors, normals and textures will be used, * simply add them with an expected component count. * This implementation will only render buffers which are being filled.
          * The buffer growing implementation will only grow the exceeded buffers, unused buffers are not resized. *

          *

          - * Note: Optional types, i.e. color, must be either not used or used w/ the same element count as vertex, etc. + * Note: Optional types, i.e. color, must be either not used or used w/ the same element count as vertex, etc. * This is a semantic constraint, same as in the original OpenGL spec. *

          */ public class ImmModeSink { protected static final boolean DEBUG_BEGIN_END; - protected static final boolean DEBUG_DRAW; + protected static final boolean DEBUG_DRAW; protected static final boolean DEBUG_BUFFER; - + static { Debug.initSingleton(); DEBUG_BEGIN_END = Debug.isPropertyDefined("jogl.debug.ImmModeSink.BeginEnd", true); - DEBUG_DRAW = Debug.isPropertyDefined("jogl.debug.ImmModeSink.Draw", true); + DEBUG_DRAW = Debug.isPropertyDefined("jogl.debug.ImmModeSink.Draw", true); DEBUG_BUFFER = Debug.isPropertyDefined("jogl.debug.ImmModeSink.Buffer", true); } @@ -68,7 +68,7 @@ public class ImmModeSink { *

          * See buffer storage details. *

          - * + * * @param initialElementCount initial buffer size, if subsequent mutable operations are about to exceed the buffer size, the buffer will grow about the initial size. * @param vComps mandatory vertex component count, should be 2, 3 or 4. * @param vDataType mandatory vertex data type, e.g. {@link GL#GL_FLOAT} @@ -78,17 +78,17 @@ public class ImmModeSink { * @param nDataType optional normal data type, e.g. {@link GL#GL_FLOAT} * @param tComps optional texture-coordinate component count, may be 0, 2 or 3 * @param tDataType optional texture-coordinate data type, e.g. {@link GL#GL_FLOAT} - * @param glBufferUsage VBO usage parameter for {@link GL#glBufferData(int, long, Buffer, int)}, e.g. {@link GL#GL_STATIC_DRAW}, + * @param glBufferUsage VBO usage parameter for {@link GL#glBufferData(int, long, Buffer, int)}, e.g. {@link GL#GL_STATIC_DRAW}, * set to 0 for no VBO usage */ - public static ImmModeSink createFixed(int initialElementCount, + public static ImmModeSink createFixed(int initialElementCount, int vComps, int vDataType, int cComps, int cDataType, - int nComps, int nDataType, - int tComps, int tDataType, + int nComps, int nDataType, + int tComps, int tDataType, int glBufferUsage) { - return new ImmModeSink(initialElementCount, - vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, + return new ImmModeSink(initialElementCount, + vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, false, glBufferUsage, null, 0); } @@ -97,7 +97,7 @@ public class ImmModeSink { *

          * See buffer storage details. *

          - * + * * @param initialElementCount initial buffer size, if subsequent mutable operations are about to exceed the buffer size, the buffer will grow about the initial size. * @param vComps mandatory vertex component count, should be 2, 3 or 4. * @param vDataType mandatory vertex data type, e.g. {@link GL#GL_FLOAT} @@ -107,21 +107,21 @@ public class ImmModeSink { * @param nDataType optional normal data type, e.g. {@link GL#GL_FLOAT} * @param tComps optional texture-coordinate component count, may be 0, 2 or 3 * @param tDataType optional texture-coordinate data type, e.g. {@link GL#GL_FLOAT} - * @param glBufferUsage VBO usage parameter for {@link GL#glBufferData(int, long, Buffer, int)}, e.g. {@link GL#GL_STATIC_DRAW}, + * @param glBufferUsage VBO usage parameter for {@link GL#glBufferData(int, long, Buffer, int)}, e.g. {@link GL#GL_STATIC_DRAW}, * set to 0 for no VBO usage * @param st ShaderState to locate the vertex attributes * @see #draw(GL, boolean) * @see com.jogamp.opengl.util.glsl.ShaderState#useProgram(GL2ES2, boolean) * @see com.jogamp.opengl.util.glsl.ShaderState#getCurrentShaderState() */ - public static ImmModeSink createGLSL(int initialElementCount, + public static ImmModeSink createGLSL(int initialElementCount, int vComps, int vDataType, int cComps, int cDataType, - int nComps, int nDataType, - int tComps, int tDataType, + int nComps, int nDataType, + int tComps, int tDataType, int glBufferUsage, ShaderState st) { - return new ImmModeSink(initialElementCount, - vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, + return new ImmModeSink(initialElementCount, + vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, true, glBufferUsage, st, 0); } @@ -130,7 +130,7 @@ public class ImmModeSink { *

          * See buffer storage details. *

          - * + * * @param initialElementCount initial buffer size, if subsequent mutable operations are about to exceed the buffer size, the buffer will grow about the initial size. * @param vComps mandatory vertex component count, should be 2, 3 or 4. * @param vDataType mandatory vertex data type, e.g. {@link GL#GL_FLOAT} @@ -140,24 +140,24 @@ public class ImmModeSink { * @param nDataType optional normal data type, e.g. {@link GL#GL_FLOAT} * @param tComps optional texture-coordinate component count, may be 0, 2 or 3 * @param tDataType optional texture-coordinate data type, e.g. {@link GL#GL_FLOAT} - * @param glBufferUsage VBO usage parameter for {@link GL#glBufferData(int, long, Buffer, int)}, e.g. {@link GL#GL_STATIC_DRAW}, + * @param glBufferUsage VBO usage parameter for {@link GL#glBufferData(int, long, Buffer, int)}, e.g. {@link GL#GL_STATIC_DRAW}, * set to 0 for no VBO usage * @param shaderProgram shader-program name to locate the vertex attributes * @see #draw(GL, boolean) * @see com.jogamp.opengl.util.glsl.ShaderState#useProgram(GL2ES2, boolean) * @see com.jogamp.opengl.util.glsl.ShaderState#getCurrentShaderState() */ - public static ImmModeSink createGLSL(int initialElementCount, + public static ImmModeSink createGLSL(int initialElementCount, int vComps, int vDataType, int cComps, int cDataType, - int nComps, int nDataType, - int tComps, int tDataType, + int nComps, int nDataType, + int tComps, int tDataType, int glBufferUsage, int shaderProgram) { - return new ImmModeSink(initialElementCount, - vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, + return new ImmModeSink(initialElementCount, + vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, true, glBufferUsage, null, shaderProgram); } - + public void destroy(GL gl) { destroyList(gl); @@ -346,7 +346,7 @@ public class ImmModeSink { public final void glColor3ub(byte x, byte y, byte z) { vboSet.glColor3ub(x,y,z); } - + public final void glColor4b(byte x, byte y, byte z, byte a) { vboSet.glColor4b(x,y,z,a); } @@ -354,7 +354,7 @@ public class ImmModeSink { public final void glColor4ub(byte x, byte y, byte z, byte a) { vboSet.glColor4ub(x,y,z,a); } - + public final void glTexCoord2b(byte x, byte y) { vboSet.glTexCoord2b(x,y); } @@ -363,26 +363,26 @@ public class ImmModeSink { vboSet.glTexCoord3b(x,y,z); } - protected ImmModeSink(int initialElementCount, - int vComps, int vDataType, - int cComps, int cDataType, - int nComps, int nDataType, - int tComps, int tDataType, + protected ImmModeSink(int initialElementCount, + int vComps, int vDataType, + int cComps, int cDataType, + int nComps, int nDataType, + int tComps, int tDataType, boolean useGLSL, int glBufferUsage, ShaderState st, int shaderProgram) { - vboSet = new VBOSet(initialElementCount, - vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, + vboSet = new VBOSet(initialElementCount, + vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, useGLSL, glBufferUsage, st, shaderProgram); this.vboSetList = new ArrayList(); } - + public boolean getUseVBO() { return vboSet.getUseVBO(); } - + /** * Returns the additional element count if buffer resize is required. * @see #setResizeElementCount(int) */ public int getResizeElementCount() { return vboSet.getResizeElementCount(); } - + /** * Sets the additional element count if buffer resize is required, * defaults to initialElementCount of factory method. @@ -390,7 +390,7 @@ public class ImmModeSink { * @see #createGLSL(int, int, int, int, int, int, int, int, int, int, ShaderState) */ public void setResizeElementCount(int v) { vboSet.setResizeElementCount(v); } - + private void destroyList(GL gl) { for(int i=0; i vboSetList; protected static class VBOSet { - protected VBOSet (int initialElementCount, - int vComps, int vDataType, - int cComps, int cDataType, - int nComps, int nDataType, - int tComps, int tDataType, + protected VBOSet (int initialElementCount, + int vComps, int vDataType, + int cComps, int cDataType, + int nComps, int nDataType, + int tComps, int tDataType, boolean useGLSL, int glBufferUsage, ShaderState st, int shaderProgram) { // final .. this.glBufferUsage=glBufferUsage; @@ -415,7 +415,7 @@ public class ImmModeSink { this.useGLSL=useGLSL; this.shaderState = st; this.shaderProgram = shaderProgram; - + if(useGLSL && null == shaderState && 0 == shaderProgram) { throw new IllegalArgumentException("Using GLSL but neither a valid shader-program nor ShaderState has been passed!"); } @@ -436,9 +436,9 @@ public class ImmModeSink { this.tDataType=tDataType; this.tDataTypeSigned=GLBuffers.isSignedGLType(tDataType); this.tComps=tComps; - this.tCompsBytes=tComps * GLBuffers.sizeOfGLType(tDataType); + this.tCompsBytes=tComps * GLBuffers.sizeOfGLType(tDataType); this.vboName = 0; - + this.vCount=0; this.cCount=0; this.nCount=0; @@ -447,9 +447,9 @@ public class ImmModeSink { this.cElems=0; this.nElems=0; this.tElems=0; - + this.pageSize = Platform.getMachineDescription().pageSizeInBytes(); - + reallocateBuffer(initialElementCount); rewind(); @@ -465,30 +465,30 @@ public class ImmModeSink { protected int getResizeElementCount() { return resizeElementCount; } protected void setResizeElementCount(int v) { resizeElementCount=v; } - + protected boolean getUseVBO() { return useVBO; } - + protected final VBOSet regenerate(GL gl) { - return new VBOSet(initialElementCount, vComps, - vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, + return new VBOSet(initialElementCount, vComps, + vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, useGLSL, glBufferUsage, shaderState, shaderProgram); } protected void checkSeal(boolean test) throws GLException { if(0==mode) { - throw new GLException("No mode set yet, call glBegin(mode) first:\n\t"+this); + throw new GLException("No mode set yet, call glBegin(mode) first:\n\t"+this); } if(sealed!=test) { if(test) { - throw new GLException("Not Sealed yet, call glEnd() first:\n\t"+this); + throw new GLException("Not Sealed yet, call glEnd() first:\n\t"+this); } else { - throw new GLException("Already Sealed, can't modify VBO after glEnd():\n\t"+this); + throw new GLException("Already Sealed, can't modify VBO after glEnd():\n\t"+this); } } } private boolean usingShaderProgram = false; - + protected void useShaderProgram(GL2ES2 gl, boolean force) { if( force || !usingShaderProgram ) { if(null != shaderState) { @@ -499,19 +499,19 @@ public class ImmModeSink { usingShaderProgram = true; } } - + protected void draw(GL gl, Buffer indices, boolean disableBufferAfterDraw, int i) { enableBuffer(gl, true); - + if(null != shaderState || 0 != shaderProgram) { useShaderProgram(gl.getGL2ES2(), false); } - + if(DEBUG_DRAW) { System.err.println("ImmModeSink.draw["+i+"].0 (disableBufferAfterDraw: "+disableBufferAfterDraw+"):\n\t"+this); } - + if (buffer!=null) { if(null==indices) { if ( GL_QUADS == mode && !gl.isGL2() ) { @@ -523,7 +523,7 @@ public class ImmModeSink { } } else { // FIXME: Impl. VBO usage .. or unroll. - if( !gl.getContext().isCPUDataSourcingAvail() ) { + if( !gl.getContext().isCPUDataSourcingAvail() ) { throw new GLException("CPU data sourcing n/a w/ "+gl.getContext()); } final int type; @@ -538,23 +538,23 @@ public class ImmModeSink { } final int idxLen = indices.remaining(); final int idx0 = indices.position(); - + if ( GL_QUADS == mode && !gl.isGL2() ) { if( GL.GL_UNSIGNED_BYTE == type ) { final ByteBuffer b = (ByteBuffer) indices; for (int j = 0; j < idxLen; j++) { gl.glDrawArrays(GL.GL_TRIANGLE_FAN, (int)(0x000000ff & b.get(idx0+j)), 4); - } + } } else if( GL.GL_UNSIGNED_SHORT == type ){ final ShortBuffer b = (ShortBuffer) indices; for (int j = 0; j < idxLen; j++) { gl.glDrawArrays(GL.GL_TRIANGLE_FAN, (int)(0x0000ffff & b.get(idx0+j)), 4); - } + } } else { final IntBuffer b = (IntBuffer) indices; for (int j = 0; j < idxLen; j++) { gl.glDrawArrays(GL.GL_TRIANGLE_FAN, (int)(0xffffffff & b.get(idx0+j)), 4); - } + } } } else { ((GL2ES1)gl).glDrawElements(mode, idxLen, type, indices); @@ -566,7 +566,7 @@ public class ImmModeSink { if(disableBufferAfterDraw) { enableBuffer(gl, false); } - + if(DEBUG_DRAW) { System.err.println("ImmModeSink.draw["+i+"].X (disableBufferAfterDraw: "+disableBufferAfterDraw+")"); } @@ -592,7 +592,7 @@ public class ImmModeSink { public void glVertex2b(byte x, byte y) { checkSeal(false); growBuffer(VERTEX); - if(vComps>0) + if(vComps>0) Buffers.putNb(vertexArray, vDataTypeSigned, x, true); if(vComps>1) Buffers.putNb(vertexArray, vDataTypeSigned, y, true); @@ -614,7 +614,7 @@ public class ImmModeSink { growBuffer(VERTEX); if(vComps>0) Buffers.putNs(vertexArray, vDataTypeSigned, x, true); - if(vComps>1) + if(vComps>1) Buffers.putNs(vertexArray, vDataTypeSigned, y, true); countAndPadding(VERTEX, vComps-2); } @@ -623,16 +623,16 @@ public class ImmModeSink { growBuffer(VERTEX); if(vComps>0) Buffers.putNs(vertexArray, vDataTypeSigned, x, true); - if(vComps>1) + if(vComps>1) Buffers.putNs(vertexArray, vDataTypeSigned, y, true); - if(vComps>2) + if(vComps>2) Buffers.putNs(vertexArray, vDataTypeSigned, z, true); countAndPadding(VERTEX, vComps-3); } public void glVertex2f(float x, float y) { checkSeal(false); growBuffer(VERTEX); - if(vComps>0) + if(vComps>0) Buffers.putNf(vertexArray, vDataTypeSigned, x); if(vComps>1) Buffers.putNf(vertexArray, vDataTypeSigned, y); @@ -641,11 +641,11 @@ public class ImmModeSink { public void glVertex3f(float x, float y, float z) { checkSeal(false); growBuffer(VERTEX); - if(vComps>0) + if(vComps>0) Buffers.putNf(vertexArray, vDataTypeSigned, x); if(vComps>1) Buffers.putNf(vertexArray, vDataTypeSigned, y); - if(vComps>2) + if(vComps>2) Buffers.putNf(vertexArray, vDataTypeSigned, z); countAndPadding(VERTEX, vComps-3); } @@ -653,33 +653,33 @@ public class ImmModeSink { public void glNormal3b(byte x, byte y, byte z) { checkSeal(false); growBuffer(NORMAL); - if(nComps>0) + if(nComps>0) Buffers.putNb(normalArray, nDataTypeSigned, x, true); - if(nComps>1) + if(nComps>1) Buffers.putNb(normalArray, nDataTypeSigned, y, true); - if(nComps>2) + if(nComps>2) Buffers.putNb(normalArray, nDataTypeSigned, z, true); countAndPadding(NORMAL, nComps-3); } public void glNormal3s(short x, short y, short z) { checkSeal(false); growBuffer(NORMAL); - if(nComps>0) + if(nComps>0) Buffers.putNs(normalArray, nDataTypeSigned, x, true); - if(nComps>1) + if(nComps>1) Buffers.putNs(normalArray, nDataTypeSigned, y, true); - if(nComps>2) + if(nComps>2) Buffers.putNs(normalArray, nDataTypeSigned, z, true); countAndPadding(NORMAL, nComps-3); } public void glNormal3f(float x, float y, float z) { checkSeal(false); growBuffer(NORMAL); - if(nComps>0) + if(nComps>0) Buffers.putNf(normalArray, nDataTypeSigned, x); if(nComps>1) Buffers.putNf(normalArray, nDataTypeSigned, y); - if(nComps>2) + if(nComps>2) Buffers.putNf(normalArray, nDataTypeSigned, z); countAndPadding(NORMAL, nComps-3); } @@ -687,96 +687,96 @@ public class ImmModeSink { public void glColor3b(byte r, byte g, byte b) { checkSeal(false); growBuffer(COLOR); - if(cComps>0) + if(cComps>0) Buffers.putNb(colorArray, cDataTypeSigned, r, true); - if(cComps>1) + if(cComps>1) Buffers.putNb(colorArray, cDataTypeSigned, g, true); - if(cComps>2) + if(cComps>2) Buffers.putNb(colorArray, cDataTypeSigned, b, true); countAndPadding(COLOR, cComps-3); } public void glColor3ub(byte r, byte g, byte b) { checkSeal(false); growBuffer(COLOR); - if(cComps>0) + if(cComps>0) Buffers.putNb(colorArray, cDataTypeSigned, r, false); - if(cComps>1) + if(cComps>1) Buffers.putNb(colorArray, cDataTypeSigned, g, false); - if(cComps>2) + if(cComps>2) Buffers.putNb(colorArray, cDataTypeSigned, b, false); countAndPadding(COLOR, cComps-3); } public void glColor4b(byte r, byte g, byte b, byte a) { checkSeal(false); growBuffer(COLOR); - if(cComps>0) + if(cComps>0) Buffers.putNb(colorArray, cDataTypeSigned, r, true); - if(cComps>1) + if(cComps>1) Buffers.putNb(colorArray, cDataTypeSigned, g, true); - if(cComps>2) + if(cComps>2) Buffers.putNb(colorArray, cDataTypeSigned, b, true); - if(cComps>3) + if(cComps>3) Buffers.putNb(colorArray, cDataTypeSigned, a, true); countAndPadding(COLOR, cComps-4); } public void glColor4ub(byte r, byte g, byte b, byte a) { checkSeal(false); growBuffer(COLOR); - if(cComps>0) + if(cComps>0) Buffers.putNb(colorArray, cDataTypeSigned, r, false); - if(cComps>1) + if(cComps>1) Buffers.putNb(colorArray, cDataTypeSigned, g, false); - if(cComps>2) + if(cComps>2) Buffers.putNb(colorArray, cDataTypeSigned, b, false); - if(cComps>3) + if(cComps>3) Buffers.putNb(colorArray, cDataTypeSigned, a, false); countAndPadding(COLOR, cComps-4); } public void glColor3s(short r, short g, short b) { checkSeal(false); growBuffer(COLOR); - if(cComps>0) + if(cComps>0) Buffers.putNs(colorArray, cDataTypeSigned, r, true); - if(cComps>1) + if(cComps>1) Buffers.putNs(colorArray, cDataTypeSigned, g, true); - if(cComps>2) + if(cComps>2) Buffers.putNs(colorArray, cDataTypeSigned, b, true); countAndPadding(COLOR, cComps-3); } public void glColor4s(short r, short g, short b, short a) { checkSeal(false); growBuffer(COLOR); - if(cComps>0) + if(cComps>0) Buffers.putNs(colorArray, cDataTypeSigned, r, true); - if(cComps>1) + if(cComps>1) Buffers.putNs(colorArray, cDataTypeSigned, g, true); - if(cComps>2) + if(cComps>2) Buffers.putNs(colorArray, cDataTypeSigned, b, true); - if(cComps>3) + if(cComps>3) Buffers.putNs(colorArray, cDataTypeSigned, a, true); countAndPadding(COLOR, cComps-4); } public void glColor3f(float r, float g, float b) { checkSeal(false); growBuffer(COLOR); - if(cComps>0) + if(cComps>0) Buffers.putNf(colorArray, cDataTypeSigned, r); - if(cComps>1) + if(cComps>1) Buffers.putNf(colorArray, cDataTypeSigned, g); - if(cComps>2) + if(cComps>2) Buffers.putNf(colorArray, cDataTypeSigned, b); countAndPadding(COLOR, cComps-3); } public void glColor4f(float r, float g, float b, float a) { checkSeal(false); growBuffer(COLOR); - if(cComps>0) + if(cComps>0) Buffers.putNf(colorArray, cDataTypeSigned, r); - if(cComps>1) + if(cComps>1) Buffers.putNf(colorArray, cDataTypeSigned, g); - if(cComps>2) + if(cComps>2) Buffers.putNf(colorArray, cDataTypeSigned, b); - if(cComps>3) + if(cComps>3) Buffers.putNf(colorArray, cDataTypeSigned, a); countAndPadding(COLOR, cComps-4); } @@ -784,60 +784,60 @@ public class ImmModeSink { public void glTexCoord2b(byte x, byte y) { checkSeal(false); growBuffer(TEXTCOORD); - if(tComps>0) + if(tComps>0) Buffers.putNb(textCoordArray, tDataTypeSigned, x, true); - if(tComps>1) + if(tComps>1) Buffers.putNb(textCoordArray, tDataTypeSigned, y, true); countAndPadding(TEXTCOORD, tComps-2); } public void glTexCoord3b(byte x, byte y, byte z) { checkSeal(false); growBuffer(TEXTCOORD); - if(tComps>0) + if(tComps>0) Buffers.putNb(textCoordArray, tDataTypeSigned, x, true); - if(tComps>1) + if(tComps>1) Buffers.putNb(textCoordArray, tDataTypeSigned, y, true); - if(tComps>2) + if(tComps>2) Buffers.putNb(textCoordArray, tDataTypeSigned, z, true); countAndPadding(TEXTCOORD, tComps-3); } public void glTexCoord2s(short x, short y) { checkSeal(false); growBuffer(TEXTCOORD); - if(tComps>0) + if(tComps>0) Buffers.putNs(textCoordArray, tDataTypeSigned, x, true); - if(tComps>1) + if(tComps>1) Buffers.putNs(textCoordArray, tDataTypeSigned, y, true); countAndPadding(TEXTCOORD, tComps-2); } public void glTexCoord3s(short x, short y, short z) { checkSeal(false); growBuffer(TEXTCOORD); - if(tComps>0) + if(tComps>0) Buffers.putNs(textCoordArray, tDataTypeSigned, x, true); - if(tComps>1) + if(tComps>1) Buffers.putNs(textCoordArray, tDataTypeSigned, y, true); - if(tComps>2) + if(tComps>2) Buffers.putNs(textCoordArray, tDataTypeSigned, z, true); countAndPadding(TEXTCOORD, tComps-3); } public void glTexCoord2f(float x, float y) { checkSeal(false); growBuffer(TEXTCOORD); - if(tComps>0) + if(tComps>0) Buffers.putNf(textCoordArray, tDataTypeSigned, x); - if(tComps>1) + if(tComps>1) Buffers.putNf(textCoordArray, tDataTypeSigned, y); countAndPadding(TEXTCOORD, tComps-2); } public void glTexCoord3f(float x, float y, float z) { checkSeal(false); growBuffer(TEXTCOORD); - if(tComps>0) + if(tComps>0) Buffers.putNf(textCoordArray, tDataTypeSigned, x); - if(tComps>1) + if(tComps>1) Buffers.putNf(textCoordArray, tDataTypeSigned, y); - if(tComps>2) + if(tComps>2) Buffers.putNf(textCoordArray, tDataTypeSigned, z); countAndPadding(TEXTCOORD, tComps-3); } @@ -864,20 +864,20 @@ public class ImmModeSink { shaderProgram = program; glslLocationSet = false; // enforce location reset! } - + /** * @param gl * @return true if all locations for all used arrays are found (min 1 array), otherwise false. - * Also sets 'glslLocationSet' to the return value! + * Also sets 'glslLocationSet' to the return value! */ private boolean resetGLSLArrayLocation(GL2ES2 gl) { int iA = 0; int iL = 0; - + if(null != vArrayData) { iA++; if( vArrayData.setLocation(gl, shaderProgram) >= 0 ) { - iL++; + iL++; } } if(null != cArrayData) { @@ -901,7 +901,7 @@ public class ImmModeSink { glslLocationSet = iA == iL; return glslLocationSet; } - + public void destroy(GL gl) { reset(gl); @@ -931,7 +931,7 @@ public class ImmModeSink { this.vElems=0; this.cElems=0; this.nElems=0; - this.tElems=0; + this.tElems=0; } public void seal(GL glObj, boolean seal) @@ -1016,20 +1016,20 @@ public class ImmModeSink { } } else { gl.glBufferData(GL.GL_ARRAY_BUFFER, buffer.limit(), buffer, glBufferUsage); - bufferWrittenOnce = true; - } + bufferWrittenOnce = true; + } } - + private void enableBufferFixed(GL gl, boolean enable) { GL2ES1 glf = gl.getGL2ES1(); - + final boolean useV = vComps>0 && vElems>0 ; final boolean useC = cComps>0 && cElems>0 ; final boolean useN = nComps>0 && nElems>0 ; final boolean useT = tComps>0 && tElems>0 ; - + if(DEBUG_DRAW) { - System.err.println("ImmModeSink.enableFixed.0 "+enable+": use [ v "+useV+", c "+useC+", n "+useN+", t "+useT+"], "+getElemUseCountStr()+", "+buffer); + System.err.println("ImmModeSink.enableFixed.0 "+enable+": use [ v "+useV+", c "+useC+", n "+useN+", t "+useT+"], "+getElemUseCountStr()+", "+buffer); } if(enable) { @@ -1038,7 +1038,7 @@ public class ImmModeSink { throw new InternalError("Using VBO but no vboName"); } glf.glBindBuffer(GL.GL_ARRAY_BUFFER, vboName); - + if(!bufferWritten) { writeBuffer(gl); } @@ -1051,7 +1051,7 @@ public class ImmModeSink { glf.glEnableClientState(GLPointerFunc.GL_VERTEX_ARRAY); glf.glVertexPointer(vArrayData); } else { - glf.glDisableClientState(GLPointerFunc.GL_VERTEX_ARRAY); + glf.glDisableClientState(GLPointerFunc.GL_VERTEX_ARRAY); } } if(useC) { @@ -1082,24 +1082,24 @@ public class ImmModeSink { if(enable && useVBO) { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); } - + if(DEBUG_DRAW) { - System.err.println("ImmModeSink.enableFixed.X "); + System.err.println("ImmModeSink.enableFixed.X "); } } private void enableBufferGLSLShaderState(GL gl, boolean enable) { GL2ES2 glsl = gl.getGL2ES2(); - + final boolean useV = vComps>0 && vElems>0 ; final boolean useC = cComps>0 && cElems>0 ; final boolean useN = nComps>0 && nElems>0 ; final boolean useT = tComps>0 && tElems>0 ; - + if(DEBUG_DRAW) { - System.err.println("ImmModeSink.enableGLSL.A.0 "+enable+": use [ v "+useV+", c "+useC+", n "+useN+", t "+useT+"], "+getElemUseCountStr()+", "+buffer); + System.err.println("ImmModeSink.enableGLSL.A.0 "+enable+": use [ v "+useV+", c "+useC+", n "+useN+", t "+useT+"], "+getElemUseCountStr()+", "+buffer); } - + if(enable) { if(useVBO) { if(0 == vboName) { @@ -1110,9 +1110,9 @@ public class ImmModeSink { writeBuffer(gl); } } - bufferWritten=true; + bufferWritten=true; } - + if(useV) { if(enable) { shaderState.enableVertexAttribArray(glsl, vArrayData); @@ -1144,30 +1144,30 @@ public class ImmModeSink { } else { shaderState.disableVertexAttribArray(glsl, tArrayData); } - } + } glslLocationSet = true; // ShaderState does set the location implicit - + if(enable && useVBO) { glsl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); } - + if(DEBUG_DRAW) { - System.err.println("ImmModeSink.enableGLSL.A.X "); + System.err.println("ImmModeSink.enableGLSL.A.X "); } } private void enableBufferGLSLSimple(GL gl, boolean enable) { GL2ES2 glsl = gl.getGL2ES2(); - + final boolean useV = vComps>0 && vElems>0 ; final boolean useC = cComps>0 && cElems>0 ; final boolean useN = nComps>0 && nElems>0 ; final boolean useT = tComps>0 && tElems>0 ; - + if(DEBUG_DRAW) { - System.err.println("ImmModeSink.enableGLSL.B.0 "+enable+": use [ v "+useV+", c "+useC+", n "+useN+", t "+useT+"], "+getElemUseCountStr()+", "+buffer); + System.err.println("ImmModeSink.enableGLSL.B.0 "+enable+": use [ v "+useV+", c "+useC+", n "+useN+", t "+useT+"], "+getElemUseCountStr()+", "+buffer); } - + if(!glslLocationSet) { if( !resetGLSLArrayLocation(glsl) ) { if(DEBUG_DRAW) { @@ -1180,7 +1180,7 @@ public class ImmModeSink { return; } } - + if(enable) { if(useVBO) { if(0 == vboName) { @@ -1226,28 +1226,28 @@ public class ImmModeSink { glsl.glDisableVertexAttribArray(tArrayData.getLocation()); } } - + if(enable && useVBO) { glsl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); } - + if(DEBUG_DRAW) { - System.err.println("ImmModeSink.enableGLSL.B.X "); + System.err.println("ImmModeSink.enableGLSL.B.X "); } } - + public String toString() { - final String glslS = useGLSL ? + final String glslS = useGLSL ? ", useShaderState "+(null!=shaderState)+ ", shaderProgram "+shaderProgram+ ", glslLocationSet "+glslLocationSet : ""; - - return "VBOSet[mode "+mode+ - ", modeOrig "+modeOrig+ + + return "VBOSet[mode "+mode+ + ", modeOrig "+modeOrig+ ", use/count "+getElemUseCountStr()+ - ", sealed "+sealed+ + ", sealed "+sealed+ ", sealedGL "+sealedGL+ - ", bufferEnabled "+bufferEnabled+ + ", bufferEnabled "+bufferEnabled+ ", bufferWritten "+bufferWritten+" (once "+bufferWrittenOnce+")"+ ", useVBO "+useVBO+", vboName "+vboName+ ", useGLSL "+useGLSL+ @@ -1264,7 +1264,7 @@ public class ImmModeSink { protected String getElemUseCountStr() { return "[v "+vElems+"/"+vCount+", c "+cElems+"/"+cCount+", n "+nElems+"/"+nCount+", t "+tElems+"/"+tCount+"]"; } - + protected boolean fitElementInBuffer(int type) { final int addElems = 1; switch (type) { @@ -1280,20 +1280,20 @@ public class ImmModeSink { throw new InternalError("XXX"); } } - + protected boolean reallocateBuffer(int addElems) { final int vAdd = addElems - ( vCount - vElems ); final int cAdd = addElems - ( cCount - cElems ); final int nAdd = addElems - ( nCount - nElems ); final int tAdd = addElems - ( tCount - tElems ); - + if( 0>=vAdd && 0>=cAdd && 0>=nAdd && 0>=tAdd) { if(DEBUG_BUFFER) { System.err.println("ImmModeSink.realloc: "+getElemUseCountStr()+" + "+addElems+" -> NOP"); } return false; } - + if(DEBUG_BUFFER) { System.err.println("ImmModeSink.realloc: "+getElemUseCountStr()+" + "+addElems); } @@ -1301,20 +1301,20 @@ public class ImmModeSink { cCount += cAdd; nCount += nAdd; tCount += tAdd; - + final int vBytes = vCount * vCompsBytes; final int cBytes = cCount * cCompsBytes; final int nBytes = nCount * nCompsBytes; final int tBytes = tCount * tCompsBytes; - + buffer = Buffers.newDirectByteBuffer( vBytes + cBytes + nBytes + tBytes ); vOffset = 0; - + if(vBytes>0) { vertexArray = GLBuffers.sliceGLBuffer(buffer, vOffset, vBytes, vDataType); } else { vertexArray = null; - } + } cOffset=vOffset+vBytes; if(cBytes>0) { @@ -1341,36 +1341,36 @@ public class ImmModeSink { buffer.flip(); if(vComps>0) { - vArrayData = GLArrayDataWrapper.createFixed(GLPointerFunc.GL_VERTEX_ARRAY, vComps, + vArrayData = GLArrayDataWrapper.createFixed(GLPointerFunc.GL_VERTEX_ARRAY, vComps, vDataType, GLBuffers.isGLTypeFixedPoint(vDataType), 0, vertexArray, 0, vOffset, GL.GL_STATIC_DRAW, GL.GL_ARRAY_BUFFER); } else { vArrayData = null; } if(cComps>0) { - cArrayData = GLArrayDataWrapper.createFixed(GLPointerFunc.GL_COLOR_ARRAY, cComps, + cArrayData = GLArrayDataWrapper.createFixed(GLPointerFunc.GL_COLOR_ARRAY, cComps, cDataType, GLBuffers.isGLTypeFixedPoint(cDataType), 0, colorArray, 0, cOffset, GL.GL_STATIC_DRAW, GL.GL_ARRAY_BUFFER); } else { cArrayData = null; } if(nComps>0) { - nArrayData = GLArrayDataWrapper.createFixed(GLPointerFunc.GL_NORMAL_ARRAY, nComps, + nArrayData = GLArrayDataWrapper.createFixed(GLPointerFunc.GL_NORMAL_ARRAY, nComps, nDataType, GLBuffers.isGLTypeFixedPoint(nDataType), 0, normalArray, 0, nOffset, GL.GL_STATIC_DRAW, GL.GL_ARRAY_BUFFER); } else { nArrayData = null; } if(tComps>0) { - tArrayData = GLArrayDataWrapper.createFixed(GLPointerFunc.GL_TEXTURE_COORD_ARRAY, tComps, + tArrayData = GLArrayDataWrapper.createFixed(GLPointerFunc.GL_TEXTURE_COORD_ARRAY, tComps, tDataType, GLBuffers.isGLTypeFixedPoint(tDataType), 0, textCoordArray, 0, tOffset, GL.GL_STATIC_DRAW, GL.GL_ARRAY_BUFFER); } else { tArrayData = null; } - + bufferWrittenOnce = false; // new buffer data storage size! - + if(DEBUG_BUFFER) { System.err.println("ImmModeSink.realloc.X: "+this.toString()); Thread.dumpStack(); @@ -1384,7 +1384,7 @@ public class ImmModeSink { if( !fitElementInBuffer(type) ) { // save olde values .. final Buffer _vertexArray=vertexArray, _colorArray=colorArray, _normalArray=normalArray, _textCoordArray=textCoordArray; - + if ( reallocateBuffer(resizeElementCount) ) { if(null!=_vertexArray) { _vertexArray.flip(); @@ -1416,7 +1416,7 @@ public class ImmModeSink { * vec4 v = vec4(0, 0, 0, 1); * vec4 c = vec4(0, 0, 0, 1); *

          - * + * * @param type * @param fill */ @@ -1426,7 +1426,7 @@ public class ImmModeSink { final Buffer dest; final boolean dSigned; final int e; // either 0 or 1 - + switch (type) { case VERTEX: dest = vertexArray; @@ -1459,7 +1459,7 @@ public class ImmModeSink { while( fill > e ) { fill--; - Buffers.putNf(dest, dSigned, 0f); + Buffers.putNf(dest, dSigned, 0f); } if( fill > 0 ) { // e == 1, add missing '1f end component' Buffers.putNf(dest, dSigned, 1f); @@ -1480,18 +1480,18 @@ public class ImmModeSink { private static final int NORMAL = 2; private static final int TEXTCOORD = 3; - private int vCount, cCount, nCount, tCount; // number of elements fit in each buffer + private int vCount, cCount, nCount, tCount; // number of elements fit in each buffer private int vOffset, cOffset, nOffset, tOffset; // offset of specific array in common buffer private int vElems, cElems, nElems, tElems; // number of used elements in each buffer - private final int vComps, cComps, nComps, tComps; // number of components for each elements [2, 3, 4] - private final int vCompsBytes, cCompsBytes, nCompsBytes, tCompsBytes; // byte size of all components + private final int vComps, cComps, nComps, tComps; // number of components for each elements [2, 3, 4] + private final int vCompsBytes, cCompsBytes, nCompsBytes, tCompsBytes; // byte size of all components private final int vDataType, cDataType, nDataType, tDataType; private final boolean vDataTypeSigned, cDataTypeSigned, nDataTypeSigned, tDataTypeSigned; private final int pageSize; private Buffer vertexArray, colorArray, normalArray, textCoordArray; private GLArrayDataWrapper vArrayData, cArrayData, nArrayData, tArrayData; - private boolean sealed, sealedGL; + private boolean sealed, sealedGL; private boolean bufferEnabled, bufferWritten, bufferWrittenOnce; private boolean glslLocationSet; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java b/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java index 58151856f..b4a0156e9 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java +++ b/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2009 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2011 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package com.jogamp.opengl.util; @@ -55,22 +55,22 @@ import com.jogamp.opengl.math.geom.Frustum; * regarding the projection (P), modelview (Mv) matrix operation * which is specified in {@link GLMatrixFunc}. *

          - * Further more, PMVMatrix provides the {@link #glGetMviMatrixf() inverse modelview matrix (Mvi)} and + * Further more, PMVMatrix provides the {@link #glGetMviMatrixf() inverse modelview matrix (Mvi)} and * {@link #glGetMvitMatrixf() inverse transposed modelview matrix (Mvit)}. * {@link Frustum} is also provided by {@link #glGetFrustum()}. * To keep these derived values synchronized after mutable Mv operations like {@link #glRotatef(float, float, float, float) glRotatef(..)} - * in {@link #glMatrixMode(int) glMatrixMode}({@link GLMatrixFunc#GL_MODELVIEW GL_MODELVIEW}), - * users have to call {@link #update()} before using Mvi and Mvit. + * in {@link #glMatrixMode(int) glMatrixMode}({@link GLMatrixFunc#GL_MODELVIEW GL_MODELVIEW}), + * users have to call {@link #update()} before using Mvi and Mvit. *

          *

          - * All matrices are provided in column-major order, - * as specified in the OpenGL fixed function pipeline, i.e. compatibility profile. + * All matrices are provided in column-major order, + * as specified in the OpenGL fixed function pipeline, i.e. compatibility profile. *

          *

          - * PMVMatrix can supplement {@link GL2ES2} applications w/ the + * PMVMatrix can supplement {@link GL2ES2} applications w/ the * lack of the described matrix functionality. *

          - *
          Matrix storage details
          + *
          Matrix storage details
          *

          * All matrices use a common FloatBuffer storage * and are a {@link Buffers#slice2Float(Buffer, float[], int, int) sliced} representation of it. @@ -78,11 +78,11 @@ import com.jogamp.opengl.math.geom.Frustum; * depending how the instance if {@link #PMVMatrix(boolean) being constructed}. *

          *

          - * Note: - *

            + * Note: + *
              *
            • The matrix is a {@link Buffers#slice2Float(Buffer, float[], int, int) sliced part } of a host matrix and it's start position has been {@link FloatBuffer#mark() marked}.
            • *
            • Use {@link FloatBuffer#reset() reset()} to rewind it to it's start position after relative operations, like {@link FloatBuffer#get() get()}.
            • - *
            • If using absolute operations like {@link FloatBuffer#get(int) get(int)}, use it's {@link FloatBuffer#reset() reset} {@link FloatBuffer#position() position} as it's offset.
            • + *
            • If using absolute operations like {@link FloatBuffer#get(int) get(int)}, use it's {@link FloatBuffer#reset() reset} {@link FloatBuffer#position() position} as it's offset.
            • *
            *

            */ @@ -96,20 +96,20 @@ public class PMVMatrix implements GLMatrixFunc { public static final int MODIFIED_TEXTURE = 1 << 2; /** Bit value stating all is modified */ public static final int MODIFIED_ALL = MODIFIED_PROJECTION | MODIFIED_MODELVIEW | MODIFIED_TEXTURE ; - + /** Bit value stating a dirty {@link #glGetMviMatrixf() inverse modelview matrix (Mvi)}. */ public static final int DIRTY_INVERSE_MODELVIEW = 1 << 0; /** Bit value stating a dirty {@link #glGetMvitMatrixf() inverse transposed modelview matrix (Mvit)}. */ - public static final int DIRTY_INVERSE_TRANSPOSED_MODELVIEW = 1 << 1; + public static final int DIRTY_INVERSE_TRANSPOSED_MODELVIEW = 1 << 1; /** Bit value stating a dirty {@link #glGetFrustum() frustum}. */ - public static final int DIRTY_FRUSTUM = 1 << 2; + public static final int DIRTY_FRUSTUM = 1 << 2; /** Bit value stating all is dirty */ public static final int DIRTY_ALL = DIRTY_INVERSE_MODELVIEW | DIRTY_INVERSE_TRANSPOSED_MODELVIEW | DIRTY_FRUSTUM; - + /** - * @param matrixModeName One of {@link GLMatrixFunc#GL_MODELVIEW GL_MODELVIEW}, {@link GLMatrixFunc#GL_PROJECTION GL_PROJECTION} or {@link GL#GL_TEXTURE GL_TEXTURE} + * @param matrixModeName One of {@link GLMatrixFunc#GL_MODELVIEW GL_MODELVIEW}, {@link GLMatrixFunc#GL_PROJECTION GL_PROJECTION} or {@link GL#GL_TEXTURE GL_TEXTURE} * @return true if the given matrix-mode name is valid, otherwise false. - */ + */ public static final boolean isMatrixModeName(final int matrixModeName) { switch(matrixModeName) { case GL_MODELVIEW_MATRIX: @@ -121,9 +121,9 @@ public class PMVMatrix implements GLMatrixFunc { } /** - * @param matrixModeName One of {@link GLMatrixFunc#GL_MODELVIEW GL_MODELVIEW}, {@link GLMatrixFunc#GL_PROJECTION GL_PROJECTION} or {@link GL#GL_TEXTURE GL_TEXTURE} + * @param matrixModeName One of {@link GLMatrixFunc#GL_MODELVIEW GL_MODELVIEW}, {@link GLMatrixFunc#GL_PROJECTION GL_PROJECTION} or {@link GL#GL_TEXTURE GL_TEXTURE} * @return The corresponding matrix-get name, one of {@link GLMatrixFunc#GL_MODELVIEW_MATRIX GL_MODELVIEW_MATRIX}, {@link GLMatrixFunc#GL_PROJECTION_MATRIX GL_PROJECTION_MATRIX} or {@link GLMatrixFunc#GL_TEXTURE_MATRIX GL_TEXTURE_MATRIX} - */ + */ public static final int matrixModeName2MatrixGetName(final int matrixModeName) { switch(matrixModeName) { case GL_MODELVIEW: @@ -138,9 +138,9 @@ public class PMVMatrix implements GLMatrixFunc { } /** - * @param matrixGetName One of {@link GLMatrixFunc#GL_MODELVIEW_MATRIX GL_MODELVIEW_MATRIX}, {@link GLMatrixFunc#GL_PROJECTION_MATRIX GL_PROJECTION_MATRIX} or {@link GLMatrixFunc#GL_TEXTURE_MATRIX GL_TEXTURE_MATRIX} + * @param matrixGetName One of {@link GLMatrixFunc#GL_MODELVIEW_MATRIX GL_MODELVIEW_MATRIX}, {@link GLMatrixFunc#GL_PROJECTION_MATRIX GL_PROJECTION_MATRIX} or {@link GLMatrixFunc#GL_TEXTURE_MATRIX GL_TEXTURE_MATRIX} * @return true if the given matrix-get name is valid, otherwise false. - */ + */ public static final boolean isMatrixGetName(final int matrixGetName) { switch(matrixGetName) { case GL_MATRIX_MODE: @@ -155,7 +155,7 @@ public class PMVMatrix implements GLMatrixFunc { /** * @param matrixGetName One of {@link GLMatrixFunc#GL_MODELVIEW_MATRIX GL_MODELVIEW_MATRIX}, {@link GLMatrixFunc#GL_PROJECTION_MATRIX GL_PROJECTION_MATRIX} or {@link GLMatrixFunc#GL_TEXTURE_MATRIX GL_TEXTURE_MATRIX} * @return The corresponding matrix-mode name, one of {@link GLMatrixFunc#GL_MODELVIEW GL_MODELVIEW}, {@link GLMatrixFunc#GL_PROJECTION GL_PROJECTION} or {@link GL#GL_TEXTURE GL_TEXTURE} - */ + */ public static final int matrixGetName2MatrixModeName(final int matrixGetName) { switch(matrixGetName) { case GL_MODELVIEW_MATRIX: @@ -168,18 +168,18 @@ public class PMVMatrix implements GLMatrixFunc { throw new GLException("unsupported matrixGetName: "+matrixGetName); } } - - /** + + /** * @param sb optional passed StringBuilder instance to be used * @param f the format string of one floating point, i.e. "%10.5f", see {@link java.util.Formatter} * @param a 4x4 matrix in column major order (OpenGL) * @return matrix string representation */ public static StringBuilder matrixToString(StringBuilder sb, String f, FloatBuffer a) { - return FloatUtil.matrixToString(sb, null, f, a, 0, 4, 4, false); + return FloatUtil.matrixToString(sb, null, f, a, 0, 4, 4, false); } - - /** + + /** * @param sb optional passed StringBuilder instance to be used * @param f the format string of one floating point, i.e. "%10.5f", see {@link java.util.Formatter} * @param a 4x4 matrix in column major order (OpenGL) @@ -187,33 +187,33 @@ public class PMVMatrix implements GLMatrixFunc { * @return side by side representation */ public static StringBuilder matrixToString(StringBuilder sb, String f, FloatBuffer a, FloatBuffer b) { - return FloatUtil.matrixToString(sb, null, f, a, 0, b, 0, 4, 4, false); + return FloatUtil.matrixToString(sb, null, f, a, 0, b, 0, 4, 4, false); } - + /** * Creates an instance of PMVMatrix {@link #PMVMatrix(boolean) PMVMatrix(boolean useBackingArray)}, - * with useBackingArray = true. + * with useBackingArray = true. */ public PMVMatrix() { this(true); } - + /** * Creates an instance of PMVMatrix. - * + * * @param useBackingArray true for non direct NIO Buffers with guaranteed backing array, * which allows faster access in Java computation. *

            false for direct NIO buffers w/o a guaranteed backing array. * In most Java implementations, direct NIO buffers have no backing array - * and hence the Java computation will be throttled down by direct IO get/put - * operations.

            + * and hence the Java computation will be throttled down by direct IO get/put + * operations.

            *

            Depending on the application, ie. whether the Java computation or - * JNI invocation and hence native data transfer part is heavier, + * JNI invocation and hence native data transfer part is heavier, * this flag shall be set to true or false

            . */ public PMVMatrix(boolean useBackingArray) { this.usesBackingArray = useBackingArray; - + // I Identity // T Texture // P Projection @@ -228,24 +228,24 @@ public class PMVMatrix implements GLMatrixFunc { matrixBuffer = Buffers.newDirectByteBuffer( ( 6*16 + ProjectFloat.getRequiredFloatBufferSize() ) * Buffers.SIZEOF_FLOAT ); matrixBuffer.mark(); } - + matrixIdent = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 0*16, 1*16); // I matrixTex = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 1*16, 1*16); // T - matrixPMvMvit = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 2*16, 4*16); // P + Mv + Mvi + Mvit + matrixPMvMvit = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 2*16, 4*16); // P + Mv + Mvi + Mvit matrixPMvMvi = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 2*16, 3*16); // P + Mv + Mvi matrixPMv = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 2*16, 2*16); // P + Mv matrixP = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 2*16, 1*16); // P matrixMv = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 3*16, 1*16); // Mv matrixMvi = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 4*16, 1*16); // Mvi matrixMvit = Buffers.slice2Float(matrixBuffer, matrixBufferArray, 5*16, 1*16); // Mvit - + projectFloat = new ProjectFloat(matrixBuffer, matrixBufferArray, 6*16); - + if(null != matrixBuffer) { matrixBuffer.reset(); - } + } FloatUtil.makeIdentityf(matrixIdent); - + vec3f = new float[3]; matrixMult = new float[16]; matrixTrans = new float[16]; @@ -263,7 +263,7 @@ public class PMVMatrix implements GLMatrixFunc { matrixTStack = new FloatStack( 0, 2*16); // growSize: GL-min size (2) matrixPStack = new FloatStack( 0, 2*16); // growSize: GL-min size (2) matrixMvStack= new FloatStack( 0, 16*16); // growSize: half GL-min size (32) - + // default values and mode glMatrixMode(GL_PROJECTION); glLoadIdentity(); @@ -275,22 +275,22 @@ public class PMVMatrix implements GLMatrixFunc { dirtyBits = DIRTY_ALL; requestMask = 0; matrixMode = GL_MODELVIEW; - + mulPMV = null; frustum = null; } /** @see #PMVMatrix(boolean) */ - public final boolean usesBackingArray() { return usesBackingArray; } - + public final boolean usesBackingArray() { return usesBackingArray; } + public final void destroy() { if(null!=projectFloat) { projectFloat.destroy(); projectFloat=null; } matrixBuffer=null; - matrixBuffer=null; matrixPMvMvit=null; matrixPMvMvi=null; matrixPMv=null; - matrixP=null; matrixTex=null; matrixMv=null; matrixMvi=null; matrixMvit=null; + matrixBuffer=null; matrixPMvMvit=null; matrixPMvMvi=null; matrixPMv=null; + matrixP=null; matrixTex=null; matrixMv=null; matrixMvi=null; matrixMvit=null; vec3f = null; matrixMult = null; @@ -299,7 +299,7 @@ public class PMVMatrix implements GLMatrixFunc { matrixScale = null; matrixOrtho = null; matrixFrustum = null; - + if(null!=matrixPStack) { matrixPStack=null; } @@ -314,13 +314,13 @@ public class PMVMatrix implements GLMatrixFunc { } } - + /** Returns the current matrix-mode, one of {@link GLMatrixFunc#GL_MODELVIEW GL_MODELVIEW}, {@link GLMatrixFunc#GL_PROJECTION GL_PROJECTION} or {@link GL#GL_TEXTURE GL_TEXTURE}. */ public final int glGetMatrixMode() { return matrixMode; } - /** + /** * Returns the {@link GLMatrixFunc#GL_TEXTURE_MATRIX texture matrix} (T). *

            * See matrix storage details. @@ -330,7 +330,7 @@ public class PMVMatrix implements GLMatrixFunc { return matrixTex; } - /** + /** * Returns the {@link GLMatrixFunc#GL_PROJECTION_MATRIX projection matrix} (P). *

            * See matrix storage details. @@ -340,7 +340,7 @@ public class PMVMatrix implements GLMatrixFunc { return matrixP; } - /** + /** * Returns the {@link GLMatrixFunc#GL_MODELVIEW_MATRIX modelview matrix} (Mv). *

            * See matrix storage details. @@ -350,7 +350,7 @@ public class PMVMatrix implements GLMatrixFunc { return matrixMv; } - /** + /** * Returns the inverse {@link GLMatrixFunc#GL_MODELVIEW_MATRIX modelview matrix} (Mvi). *

            * Method enables the Mvi matrix update, and performs it's update w/o clearing the modified bits. @@ -367,7 +367,7 @@ public class PMVMatrix implements GLMatrixFunc { return matrixMvi; } - /** + /** * Returns the inverse transposed {@link GLMatrixFunc#GL_MODELVIEW_MATRIX modelview matrix} (Mvit). *

            * Method enables the Mvit matrix update, and performs it's update w/o clearing the modified bits. @@ -383,9 +383,9 @@ public class PMVMatrix implements GLMatrixFunc { updateImpl(false); return matrixMvit; } - - /** - * Returns 2 matrices within one FloatBuffer: {@link #glGetPMatrixf() P} and {@link #glGetMvMatrixf() Mv}. + + /** + * Returns 2 matrices within one FloatBuffer: {@link #glGetPMatrixf() P} and {@link #glGetMvMatrixf() Mv}. *

            * See matrix storage details. *

            @@ -393,9 +393,9 @@ public class PMVMatrix implements GLMatrixFunc { public final FloatBuffer glGetPMvMatrixf() { return matrixPMv; } - - /** - * Returns 3 matrices within one FloatBuffer: {@link #glGetPMatrixf() P}, {@link #glGetMvMatrixf() Mv} and {@link #glGetMviMatrixf() Mvi}. + + /** + * Returns 3 matrices within one FloatBuffer: {@link #glGetPMatrixf() P}, {@link #glGetMvMatrixf() Mv} and {@link #glGetMviMatrixf() Mvi}. *

            * Method enables the Mvi matrix update, and performs it's update w/o clearing the modified bits. *

            @@ -410,9 +410,9 @@ public class PMVMatrix implements GLMatrixFunc { updateImpl(false); return matrixPMvMvi; } - - /** - * Returns 4 matrices within one FloatBuffer: {@link #glGetPMatrixf() P}, {@link #glGetMvMatrixf() Mv}, {@link #glGetMviMatrixf() Mvi} and {@link #glGetMvitMatrixf() Mvit}. + + /** + * Returns 4 matrices within one FloatBuffer: {@link #glGetPMatrixf() P}, {@link #glGetMvMatrixf() Mv}, {@link #glGetMviMatrixf() Mvi} and {@link #glGetMvitMatrixf() Mvit}. *

            * Method enables the Mvi and Mvit matrix update, and performs it's update w/o clearing the modified bits. *

            @@ -427,14 +427,14 @@ public class PMVMatrix implements GLMatrixFunc { updateImpl(false); return matrixPMvMvit; } - + /** Returns the frustum, derived from projection * modelview */ public Frustum glGetFrustum() { requestMask |= DIRTY_FRUSTUM; updateImpl(false); return frustum; } - + /* * @return the matrix of the current matrix-mode */ @@ -443,7 +443,7 @@ public class PMVMatrix implements GLMatrixFunc { } /** - * @param matrixName Either a matrix-get-name, i.e. + * @param matrixName Either a matrix-get-name, i.e. * {@link GLMatrixFunc#GL_MODELVIEW_MATRIX GL_MODELVIEW_MATRIX}, {@link GLMatrixFunc#GL_PROJECTION_MATRIX GL_PROJECTION_MATRIX} or {@link GLMatrixFunc#GL_TEXTURE_MATRIX GL_TEXTURE_MATRIX}, * or a matrix-mode-name, i.e. * {@link GLMatrixFunc#GL_MODELVIEW GL_MODELVIEW}, {@link GLMatrixFunc#GL_PROJECTION GL_PROJECTION} or {@link GL#GL_TEXTURE GL_TEXTURE} @@ -462,10 +462,10 @@ public class PMVMatrix implements GLMatrixFunc { return matrixTex; default: throw new GLException("unsupported matrixName: "+matrixName); - } + } } - // + // // GLMatrixFunc implementation // @@ -494,7 +494,7 @@ public class PMVMatrix implements GLMatrixFunc { } params.position(pos); } - + @Override public final void glGetFloatv(int matrixGetName, float[] params, int params_offset) { if(matrixGetName==GL_MATRIX_MODE) { @@ -505,7 +505,7 @@ public class PMVMatrix implements GLMatrixFunc { matrix.reset(); } } - + @Override public final void glGetIntegerv(int pname, IntBuffer params) { int pos = params.position(); @@ -516,7 +516,7 @@ public class PMVMatrix implements GLMatrixFunc { } params.position(pos); } - + @Override public final void glGetIntegerv(int pname, int[] params, int params_offset) { if(pname==GL_MATRIX_MODE) { @@ -537,12 +537,12 @@ public class PMVMatrix implements GLMatrixFunc { matrixP.put(values, offset, 16); matrixP.reset(); dirtyBits |= DIRTY_FRUSTUM ; - modifiedBits |= MODIFIED_PROJECTION; + modifiedBits |= MODIFIED_PROJECTION; } else if(matrixMode==GL.GL_TEXTURE) { matrixTex.put(values, offset, 16); matrixTex.reset(); modifiedBits |= MODIFIED_TEXTURE; - } + } } @Override @@ -557,12 +557,12 @@ public class PMVMatrix implements GLMatrixFunc { matrixP.put(m); matrixP.reset(); dirtyBits |= DIRTY_FRUSTUM ; - modifiedBits |= MODIFIED_PROJECTION; + modifiedBits |= MODIFIED_PROJECTION; } else if(matrixMode==GL.GL_TEXTURE) { matrixTex.put(m); matrixTex.reset(); modifiedBits |= MODIFIED_TEXTURE; - } + } m.position(spos); } @@ -584,9 +584,9 @@ public class PMVMatrix implements GLMatrixFunc { @Override public final void glPushMatrix() { - if(matrixMode==GL_MODELVIEW) { + if(matrixMode==GL_MODELVIEW) { matrixMvStack.putOnTop(matrixMv, 16); - matrixMv.reset(); + matrixMv.reset(); } else if(matrixMode==GL_PROJECTION) { matrixPStack.putOnTop(matrixP, 16); matrixP.reset(); @@ -612,8 +612,8 @@ public class PMVMatrix implements GLMatrixFunc { matrixTex.put(matrixIdent); matrixTex.reset(); modifiedBits |= MODIFIED_TEXTURE; - } - matrixIdent.reset(); + } + matrixIdent.reset(); } @Override @@ -629,7 +629,7 @@ public class PMVMatrix implements GLMatrixFunc { } else if(matrixMode==GL.GL_TEXTURE) { FloatUtil.multMatrixf(matrixTex, m); modifiedBits |= MODIFIED_TEXTURE; - } + } } @Override @@ -645,12 +645,12 @@ public class PMVMatrix implements GLMatrixFunc { } else if(matrixMode==GL.GL_TEXTURE) { FloatUtil.multMatrixf(matrixTex, m, m_offset); modifiedBits |= MODIFIED_TEXTURE; - } + } } @Override public final void glTranslatef(final float x, final float y, final float z) { - // Translation matrix: + // Translation matrix: // 1 0 0 x // 0 1 0 y // 0 0 1 z @@ -665,7 +665,7 @@ public class PMVMatrix implements GLMatrixFunc { public final void glRotatef(final float angdeg, float x, float y, float z) { final float angrad = angdeg * (float) Math.PI / 180.0f; final float c = (float)Math.cos(angrad); - final float ic= 1.0f - c; + final float ic= 1.0f - c; final float s = (float)Math.sin(angrad); vec3f[0]=x; vec3f[1]=y; vec3f[2]=z; @@ -700,7 +700,7 @@ public class PMVMatrix implements GLMatrixFunc { @Override public final void glScalef(final float x, final float y, final float z) { - // Scale matrix: + // Scale matrix: // x 0 0 0 // 0 y 0 0 // 0 0 z 0 @@ -714,7 +714,7 @@ public class PMVMatrix implements GLMatrixFunc { @Override public final void glOrthof(final float left, final float right, final float bottom, final float top, final float zNear, final float zFar) { - // Ortho matrix: + // Ortho matrix: // 2/dx 0 0 tx // 0 2/dy 0 ty // 0 0 2/dz tz @@ -744,7 +744,7 @@ public class PMVMatrix implements GLMatrixFunc { if(left==right || top==bottom) { throw new GLException("GL_INVALID_VALUE: top,bottom and left,right must not be equal"); } - // Frustum matrix: + // Frustum matrix: // 2*zNear/dx 0 A 0 // 0 2*zNear/dy B 0 // 0 0 C D @@ -774,7 +774,7 @@ public class PMVMatrix implements GLMatrixFunc { // // Extra functionality // - + /** * {@link #glMultMatrixf(FloatBuffer) Multiply} the {@link #glGetMatrixMode() current matrix} with the perspective/frustum matrix. */ @@ -787,7 +787,7 @@ public class PMVMatrix implements GLMatrixFunc { } /** - * {@link #glMultMatrixf(FloatBuffer) Multiply} and {@link #glTranslatef(float, float, float) translate} the {@link #glGetMatrixMode() current matrix} + * {@link #glMultMatrixf(FloatBuffer) Multiply} and {@link #glTranslatef(float, float, float) translate} the {@link #glGetMatrixMode() current matrix} * with the eye, object and orientation. */ public final void gluLookAt(float eyex, float eyey, float eyez, @@ -798,7 +798,7 @@ public class PMVMatrix implements GLMatrixFunc { /** * Map object coordinates to window coordinates. - * + * * @param objx * @param objy * @param objz @@ -815,20 +815,20 @@ public class PMVMatrix implements GLMatrixFunc { return projectFloat.gluProject(objx, objy, objz, matrixMv.array(), matrixMv.position(), matrixP.array(), matrixP.position(), - viewport, viewport_offset, + viewport, viewport_offset, win_pos, win_pos_offset); } else { return projectFloat.gluProject(objx, objy, objz, matrixMv, matrixP, - viewport, viewport_offset, + viewport, viewport_offset, win_pos, win_pos_offset); } } /** * Map window coordinates to object coordinates. - * + * * @param winx * @param winy * @param winz @@ -845,23 +845,23 @@ public class PMVMatrix implements GLMatrixFunc { return projectFloat.gluUnProject(winx, winy, winz, matrixMv.array(), matrixMv.position(), matrixP.array(), matrixP.position(), - viewport, viewport_offset, + viewport, viewport_offset, obj_pos, obj_pos_offset); } else { return projectFloat.gluUnProject(winx, winy, winz, matrixMv, matrixP, - viewport, viewport_offset, + viewport, viewport_offset, obj_pos, obj_pos_offset); - } + } } - + public final void gluPickMatrix(float x, float y, float deltaX, float deltaY, int[] viewport, int viewport_offset) { projectFloat.gluPickMatrix(this, x, y, deltaX, deltaY, viewport, viewport_offset); } - + public StringBuilder toString(StringBuilder sb, String f) { if(null == sb) { sb = new StringBuilder(); @@ -874,8 +874,8 @@ public class PMVMatrix implements GLMatrixFunc { final boolean frustumReq = 0 != (DIRTY_FRUSTUM & requestMask); final boolean modP = 0 != ( MODIFIED_PROJECTION & modifiedBits ); final boolean modMv = 0 != ( MODIFIED_MODELVIEW & modifiedBits ); - final boolean modT = 0 != ( MODIFIED_TEXTURE & modifiedBits ); - + final boolean modT = 0 != ( MODIFIED_TEXTURE & modifiedBits ); + sb.append("PMVMatrix[backingArray ").append(this.usesBackingArray()); sb.append(", modified[P ").append(modP).append(", Mv ").append(modMv).append(", T ").append(modT); sb.append("], dirty/req[Mvi ").append(mviDirty).append("/").append(mviReq).append(", Mvit ").append(mvitDirty).append("/").append(mvitReq).append(", Frustum ").append(frustumDirty).append("/").append(frustumReq); @@ -887,28 +887,28 @@ public class PMVMatrix implements GLMatrixFunc { matrixToString(sb, f, matrixTex); if( 0 != ( requestMask & DIRTY_INVERSE_MODELVIEW ) ) { sb.append(", Inverse Modelview").append(Platform.NEWLINE); - matrixToString(sb, f, matrixMvi); + matrixToString(sb, f, matrixMvi); } if( 0 != ( requestMask & DIRTY_INVERSE_TRANSPOSED_MODELVIEW ) ) { sb.append(", Inverse Transposed Modelview").append(Platform.NEWLINE); - matrixToString(sb, f, matrixMvit); + matrixToString(sb, f, matrixMvit); } sb.append("]"); return sb; } - + public String toString() { return toString(null, "%10.5f").toString(); } - /** + /** * Returns the modified bits due to mutable operations.. *

            * A modified bit is set, if the corresponding matrix had been modified by a mutable operation * since last {@link #update()} or {@link #getModifiedBits(boolean) getModifiedBits(true)} call. *

            * @param clear if true, clears the modified bits, otherwise leaves them untouched. - * + * * @see #MODIFIED_PROJECTION * @see #MODIFIED_MODELVIEW * @see #MODIFIED_TEXTURE @@ -920,16 +920,16 @@ public class PMVMatrix implements GLMatrixFunc { } return r; } - - /** + + /** * Returns the dirty bits due to mutable operations. *

            * A dirty bit is set , if the corresponding matrix had been modified by a mutable operation * since last {@link #update()} call. The latter clears the dirty state only if the dirty matrix (Mvi or Mvit) or {@link Frustum} - * has been requested by one of the {@link #glGetMviMatrixf() Mvi get}, {@link #glGetMvitMatrixf() Mvit get} + * has been requested by one of the {@link #glGetMviMatrixf() Mvi get}, {@link #glGetMvitMatrixf() Mvit get} * or {@link #glGetFrustum() Frustum get} methods. *

            - * + * * @deprecated Function is exposed for debugging purposes only. * @see #DIRTY_INVERSE_MODELVIEW * @see #DIRTY_INVERSE_TRANSPOSED_MODELVIEW @@ -944,12 +944,12 @@ public class PMVMatrix implements GLMatrixFunc { return dirtyBits; } - /** + /** * Returns the request bit mask, which uses bit values equal to the dirty mask. *

            - * The request bit mask is set by one of the {@link #glGetMviMatrixf() Mvi get}, {@link #glGetMvitMatrixf() Mvit get} + * The request bit mask is set by one of the {@link #glGetMviMatrixf() Mvi get}, {@link #glGetMvitMatrixf() Mvit get} * or {@link #glGetFrustum() Frustum get} methods. - *

            + *

            * * @deprecated Function is exposed for debugging purposes only. * @see #clearAllUpdateRequests() @@ -965,16 +965,16 @@ public class PMVMatrix implements GLMatrixFunc { public final int getRequestMask() { return requestMask; } - - + + /** * Clears all {@link #update()} requests of the Mvi and Mvit matrix and Frustum - * after it has been enabled by one of the {@link #glGetMviMatrixf() Mvi get}, {@link #glGetMvitMatrixf() Mvit get} + * after it has been enabled by one of the {@link #glGetMviMatrixf() Mvi get}, {@link #glGetMvitMatrixf() Mvit get} * or {@link #glGetFrustum() Frustum get} methods. *

            * Allows user to disable subsequent Mvi, Mvit and {@link Frustum} updates if no more required. - *

            - * + *

            + * * @see #glGetMviMatrixf() * @see #glGetMvitMatrixf() * @see #glGetPMvMviMatrixf() @@ -983,14 +983,14 @@ public class PMVMatrix implements GLMatrixFunc { * @see #getRequestMask() */ public final void clearAllUpdateRequests() { - requestMask &= ~DIRTY_ALL; + requestMask &= ~DIRTY_ALL; } - + /** * Update the derived {@link #glGetMviMatrixf() inverse modelview (Mvi)}, - * {@link #glGetMvitMatrixf() inverse transposed modelview (Mvit)} matrices and {@link Frustum} - * if they are dirty and they were requested - * by one of the {@link #glGetMviMatrixf() Mvi get}, {@link #glGetMvitMatrixf() Mvit get} + * {@link #glGetMvitMatrixf() inverse transposed modelview (Mvit)} matrices and {@link Frustum} + * if they are dirty and they were requested + * by one of the {@link #glGetMviMatrixf() Mvi get}, {@link #glGetMvitMatrixf() Mvit get} * or {@link #glGetFrustum() Frustum get} methods. *

            * The Mvi and Mvit matrices and {@link Frustum} are considered dirty, if their corresponding @@ -999,7 +999,7 @@ public class PMVMatrix implements GLMatrixFunc { *

            * Method should be called manually in case mutable operations has been called * and caller operates on already fetched references, i.e. not calling - * {@link #glGetMviMatrixf() Mvi get}, {@link #glGetMvitMatrixf() Mvit get} + * {@link #glGetMviMatrixf() Mvi get}, {@link #glGetMvitMatrixf() Mvit get} * or {@link #glGetFrustum() Frustum get} etc anymore. *

            *

            @@ -1007,12 +1007,12 @@ public class PMVMatrix implements GLMatrixFunc { * which are set by any mutable operation. The modified bits have no impact * on this method, but the return value. *

            - * - * @return true if any matrix has been modified since last update call or + * + * @return true if any matrix has been modified since last update call or * if the derived matrices Mvi and Mvit or {@link Frustum} were updated, otherwise false. * In other words, method returns true if any matrix used by the caller must be updated, * e.g. uniforms in a shader program. - * + * * @see #getModifiedBits(boolean) * @see #MODIFIED_PROJECTION * @see #MODIFIED_MODELVIEW @@ -1035,7 +1035,7 @@ public class PMVMatrix implements GLMatrixFunc { if(clearModBits) { modifiedBits = 0; } - + if( 0 != ( dirtyBits & ( DIRTY_FRUSTUM & requestMask ) ) ) { if( null == frustum ) { frustum = new Frustum(); @@ -1046,7 +1046,7 @@ public class PMVMatrix implements GLMatrixFunc { dirtyBits &= ~DIRTY_FRUSTUM; mod = true; } - + if( 0 == ( dirtyBits & requestMask ) ) { return mod; // nothing more requested which may have been dirty } @@ -1061,9 +1061,9 @@ public class PMVMatrix implements GLMatrixFunc { } return setMviMvitNIODirectAccess() || mod; } - + // - // private + // private // private int nioBackupArraySupported = 0; // -1 not supported, 0 - TBD, 1 - supported private final String msgCantComputeInverse = "Invalid source Mv matrix, can't compute inverse"; @@ -1080,7 +1080,7 @@ public class PMVMatrix implements GLMatrixFunc { res = true; } if( 0 != ( requestMask & ( dirtyBits & DIRTY_INVERSE_TRANSPOSED_MODELVIEW ) ) ) { // only if requested & dirty - // transpose matrix + // transpose matrix final float[] _matrixMvit = matrixMvit.array(); final int _matrixMvitOffset = matrixMvit.position(); for (int i = 0; i < 4; i++) { @@ -1093,7 +1093,7 @@ public class PMVMatrix implements GLMatrixFunc { } return res; } - + private final boolean setMviMvitNIODirectAccess() { boolean res = false; if( 0 != ( dirtyBits & DIRTY_INVERSE_MODELVIEW ) ) { // only if dirt; always requested at this point, see update() @@ -1104,7 +1104,7 @@ public class PMVMatrix implements GLMatrixFunc { res = true; } if( 0 != ( requestMask & ( dirtyBits & DIRTY_INVERSE_TRANSPOSED_MODELVIEW ) ) ) { // only if requested & dirty - // transpose matrix + // transpose matrix for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { matrixMvit.put(j+i*4, matrixMvi.get(i+j*4)); diff --git a/src/jogl/classes/com/jogamp/opengl/util/RandomTileRenderer.java b/src/jogl/classes/com/jogamp/opengl/util/RandomTileRenderer.java index a2b7ba343..b00866dd9 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/RandomTileRenderer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/RandomTileRenderer.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -35,14 +35,14 @@ import javax.media.opengl.GLException; import com.jogamp.opengl.util.GLPixelBuffer.GLPixelAttributes; /** - * Variation of {@link TileRenderer} w/o using fixed tiles but arbitrary rectangular regions. + * Variation of {@link TileRenderer} w/o using fixed tiles but arbitrary rectangular regions. *

            * See {@link TileRendererBase} for details. *

            */ public class RandomTileRenderer extends TileRendererBase { private boolean tileRectSet = false; - + /** * Creates a new TileRenderer object */ @@ -72,15 +72,15 @@ public class RandomTileRenderer extends TileRendererBase { /** * Set the tile rectangle for the subsequent rendering calls. - * - * @throws IllegalArgumentException is tile x/y are < 0 or tile size is <= 0x0 + * + * @throws IllegalArgumentException is tile x/y are < 0 or tile size is <= 0x0 */ public void setTileRect(int tX, int tY, int tWidth, int tHeight) throws IllegalStateException, IllegalArgumentException { if( 0 > tX || 0 > tX ) { - throw new IllegalArgumentException("Tile pos must be >= 0/0"); + throw new IllegalArgumentException("Tile pos must be >= 0/0"); } if( 0 >= tWidth || 0 >= tHeight ) { - throw new IllegalArgumentException("Tile size must be > 0x0"); + throw new IllegalArgumentException("Tile size must be > 0x0"); } this.currentTileXPos = tX; this.currentTileYPos = tY; @@ -88,57 +88,57 @@ public class RandomTileRenderer extends TileRendererBase { this.currentTileHeight = tHeight; tileRectSet = true; } - + @Override public final boolean isSetup() { return 0 < imageSize.getWidth() && 0 < imageSize.getHeight() && tileRectSet; } - + /** * {@inheritDoc} - * - *

            + * + *

            * end of tiling is never reached w/ {@link RandomRileRenderer}, * i.e. method always returns false. *

            */ @Override public final boolean eot() { return false; } - + /** * {@inheritDoc} - * + * * Reset internal states of {@link RandomTileRenderer} are: none. */ @Override public final void reset() { } - + /** * {@inheritDoc} - * - * @throws IllegalStateException if {@link #setImageSize(int, int) image-size} has not been set or + * + * @throws IllegalStateException if {@link #setImageSize(int, int) image-size} has not been set or * {@link #setTileRect(int, int, int, int) tile-rect} has not been set. */ @Override public final void beginTile(GL gl) throws IllegalStateException, GLException { if( 0 >= imageSize.getWidth() || 0 >= imageSize.getHeight() ) { - throw new IllegalStateException("Image size has not been set"); + throw new IllegalStateException("Image size has not been set"); } if( !tileRectSet ) { throw new IllegalStateException("tileRect has not been set"); } validateGL(gl); - + gl.glViewport( 0, 0, currentTileWidth, currentTileHeight ); - + if( DEBUG ) { System.err.println("TileRenderer.begin.X: "+this.toString()); } - + // Do not forget to issue: // reshape( 0, 0, tW, tH ); // which shall reflect tile renderer fileds: currentTileXPos, currentTileYPos and imageSize - + beginCalled = true; } @@ -148,7 +148,7 @@ public class RandomTileRenderer extends TileRendererBase { throw new IllegalStateException("beginTile(..) has not been called"); } validateGL(gl); - + // be sure OpenGL rendering is finished gl.glFlush(); @@ -220,13 +220,13 @@ public class RandomTileRenderer extends TileRendererBase { /* restore previous glPixelStore values */ psm.restore(gl); - + beginCalled = false; } - + /** * Rendering one tile, by simply calling {@link GLAutoDrawable#display()}. - * + * * @throws IllegalStateException if no {@link GLAutoDrawable} is {@link #attachAutoDrawable(GLAutoDrawable) attached} * or imageSize is not set */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/TGAWriter.java b/src/jogl/classes/com/jogamp/opengl/util/TGAWriter.java index b949f0e39..47d56bcb1 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/TGAWriter.java +++ b/src/jogl/classes/com/jogamp/opengl/util/TGAWriter.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 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 @@ -28,7 +28,7 @@ * 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. @@ -46,7 +46,7 @@ import java.nio.channels.*; * class; can also be used in conjunction with the {@link com.jogamp.opengl.util.gl2.TileRenderer} class. */ public class TGAWriter { - + private static final int TARGA_HEADER_SIZE = 18; private FileChannel ch; @@ -91,7 +91,7 @@ public class TGAWriter { image.put(14, (byte) (height & 0xFF)); // height image.put(15, (byte) (height >> 8)); // height image.put(16, (byte) pixelSize); // pixel size - + // go to image data position image.position(TARGA_HEADER_SIZE); // jogl needs a sliced buffer diff --git a/src/jogl/classes/com/jogamp/opengl/util/TileRenderer.java b/src/jogl/classes/com/jogamp/opengl/util/TileRenderer.java index 999db77a9..7f86b14c6 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/TileRenderer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/TileRenderer.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,18 +20,18 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. - * + * * --------------------- - * + * * Based on Brian Paul's tile rendering library, found * at http://www.mesa3d.org/brianp/TR.html. - * - * Copyright (C) 1997-2005 Brian Paul. - * Licensed under BSD-compatible terms with permission of the author. + * + * Copyright (C) 1997-2005 Brian Paul. + * Licensed under BSD-compatible terms with permission of the author. * See LICENSE.txt for license information. */ package com.jogamp.opengl.util; @@ -60,7 +60,7 @@ import com.jogamp.opengl.util.GLPixelBuffer.GLPixelAttributes; *

            * See {@link TileRendererBase} for details. *

            - * + * * @author ryanm, sgothel */ public class TileRenderer extends TileRendererBase { @@ -150,7 +150,7 @@ public class TileRenderer extends TileRendererBase { .append("rowOrder "+rowOrder+", offset/size "+offsetX+"/"+offsetY+" "+tileSize.getWidth()+"x"+tileSize.getHeight()+" brd "+tileBorder+", "); return super.tileDetails(sb); } - + /** * Creates a new TileRenderer object */ @@ -169,7 +169,7 @@ public class TileRenderer extends TileRendererBase { super.setImageSize(width, height); reset(); } - + /** * Clips the image-size this tile-renderer iterates through, * which can be retrieved via {@link #getClippedImageSize()}. @@ -179,7 +179,7 @@ public class TileRenderer extends TileRendererBase { *

            * Implementation {@link #reset()} internal states. *

            - * + * * @param width The image-clipping.width * @param height The image-clipping.height * @see #getClippedImageSize() @@ -208,7 +208,7 @@ public class TileRenderer extends TileRendererBase { * {@link #TR_IMAGE_CLIPPING_HEIGHT}. *

            */ - public final DimensionImmutable getClippedImageSize() { + public final DimensionImmutable getClippedImageSize() { if( null != imageClippingDim ) { return new Dimension(Math.min(imageClippingDim.getWidth(), imageSize.getWidth()), Math.min(imageClippingDim.getHeight(), imageSize.getHeight()) ); @@ -224,7 +224,7 @@ public class TileRenderer extends TileRendererBase { *

            * Implementation {@link #reset()} internal states. *

            - * + * * @param width * The width of the tiles. Must not be larger than the GL * context @@ -238,10 +238,10 @@ public class TileRenderer extends TileRendererBase { */ public final void setTileSize(int width, int height, int border) { if( 0 > border ) { - throw new IllegalArgumentException("Tile border must be >= 0"); + throw new IllegalArgumentException("Tile border must be >= 0"); } if( 2 * border >= width || 2 * border >= height ) { - throw new IllegalArgumentException("Tile size must be > 0x0 minus 2*border"); + throw new IllegalArgumentException("Tile size must be > 0x0 minus 2*border"); } tileBorder = border; tileSize.set( width, height ); @@ -249,7 +249,7 @@ public class TileRenderer extends TileRendererBase { reset(); } - /** + /** * Sets an xy offset for the resulting tiles * {@link TileRendererBase#TR_CURRENT_TILE_X_POS x-pos} and {@link TileRendererBase#TR_CURRENT_TILE_Y_POS y-pos}. * @see #TR_TILE_X_OFFSET @@ -259,12 +259,12 @@ public class TileRenderer extends TileRendererBase { offsetX = xoff; offsetY = yoff; } - + /** * {@inheritDoc} - * + * * Reset internal states of {@link TileRenderer} are: - *
              + *
                *
              • {@link #TR_ROWS}
              • *
              • {@link #TR_COLUMNS}
              • *
              • {@link #TR_CURRENT_COLUMN}
              • @@ -291,13 +291,13 @@ public class TileRenderer extends TileRendererBase { assert columns >= 0; assert rows >= 0; - + beginCalled = false; isInit = true; } /* pp */ final int getCurrentTile() { return currentTile; } - + @Override public final int getParam(int pname) { switch (pname) { @@ -346,7 +346,7 @@ public class TileRenderer extends TileRendererBase { /** * Sets the order of row traversal, default is {@link #TR_BOTTOM_TO_TOP}. - * + * * @param order The row traversal order, must be either {@link #TR_TOP_TO_BOTTOM} or {@link #TR_BOTTOM_TO_TOP}. */ public final void setRowOrder(int order) { @@ -361,11 +361,11 @@ public class TileRenderer extends TileRendererBase { public final boolean isSetup() { return 0 < imageSize.getWidth() && 0 < imageSize.getHeight(); } - + /** * {@inheritDoc} - * - *

                + * + *

                * end of tiling is reached w/ {@link TileRenderer}, if at least one of the following is true: *

                  *
                • all tiles have been rendered, i.e. {@link #TR_CURRENT_TILE_NUM} is -1
                • @@ -378,13 +378,13 @@ public class TileRenderer extends TileRendererBase { if ( !isInit ) { // ensure at least one reset-call reset(); } - return 0 > currentTile || 0 >= columns*rows; + return 0 > currentTile || 0 >= columns*rows; } - + /** * {@inheritDoc} - * - * @throws IllegalStateException if {@link #setImageSize(int, int) image-size} has not been set or + * + * @throws IllegalStateException if {@link #setImageSize(int, int) image-size} has not been set or * {@link #eot() end-of-tiling} has been reached. */ @Override @@ -396,7 +396,7 @@ public class TileRenderer extends TileRendererBase { throw new IllegalStateException("EOT reached: "+this); } validateGL(gl); - + /* which tile (by row and column) we're about to render */ if (rowOrder == TR_BOTTOM_TO_TOP) { currentRow = currentTile / columns; @@ -434,11 +434,11 @@ public class TileRenderer extends TileRendererBase { currentTileHeight = tH; gl.glViewport( 0, 0, tW, tH ); - + if( DEBUG ) { System.err.println("TileRenderer.begin: "+this.toString()); } - + // Do not forget to issue: // reshape( 0, 0, tW, tH ); // which shall reflect tile renderer tiles: currentTileXPos, currentTileYPos and imageSize @@ -454,7 +454,7 @@ public class TileRenderer extends TileRendererBase { // be sure OpenGL rendering is finished gl.glFlush(); - + // save current glPixelStore values psm.save(gl); psm.setPackAlignment(gl, 1); @@ -467,13 +467,13 @@ public class TileRenderer extends TileRendererBase { } else { gl2es3 = null; readBuffer = 0; // undef. probably default: GL_FRONT (single buffering) GL_BACK (double buffering) - } + } if( DEBUG ) { System.err.println("TileRenderer.end.0: readBuffer 0x"+Integer.toHexString(readBuffer)+", "+this.toString()); } - + final int tmp[] = new int[1]; - + if( tileBuffer != null ) { final GLPixelAttributes pixelAttribs = tileBuffer.pixelAttributes; final int srcX = tileBorder; @@ -527,7 +527,7 @@ public class TileRenderer extends TileRendererBase { psm.restore(gl); beginCalled = false; - + /* increment tile counter, return 1 if more tiles left to render */ currentTile++; if( currentTile >= rows * columns ) { diff --git a/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java b/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java index 0553d5673..ff7cc5516 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java +++ b/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,18 +20,18 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. - * + * * --------------------- - * + * * Based on Brian Paul's tile rendering library, found * at http://www.mesa3d.org/brianp/TR.html. - * - * Copyright (C) 1997-2005 Brian Paul. - * Licensed under BSD-compatible terms with permission of the author. + * + * Copyright (C) 1997-2005 Brian Paul. + * Licensed under BSD-compatible terms with permission of the author. * See LICENSE.txt for license information. */ package com.jogamp.opengl.util; @@ -66,17 +66,17 @@ import jogamp.opengl.Debug; * The PMV matrix needs to be reshaped in user code * after calling {@link #beginTile(GL)}, See {@link #beginTile(GL)}. *

                  - *

                  + *

                  * If {@link #attachAutoDrawable(GLAutoDrawable) attaching to} an {@link GLAutoDrawable}, * the {@link TileRendererListener#reshapeTile(TileRendererBase, int, int, int, int, int, int)} method * is being called after {@link #beginTile(GL)} for each rendered tile. - * It's implementation shall reshape the PMV matrix according to {@link #beginTile(GL)}. + * It's implementation shall reshape the PMV matrix according to {@link #beginTile(GL)}. *

                  *
                  GL Profile Requirement
                  *

                  - * Note that {@link #setImageBuffer(GLPixelBuffer) image buffer} can only be used + * Note that {@link #setImageBuffer(GLPixelBuffer) image buffer} can only be used * in conjunction w/ a {@link GL} instance ≥ {@link GL2ES3} passed to {@link #beginTile(GL)} and {@link #endTile(GL)}.
                  - * This is due to setting up the {@link GL2ES3#GL_PACK_ROW_LENGTH pack row length} + * This is due to setting up the {@link GL2ES3#GL_PACK_ROW_LENGTH pack row length} * for an {@link #setImageSize(int, int) image width} != tile-width, which usually is the case.
                  * Hence a {@link GLException} is thrown in both methods, * if using an {@link #setImageBuffer(GLPixelBuffer) image buffer} @@ -86,7 +86,7 @@ import jogamp.opengl.Debug; * Further more, reading back of MSAA buffers is only supported since {@link GL2ES3} * since it requires to set the {@link GL2ES3#glReadBuffer(int) read-buffer}. *

                  - * + * * @author ryanm, sgothel */ public abstract class TileRendererBase { @@ -114,16 +114,16 @@ public abstract class TileRendererBase { * The height of the current tile. See {@link #getParam(int)}. */ public static final int TR_CURRENT_TILE_HEIGHT = 6; - + /* pp */ static final boolean DEBUG = Debug.debug("TileRenderer"); - - /** + + /** * Listener for tile renderer events, intended to extend {@link GLEventListener} implementations, * enabling tile rendering via {@link TileRendererBase#attachAutoDrawable(GLAutoDrawable)}. */ public static interface TileRendererListener { - /** - * The owning {@link GLAutoDrawable} is {@link TileRendererBase#attachAutoDrawable(GLAutoDrawable) attached} + /** + * The owning {@link GLAutoDrawable} is {@link TileRendererBase#attachAutoDrawable(GLAutoDrawable) attached} * to the given {@link TileRendererBase} instance. *

                  * The {@link GLContext} of the {@link TileRendererBase}'s {@link TileRendererBase#getAttachedDrawable() attached} {@link GLAutoDrawable} @@ -133,9 +133,9 @@ public abstract class TileRendererBase { * @see TileRendererBase#getAttachedDrawable() */ public void addTileRendererNotify(TileRendererBase tr); - - /** - * The owning {@link GLAutoDrawable} is {@link TileRendererBase#detachAutoDrawable() detached} + + /** + * The owning {@link GLAutoDrawable} is {@link TileRendererBase#detachAutoDrawable() detached} * from the given {@link TileRendererBase} instance. *

                  * The {@link GLContext} of the {@link TileRendererBase}'s {@link TileRendererBase#getAttachedDrawable() attached} {@link GLAutoDrawable} @@ -145,10 +145,10 @@ public abstract class TileRendererBase { * @see TileRendererBase#getAttachedDrawable() */ public void removeTileRendererNotify(TileRendererBase tr); - - /** + + /** * Called by the {@link TileRendererBase} during tile-rendering via an - * {@link TileRendererBase#getAttachedDrawable() attached} {@link GLAutoDrawable}'s + * {@link TileRendererBase#getAttachedDrawable() attached} {@link GLAutoDrawable}'s * {@link GLAutoDrawable#display()} call for each tile before {@link #display(GLAutoDrawable)}. *

                  * The PMV Matrix shall be reshaped @@ -175,14 +175,14 @@ public abstract class TileRendererBase { * @see TileRendererBase#getAttachedDrawable() */ public void reshapeTile(TileRendererBase tr, - int tileX, int tileY, int tileWidth, int tileHeight, + int tileX, int tileY, int tileWidth, int tileHeight, int imageWidth, int imageHeight); /** - * Called by the {@link TileRendererBase} during tile-rendering + * Called by the {@link TileRendererBase} during tile-rendering * after {@link TileRendererBase#beginTile(GL)} and before {@link #reshapeTile(TileRendererBase, int, int, int, int, int, int) reshapeTile(..)}. *

                  - * If {@link TileRendererBase} is of type {@link TileRenderer}, + * If {@link TileRendererBase} is of type {@link TileRenderer}, * method is called for the first tile of all tiles.
                  * Otherwise, i.e. {@link RandomTileRenderer}, method is called for each particular tile. *

                  @@ -193,12 +193,12 @@ public abstract class TileRendererBase { * @param tr the issuing {@link TileRendererBase} */ public void startTileRendering(TileRendererBase tr); - + /** * Called by the {@link TileRenderer} during tile-rendering * after {@link TileRendererBase#endTile(GL)} and {@link GLAutoDrawable#swapBuffers()}. *

                  - * If {@link TileRendererBase} is of type {@link TileRenderer}, + * If {@link TileRendererBase} is of type {@link TileRenderer}, * method is called for the last tile of all tiles.
                  * Otherwise, i.e. {@link RandomTileRenderer}, method is called for each particular tile. *

                  @@ -210,7 +210,7 @@ public abstract class TileRendererBase { */ public void endTileRendering(TileRendererBase tr); } - + protected final Dimension imageSize = new Dimension(0, 0); protected final GLPixelStorageModes psm = new GLPixelStorageModes(); protected GLPixelBuffer imageBuffer; @@ -249,24 +249,24 @@ public abstract class TileRendererBase { return getClass().getSimpleName()+ "["+toString(sb).toString()+"]"; } - + protected TileRendererBase() { } /** * Gets the parameters of this TileRenderer object - * + * * @param pname The parameter name that is to be retrieved * @return the value of the parameter * @throws IllegalArgumentException if pname is not handled */ public abstract int getParam(int pname) throws IllegalArgumentException; - + /** * Specify a buffer the tiles to be copied to. This is not * necessary for the creation of the final image, but useful if you * want to inspect each tile in turn. - * + * * @param buffer The buffer itself. Must be large enough to contain a random tile */ public final void setTileBuffer(GLPixelBuffer buffer) { @@ -281,7 +281,7 @@ public abstract class TileRendererBase { /** * Sets the desired size of the final image - * + * * @param width The width of the final image * @param height The height of the final image */ @@ -294,7 +294,7 @@ public abstract class TileRendererBase { /** * Sets the buffer in which to store the final image - * + * * @param buffer the buffer itself, must be large enough to hold the final image */ public final void setImageBuffer(GLPixelBuffer buffer) { @@ -310,16 +310,16 @@ public abstract class TileRendererBase { /* pp */ final void validateGL(GL gl) throws GLException { if( imageBuffer != null && !gl.isGL2ES3()) { throw new GLException("Using image-buffer w/ inssufficient GL context: "+gl.getContext().getGLVersion()+", "+gl.getGLProfile()); - } + } } - - /** + + /** * Returns true if this instance is setup properly, i.e. {@link #setImageSize(int, int)} .., * and ready for {@link #beginTile(GL)}. * Otherwise returns false. */ public abstract boolean isSetup(); - + /** * Returns true if end of tiling has been reached, otherwise false. *

                  @@ -331,7 +331,7 @@ public abstract class TileRendererBase { *

                  */ public abstract boolean eot(); - + /** * Method resets implementation's internal state to start of tiling * as required for {@link #beginTile(GL)} if {@link #eot() end of tiling} has been reached. @@ -340,7 +340,7 @@ public abstract class TileRendererBase { *

                  */ public abstract void reset(); - + /** * Begins rendering a tile. *

                  @@ -367,7 +367,7 @@ public abstract class TileRendererBase { *

                  *

                  * Use shall render the scene afterwards, concluded with a call to - * this renderer {@link #endTile(GL)}. + * this renderer {@link #endTile(GL)}. *

                  *

                  * User has to comply with the GL profile requirement. @@ -376,10 +376,10 @@ public abstract class TileRendererBase { * If {@link #eot() end of tiling} has been reached, * user needs to {@link #reset()} tiling before calling this method. *

                  - * + * * @param gl The gl context * @throws IllegalStateException if {@link #setImageSize(int, int) image-size} is undefined, - * an {@link #isSetup() implementation related setup} has not be performed + * an {@link #isSetup() implementation related setup} has not be performed * or {@ link #eot()} has been reached. See implementing classes. * @throws GLException if {@link #setImageBuffer(GLPixelBuffer) image buffer} is used but gl instance is < {@link GL2ES3} * @see #isSetup() @@ -387,7 +387,7 @@ public abstract class TileRendererBase { * @see #reset() */ public abstract void beginTile(GL gl) throws IllegalStateException, GLException; - + /** * Must be called after rendering the scene, * see {@link #beginTile(GL)}. @@ -399,13 +399,13 @@ public abstract class TileRendererBase { *

                  * User has to comply with the GL profile requirement. *

                  - * + * * @param gl the gl context * @throws IllegalStateException if beginTile(gl) has not been called * @throws GLException if {@link #setImageBuffer(GLPixelBuffer) image buffer} is used but gl instance is < {@link GL2ES3} */ public abstract void endTile( GL gl ) throws IllegalStateException, GLException; - + /** * Determines whether the chosen {@link GLCapabilitiesImmutable} * requires a pre-{@link GLDrawable#swapBuffers() swap-buffers} @@ -417,18 +417,18 @@ public abstract class TileRendererBase { * Here {@link GLDrawable#swapBuffers() swap-buffers} shall happen after calling {@link #endTile(GL)}, the default. *

                  *

                  - * However, multisampling offscreen {@link GLFBODrawable}s + * However, multisampling offscreen {@link GLFBODrawable}s * utilize {@link GLDrawable#swapBuffers() swap-buffers} to downsample * the multisamples into the readable sampling sink. - * In this case, we require a {@link GLDrawable#swapBuffers() swap-buffers} before calling {@link #endTile(GL)}. - *

                  - * @param chosenCaps the chosen {@link GLCapabilitiesImmutable} + * In this case, we require a {@link GLDrawable#swapBuffers() swap-buffers} before calling {@link #endTile(GL)}. + *

                  + * @param chosenCaps the chosen {@link GLCapabilitiesImmutable} * @return chosenCaps.isFBO() && chosenCaps.getSampleBuffers() */ public final boolean reqPreSwapBuffers(GLCapabilitiesImmutable chosenCaps) { return chosenCaps.isFBO() && chosenCaps.getSampleBuffers(); } - + /** * Attaches the given {@link GLAutoDrawable} to this tile renderer. *

                  @@ -440,17 +440,17 @@ public abstract class TileRendererBase { *

                  * The {@link GLAutoDrawable}'s {@link GLAutoDrawable#getAutoSwapBufferMode() auto-swap mode} is cached * and set to false, since {@link GLAutoDrawable#swapBuffers() swapBuffers()} maybe issued before {@link #endTile(GL)}, - * see {@link #reqPreSwapBuffers(GLCapabilitiesImmutable)}. + * see {@link #reqPreSwapBuffers(GLCapabilitiesImmutable)}. *

                  *

                  - * This tile renderer's internal {@link GLEventListener} is then added to the attached {@link GLAutoDrawable} + * This tile renderer's internal {@link GLEventListener} is then added to the attached {@link GLAutoDrawable} * to handle the tile rendering, replacing the original {@link GLEventListener}.
                  * It's {@link GLEventListener#display(GLAutoDrawable) display} implementations issues: *

                    *
                  • Optional {@link #setGLEventListener(GLEventListener, GLEventListener) pre-glel}.{@link GLEventListener#display(GLAutoDrawable) display(..)}
                  • *
                  • {@link #beginTile(GL)}
                  • *
                  • for all original {@link TileRendererListener}: - *
                      + *
                        *
                      • {@link TileRendererListener#reshapeTile(TileRendererBase, int, int, int, int, int, int) reshapeTile(tileX, tileY, tileWidth, tileHeight, imageWidth, imageHeight)}
                      • *
                      • {@link GLEventListener#display(GLAutoDrawable) display(autoDrawable)}
                      • *
                      @@ -468,7 +468,7 @@ public abstract class TileRendererBase { * since it's called after {@link #endTile(GL)}. *

                      *

                      - * Call {@link #detachAutoDrawable()} to remove the attached {@link GLAutoDrawable} from this tile renderer + * Call {@link #detachAutoDrawable()} to remove the attached {@link GLAutoDrawable} from this tile renderer * and to restore it's original {@link GLEventListener}. *

                      * @param glad the {@link GLAutoDrawable} to attach. @@ -481,7 +481,7 @@ public abstract class TileRendererBase { throw new IllegalStateException("GLAutoDrawable already attached"); } this.glad = glad; - + final int aSz = glad.getGLEventListenerCount(); listeners = new GLEventListener[aSz]; listenersInit = new boolean[aSz]; @@ -510,11 +510,11 @@ public abstract class TileRendererBase { } } - /** - * Returns a previously {@link #attachAutoDrawable(GLAutoDrawable) attached} {@link GLAutoDrawable}, + /** + * Returns a previously {@link #attachAutoDrawable(GLAutoDrawable) attached} {@link GLAutoDrawable}, * null if none is attached. *

                      - * If called from {@link TileRendererListener#addTileRendererNotify(TileRendererBase)} + * If called from {@link TileRendererListener#addTileRendererNotify(TileRendererBase)} * or {@link TileRendererListener#removeTileRendererNotify(TileRendererBase)}, method returns the * just attached or soon to be detached {@link GLAutoDrawable}. *

                      @@ -522,9 +522,9 @@ public abstract class TileRendererBase { * @see #detachAutoDrawable() */ public final GLAutoDrawable getAttachedDrawable() { - return glad; + return glad; } - + /** * Detaches the given {@link GLAutoDrawable} from this tile renderer. * @see #attachAutoDrawable(GLAutoDrawable) @@ -547,16 +547,16 @@ public abstract class TileRendererBase { System.err.println("TileRenderer: detached: "+glad); System.err.println("TileRenderer: "+glad.getChosenGLCapabilities()); } - + listeners = null; listenersInit = null; glad = null; } } - + /** * Set {@link GLEventListener} for pre- and post operations when used w/ - * {@link #attachAutoDrawable(GLAutoDrawable)} + * {@link #attachAutoDrawable(GLAutoDrawable)} * for each {@link GLEventListener} callback. * @param preTile the pre operations * @param postTile the post operations @@ -565,10 +565,10 @@ public abstract class TileRendererBase { glEventListenerPre = preTile; glEventListenerPost = postTile; } - + /** * Rendering one tile, by simply calling {@link GLAutoDrawable#display()}. - * + * * @throws IllegalStateException if no {@link GLAutoDrawable} is {@link #attachAutoDrawable(GLAutoDrawable) attached} * or imageSize is not set */ @@ -578,10 +578,10 @@ public abstract class TileRendererBase { } glad.display(); } - + private final GLEventListener tiledGLEL = new GLEventListener() { final TileRenderer tileRenderer = TileRendererBase.this instanceof TileRenderer ? (TileRenderer) TileRendererBase.this : null; - + @Override public void init(GLAutoDrawable drawable) { if( null != glEventListenerPre ) { @@ -642,13 +642,13 @@ public abstract class TileRendererBase { if( null == tileRenderer || 0 == tileRenderer.getCurrentTile() ) { tl.startTileRendering(TileRendererBase.this); } - tl.reshapeTile(TileRendererBase.this, + tl.reshapeTile(TileRendererBase.this, currentTileXPos, currentTileYPos, currentTileWidth, currentTileHeight, imageSize.getWidth(), imageSize.getHeight()); l.display(drawable); } } - + if( gladRequiresPreSwap ) { glad.swapBuffers(); endTile(gl); @@ -662,7 +662,7 @@ public abstract class TileRendererBase { if( l instanceof TileRendererListener ) { ((TileRendererListener)l).endTileRendering(TileRendererBase.this); } - } + } } if( null != glEventListenerPost ) { glEventListenerPost.reshape(drawable, 0, 0, currentTileWidth, currentTileHeight); diff --git a/src/jogl/classes/com/jogamp/opengl/util/TimeFrameI.java b/src/jogl/classes/com/jogamp/opengl/util/TimeFrameI.java index e2bca010c..45f5d2694 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/TimeFrameI.java +++ b/src/jogl/classes/com/jogamp/opengl/util/TimeFrameI.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,51 +20,51 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ package com.jogamp.opengl.util; -/** +/** * Integer time frame in milliseconds, maybe specialized for texture/video, audio, .. animated content. *

                      * Type and value range has been chosen to suit embedded CPUs * and characteristics of audio / video streaming and animations. - * Milliseconds of type integer with a maximum value of {@link Integer#MAX_VALUE} + * Milliseconds of type integer with a maximum value of {@link Integer#MAX_VALUE} * will allow tracking time up 2,147,483.647 seconds or * 24 days 20 hours 31 minutes and 23 seconds. *

                      *

                      * Milliseconds granularity is also more than enough to deal with A-V synchronization, * where the threshold usually lies within 22ms. - *

                      + *

                      *

                      * Milliseconds granularity for displaying video frames might seem inaccurate * for each single frame, i.e. 60Hz != 16ms, however, accumulated values diminish - * this error and vertical sync is achieved by build-in V-Sync of the video drivers. + * this error and vertical sync is achieved by build-in V-Sync of the video drivers. *

                      */ public class TimeFrameI { /** Constant marking an invalid PTS, i.e. Integer.MIN_VALUE == 0x80000000 == {@value}. Sync w/ native code. */ public static final int INVALID_PTS = 0x80000000; - + /** Constant marking the end of the stream PTS, i.e. Integer.MIN_VALUE - 1 == 0x7FFFFFFF == {@value}. Sync w/ native code. */ - public static final int END_OF_STREAM_PTS = 0x7FFFFFFF; + public static final int END_OF_STREAM_PTS = 0x7FFFFFFF; protected int pts; protected int duration; - + public TimeFrameI() { pts = INVALID_PTS; - duration = 0; + duration = 0; } public TimeFrameI(int pts, int duration) { this.pts = pts; - this.duration = duration; + this.duration = duration; } - + /** Get this frame's presentation timestamp (PTS) in milliseconds. */ public final int getPTS() { return pts; } /** Set this frame's presentation timestamp (PTS) in milliseconds. */ @@ -73,7 +73,7 @@ public class TimeFrameI { public final int getDuration() { return duration; } /** Set this frame's duration in milliseconds. */ public final void setDuration(int duration) { this.duration = duration; } - + public String toString() { return "TimeFrame[pts " + pts + " ms, l " + duration + " ms]"; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/av/AudioSink.java b/src/jogl/classes/com/jogamp/opengl/util/av/AudioSink.java index 8751fc816..dffdfae8e 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/av/AudioSink.java +++ b/src/jogl/classes/com/jogamp/opengl/util/av/AudioSink.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -35,10 +35,10 @@ import jogamp.opengl.Debug; public interface AudioSink { public static final boolean DEBUG = Debug.debug("AudioSink"); - + /** Default frame duration in millisecond, i.e. 1 frame per {@value} ms. */ public static final int DefaultFrameDuration = 32; - + /** Initial audio queue size in milliseconds. {@value} ms, i.e. 16 frames per 32 ms. See {@link #init(AudioFormat, float, int, int, int)}.*/ public static final int DefaultInitialQueueSize = 16 * 32; // 512 ms /** Audio queue grow size in milliseconds. {@value} ms, i.e. 16 frames per 32 ms. See {@link #init(AudioFormat, float, int, int, int)}.*/ @@ -47,7 +47,7 @@ public interface AudioSink { public static final int DefaultQueueLimitWithVideo = 96 * 32; // 3072 ms /** Audio queue limit w/o video in milliseconds. {@value} ms, i.e. 32 frames per 32 ms. See {@link #init(AudioFormat, float, int, int, int)}.*/ public static final int DefaultQueueLimitAudioOnly = 32 * 32; // 1024 ms - + /** * Specifies the linear audio PCM format. */ @@ -78,7 +78,7 @@ public interface AudioSink { } } } - + /** Sample rate in Hz (1/s). */ public final int sampleRate; /** Sample size in bits. */ @@ -91,36 +91,36 @@ public interface AudioSink { /** Planar or packed samples. If planar, each channel has their own data buffer. If packed, channel data is interleaved in one buffer. */ public final boolean planar; public final boolean littleEndian; - - + + // // Time <-> Bytes // - - /** - * Returns the byte size of the given milliseconds + + /** + * Returns the byte size of the given milliseconds * according to {@link #sampleSize}, {@link #channelCount} and {@link #sampleRate}. *

                      * Time -> Byte Count - *

                      + *

                      */ public final int getDurationsByteSize(int millisecs) { final int bytesPerSample = sampleSize >>> 3; // /8 return millisecs * ( channelCount * bytesPerSample * ( sampleRate / 1000 ) ); } - - /** - * Returns the duration in milliseconds of the given byte count - * according to {@link #sampleSize}, {@link #channelCount} and {@link #sampleRate}. + + /** + * Returns the duration in milliseconds of the given byte count + * according to {@link #sampleSize}, {@link #channelCount} and {@link #sampleRate}. *

                      * Byte Count -> Time - *

                      + *

                      */ public final int getBytesDuration(int byteCount) { final int bytesPerSample = sampleSize >>> 3; // /8 - return byteCount / ( channelCount * bytesPerSample * ( sampleRate / 1000 ) ); + return byteCount / ( channelCount * bytesPerSample * ( sampleRate / 1000 ) ); } - + /** * Returns the duration in milliseconds of the given sample count per frame and channel * according to the {@link #sampleRate}, i.e. @@ -129,13 +129,13 @@ public interface AudioSink { *
          *

          * Sample Count -> Time - *

          + *

          * @param sampleCount sample count per frame and channel */ public final float getSamplesDuration(int sampleCount) { return ( 1000f * (float) sampleCount ) / (float)sampleRate; } - + /** * Returns the rounded frame count of the given milliseconds and frame duration. *
          @@ -147,36 +147,36 @@ public interface AudioSink {
                    * 

          *

          * Frame Time -> Frame Count - *

          + *

          * @param millisecs time in milliseconds * @param frameDuration duration per frame in milliseconds. */ public final int getFrameCount(int millisecs, float frameDuration) { return Math.max(1, (int) ( (float)millisecs / frameDuration + 0.5f )); } - + /** * Returns the byte size of given sample count - * according to the {@link #sampleSize}, i.e.: + * according to the {@link #sampleSize}, i.e.: *
                    *  sampleCount * ( sampleSize / 8 )
                    * 
          *

          - * Note: To retrieve the byte size for all channels, + * Note: To retrieve the byte size for all channels, * you need to pre-multiply sampleCount with {@link #channelCount}. *

          *

          * Sample Count -> Byte Count - *

          + *

          * @param sampleCount sample count */ public final int getSamplesByteCount(int sampleCount) { return sampleCount * ( sampleSize >>> 3 ); } - + /** * Returns the sample count of given byte count - * according to the {@link #sampleSize}, i.e.: + * according to the {@link #sampleSize}, i.e.: *
                    *  ( byteCount * 8 ) / sampleSize
                    * 
          @@ -186,24 +186,24 @@ public interface AudioSink { *

          *

          * Byte Count -> Sample Count - *

          + *

          * @param sampleCount sample count */ public final int getBytesSampleCount(int byteCount) { return ( byteCount << 3 ) / sampleSize; } - - public String toString() { + + public String toString() { return "AudioDataFormat[sampleRate "+sampleRate+", sampleSize "+sampleSize+", channelCount "+channelCount+ ", signed "+signed+", fixedP "+fixedP+", "+(planar?"planar":"packed")+", "+(littleEndian?"little":"big")+"-endian]"; } } - /** Default {@link AudioFormat}, [type PCM, sampleRate 44100, sampleSize 16, channelCount 2, signed, fixedP, !planar, littleEndian]. */ - public static final AudioFormat DefaultFormat = new AudioFormat(44100, 16, 2, true /* signed */, + /** Default {@link AudioFormat}, [type PCM, sampleRate 44100, sampleSize 16, channelCount 2, signed, fixedP, !planar, littleEndian]. */ + public static final AudioFormat DefaultFormat = new AudioFormat(44100, 16, 2, true /* signed */, true /* fixed point */, false /* planar */, true /* littleEndian */); - + public static abstract class AudioFrame extends TimeFrameI { protected int byteSize; - + public AudioFrame() { this.byteSize = 0; } @@ -211,19 +211,19 @@ public interface AudioSink { super(pts, duration); this.byteSize=byteCount; } - + /** Get this frame's size in bytes. */ public final int getByteSize() { return byteSize; } /** Set this frame's size in bytes. */ public final void setByteSize(int size) { this.byteSize=size; } - - public String toString() { + + public String toString() { return "AudioFrame[pts " + pts + " ms, l " + duration + " ms, "+byteSize + " bytes]"; } } public static class AudioDataFrame extends AudioFrame { protected final ByteBuffer data; - + public AudioDataFrame(int pts, int duration, ByteBuffer bytes, int byteCount) { super(pts, duration, byteCount); if( byteCount > bytes.remaining() ) { @@ -231,62 +231,62 @@ public interface AudioSink { } this.data=bytes; } - + /** Get this frame's data. */ public final ByteBuffer getData() { return data; } - - public String toString() { + + public String toString() { return "AudioDataFrame[pts " + pts + " ms, l " + duration + " ms, "+byteSize + " bytes, " + data + "]"; } } - - /** + + /** * Returns the initialized state of this instance. *

          * The initialized state is affected by this instance * overall availability, i.e. after instantiation, * as well as by {@link #destroy()}. - *

          + *

          */ public boolean isInitialized(); /** Returns the playback speed. */ public float getPlaySpeed(); - - /** + + /** * Sets the playback speed. *

          * To simplify test, play speed is normalized, i.e. - *

            - *
          • 1.0f: if Math.abs(1.0f - rate) < 0.01f
          • + *
              + *
            • 1.0f: if Math.abs(1.0f - rate) < 0.01f
            • *
            *

            - * @return true if successful, otherwise false, i.e. due to unsupported value range of implementation. + * @return true if successful, otherwise false, i.e. due to unsupported value range of implementation. */ public boolean setPlaySpeed(float s); - + /** Returns the volume. */ public float getVolume(); - - /** + + /** * Sets the volume [0f..1f]. *

            * To simplify test, volume is normalized, i.e. - *

              - *
            • 0.0f: if Math.abs(v) < 0.01f
            • - *
            • 1.0f: if Math.abs(1.0f - v) < 0.01f
            • + *
                + *
              • 0.0f: if Math.abs(v) < 0.01f
              • + *
              • 1.0f: if Math.abs(1.0f - v) < 0.01f
              • *
              *

              - * @return true if successful, otherwise false, i.e. due to unsupported value range of implementation. + * @return true if successful, otherwise false, i.e. due to unsupported value range of implementation. */ public boolean setVolume(float v); - - /** + + /** * Returns the preferred {@link AudioFormat} by this sink. *

              - * The preferred format is guaranteed to be supported + * The preferred format is guaranteed to be supported * and shall reflect this sinks most native format, - * i.e. best performance w/o data conversion. + * i.e. best performance w/o data conversion. *

              *

              * Known {@link #AudioFormat} attributes considered by implementations: @@ -295,20 +295,20 @@ public interface AudioSink { *

            *

            * @see #initSink(AudioFormat) - * @see #isSupported(AudioFormat) + * @see #isSupported(AudioFormat) */ public AudioFormat getPreferredFormat(); - + /** Return the maximum number of supported channels. */ public int getMaxSupportedChannels(); - + /** * Returns true if the given format is supported by the sink, otherwise false. * @see #initSink(AudioFormat) - * @see #getPreferredFormat() + * @see #getPreferredFormat() */ public boolean isSupported(AudioFormat format); - + /** * Initializes the sink. *

            @@ -319,7 +319,7 @@ public interface AudioSink { * beforehand and try to find a suitable supported one. * {@link #getPreferredFormat()} and {@link #getMaxSupportedChannels()} may help. *

            - * @param requestedFormat the requested {@link AudioFormat}. + * @param requestedFormat the requested {@link AudioFormat}. * @param frameDuration average or fixed frame duration in milliseconds * helping a caching {@link AudioFrame} based implementation to determine the frame count in the queue. * See {@link #DefaultFrameDuration}. @@ -328,31 +328,31 @@ public interface AudioSink { * @param queueLimit maximum time in milliseconds the queue can hold (and grow), see {@link #DefaultQueueLimitWithVideo} and {@link #DefaultQueueLimitAudioOnly}. * @return true if successful, otherwise false */ - public boolean init(AudioFormat requestedFormat, float frameDuration, + public boolean init(AudioFormat requestedFormat, float frameDuration, int initialQueueSize, int queueGrowAmount, int queueLimit); - + /** * Returns true, if {@link #play()} has been requested and the sink is still playing, * otherwise false. */ public boolean isPlaying(); - - /** + + /** * Play buffers queued via {@link #enqueueData(AudioFrame)} from current internal position. * If no buffers are yet queued or the queue runs empty, playback is being continued when buffers are enqueued later on. * @see #enqueueData(AudioFrame) - * @see #pause() + * @see #pause() */ public void play(); - - /** + + /** * Pause playing buffers while keeping enqueued data incl. it's internal position. * @see #play() * @see #flush() * @see #enqueueData(AudioFrame) */ public void pause(); - + /** * Flush all queued buffers, implies {@link #pause()}. *

            @@ -363,28 +363,28 @@ public interface AudioSink { * @see #enqueueData(AudioFrame) */ public void flush(); - + /** Destroys this instance, i.e. closes all streams and devices allocated. */ public void destroy(); - - /** - * Returns the number of allocated buffers as requested by + + /** + * Returns the number of allocated buffers as requested by * {@link #init(AudioFormat, float, int, int, int)}. */ public int getFrameCount(); /** @return the current enqueued frames count since {@link #init(AudioFormat, float, int, int, int)}. */ public int getEnqueuedFrameCount(); - - /** + + /** * Returns the current number of frames queued for playing. *

            * {@link #init(AudioFormat, float, int, int, int)} must be called first. *

            */ public int getQueuedFrameCount(); - - /** + + /** * Returns the current number of bytes queued for playing. *

            * {@link #init(AudioFormat, float, int, int, int)} must be called first. @@ -392,28 +392,28 @@ public interface AudioSink { */ public int getQueuedByteCount(); - /** + /** * Returns the current queued frame time in milliseconds for playing. *

            * {@link #init(AudioFormat, float, int, int, int)} must be called first. *

            */ public int getQueuedTime(); - - /** + + /** * Return the current audio presentation timestamp (PTS) in milliseconds. */ public int getPTS(); - - /** + + /** * Returns the current number of frames in the sink available for writing. *

            * {@link #init(AudioFormat, float, int, int, int)} must be called first. *

            */ public int getFreeFrameCount(); - - /** + + /** * Enqueue the remaining bytes of the given {@link AudioDataFrame}'s direct ByteBuffer to this sink. *

            * The data must comply with the chosen {@link AudioFormat} as returned by {@link #initSink(AudioFormat)}. @@ -426,8 +426,8 @@ public interface AudioSink { * to reuse specialized {@link AudioFrame} instances. */ public AudioFrame enqueueData(AudioDataFrame audioDataFrame); - - /** + + /** * Enqueue byteCount bytes of the remaining bytes of the given NIO {@link ByteBuffer} to this sink. *

            * The data must comply with the chosen {@link AudioFormat} as returned by {@link #initSink(AudioFormat)}. diff --git a/src/jogl/classes/com/jogamp/opengl/util/av/AudioSinkFactory.java b/src/jogl/classes/com/jogamp/opengl/util/av/AudioSinkFactory.java index a6a14f7dd..2cfd40df7 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/av/AudioSinkFactory.java +++ b/src/jogl/classes/com/jogamp/opengl/util/av/AudioSinkFactory.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -58,7 +58,7 @@ public class AudioSinkFactory { if( audioSink.isInitialized() ) { return audioSink; } - } catch (Throwable t) { + } catch (Throwable t) { if(AudioSink.DEBUG) { System.err.println("Catched "+t.getClass().getName()+": "+t.getMessage()); t.printStackTrace(); } } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayer.java b/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayer.java index 74036a3f7..db6f5fdee 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayer.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -49,9 +49,9 @@ import com.jogamp.opengl.util.TimeFrameI; * using the appropriate stream id's. *

            *

            - * Camera input can be selected using the {@link #CameraInputScheme} URI. + * Camera input can be selected using the {@link #CameraInputScheme} URI. *

            - * + * *
            StreamWorker Decoding Thread
            *

            * Most of the stream processing is performed on the decoding thread, a.k.a. StreamWorker: @@ -61,7 +61,7 @@ import com.jogamp.opengl.util.TimeFrameI; *

          • Caught exceptions on the decoding thread are delivered as {@link StreamException}s.
          • *
          * StreamWorker generates it's own {@link GLContext}, shared with the one passed to {@link #initGL(GL)}. - * The shared {@link GLContext} allows the decoding thread to push the video frame data directly into + * The shared {@link GLContext} allows the decoding thread to push the video frame data directly into * the designated {@link TextureFrame}, later returned via {@link #getNextTexture(GL)} and used by the user. *

          * StreamWorker Error Handling @@ -71,12 +71,12 @@ import com.jogamp.opengl.util.TimeFrameI; *

          *

          * An occurring {@link StreamException} triggers a {@link GLMediaEventListener#EVENT_CHANGE_ERR EVENT_CHANGE_ERR} event, - * which can be listened to via {@link GLMediaEventListener#attributesChanged(GLMediaPlayer, int, long)}. + * which can be listened to via {@link GLMediaEventListener#attributesChanged(GLMediaPlayer, int, long)}. *

          *

          - * An occurred {@link StreamException} can be read via {@link #getStreamException()}. + * An occurred {@link StreamException} can be read via {@link #getStreamException()}. *

          - * + * *

          *
          GLMediaPlayer Lifecycle
          *

          @@ -94,7 +94,7 @@ import com.jogamp.opengl.util.TimeFrameI; * {@link #destroy(GL)} ANY {@link State#Uninitialized Uninitialized} {@link GLMediaEventListener#EVENT_CHANGE_UNINIT EVENT_CHANGE_UNINIT} * *

          - * + * *
          Audio and video Stream IDs
          *

          * @@ -110,7 +110,7 @@ import com.jogamp.opengl.util.TimeFrameI; *
        • {@link jogamp.opengl.util.av.NullGLMediaPlayer}
        • *
        • {@link jogamp.opengl.util.av.impl.OMXGLMediaPlayer}
        • *
        • {@link jogamp.opengl.util.av.impl.FFMPEGMediaPlayer}
        • - *
        • {@link jogamp.opengl.android.av.AndroidGLMediaPlayerAPI14}
        • + *
        • {@link jogamp.opengl.android.av.AndroidGLMediaPlayerAPI14}
        • * *

          *

          @@ -127,7 +127,7 @@ import com.jogamp.opengl.util.TimeFrameI; * Timestamp type and value range has been chosen to suit embedded CPUs * and characteristics of audio and video streaming. See {@link TimeFrameI}. *

          - * + * *
          Audio and video synchronization
          *

          * The class follows a passive A/V synchronization pattern. @@ -158,7 +158,7 @@ import com.jogamp.opengl.util.TimeFrameI; *

        • Film: +22ms and -22ms. audio ahead video / audio after video.
        • * *

          - * + * *
          Test Streams
          *

          *

          @@ -185,16 +185,16 @@ import com.jogamp.opengl.util.TimeFrameI; public interface GLMediaPlayer extends TextureSequence { public static final boolean DEBUG = Debug.debug("GLMediaPlayer"); public static final boolean DEBUG_NATIVE = Debug.debug("GLMediaPlayer.Native"); - + /** Minimum texture count, value {@value}. */ public static final int TEXTURE_COUNT_MIN = 4; - + /** Constant {@value} for mute or not available. See Audio and video Stream IDs. */ public static final int STREAM_ID_NONE = -2; /** Constant {@value} for auto or unspecified. See Audio and video Stream IDs. */ public static final int STREAM_ID_AUTO = -1; - - /** + + /** * {@link URI#getScheme() URI scheme} name {@value} for camera input. E.g. camera:/0 * for the 1st camera device. *

          @@ -203,7 +203,7 @@ public interface GLMediaPlayer extends TextureSequence { *

          *

          * The ID is usually an integer value indexing the camera - * ranging from [0..max-number]. + * ranging from [0..max-number]. *

          *

          * The {@link URI#getRawQuery() URI query} is used to pass options to the camera @@ -220,7 +220,7 @@ public interface GLMediaPlayer extends TextureSequence { * w/ authority: [user-info@]host[:port] * Note: 'path' starts w/ fwd slash * - *

          + *

          */ public static final String CameraInputScheme = "camera"; /** Camera property {@value}, size as string, e.g. 1280x720, hd720. May not be supported on all platforms. See {@link #CameraInputScheme}. */ @@ -231,10 +231,10 @@ public interface GLMediaPlayer extends TextureSequence { public static final String CameraPropHeight = "height"; /** Camera property {@value}. See {@link #CameraInputScheme}. */ public static final String CameraPropRate = "rate"; - + /** Maximum video frame async of {@value} milliseconds. */ public static final int MAXIMUM_VIDEO_ASYNC = 22; - + /** * A StreamException encapsulates a caught exception in the decoder thread, a.k.a StreamWorker, * see See StreamWorker Error Handling. @@ -248,15 +248,15 @@ public interface GLMediaPlayer extends TextureSequence { super(message, cause); } } - + /** * {@inheritDoc} *

          * See {@link TexSeqEventListener} for semantics and usage. *

          - */ + */ public interface GLMediaEventListener extends TexSeqEventListener { - + /** State changed to {@link State#Initialized}. See Lifecycle.*/ static final int EVENT_CHANGE_INIT = 1<<0; /** State changed to {@link State#Uninitialized}. See Lifecycle.*/ @@ -269,7 +269,7 @@ public interface GLMediaPlayer extends TextureSequence { static final int EVENT_CHANGE_EOS = 1<<4; /** An error occurred, e.g. during off-thread initialization. See {@link StreamException} and Lifecycle. */ static final int EVENT_CHANGE_ERR = 1<<5; - + /** Stream video id change. */ static final int EVENT_CHANGE_VID = 1<<16; /** Stream audio id change. */ @@ -284,55 +284,55 @@ public interface GLMediaPlayer extends TextureSequence { static final int EVENT_CHANGE_LENGTH = 1<<21; /** Stream codec change. */ static final int EVENT_CHANGE_CODEC = 1<<22; - + /** - * @param mp the event source + * @param mp the event source * @param event_mask the changes attributes - * @param when system time in msec. + * @param when system time in msec. */ - public void attributesChanged(GLMediaPlayer mp, int event_mask, long when); + public void attributesChanged(GLMediaPlayer mp, int event_mask, long when); } - + /** * See Lifecycle. */ public enum State { /** Uninitialized player, no resources shall be hold. */ Uninitialized(0), - /** Stream has been initialized, user may play or call {@link #initGL(GL)}. */ - Initialized(1), + /** Stream has been initialized, user may play or call {@link #initGL(GL)}. */ + Initialized(1), /** Stream is playing. */ Playing(2), /** Stream is pausing. */ Paused(3); - + public final int id; State(int id){ this.id = id; } } - + public int getTextureCount(); - + /** Returns the texture target used by implementation. */ public int getTextureTarget(); /** Sets the texture unit. Defaults to 0. */ public void setTextureUnit(int u); - + /** Sets the texture min-mag filter, defaults to {@link GL#GL_NEAREST}. */ public void setTextureMinMagFilter(int[] minMagFilter); /** Sets the texture min-mag filter, defaults to {@link GL#GL_CLAMP_TO_EDGE}. */ public void setTextureWrapST(int[] wrapST); - - /** + + /** * Issues asynchronous stream initialization. *

          * Lifecycle: {@link State#Uninitialized} -> {@link State#Initialized}1 or {@link State#Uninitialized} *

          *

          - * {@link State#Initialized} is reached asynchronous, + * {@link State#Initialized} is reached asynchronous, * i.e. user gets notified via {@link GLMediaEventListener#attributesChanged(GLMediaPlayer, int, long) attributesChanges(..)}. *

          *

          @@ -344,7 +344,7 @@ public interface GLMediaPlayer extends TextureSequence { *

          *

          * Muted video can be achieved by passing {@link #STREAM_ID_NONE} to vid, - * in which case textureCount is ignored as well as the passed GL object of the subsequent {@link #initGL(GL)} call. + * in which case textureCount is ignored as well as the passed GL object of the subsequent {@link #initGL(GL)} call. *

          * @param streamLoc the stream location * @param vid video stream id, see audio and video Stream IDs @@ -352,41 +352,41 @@ public interface GLMediaPlayer extends TextureSequence { * @param textureCount desired number of buffered textures to be decoded off-thread, will be validated by implementation. * The minimum value is {@link #TEXTURE_COUNT_MIN}. * Ignored if video is muted. - * @throws IllegalStateException if not invoked in {@link State#Uninitialized} + * @throws IllegalStateException if not invoked in {@link State#Uninitialized} * @throws IllegalArgumentException if arguments are invalid */ public void initStream(URI streamLoc, int vid, int aid, int textureCount) throws IllegalStateException, IllegalArgumentException; - + /** * Returns the {@link StreamException} caught in the decoder thread, or null. * @see GLMediaEventListener#EVENT_CHANGE_ERR * @see StreamException */ public StreamException getStreamException(); - - /** + + /** * Initializes OpenGL related resources. *

          * Lifecycle: {@link State#Initialized} -> {@link State#Paused} or {@link State#Initialized} *

          * Argument gl is ignored if video is muted, see {@link #initStream(URI, int, int, int)}. - * + * * @param gl current GL object. Maybe null, for audio only. - * @throws IllegalStateException if not invoked in {@link State#Initialized}. + * @throws IllegalStateException if not invoked in {@link State#Initialized}. * @throws StreamException forwarded from the off-thread stream initialization * @throws GLException in case of difficulties to initialize the GL resources */ public void initGL(GL gl) throws IllegalStateException, StreamException, GLException; - - /** + + /** * If implementation uses a {@link AudioSink}, it's instance will be returned. - *

          - * The {@link AudioSink} instance is available after {@link #initStream(URI, int, int, int)}, + *

          + * The {@link AudioSink} instance is available after {@link #initStream(URI, int, int, int)}, * if used by implementation. - *

          + *

          */ public AudioSink getAudioSink(); - + /** * Releases the GL and stream resources. *

          @@ -399,11 +399,11 @@ public interface GLMediaPlayer extends TextureSequence { * Sets the playback speed. *

          * To simplify test, play speed is normalized, i.e. - *

            - *
          • 1.0f: if Math.abs(1.0f - rate) < 0.01f
          • + *
              + *
            • 1.0f: if Math.abs(1.0f - rate) < 0.01f
            • *
            *

            - * @return true if successful, otherwise false, i.e. due to unsupported value range of implementation. + * @return true if successful, otherwise false, i.e. due to unsupported value range of implementation. */ public boolean setPlaySpeed(float rate); @@ -414,18 +414,18 @@ public interface GLMediaPlayer extends TextureSequence { * Sets the audio volume, [0f..1f]. *

            * To simplify test, volume is normalized, i.e. - *

              - *
            • 0.0f: if Math.abs(v) < 0.01f
            • - *
            • 1.0f: if Math.abs(1.0f - v) < 0.01f
            • + *
                + *
              • 0.0f: if Math.abs(v) < 0.01f
              • + *
              • 1.0f: if Math.abs(1.0f - v) < 0.01f
              • *
              *

              - * @return true if successful, otherwise false, i.e. due to unsupported value range of implementation. + * @return true if successful, otherwise false, i.e. due to unsupported value range of implementation. */ public boolean setAudioVolume(float v); - + /** Returns the audio volume. */ public float getAudioVolume(); - + /** * Starts or resumes the StreamWorker decoding thread. *

              @@ -441,9 +441,9 @@ public interface GLMediaPlayer extends TextureSequence { *

              *

              * If a new frame is desired after the next {@link #play()} call, - * e.g. to make a snapshot of a camera input stream, + * e.g. to make a snapshot of a camera input stream, * flush shall be set to true. - *

              + *

              * @param flush if true flushes the video and audio buffers, otherwise keep them intact. */ public State pause(boolean flush); @@ -454,10 +454,10 @@ public interface GLMediaPlayer extends TextureSequence { *

              * Allowed in state {@link State#Playing} and {@link State#Paused}, otherwise ignored, * see Lifecycle. - *

              - * - * @param msec absolute desired time position in milliseconds - * @return time current position in milliseconds, after seeking to the desired position + *

              + * + * @param msec absolute desired time position in milliseconds + * @return time current position in milliseconds, after seeking to the desired position **/ public int seek(int msec); @@ -466,39 +466,39 @@ public interface GLMediaPlayer extends TextureSequence { * @return the current state, either {@link State#Uninitialized}, {@link State#Initialized}, {@link State#Playing} or {@link State#Paused} */ public State getState(); - + /** * Return the video stream id, see audio and video Stream IDs. */ public int getVID(); - + /** * Return the audio stream id, see audio and video Stream IDs. */ public int getAID(); - + /** - * @return the current decoded frame count since {@link #play()} and {@link #seek(int)} + * @return the current decoded frame count since {@link #play()} and {@link #seek(int)} * as increased by {@link #getNextTexture(GL)} or the decoding thread. */ public int getDecodedFrameCount(); - + /** - * @return the current presented frame count since {@link #play()} and {@link #seek(int)} + * @return the current presented frame count since {@link #play()} and {@link #seek(int)} * as increased by {@link #getNextTexture(GL)} for new frames. */ public int getPresentedFrameCount(); - + /** - * @return current video presentation timestamp (PTS) in milliseconds of {@link #getLastTexture()} + * @return current video presentation timestamp (PTS) in milliseconds of {@link #getLastTexture()} **/ public int getVideoPTS(); - + /** - * @return current audio presentation timestamp (PTS) in milliseconds. + * @return current audio presentation timestamp (PTS) in milliseconds. **/ public int getAudioPTS(); - + /** * {@inheritDoc} *

              @@ -511,7 +511,7 @@ public interface GLMediaPlayer extends TextureSequence { /** * {@inheritDoc} - * + * *

              * In case the current state is not {@link State#Playing}, {@link #getLastTexture()} is returned. *

              @@ -519,25 +519,25 @@ public interface GLMediaPlayer extends TextureSequence { * See audio and video synchronization. *

              * @throws IllegalStateException if not invoked in {@link State#Paused} or {@link State#Playing} - * + * * @see #addEventListener(GLMediaEventListener) * @see GLMediaEventListener#newFrameAvailable(GLMediaPlayer, TextureFrame, long) */ @Override public TextureSequence.TextureFrame getNextTexture(GL gl) throws IllegalStateException; - + /** Return the stream location, as set by {@link #initStream(URI, int, int, int)}. */ public URI getURI(); /** * Warning: Optional information, may not be supported by implementation. - * @return the code of the video stream, if available + * @return the code of the video stream, if available */ public String getVideoCodec(); /** * Warning: Optional information, may not be supported by implementation. - * @return the code of the audio stream, if available + * @return the code of the audio stream, if available */ public String getAudioCodec(); @@ -557,25 +557,25 @@ public interface GLMediaPlayer extends TextureSequence { * @return total duration of stream in msec. */ public int getDuration(); - + /** * Warning: Optional information, may not be supported by implementation. - * @return the overall bitrate of the stream. + * @return the overall bitrate of the stream. */ public long getStreamBitrate(); /** * Warning: Optional information, may not be supported by implementation. - * @return video bitrate + * @return video bitrate */ public int getVideoBitrate(); - + /** * Warning: Optional information, may not be supported by implementation. - * @return the audio bitrate + * @return the audio bitrate */ public int getAudioBitrate(); - + /** * Warning: Optional information, may not be supported by implementation. * @return the framerate of the video @@ -583,10 +583,10 @@ public interface GLMediaPlayer extends TextureSequence { public float getFramerate(); /** - * Returns true if the video frame is oriented in + * Returns true if the video frame is oriented in * OpenGL's coordinate system, origin at bottom left. *

              - * Otherwise returns false, i.e. + * Otherwise returns false, i.e. * video frame is oriented origin at top left. *

              *

              @@ -594,14 +594,14 @@ public interface GLMediaPlayer extends TextureSequence { * but user shall not rely on. *

              *

              - * false GL orientation leads to + * false GL orientation leads to * {@link Texture#getMustFlipVertically()} == true, * as reflected by all {@link TextureFrame}'s {@link Texture}s - * retrieved via {@link #getLastTexture()} or {@link #getNextTexture(GL)}. + * retrieved via {@link #getLastTexture()} or {@link #getNextTexture(GL)}. *

              */ public boolean isGLOriented(); - + /** Returns the width of the video. */ public int getWidth(); @@ -613,7 +613,7 @@ public interface GLMediaPlayer extends TextureSequence { /** Returns a string represantation of this player's performance values. */ public String getPerfString(); - + /** Adds a {@link GLMediaEventListener} to this player. */ public void addEventListener(GLMediaEventListener l); diff --git a/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayerFactory.java b/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayerFactory.java index c7e1ab5e6..248e265f5 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayerFactory.java +++ b/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayerFactory.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -36,7 +36,7 @@ public class GLMediaPlayerFactory { private static final String FFMPEGMediaPlayerClazzName = "jogamp.opengl.util.av.impl.FFMPEGMediaPlayer"; private static final String OMXGLMediaPlayerClazzName = "jogamp.opengl.util.av.impl.OMXGLMediaPlayer"; private static final String isAvailableMethodName = "isAvailable"; - + public static GLMediaPlayer createDefault() { final ClassLoader cl = GLMediaPlayerFactory.class.getClassLoader(); GLMediaPlayer sink = create(cl, OMXGLMediaPlayerClazzName); @@ -54,7 +54,7 @@ public class GLMediaPlayerFactory { public static GLMediaPlayer createNull() { return new NullGLMediaPlayer(); } - + public static GLMediaPlayer create(final ClassLoader cl, String implName) { try { if(((Boolean)ReflectionUtil.callStaticMethod(implName, isAvailableMethodName, null, null, cl)).booleanValue()) { diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java b/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java index 9d2ef6572..fb2bdbbcb 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -41,22 +41,22 @@ import javax.media.opengl.GL; import com.jogamp.common.nio.Buffers; import com.jogamp.opengl.util.GLPixelBuffer; -/** - * AWT {@link GLPixelBuffer} backed by an {@link BufferedImage} of type +/** + * AWT {@link GLPixelBuffer} backed by an {@link BufferedImage} of type * {@link BufferedImage#TYPE_INT_ARGB} or {@link BufferedImage#TYPE_INT_RGB}. *

              * Implementation uses an array backed {@link IntBuffer}. *

              *

              - * {@link AWTGLPixelBuffer} can be produced via {@link AWTGLPixelBufferProvider}'s - * {@link AWTGLPixelBufferProvider#allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocate(..)}. + * {@link AWTGLPixelBuffer} can be produced via {@link AWTGLPixelBufferProvider}'s + * {@link AWTGLPixelBufferProvider#allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocate(..)}. *

              *

              * See {@link AWTGLPixelBuffer#requiresNewBuffer(GL, int, int, int)} for {@link #allowRowStride} details. *

              *

              * If using allowRowStride == true, user may needs to get the {@link #getAlignedImage(int, int) aligned image} - * since {@link #requiresNewBuffer(GL, int, int, int)} will allow different width in this case. + * since {@link #requiresNewBuffer(GL, int, int, int)} will allow different width in this case. *

              */ public class AWTGLPixelBuffer extends GLPixelBuffer { @@ -65,9 +65,9 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { /** The underlying {@link BufferedImage}. */ public final BufferedImage image; - + /** - * + * * @param pixelAttributes the desired {@link GLPixelAttributes} * @param width in pixels * @param height in pixels @@ -76,26 +76,26 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { * @param image the AWT image * @param buffer the backing array * @param allowRowStride If true, allow row-stride, otherwise not. See {@link #requiresNewBuffer(GL, int, int, int)}. - * If true, user shall decide whether to use a {@link #getAlignedImage(int, int) width-aligned image}. + * If true, user shall decide whether to use a {@link #getAlignedImage(int, int) width-aligned image}. */ - public AWTGLPixelBuffer(GLPixelAttributes pixelAttributes, int width, int height, int depth, boolean pack, BufferedImage image, + public AWTGLPixelBuffer(GLPixelAttributes pixelAttributes, int width, int height, int depth, boolean pack, BufferedImage image, Buffer buffer, boolean allowRowStride) { super(pixelAttributes, width, height, depth, pack, buffer, allowRowStride); this.image = image; } - + @Override public void dispose() { image.flush(); super.dispose(); } - + /** * Returns a width- and height-aligned image representation sharing data w/ {@link #image}. * @param width * @param height * @return - * @throws IllegalArgumentException if requested size exceeds image size + * @throws IllegalArgumentException if requested size exceeds image size */ public BufferedImage getAlignedImage(int width, int height) throws IllegalArgumentException { if( width * height > image.getWidth() * image.getHeight() ) { @@ -111,12 +111,12 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { final WritableRaster raster = image.getRaster(); final DataBuffer dataBuffer = raster.getDataBuffer(); final SinglePixelPackedSampleModel sppsm0 = (SinglePixelPackedSampleModel) raster.getSampleModel(); - final SinglePixelPackedSampleModel sppsm1 = new SinglePixelPackedSampleModel(dataBuffer.getDataType(), + final SinglePixelPackedSampleModel sppsm1 = new SinglePixelPackedSampleModel(dataBuffer.getDataType(), width, height, width /* scanLineStride */, sppsm0.getBitMasks()); final WritableRaster raster1 = WritableRaster.createWritableRaster(sppsm1, dataBuffer, null); return new BufferedImage (cm, raster1, cm.isAlphaPremultiplied(), null); } - + public StringBuilder toString(StringBuilder sb) { sb = super.toString(sb); sb.append(", allowRowStride ").append(allowRowStride).append(", image [").append(image.getWidth()).append("x").append(image.getHeight()).append(", ").append(image.toString()).append("]"); @@ -125,29 +125,29 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { public String toString() { return "AWTGLPixelBuffer["+toString(null).toString()+"]"; } - + /** * Provider for {@link AWTGLPixelBuffer} instances. */ public static class AWTGLPixelBufferProvider implements GLPixelBufferProvider { private final boolean allowRowStride; - + /** - * @param allowRowStride If true, allow row-stride, otherwise not. + * @param allowRowStride If true, allow row-stride, otherwise not. * See {@link #getAllowRowStride()} and {@link AWTGLPixelBuffer#requiresNewBuffer(GL, int, int, int)}. - * If true, user shall decide whether to use a {@link AWTGLPixelBuffer#getAlignedImage(int, int) width-aligned image}. + * If true, user shall decide whether to use a {@link AWTGLPixelBuffer#getAlignedImage(int, int) width-aligned image}. */ public AWTGLPixelBufferProvider(boolean allowRowStride) { - this.allowRowStride = allowRowStride; + this.allowRowStride = allowRowStride; } @Override public boolean getAllowRowStride() { return allowRowStride; } - + @Override public GLPixelAttributes getAttributes(GL gl, int componentCount) { return 4 == componentCount ? awtPixelAttributesIntRGBA4 : awtPixelAttributesIntRGB3; } - + /** * {@inheritDoc} *

              @@ -162,28 +162,28 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { return new AWTGLPixelBuffer(pixelAttributes, width, height, depth, pack, image, ibuffer, allowRowStride); } } - + /** * Provider for singleton {@link AWTGLPixelBuffer} instances. *

              * Provider instance holds the last {@link AWTGLPixelBuffer} instance * {@link #allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocated}. - * A new {@link #allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocation} + * A new {@link #allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocation} * will return same instance, if a new buffer is not {@link AWTGLPixelBuffer#requiresNewBuffer(GL, int, int, int) required}. - * The latter is true if size are compatible, hence allowRowStride should be enabled, if possible. + * The latter is true if size are compatible, hence allowRowStride should be enabled, if possible. *

              - */ + */ public static class SingleAWTGLPixelBufferProvider extends AWTGLPixelBufferProvider implements SingletonGLPixelBufferProvider { private AWTGLPixelBuffer singleRGBA4 = null; private AWTGLPixelBuffer singleRGB3 = null; - + /** * @param allowRowStride If true, allow row-stride, otherwise not. See {@link AWTGLPixelBuffer#requiresNewBuffer(GL, int, int, int)}. */ public SingleAWTGLPixelBufferProvider(boolean allowRowStride) { super(allowRowStride); } - + /** * {@inheritDoc} *

              @@ -194,7 +194,7 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { public AWTGLPixelBuffer allocate(GL gl, GLPixelAttributes pixelAttributes, int width, int height, int depth, boolean pack, int minByteSize) { if( 4 == pixelAttributes.componentCount ) { if( null == singleRGBA4 || singleRGBA4.requiresNewBuffer(gl, width, height, minByteSize) ) { - singleRGBA4 = allocateImpl(pixelAttributes, width, height, depth, pack, minByteSize); + singleRGBA4 = allocateImpl(pixelAttributes, width, height, depth, pack, minByteSize); } return singleRGBA4; } else { @@ -204,33 +204,33 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { return singleRGB3; } } - + private AWTGLPixelBuffer allocateImpl(GLPixelAttributes pixelAttributes, int width, int height, int depth, boolean pack, int minByteSize) { final BufferedImage image = new BufferedImage(width, height, 4 == pixelAttributes.componentCount ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB); final int[] readBackIntBuffer = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); final Buffer ibuffer = IntBuffer.wrap( readBackIntBuffer ); return new AWTGLPixelBuffer(pixelAttributes, width, height, depth, pack, image, ibuffer, getAllowRowStride()); } - - /** Return the last {@link #allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocated} {@link AWTGLPixelBuffer} w/ {@link GLPixelAttributes#componentCount}. */ + + /** Return the last {@link #allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocated} {@link AWTGLPixelBuffer} w/ {@link GLPixelAttributes#componentCount}. */ public AWTGLPixelBuffer getSingleBuffer(GLPixelAttributes pixelAttributes) { return 4 == pixelAttributes.componentCount ? singleRGBA4 : singleRGB3; } - - /** + + /** * Initializes the single {@link AWTGLPixelBuffer} w/ a given size, if not yet {@link #allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocated}. * @return the newly initialized single {@link AWTGLPixelBuffer}, or null if already allocated. */ public AWTGLPixelBuffer initSingleton(int componentCount, int width, int height, int depth, boolean pack) { if( 4 == componentCount ) { if( null != singleRGBA4 ) { - return null; + return null; } singleRGBA4 = allocateImpl(AWTGLPixelBuffer.awtPixelAttributesIntRGBA4, width, height, depth, pack, 0); return singleRGBA4; } else { if( null != singleRGB3 ) { - return null; + return null; } singleRGB3 = allocateImpl(AWTGLPixelBuffer.awtPixelAttributesIntRGB3, width, height, depth, pack, 0); return singleRGB3; diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLReadBufferUtil.java b/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLReadBufferUtil.java index e85f04092..f5d31a132 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLReadBufferUtil.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLReadBufferUtil.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -42,7 +42,7 @@ import com.jogamp.opengl.util.GLReadBufferUtil; public class AWTGLReadBufferUtil extends GLReadBufferUtil { /** * {@inheritDoc} - * + * * @param alpha */ public AWTGLReadBufferUtil(GLProfile glp, boolean alpha) { @@ -50,7 +50,7 @@ public class AWTGLReadBufferUtil extends GLReadBufferUtil { } public AWTGLPixelBuffer getAWTGLPixelBuffer() { return (AWTGLPixelBuffer)this.getPixelBuffer(); } - + public BufferedImage readPixelsToBufferedImage(GL gl, boolean awtOrientation) { return readPixelsToBufferedImage(gl, 0, 0, 0, 0, awtOrientation); } diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/ImageUtil.java b/src/jogl/classes/com/jogamp/opengl/util/awt/ImageUtil.java index a3139b16a..df3cc4a39 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/ImageUtil.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/ImageUtil.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 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 @@ -28,11 +28,11 @@ * 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. */ @@ -54,7 +54,7 @@ public class ImageUtil { WritableRaster raster = image.getRaster(); Object scanline1 = null; Object scanline2 = null; - + for (int i = 0; i < image.getHeight() / 2; i++) { scanline1 = raster.getDataElements(0, i, image.getWidth(), 1, scanline1); scanline2 = raster.getDataElements(0, image.getHeight() - i - 1, image.getWidth(), 1, scanline2); @@ -97,21 +97,21 @@ public class ImageUtil { if (thumbWidth > image.getWidth()) { throw new IllegalArgumentException("Thumbnail width must be greater than image width"); } - + if (thumbWidth == image.getWidth()) { return image; } - + float ratio = (float) image.getWidth() / (float) image.getHeight(); int width = image.getWidth(); BufferedImage thumb = image; - + do { width /= 2; if (width < thumbWidth) { width = thumbWidth; } - + BufferedImage temp = createCompatibleImage(width, (int) (width / ratio)); Graphics2D g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, @@ -120,7 +120,7 @@ public class ImageUtil { g2.dispose(); thumb = temp; } while (width != thumbWidth); - + return thumb; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/Overlay.java b/src/jogl/classes/com/jogamp/opengl/util/awt/Overlay.java index 73d694cd9..931f59869 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/Overlay.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/Overlay.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2006 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/Screenshot.java b/src/jogl/classes/com/jogamp/opengl/util/awt/Screenshot.java index 2ffc27260..f686b672a 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/Screenshot.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/Screenshot.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2013 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 @@ -29,7 +29,7 @@ * 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. @@ -56,18 +56,18 @@ import com.jogamp.opengl.GLExtensions; import com.jogamp.opengl.util.GLPixelStorageModes; import com.jogamp.opengl.util.TGAWriter; -/** +/** * Utilities for taking screenshots of OpenGL applications. - * @deprecated Please consider using {@link com.jogamp.opengl.util.GLReadBufferUtil}, - * which is AWT independent and does not require a CPU based vertical image flip + * @deprecated Please consider using {@link com.jogamp.opengl.util.GLReadBufferUtil}, + * which is AWT independent and does not require a CPU based vertical image flip * in case drawable {@link GLDrawable#isGLOriented() is in OpenGL orientation}. - * Further more you may use {@link AWTGLReadBufferUtil} to read out + * Further more you may use {@link AWTGLReadBufferUtil} to read out * the framebuffer into a BufferedImage for further AWT processing. */ public class Screenshot { private Screenshot() {} - /** + /** * Takes a fast screenshot of the current OpenGL drawable to a Targa * file. Requires the OpenGL context for the desired drawable to be * current. Takes the screenshot from the last assigned read buffer, @@ -94,7 +94,7 @@ public class Screenshot { writeToTargaFile(file, width, height, false); } - /** + /** * Takes a fast screenshot of the current OpenGL drawable to a Targa * file. Requires the OpenGL context for the desired drawable to be * current. Takes the screenshot from the last assigned read buffer, @@ -122,7 +122,7 @@ public class Screenshot { writeToTargaFile(file, 0, 0, width, height, alpha); } - /** + /** * Takes a fast screenshot of the current OpenGL drawable to a Targa * file. Requires the OpenGL context for the desired drawable to be * current. Takes the screenshot from the last assigned read buffer, @@ -410,5 +410,5 @@ public class Screenshot { if (!gl.isExtensionAvailable(GLExtensions.EXT_abgr)) { throw new IllegalArgumentException("Saving alpha channel requires GL_EXT_abgr"); } - } + } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java index c67141525..6e504c089 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java @@ -129,7 +129,7 @@ import jogamp.opengl.Debug; */ public class TextRenderer { private static final boolean DEBUG; - + static { Debug.initSingleton(); DEBUG = Debug.isPropertyDefined("jogl.debug.TextRenderer", true); @@ -200,10 +200,10 @@ public class TextRenderer { // Debugging purposes only private boolean debugged; Pipelined_QuadRenderer mPipelinedQuadRenderer; - + //emzic: added boolean flag private boolean useVertexArrays = true; - + //emzic: added boolean flag private boolean isExtensionAvailable_GL_VERSION_1_5; private boolean checkFor_isExtensionAvailable_GL_VERSION_1_5; @@ -707,7 +707,7 @@ public class TextRenderer { /** * emzic: here the call to glBindBuffer crashes on certain graphicscard/driver combinations * this is why the ugly try-catch block has been added, which falls back to the old textrenderer - * + * * @param ortho * @throws GLException */ @@ -891,7 +891,7 @@ public class TextRenderer { data.markUsed(); Rectangle2D origRect = data.origRect(); - + // Align the leftmost point of the baseline to the (x, y, z) coordinate requested renderer.draw3DRect(x - (scaleFactor * data.origOriginX()), y - (scaleFactor * ((float) origRect.getHeight() - data.origOriginY())), z, @@ -1715,7 +1715,7 @@ public class TextRenderer { return glyph; } } - + private static class CharacterCache { private CharacterCache() { } diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/TextureRenderer.java b/src/jogl/classes/com/jogamp/opengl/util/awt/TextureRenderer.java index 922fc69c1..26e1eb041 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/TextureRenderer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/TextureRenderer.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2006 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 @@ -29,11 +29,11 @@ * 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. */ @@ -407,7 +407,7 @@ public class TextureRenderer { this.a = a; gl.glColor4f(this.r, this.g, this.b, this.a); - } + } private float[] compArray; /** Changes the current color of this TextureRenderer to the @@ -437,7 +437,7 @@ public class TextureRenderer { @param screenx the on-screen x coordinate at which to draw the rectangle @param screeny the on-screen y coordinate (relative to lower left) at which to draw the rectangle - + @throws GLException If an OpenGL context is not current when this method is called */ public void drawOrthoRect(int screenx, int screeny) throws GLException { @@ -459,7 +459,7 @@ public class TextureRenderer { rectangle to draw @param width the width of the rectangle to draw @param height the height of the rectangle to draw - + @throws GLException If an OpenGL context is not current when this method is called */ public void drawOrthoRect(int screenx, int screeny, @@ -490,7 +490,7 @@ public class TextureRenderer { @param height the height in texels of the rectangle to draw @param scaleFactor the scale factor to apply (multiplicatively) to the size of the drawn rectangle - + @throws GLException If an OpenGL context is not current when this method is called */ public void draw3DRect(float x, float y, float z, @@ -518,7 +518,7 @@ public class TextureRenderer { OpenGL texture to the screen, if the application intends to draw them as a flat overlay on to the screen. Must be used if {@link #beginOrthoRendering} is used to set up the rendering stage for - this overlay. + this overlay. @throws GLException If an OpenGL context is not current when this method is called */ @@ -552,7 +552,7 @@ public class TextureRenderer { private void beginRendering(boolean ortho, int width, int height, boolean disableDepthTestForOrtho) { GL2 gl = GLContext.getCurrentGL().getGL2(); - int attribBits = + int attribBits = GL2.GL_ENABLE_BIT | GL2.GL_TEXTURE_BIT | GL2.GL_COLOR_BUFFER_BIT | (ortho ? (GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_TRANSFORM_BIT) : 0); gl.glPushAttrib(attribBits); @@ -622,7 +622,7 @@ public class TextureRenderer { // Infer the internal format if not an intensity texture int internalFormat = (intensity ? GL2.GL_INTENSITY : 0); - int imageType = + int imageType = (intensity ? BufferedImage.TYPE_BYTE_GRAY : (alpha ? BufferedImage.TYPE_INT_ARGB_PRE : BufferedImage.TYPE_INT_RGB)); image = new BufferedImage(width, height, imageType); diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/BitmapCharRec.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/BitmapCharRec.java index 34685e1b2..e8df6aaec 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/BitmapCharRec.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/BitmapCharRec.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ @@ -41,8 +41,8 @@ package com.jogamp.opengl.util.gl2; /* Copyright (c) Mark J. Kilgard, 1994, 1998. */ -/* This program is freely distributable without licensing fees - and is provided without guarantee or warrantee expressed or +/* This program is freely distributable without licensing fees + and is provided without guarantee or warrantee expressed or implied. This program is -not- in the public domain. */ class BitmapCharRec { diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/BitmapFontRec.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/BitmapFontRec.java index 18f7d3b28..d4ee12b32 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/BitmapFontRec.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/BitmapFontRec.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ @@ -41,8 +41,8 @@ package com.jogamp.opengl.util.gl2; /* Copyright (c) Mark J. Kilgard, 1994, 1998. */ -/* This program is freely distributable without licensing fees - and is provided without guarantee or warrantee expressed or +/* This program is freely distributable without licensing fees + and is provided without guarantee or warrantee expressed or implied. This program is -not- in the public domain. */ class BitmapFontRec { diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/CoordRec.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/CoordRec.java index 9ad95ec03..5e26e0d14 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/CoordRec.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/CoordRec.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ @@ -41,8 +41,8 @@ package com.jogamp.opengl.util.gl2; /* Copyright (c) Mark J. Kilgard, 1994, 1998. */ -/* This program is freely distributable without licensing fees - and is provided without guarantee or warrantee expressed or +/* This program is freely distributable without licensing fees + and is provided without guarantee or warrantee expressed or implied. This program is -not- in the public domain. */ class CoordRec { diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUT.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUT.java index 010ce6699..42529f3f1 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUT.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUT.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ @@ -163,7 +163,7 @@ public class GLUT { public void glutSolidCylinder(double radius, double height, int slices, int stacks) { GL2 gl = GLUgl2.getCurrentGL2(); - + // Prepare table of points for drawing end caps double [] x = new double[slices]; double [] y = new double[slices]; @@ -174,7 +174,7 @@ public class GLUT { x[i] = Math.cos(angle) * radius; y[i] = Math.sin(angle) * radius; } - + // Draw bottom cap gl.glBegin(GL2.GL_TRIANGLE_FAN); gl.glNormal3d(0,0,-1); @@ -184,7 +184,7 @@ public class GLUT { } gl.glVertex3d(x[0], y[0], 0); gl.glEnd(); - + // Draw top cap gl.glBegin(GL2.GL_TRIANGLE_FAN); gl.glNormal3d(0,0,1); @@ -194,7 +194,7 @@ public class GLUT { } gl.glVertex3d(x[0], y[0], height); gl.glEnd(); - + // Draw walls quadObjInit(glu); glu.gluQuadricDrawStyle(quadObj, GLU.GLU_FILL); @@ -262,7 +262,7 @@ public class GLUT { /** * Renders the teapot as a solid shape of the specified size. The teapot is * created in a way that replicates the C GLUT implementation. - * + * * @param scale * the factor by which to scale the teapot */ @@ -278,7 +278,7 @@ public class GLUT { * instead of the y=-1 plane). Both surface normals and texture coordinates * for the teapot are generated. The teapot is generated with OpenGL * evaluators. - * + * * @param scale * the factor by which to scale the teapot * @param cStyle @@ -292,14 +292,14 @@ public class GLUT { /** * Renders the teapot as a wireframe shape of the specified size. The teapot * is created in a way that replicates the C GLUT implementation. - * + * * @param scale * the factor by which to scale the teapot */ public void glutWireTeapot(double scale) { glutWireTeapot(scale, true); } - + /** * Renders the teapot as a wireframe shape of the specified size. The teapot * can either be created in a way that is backward-compatible with the @@ -308,7 +308,7 @@ public class GLUT { * plane, instead of the y=-1 plane). Both surface normals and texture * coordinates for the teapot are generated. The teapot is generated with * OpenGL evaluators. - * + * * @param scale * the factor by which to scale the teapot * @param cStyle @@ -356,7 +356,7 @@ public class GLUT { int[] skiprows = new int[1]; int[] skippixels = new int[1]; int[] alignment = new int[1]; - beginBitmap(gl, + beginBitmap(gl, swapbytes, lsbfirst, rowlength, @@ -367,7 +367,7 @@ public class GLUT { for (int i = 0; i < len; i++) { bitmapCharacterImpl(gl, font, string.charAt(i)); } - endBitmap(gl, + endBitmap(gl, swapbytes, lsbfirst, rowlength, @@ -502,7 +502,7 @@ public class GLUT { gl.glEnd( ); } } - + /** This function draws a solid-shaded dodecahedron whose facets are rhombic and @@ -522,7 +522,7 @@ public class GLUT { } gl.glEnd( ); } - + //---------------------------------------------------------------------- // Internals only below this point // @@ -879,7 +879,7 @@ public class GLUT { } /* rhombic dodecahedron data: */ - + private static final double rdod_r[][] = { { 0.0, 0.0, 1.0 }, @@ -897,7 +897,7 @@ public class GLUT { { 0.000000000000, -0.707106781187, -0.5 }, { 0.0, 0.0, -1.0 } }; - + private static final int rdod_v[][] = { { 0, 1, 5, 2 }, @@ -913,7 +913,7 @@ public class GLUT { { 7, 11, 13, 12 }, { 8, 12, 13, 9 } }; - + private static final double rdod_n[][] = { { 0.353553390594, 0.353553390594, 0.5 }, @@ -929,7 +929,7 @@ public class GLUT { { -0.353553390594, -0.353553390594, -0.5 }, { 0.353553390594, -0.353553390594, -0.5 } }; - + /* tetrahedron data: */ private static final float T = 1.73205080756887729f; @@ -1124,7 +1124,7 @@ public class GLUT { float[] r = new float[4*4*3]; float[] s = new float[4*4*3]; int i, j, k, l; - + gl.glPushAttrib(GL2.GL_ENABLE_BIT | GL2.GL_EVAL_BIT | GL2.GL_POLYGON_BIT); gl.glEnable(GL2.GL_AUTO_NORMAL); gl.glEnable(GL2.GL_NORMALIZE); @@ -1183,7 +1183,7 @@ public class GLUT { gl.glPopMatrix(); gl.glPopAttrib(); } - + private static void evaluateTeapotMesh(GL2 gl, int grid, int type, diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmap8x13.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmap8x13.java index 07ded652a..c24483777 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmap8x13.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmap8x13.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmap9x15.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmap9x15.java index 5d357f3f7..62af3b631 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmap9x15.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmap9x15.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica10.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica10.java index b9c7e6e50..5f06d697e 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica10.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica10.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica12.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica12.java index bc86f6216..8326d6461 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica12.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica12.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica18.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica18.java index 1b2e69ba4..cb11f6bec 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica18.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapHelvetica18.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapTimesRoman10.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapTimesRoman10.java index f753b56f7..17cbd0796 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapTimesRoman10.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapTimesRoman10.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapTimesRoman24.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapTimesRoman24.java index 073e6e673..9cc2bdc3a 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapTimesRoman24.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTBitmapTimesRoman24.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTStrokeMonoRoman.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTStrokeMonoRoman.java index b8296924e..3587ca992 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTStrokeMonoRoman.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTStrokeMonoRoman.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTStrokeRoman.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTStrokeRoman.java index 94fa1c4fd..cf51ddd3c 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTStrokeRoman.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/GLUTStrokeRoman.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeCharRec.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeCharRec.java index af3d538ae..515212f0e 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeCharRec.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeCharRec.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ @@ -41,8 +41,8 @@ package com.jogamp.opengl.util.gl2; /* Copyright (c) Mark J. Kilgard, 1994, 1998. */ -/* This program is freely distributable without licensing fees - and is provided without guarantee or warrantee expressed or +/* This program is freely distributable without licensing fees + and is provided without guarantee or warrantee expressed or implied. This program is -not- in the public domain. */ class StrokeCharRec { diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeFontRec.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeFontRec.java index d3195f24d..5335c8523 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeFontRec.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeFontRec.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ @@ -41,8 +41,8 @@ package com.jogamp.opengl.util.gl2; /* Copyright (c) Mark J. Kilgard, 1994, 1998. */ -/* This program is freely distributable without licensing fees - and is provided without guarantee or warrantee expressed or +/* This program is freely distributable without licensing fees + and is provided without guarantee or warrantee expressed or implied. This program is -not- in the public domain. */ class StrokeFontRec { diff --git a/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeRec.java b/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeRec.java index 8796e8b08..b0c91c696 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeRec.java +++ b/src/jogl/classes/com/jogamp/opengl/util/gl2/StrokeRec.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ @@ -41,14 +41,14 @@ package com.jogamp.opengl.util.gl2; /* Copyright (c) Mark J. Kilgard, 1994, 1998. */ -/* This program is freely distributable without licensing fees - and is provided without guarantee or warrantee expressed or +/* This program is freely distributable without licensing fees + and is provided without guarantee or warrantee expressed or implied. This program is -not- in the public domain. */ class StrokeRec { public int num_coords; public CoordRec[] coord; - + public StrokeRec(int num_coords, CoordRec[] coord) { this.num_coords = num_coords; diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java index edc3d2677..68c1d0fec 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java @@ -62,7 +62,7 @@ import com.jogamp.common.util.VersionNumber; * A documented example of how to use this code is available * {@link #create(GL2ES2, int, Class, String, String, String, boolean) here} and * {@link #create(GL2ES2, int, int, Class, String, String[], String, String) here}. - *

              + *

              */ public class ShaderCode { public static final boolean DEBUG = Debug.debug("GLSLCode"); @@ -70,22 +70,22 @@ public class ShaderCode { /** Unique resource suffix for {@link GL2ES2#GL_VERTEX_SHADER} in source code: vp */ public static final String SUFFIX_VERTEX_SOURCE = "vp" ; - + /** Unique resource suffix for {@link GL2ES2#GL_VERTEX_SHADER} in binary: bvp */ public static final String SUFFIX_VERTEX_BINARY = "bvp" ; - + /** Unique resource suffix for {@link GL3#GL_GEOMETRY_SHADER} in source code: gp */ public static final String SUFFIX_GEOMETRY_SOURCE = "gp" ; - + /** Unique resource suffix for {@link GL3#GL_GEOMETRY_SHADER} in binary: bgp */ public static final String SUFFIX_GEOMETRY_BINARY = "bgp" ; - + /** Unique resource suffix for {@link GL2ES2#GL_FRAGMENT_SHADER} in source code: fp */ public static final String SUFFIX_FRAGMENT_SOURCE = "fp" ; - + /** Unique resource suffix for {@link GL2ES2#GL_FRAGMENT_SHADER} in binary: bfp */ public static final String SUFFIX_FRAGMENT_BINARY = "bfp" ; - + /** Unique relative path for binary shader resources for {@link GLES2#GL_NVIDIA_PLATFORM_BINARY_NV NVIDIA}: nvidia */ public static final String SUB_PATH_NVIDIA = "nvidia" ; @@ -94,7 +94,7 @@ public class ShaderCode { * @param count number of shaders * @param source CharSequence array containing the shader sources, organized as source[count][strings-per-shader]. * May be either an immutable String - or mutable StringBuilder array. - * + * * @throws IllegalArgumentException if count and source.length do not match */ public ShaderCode(int type, int count, CharSequence[][] source) { @@ -125,7 +125,7 @@ public class ShaderCode { /** * @param type either {@link GL2ES2#GL_VERTEX_SHADER}, {@link GL2ES2#GL_FRAGMENT_SHADER} or {@link GL3#GL_GEOMETRY_SHADER} * @param count number of shaders - * @param binary binary buffer containing the shader binaries, + * @param binary binary buffer containing the shader binaries, */ public ShaderCode(int type, int count, int binFormat, Buffer binary) { switch (type) { @@ -147,19 +147,19 @@ public class ShaderCode { /** * Creates a complete {@link ShaderCode} object while reading all shader source of sourceFiles, * which location is resolved using the context class, see {@link #readShaderSource(Class, String)}. - * + * * @param gl current GL object to determine whether a shader compiler is available. If null, no validation is performed. * @param type either {@link GL2ES2#GL_VERTEX_SHADER}, {@link GL2ES2#GL_FRAGMENT_SHADER} or {@link GL3#GL_GEOMETRY_SHADER} * @param count number of shaders * @param context class used to help resolving the source location * @param sourceFiles array of source locations, organized as sourceFiles[count] * @param mutableStringBuilder if true method returns a mutable StringBuilder instance - * which can be edited later on at the costs of a String conversion when passing to + * which can be edited later on at the costs of a String conversion when passing to * {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}. * If false method returns an immutable String instance, * which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)} * at no additional costs. - * + * * @throws IllegalArgumentException if count and sourceFiles.length do not match * @see #readShaderSource(Class, String) */ @@ -192,16 +192,16 @@ public class ShaderCode { /** * Creates a complete {@link ShaderCode} object while reading the shader binary of binaryFile, * which location is resolved using the context class, see {@link #readShaderBinary(Class, String)}. - * + * * @param type either {@link GL2ES2#GL_VERTEX_SHADER}, {@link GL2ES2#GL_FRAGMENT_SHADER} or {@link GL3#GL_GEOMETRY_SHADER} * @param count number of shaders * @param context class used to help resolving the source location * @param binFormat a valid native binary format as they can be queried by {@link ShaderUtil#getShaderBinaryFormats(GL)}. * @param sourceFiles array of source locations, organized as sourceFiles[count] - * + * * @see #readShaderBinary(Class, String) * @see ShaderUtil#getShaderBinaryFormats(GL) - */ + */ public static ShaderCode create(int type, int count, Class context, int binFormat, String binaryFile) { ByteBuffer shaderBinary = null; if(null!=binaryFile && 0<=binFormat) { @@ -231,12 +231,12 @@ public class ShaderCode { *
            • {@link GL2ES2#GL_VERTEX_SHADER vertex}: {@link #SUFFIX_VERTEX_BINARY}
            • *
            • {@link GL2ES2#GL_FRAGMENT_SHADER fragment}: {@link #SUFFIX_FRAGMENT_BINARY}
            • *
            • {@link GL3#GL_GEOMETRY_SHADER geometry}: {@link #SUFFIX_GEOMETRY_BINARY}
            - *
          - * @param binary true for a binary resource, false for a source resource + * + * @param binary true for a binary resource, false for a source resource * @param type either {@link GL2ES2#GL_VERTEX_SHADER}, {@link GL2ES2#GL_FRAGMENT_SHADER} or {@link GL3#GL_GEOMETRY_SHADER} - * + * * @throws GLException if type is not supported - * + * * @see #create(GL2ES2, int, Class, String, String, String, boolean) */ public static String getFileSuffix(boolean binary, int type) { @@ -252,16 +252,16 @@ public class ShaderCode { } } - /** + /** * Returns a unique relative path for binary shader resources as follows: *
            *
          • {@link GLES2#GL_NVIDIA_PLATFORM_BINARY_NV NVIDIA}: {@link #SUB_PATH_NVIDIA}
          • *
          - * + * * @throws GLException if binFormat is not supported - * + * * @see #create(GL2ES2, int, Class, String, String, String, boolean) - */ + */ public static String getBinarySubPath(int binFormat) { switch (binFormat) { case GLES2.GL_NVIDIA_PLATFORM_BINARY_NV: @@ -272,42 +272,42 @@ public class ShaderCode { } /** - * Convenient creation method for instantiating a complete {@link ShaderCode} object - * either from source code using {@link #create(GL2ES2, int, int, Class, String[])}, + * Convenient creation method for instantiating a complete {@link ShaderCode} object + * either from source code using {@link #create(GL2ES2, int, int, Class, String[])}, * or from a binary code using {@link #create(int, int, Class, int, String)}, * whatever is available first. *

          - * The source and binary location names are expected w/o suffixes which are + * The source and binary location names are expected w/o suffixes which are * resolved and appended using {@link #getFileSuffix(boolean, int)}. *

          *

          * Additionally, the binary resource is expected within a subfolder of binRoot * which reflects the vendor specific binary format, see {@link #getBinarySubPath(int)}. * All {@link ShaderUtil#getShaderBinaryFormats(GL)} are being iterated - * using the binary subfolder, the first existing resource is being used. + * using the binary subfolder, the first existing resource is being used. *

          - * + * * Example: *
                *   Your std JVM layout (plain or within a JAR):
          -     *   
          +     *
                *      org/test/glsl/MyShaderTest.class
                *      org/test/glsl/shader/vertex.vp
                *      org/test/glsl/shader/fragment.fp
                *      org/test/glsl/shader/bin/nvidia/vertex.bvp
                *      org/test/glsl/shader/bin/nvidia/fragment.bfp
          -     *      
          +     *
                *   Your Android APK layout:
          -     *   
          +     *
                *      classes.dex
                *      assets/org/test/glsl/shader/vertex.vp
                *      assets/org/test/glsl/shader/fragment.fp
                *      assets/org/test/glsl/shader/bin/nvidia/vertex.bvp
                *      assets/org/test/glsl/shader/bin/nvidia/fragment.bfp
                *      ...
          -     *   
          +     *
                *   Your invocation in org/test/glsl/MyShaderTest.java:
          -     *   
          +     *
                *      ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, this.getClass(),
                *                                         "shader", new String[] { "vertex" }, "shader/bin", "vertex");
                *      ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, this.getClass(),
          @@ -318,11 +318,11 @@ public class ShaderCode {
                *      st.attachShaderProgram(gl, sp0, true);
                * 
          * A simplified entry point is {@link #create(GL2ES2, int, Class, String, String, String, boolean)}. - * + * *

          * The location is finally being resolved using the context class, see {@link #readShaderBinary(Class, String)}. *

          - * + * * @param gl current GL object to determine whether a shader compiler is available (if source is used), * or to determine the shader binary format (if binary is used). * @param type either {@link GL2ES2#GL_VERTEX_SHADER}, {@link GL2ES2#GL_FRAGMENT_SHADER} or {@link GL3#GL_GEOMETRY_SHADER} @@ -333,22 +333,22 @@ public class ShaderCode { * @param binRoot relative root path for binBasenames * @param binBasename basename w/o path or suffix relative to binRoot for the shader's binary code * @param mutableStringBuilder if true method returns a mutable StringBuilder instance - * which can be edited later on at the costs of a String conversion when passing to + * which can be edited later on at the costs of a String conversion when passing to * {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}. * If false method returns an immutable String instance, * which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)} * at no additional costs. - * + * * @throws IllegalArgumentException if count and srcBasenames.length do not match - * + * * @see #create(GL2ES2, int, int, Class, String[]) * @see #create(int, int, Class, int, String) * @see #readShaderSource(Class, String) * @see #getFileSuffix(boolean, int) * @see ShaderUtil#getShaderBinaryFormats(GL) * @see #getBinarySubPath(int) - */ - public static ShaderCode create(GL2ES2 gl, int type, int count, Class context, + */ + public static ShaderCode create(GL2ES2 gl, int type, int count, Class context, String srcRoot, String[] srcBasenames, String binRoot, String binBasename, boolean mutableStringBuilder) { ShaderCode res = null; @@ -391,28 +391,28 @@ public class ShaderCode { /** * Simplified variation of {@link #create(GL2ES2, int, int, Class, String, String[], String, String)}. *
          - * + * * Example: *
                *   Your std JVM layout (plain or within a JAR):
          -     *   
          +     *
                *      org/test/glsl/MyShaderTest.class
                *      org/test/glsl/shader/vertex.vp
                *      org/test/glsl/shader/fragment.fp
                *      org/test/glsl/shader/bin/nvidia/vertex.bvp
                *      org/test/glsl/shader/bin/nvidia/fragment.bfp
          -     *      
          +     *
                *   Your Android APK layout:
          -     *   
          +     *
                *      classes.dex
                *      assets/org/test/glsl/shader/vertex.vp
                *      assets/org/test/glsl/shader/fragment.fp
                *      assets/org/test/glsl/shader/bin/nvidia/vertex.bvp
                *      assets/org/test/glsl/shader/bin/nvidia/fragment.bfp
                *      ...
          -     *   
          +     *
                *   Your invocation in org/test/glsl/MyShaderTest.java:
          -     *   
          +     *
                *      ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(),
                *                                         "shader", "shader/bin", "vertex");
                *      ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(),
          @@ -422,7 +422,7 @@ public class ShaderCode {
                *      sp0.add(gl, fp0, System.err);
                *      st.attachShaderProgram(gl, sp0, true);
                * 
          - * + * * @param gl current GL object to determine whether a shader compiler is available (if source is used), * or to determine the shader binary format (if binary is used). * @param type either {@link GL2ES2#GL_VERTEX_SHADER}, {@link GL2ES2#GL_FRAGMENT_SHADER} or {@link GL3#GL_GEOMETRY_SHADER} @@ -433,20 +433,20 @@ public class ShaderCode { * @param basenames basename w/o path or suffix relative to srcRoot and binRoot * for the shader's source and binary code. * @param mutableStringBuilder if true method returns a mutable StringBuilder instance - * which can be edited later on at the costs of a String conversion when passing to + * which can be edited later on at the costs of a String conversion when passing to * {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}. * If false method returns an immutable String instance, * which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)} * at no additional costs. * @throws IllegalArgumentException if count is not 1 - * + * * @see #create(GL2ES2, int, int, Class, String, String[], String, String) - */ - public static ShaderCode create(GL2ES2 gl, int type, Class context, + */ + public static ShaderCode create(GL2ES2 gl, int type, Class context, String srcRoot, String binRoot, String basename, boolean mutableStringBuilder) { - return create(gl, type, 1, context, srcRoot, new String[] { basename }, binRoot, basename, mutableStringBuilder ); + return create(gl, type, 1, context, srcRoot, new String[] { basename }, binRoot, basename, mutableStringBuilder ); } - + /** * returns the uniq shader id as an integer */ @@ -455,7 +455,7 @@ public class ShaderCode { public int shaderType() { return shaderType; } public String shaderTypeStr() { return shaderTypeStr(shaderType); } - public static String shaderTypeStr(int type) { + public static String shaderTypeStr(int type) { switch (type) { case GL2ES2.GL_VERTEX_SHADER: return "VERTEX_SHADER"; @@ -553,7 +553,7 @@ public class ShaderCode { } else { CharSequence[] src = shaderSource[i]; int lineno=0; - + for(int j=0; jdata after the line containing tag. *

          * Note: The shader source to be edit must be created using a mutable StringBuilder. *

          - * + * * @param shaderIdx the shader index to be used. * @param tag search string * @param fromIndex start search tag begininig with this index * @param data the text to be inserted. Shall end with an EOL '\n' character. * @return index after the inserted data - * + * * @throws IllegalStateException if the shader source's CharSequence is immutable, i.e. not of type StringBuilder */ public int insertShaderSource(int shaderIdx, String tag, int fromIndex, CharSequence data) { @@ -595,7 +595,7 @@ public class ShaderCode { final int sourceCount = (null!=shaderSource)?shaderSource.length:0; if(shaderIdx>=sourceCount) { throw new IndexOutOfBoundsException("shaderIdx not within source bounds [0.."+(sourceCount-1)+"]: "+shaderIdx); - } + } final CharSequence[] src = shaderSource[shaderIdx]; int curEndIndex = 0; for(int j=0; joldName
          with newName in all shader sources. *

          * In case oldName and newName are equal, no action is performed. - *

          + *

          *

          * Note: The shader source to be edit must be created using a mutable StringBuilder. *

          - * + * * @param oldName the to be replace string * @param newName the replacement string * @return the number of replacements - * + * * @throws IllegalStateException if the shader source's CharSequence is immutable, i.e. not of type StringBuilder */ public int replaceInShaderSource(String oldName, String newName) { @@ -675,18 +675,18 @@ public class ShaderCode { } return num; } - + /** * Adds data at offset in shader source for shader shaderIdx. *

          * Note: The shader source to be edit must be created using a mutable StringBuilder. *

          - * + * * @param shaderIdx the shader index to be used. * @param position in shader source segments of shader shaderIdx * @param data the text to be inserted. Shall end with an EOL '\n' character * @return index after the inserted data - * + * * @throws IllegalStateException if the shader source's CharSequence is immutable, i.e. not of type StringBuilder */ public int insertShaderSource(int shaderIdx, int position, CharSequence data) { @@ -700,7 +700,7 @@ public class ShaderCode { final int sourceCount = (null!=shaderSource)?shaderSource.length:0; if(shaderIdx>=sourceCount) { throw new IndexOutOfBoundsException("shaderIdx not within source bounds [0.."+(sourceCount-1)+"]: "+shaderIdx); - } + } final CharSequence[] src = shaderSource[shaderIdx]; int curEndIndex = 0; for(int j=0; j context, URLConnection conn, StringBuilder result) throws IOException { readShaderSource(context, conn, result, 0); } - + /** * Reads shader source located in path, * either relative to the context class or absolute as-is. @@ -774,21 +774,21 @@ public class ShaderCode { * Final location lookup is performed via {@link ClassLoader#getResource(String)} and {@link ClassLoader#getSystemResource(String)}, * see {@link IOUtil#getResource(Class, String)}. *

          - * + * * @param context class used to help resolve the source location * @param path location of shader source * @param mutableStringBuilder if true method returns a mutable StringBuilder instance - * which can be edited later on at the costs of a String conversion when passing to + * which can be edited later on at the costs of a String conversion when passing to * {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}. * If false method returns an immutable String instance, * which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)} * at no additional costs. - * @throws IOException - * + * @throws IOException + * * @see IOUtil#getResource(Class, String) - */ + */ public static CharSequence readShaderSource(Class context, String path, boolean mutableStringBuilder) throws IOException { - URLConnection conn = IOUtil.getResource(context, path); + URLConnection conn = IOUtil.getResource(context, path); if (conn == null) { return null; } @@ -798,17 +798,17 @@ public class ShaderCode { } /** - * Reads shader binary located in path, + * Reads shader binary located in path, * either relative to the context class or absolute as-is. *

          * Final location lookup is perfomed via {@link ClassLoader#getResource(String)} and {@link ClassLoader#getSystemResource(String)}, * see {@link IOUtil#getResource(Class, String)}. *

          - * + * * @param context class used to help resolve the source location * @param path location of shader binary - * @throws IOException - * + * @throws IOException + * * @see IOUtil#getResource(Class, String) */ public static ByteBuffer readShaderBinary(Class context, String path) throws IOException { @@ -824,41 +824,41 @@ public class ShaderCode { } } - // Shall we use: #ifdef GL_FRAGMENT_PRECISION_HIGH .. #endif for using highp in fragment shader if avail ? + // Shall we use: #ifdef GL_FRAGMENT_PRECISION_HIGH .. #endif for using highp in fragment shader if avail ? /** Default precision of {@link GL#isGLES2() ES2} for {@link GL2ES2#GL_VERTEX_SHADER vertex-shader}: {@value #es2_default_precision_vp} */ public static final String es2_default_precision_vp = "\nprecision highp float;\nprecision highp int;\n"; /** Default precision of {@link GL#isGLES2() ES2} for {@link GL2ES2#GL_FRAGMENT_SHADER fragment-shader}: {@value #es2_default_precision_fp} */ public static final String es2_default_precision_fp = "\nprecision mediump float;\nprecision mediump int;\n/*precision lowp sampler2D;*/\n"; - + /** Default precision of GLSL ≥ 1.30 as required until < 1.50 for {@link GL2ES2#GL_VERTEX_SHADER vertex-shader} or {@link GL3#GL_GEOMETRY_SHADER geometry-shader}: {@value #gl3_default_precision_vp_gp}. See GLSL Spec 1.30-1.50 Section 4.5.3. */ public static final String gl3_default_precision_vp_gp = "\nprecision highp float;\nprecision highp int;\n"; /** Default precision of GLSL ≥ 1.30 as required until < 1.50 for {@link GL2ES2#GL_FRAGMENT_SHADER fragment-shader}: {@value #gl3_default_precision_fp}. See GLSL Spec 1.30-1.50 Section 4.5.3. */ public static final String gl3_default_precision_fp = "\nprecision highp float;\nprecision mediump int;\n/*precision mediump sampler2D;*/\n"; - + /** Prefer enable over require, since it won't force a failure. */ public static final String extOESDerivativesEnable = "#extension GL_OES_standard_derivatives : enable\n"; - + /** * Add GLSL version at the head of this shader source code. *

          * Note: The shader source to be edit must be created using a mutable StringBuilder. *

          - * @param gl a GL context, which must have been made current once + * @param gl a GL context, which must have been made current once * @return the index after the inserted data, maybe 0 if nothing has be inserted. */ public final int addGLSLVersion(GL2ES2 gl) { return insertShaderSource(0, 0, gl.getContext().getGLSLVersionString()); } - + /** * Adds default precision to source code at given position if required, i.e. - * {@link #es2_default_precision_vp}, {@link #es2_default_precision_fp}, + * {@link #es2_default_precision_vp}, {@link #es2_default_precision_fp}, * {@link #gl3_default_precision_vp_gp}, {@link #gl3_default_precision_fp} or none, * depending on the {@link GLContext#getGLSLVersionNumber() GLSL version} being used. *

          * Note: The shader source to be edit must be created using a mutable StringBuilder. *

          - * @param gl a GL context, which must have been made current once + * @param gl a GL context, which must have been made current once * @param pos position within this mutable shader source. * @return the index after the inserted data, maybe 0 if nothing has be inserted. */ @@ -871,7 +871,7 @@ public class ShaderCode { case GL2ES2.GL_FRAGMENT_SHADER: defaultPrecision = es2_default_precision_vp; break; default: - defaultPrecision = null; + defaultPrecision = null; break; } } else if( requiresGL3DefaultPrecision(gl) ) { @@ -883,7 +883,7 @@ public class ShaderCode { case GL2ES2.GL_FRAGMENT_SHADER: defaultPrecision = gl3_default_precision_fp; break; default: - defaultPrecision = null; + defaultPrecision = null; break; } } else { @@ -894,7 +894,7 @@ public class ShaderCode { } return pos; } - + /** Returns true, if GLSL version requires default precision, i.e. ES2 or GLSL [1.30 .. 1.50[. */ public static final boolean requiresDefaultPrecision(GL2ES2 gl) { if( gl.isGLES2() ) { @@ -902,7 +902,7 @@ public class ShaderCode { } return requiresGL3DefaultPrecision(gl); } - + /** Returns true, if GL3 GLSL version requires default precision, i.e. GLSL [1.30 .. 1.50[. */ public static final boolean requiresGL3DefaultPrecision(GL2ES2 gl) { if( gl.isGL3() ) { @@ -912,16 +912,16 @@ public class ShaderCode { return false; } } - + /** * Default customization of this shader source code. *

          * Note: The shader source to be edit must be created using a mutable StringBuilder. *

          - * @param gl a GL context, which must have been made current once + * @param gl a GL context, which must have been made current once * @param preludeVersion if true {@link GLContext#getGLSLVersionString()} is preluded, otherwise not. - * @param addDefaultPrecision if true default precision source code line(s) are added, i.e. - * {@link #es2_default_precision_vp}, {@link #es2_default_precision_fp}, + * @param addDefaultPrecision if true default precision source code line(s) are added, i.e. + * {@link #es2_default_precision_vp}, {@link #es2_default_precision_fp}, * {@link #gl3_default_precision_vp_gp}, {@link #gl3_default_precision_fp} or none, * depending on the {@link GLContext#getGLSLVersionNumber() GLSL version} being used. * @return the index after the inserted data, maybe 0 if nothing has be inserted. @@ -940,13 +940,13 @@ public class ShaderCode { } return pos; } - + /** * Default customization of this shader source code. *

          * Note: The shader source to be edit must be created using a mutable StringBuilder. *

          - * @param gl a GL context, which must have been made current once + * @param gl a GL context, which must have been made current once * @param preludeVersion if true {@link GLContext#getGLSLVersionString()} is preluded, otherwise not. * @param esDefaultPrecision optional default precision source code line(s) preluded if not null and if {@link GL#isGLES()}. * You may use {@link #es2_default_precision_fp} for fragment shader and {@link #es2_default_precision_vp} for vertex shader. @@ -967,8 +967,8 @@ public class ShaderCode { pos = addDefaultShaderPrecision(gl, pos); } return pos; - } - + } + //---------------------------------------------------------------------- // Internals only below this point // diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderProgram.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderProgram.java index 1337a7e2b..d737d6f4e 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderProgram.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderProgram.java @@ -37,7 +37,7 @@ import java.util.Iterator; import java.io.PrintStream; public class ShaderProgram { - + public ShaderProgram() { id = getNextID(); } @@ -111,7 +111,7 @@ public class ShaderProgram { /** * Adds a new shader to this program. - * + * *

          This command does not compile and attach the shader, * use {@link #add(GL2ES2, ShaderCode)} for this purpose.

          */ @@ -122,7 +122,7 @@ public class ShaderProgram { public synchronized boolean contains(ShaderCode shaderCode) { return allShaderCode.contains(shaderCode); } - + /** * Warning slow O(n) operation .. * @param id @@ -145,9 +145,9 @@ public class ShaderProgram { /** * Creates the empty GL program object using {@link GL2ES2#glCreateProgram()}, * if not already created. - * + * * @param gl - * @return true if shader program is valid, i.e. not zero + * @return true if shader program is valid, i.e. not zero */ public synchronized final boolean init(GL2ES2 gl) { if( 0 == shaderProgram ) { @@ -155,12 +155,12 @@ public class ShaderProgram { } return 0 != shaderProgram; } - + /** * Adds a new shader to a this non running program. * *

          Compiles and attaches the shader, if not done yet.

          - * + * * @return true if the shader was successfully added, false if compilation failed. */ public synchronized boolean add(GL2ES2 gl, ShaderCode shaderCode, PrintStream verboseOut) { @@ -179,11 +179,11 @@ public class ShaderProgram { /** * Replace a shader in a program and re-links the program. * - * @param gl + * @param gl * @param oldShader the to be replace Shader * @param newShader the new ShaderCode * @param verboseOut the optional verbose output stream - * + * * @return true if all steps are valid, shader compilation, attachment and linking; otherwise false. * * @see ShaderState#glEnableVertexAttribArray @@ -199,25 +199,25 @@ public class ShaderProgram { if(!init(gl) || !newShader.compile(gl, verboseOut)) { return false; } - + boolean shaderWasInUse = inUse(); if(shaderWasInUse) { useProgram(gl, false); } - + if(null != oldShader && allShaderCode.remove(oldShader)) { if(attachedShaderCode.remove(oldShader)) { ShaderUtil.detachShader(gl, shaderProgram, oldShader.shader()); } } - + add(newShader); if(attachedShaderCode.add(newShader)) { ShaderUtil.attachShader(gl, shaderProgram, newShader.shader()); } - + gl.glLinkProgram(shaderProgram); - + programLinked = ShaderUtil.isProgramLinkStatusValid(gl, shaderProgram, System.err); if ( programLinked && shaderWasInUse ) { useProgram(gl, true); @@ -227,19 +227,19 @@ public class ShaderProgram { /** * Links the shader code to the program. - * + * *

          Compiles and attaches the shader code to the program if not done by yet

          - * + * *

          Within this process, all GL resources (shader and program objects) are created if necessary.

          - * + * * @param gl * @param verboseOut * @return true if program was successfully linked and is valid, otherwise false - * + * * @see #init(GL2ES2) */ public synchronized boolean link(GL2ES2 gl, PrintStream verboseOut) { - if( !init(gl) ) { + if( !init(gl) ) { programLinked = false; // mark unlinked due to user attempt to [re]link return false; } @@ -287,7 +287,7 @@ public class ShaderProgram { sb.append("]"); return sb; } - + public String toString() { return toString(null).toString(); } @@ -299,7 +299,7 @@ public class ShaderProgram { public synchronized boolean validateProgram(GL2ES2 gl, PrintStream verboseOut) { return ShaderUtil.isProgramExecStatusValid(gl, shaderProgram, verboseOut); } - + public synchronized void useProgram(GL2ES2 gl, boolean on) { if(!programLinked) { throw new GLException("Program is not linked"); } if(programInUse==on) { return; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java index 8e7781f07..f60cb6088 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java @@ -48,21 +48,21 @@ import com.jogamp.opengl.util.GLArrayDataEditable; * while updating the attribute and uniform locations when switching. *

          * This allows seamless switching of programs using almost same data - * but performing different artifacts. + * but performing different artifacts. *

          *

          * A {@link #useProgram(GL2ES2, boolean) used} ShaderState is attached to the current GL context * and can be retrieved via {@link #getShaderState(GL)}. *

          */ -public class ShaderState { +public class ShaderState { public static final boolean DEBUG; - + static { Debug.initSingleton(); DEBUG = Debug.isPropertyDefined("jogl.debug.GLSLState", true); } - + public ShaderState() { } @@ -80,7 +80,7 @@ public class ShaderState { /** * Attach user object for the given name to this ShaderState. * Returns the previously set object or null. - * + * * @return the previous mapped object or null if none */ public final Object attachObject(String name, Object obj) { @@ -89,13 +89,13 @@ public class ShaderState { /** * @param name name of the mapped object to detach - * + * * @return the previous mapped object or null if none */ public final Object detachObject(String name) { return attachedObjectsByString.remove(name); - } - + } + /** * Turns the shader program on or off.
          * @@ -104,7 +104,7 @@ public class ShaderState { * @see com.jogamp.opengl.util.glsl.ShaderState#useProgram(GL2ES2, boolean) */ public synchronized void useProgram(GL2ES2 gl, boolean on) throws GLException { - if(null==shaderProgram) { throw new GLException("No program is attached"); } + if(null==shaderProgram) { throw new GLException("No program is attached"); } if(on) { if(shaderProgram.linked()) { shaderProgram.useProgram(gl, true); @@ -112,7 +112,7 @@ public class ShaderState { resetAllAttributes(gl); resetAllUniforms(gl); } - } else { + } else { if(resetAllShaderData) { setAllAttributes(gl); } @@ -124,7 +124,7 @@ public class ShaderState { resetAllUniforms(gl); } } - resetAllShaderData = false; + resetAllShaderData = false; } else { shaderProgram.useProgram(gl, false); } @@ -141,17 +141,17 @@ public class ShaderState { /** * Attach or switch a shader program * - *

          Attaching a shader program the first time, + *

          Attaching a shader program the first time, * as well as switching to another program on the fly, * while managing all attribute and uniform data.

          - * + * *

          [Re]sets all data and use program in case of a program switch.

          - * + * *

          Use program, {@link #useProgram(GL2ES2, boolean)}, * if enable is true.

          - * + * * @return true if shader program was attached, otherwise false (already attached) - * + * * @throws GLException if program was not linked and linking fails */ public synchronized boolean attachShaderProgram(GL2ES2 gl, ShaderProgram prog, boolean enable) throws GLException { @@ -161,7 +161,7 @@ public class ShaderState { System.err.println("ShaderState: attachShaderProgram: "+curId+" -> "+newId+" (enable: "+enable+")\n\t"+shaderProgram+"\n\t"+prog); if(DEBUG) { Thread.dumpStack(); - } + } } if(null!=shaderProgram) { if(shaderProgram.equals(prog)) { @@ -190,7 +190,7 @@ public class ShaderState { shaderProgram = prog; if(null!=shaderProgram) { - // [re]set all data and use program if switching program, + // [re]set all data and use program if switching program, // or use program if program is linked if(resetAllShaderData || enable) { useProgram(gl, true); // may reset all data @@ -216,7 +216,7 @@ public class ShaderState { */ public synchronized void destroy(GL2ES2 gl) { release(gl, true, true, true); - attachedObjectsByString.clear(); + attachedObjectsByString.clear(); } /** @@ -242,7 +242,7 @@ public class ShaderState { if(destroyBoundAttributes) { for(Iterator iter = managedAttributes.iterator(); iter.hasNext(); ) { iter.next().destroy(gl); - } + } } releaseAllAttributes(gl); releaseAllUniforms(gl); @@ -258,7 +258,7 @@ public class ShaderState { /** * Gets the cached location of a shader attribute. * - * @return -1 if there is no such attribute available, + * @return -1 if there is no such attribute available, * otherwise >= 0 * * @see #bindAttribLocation(GL2ES2, int, String) @@ -270,7 +270,7 @@ public class ShaderState { Integer idx = activeAttribLocationMap.get(name); return (null!=idx)?idx.intValue():-1; } - + /** * Get the previous cached vertex attribute data. * @@ -289,27 +289,27 @@ public class ShaderState { public GLArrayData getAttribute(String name) { return activeAttribDataMap.get(name); } - + public boolean isActiveAttribute(GLArrayData attribute) { return attribute == activeAttribDataMap.get(attribute.getName()); } - + /** * Binds or unbinds the {@link GLArrayData} lifecycle to this ShaderState. - * + * *

          If an attribute location is cached (ie {@link #bindAttribLocation(GL2ES2, int, String)}) * it is promoted to the {@link GLArrayData} instance.

          - * - *

          The attribute will be destroyed with {@link #destroy(GL2ES2)} + * + *

          The attribute will be destroyed with {@link #destroy(GL2ES2)} * and it's location will be reset when switching shader with {@link #attachShaderProgram(GL2ES2, ShaderProgram)}.

          - * + * *

          The data will not be transfered to the GPU, use {@link #vertexAttribPointer(GL2ES2, GLArrayData)} additionally.

          - * + * *

          The data will also be {@link GLArrayData#associate(Object, boolean) associated} with this ShaderState.

          - * + * * @param attribute the {@link GLArrayData} which lifecycle shall be managed * @param own true if owning shall be performs, false if disowning. - * + * * @see #bindAttribLocation(GL2ES2, int, String) * @see #getAttribute(String) * @see GLArrayData#associate(Object, boolean) @@ -326,11 +326,11 @@ public class ShaderState { } attribute.associate(this, own); } - + public boolean ownsAttribute(GLArrayData attribute) { return managedAttributes.contains(attribute); } - + /** * Binds a shader attribute to a location. * Multiple names can be bound to one location. @@ -339,14 +339,14 @@ public class ShaderState { * * @throws GLException if no program is attached * @throws GLException if the program is already linked - * + * * @see javax.media.opengl.GL2ES2#glBindAttribLocation(int, int, String) * @see #getAttribLocation(GL2ES2, String) * @see #getCachedAttribLocation(String) */ public void bindAttribLocation(GL2ES2 gl, int location, String name) { if(null==shaderProgram) throw new GLException("No program is attached"); - if(shaderProgram.linked()) throw new GLException("Program is already linked"); + if(shaderProgram.linked()) throw new GLException("Program is already linked"); final Integer loc = new Integer(location); activeAttribLocationMap.put(name, loc); gl.glBindAttribLocation(shaderProgram.program(), location, name); @@ -361,7 +361,7 @@ public class ShaderState { * * @throws GLException if no program is attached * @throws GLException if the program is already linked - * + * * @see javax.media.opengl.GL2ES2#glBindAttribLocation(int, int, String) * @see #getAttribLocation(GL2ES2, String) * @see #getCachedAttribLocation(String) @@ -382,7 +382,7 @@ public class ShaderState { * or the GLSL queried via {@link GL2ES2#glGetAttribLocation(int, String)}.
          * The location will be cached. * - * @return -1 if there is no such attribute available, + * @return -1 if there is no such attribute available, * otherwise >= 0 * @throws GLException if no program is attached * @throws GLException if the program is not linked and no location was cached. @@ -407,22 +407,22 @@ public class ShaderState { System.err.println("ShaderState: glGetAttribLocation failed, no location for: "+name+", loc: "+location); if(DEBUG) { Thread.dumpStack(); - } + } } } return location; } - + /** * Validates and returns the location of a shader attribute.
          - * Uses either the cached value {@link #getCachedAttribLocation(String)} if valid, + * Uses either the cached value {@link #getCachedAttribLocation(String)} if valid, * or the GLSL queried via {@link GL2ES2#glGetAttribLocation(int, String)}.
          - * The location will be cached and set in the + * The location will be cached and set in the * {@link GLArrayData} object. * - * @return -1 if there is no such attribute available, + * @return -1 if there is no such attribute available, * otherwise >= 0 - * + * * @throws GLException if no program is attached * @throws GLException if the program is not linked and no location was cached. * @@ -451,13 +451,13 @@ public class ShaderState { System.err.println("ShaderState: glGetAttribLocation failed, no location for: "+name+", loc: "+location); if(DEBUG) { Thread.dumpStack(); - } + } } - } + } activeAttribDataMap.put(data.getName(), data); return location; } - + // // Enabled Vertex Arrays and its data // @@ -469,14 +469,14 @@ public class ShaderState { final Boolean v = activedAttribEnabledMap.get(name); return null != v && v.booleanValue(); } - + /** * @return true if the {@link GLArrayData} attribute is enable */ public final boolean isVertexAttribArrayEnabled(GLArrayData data) { return isVertexAttribArrayEnabled(data.getName()); } - + private boolean enableVertexAttribArray(GL2ES2 gl, String name, int location) { activedAttribEnabledMap.put(name, Boolean.TRUE); if(0>location) { @@ -486,7 +486,7 @@ public class ShaderState { System.err.println("ShaderState: glEnableVertexAttribArray failed, no index for: "+name); if(DEBUG) { Thread.dumpStack(); - } + } } return false; } @@ -497,12 +497,12 @@ public class ShaderState { gl.glEnableVertexAttribArray(location); return true; } - + /** * Enables a vertex attribute array. - * + * * This method retrieves the the location via {@link #getAttribLocation(GL2ES2, GLArrayData)} - * hence {@link #enableVertexAttribArray(GL2ES2, GLArrayData)} shall be preferred. + * hence {@link #enableVertexAttribArray(GL2ES2, GLArrayData)} shall be preferred. * * Even if the attribute is not found in the current shader, * it is marked enabled in this state. @@ -510,7 +510,7 @@ public class ShaderState { * @return false, if the name is not found, otherwise true * * @throws GLException if the program is not linked and no location was cached. - * + * * @see #glEnableVertexAttribArray * @see #glDisableVertexAttribArray * @see #glVertexAttribPointer @@ -519,7 +519,7 @@ public class ShaderState { public boolean enableVertexAttribArray(GL2ES2 gl, String name) { return enableVertexAttribArray(gl, name, -1); } - + /** * Enables a vertex attribute array, usually invoked by {@link GLArrayDataEditable#enableBuffer(GL, boolean)}. @@ -528,7 +528,7 @@ public class ShaderState { * and is the preferred alternative to {@link #enableVertexAttribArray(GL2ES2, String)}. * If data location is unset it will be retrieved via {@link #getAttribLocation(GL2ES2, GLArrayData)} set * and cached in this state. - * + * * Even if the attribute is not found in the current shader, * it is marked enabled in this state. * @@ -547,11 +547,11 @@ public class ShaderState { getAttribLocation(gl, data); } else { // ensure data is the current bound one - activeAttribDataMap.put(data.getName(), data); + activeAttribDataMap.put(data.getName(), data); } return enableVertexAttribArray(gl, data.getName(), data.getLocation()); } - + private boolean disableVertexAttribArray(GL2ES2 gl, String name, int location) { activedAttribEnabledMap.put(name, Boolean.FALSE); if(0>location) { @@ -572,13 +572,13 @@ public class ShaderState { gl.glDisableVertexAttribArray(location); return true; } - + /** * Disables a vertex attribute array * * This method retrieves the the location via {@link #getAttribLocation(GL2ES2, GLArrayData)} * hence {@link #disableVertexAttribArray(GL2ES2, GLArrayData)} shall be preferred. - * + * * Even if the attribute is not found in the current shader, * it is removed from this state enabled list. * @@ -603,7 +603,7 @@ public class ShaderState { * and is the preferred alternative to {@link #disableVertexAttribArray(GL2ES2, String)}. * If data location is unset it will be retrieved via {@link #getAttribLocation(GL2ES2, GLArrayData)} set * and cached in this state. - * + * * Even if the attribute is not found in the current shader, * it is removed from this state enabled list. * @@ -623,20 +623,20 @@ public class ShaderState { } return disableVertexAttribArray(gl, data.getName(), data.getLocation()); } - + /** * Set the {@link GLArrayData} vertex attribute data, if it's location is valid, i.e. ≥ 0. *

          * This method uses the {@link GLArrayData}'s location if valid, i.e. ≥ 0.
          - * If data's location is invalid, it will be retrieved via {@link #getAttribLocation(GL2ES2, GLArrayData)}, + * If data's location is invalid, it will be retrieved via {@link #getAttribLocation(GL2ES2, GLArrayData)}, * set and cached in this state. *

          - * + * * @return false, if the location could not be determined, otherwise true * * @throws GLException if no program is attached * @throws GLException if the program is not linked and no location was cached. - * + * * @see #glEnableVertexAttribArray * @see #glDisableVertexAttribArray * @see #glVertexAttribPointer @@ -646,7 +646,7 @@ public class ShaderState { int location = data.getLocation(); if(0 > location) { location = getAttribLocation(gl, data); - } + } if(0 <= location) { // only pass the data, if the attribute exists in the current shader if(DEBUG) { @@ -683,16 +683,16 @@ public class ShaderState { activeAttribDataMap.clear(); activedAttribEnabledMap.clear(); activeAttribLocationMap.clear(); - managedAttributes.clear(); + managedAttributes.clear(); } - + /** * Disables all vertex attribute arrays. * * Their enabled stated will be removed from this state only * if 'removeFromState' is true. * - * This method purpose is more for debugging. + * This method purpose is more for debugging. * * @see #glEnableVertexAttribArray * @see #glDisableVertexAttribArray @@ -717,7 +717,7 @@ public class ShaderState { } private final void relocateAttribute(GL2ES2 gl, GLArrayData attribute) { - // get new location .. note: 'activeAttribLocationMap' is cleared before + // get new location .. note: 'activeAttribLocationMap' is cleared before final String name = attribute.getName(); final int loc = attribute.setLocation(gl, shaderProgram.program()); if(0<=loc) { @@ -729,34 +729,34 @@ public class ShaderState { // enable attrib, VBO and pass location/data gl.glEnableVertexAttribArray(loc); } - + if( attribute.isVBO() ) { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, attribute.getVBOName()); gl.glVertexAttribPointer(attribute); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); - } else { + } else { gl.glVertexAttribPointer(attribute); } } } - + /** * Reset all previously enabled mapped vertex attribute data. - * + * *

          * Attribute data is bound to the GL state, i.e. VBO data itself will not be updated. *

          - * + * *

          * Attribute location and it's data assignment is bound to the program, * hence both are updated. *

          - * + * *

          - * Note: Such update could only be prevented, + * Note: Such update could only be prevented, * if tracking am attribute/program dirty flag. *

          - * + * * @throws GLException is the program is not linked * * @see #attachShaderProgram(GL2ES2, ShaderProgram) @@ -764,7 +764,7 @@ public class ShaderState { private final void resetAllAttributes(GL2ES2 gl) { if(!shaderProgram.linked()) throw new GLException("Program is not linked"); activeAttribLocationMap.clear(); - + for(int i=0; i= 0 */ public final int getCachedUniformLocation(String name) { @@ -822,38 +822,38 @@ public class ShaderState { /** * Bind the {@link GLUniform} lifecycle to this ShaderState. - * + * *

          If a uniform location is cached it is promoted to the {@link GLUniformData} instance.

          - * - *

          The attribute will be destroyed with {@link #destroy(GL2ES2)} + * + *

          The attribute will be destroyed with {@link #destroy(GL2ES2)} * and it's location will be reset when switching shader with {@link #attachShaderProgram(GL2ES2, ShaderProgram)}.

          - * + * *

          The data will not be transfered to the GPU, use {@link #uniform(GL2ES2, GLUniformData)} additionally.

          - * + * * @param uniform the {@link GLUniformData} which lifecycle shall be managed - * + * * @see #getUniform(String) */ public void ownUniform(GLUniformData uniform) { final int location = getCachedUniformLocation(uniform.getName()); if(0<=location) { uniform.setLocation(location); - } + } activeUniformDataMap.put(uniform.getName(), uniform); - managedUniforms.add(uniform); + managedUniforms.add(uniform); } - + public boolean ownsUniform(GLUniformData uniform) { return managedUniforms.contains(uniform); } - + /** * Gets the location of a shader uniform with given name.
          * Uses either the cached value {@link #getCachedUniformLocation(String)} if valid, * or the GLSL queried via {@link GL2ES2#glGetUniformLocation(int, String)}.
          * The location will be cached. *

          - * The current shader program ({@link #attachShaderProgram(GL2ES2, ShaderProgram)}) + * The current shader program ({@link #attachShaderProgram(GL2ES2, ShaderProgram)}) * must be in use ({@link #useProgram(GL2ES2, boolean) }) !

          * * @return -1 if there is no such attribute available, @@ -884,15 +884,15 @@ public class ShaderState { } return location; } - + /** * Validates and returns the location of a shader uniform.
          * Uses either the cached value {@link #getCachedUniformLocation(String)} if valid, * or the GLSL queried via {@link GL2ES2#glGetUniformLocation(int, String)}.
          - * The location will be cached and set in the + * The location will be cached and set in the * {@link GLUniformData} object. *

          - * The current shader program ({@link #attachShaderProgram(GL2ES2, ShaderProgram)}) + * The current shader program ({@link #attachShaderProgram(GL2ES2, ShaderProgram)}) * must be in use ({@link #useProgram(GL2ES2, boolean) }) !

          * * @return -1 if there is no such attribute available, @@ -922,16 +922,16 @@ public class ShaderState { Thread.dumpStack(); } } - } - activeUniformDataMap.put(name, data); + } + activeUniformDataMap.put(name, data); return location; } - + /** * Set the uniform data, if it's location is valid, i.e. ≥ 0. *

          * This method uses the {@link GLUniformData}'s location if valid, i.e. ≥ 0.
          - * If data's location is invalid, it will be retrieved via {@link #getUniformLocation(GL2ES2, GLUniformData)}, + * If data's location is invalid, it will be retrieved via {@link #getUniformLocation(GL2ES2, GLUniformData)}, * set and cached in this state. *

          * @@ -959,7 +959,7 @@ public class ShaderState { } return false; } - + /** * Get the uniform data, previously set. * @@ -978,7 +978,7 @@ public class ShaderState { activeUniformLocationMap.clear(); managedUniforms.clear(); } - + /** * Reset all previously mapped uniform data *

          @@ -986,20 +986,20 @@ public class ShaderState { * hence both are updated. *

          *

          - * Note: Such update could only be prevented, + * Note: Such update could only be prevented, * if tracking a uniform/program dirty flag. *

          - * + * * @throws GLException is the program is not in use - * + * * @see #attachShaderProgram(GL2ES2, ShaderProgram) */ private final void resetAllUniforms(GL2ES2 gl) { - if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); + if(!shaderProgram.inUse()) throw new GLException("Program is not in use"); activeUniformLocationMap.clear(); for(Iterator iter = managedUniforms.iterator(); iter.hasNext(); ) { iter.next().setLocation(-1); - } + } for(Iterator iter = activeUniformDataMap.values().iterator(); iter.hasNext(); ) { final GLUniformData data = iter.next(); final int loc = data.setLocation(gl, shaderProgram.program()); @@ -1018,9 +1018,9 @@ public class ShaderState { if(null==sb) { sb = new StringBuilder(); } - + sb.append("ShaderState[ "); - + sb.append(Platform.getNewline()).append(" "); if(null != shaderProgram) { shaderProgram.toString(sb); @@ -1066,25 +1066,25 @@ public class ShaderState { sb.append(Platform.getNewline()).append(" ]").append(Platform.getNewline()).append("]"); return sb; } - + @Override public String toString() { return toString(null, DEBUG).toString(); } - + private boolean verbose = DEBUG; private ShaderProgram shaderProgram=null; - + private HashMap activedAttribEnabledMap = new HashMap(); private HashMap activeAttribLocationMap = new HashMap(); private HashMap activeAttribDataMap = new HashMap(); private ArrayList managedAttributes = new ArrayList(); - + private HashMap activeUniformLocationMap = new HashMap(); private HashMap activeUniformDataMap = new HashMap(); private ArrayList managedUniforms = new ArrayList(); - - private HashMap attachedObjectsByString = new HashMap(); + + private HashMap attachedObjectsByString = new HashMap(); private boolean resetAllShaderData = false; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java index d18fd4bae..5cd384c58 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2009 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 @@ -28,7 +28,7 @@ * 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. - * + * */ package com.jogamp.opengl.util.glsl; @@ -117,11 +117,11 @@ public class ShaderUtil { } return true; } - + /** * Performs {@link GL2ES2#glValidateProgram(int)} *

          - * One shall only call this method while debugging and only if all required + * One shall only call this method while debugging and only if all required * resources by the shader are set. *

          *

          @@ -150,7 +150,7 @@ public class ShaderUtil { } /** - * If supported, queries the natively supported shader binary formats using + * If supported, queries the natively supported shader binary formats using * {@link GL2ES2#GL_NUM_SHADER_BINARY_FORMATS} and {@link GL2ES2#GL_SHADER_BINARY_FORMATS} * via {@link GL2ES2#glGetIntegerv(int, int[], int)}. */ @@ -172,9 +172,9 @@ public class ShaderUtil { info.shaderBinaryFormats.add(new Integer(formats[i])); } } - } catch (GLException gle) { - System.err.println("Catched Exception on thread "+Thread.currentThread().getName()); - gle.printStackTrace(); + } catch (GLException gle) { + System.err.println("Catched Exception on thread "+Thread.currentThread().getName()); + gle.printStackTrace(); } } } @@ -202,13 +202,13 @@ public class ShaderUtil { } info.shaderCompilerAvailable = new Boolean(v); queryOK = true; - } catch (GLException gle) { - System.err.println("Catched Exception on thread "+Thread.currentThread().getName()); - gle.printStackTrace(); + } catch (GLException gle) { + System.err.println("Catched Exception on thread "+Thread.currentThread().getName()); + gle.printStackTrace(); } if(!queryOK) { info.shaderCompilerAvailable = new Boolean(true); - } + } } else if( gl.isGL2ES2() ) { info.shaderCompilerAvailable = new Boolean(true); } else { @@ -217,8 +217,8 @@ public class ShaderUtil { } return info.shaderCompilerAvailable.booleanValue(); } - - /** Returns true if GeometryShader is supported, i.e. whether GLContext is ≥ 3.2 or ARB_geometry_shader4 extension is available. */ + + /** Returns true if GeometryShader is supported, i.e. whether GLContext is ≥ 3.2 or ARB_geometry_shader4 extension is available. */ public static boolean isGeometryShaderSupported(GL _gl) { final GLContext ctx = _gl.getContext(); return ctx.getGLVersionNumber().compareTo(GLContext.Version320) >= 0 || @@ -240,7 +240,7 @@ public class ShaderUtil { IntBuffer lengths = Buffers.newDirectIntBuffer(count); for(int i=0; i shaderBinaryFormats = null; - } + } private static ProfileInformation getProfileInformation(GL gl) { final GLContext context = gl.getContext(); diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/fixedfunc/FixedFuncUtil.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/fixedfunc/FixedFuncUtil.java index a653bd467..2f8884a3a 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/fixedfunc/FixedFuncUtil.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/fixedfunc/FixedFuncUtil.java @@ -24,13 +24,13 @@ import com.jogamp.opengl.util.PMVMatrix; public class FixedFuncUtil { /** * @param gl - * @param mode one of the {@link ShaderSelectionMode}s + * @param mode one of the {@link ShaderSelectionMode}s * @param pmvMatrix optional pass through PMVMatrix for the {@link FixedFuncHook} and {@link FixedFuncPipeline} * @return If gl is a GL2ES1 and force is false, return the type cast object, * otherwise create a fixed function emulation pipeline using the given GL2ES2 impl * and hook it to the GLContext via {@link GLContext#setGL(GL)}. * @throws GLException if the GL object is neither GL2ES1 nor GL2ES2 - * + * * @see ShaderSelectionMode#AUTO * @see ShaderSelectionMode#COLOR * @see ShaderSelectionMode#COLOR_LIGHT_PER_VERTEX @@ -53,13 +53,13 @@ public class FixedFuncUtil { /** * @param gl - * @param mode one of the {@link ShaderSelectionMode}s + * @param mode one of the {@link ShaderSelectionMode}s * @param pmvMatrix optional pass through PMVMatrix for the {@link FixedFuncHook} and {@link FixedFuncPipeline} * @return If gl is a GL2ES1, return the type cast object, * otherwise create a fixed function emulation pipeline using the GL2ES2 impl. * and hook it to the GLContext via {@link GLContext#setGL(GL)}. * @throws GLException if the GL object is neither GL2ES1 nor GL2ES2 - * + * * @see ShaderSelectionMode#AUTO * @see ShaderSelectionMode#COLOR * @see ShaderSelectionMode#COLOR_LIGHT_PER_VERTEX @@ -71,11 +71,11 @@ public class FixedFuncUtil { } /** - * Mapping fixed function (client) array indices to + * Mapping fixed function (client) array indices to * GLSL array attribute names. * * Useful for uniq mapping of canonical array index names as listed. - * + * * @see #mgl_Vertex * @see javax.media.opengl.fixedfunc.GLPointerFunc#GL_VERTEX_ARRAY * @see #mgl_Normal diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/fixedfunc/ShaderSelectionMode.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/fixedfunc/ShaderSelectionMode.java index e6bdf702c..426fb0d85 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/fixedfunc/ShaderSelectionMode.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/fixedfunc/ShaderSelectionMode.java @@ -1,8 +1,8 @@ package com.jogamp.opengl.util.glsl.fixedfunc; -/** +/** * Shader selection mode - * + * * @see ShaderSelectionMode#AUTO * @see ShaderSelectionMode#COLOR * @see ShaderSelectionMode#COLOR_LIGHT_PER_VERTEX @@ -11,17 +11,17 @@ package com.jogamp.opengl.util.glsl.fixedfunc; */ public enum ShaderSelectionMode { /** Auto shader selection, based upon FFP states. */ - AUTO, + AUTO, /** Fixed shader selection: Simple color. */ - COLOR, + COLOR, /** Fixed shader selection: Multi-Textured color. 2 texture units. */ - COLOR_TEXTURE2, + COLOR_TEXTURE2, /** Fixed shader selection: Multi-Textured color. 4 texture units. */ - COLOR_TEXTURE4, + COLOR_TEXTURE4, /** Fixed shader selection: Multi-Textured color. 8 texture units. */ - COLOR_TEXTURE8, + COLOR_TEXTURE8, /** Fixed shader selection: Color with vertex-lighting. */ - COLOR_LIGHT_PER_VERTEX, + COLOR_LIGHT_PER_VERTEX, /** Fixed shader selection: Multi-Textured color with vertex-lighting. 8 texture units.*/ - COLOR_TEXTURE8_LIGHT_PER_VERTEX + COLOR_TEXTURE8_LIGHT_PER_VERTEX } \ No newline at end of file diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java index a5b1c6687..9573ea5c3 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java @@ -55,8 +55,8 @@ public abstract class CompileShader { URL resourceURL = IOUtil.getResource(null, resourceName).getURL(); String dirName = dirname(resourceURL.getPath()); - outName = dirName + File.separator + "bin" + File.separator + - ShaderCode.getBinarySubPath(getBinaryFormat()) + File.separator + + outName = dirName + File.separator + "bin" + File.separator + + ShaderCode.getBinarySubPath(getBinaryFormat()) + File.separator + outName; processOneShader(resourceName, outName, type); } diff --git a/src/jogl/classes/com/jogamp/opengl/util/packrect/BackingStoreManager.java b/src/jogl/classes/com/jogamp/opengl/util/packrect/BackingStoreManager.java index 7b6a1b479..c1b5025f8 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/packrect/BackingStoreManager.java +++ b/src/jogl/classes/com/jogamp/opengl/util/packrect/BackingStoreManager.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2006 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/packrect/Level.java b/src/jogl/classes/com/jogamp/opengl/util/packrect/Level.java index 5ba3f7330..44b4fea9e 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/packrect/Level.java +++ b/src/jogl/classes/com/jogamp/opengl/util/packrect/Level.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2006 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 @@ -28,11 +28,11 @@ * 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. */ @@ -128,7 +128,7 @@ public class Level { candidate.setSize(candidate.w() - rect.w(), height); freeList.add(candidate); } - + coalesceFreeList(); return true; diff --git a/src/jogl/classes/com/jogamp/opengl/util/packrect/LevelSet.java b/src/jogl/classes/com/jogamp/opengl/util/packrect/LevelSet.java index 6783aec3b..e14eef5ba 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/packrect/LevelSet.java +++ b/src/jogl/classes/com/jogamp/opengl/util/packrect/LevelSet.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2006 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 @@ -28,11 +28,11 @@ * 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. */ @@ -108,7 +108,7 @@ public class LevelSet { if (level.remove(rect)) return true; } - + return false; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/packrect/Rect.java b/src/jogl/classes/com/jogamp/opengl/util/packrect/Rect.java index 6206c4a11..23f143b83 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/packrect/Rect.java +++ b/src/jogl/classes/com/jogamp/opengl/util/packrect/Rect.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2006 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 @@ -28,11 +28,11 @@ * 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. */ @@ -72,7 +72,7 @@ public class Rect { // there is no room left due either to fragmentation or just being // out of space) private Rect nextLocation; - + public Rect() { this(null); } diff --git a/src/jogl/classes/com/jogamp/opengl/util/packrect/RectVisitor.java b/src/jogl/classes/com/jogamp/opengl/util/packrect/RectVisitor.java index 49cfc82e6..5db216742 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/packrect/RectVisitor.java +++ b/src/jogl/classes/com/jogamp/opengl/util/packrect/RectVisitor.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2006 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/packrect/RectanglePacker.java b/src/jogl/classes/com/jogamp/opengl/util/packrect/RectanglePacker.java index 1496a04a6..a9d609745 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/packrect/RectanglePacker.java +++ b/src/jogl/classes/com/jogamp/opengl/util/packrect/RectanglePacker.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2006 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 @@ -28,11 +28,11 @@ * 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. */ @@ -203,7 +203,7 @@ public class RectanglePacker { } nextLevelSet = new LevelSet(newWidth, newHeight); - + // Make copies of all existing rectangles List/**/ newRects = new ArrayList/**/(); for (Iterator i1 = levels.iterator(); i1.hasNext(); ) { diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java b/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java index 4236e22fb..fd026d76e 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 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 @@ -29,7 +29,7 @@ * 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. @@ -53,8 +53,8 @@ import com.jogamp.opengl.util.texture.spi.*; * for enabling/disabling OpenGL texture state, binding this texture, * and computing texture coordinates for both the entire image as well * as a sub-image. - * - *

          Order of Texture Commands
          + * + *
          Order of Texture Commands
          *

          * Due to many confusions w/ texture usage, following list described the order * and semantics of texture unit selection, binding and enabling. @@ -67,16 +67,16 @@ import com.jogamp.opengl.util.texture.spi.*; *

        • Issue draw commands
        • * *

          - * + * *

          Non-power-of-two restrictions *
          When creating an OpenGL texture object, the Texture class will * attempt to use non-power-of-two textures (NPOT) if available, see {@link GL#isNPOTTextureAvailable()}. - * Further more, + * Further more, * GL_ARB_texture_rectangle * (RECT) will be attempted on OSX w/ ATI drivers. * If NPOT is not available or RECT not chosen, the Texture class will simply upload a non-pow2-sized * image into a standard pow2-sized texture (without any special - * scaling). + * scaling). * Since the choice of extension (or whether one is used at * all) depends on the user's machine configuration, developers are * recommended to use {@link #getImageTexCoords} and {@link @@ -106,7 +106,7 @@ import com.jogamp.opengl.util.texture.spi.*; * #bind}, but when drawing many triangles all using the same texture, * for best performance only one call to {@link #bind} should be made. * User may also utilize multiple texture units, - * see order of texture commands above. + * see order of texture commands above. * *

          Alpha premultiplication and blending *

          @@ -119,7 +119,7 @@ import com.jogamp.opengl.util.texture.spi.*; *

          * The mathematically correct way to perform blending in OpenGL * with the SrcOver "source over destination" mode, or any other - * Porter-Duff rule, is to use premultiplied color components, + * Porter-Duff rule, is to use premultiplied color components, * which means the R/G/ B color components must have been multiplied by * the alpha value. If using premultiplied color components * it is important to use the correct blending function; for @@ -137,7 +137,7 @@ import com.jogamp.opengl.util.texture.spi.*; float g = g * a; float b = b * a; gl.glColor4f(r, g, b, a); - + * * For reference, here is a list of the Porter-Duff compositing rules * and the associated OpenGL blend functions (source and destination @@ -187,8 +187,8 @@ public class Texture { /** The texture coordinates corresponding to the entire image. */ private TextureCoords coords; - - public String toString() { + + public String toString() { return "Texture[target 0x"+Integer.toHexString(target)+", name "+texID+", "+ imgWidth+"/"+texWidth+" x "+imgHeight+"/"+texHeight+", y-flip "+mustFlipVertically+ ", "+estimatedMemorySize+" bytes]"; @@ -237,7 +237,7 @@ public class Texture { * gl.glEnable(texture.getTarget()); * *

          - * Call is ignored if the {@link GL} object's context + * Call is ignored if the {@link GL} object's context * is using a core profile, see {@link GL#isGLcore()}, * or if {@link #getTarget()} is {@link GLES2#GL_TEXTURE_EXTERNAL_OES}. *

          @@ -255,7 +255,7 @@ public class Texture { gl.glEnable(target); } } - + /** * Disables this texture's target (e.g., GL_TEXTURE_2D) in the * given GL state. This method is a shorthand equivalent @@ -264,7 +264,7 @@ public class Texture { * gl.glDisable(texture.getTarget()); * *

          - * Call is ignored if the {@link GL} object's context + * Call is ignored if the {@link GL} object's context * is using a core profile, see {@link GL#isGLcore()}, * or if {@link #getTarget()} is {@link GLES2#GL_TEXTURE_EXTERNAL_OES}. *

          @@ -282,7 +282,7 @@ public class Texture { gl.glDisable(target); } } - + /** * Binds this texture to the given GL context. This method is a * shorthand equivalent of the following OpenGL code: @@ -292,16 +292,16 @@ public class Texture { * * See the performance tips above for hints * on how to maximize performance when using many Texture objects. - * + * * @param gl the current GL context * @throws GLException if no OpenGL context was current or if any * OpenGL-related errors occurred */ public void bind(GL gl) throws GLException { validateTexID(gl, true); - gl.glBindTexture(target, texID); + gl.glBindTexture(target, texID); } - + /** * Destroys the native resources used by this texture object. * @@ -335,7 +335,7 @@ public class Texture { public int getWidth() { return texWidth; } - + /** * Returns the height of the allocated OpenGL texture in pixels. * Note that the texture height will be greater than or equal to the @@ -345,9 +345,9 @@ public class Texture { */ public int getHeight() { return texHeight; - } - - /** + } + + /** * Returns the width of the image contained within this texture. * Note that for non-power-of-two textures in particular this may * not be equal to the result of {@link #getWidth}. It is @@ -389,7 +389,7 @@ public class Texture { * entire image. If the TextureData indicated that the texture * coordinates must be flipped vertically, the returned * TextureCoords will take that into account. - * + * * @return the texture coordinates corresponding to the entire image */ public TextureCoords getImageTexCoords() { @@ -406,7 +406,7 @@ public class Texture { * flipped vertically, the returned TextureCoords will take that * into account; this should not be handled by the end user in the * specification of the y1 and y2 coordinates. - * + * * @return the texture coordinates corresponding to the specified sub-image */ public TextureCoords getSubImageTexCoords(int x1, int y1, int x2, int y2) { @@ -431,9 +431,9 @@ public class Texture { } /** - * Updates the entire content area incl. {@link TextureCoords} + * Updates the entire content area incl. {@link TextureCoords} * of this texture using the data in the given image. - * + * * @throws GLException if any OpenGL-related errors occurred */ public void updateImage(GL gl, TextureData data) throws GLException { @@ -465,12 +465,12 @@ public class Texture { updateTexCoords(); } } - + /** * Updates the content area incl. {@link TextureCoords} of the specified target of this texture * using the data in the given image. In general this is intended * for construction of cube maps. - * + * * @throws GLException if any OpenGL-related errors occurred */ public void updateImage(GL gl, TextureData data, int targetOverride) throws GLException { @@ -791,7 +791,7 @@ public class Texture { * texture's target. This gives control over parameters such as * GL_TEXTURE_MAX_ANISOTROPY_EXT. Causes this texture to be bound to * the current texture state. - * + * * @throws GLException if no OpenGL context was current or if any * OpenGL-related errors occurred */ @@ -805,7 +805,7 @@ public class Texture { * Sets the OpenGL multi-floating-point texture parameter for the * texture's target. Causes this texture to be bound to the current * texture state. - * + * * @throws GLException if any OpenGL-related errors occurred */ public void setTexParameterfv(GL gl, int parameterName, @@ -818,7 +818,7 @@ public class Texture { * Sets the OpenGL multi-floating-point texture parameter for the * texture's target. Causes this texture to be bound to the current * texture state. - * + * * @throws GLException if any OpenGL-related errors occurred */ public void setTexParameterfv(GL gl, int parameterName, @@ -834,7 +834,7 @@ public class Texture { * to GL_CLAMP_TO_EDGE if OpenGL 1.2 is supported on the current * platform and GL_CLAMP if not. Causes this texture to be bound to * the current texture state. - * + * * @throws GLException if any OpenGL-related errors occurred */ public void setTexParameteri(GL gl, int parameterName, @@ -847,7 +847,7 @@ public class Texture { * Sets the OpenGL multi-integer texture parameter for the texture's * target. Causes this texture to be bound to the current texture * state. - * + * * @throws GLException if any OpenGL-related errors occurred */ public void setTexParameteriv(GL gl, int parameterName, @@ -860,7 +860,7 @@ public class Texture { * Sets the OpenGL multi-integer texture parameter for the texture's * target. Causes this texture to be bound to the current texture * state. - * + * * @throws GLException if any OpenGL-related errors occurred */ public void setTexParameteriv(GL gl, int parameterName, @@ -886,7 +886,7 @@ public class Texture { } /** - * Returns the underlying OpenGL texture object for this texture, + * Returns the underlying OpenGL texture object for this texture, * maybe 0 if not yet generated. *

          * Most applications will not need to access this, since it is @@ -967,19 +967,19 @@ public class Texture { } } else { if (mustFlipVertically) { - coords = new TextureCoords(0, // l + coords = new TextureCoords(0, // l (float) imgHeight / (float) texHeight, // b (float) imgWidth / (float) texWidth, // r 0 // t ); } else { - coords = new TextureCoords(0, // l + coords = new TextureCoords(0, // l 0, // b (float) imgWidth / (float) texWidth, // r (float) imgHeight / (float) texHeight // t ); } - } + } } private void updateSubImageImpl(GL gl, TextureData data, int newTarget, int mipmapLevel, diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java index 3931b7290..63f100630 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2012 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 @@ -29,7 +29,7 @@ * 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. @@ -77,7 +77,7 @@ public class TextureCoords { d[6+d_off] = right *ss; d[7+d_off] = top *ts; return d; } - + /** Returns the leftmost (x) texture coordinate of this rectangle. */ public float left() { return left; } @@ -93,6 +93,6 @@ public class TextureCoords { /** Returns the topmost (y) texture coordinate of this rectangle. */ public float top() { return top; } - + public String toString() { return "TexCoord[h: "+left+" - "+right+", v: "+bottom+" - "+top+"]"; } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java index afc5bf70c..28029efc5 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 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 @@ -29,7 +29,7 @@ * 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. @@ -57,8 +57,8 @@ import com.jogamp.opengl.util.GLPixelBuffer.GLPixelAttributes; public class TextureData { /** ColorSpace of pixel data. */ - public static enum ColorSpace { RGB, YCbCr, YCCK, CMYK }; - + public static enum ColorSpace { RGB, YCbCr, YCCK, CMYK }; + protected int width; protected int height; private int border; @@ -83,7 +83,7 @@ public class TextureData { protected GLProfile glProfile; protected ColorSpace pixelCS = ColorSpace.RGB; - /** + /** * Constructs a new TextureData object with the specified parameters * and data contained in the given Buffer. The optional Flusher can * be used to clean up native resources associated with this @@ -123,7 +123,7 @@ public class TextureData { * data were invalid, such as requesting mipmap generation for a * compressed texture */ - public TextureData(GLProfile glp, + public TextureData(GLProfile glp, int internalFormat, int width, int height, @@ -135,11 +135,11 @@ public class TextureData { boolean mustFlipVertically, Buffer buffer, Flusher flusher) throws IllegalArgumentException { - this(glp, internalFormat, width, height, border, new GLPixelAttributes(pixelFormat, pixelType), + this(glp, internalFormat, width, height, border, new GLPixelAttributes(pixelFormat, pixelType), mipmap, dataIsCompressed, mustFlipVertically, buffer, flusher); } - /** + /** * Constructs a new TextureData object with the specified parameters * and data contained in the given Buffer. The optional Flusher can * be used to clean up native resources associated with this @@ -178,7 +178,7 @@ public class TextureData { * data were invalid, such as requesting mipmap generation for a * compressed texture */ - public TextureData(GLProfile glp, + public TextureData(GLProfile glp, int internalFormat, int width, int height, @@ -207,8 +207,8 @@ public class TextureData { alignment = 1; // FIXME: is this correct enough in all situations? estimatedMemorySize = estimatedMemorySize(buffer); } - - /** + + /** * Constructs a new TextureData object with the specified parameters * and data for multiple mipmap levels contained in the given array * of Buffers. The optional Flusher can be used to clean up native @@ -258,11 +258,11 @@ public class TextureData { boolean mustFlipVertically, Buffer[] mipmapData, Flusher flusher) throws IllegalArgumentException { - this(glp, internalFormat, width, height, border, new GLPixelAttributes(pixelFormat, pixelType), + this(glp, internalFormat, width, height, border, new GLPixelAttributes(pixelFormat, pixelType), dataIsCompressed, mustFlipVertically, mipmapData, flusher); } - /** + /** * Constructs a new TextureData object with the specified parameters * and data for multiple mipmap levels contained in the given array * of Buffers. The optional Flusher can be used to clean up native @@ -325,19 +325,19 @@ public class TextureData { estimatedMemorySize += estimatedMemorySize(mipmapData[i]); } } - - /** + + /** * Returns the color space of the pixel data. - * @see #setColorSpace(ColorSpace) + * @see #setColorSpace(ColorSpace) */ public ColorSpace getColorSpace() { return pixelCS; } - /** + /** * Set the color space of the pixel data, which defaults to {@link ColorSpace#RGB}. - * @see #getColorSpace() + * @see #getColorSpace() */ public void setColorSpace(ColorSpace cs) { pixelCS = cs; } - + /** Used only by subclasses */ protected TextureData(GLProfile glp) { this.glProfile = glp; this.pixelAttributes = GLPixelAttributes.UNDEF; } @@ -346,8 +346,8 @@ public class TextureData { /** Returns the height in pixels of the texture data. */ public int getHeight() { return height; } /** Returns the border in pixels of the texture data. */ - public int getBorder() { - return border; + public int getBorder() { + return border; } /** Returns the intended OpenGL {@link GLPixelAttributes} of the texture data, i.e. format and type. */ public GLPixelAttributes getPixelAttributes() { @@ -362,21 +362,21 @@ public class TextureData { return pixelAttributes.type; } /** Returns the intended OpenGL internal format of the texture data. */ - public int getInternalFormat() { - return internalFormat; + public int getInternalFormat() { + return internalFormat; } /** Returns whether mipmaps should be generated for the texture data. */ - public boolean getMipmap() { - return mipmap; + public boolean getMipmap() { + return mipmap; } /** Indicates whether the texture data is in compressed form. */ - public boolean isDataCompressed() { - return dataIsCompressed; + public boolean isDataCompressed() { + return dataIsCompressed; } /** Indicates whether the texture coordinates must be flipped vertically for proper display. */ - public boolean getMustFlipVertically() { - return mustFlipVertically; + public boolean getMustFlipVertically() { + return mustFlipVertically; } /** Returns the texture data, or null if it is specified as a set of mipmaps. */ public Buffer getBuffer() { @@ -384,18 +384,18 @@ public class TextureData { } /** Returns all mipmap levels for the texture data, or null if it is specified as a single image. */ - public Buffer[] getMipmapData() { - return mipmapData; + public Buffer[] getMipmapData() { + return mipmapData; } /** Returns the required byte alignment for the texture data. */ - public int getAlignment() { - return alignment; + public int getAlignment() { + return alignment; } /** Returns the row length needed for correct GL_UNPACK_ROW_LENGTH specification. This is currently only supported for non-mipmapped, non-compressed textures. */ - public int getRowLength() { - return rowLength; + public int getRowLength() { + return rowLength; } /** Sets the width in pixels of the texture data. */ @@ -405,25 +405,25 @@ public class TextureData { /** Sets the border in pixels of the texture data. */ public void setBorder(int border) { this.border = border; } /** Sets the intended OpenGL pixel format of the texture data. */ - public void setPixelAttributes(GLPixelAttributes pixelAttributes) { this.pixelAttributes = pixelAttributes; } - /** + public void setPixelAttributes(GLPixelAttributes pixelAttributes) { this.pixelAttributes = pixelAttributes; } + /** * Sets the intended OpenGL pixel format component of {@link GLPixelAttributes} of the texture data. *

          - * Use {@link #setPixelAttributes(GLPixelAttributes)}, if setting format and type. - *

          + * Use {@link #setPixelAttributes(GLPixelAttributes)}, if setting format and type. + *

          */ public void setPixelFormat(int pixelFormat) { if( pixelAttributes.format != pixelFormat ) { pixelAttributes = new GLPixelAttributes(pixelFormat, pixelAttributes.type); } } - /** + /** * Sets the intended OpenGL pixel type component of {@link GLPixelAttributes} of the texture data. *

          - * Use {@link #setPixelAttributes(GLPixelAttributes)}, if setting format and type. - *

          + * Use {@link #setPixelAttributes(GLPixelAttributes)}, if setting format and type. + *

          */ - public void setPixelType(int pixelType) { + public void setPixelType(int pixelType) { if( pixelAttributes.type != pixelType) { pixelAttributes = new GLPixelAttributes(pixelAttributes.format, pixelType); } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java index 3748cd336..b6d89d6d2 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2011 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 @@ -29,11 +29,11 @@ * 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. */ @@ -161,11 +161,11 @@ public class TextureIO { /** Constant which can be used as a file suffix to indicate a PAM file, NetPbm magic 7 - binary RGB and RGBA. Write support only. */ public static final String PAM = "pam"; - + /** Constant which can be used as a file suffix to indicate a PAM file, NetPbm magic 6 - binary RGB. Write support only. */ public static final String PPM = "ppm"; - + private static final boolean DEBUG = Debug.debug("TextureIO"); // For manually disabling the use of the texture rectangle @@ -421,7 +421,7 @@ public class TextureIO { // methods that *do* require a current context // - /** + /** * Creates an OpenGL texture object from the specified TextureData * using the current OpenGL context. * @@ -434,7 +434,7 @@ public class TextureIO { return newTexture(GLContext.getCurrentGL(), data); } - /** + /** * Creates an OpenGL texture object from the specified TextureData * using the given OpenGL context. * @@ -449,8 +449,8 @@ public class TextureIO { } return new Texture(gl, data); } - - /** + + /** * Creates an OpenGL texture object from the specified file using * the current OpenGL context. * @@ -474,7 +474,7 @@ public class TextureIO { return texture; } - /** + /** * Creates an OpenGL texture object from the specified stream using * the current OpenGL context. * @@ -503,7 +503,7 @@ public class TextureIO { return texture; } - /** + /** * Creates an OpenGL texture object from the specified URL using the * current OpenGL context. * @@ -535,13 +535,13 @@ public class TextureIO { return texture; } - /** + /** * Creates an OpenGL texture object associated with the given OpenGL * texture target. The texture has * no initial data. This is used, for example, to construct cube * maps out of multiple TextureData objects. * - * @param target the OpenGL target type, eg GL.GL_TEXTURE_2D, + * @param target the OpenGL target type, eg GL.GL_TEXTURE_2D, * GL.GL_TEXTURE_RECTANGLE_ARB */ public static Texture newTexture(int target) { @@ -556,7 +556,7 @@ public class TextureIO { * undefined results. * * @param textureID the OpenGL texture object to wrap - * @param target the OpenGL texture target, eg GL.GL_TEXTURE_2D, + * @param target the OpenGL texture target, eg GL.GL_TEXTURE_2D, * GL2.GL_TEXTURE_RECTANGLE * @param texWidth the width of the texture in pixels * @param texHeight the height of the texture in pixels @@ -689,7 +689,7 @@ public class TextureIO { gl.glPixelStorei(GL2.GL_PACK_SKIP_ROWS, packSkipRows); gl.glPixelStorei(GL2.GL_PACK_SKIP_PIXELS, packSkipPixels); gl.glPixelStorei(GL2.GL_PACK_SWAP_BYTES, packSwapBytes); - + data = new TextureData(gl.getGLProfile(), internalFormat, width, height, border, fetchedFormat, GL.GL_UNSIGNED_BYTE, false, false, false, res, null); @@ -701,7 +701,7 @@ public class TextureIO { write(data, file); } - + public static void write(TextureData data, File file) throws IOException, GLException { for (Iterator iter = textureWriters.iterator(); iter.hasNext(); ) { TextureWriter writer = iter.next(); @@ -712,12 +712,12 @@ public class TextureIO { throw new IOException("No suitable texture writer found for "+file.getAbsolutePath()); } - + //---------------------------------------------------------------------- // SPI support // - /** + /** * Adds a TextureProvider to support reading of a new file format. *

          * The last provider added, will be the first provider to be tested. @@ -730,7 +730,7 @@ public class TextureIO { textureProviders.add(0, provider); } - /** + /** * Adds a TextureWriter to support writing of a new file format. *

          * The last provider added, will be the first provider to be tested. @@ -779,7 +779,7 @@ public class TextureIO { private static List textureProviders = new ArrayList(); private static List textureWriters = new ArrayList(); - static { + static { // ImageIO provider, the fall-back, must be the first one added if(GLProfile.isAWTAvailable()) { try { @@ -1221,7 +1221,7 @@ public class TextureIO { return null; } } - + //---------------------------------------------------------------------- // DDS texture writer // @@ -1249,7 +1249,7 @@ public class TextureIO { case GL.GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: d3dFormat = DDSImage.D3DFMT_DXT5; break; default: throw new IOException("Unsupported pixel format 0x" + Integer.toHexString(pixelFormat) + " by DDS writer"); } - + ByteBuffer[] mipmaps = null; if (data.getMipmapData() != null) { mipmaps = new ByteBuffer[data.getMipmapData().length]; @@ -1319,7 +1319,7 @@ public class TextureIO { //---------------------------------------------------------------------- // TGA (Targa) texture writer - + static class TGATextureWriter implements TextureWriter { public boolean write(File file, TextureData data) throws IOException { @@ -1329,19 +1329,19 @@ public class TextureIO { final int pixelFormat = pixelAttribs.format; final int pixelType = pixelAttribs.type; if ((pixelFormat == GL.GL_RGB || - pixelFormat == GL.GL_RGBA || + pixelFormat == GL.GL_RGBA || pixelFormat == GL2.GL_BGR || pixelFormat == GL.GL_BGRA ) && (pixelType == GL.GL_BYTE || pixelType == GL.GL_UNSIGNED_BYTE)) { - + ByteBuffer buf = (ByteBuffer) data.getBuffer(); if (null == buf) { buf = (ByteBuffer) data.getMipmapData()[0]; } buf.rewind(); - - if( pixelFormat == GL.GL_RGB || pixelFormat == GL.GL_RGBA ) { + + if( pixelFormat == GL.GL_RGB || pixelFormat == GL.GL_RGBA ) { // Must reverse order of red and blue channels to get correct results int skip = ((pixelFormat == GL.GL_RGB) ? 3 : 4); for (int i = 0; i < buf.remaining(); i += skip) { @@ -1364,12 +1364,12 @@ public class TextureIO { } return false; - } + } } //---------------------------------------------------------------------- // PNG texture writer - + static class PNGTextureWriter implements TextureWriter { public boolean write(File file, TextureData data) throws IOException { if (PNG.equals(IOUtil.getFileSuffix(file))) { @@ -1402,13 +1402,13 @@ public class TextureIO { break; } if ( ( 1 == bytesPerPixel || 3 == bytesPerPixel || 4 == bytesPerPixel) && - ( pixelType == GL.GL_BYTE || pixelType == GL.GL_UNSIGNED_BYTE)) { + ( pixelType == GL.GL_BYTE || pixelType == GL.GL_UNSIGNED_BYTE)) { ByteBuffer buf = (ByteBuffer) data.getBuffer(); if (null == buf) { buf = (ByteBuffer) data.getMipmapData()[0]; } buf.rewind(); - + PNGImage image = PNGImage.createFromData(data.getWidth(), data.getHeight(), -1f, -1f, bytesPerPixel, reversedChannels, !data.getMustFlipVertically(), buf); image.write(file, true); @@ -1418,9 +1418,9 @@ public class TextureIO { " / type 0x"+Integer.toHexString(pixelFormat)+" (only GL_RGB/A, GL_BGR/A + bytes)"); } return false; - } + } } - + //---------------------------------------------------------------------- // Helper routines // diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java index 5c6b63535..e4f72abf0 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -36,26 +36,26 @@ import com.jogamp.opengl.util.TimeFrameI; /** * Protocol for texture sequences, like animations, movies, etc. *

          - * Ensure to respect the texture coordinates provided by + * Ensure to respect the texture coordinates provided by * {@link TextureFrame}.{@link TextureFrame#getTexture() getTexture()}.{@link Texture#getImageTexCoords() getImageTexCoords()}. *

          - * The user's shader shall be fitted for this implementation. + * The user's shader shall be fitted for this implementation. * Assuming we use a base shader code w/o headers using
          ShaderCode
          . * (Code copied from unit test / demo TexCubeES2) *
          - * 
          + *
               static final String[] es2_prelude = { "#version 100\n", "precision mediump float;\n" };
               static final String gl2_prelude = "#version 110\n";
               static final String shaderBasename = "texsequence_xxx";  // the base shader code w/o headers
          -    static final String myTextureLookupName = "myTexture2D"; // the desired texture lookup function    
          -    
          +    static final String myTextureLookupName = "myTexture2D"; // the desired texture lookup function
          +
               private void initShader(GL2ES2 gl, TextureSequence texSeq) {
                   // Create & Compile the shader objects
          -        ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, TexCubeES2.class, 
          +        ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, TexCubeES2.class,
                                                       "shader", "shader/bin", shaderBasename, true);
          -        ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, TexCubeES2.class, 
          +        ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, TexCubeES2.class,
                                                       "shader", "shader/bin", shaderBasename, true);
          -        
          +
                   // Prelude shader code w/ GLSL profile specifics [ 1. pre-proc, 2. other ]
                   int rsFpPos;
                   if(gl.isGLES2()) {
          @@ -72,25 +72,25 @@ import com.jogamp.opengl.util.TimeFrameI;
                   if(gl.isGLES2()) {
                       // insert ES2 default precision declaration
                       rsFpPos = rsFp.insertShaderSource(0, rsFpPos, es2_prelude[1]);
          -        }        
          +        }
                   // negotiate the texture lookup function name
                   final String texLookupFuncName = texSeq.getTextureLookupFunctionName(myTextureLookupName);
          -        
          -        // in case a fixed lookup function is being chosen, replace the name in our code        
          +
          +        // in case a fixed lookup function is being chosen, replace the name in our code
                   rsFp.replaceInShaderSource(myTextureLookupName, texLookupFuncName);
          -        
          +
                   // Cache the TextureSequence shader details in StringBuilder:
                   final StringBuilder sFpIns = new StringBuilder();
          -        
          +
                   // .. declaration of the texture sampler using the implementation specific type
                   sFpIns.append("uniform ").append(texSeq.getTextureSampler2DType()).append(" mgl_ActiveTexture;\n");
          -        
          +
                   // .. the actual texture lookup function, maybe null in case a built-in function is being used
                   sFpIns.append(texSeq.getTextureLookupFragmentShaderImpl());
          -        
          +
                   // Now insert the TextureShader details in our shader after the given tag:
                   rsFp.insertShaderSource(0, "TEXTURE-SEQUENCE-CODE-BEGIN", 0, sFpIns);
          -        
          +
                   // Create & Link the shader program
                   ShaderProgram sp = new ShaderProgram();
                   sp.add(rsVp);
          @@ -102,16 +102,16 @@ import com.jogamp.opengl.util.TimeFrameI;
            * 
          * The above procedure might look complicated, however, it allows most flexibility and * workarounds to also deal with GLSL bugs. - * + * */ public interface TextureSequence { public static final String GL_OES_EGL_image_external_Required_Prelude = "#extension GL_OES_EGL_image_external : enable\n"; public static final String samplerExternalOES = "samplerExternalOES"; public static final String sampler2D = "sampler2D"; - - /** + + /** * Texture holder interface, maybe specialized by implementation - * to associated related data. + * to associated related data. */ public static class TextureFrame extends TimeFrameI { public TextureFrame(Texture t, int pts, int duration) { @@ -121,9 +121,9 @@ public interface TextureSequence { public TextureFrame(Texture t) { texture = t; } - + public final Texture getTexture() { return texture; } - + public String toString() { return "TextureFrame[pts " + pts + " ms, l " + duration + " ms, texID "+ (null != texture ? texture.getTextureObject() : 0) + "]"; } @@ -139,30 +139,30 @@ public interface TextureSequence { *

          * Further more, the call may happen off-thread, possibly holding another, possibly shared, OpenGL context current. *

          - * Hence a user shall not issue any OpenGL, time consuming + * Hence a user shall not issue any OpenGL, time consuming * or {@link TextureSequence} lifecycle operations directly.
          * Instead, the user shall: *
            *
          • issue commands off-thread via spawning off another thread, or
          • *
          • injecting {@link GLRunnable} objects via {@link GLAutoDrawable#invoke(boolean, GLRunnable)}, or
          • *
          • simply changing a volatile state of their {@link GLEventListener} implementation.
          • - *
          + * *

          * */ public interface TexSeqEventListener { - /** + /** * Signaling listeners that a new {@link TextureFrame} is available. *

          - * User shall utilize {@link TextureSequence#getNextTexture(GL)} to dequeue it to maintain - * a consistent queue. + * User shall utilize {@link TextureSequence#getNextTexture(GL)} to dequeue it to maintain + * a consistent queue. *

          - * @param ts the event source + * @param ts the event source * @param newFrame the newly enqueued frame - * @param when system time in msec. + * @param when system time in msec. **/ public void newFrameAvailable(T ts, TextureFrame newFrame, long when); } - + /** Return the texture unit used to render the current frame. */ public int getTextureUnit(); @@ -174,17 +174,17 @@ public interface TextureSequence { * Returns the last updated texture. *

          * In case the instance is just initialized, it shall return a TextureFrame - * object with valid attributes. The texture content may be undefined + * object with valid attributes. The texture content may be undefined * until the first call of {@link #getNextTexture(GL)}.
          - *

          + *

          * Not blocking. - * - * @throws IllegalStateException if instance is not initialized + * + * @throws IllegalStateException if instance is not initialized */ public TextureFrame getLastTexture() throws IllegalStateException ; /** - * Returns the next texture to be rendered. + * Returns the next texture to be rendered. *

          * Implementation shall return the next frame if available, may block if a next frame may arrive soon. * Otherwise implementation shall return the last frame. @@ -192,41 +192,41 @@ public interface TextureSequence { *

          * Shall return null in case no next or last frame is available. *

          - * - * @throws IllegalStateException if instance is not initialized + * + * @throws IllegalStateException if instance is not initialized */ public TextureFrame getNextTexture(GL gl) throws IllegalStateException ; - + /** - * In case a shader extension is required, based on the implementation + * In case a shader extension is required, based on the implementation * and the runtime GL profile, this method returns the preprocessor macros, e.g.: *
                * #extension GL_OES_EGL_image_external : enable
          -     * 
          - * - * @throws IllegalStateException if instance is not initialized + * + * + * @throws IllegalStateException if instance is not initialized */ public String getRequiredExtensionsShaderStub() throws IllegalStateException ; - - /** + + /** * Returns either sampler2D or samplerExternalOES - * depending on {@link #getLastTexture()}.{@link TextureFrame#getTexture() getTexture()}.{@link Texture#getTarget() getTarget()}. - * - * @throws IllegalStateException if instance is not initialized + * depending on {@link #getLastTexture()}.{@link TextureFrame#getTexture() getTexture()}.{@link Texture#getTarget() getTarget()}. + * + * @throws IllegalStateException if instance is not initialized **/ public String getTextureSampler2DType() throws IllegalStateException ; - + /** * @param desiredFuncName desired lookup function name. If null or ignored by the implementation, - * a build-in name is returned. + * a build-in name is returned. * @return the final lookup function name - * + * * @see {@link #getTextureLookupFragmentShaderImpl()} - * + * * @throws IllegalStateException if instance is not initialized */ public String getTextureLookupFunctionName(String desiredFuncName) throws IllegalStateException ; - + /** * Returns the complete texture2D lookup function code of type *
          @@ -239,14 +239,14 @@ public interface TextureSequence {
                * funcName can be negotiated and queried via {@link #getTextureLookupFunctionName(String)}.
                * 

          * Note: This function may return an empty string in case a build-in lookup - * function is being chosen. If the implementation desires so, + * function is being chosen. If the implementation desires so, * {@link #getTextureLookupFunctionName(String)} will ignore the desired function name * and returns the build-in lookup function name. *

          * @see #getTextureLookupFunctionName(String) * @see #getTextureSampler2DType() - * - * @throws IllegalStateException if instance is not initialized + * + * @throws IllegalStateException if instance is not initialized */ - public String getTextureLookupFragmentShaderImpl() throws IllegalStateException ; + public String getTextureLookupFragmentShaderImpl() throws IllegalStateException ; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureState.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureState.java index 4a5d368e3..c8437d07c 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureState.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureState.java @@ -43,55 +43,55 @@ import javax.media.opengl.GLException; * - GL.GL_TEXTURE_MAG_FILTER * - GL.GL_TEXTURE_MIN_FILTER * - GL.GL_TEXTURE_WRAP_S - * - GL.GL_TEXTURE_WRAP_T + * - GL.GL_TEXTURE_WRAP_T *
          */ public class TextureState { - /** + /** * Returns the pname to query the textureTarget currently bound to the active texture-unit. *

          * Returns 0 is textureTarget is not supported. - *

          - */ + *

          + */ public static final int getTextureTargetQueryName(int textureTarget) { final int texBindQName; switch(textureTarget) { - case GL.GL_TEXTURE_2D: texBindQName = GL.GL_TEXTURE_BINDING_2D; break; - case GL.GL_TEXTURE_CUBE_MAP: texBindQName = GL.GL_TEXTURE_BINDING_CUBE_MAP; break; - case GL2ES2.GL_TEXTURE_3D: texBindQName = GL2ES2.GL_TEXTURE_BINDING_3D; break; - case GL2GL3.GL_TEXTURE_1D: texBindQName = GL2GL3.GL_TEXTURE_BINDING_1D; break; - case GL2GL3.GL_TEXTURE_1D_ARRAY: texBindQName = GL2GL3.GL_TEXTURE_BINDING_1D_ARRAY; break; - case GL2GL3.GL_TEXTURE_2D_ARRAY: texBindQName = GL2GL3.GL_TEXTURE_BINDING_2D_ARRAY; break; - case GL2GL3.GL_TEXTURE_RECTANGLE: texBindQName = GL2GL3.GL_TEXTURE_BINDING_RECTANGLE; break; - case GL2GL3.GL_TEXTURE_BUFFER: texBindQName = GL2GL3.GL_TEXTURE_BINDING_BUFFER; break; - case GL3.GL_TEXTURE_2D_MULTISAMPLE: texBindQName = GL3.GL_TEXTURE_BINDING_2D_MULTISAMPLE; break; + case GL.GL_TEXTURE_2D: texBindQName = GL.GL_TEXTURE_BINDING_2D; break; + case GL.GL_TEXTURE_CUBE_MAP: texBindQName = GL.GL_TEXTURE_BINDING_CUBE_MAP; break; + case GL2ES2.GL_TEXTURE_3D: texBindQName = GL2ES2.GL_TEXTURE_BINDING_3D; break; + case GL2GL3.GL_TEXTURE_1D: texBindQName = GL2GL3.GL_TEXTURE_BINDING_1D; break; + case GL2GL3.GL_TEXTURE_1D_ARRAY: texBindQName = GL2GL3.GL_TEXTURE_BINDING_1D_ARRAY; break; + case GL2GL3.GL_TEXTURE_2D_ARRAY: texBindQName = GL2GL3.GL_TEXTURE_BINDING_2D_ARRAY; break; + case GL2GL3.GL_TEXTURE_RECTANGLE: texBindQName = GL2GL3.GL_TEXTURE_BINDING_RECTANGLE; break; + case GL2GL3.GL_TEXTURE_BUFFER: texBindQName = GL2GL3.GL_TEXTURE_BINDING_BUFFER; break; + case GL3.GL_TEXTURE_2D_MULTISAMPLE: texBindQName = GL3.GL_TEXTURE_BINDING_2D_MULTISAMPLE; break; case GL3.GL_TEXTURE_2D_MULTISAMPLE_ARRAY: texBindQName = GL3.GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY; break; default: texBindQName = 0; } return texBindQName; } - + private final int target; - /** + /** *
                *   0 - unit
                *   1 - texture object
                *   2 - GL.GL_TEXTURE_MAG_FILTER
                *   3 - GL.GL_TEXTURE_MIN_FILTER
                *   4 - GL.GL_TEXTURE_WRAP_S
          -     *   5 - GL.GL_TEXTURE_WRAP_T            
          +     *   5 - GL.GL_TEXTURE_WRAP_T
                * 
          */ private final int[] state = new int[] { 0, 0, 0, 0, 0, 0 }; - + private static final String toHexString(int i) { return "0x"+Integer.toHexString(i); } - + private static final int activeTexture(GL gl) { final int[] vi = { 0 }; gl.glGetIntegerv(GL.GL_ACTIVE_TEXTURE, vi, 0); return vi[0]; } - + /** * Creates a texture state for the retrieved active texture-unit and the given texture-target. * See {@link TextureState}. @@ -102,7 +102,7 @@ public class TextureState { public TextureState(GL gl, int textureTarget) throws GLException { this(gl, activeTexture(gl), textureTarget); } - + /** * Creates a texture state for the given active texture-unit and the given texture-target. * See {@link TextureState}. @@ -124,7 +124,7 @@ public class TextureState { gl.glGetTexParameteriv(target, GL.GL_TEXTURE_WRAP_S, state, 4); gl.glGetTexParameteriv(target, GL.GL_TEXTURE_WRAP_T, state, 5); } - + /** * Restores the texture-unit's texture-target state. *

          @@ -140,12 +140,12 @@ public class TextureState { gl.glTexParameteri(target, GL.GL_TEXTURE_WRAP_S, state[4]); gl.glTexParameteri(target, GL.GL_TEXTURE_WRAP_T, state[5]); } - + /** Returns the texture-unit of this state, key value. Unit is of range [ {@link GL#GL_TEXTURE0}.. ]. */ public final int getUnit() { return state[0]; } /** Returns the texture-target of this state, key value. */ public final int getTarget() { return target; } - + /** Returns the state's texture-object. */ public final int getObject() { return state[1]; } /** Returns the state's mag-filter param. */ @@ -156,12 +156,12 @@ public class TextureState { public final int getWrapS() { return state[4]; } /** Returns the state's wrap-t param. */ public final int getWrapT() { return state[5]; } - - + + public final String toString() { return "TextureState[unit "+(state[0] - GL.GL_TEXTURE0)+", target "+toHexString(target)+ ": obj "+toHexString(state[1])+ - ", filter[mag "+toHexString(state[2])+", min "+toHexString(state[3])+"], "+ + ", filter[mag "+toHexString(state[2])+", min "+toHexString(state[3])+"], "+ ": wrap[s "+toHexString(state[4])+", t "+toHexString(state[5])+"]]"; } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureData.java b/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureData.java index d7e825c1d..202c08e4e 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureData.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureData.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 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 @@ -29,7 +29,7 @@ * 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. @@ -80,7 +80,7 @@ public class AWTTextureData extends TextureData { private static final java.awt.image.ColorModel rgbaColorModel = new ComponentColorModel(java.awt.color.ColorSpace.getInstance(java.awt.color.ColorSpace.CS_sRGB), - new int[] {8, 8, 8, 8}, true, true, + new int[] {8, 8, 8, 8}, true, true, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); private static final java.awt.image.ColorModel rgbColorModel = @@ -90,7 +90,7 @@ public class AWTTextureData extends TextureData { DataBuffer.TYPE_BYTE); - /** + /** * Constructs a new TextureData object with the specified parameters * and data contained in the given BufferedImage. The resulting * TextureData "wraps" the contents of the BufferedImage, so if a @@ -113,7 +113,7 @@ public class AWTTextureData extends TextureData { * texture * @param image the image containing the texture data */ - public AWTTextureData(GLProfile glp, + public AWTTextureData(GLProfile glp, int internalFormat, int pixelFormat, boolean mipmap, @@ -142,15 +142,15 @@ public class AWTTextureData extends TextureData { (expectingGL12 && haveGL12))) { revertPixelAttributes(); } - } + } } - + @Override public GLPixelAttributes getPixelAttributes() { validatePixelAttributes(); return super.getPixelAttributes(); } - + @Override public int getPixelFormat() { validatePixelAttributes(); @@ -246,7 +246,7 @@ public class AWTTextureData extends TextureData { // we can pass the image data directly to OpenGL only if // we have an integral number of pixels in each scanline // and only if the GL_EXT_abgr extension is present - + // NOTE: disabling this code path for now as it appears it's // buggy at least on some NVidia drivers and doesn't perform // the necessary byte swapping (FIXME: needs more @@ -255,7 +255,7 @@ public class AWTTextureData extends TextureData { pixelAttributes = new GLPixelAttributes(GL2.GL_ABGR_EXT, GL.GL_UNSIGNED_BYTE); rowLength = scanlineStride / 4; alignment = 4; - + // Store a reference to the original image for later in // case it turns out that we don't have GL_EXT_abgr at the // time we're going to do the texture upload to OpenGL diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureIO.java b/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureIO.java index fdd1365f7..c70f5d0f3 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureIO.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureIO.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 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 @@ -28,11 +28,11 @@ * 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. */ @@ -100,7 +100,7 @@ public class AWTTextureIO extends TextureIO { return newTextureDataImpl(glp, image, internalFormat, pixelFormat, mipmap); } - /** + /** * Creates an OpenGL texture object from the specified BufferedImage * using the current OpenGL context. * @@ -119,7 +119,7 @@ public class AWTTextureIO extends TextureIO { return texture; } - private static TextureData newTextureDataImpl(GLProfile glp, + private static TextureData newTextureDataImpl(GLProfile glp, BufferedImage image, int internalFormat, int pixelFormat, diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/DDSImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/DDSImage.java index 3f91ae966..d75bb3767 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/DDSImage.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/DDSImage.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 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 @@ -28,11 +28,11 @@ * 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. */ @@ -166,7 +166,7 @@ public class DDSImage { public static DDSImage read(String filename) throws IOException { return read(new File(filename)); } - + /** Reads a DirectDraw surface from the specified file, returning the resulting DDSImage. @@ -212,7 +212,7 @@ public class DDSImage { } } - /** + /** * Creates a new DDSImage from data supplied by the user. The * resulting DDSImage can be written to disk using the write() * method. @@ -763,7 +763,7 @@ public class DDSImage { default: throw new IllegalArgumentException("d3dFormat must be one of the known formats"); } - + // Now check the mipmaps against this size int curSize = topmostMipmapSize; int totalSize = 0; @@ -785,7 +785,7 @@ public class DDSImage { buf.put(mipmapData[i]); } this.buf = buf; - + // Allocate and initialize a Header header = new Header(); header.size = Header.size(); diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/JPEGImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/JPEGImage.java index 4d3d088ba..471938754 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/JPEGImage.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/JPEGImage.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -40,12 +40,12 @@ import com.jogamp.common.nio.Buffers; import com.jogamp.opengl.util.texture.TextureData.ColorSpace; public class JPEGImage { - private static final boolean DEBUG = Debug.debug("JPEGImage"); - - + private static final boolean DEBUG = Debug.debug("JPEGImage"); + + /** * Reads a JPEG image from the specified InputStream, using the given color space for storage. - * + * * @param in * @param cs Storage color space, either {@link ColorSpace#RGB} or {@link ColorSpace#YCbCr}. {@link ColorSpace#YCCK} and {@link ColorSpace#CMYK} will throw an exception! * @return @@ -54,12 +54,12 @@ public class JPEGImage { public static JPEGImage read(InputStream in, ColorSpace cs) throws IOException { return new JPEGImage(in, cs); } - + /** Reads a JPEG image from the specified InputStream, using the {@link ColorSpace#RGB}. */ public static JPEGImage read(InputStream in) throws IOException { return new JPEGImage(in, ColorSpace.RGB); } - + private static class JPEGColorSink implements JPEGDecoder.ColorSink { int width=0, height=0; int sourceComponents=0; @@ -67,7 +67,7 @@ public class JPEGImage { int storageComponents; final ColorSpace storageCS; ByteBuffer data = null; - + JPEGColorSink(ColorSpace storageCM) { this.storageCS = storageCM; switch(storageCS) { @@ -79,7 +79,7 @@ public class JPEGImage { throw new IllegalArgumentException("Unsupported storage color-space: "+storageCS); } } - + @Override public final ColorSpace allocate(int width, int height, ColorSpace sourceCM, int sourceComponents) throws RuntimeException { this.width = width; @@ -96,7 +96,7 @@ public class JPEGImage { data.put(i++, r); data.put(i++, g); data.put(i++, b); - // data.put(i++, (byte)0xff); + // data.put(i++, (byte)0xff); } @Override @@ -111,12 +111,12 @@ public class JPEGImage { data.put(i++, Cb); data.put(i++, Cr); } - + public String toString() { return "JPEGPixels["+width+"x"+height+", sourceComp "+sourceComponents+", sourceCS "+sourceCS+", storageCS "+storageCS+", storageComp "+storageComponents+"]"; } }; - + private JPEGImage(InputStream in, ColorSpace cs) throws IOException { pixelStorage = new JPEGColorSink(cs); final JPEGDecoder decoder = new JPEGDecoder(); @@ -126,7 +126,7 @@ public class JPEGImage { decoder.getPixel(pixelStorage, pixelWidth, pixelHeight); data = pixelStorage.data; final boolean hasAlpha = false; - + bytesPerPixel = 3; glFormat = GL.GL_RGB; reversedChannels = false; // RGB[A] @@ -142,7 +142,7 @@ public class JPEGImage { private final int pixelWidth, pixelHeight, glFormat, bytesPerPixel; private boolean reversedChannels; private final ByteBuffer data; - + /** Returns the color space of the pixel data */ public ColorSpace getColorSpace() { return pixelStorage.storageCS; } @@ -157,10 +157,10 @@ public class JPEGImage { /** Returns true if data has the channels reversed to BGR or BGRA, otherwise RGB or RGBA is expected. */ public boolean getHasReversedChannels() { return reversedChannels; } - + /** Returns the OpenGL format for this texture; e.g. GL.GL_LUMINANCE, GL.GL_RGB or GL.GL_RGBA. */ public int getGLFormat() { return glFormat; } - + /** Returns the OpenGL data type: GL.GL_UNSIGNED_BYTE. */ public int getGLType() { return GL.GL_UNSIGNED_BYTE; } @@ -170,6 +170,6 @@ public class JPEGImage { /** Returns the raw data for this texture in the correct (bottom-to-top) order for calls to glTexImage2D. */ public ByteBuffer getData() { return data; } - + public String toString() { return "JPEGImage["+pixelWidth+"x"+pixelHeight+", bytesPerPixel "+bytesPerPixel+", reversedChannels "+reversedChannels+", "+pixelStorage+", "+data+"]"; } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataInputStream.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataInputStream.java index b7262aa3e..4020ab3c0 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataInputStream.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataInputStream.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ @@ -148,7 +148,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput } public final int readUnsignedShort() throws IOException - { + { int ch1 = dataIn.read(); int ch2 = dataIn.read(); if ((ch1 | ch2) < 0) @@ -195,7 +195,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput /** * dont call this it is not implemented. - * @return empty new string + * @return empty new string **/ public final String readLine() throws IOException { @@ -204,7 +204,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput /** * dont call this it is not implemented - * @return empty new string + * @return empty new string **/ public final String readUTF() throws IOException { @@ -213,7 +213,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput /** * dont call this it is not implemented - * @return empty new string + * @return empty new string **/ public final static String readUTF(DataInput in) throws IOException { diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataOutputStream.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataOutputStream.java index e1e1ca924..a7101a576 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataOutputStream.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataOutputStream.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java index cd42a1157..43b8eebe6 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 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 @@ -28,11 +28,11 @@ * 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. */ @@ -87,8 +87,8 @@ public class NetPbmTextureWriter implements TextureWriter { public boolean write(File file, TextureData data) throws IOException { boolean res; final int magic_old = magic; - - // file suffix selection + + // file suffix selection if (0==magic) { if (PPM.equals(IOUtil.getFileSuffix(file))) { magic = 6; @@ -97,7 +97,7 @@ public class NetPbmTextureWriter implements TextureWriter { } else { return false; } - } + } try { res = writeImpl(file, data); } finally { @@ -105,7 +105,7 @@ public class NetPbmTextureWriter implements TextureWriter { } return res; } - + private boolean writeImpl(File file, TextureData data) throws IOException { int pixelFormat = data.getPixelFormat(); final int pixelType = data.getPixelType(); @@ -115,16 +115,16 @@ public class NetPbmTextureWriter implements TextureWriter { pixelFormat == GL.GL_BGRA ) && (pixelType == GL.GL_BYTE || pixelType == GL.GL_UNSIGNED_BYTE)) { - + ByteBuffer buf = (ByteBuffer) data.getBuffer(); if (null == buf ) { buf = (ByteBuffer) data.getMipmapData()[0]; } buf.rewind(); - + int comps = ( pixelFormat == GL.GL_RGBA || pixelFormat == GL.GL_BGRA ) ? 4 : 3 ; - - if( pixelFormat == GL2.GL_BGR || pixelFormat == GL.GL_BGRA ) { + + if( pixelFormat == GL2.GL_BGR || pixelFormat == GL.GL_BGRA ) { // Must reverse order of red and blue channels to get correct results for (int i = 0; i < buf.remaining(); i += comps) { byte red = buf.get(i + 0); @@ -141,7 +141,7 @@ public class NetPbmTextureWriter implements TextureWriter { } FileOutputStream fos = IOUtil.getFileOutputStream(file, true); - + StringBuilder header = new StringBuilder(); header.append("P"); header.append(magic); @@ -171,7 +171,7 @@ public class NetPbmTextureWriter implements TextureWriter { } fos.write(header.toString().getBytes()); - + FileChannel fosc = fos.getChannel(); fosc.write(buf); fosc.force(true); @@ -180,7 +180,7 @@ public class NetPbmTextureWriter implements TextureWriter { buf.rewind(); return true; - } + } throw new IOException("NetPbmTextureWriter writer doesn't support this pixel format / type (only GL_RGB/A + bytes)"); } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java index 0f4559036..bfde1bfac 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -51,15 +51,15 @@ import com.jogamp.common.nio.Buffers; import com.jogamp.common.util.IOUtil; public class PNGImage { - private static final boolean DEBUG = Debug.debug("PNGImage"); - + private static final boolean DEBUG = Debug.debug("PNGImage"); + /** * Creates a PNGImage from data supplied by the end user. Shares * data with the passed ByteBuffer. Assumes the data is already in * the correct byte order for writing to disk, i.e., LUMINANCE, RGB or RGBA. * Orientation is bottom-to-top (OpenGL coord. default) * or top-to-bottom depending on isGLOriented. - * + * * @param width * @param height * @param dpiX @@ -74,17 +74,17 @@ public class PNGImage { int bytesPerPixel, boolean reversedChannels, boolean isGLOriented, ByteBuffer data) { return new PNGImage(width, height, dpiX, dpiY, bytesPerPixel, reversedChannels, isGLOriented, data); } - - /** + + /** * Reads a PNG image from the specified InputStream. *

          * Implicitly flip image to GL orientation, see {@link #isGLOriented()}. - *

          + *

          */ public static PNGImage read(InputStream in) throws IOException { return new PNGImage(in); } - + /** Reverse read and store, implicitly flip image to GL orientation, see {@link #isGLOriented()}. */ private static final int getPixelRGBA8(ByteBuffer d, int dOff, int[] scanline, int lineOff, boolean hasAlpha) { final int b = hasAlpha ? 4-1 : 3-1; @@ -95,11 +95,11 @@ public class PNGImage { d.put(dOff--, (byte)scanline[lineOff + 3]); // A } d.put(dOff--, (byte)scanline[lineOff + 2]); // B - d.put(dOff--, (byte)scanline[lineOff + 1]); // G + d.put(dOff--, (byte)scanline[lineOff + 1]); // G d.put(dOff--, (byte)scanline[lineOff ]); // R return dOff; } - + /** Reverse write and store, implicitly flip image from current orientation, see {@link #isGLOriented()}. Handle reversed channels (BGR[A]). */ private int setPixelRGBA8(ImageLine line, int lineOff, ByteBuffer d, int dOff, boolean hasAlpha) { final int b = hasAlpha ? 4-1 : 3-1; @@ -138,9 +138,9 @@ public class PNGImage { this.bytesPerPixel = bytesPerPixel; this.reversedChannels = reversedChannels; this.isGLOriented = isGLOriented; - this.data = data; + this.data = data; } - + private PNGImage(InputStream in) { final PngReader pngr = new PngReader(new BufferedInputStream(in), null); final ImageInfo imgInfo = pngr.imgInfo; @@ -148,12 +148,12 @@ public class PNGImage { final PngChunkTRNS trns = pngr.getMetadata().getTRNS(); final boolean indexed = imgInfo.indexed; final boolean hasAlpha = indexed ? ( trns != null ) : imgInfo.alpha ; - + final int channels = indexed ? ( hasAlpha ? 4 : 3 ) : imgInfo.channels ; if ( ! ( 1 == channels || 3 == channels || 4 == channels ) ) { throw new RuntimeException("PNGImage can only handle Lum/RGB/RGBA [1/3/4 channels] images for now. Channels "+channels + " Paletted: " + indexed); } - + bytesPerPixel = indexed ? channels : imgInfo.bytesPixel ; if ( ! ( 1 == bytesPerPixel || 3 == bytesPerPixel || 4 == bytesPerPixel ) ) { throw new RuntimeException("PNGImage can only handle Lum/RGB/RGBA [1/3/4 bpp] images for now. BytesPerPixel "+bytesPerPixel); @@ -189,14 +189,14 @@ public class PNGImage { ", bytesPerPixel "+bytesPerPixel+"/"+imgInfo.bytesPixel+ ", pixels "+pixelWidth+"x"+pixelHeight+", dpi "+dpi[0]+"x"+dpi[1]+", glFormat 0x"+Integer.toHexString(glFormat)); } - + data = Buffers.newDirectByteBuffer(bytesPerPixel * pixelWidth * pixelHeight); reversedChannels = false; // RGB[A] isGLOriented = true; int dataOff = bytesPerPixel * pixelWidth * pixelHeight - 1; // start at end-of-buffer, reverse store int[] rgbaScanline = indexed ? new int[imgInfo.cols * channels] : null; - + for (int row = 0; row < pixelHeight; row++) { final ImageLine l1 = pngr.readRow(row); int lineOff = ( pixelWidth - 1 ) * bytesPerPixel ; // start w/ last pixel in line, reverse read (PNG top-left -> OpenGL bottom-left origin) @@ -224,7 +224,7 @@ public class PNGImage { private final boolean isGLOriented; private final double[] dpi; private final ByteBuffer data; - + /** Returns the width of the image. */ public int getWidth() { return pixelWidth; } @@ -233,23 +233,23 @@ public class PNGImage { /** Returns true if data has the channels reversed to BGR or BGRA, otherwise RGB or RGBA is expected. */ public boolean getHasReversedChannels() { return reversedChannels; } - + /** - * Returns true if the drawable is rendered in + * Returns true if the drawable is rendered in * OpenGL's coordinate system, origin at bottom left. * Otherwise returns false, i.e. origin at top left. *

          * Default impl. is true, i.e. OpenGL coordinate system. - *

          + *

          */ public boolean isGLOriented() { return isGLOriented; } - + /** Returns the dpi of the image. */ public double[] getDpi() { return dpi; } - + /** Returns the OpenGL format for this texture; e.g. GL.GL_LUMINANCE, GL.GL_RGB or GL.GL_RGBA. */ public int getGLFormat() { return glFormat; } - + /** Returns the OpenGL data type: GL.GL_UNSIGNED_BYTE. */ public int getGLType() { return GL.GL_UNSIGNED_BYTE; } @@ -260,12 +260,12 @@ public class PNGImage { (bottom-to-top) order for calls to glTexImage2D. */ public ByteBuffer getData() { return data; } - public void write(File out, boolean allowOverwrite) throws IOException { - final ImageInfo imi = new ImageInfo(pixelWidth, pixelHeight, 8, (4 == bytesPerPixel) ? true : false); // 8 bits per channel, no alpha + public void write(File out, boolean allowOverwrite) throws IOException { + final ImageInfo imi = new ImageInfo(pixelWidth, pixelHeight, 8, (4 == bytesPerPixel) ? true : false); // 8 bits per channel, no alpha // open image for writing to a output stream final OutputStream outs = new BufferedOutputStream(IOUtil.getFileOutputStream(out, allowOverwrite)); try { - final PngWriter png = new PngWriter(outs, imi); + final PngWriter png = new PngWriter(outs, imi); // add some optional metadata (chunks) png.getMetadata().setDpi(dpi[0], dpi[1]); png.getMetadata().setTimeNow(0); // 0 seconds fron now = now @@ -275,7 +275,7 @@ public class PNGImage { final ImageLine l1 = new ImageLine(imi); if( isGLOriented ) { // start at last pixel at end-of-buffer, reverse read (OpenGL bottom-left -> PNG top-left origin) - int dataOff = ( pixelWidth * bytesPerPixel * ( pixelHeight - 1 ) ) + // full lines - 1 line + int dataOff = ( pixelWidth * bytesPerPixel * ( pixelHeight - 1 ) ) + // full lines - 1 line ( ( pixelWidth - 1 ) * bytesPerPixel ); // one line - 1 pixel for (int row = 0; row < pixelHeight; row++) { int lineOff = ( pixelWidth - 1 ) * bytesPerPixel ; // start w/ last pixel in line, reverse store (OpenGL bottom-left -> PNG top-left origin) @@ -306,13 +306,13 @@ public class PNGImage { } } png.writeRow(l1, row); - } + } } png.end(); } finally { IOUtil.close(outs, false); } } - - public String toString() { return "PNGImage["+pixelWidth+"x"+pixelHeight+", dpi "+dpi[0]+" x "+dpi[1]+", bytesPerPixel "+bytesPerPixel+", reversedChannels "+reversedChannels+", "+data+"]"; } + + public String toString() { return "PNGImage["+pixelWidth+"x"+pixelHeight+", dpi "+dpi[0]+" x "+dpi[1]+", bytesPerPixel "+bytesPerPixel+", reversedChannels "+reversedChannels+", "+data+"]"; } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java index d35330f58..fd96fba80 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java @@ -1,21 +1,21 @@ /* * Portions Copyright (c) 2005 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 @@ -28,11 +28,11 @@ * 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. */ @@ -72,15 +72,15 @@ public class SGIImage { byte storage; // Storage format // 0 for uncompressed // 1 for RLE compression - byte bpc; // Number of bytes per pixel channel + byte bpc; // Number of bytes per pixel channel // Legally 1 or 2 short dimension; // Number of dimensions // Legally 1, 2, or 3 // 1 means a single row, XSIZE long // 2 means a single 2D image // 3 means multiple 2D images - short xsize; // X size in pixels - short ysize; // Y size in pixels + short xsize; // X size in pixels + short ysize; // Y size in pixels short zsize; // Number of channels // 1 indicates greyscale // 3 indicates RGB @@ -233,7 +233,7 @@ public class SGIImage { //---------------------------------------------------------------------- // Internals only below this point // - + private void decodeImage(DataInputStream in) throws IOException { if (header.storage == 1) { // Read RLE compression data; row starts and sizes @@ -478,7 +478,7 @@ public class SGIImage { for (int z = 0; z < zsize; z++) { for (int y = ystart; y != yend; y += yincr) { // RLE-compress each row. - + int x = 0; byte count = 0; boolean repeat_mode = false; @@ -486,7 +486,7 @@ public class SGIImage { int start_ptr = ptr; int num_ptr = ptr++; byte repeat_val = 0; - + while (x < xsize) { // see if we should switch modes should_switch = false; @@ -503,7 +503,7 @@ public class SGIImage { if (DEBUG) System.err.println("left side was " + ((int) imgref(data, x, y, z, xsize, ysize, zsize)) + ", right side was " + (int)imgref(data, x+i, y, z, xsize, ysize, zsize)); - + if (imgref(data, x, y, z, xsize, ysize, zsize) != imgref(data, x+i, y, z, xsize, ysize, zsize)) should_switch = false; @@ -531,7 +531,7 @@ public class SGIImage { repeat_mode = true; repeat_val = imgref(data, x, y, z, xsize, ysize, zsize); } - + if (x > 0) { // reset the number pointer num_ptr = ptr++; @@ -539,7 +539,7 @@ public class SGIImage { count = 0; } } - + // if not in repeat mode, copy element to ptr if (!repeat_mode) { rlebuf[ptr++] = imgref(data, x, y, z, xsize, ysize, zsize); @@ -581,8 +581,8 @@ public class SGIImage { // Now we have the offset tables computed, as well as the RLE data. // Output this information to the file. total_size = ptr; - - if (DEBUG) + + if (DEBUG) System.err.println("total_size was " + total_size); DataOutputStream stream = new DataOutputStream(new BufferedOutputStream(IOUtil.getFileOutputStream(file, true))); @@ -604,7 +604,7 @@ public class SGIImage { byte[] dest = new byte[16384]; int pos = 0; int numRead = 0; - + boolean done = false; do { diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java index 2ff3b9cf0..df9430a26 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2003-2005 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 @@ -28,11 +28,11 @@ * 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. */ @@ -146,9 +146,9 @@ public class TGAImage { tgaType = TYPE_OLD; // dont try and get footer. // initial header fields - idLength = in.readUnsignedByte(); + idLength = in.readUnsignedByte(); colorMapType = in.readUnsignedByte(); - imageType = in.readUnsignedByte(); + imageType = in.readUnsignedByte(); // color map header fields firstEntryIndex = in.readUnsignedShort(); @@ -288,14 +288,14 @@ public class TGAImage { throw new IOException("TGADecoder Compressed Grayscale images not supported"); } } - + /** * This assumes that the body is for a 24 bit or 32 bit for a * RGB or ARGB image respectively. */ private void decodeRGBImageU24_32(GLProfile glp, LEDataInputStream dIn) throws IOException { setupImage24_32(glp); - + int i; // row index int y; // output row index int rawWidth = header.width() * bpp; @@ -317,14 +317,14 @@ public class TGAImage { swapBGR(tmpData, rawWidth, header.height(), bpp); data = ByteBuffer.wrap(tmpData); } - + /** * This assumes that the body is for a 24 bit or 32 bit for a * RGB or ARGB image respectively. */ private void decodeRGBImageRLE24_32(GLProfile glp, LEDataInputStream dIn) throws IOException { setupImage24_32(glp); - + byte[] pixel = new byte[bpp]; int rawWidth = header.width() * bpp; byte[] tmpData = new byte[rawWidth * header.height()]; @@ -341,17 +341,17 @@ public class TGAImage { dIn.read(tmpData, i, len * bpp); i += bpp * len; } - + if(format == GL.GL_RGB || format == GL.GL_RGBA) swapBGR(tmpData, rawWidth, header.height(), bpp); data = ByteBuffer.wrap(tmpData); } - + private void setupImage24_32(GLProfile glp) { bpp = header.pixelDepth / 8; switch (header.pixelDepth) { - case 24: - format = glp.isGL2GL3() ? GL2GL3.GL_BGR : GL.GL_RGB; + case 24: + format = glp.isGL2GL3() ? GL2GL3.GL_BGR : GL.GL_RGB; break; case 32: boolean useBGRA = glp.isGL2GL3(); diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TextureProvider.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TextureProvider.java index 88018edbe..0299531b1 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TextureProvider.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TextureProvider.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TextureWriter.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TextureWriter.java index 55527cef5..35b8efa72 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TextureWriter.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TextureWriter.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureProvider.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureProvider.java index 6e2f1b992..f23cb74bf 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureProvider.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureProvider.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureWriter.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureWriter.java index 89d0d20a1..438ab6cc2 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureWriter.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureWriter.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 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 @@ -28,11 +28,11 @@ * 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. */ @@ -113,7 +113,7 @@ public class IIOTextureWriter implements TextureWriter { return ImageIO.write(image, IOUtil.getFileSuffix(file), file); } - + throw new IOException("ImageIO writer doesn't support this pixel format / type (only GL_RGB/A + bytes)"); } } diff --git a/src/jogl/classes/javax/media/opengl/DebugGL2.java b/src/jogl/classes/javax/media/opengl/DebugGL2.java index 05bcf3d5e..3c064a18f 100644 --- a/src/jogl/classes/javax/media/opengl/DebugGL2.java +++ b/src/jogl/classes/javax/media/opengl/DebugGL2.java @@ -10,7 +10,7 @@ package javax.media.opengl; * Sample code which installs this pipeline, manual: *
            *     gl = drawable.setGL(new DebugGL(drawable.getGL()));
          - * 
          + * * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}. *

          */ diff --git a/src/jogl/classes/javax/media/opengl/DebugGL3.java b/src/jogl/classes/javax/media/opengl/DebugGL3.java index c17f90667..b490a63f4 100644 --- a/src/jogl/classes/javax/media/opengl/DebugGL3.java +++ b/src/jogl/classes/javax/media/opengl/DebugGL3.java @@ -10,7 +10,7 @@ package javax.media.opengl; * Sample code which installs this pipeline, manual: *
            *     gl = drawable.setGL(new DebugGL(drawable.getGL()));
          - * 
          + * * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}. *

          */ diff --git a/src/jogl/classes/javax/media/opengl/DebugGL3bc.java b/src/jogl/classes/javax/media/opengl/DebugGL3bc.java index 6e294d42b..1d42afbc6 100644 --- a/src/jogl/classes/javax/media/opengl/DebugGL3bc.java +++ b/src/jogl/classes/javax/media/opengl/DebugGL3bc.java @@ -10,7 +10,7 @@ package javax.media.opengl; * Sample code which installs this pipeline, manual: *
            *     gl = drawable.setGL(new DebugGL(drawable.getGL()));
          - * 
          + * * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}. *

          */ diff --git a/src/jogl/classes/javax/media/opengl/DebugGL4.java b/src/jogl/classes/javax/media/opengl/DebugGL4.java index d21d39390..249d850a3 100644 --- a/src/jogl/classes/javax/media/opengl/DebugGL4.java +++ b/src/jogl/classes/javax/media/opengl/DebugGL4.java @@ -10,7 +10,7 @@ package javax.media.opengl; * Sample code which installs this pipeline, manual: *
            *     gl = drawable.setGL(new DebugGL(drawable.getGL()));
          - * 
          + * * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}. *

          */ diff --git a/src/jogl/classes/javax/media/opengl/DebugGLES2.java b/src/jogl/classes/javax/media/opengl/DebugGLES2.java index dee363c1b..6d666d82a 100644 --- a/src/jogl/classes/javax/media/opengl/DebugGLES2.java +++ b/src/jogl/classes/javax/media/opengl/DebugGLES2.java @@ -10,7 +10,7 @@ package javax.media.opengl; * Sample code which installs this pipeline, manual: *
            *     gl = drawable.setGL(new DebugGL(drawable.getGL()));
          - * 
          + * * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}. *

          */ diff --git a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java index b0f3da8e4..7e243471e 100644 --- a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java +++ b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003-2009 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 @@ -29,11 +29,11 @@ * 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. */ @@ -91,7 +91,7 @@ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { Debug.initSingleton(); DEBUG = Debug.isPropertyDefined("jogl.debug.CapabilitiesChooser", true); } - + private final static int NO_SCORE = -9999999; private final static int DOUBLE_BUFFER_MISMATCH_PENALTY = 1000; private final static int OPAQUE_MISMATCH_PENALTY = 750; @@ -106,7 +106,7 @@ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { private final static int ACCUM_MISMATCH_PENALTY_SCALE = 1; private final static int STENCIL_MISMATCH_PENALTY_SCALE = 3; private final static int MULTISAMPLE_MISMATCH_PENALTY_SCALE = 3; - + @Override public int chooseCapabilities(final CapabilitiesImmutable desired, final List available, @@ -143,12 +143,12 @@ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { // Create score array int[] scores = new int[availnum]; - + for (int i = 0; i < scores.length; i++) { scores[i] = NO_SCORE; } final int gldes_samples = gldes.getNumSamples(); - + // Compute score for each for (int i = 0; i < availnum; i++) { final GLCapabilitiesImmutable cur = (GLCapabilitiesImmutable) available.get(i); @@ -165,24 +165,24 @@ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { } */ if (gldes.isPBuffer() && !cur.isPBuffer()) { continue; // requested pBuffer, but n/a - } + } if (gldes.isBitmap() && !cur.isBitmap()) { continue; // requested pBuffer, but n/a - } + } } if (gldes.getStereo() != cur.getStereo()) { continue; } final int cur_samples = cur.getNumSamples() ; 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()) - (gldes.getRedBits() + gldes.getGreenBits() + gldes.getBlueBits() + gldes.getAlphaBits()))); // Compute difference in depth buffer depth - score += (DEPTH_MISMATCH_PENALTY_SCALE * sign(score) * + score += (DEPTH_MISMATCH_PENALTY_SCALE * sign(score) * Math.abs(cur.getDepthBits() - gldes.getDepthBits())); // Compute difference in accumulation buffer depth score += (ACCUM_MISMATCH_PENALTY_SCALE * sign(score) * @@ -261,7 +261,7 @@ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser { System.err.println(" ]"); } - // Ready to select. Choose score closest to 0. + // Ready to select. Choose score closest to 0. int scoreClosestToZero = NO_SCORE; int chosenIndex = -1; for (int i = 0; i < availnum; i++) { diff --git a/src/jogl/classes/javax/media/opengl/FPSCounter.java b/src/jogl/classes/javax/media/opengl/FPSCounter.java index 9c07b58e4..4997258e0 100644 --- a/src/jogl/classes/javax/media/opengl/FPSCounter.java +++ b/src/jogl/classes/javax/media/opengl/FPSCounter.java @@ -36,28 +36,28 @@ import java.io.PrintStream; */ public interface FPSCounter { public static final int DEFAULT_FRAMES_PER_INTERVAL = 5*60; - + /** - * @param frames Update interval in frames.
          At every rendered frames interval the currentTime and fps values are updated. + * @param frames Update interval in frames.
          At every rendered frames interval the currentTime and fps values are updated. * If the frames interval is <= 0, no update will be issued, ie the FPSCounter feature is turned off. You may choose {@link #DEFAULT_FRAMES_PER_INTERVAL}. - * @param out optional print stream where the fps values gets printed if not null at every frames interval + * @param out optional print stream where the fps values gets printed if not null at every frames interval */ void setUpdateFPSFrames(int frames, PrintStream out); - + /** * Reset all performance counter (startTime, currentTime, frame number) */ void resetFPSCounter(); - + /** * @return update interval in frames - * + * * @see #setUpdateFPSFrames(int, PrintStream) */ int getUpdateFPSFrames(); - + /** - * Returns the time of the first display call in milliseconds after enabling this feature via {@link #setUpdateFPSFrames(int, PrintStream)}.
          + * Returns the time of the first display call in milliseconds after enabling this feature via {@link #setUpdateFPSFrames(int, PrintStream)}.
          * This value is reset via {@link #resetFPSCounter()}. * * @see #setUpdateFPSFrames(int, PrintStream) @@ -81,18 +81,18 @@ public interface FPSCounter { * @see #resetFPSCounter() */ long getLastFPSPeriod(); - + /** * @return Last update interval's frames per seconds, {@link #getUpdateFPSFrames()} / {@link #getLastFPSPeriod()} - * + * * @see #setUpdateFPSFrames(int, PrintStream) * @see #resetFPSCounter() */ - float getLastFPS(); - + float getLastFPS(); + /** * @return Number of frame rendered since {@link #getFPSStartTime()} up to {@link #getLastFPSUpdateTime()} - * + * * @see #setUpdateFPSFrames(int, PrintStream) * @see #resetFPSCounter() */ @@ -108,10 +108,10 @@ public interface FPSCounter { /** - * @return Total frames per seconds, {@link #getTotalFPSFrames()} / {@link #getTotalFPSDuration()} - * + * @return Total frames per seconds, {@link #getTotalFPSFrames()} / {@link #getTotalFPSDuration()} + * * @see #setUpdateFPSFrames(int, PrintStream) * @see #resetFPSCounter() */ - float getTotalFPS(); + float getTotalFPS(); } diff --git a/src/jogl/classes/javax/media/opengl/GLAnimatorControl.java b/src/jogl/classes/javax/media/opengl/GLAnimatorControl.java index a72403eae..827145654 100644 --- a/src/jogl/classes/javax/media/opengl/GLAnimatorControl.java +++ b/src/jogl/classes/javax/media/opengl/GLAnimatorControl.java @@ -29,7 +29,7 @@ package javax.media.opengl; /** - * An animator control interface, + * An animator control interface, * which implementation may drive a {@link javax.media.opengl.GLAutoDrawable} animation. */ public interface GLAnimatorControl extends FPSCounter { @@ -56,8 +56,8 @@ public interface GLAnimatorControl extends FPSCounter { boolean isAnimating(); /** - * Indicates whether this animator {@link #isStarted() is started} - * and either {@link #pause() manually paused} or paused + * Indicates whether this animator {@link #isStarted() is started} + * and either {@link #pause() manually paused} or paused * automatically due to no {@link #add(GLAutoDrawable) added} {@link GLAutoDrawable}s. * * @see #start() @@ -157,15 +157,15 @@ public interface GLAnimatorControl extends FPSCounter { /** * Adds a drawable to this animator's list of rendering drawables. *

          - * This allows the animator thread to become {@link #isAnimating() animating}, + * This allows the animator thread to become {@link #isAnimating() animating}, * in case the first drawable is added and the animator {@link #isStarted() is started}. *

          - * + * * @param drawable the drawable to be added * @throws IllegalArgumentException if drawable was already added to this animator */ void add(GLAutoDrawable drawable); - + /** * Removes a drawable from the animator's list of rendering drawables. *

          @@ -173,10 +173,10 @@ public interface GLAnimatorControl extends FPSCounter { * and will not be recovered. *

          *

          - * This allows the animator thread to become {@link #isAnimating() not animating}, + * This allows the animator thread to become {@link #isAnimating() not animating}, * in case the last drawable has been removed. *

          - * + * * @param drawable the drawable to be removed * @throws IllegalArgumentException if drawable was not added to this animator */ diff --git a/src/jogl/classes/javax/media/opengl/GLArrayData.java b/src/jogl/classes/javax/media/opengl/GLArrayData.java index 8e1383031..4025170cf 100644 --- a/src/jogl/classes/javax/media/opengl/GLArrayData.java +++ b/src/jogl/classes/javax/media/opengl/GLArrayData.java @@ -43,7 +43,7 @@ public interface GLArrayData { * Implementation and type dependent object association. *

          * One currently known use case is to associate a {@link com.jogamp.opengl.util.glsl.ShaderState ShaderState} - * to an GLSL aware vertex attribute object, allowing to use the ShaderState to handle it's + * to an GLSL aware vertex attribute object, allowing to use the ShaderState to handle it's * data persistence, location and state change.
          * This is implicitly done via {@link com.jogamp.opengl.util.glsl.ShaderState#ownAttribute(GLArrayData, boolean) shaderState.ownAttribute(GLArrayData, boolean)}. *

          @@ -51,7 +51,7 @@ public interface GLArrayData { * @param enable pass true to enable the association and false to disable it. */ public void associate(Object obj, boolean enable); - + /** * Returns true if this data set is intended for a GLSL vertex shader attribute, * otherwise false, ie intended for fixed function vertex pointer @@ -110,7 +110,7 @@ public interface GLArrayData { * <0 denotes an invalid location, i.e. not found or used in the given shader program. */ public int setLocation(GL2ES2 gl, int program); - + /** * Binds the location of the shader attribute to the given location for the unlinked shader program. *

          @@ -121,7 +121,7 @@ public interface GLArrayData { * @return the given location */ public int setLocation(GL2ES2 gl, int program, int location); - + /** * Determines whether the data is server side (VBO) and enabled, * or a client side array (false). @@ -150,7 +150,7 @@ public interface GLArrayData { */ public int getVBOTarget(); - + /** * The Buffer holding the data, may be null if a GPU buffer without client bound data */ @@ -179,7 +179,7 @@ public interface GLArrayData { * In case the buffer's position is 0 (sealed, flipped), it's based on it's limit instead of it's position. */ public int getElementCount(); - + /** * The currently used size in bytes.
          * In case the buffer's position is 0 (sealed, flipped), it's based on it's limit instead of it's position. @@ -187,18 +187,18 @@ public interface GLArrayData { public int getSizeInBytes(); /** - * True, if GL shall normalize fixed point data while converting + * True, if GL shall normalize fixed point data while converting * them into float. - *

          + *

          * Default behavior (of the fixed function pipeline) is true * for fixed point data type and false for floating point data types. *

          */ public boolean getNormalized(); - /** + /** * @return the byte offset between consecutive components - */ + */ public int getStride(); public String toString(); diff --git a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java index 989a61aaf..38824ce8f 100644 --- a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java +++ b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java @@ -50,8 +50,8 @@ import jogamp.opengl.Debug; rendering context which is associated with the GLAutoDrawable for the lifetime of the object.

          - Since the {@link GLContext} {@link GLContext#makeCurrent makeCurrent} - implementation is synchronized, i.e. blocks if the context + Since the {@link GLContext} {@link GLContext#makeCurrent makeCurrent} + implementation is synchronized, i.e. blocks if the context is current on another thread, the internal {@link GLContext} for the GLAutoDrawable can be used for the event based rendering mechanism and by end users directly. @@ -123,7 +123,7 @@ public interface GLAutoDrawable extends GLDrawable { * otherwise return this instance. */ public GLDrawable getDelegatedDrawable(); - + /** * Returns the context associated with this drawable. The returned * context will be synchronized. @@ -135,38 +135,38 @@ public interface GLAutoDrawable extends GLDrawable { * Associate the new context, newtCtx, to this auto-drawable. *

          * The current context will be destroyed if destroyPrevCtx is true, - * otherwise it will be dis-associated from this auto-drawable + * otherwise it will be dis-associated from this auto-drawable * via {@link GLContext#setGLDrawable(GLDrawable, boolean) setGLDrawable(null, true);} first. *

          *

          - * The new context will be associated with this auto-drawable + * The new context will be associated with this auto-drawable * via {@link GLContext#setGLDrawable(GLDrawable, boolean) newCtx.setGLDrawable(drawable, true);}. - *

          + *

          *

          * If the old or new context was current on this thread, it is being released before switching the association. - * The new context will be made current afterwards, if it was current before. + * The new context will be made current afterwards, if it was current before. * However the user shall take extra care that no other thread * attempts to make this context current. *

          - * + * * @param newCtx the new context, maybe null for dis-association. - * @param destroyPrevCtx if true, destroy the previous context if exists + * @param destroyPrevCtx if true, destroy the previous context if exists * @return the previous GLContext, maybe null - * + * * @see GLContext#setGLDrawable(GLDrawable, boolean) * @see GLContext#setGLReadDrawable(GLDrawable) * @see jogamp.opengl.GLDrawableHelper#switchContext(GLDrawable, GLContext, boolean, GLContext, int) */ public GLContext setContext(GLContext newCtx, boolean destroyPrevCtx); - + /** * Adds the given {@link GLEventListener listener} to the end of this drawable queue. * The {@link GLEventListener listeners} are notified of events in the order of the queue. *

          - * The newly added listener's {@link GLEventListener#init(GLAutoDrawable) init(..)} + * The newly added listener's {@link GLEventListener#init(GLAutoDrawable) init(..)} * method will be called once before any other of it's callback methods. * See {@link #getGLEventListenerInitState(GLEventListener)} for details. - *

          + *

          * @param listener The GLEventListener object to be inserted */ public void addGLEventListener(GLEventListener listener); @@ -175,10 +175,10 @@ public interface GLAutoDrawable extends GLDrawable { * Adds the given {@link GLEventListener listener} at the given index of this drawable queue. * The {@link GLEventListener listeners} are notified of events in the order of the queue. *

          - * The newly added listener's {@link GLEventListener#init(GLAutoDrawable) init(..)} + * The newly added listener's {@link GLEventListener#init(GLAutoDrawable) init(..)} * method will be called once before any other of it's callback methods. * See {@link #getGLEventListenerInitState(GLEventListener)} for details. - *

          + *

          * @param index Position where the listener will be inserted. * Should be within (0 <= index && index <= size()). * An index value of -1 is interpreted as the end of the list, size(). @@ -192,7 +192,7 @@ public interface GLAutoDrawable extends GLDrawable { * @return The number of GLEventListener objects of this drawable queue. */ public int getGLEventListenerCount(); - + /** * Returns the {@link GLEventListener} at the given index of this drawable queue. * @param index Position of the listener to be returned. @@ -202,18 +202,18 @@ public interface GLAutoDrawable extends GLDrawable { * @throws IndexOutOfBoundsException If the index is not within (0 <= index && index < size()), or -1 */ public GLEventListener getGLEventListener(int index) throws IndexOutOfBoundsException; - + /** * Retrieves whether the given {@link GLEventListener listener} is initialized or not. *

          - * After {@link #addGLEventListener(GLEventListener) adding} a {@link GLEventListener} it is + * After {@link #addGLEventListener(GLEventListener) adding} a {@link GLEventListener} it is * marked uninitialized and added to a list of to be initialized {@link GLEventListener}. - * If such uninitialized {@link GLEventListener}'s handler methods (reshape, display) + * If such uninitialized {@link GLEventListener}'s handler methods (reshape, display) * are about to be invoked, it's {@link GLEventListener#init(GLAutoDrawable) init(..)} method is invoked first. * Afterwards the {@link GLEventListener} is marked initialized * and removed from the list of to be initialized {@link GLEventListener}. *

          - *

          + *

          * This methods returns the {@link GLEventListener} initialized state, * i.e. returns false if it is included in the list of to be initialized {@link GLEventListener}, * otherwise true. @@ -221,17 +221,17 @@ public interface GLAutoDrawable extends GLDrawable { * @param listener the GLEventListener object to query it's initialized state. */ public boolean getGLEventListenerInitState(GLEventListener listener); - + /** * Sets the given {@link GLEventListener listener's} initialized state. - *

          + *

          * This methods allows manually setting the {@link GLEventListener} initialized state, * i.e. adding it to, or removing it from the list of to be initialized {@link GLEventListener}. * See {@link #getGLEventListenerInitState(GLEventListener)} for details. *

          *

          * Warning: This method does not validate whether the given {@link GLEventListener listener's} - * is member of this drawable queue, i.e. {@link #addGLEventListener(GLEventListener) added}. + * is member of this drawable queue, i.e. {@link #addGLEventListener(GLEventListener) added}. *

          *

          * This method is only exposed to allow users full control over the {@link GLEventListener}'s state @@ -239,16 +239,16 @@ public interface GLAutoDrawable extends GLDrawable { *

          *

          * One use case is moving a {@link GLContext} and their initialized {@link GLEventListener} - * from one {@link GLAutoDrawable} to another, + * from one {@link GLAutoDrawable} to another, * where a subsequent {@link GLEventListener#init(GLAutoDrawable) init(..)} call after adding it - * to the new owner is neither required nor desired. + * to the new owner is neither required nor desired. * See {@link com.jogamp.opengl.util.GLDrawableUtil#swapGLContextAndAllGLEventListener(GLAutoDrawable, GLAutoDrawable) swapGLContextAndAllGLEventListener(..)}. *

          * @param listener the GLEventListener object to perform a state change. - * @param initialized if true, mark the listener initialized, otherwise uninitialized. + * @param initialized if true, mark the listener initialized, otherwise uninitialized. */ public void setGLEventListenerInitState(GLEventListener listener, boolean initialized); - + /** * Disposes the given {@link GLEventListener listener} via {@link GLEventListener#dispose(GLAutoDrawable) dispose(..)} * if it has been initialized and added to this queue. @@ -257,7 +257,7 @@ public interface GLAutoDrawable extends GLDrawable { * otherwise marked uninitialized. *

          *

          - * If an {@link GLAnimatorControl} is being attached and the current thread is different + * If an {@link GLAnimatorControl} is being attached and the current thread is different * than {@link GLAnimatorControl#getThread() the animator's thread}, it is paused during the operation. *

          *

          @@ -268,8 +268,8 @@ public interface GLAutoDrawable extends GLDrawable { * Use {@link #removeGLEventListener(GLEventListener) removeGLEventListener(listener)} instead * if you just want to remove the {@link GLEventListener listener} and don't care about the disposal of the it's (OpenGL) resources. *

          - *

          - * Also note that this is done from within a particular drawable's + *

          + * Also note that 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. @@ -277,30 +277,30 @@ public interface GLAutoDrawable extends GLDrawable { * @param listener The GLEventListener object to be disposed and removed if remove is true * @param remove pass true to have the listener removed from this drawable queue, otherwise pass false * @return the disposed and/or removed GLEventListener, or null if no action was performed, i.e. listener was not added - */ + */ public GLEventListener disposeGLEventListener(GLEventListener listener, boolean remove); - - /** + + /** * Removes the given {@link GLEventListener listener} from this drawable queue. *

          - * This is an inexpensive operation, since the removed listener's + * This is an inexpensive operation, since the removed listener's * {@link GLEventListener#dispose(GLAutoDrawable) dispose(..)} method will not be called. *

          *

          - * Use {@link #disposeGLEventListener(GLEventListener, boolean) disposeGLEventListener(listener, true)} + * Use {@link #disposeGLEventListener(GLEventListener, boolean) disposeGLEventListener(listener, true)} * instead to ensure disposal of the {@link GLEventListener listener}'s (OpenGL) resources. - *

          - *

          - * Note that if this is done from within a particular drawable's + *

          + *

          + * 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. *

          * @param listener The GLEventListener object to be removed * @return the removed GLEventListener, or null if listener was not added - */ + */ public GLEventListener removeGLEventListener(GLEventListener listener); - + /** * Registers the usage of an animator, an {@link javax.media.opengl.GLAnimatorControl} implementation. * The animator will be queried whether it's animating, ie periodically issuing {@link #display()} calls or not. @@ -334,17 +334,17 @@ public interface GLAutoDrawable extends GLDrawable { /** * Dedicates this instance's {@link GLContext} to the given thread.
          * The thread will exclusively claim the {@link GLContext} via {@link #display()} and not release it - * until {@link #destroy()} or setExclusiveContextThread(null) has been called. + * until {@link #destroy()} or setExclusiveContextThread(null) has been called. *

          * Default non-exclusive behavior is requested via setExclusiveContextThread(null), - * which will cause the next call of {@link #display()} on the exclusive thread to - * release the {@link GLContext}. Only after it's async release, {@link #getExclusiveContextThread()} + * which will cause the next call of {@link #display()} on the exclusive thread to + * release the {@link GLContext}. Only after it's async release, {@link #getExclusiveContextThread()} * will return null. *

          *

          * To release a previous made exclusive thread, a user issues setExclusiveContextThread(null) - * and may poll {@link #getExclusiveContextThread()} until it returns null, - * while the exclusive thread is still running. + * and may poll {@link #getExclusiveContextThread()} until it returns null, + * while the exclusive thread is still running. *

          *

          * Note: Setting a new exclusive thread without properly releasing a previous one @@ -359,17 +359,17 @@ public interface GLAutoDrawable extends GLDrawable { * and spare redundant context switches, see {@link com.jogamp.opengl.util.AnimatorBase#setExclusiveContext(boolean)}. *

          * @param t the exclusive thread to claim the context, or null for default operation. - * @return previous exclusive context thread + * @return previous exclusive context thread * @throws GLException If an exclusive thread is still active but a new one is attempted to be set * @see com.jogamp.opengl.util.AnimatorBase#setExclusiveContext(boolean) */ public Thread setExclusiveContextThread(Thread t) throws GLException; - + /** - * @see #setExclusiveContextThread(Thread) + * @see #setExclusiveContextThread(Thread) */ public Thread getExclusiveContextThread(); - + /** * Enqueues a one-shot {@link GLRunnable}, * which will be executed within the next {@link #display()} call @@ -391,7 +391,7 @@ public interface GLAutoDrawable extends GLDrawable { * has been executed by the {@link GLAnimatorControl animator}, otherwise the method returns immediately. *

          *

          - * If wait is true and + * If wait is true and * {@link #isRealized()} returns false or {@link #getContext()} returns null, * the call is ignored and returns false.
          * This helps avoiding deadlocking the caller. @@ -404,16 +404,16 @@ public interface GLAutoDrawable extends GLDrawable { * @param wait if true block until execution of glRunnable is finished, otherwise return immediately w/o waiting * @param glRunnable the {@link GLRunnable} to execute within {@link #display()} * @return true if the {@link GLRunnable} has been processed or queued, otherwise false. - * + * * @see #setAnimator(GLAnimatorControl) * @see #display() * @see GLRunnable * @see #invoke(boolean, List) */ public boolean invoke(boolean wait, GLRunnable glRunnable); - + /** - * Extends {@link #invoke(boolean, GLRunnable)} functionality + * Extends {@link #invoke(boolean, GLRunnable)} functionality * allowing to inject a list of {@link GLRunnable}s. * @param wait if true block until execution of the last glRunnable is finished, otherwise return immediately w/o waiting * @param glRunnables the {@link GLRunnable}s to execute within {@link #display()} @@ -494,16 +494,16 @@ public interface GLAutoDrawable extends GLDrawable { *

          * This GLAutoDrawable implementation holds it's own GLContext reference, * thus created a GLContext using this methods won't replace it implicitly. - * To replace or set this GLAutoDrawable's GLContext you need to call {@link #setContext(GLContext, boolean)}. + * To replace or set this GLAutoDrawable's GLContext you need to call {@link #setContext(GLContext, boolean)}. *

          *

          - * The GLAutoDrawable implementation shall also set the - * context creation flags as customized w/ {@link #setContextCreationFlags(int)}. + * The GLAutoDrawable implementation shall also set the + * context creation flags as customized w/ {@link #setContextCreationFlags(int)}. *

          */ @Override public GLContext createContext(GLContext shareWith); - + /** 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 @@ -522,13 +522,13 @@ public interface GLAutoDrawable extends GLDrawable { demos for examples. @return the set GL pipeline or null if not successful */ public GL setGL(GL gl); - + /** * Method may return the upstream UI toolkit object * holding this {@link GLAutoDrawable} instance, if exist. *

          * Currently known Java UI toolkits and it's known return types are: - * + * *

          *
          Toolkit GLAutoDrawable Implementation ~ Return Type of getUpstreamWidget() *
          NEWT {@link com.jogamp.newt.opengl.GLWindow} has a {@link com.jogamp.newt.Window} @@ -536,7 +536,7 @@ public interface GLAutoDrawable extends GLDrawable { *
          AWT {@link javax.media.opengl.awt.GLCanvas} is a {@link java.awt.Canvas} *
          AWT {@link javax.media.opengl.awt.GLJPanel} is a {@link javax.swing.JPanel} *
          - * However, the result may be other object types than the listed above + * However, the result may be other object types than the listed above * due to new supported toolkits. *

          *

          diff --git a/src/jogl/classes/javax/media/opengl/GLBase.java b/src/jogl/classes/javax/media/opengl/GLBase.java index 1f75a7b4a..e84dd7be9 100644 --- a/src/jogl/classes/javax/media/opengl/GLBase.java +++ b/src/jogl/classes/javax/media/opengl/GLBase.java @@ -32,7 +32,7 @@ package javax.media.opengl; /** *

          The base interface from which all GL profiles derive, providing * checked conversion down to concrete profiles, access to the - * OpenGL context associated with the GL and extension/function + * OpenGL context associated with the GL and extension/function * availability queries as described below.

          * *

          While the APIs for vendor extensions are unconditionally @@ -79,7 +79,7 @@ package javax.media.opengl; * */ public interface GLBase { - + /** * Indicates whether this GL object conforms to any of the OpenGL profiles. */ @@ -131,7 +131,7 @@ public interface GLBase { *

          * Remark: ES2 compatible desktop profiles are not included. * To query whether core ES2 functionality is provided, use {@link #isGLES2Compatible()}. - *

          + *

          * @see #isGLES2Compatible() * @see GLContext#isGLES2() */ @@ -142,12 +142,12 @@ public interface GLBase { *

          * Remark: ES3 compatible desktop profiles are not included. * To query whether core ES3 functionality is provided, use {@link #isGLES3Compatible()}. - *

          + *

          * @see #isGLES3Compatible() * @see GLContext#isGLES3() */ public boolean isGLES3(); - + /** * Indicates whether this GL object conforms to one of the OpenGL ES profiles, * see {@link #isGLES1()} and {@link #isGLES2()}. @@ -180,7 +180,7 @@ public interface GLBase { public boolean isGL3ES3(); /** - * Returns true if this GL object conforms to a GL4ES3 compatible profile, i.e. if {@link #isGLES3Compatible()} returns true. + * Returns true if this GL object conforms to a GL4ES3 compatible profile, i.e. if {@link #isGLES3Compatible()} returns true. *

          Includes [ GL ≥ 4.3, GL ≥ 3.1 w/ GL_ARB_ES3_compatibility and GLES3 ]

          * @see GLContext#isGL4ES3() */ @@ -192,29 +192,29 @@ public interface GLBase { */ public boolean isGL2GL3(); - /** + /** * Indicates whether this GL object uses a GL4 core profile.

          Includes [ GL4 ].

          * @see GLContext#isGL4core() */ public boolean isGL4core(); - - /** + + /** * Indicates whether this GL object uses a GL3 core profile.

          Includes [ GL4, GL3 ].

          * @see GLContext#isGL3core() */ public boolean isGL3core(); - - /** + + /** * Indicates whether this GL object uses a GL core profile.

          Includes [ GL4, GL3, GLES3, GL2ES2 ].

          * @see GLContext#isGLcore() */ public boolean isGLcore(); - + /** * Indicates whether this GL object is compatible with the core OpenGL ES2 functionality. - * @return true if this context is an ES2 context or implements + * @return true if this context is an ES2 context or implements * the extension GL_ARB_ES2_compatibility, otherwise false - * @see GLContext#isGLES2Compatible() + * @see GLContext#isGLES2Compatible() */ public boolean isGLES2Compatible(); @@ -227,26 +227,26 @@ public interface GLBase { *

          * Includes [ GL ≥ 4.3, GL ≥ 3.1 w/ GL_ARB_ES3_compatibility and GLES3 ] *

          - * @see GLContext#isGLES3Compatible() + * @see GLContext#isGLES3Compatible() */ public boolean isGLES3Compatible(); - /** - * Indicates whether this GL object supports GLSL. - * @see GLContext#hasGLSL() + /** + * Indicates whether this GL object supports GLSL. + * @see GLContext#hasGLSL() */ public boolean hasGLSL(); /** * Returns the downstream GL instance in case this is a wrapping pipeline, otherwise null. *

          - * See {@link #getRootGL()} for retrieving the implementing root instance. + * See {@link #getRootGL()} for retrieving the implementing root instance. *

          * @throws GLException if the downstream instance is not null and not a GL implementation * @see #getRootGL() */ public GL getDownstreamGL() throws GLException; - + /** * Returns the implementing root instance, considering a wrapped pipelined hierarchy, see {@link #getDownstreamGL()}. *

          @@ -256,7 +256,7 @@ public interface GLBase { * @throws GLException if the root instance is not a GL implementation */ public GL getRootGL() throws GLException; - + /** * Casts this object to the GL interface. * @throws GLException if this object is not a GL implementation @@ -360,14 +360,14 @@ public interface GLBase { /** * Returns true if the specified OpenGL core- or extension-function can be * used successfully through this GL instance given the current host (OpenGL - * client) and display (OpenGL server) configuration.

          - * By "successfully" we mean that the function is both callable - * on the machine running the program and available on the current - * display.

          + * client) and display (OpenGL server) configuration.

          + * By "successfully" we mean that the function is both callable + * on the machine running the program and available on the current + * display.

          * * In order to call a function successfully, the function must be both - * callable on the machine running the program and available on - * the display device that is rendering the output (note: on non-networked, + * callable on the machine running the program and available on + * the display device that is rendering the output (note: on non-networked, * single-display machines these two conditions are identical; on networked and/or * multi-display machines this becomes more complicated). These conditions are * met if the function is either part of the core OpenGL version supported by @@ -376,7 +376,7 @@ public interface GLBase { * * A GL function is callable if it is successfully linked at runtime, * hence the GLContext must be made current at least once. - * + * * @param glFunctionName the name of the OpenGL function (e.g., use * "glBindRenderbufferEXT" or "glBindRenderbuffer" to check if {@link * GL#glBindRenderbuffer(int,int)} is available). @@ -386,14 +386,14 @@ public interface GLBase { /** * Returns true if the specified OpenGL extension can be * used successfully through this GL instance given the current host (OpenGL - * client) and display (OpenGL server) configuration.

          + * client) and display (OpenGL server) configuration.

          * * @param glExtensionName the name of the OpenGL extension (e.g., * "GL_ARB_vertex_program"). */ public boolean isExtensionAvailable(String glExtensionName); - /** + /** * Returns true if basic FBO support is available, otherwise false. *

          * Basic FBO is supported if the context is either GL-ES >= 2.0, GL >= core 3.0 or implements the extensions @@ -407,12 +407,12 @@ public interface GLBase { */ public boolean hasBasicFBOSupport(); - /** + /** * Returns true if full FBO support is available, otherwise false. *

          * Full FBO is supported if the context is either GL >= core 3.0 or implements the extensions * ARB_framebuffer_object, or all of - * EXT_framebuffer_object, EXT_framebuffer_multisample, + * EXT_framebuffer_object, EXT_framebuffer_multisample, * EXT_framebuffer_blit, GL_EXT_packed_depth_stencil. *

          *

          @@ -424,7 +424,7 @@ public interface GLBase { /** * Returns the maximum number of FBO RENDERBUFFER samples - * if {@link #hasFullFBOSupport() full FBO is supported}, otherwise false. + * if {@link #hasFullFBOSupport() full FBO is supported}, otherwise false. * @see GLContext#getMaxRenderbufferSamples() */ public int getMaxRenderbufferSamples(); @@ -440,7 +440,7 @@ public interface GLBase { public boolean isNPOTTextureAvailable(); public boolean isTextureFormatBGRA8888Available(); - + /** Provides a platform-independent way to specify the minimum swap interval for buffer swaps. An argument of 0 disables sync-to-vertical-refresh completely, while an argument of 1 @@ -449,7 +449,7 @@ public interface GLBase { is usually either 0 or 1. This function is not guaranteed to have an effect, and in particular only affects heavyweight onscreen components. - + @see #getSwapInterval @throws GLException if this context is not the current */ @@ -458,8 +458,8 @@ public interface GLBase { /** Provides a platform-independent way to get the swap interval set by {@link #setSwapInterval}.
          - If the interval is not set by {@link #setSwapInterval} yet, - -1 is returned, indicating that the platforms default + If the interval is not set by {@link #setSwapInterval} yet, + -1 is returned, indicating that the platforms default is being used. @see #setSwapInterval @@ -498,10 +498,10 @@ public interface GLBase { */ public Object getExtension(String extensionName); - /** Aliased entrypoint of void {@native glClearDepth}(GLclampd depth); and void {@native glClearDepthf}(GLclampf depth); . */ + /** Aliased entrypoint of void {@native glClearDepth}(GLclampd depth); and void {@native glClearDepthf}(GLclampf depth); . */ public void glClearDepth( double depth ); - /** Aliased entrypoint of void {@native glDepthRange}(GLclampd depth); and void {@native glDepthRangef}(GLclampf depth); . */ + /** Aliased entrypoint of void {@native glDepthRange}(GLclampd depth); and void {@native glDepthRangef}(GLclampf depth); . */ public void glDepthRange(double zNear, double zFar); /** @@ -526,44 +526,44 @@ public interface GLBase { */ public boolean glIsVBOElementArrayBound(); - /** - * Return the framebuffer name bound to this context, + /** + * Return the framebuffer name bound to this context, * see {@link GL#glBindFramebuffer(int, int)}. */ public int getBoundFramebuffer(int target); - /** + /** * Return the default draw framebuffer name. - *

          + *

          * May differ from it's default zero * in case an framebuffer object ({@link com.jogamp.opengl.FBObject}) based drawable * is being used. - *

          + *

          */ public int getDefaultDrawFramebuffer(); - /** + /** * Return the default read framebuffer name. - *

          + *

          * May differ from it's default zero * in case an framebuffer object ({@link com.jogamp.opengl.FBObject}) based drawable * is being used. - *

          + *

          */ public int getDefaultReadFramebuffer(); - - /** - * Returns the default color buffer within the current bound + + /** + * Returns the default color buffer within the current bound * {@link #getDefaultReadFramebuffer()}, i.e. GL_READ_FRAMEBUFFER, - * which will be used as the source for pixel reading commands, + * which will be used as the source for pixel reading commands, * like {@link GL#glReadPixels(int, int, int, int, int, int, java.nio.Buffer)} etc. *

          * For offscreen framebuffer objects this is {@link GL#GL_COLOR_ATTACHMENT0}, - * otherwise this is {@link GL#GL_FRONT} for single buffer configurations + * otherwise this is {@link GL#GL_FRONT} for single buffer configurations * and {@link GL#GL_BACK} for double buffer configurations. - *

          + *

          */ public int getDefaultReadBuffer(); - + } diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilities.java b/src/jogl/classes/javax/media/opengl/GLCapabilities.java index 872069fb8..b825d6388 100644 --- a/src/jogl/classes/javax/media/opengl/GLCapabilities.java +++ b/src/jogl/classes/javax/media/opengl/GLCapabilities.java @@ -99,7 +99,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil } /** - * Copies all {@link GLCapabilities} and {@link Capabilities} values + * Copies all {@link GLCapabilities} and {@link Capabilities} values * from source into this instance. * @return this instance */ @@ -122,11 +122,11 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil sampleExtension = source.getSampleExtension(); return this; } - + @Override public int hashCode() { // 31 * x == (x << 5) - x - int hash = super.hashCode(); + int hash = super.hashCode(); hash = ((hash << 5) - hash) + this.glProfile.hashCode() ; hash = ((hash << 5) - hash) + ( this.hardwareAccelerated ? 1 : 0 ); hash = ((hash << 5) - hash) + ( this.stereo ? 1 : 0 ); @@ -238,7 +238,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil public void setGLProfile(GLProfile profile) { glProfile=profile; } - + @Override public final boolean isPBuffer() { return isPBuffer; @@ -255,7 +255,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil *

          * Requesting offscreen pbuffer mode disables the offscreen auto selection. *

          - */ + */ public void setPBuffer(boolean enable) { if(enable) { setOnscreen(false); @@ -267,7 +267,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil public final boolean isFBO() { return isFBO; } - + /** * Requesting offscreen FBO mode. *

          @@ -422,7 +422,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil return sampleBuffers; } - /** + /** * If sample buffers are enabled, indicates the number of buffers * to be allocated. Defaults to 2. * @see #getNumSamples() @@ -491,7 +491,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil if(isOnscreen()) { sink.append("."); // no additional off-screen modes besides on-screen } else { - sink.append("auto-cfg"); // auto-config off-screen mode + sink.append("auto-cfg"); // auto-config off-screen mode } } sink.append("]"); diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilitiesChooser.java b/src/jogl/classes/javax/media/opengl/GLCapabilitiesChooser.java index 5d575c2ee..2e0bec1f9 100644 --- a/src/jogl/classes/javax/media/opengl/GLCapabilitiesChooser.java +++ b/src/jogl/classes/javax/media/opengl/GLCapabilitiesChooser.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003-2009 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 @@ -29,11 +29,11 @@ * 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. */ @@ -53,7 +53,7 @@ import javax.media.opengl.GLCapabilitiesImmutable; the appropriate method of {@link GLDrawableFactory}; the chooser will be called during the OpenGL context creation process. Note that this is only a marker interface; its signature is the same as - {@link CapabilitiesChooser} and the {@link List} of + {@link CapabilitiesChooser} and the {@link List} of objects extending {@link CapabilitiesImmutable} passed to {@link #chooseCapabilities chooseCapabilities} is actually a {@link List} of type {@link GLCapabilitiesImmutable}. */ diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java b/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java index 6af35021f..dc28539a0 100644 --- a/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java +++ b/src/jogl/classes/javax/media/opengl/GLCapabilitiesImmutable.java @@ -37,13 +37,13 @@ import javax.media.nativewindow.CapabilitiesImmutable; * @see javax.media.nativewindow.CapabilitiesImmutable */ public interface GLCapabilitiesImmutable extends CapabilitiesImmutable { - /** - * One of the platform's default sample extension + /** + * One of the platform's default sample extension * EGL.EGL_SAMPLES, GLX.GLX_SAMPLES, WGLExt.WGL_SAMPLES_ARB * if available, or any other known fallback one, ie EGLExt.EGL_COVERAGE_SAMPLES_NV */ public static final String DEFAULT_SAMPLE_EXTENSION = "default" ; - + /** * Returns the GL profile you desire or used by the drawable. */ @@ -110,10 +110,10 @@ public interface GLCapabilitiesImmutable extends CapabilitiesImmutable { *

          */ String getSampleExtension(); - + /** * Returns whether sample buffers for full-scene antialiasing - * (FSAA) should be allocated for this drawable. + * (FSAA) should be allocated for this drawable. *

          * Default is false. *

          diff --git a/src/jogl/classes/javax/media/opengl/GLContext.java b/src/jogl/classes/javax/media/opengl/GLContext.java index f4dbde6b2..bd6867359 100644 --- a/src/jogl/classes/javax/media/opengl/GLContext.java +++ b/src/jogl/classes/javax/media/opengl/GLContext.java @@ -72,14 +72,14 @@ import com.jogamp.opengl.GLRendererQuirks; abstraction provides a stable object which clients can use to refer to a given context. */ public abstract class GLContext { - + public static final boolean DEBUG = Debug.debug("GLContext"); public static final boolean TRACE_SWITCH = Debug.isPropertyDefined("jogl.debug.GLContext.TraceSwitch", true); - public static final boolean DEBUG_TRACE_SWITCH = DEBUG || TRACE_SWITCH; + public static final boolean DEBUG_TRACE_SWITCH = DEBUG || TRACE_SWITCH; - /** - * If true (default), bootstrapping the available GL profiles - * will use the highest compatible GL context for each profile, + /** + * If true (default), bootstrapping the available GL profiles + * will use the highest compatible GL context for each profile, * hence skipping querying lower profiles if a compatible higher one is found: *
            *
          • 4.2-core -> 4.2-core, 3.3-core
          • @@ -95,17 +95,17 @@ public abstract class GLContext { *
          * Using aliasing speeds up initialization about: *
            - *
          • Linux x86_64 - Nvidia: 28%, 700ms down to 500ms
          • - *
          • Linux x86_64 - AMD : 40%, 1500ms down to 900ms
          • + *
          • Linux x86_64 - Nvidia: 28%, 700ms down to 500ms
          • + *
          • Linux x86_64 - AMD : 40%, 1500ms down to 900ms
          • *

            * Can be turned off with property jogl.debug.GLContext.NoProfileAliasing. *

            */ public static final boolean PROFILE_ALIASING = !Debug.isPropertyDefined("jogl.debug.GLContext.NoProfileAliasing", true); - + protected static final boolean FORCE_NO_FBO_SUPPORT = Debug.isPropertyDefined("jogl.fbo.force.none", true); protected static final boolean FORCE_MIN_FBO_SUPPORT = Debug.isPropertyDefined("jogl.fbo.force.min", true); - + /** Reflects property jogl.debug.DebugGL. If true, the debug pipeline is enabled at context creation. */ public static final boolean DEBUG_GL = Debug.isPropertyDefined("jogl.debug.DebugGL", true); /** Reflects property jogl.debug.TraceGL. If true, the trace pipeline is enabled at context creation. */ @@ -130,31 +130,31 @@ public abstract class GLContext { public static final VersionNumber Version140 = new VersionNumber(1, 40, 0); /* Version 1.50, i.e. GLSL 1.50 for GL 3.2. */ public static final VersionNumber Version150 = new VersionNumber(1, 50, 0); - + /** Version 3.0. As an OpenGL version, it qualifies for desktop {@link #isGL2()} only, or ES 3.0. */ public static final VersionNumber Version300 = new VersionNumber(3, 0, 0); - + /** Version 3.1. As an OpenGL version, it qualifies for {@link #isGL3core()}, {@link #isGL3bc()} and {@link #isGL3()} */ public static final VersionNumber Version310 = new VersionNumber(3, 1, 0); - + /** Version 3.2. As an OpenGL version, it qualifies for geometry shader */ public static final VersionNumber Version320 = new VersionNumber(3, 2, 0); - + /** Version 4.3. As an OpenGL version, it qualifies for GL_ARB_ES3_compatibility */ public static final VersionNumber Version430 = new VersionNumber(4, 3, 0); - + protected static final VersionNumber Version800 = new VersionNumber(8, 0, 0); // // Cached keys, bits [0..15] // - + /** Context option bits, full bit mask covering bits [0..15], i.e. 0x0000FFFF, {@value}. */ protected static final int CTX_IMPL_FULL_MASK = 0x0000FFFF; - + /** Context option bits, cached bit mask covering 9 bits [0..8], i.e. 0x000001FF, {@value}. Leaving 7 bits for non cached options, i.e. 9:7. */ protected static final int CTX_IMPL_CACHE_MASK = 0x000001FF; - + /** ARB_create_context related: created via ARB_create_context. Cache key value. See {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ protected static final int CTX_IS_ARB_CREATED = 1 << 0; /** ARB_create_context related: desktop compatibility profile. Cache key value. See {@link #isGLCompatibilityProfile()}, {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ @@ -173,14 +173,14 @@ public abstract class GLContext { // // Non cached keys, bits [9..15] // - + /** GL_ARB_ES2_compatibility implementation related: Context is compatible w/ ES2. Not a cache key. See {@link #isGLES2Compatible()}, {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ protected static final int CTX_IMPL_ES2_COMPAT = 1 << 9; /** GL_ARB_ES3_compatibility implementation related: Context is compatible w/ ES3. Not a cache key. See {@link #isGLES3Compatible()}, {@link #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile)}. */ protected static final int CTX_IMPL_ES3_COMPAT = 1 << 10; - - /** + + /** * Context supports basic FBO, details see {@link #hasBasicFBOSupport()}. * Not a cache key. * @see #hasBasicFBOSupport() @@ -188,15 +188,15 @@ public abstract class GLContext { */ protected static final int CTX_IMPL_FBO = 1 << 11; - /** - * Context supports OES_single_precision, fp32, fixed function point (FFP) compatibility entry points, + /** + * Context supports OES_single_precision, fp32, fixed function point (FFP) compatibility entry points, * see {@link #hasFP32CompatAPI()}. * Not a cache key. * @see #hasFP32CompatAPI() * @see #getAvailableContextProperties(AbstractGraphicsDevice, GLProfile) */ protected static final int CTX_IMPL_FP32_COMPAT_API = 1 << 12; - + private static final ThreadLocal currentContext = new ThreadLocal(); private final HashMap attachedObjects = new HashMap(); @@ -219,9 +219,9 @@ public abstract class GLContext { private int currentSwapInterval; protected GLRendererQuirks glRendererQuirks; - /** Did the drawable association changed ? see {@link GLRendererQuirks#NoSetSwapIntervalPostRetarget} */ - protected boolean drawableRetargeted; - + /** Did the drawable association changed ? see {@link GLRendererQuirks#NoSetSwapIntervalPostRetarget} */ + protected boolean drawableRetargeted; + /** * @param isInit true if called for class initialization, otherwise false (re-init or destruction). */ @@ -242,12 +242,12 @@ public abstract class GLContext { drawableRetargeted = false; } - /** + /** * Returns the instance of {@link GLRendererQuirks}, allowing one to determine workarounds. * @return instance of {@link GLRendererQuirks} if context was made current once, otherwise null. */ public final GLRendererQuirks getRendererQuirks() { return glRendererQuirks; } - + /** * Returns true if the quirk exist in {@link #getRendererQuirks()}, otherwise false. *

            @@ -260,10 +260,10 @@ public abstract class GLContext { * @param quirk the quirk to be tested, e.g. {@link GLRendererQuirks#NoDoubleBufferedPBuffer}. * @throws IllegalArgumentException if the quirk is out of range */ - public final boolean hasRendererQuirk(int quirk) throws IllegalArgumentException { - return null != glRendererQuirks ? glRendererQuirks.exist(quirk) : false ; + public final boolean hasRendererQuirk(int quirk) throws IllegalArgumentException { + return null != glRendererQuirks ? glRendererQuirks.exist(quirk) : false ; } - + /** * Sets the read/write drawable for framebuffer operations. *

            @@ -276,13 +276,13 @@ public abstract class GLContext { * attempts to make this context current. Otherwise a race condition may happen. *

            * @param readWrite The read/write drawable for framebuffer operations, maybe null to remove association. - * @param setWriteOnly Only change the write-drawable, if setWriteOnly is true and - * if the {@link #getGLReadDrawable() read-drawable} differs - * from the {@link #getGLDrawable() write-drawable}. + * @param setWriteOnly Only change the write-drawable, if setWriteOnly is true and + * if the {@link #getGLReadDrawable() read-drawable} differs + * from the {@link #getGLDrawable() write-drawable}. * Otherwise set both drawables, read and write. * @return The previous read/write drawable * - * @throws GLException in case null is being passed or + * @throws GLException in case null is being passed or * this context is made current on another thread. * * @see #isGLReadDrawableAvailable() @@ -292,13 +292,13 @@ public abstract class GLContext { * @see #getGLDrawable() */ public abstract GLDrawable setGLDrawable(GLDrawable readWrite, boolean setWriteOnly); - + /** * Returns the write-drawable this context uses for framebuffer operations. *

            * If the read-drawable has not been changed manually via {@link #setGLReadDrawable(GLDrawable)}, * it equals to the write-drawable (default). - *

            + *

            * @see #setGLDrawable(GLDrawable, boolean) * @see #setGLReadDrawable(GLDrawable) */ @@ -336,10 +336,10 @@ public abstract class GLContext { *

            * If the read-drawable has not been changed manually via {@link #setGLReadDrawable(GLDrawable)}, * it equals to the write-drawable (default). - *

            + *

            * @see #isGLReadDrawableAvailable() * @see #setGLReadDrawable(GLDrawable) - * @see #getGLReadDrawable() + * @see #getGLReadDrawable() */ public abstract GLDrawable getGLReadDrawable(); @@ -354,9 +354,9 @@ public abstract class GLContext { *

            *

            * A return value of {@link #CONTEXT_CURRENT_NEW} - * indicates that that context has been made current for the 1st time, + * indicates that that context has been made current for the 1st time, * or that the state of the underlying context or drawable has - * changed since the last time this context was current. + * changed since the last time this context was current. * In this case, the application may wish to initialize the render state. *

            *

            @@ -378,7 +378,7 @@ public abstract class GLContext { *

            * * @return
              - *
            • {@link #CONTEXT_CURRENT_NEW} if the context was successfully made current the 1st time,
            • + *
            • {@link #CONTEXT_CURRENT_NEW} if the context was successfully made current the 1st time,
            • *
            • {@link #CONTEXT_CURRENT} if the context was successfully made current,
            • *
            • {@link #CONTEXT_NOT_CURRENT} if the context could not be made current.
            • *
            @@ -514,7 +514,7 @@ public abstract class GLContext { public abstract void destroy(); /** - * Returns the implementing root GL instance of this GLContext's GL object, + * Returns the implementing root GL instance of this GLContext's GL object, * considering a wrapped pipelined hierarchy, see {@link GLBase#getDownstreamGL()}. * @throws GLException if the root instance is not a GL implementation * @see GLBase#getRootGL() @@ -523,7 +523,7 @@ public abstract class GLContext { * @see #setGL(GL) */ public abstract GL getRootGL(); - + /** * Returns the GL pipeline object for this GLContext. * @@ -716,16 +716,16 @@ public abstract class GLContext { } /** - * Returns this context OpenGL version. - * @see #getGLSLVersionNumber() + * Returns this context OpenGL version. + * @see #getGLSLVersionNumber() **/ public final VersionNumber getGLVersionNumber() { return ctxVersion; } - /** + /** * Returns the vendor's version, i.e. version number at the end of GL_VERSION not being the GL version. *

            - * In case no such version exists within GL_VERSION, + * In case no such version exists within GL_VERSION, * the {@link VersionNumberString#zeroVersion zero version} instance is returned. - *

            + *

            *

            * The vendor's version is usually the vendor's OpenGL driver version. *

            @@ -743,31 +743,31 @@ public abstract class GLContext { * via {@link GL2ES2#GL_SHADING_LANGUAGE_VERSION} if ≥ ES2.0 or GL2.0, * otherwise a static match is being utilized. *

            - * The context must have been current once, - * otherwise the {@link VersionNumberString#zeroVersion zero version} instance is returned. + * The context must have been current once, + * otherwise the {@link VersionNumberString#zeroVersion zero version} instance is returned. *

            *

            - * Examples w/ major.minor: + * Examples w/ major.minor: *

            -   *    1.00 (ES 2.0), 1.10 (GL 2.0), 1.20 (GL 2.1), 1.50 (GL 3.2), 
            +   *    1.00 (ES 2.0), 1.10 (GL 2.0), 1.20 (GL 2.1), 1.50 (GL 3.2),
                *    3.30 (GL 3.3), 4.00 (GL 4.0), 4.10 (GL 4.1), 4.20 (GL 4.2)
                * 
            *

            *

            * Matching could also refer to the maximum GLSL version usable by this context * since normal GL implementations are capable of using a lower GLSL version as well. - * The latter is not true on OSX w/ a GL3 context. + * The latter is not true on OSX w/ a GL3 context. *

            - * - * @return GLSL version number if context has been made current at least once, + * + * @return GLSL version number if context has been made current at least once, * otherwise the {@link VersionNumberString#zeroVersion zero version} instance is returned. - * + * * @see #getGLVersionNumber() */ public final VersionNumber getGLSLVersionNumber() { return ctxGLSLVersion; } - + /** * Returns the GLSL version string as to be used in a shader program, including a terminating newline '\n', * i.e. for desktop @@ -794,10 +794,10 @@ public abstract class GLContext { return ""; } final int minor = ctxGLSLVersion.getMinor(); - final String esSuffix = isGLES() && ctxGLSLVersion.compareTo(Version300) >= 0 ? " es" : ""; + final String esSuffix = isGLES() && ctxGLSLVersion.compareTo(Version300) >= 0 ? " es" : ""; return "#version " + ctxGLSLVersion.getMajor() + ( minor < 10 ? "0"+minor : minor ) + esSuffix + "\n" ; } - + protected static final VersionNumber getStaticGLSLVersionNumber(int glMajorVersion, int glMinorVersion, int ctxOptions) { if( 0 != ( CTX_PROFILE_ES & ctxOptions ) ) { if( 3 > glMajorVersion ) { @@ -814,13 +814,13 @@ public abstract class GLContext { switch ( glMinorVersion ) { case 0: return Version130; // GL 3.0 -> GLSL 1.30 case 1: return Version140; // GL 3.1 -> GLSL 1.40 - default: return Version150; // GL 3.2 -> GLSL 1.50 + default: return Version150; // GL 3.2 -> GLSL 1.50 } } // The new default: GL >= 3.3, ES >= 3.0 return new VersionNumber(glMajorVersion, glMinorVersion * 10, 0); // GL M.N -> GLSL M.N } - + /** * @return true if this context is an ES2 context or implements * the extension GL_ARB_ES3_compatibility or GL_ARB_ES2_compatibility, otherwise false @@ -840,18 +840,18 @@ public abstract class GLContext { return 0 != ( ctxOptions & CTX_IMPL_ES3_COMPAT ) ; } - /** + /** * @return true if impl. is a hardware rasterizer, otherwise false. * @see #isHardwareRasterizer(AbstractGraphicsDevice, GLProfile) - * @see GLProfile#isHardwareRasterizer() + * @see GLProfile#isHardwareRasterizer() */ public final boolean isHardwareRasterizer() { return 0 == ( ctxOptions & CTX_IMPL_ACCEL_SOFT ) ; } - + /** * @return true if context supports GLSL, i.e. is either {@link #isGLES2()}, {@link #isGL3()} or {@link #isGL2()} and major-version > 1. - * @see GLProfile#hasGLSL() + * @see GLProfile#hasGLSL() */ public final boolean hasGLSL() { return isGLES2() || @@ -859,7 +859,7 @@ public abstract class GLContext { isGL2() && ctxVersion.getMajor()>1 ; } - /** + /** * Returns true if basic FBO support is available, otherwise false. *

            * Basic FBO is supported if the context is either GL-ES >= 2.0, GL >= core 3.0 or implements the extensions @@ -875,30 +875,30 @@ public abstract class GLContext { return 0 != ( ctxOptions & CTX_IMPL_FBO ) ; } - /** - * Returns true if OES_single_precision, fp32, fixed function point (FFP) compatibility entry points available, + /** + * Returns true if OES_single_precision, fp32, fixed function point (FFP) compatibility entry points available, * otherwise false. * @see #CTX_IMPL_FP32_COMPAT_API */ public final boolean hasFP32CompatAPI() { return 0 != ( ctxOptions & CTX_IMPL_FP32_COMPAT_API ) ; } - - /** + + /** * Returns true if full FBO support is available, otherwise false. *

            * Full FBO is supported if the context is either GL >= core 3.0 or implements the extensions * ARB_framebuffer_object, or all of - * EXT_framebuffer_object, EXT_framebuffer_multisample, + * EXT_framebuffer_object, EXT_framebuffer_multisample, * EXT_framebuffer_blit, GL_EXT_packed_depth_stencil. *

            *

            * Full FBO support includes multiple color attachments and multisampling. *

            */ - public final boolean hasFullFBOSupport() { + public final boolean hasFullFBOSupport() { return hasBasicFBOSupport() && !hasRendererQuirk(GLRendererQuirks.NoFullFBOSupport) && - ( isGL3() || // GL >= 3.0 + ( isGL3() || // GL >= 3.0 isExtensionAvailable(GLExtensions.ARB_framebuffer_object) || // ARB_framebuffer_object ( isExtensionAvailable(GLExtensions.EXT_framebuffer_object) && // All EXT_framebuffer_object* isExtensionAvailable(GLExtensions.EXT_framebuffer_multisample) && @@ -907,10 +907,10 @@ public abstract class GLContext { ) ) ; } - + /** * Returns the maximum number of FBO RENDERBUFFER samples - * if {@link #hasFullFBOSupport() full FBO is supported}, otherwise false. + * if {@link #hasFullFBOSupport() full FBO is supported}, otherwise false. */ public final int getMaxRenderbufferSamples() { if( hasFullFBOSupport() ) { @@ -928,7 +928,7 @@ public abstract class GLContext { } return 0; } - + /** Note: The GL impl. may return a const value, ie {@link GLES2#isNPOTTextureAvailable()} always returns true. */ public boolean isNPOTTextureAvailable() { return isGL3() || isGLES2Compatible() || isExtensionAvailable(GLExtensions.ARB_texture_non_power_of_two); @@ -940,9 +940,9 @@ public abstract class GLContext { isExtensionAvailable(GLExtensions.IMG_texture_format_BGRA8888) ; } - /** + /** * Indicates whether this GLContext is capable of GL4bc.

            Includes [ GL4bc ].

            - * @see GLProfile#isGL4bc() + * @see GLProfile#isGL4bc() */ public final boolean isGL4bc() { return 0 != (ctxOptions & CTX_IS_ARB_CREATED) && @@ -950,9 +950,9 @@ public abstract class GLContext { ctxVersion.getMajor() >= 4; } - /** + /** * Indicates whether this GLContext is capable of GL4.

            Includes [ GL4bc, GL4 ].

            - * @see GLProfile#isGL4() + * @see GLProfile#isGL4() */ public final boolean isGL4() { return 0 != (ctxOptions & CTX_IS_ARB_CREATED) && @@ -960,7 +960,7 @@ public abstract class GLContext { ctxVersion.getMajor() >= 4; } - /** + /** * Indicates whether this GLContext uses a GL4 core profile.

            Includes [ GL4 ].

            */ public final boolean isGL4core() { @@ -968,10 +968,10 @@ public abstract class GLContext { 0 != ( ctxOptions & CTX_PROFILE_CORE ) && ctxVersion.getMajor() >= 4; } - - /** + + /** * Indicates whether this GLContext is capable of GL3bc.

            Includes [ GL4bc, GL3bc ].

            - * @see GLProfile#isGL3bc() + * @see GLProfile#isGL3bc() */ public final boolean isGL3bc() { return 0 != (ctxOptions & CTX_IS_ARB_CREATED) && @@ -979,17 +979,17 @@ public abstract class GLContext { ctxVersion.compareTo(Version310) >= 0 ; } - /** + /** * Indicates whether this GLContext is capable of GL3.

            Includes [ GL4bc, GL4, GL3bc, GL3 ].

            - * @see GLProfile#isGL3() + * @see GLProfile#isGL3() */ public final boolean isGL3() { return 0 != (ctxOptions & CTX_IS_ARB_CREATED) && 0 != (ctxOptions & (CTX_PROFILE_COMPAT|CTX_PROFILE_CORE)) && ctxVersion.compareTo(Version310) >= 0 ; - } - - /** + } + + /** * Indicates whether this GLContext uses a GL3 core profile.

            Includes [ GL4, GL3 ].

            */ public final boolean isGL3core() { @@ -997,8 +997,8 @@ public abstract class GLContext { 0 != ( ctxOptions & CTX_PROFILE_CORE ) && ctxVersion.compareTo(Version310) >= 0; } - - /** + + /** * Indicates whether this GLContext uses a GL core profile.

            Includes [ GL4, GL3, GLES3, GLES2 ].

            */ public final boolean isGLcore() { @@ -1008,26 +1008,26 @@ public abstract class GLContext { ctxVersion.compareTo(Version310) >= 0 ) ; } - + /** * Indicates whether this GLContext allows CPU data sourcing (indices, vertices ..) as opposed to using a GPU buffer source (VBO), - * e.g. {@link GL2#glDrawElements(int, int, int, java.nio.Buffer)}. + * e.g. {@link GL2#glDrawElements(int, int, int, java.nio.Buffer)}. *

            Includes [GL2ES1, GLES2] == [ GL4bc, GL3bc, GL2, GLES1, GL2ES1, GLES2 ].

            *

            See Bug 852 - https://jogamp.org/bugzilla/show_bug.cgi?id=852

            */ public final boolean isCPUDataSourcingAvail() { return isGL2ES1() || isGLES2(); } - - /** - * Indicates whether this GLContext's native profile does not implement a default vertex array object (VAO), + + /** + * Indicates whether this GLContext's native profile does not implement a default vertex array object (VAO), * starting w/ OpenGL 3.1 core and GLES3. *

            Includes [ GL4, GL3, GLES3 ].

            *
                  Due to GL 3.1 core spec: E.1. DEPRECATED AND REMOVED FEATURES (p 296),
                         GL 3.2 core spec: E.2. DEPRECATED AND REMOVED FEATURES (p 331)
                  there is no more default VAO buffer 0 bound, hence generating and binding one
            -     to avoid INVALID_OPERATION at VertexAttribPointer. 
            +     to avoid INVALID_OPERATION at VertexAttribPointer.
                  More clear is GL 4.3 core spec: 10.4 (p 307).
                * 
            *
            @@ -1047,87 +1047,87 @@ public abstract class GLContext {
                            ctxVersion.compareTo(Version310) >= 0
                          ) ;
               }
            -  
            +
               /**
                * If this GLContext does not implement a default VAO, see {@link #hasNoDefaultVAO()},
                * an own default VAO will be created and bound at context creation.
                * 

            * If this GLContext does implement a default VAO, i.e. {@link #hasNoDefaultVAO()} * returns false, this method returns 0. - *

            + *

            *

            * Otherwise this method returns the VAO object name - * representing this GLContext's own default VAO. - *

            + * representing this GLContext's own default VAO. + *

            * @see #hasNoDefaultVAO() */ public abstract int getDefaultVAO(); - /** + /** * Indicates whether this GLContext is capable of GL2.

            Includes [ GL4bc, GL3bc, GL2 ].

            - * @see GLProfile#isGL2() + * @see GLProfile#isGL2() */ public final boolean isGL2() { return 0 != ( ctxOptions & CTX_PROFILE_COMPAT ) && ctxVersion.getMajor()>=1 ; } - /** + /** * Indicates whether this GLContext is capable of GL2GL3.

            Includes [ GL4bc, GL4, GL3bc, GL3, GL2, GL2GL3 ].

            - * @see GLProfile#isGL2GL3() - */ + * @see GLProfile#isGL2GL3() + */ public final boolean isGL2GL3() { return isGL2() || isGL3(); } - /** + /** * Indicates whether this GLContext is capable of GLES1.

            Includes [ GLES1 ].

            - * @see GLProfile#isGLES1() + * @see GLProfile#isGLES1() */ public final boolean isGLES1() { return 0 != ( ctxOptions & CTX_PROFILE_ES ) && ctxVersion.getMajor() == 1 ; } /** - * Indicates whether this GLContext is capable of GLES2.

            Includes [ GLES2 ].

            - * @see GLProfile#isGLES2() + * Indicates whether this GLContext is capable of GLES2.

            Includes [ GLES2 ].

            + * @see GLProfile#isGLES2() */ public final boolean isGLES2() { return 0 != ( ctxOptions & CTX_PROFILE_ES ) && ctxVersion.getMajor() == 2 ; } - /** + /** * Indicates whether this GLContext is capable of GLES3.

            Includes [ GLES3 ].

            - * @see GLProfile#isGLES3() + * @see GLProfile#isGLES3() */ public final boolean isGLES3() { return 0 != ( ctxOptions & CTX_PROFILE_ES ) && ctxVersion.getMajor() >= 3 ; } - /** + /** * Indicates whether this GLContext is capable of GLES.

            Includes [ GLES3, GLES1, GLES2 ].

            - * @see GLProfile#isGLES() + * @see GLProfile#isGLES() */ public final boolean isGLES() { return 0 != ( CTX_PROFILE_ES & ctxOptions ) ; } - /** + /** * Indicates whether this GLContext is capable of GL2ES1.

            Includes [ GL4bc, GL3bc, GL2, GLES1, GL2ES1 ].

            - * @see GLProfile#isGL2ES1() + * @see GLProfile#isGL2ES1() */ public final boolean isGL2ES1() { return isGLES1() || isGL2(); } - /** + /** * Indicates whether this GLContext is capable of GL2ES2.

            Includes [ GL4bc, GL4, GL3bc, GL3, GLES3, GL2, GL2GL3, GL2ES2, GLES2 ].

            - * @see GLProfile#isGL2ES2() + * @see GLProfile#isGL2ES2() */ public final boolean isGL2ES2() { return isGLES2() || isGL2GL3(); } - /** + /** * Indicates whether this GLContext is capable of GL2ES3.

            Includes [ GL4bc, GL4, GL3bc, GL3, GLES3, GL3ES3, GL2, GL2GL3 ].

            * @see GLProfile#isGL2ES3() * @see #isGL3ES3() @@ -1137,16 +1137,16 @@ public abstract class GLContext { return isGL3ES3() || isGL2GL3(); } - /** + /** * Indicates whether this GLContext is capable of GL3ES3.

            Includes [ GL4bc, GL4, GL3bc, GL3, GLES3 ].

            - * @see GLProfile#isGL3ES3() + * @see GLProfile#isGL3ES3() */ public final boolean isGL3ES3() { return isGL4ES3() || isGL3(); } - /** - * Returns true if this profile is capable of GL4ES3, i.e. if {@link #isGLES3Compatible()} returns true. + /** + * Returns true if this profile is capable of GL4ES3, i.e. if {@link #isGLES3Compatible()} returns true. *

            Includes [ GL ≥ 4.3, GL ≥ 3.1 w/ GL_ARB_ES3_compatibility and GLES3 ]

            * @see GLProfile#isGL4ES3() */ @@ -1185,7 +1185,7 @@ public abstract class GLContext { *

            *

            * For a valid context the default value is 1 - * in case of an EGL based profile (ES1 or ES2) and -1 + * in case of an EGL based profile (ES1 or ES2) and -1 * (undefined) for desktop. *

            */ @@ -1222,51 +1222,51 @@ public abstract class GLContext { } protected boolean bindSwapBarrierImpl(int group, int barrier) { /** nop per default .. **/ return false; } - /** - * Return the framebuffer name bound to this context, + /** + * Return the framebuffer name bound to this context, * see {@link GL#glBindFramebuffer(int, int)}. */ public abstract int getBoundFramebuffer(int target); - - /** + + /** * Return the default draw framebuffer name. - *

            + *

            * May differ from it's default zero * in case an framebuffer object ({@link com.jogamp.opengl.FBObject}) based drawable * is being used. - *

            + *

            */ public abstract int getDefaultDrawFramebuffer(); - - /** + + /** * Return the default read framebuffer name. - *

            + *

            * May differ from it's default zero * in case an framebuffer object ({@link com.jogamp.opengl.FBObject}) based drawable * is being used. - *

            + *

            */ public abstract int getDefaultReadFramebuffer(); - - /** - * Returns the default color buffer within the current bound - * {@link #getDefaultReadFramebuffer()}, i.e. GL_READ_FRAMEBUFFER​, - * which will be used as the source for pixel reading commands, + + /** + * Returns the default color buffer within the current bound + * {@link #getDefaultReadFramebuffer()}, i.e. GL_READ_FRAMEBUFFER​, + * which will be used as the source for pixel reading commands, * like {@link GL#glReadPixels(int, int, int, int, int, int, java.nio.Buffer)} etc. *

            * For offscreen framebuffer objects this is {@link GL#GL_COLOR_ATTACHMENT0}, - * otherwise this is {@link GL#GL_FRONT} for single buffer configurations + * otherwise this is {@link GL#GL_FRONT} for single buffer configurations * and {@link GL#GL_BACK} for double buffer configurations. - *

            + *

            */ public abstract int getDefaultReadBuffer(); - + /** Get the default pixel data type, as required by e.g. {@link GL#glReadPixels(int, int, int, int, int, int, java.nio.Buffer)}. */ public abstract int getDefaultPixelDataType(); - + /** Get the default pixel data format, as required by e.g. {@link GL#glReadPixels(int, int, int, int, int, int, java.nio.Buffer)}. */ public abstract int getDefaultPixelDataFormat(); - + /** * @return The extension implementing the GLDebugOutput feature, * either {@link GLExtensions#ARB_debug_output} or {@link GLExtensions#AMD_debug_output}. @@ -1486,13 +1486,13 @@ public abstract class GLContext { } if (DEBUG) { System.err.println(getThreadName() + ": createContextARB: SET mappedVersionsAvailableSet "+devKey); - System.err.println(GLContext.dumpAvailableGLVersions(null).toString()); + System.err.println(GLContext.dumpAvailableGLVersions(null).toString()); } } } - /** - * Returns a unique String object using {@link String#intern()} for the given arguments, + /** + * Returns a unique String object using {@link String#intern()} for the given arguments, * which object reference itself can be used as a key. */ protected static String getDeviceVersionAvailableKey(AbstractGraphicsDevice device, int major, int profile) { @@ -1575,7 +1575,7 @@ public abstract class GLContext { } return val; } - + /** * @param reqMajor Key Value either 1, 2, 3 or 4 * @param reqProfile Key Value either {@link #CTX_PROFILE_COMPAT}, {@link #CTX_PROFILE_CORE} or {@link #CTX_PROFILE_ES} @@ -1647,7 +1647,7 @@ public abstract class GLContext { reqMajorCTP[1]=CTX_PROFILE_CORE; } } - + /** * @param device the device the context profile is being requested for * @param GLProfile the GLProfile the context profile is being requested for @@ -1656,7 +1656,7 @@ public abstract class GLContext { protected static final int getAvailableContextProperties(final AbstractGraphicsDevice device, final GLProfile glp) { final int[] reqMajorCTP = new int[] { 0, 0 }; getRequestMajorAndCompat(glp, reqMajorCTP); - + int _major[] = { 0 }; int _minor[] = { 0 }; int _ctp[] = { 0 }; @@ -1702,7 +1702,7 @@ public abstract class GLContext { * Returns true if it is possible to create an framebuffer object (FBO). *

            * FBO feature is implemented in OpenGL, hence it is {@link GLProfile} dependent. - *

            + *

            *

            * FBO support is queried as described in {@link #hasBasicFBOSupport()}. *

            @@ -1714,16 +1714,16 @@ public abstract class GLContext { public static final boolean isFBOAvailable(AbstractGraphicsDevice device, GLProfile glp) { return 0 != ( CTX_IMPL_FBO & getAvailableContextProperties(device, glp) ); } - + /** - * @return 1 if using a hardware rasterizer, 0 if using a software rasterizer and -1 if not determined yet. + * @return 1 if using a hardware rasterizer, 0 if using a software rasterizer and -1 if not determined yet. * @see GLContext#isHardwareRasterizer() - * @see GLProfile#isHardwareRasterizer() + * @see GLProfile#isHardwareRasterizer() */ public static final int isHardwareRasterizer(AbstractGraphicsDevice device, GLProfile glp) { final int r; final int ctp = getAvailableContextProperties(device, glp); - if(0 == ctp) { + if(0 == ctp) { r = -1; } else if( 0 == ( CTX_IMPL_ACCEL_SOFT & ctp ) ) { r = 1; @@ -1732,7 +1732,7 @@ public abstract class GLContext { } return r; } - + /** * @param device the device to request whether the profile is available for * @param reqMajor Key Value either 1, 2, 3 or 4 @@ -1774,7 +1774,7 @@ public abstract class GLContext { int minor[] = { 0 }; int ctp[] = { 0 }; boolean ok; - + ok = GLContext.getAvailableGLVersion(device, 3, GLContext.CTX_PROFILE_ES, major, minor, ctp); if( !ok ) { ok = GLContext.getAvailableGLVersion(device, 3, GLContext.CTX_PROFILE_CORE, major, minor, ctp); @@ -1784,7 +1784,7 @@ public abstract class GLContext { } return 0 != ( ctp[0] & CTX_IMPL_ES3_COMPAT ); } - + public static boolean isGL4bcAvailable(AbstractGraphicsDevice device, boolean isHardware[]) { return isGLVersionAvailable(device, 4, CTX_PROFILE_COMPAT, isHardware); } @@ -1859,6 +1859,6 @@ public abstract class GLContext { } protected static String getThreadName() { return Thread.currentThread().getName(); } - + } diff --git a/src/jogl/classes/javax/media/opengl/GLDebugListener.java b/src/jogl/classes/javax/media/opengl/GLDebugListener.java index 8887d022a..ec7f7cec1 100644 --- a/src/jogl/classes/javax/media/opengl/GLDebugListener.java +++ b/src/jogl/classes/javax/media/opengl/GLDebugListener.java @@ -29,16 +29,16 @@ package javax.media.opengl; /** * Listener for {@link GLDebugMessage}s. - * + * *

            One can enable GLDebugOutput via {@link GLContext#enableGLDebugMessage(boolean)} * and add listeners via {@link GLContext#addGLDebugListener(GLDebugListener)}. */ public interface GLDebugListener { - /** + /** * Handle {@link GLDebugMessage} message sent from native GL implementation. - * + * *

            Since this method is invoked directly by the GL implementation, it shall * return as fast as possible.

            */ - void messageSent(GLDebugMessage event); + void messageSent(GLDebugMessage event); } diff --git a/src/jogl/classes/javax/media/opengl/GLDebugMessage.java b/src/jogl/classes/javax/media/opengl/GLDebugMessage.java index 4b8d62898..1032cf929 100644 --- a/src/jogl/classes/javax/media/opengl/GLDebugMessage.java +++ b/src/jogl/classes/javax/media/opengl/GLDebugMessage.java @@ -30,18 +30,18 @@ package javax.media.opengl; import com.jogamp.common.os.Platform; /** - * OpenGL debug message generated by the driver + * OpenGL debug message generated by the driver * and delivered via {@link GLDebugListener}. */ public class GLDebugMessage { final GLContext source; - final long when; + final long when; final int dbgSource; final int dbgType; final int dbgId; final int dbgSeverity; final String dbgMsg; - + /** * @param source The source of the event * @param when The time of the event @@ -60,9 +60,9 @@ public class GLDebugMessage { this.dbgSeverity = dbgSeverity; this.dbgMsg = dbgMsg; } - + /** - * + * * @param source * @param when * @param dbgId @@ -73,88 +73,88 @@ public class GLDebugMessage { */ public static GLDebugMessage translateAMDEvent(GLContext source, long when, int dbgId, int amdDbgCategory, int dbgSeverity, String dbgMsg) { int dbgSource, dbgType; - + // AMD category == ARB source/type switch(amdDbgCategory) { - case GL2GL3.GL_DEBUG_CATEGORY_API_ERROR_AMD: + case GL2GL3.GL_DEBUG_CATEGORY_API_ERROR_AMD: dbgSource = GL2GL3.GL_DEBUG_SOURCE_API; - dbgType = GL2GL3.GL_DEBUG_TYPE_ERROR; + dbgType = GL2GL3.GL_DEBUG_TYPE_ERROR; break; // // def source / other type // - - case GL2GL3.GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD: + + case GL2GL3.GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD: dbgSource = GL2GL3.GL_DEBUG_SOURCE_WINDOW_SYSTEM; - dbgType = GL2GL3.GL_DEBUG_TYPE_OTHER; + dbgType = GL2GL3.GL_DEBUG_TYPE_OTHER; break; - + case GL2GL3.GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD: dbgSource = GL2GL3.GL_DEBUG_SOURCE_SHADER_COMPILER; - dbgType = GL2GL3.GL_DEBUG_TYPE_OTHER; + dbgType = GL2GL3.GL_DEBUG_TYPE_OTHER; break; - + case GL2GL3.GL_DEBUG_CATEGORY_APPLICATION_AMD: dbgSource = GL2GL3.GL_DEBUG_SOURCE_APPLICATION; dbgType = GL2GL3.GL_DEBUG_TYPE_OTHER; break; - - + + // // other source / def type // - + case GL2GL3.GL_DEBUG_CATEGORY_DEPRECATION_AMD: dbgSource = GL2GL3.GL_DEBUG_SOURCE_OTHER; - dbgType = GL2GL3.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR; + dbgType = GL2GL3.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR; break; - + case GL2GL3.GL_DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD: dbgSource = GL2GL3.GL_DEBUG_SOURCE_OTHER; - dbgType = GL2GL3.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR; + dbgType = GL2GL3.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR; break; - + case GL2GL3.GL_DEBUG_CATEGORY_PERFORMANCE_AMD: dbgSource = GL2GL3.GL_DEBUG_SOURCE_OTHER; - dbgType = GL2GL3.GL_DEBUG_TYPE_PERFORMANCE; + dbgType = GL2GL3.GL_DEBUG_TYPE_PERFORMANCE; break; - - case GL2GL3.GL_DEBUG_CATEGORY_OTHER_AMD: + + case GL2GL3.GL_DEBUG_CATEGORY_OTHER_AMD: default: dbgSource = GL2GL3.GL_DEBUG_SOURCE_OTHER; dbgType = GL2GL3.GL_DEBUG_TYPE_OTHER; } - - return new GLDebugMessage(source, when, dbgSource, dbgType, dbgId, dbgSeverity, dbgMsg); + + return new GLDebugMessage(source, when, dbgSource, dbgType, dbgId, dbgSeverity, dbgMsg); } public static int translateARB2AMDCategory(int dbgSource, int dbgType) { switch (dbgSource) { case GL2GL3.GL_DEBUG_SOURCE_WINDOW_SYSTEM: - return GL2GL3.GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD; - + return GL2GL3.GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD; + case GL2GL3.GL_DEBUG_SOURCE_SHADER_COMPILER: return GL2GL3.GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD; - + case GL2GL3.GL_DEBUG_SOURCE_APPLICATION: return GL2GL3.GL_DEBUG_CATEGORY_APPLICATION_AMD; } - + switch(dbgType) { case GL2GL3.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return GL2GL3.GL_DEBUG_CATEGORY_DEPRECATION_AMD; - + case GL2GL3.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return GL2GL3.GL_DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD; - - case GL2GL3.GL_DEBUG_TYPE_PERFORMANCE: + + case GL2GL3.GL_DEBUG_TYPE_PERFORMANCE: return GL2GL3.GL_DEBUG_CATEGORY_PERFORMANCE_AMD; } - - return GL2GL3.GL_DEBUG_CATEGORY_OTHER_AMD; + + return GL2GL3.GL_DEBUG_CATEGORY_OTHER_AMD; } - + public GLContext getSource() { return source; } @@ -162,7 +162,7 @@ public class GLDebugMessage { public long getWhen() { return when; } - + public int getDbgSource() { return dbgSource; } @@ -182,14 +182,14 @@ public class GLDebugMessage { public String getDbgMsg() { return dbgMsg; } - + public StringBuilder toString(StringBuilder sb) { - final String crtab = Platform.getNewline()+"\t"; + final String crtab = Platform.getNewline()+"\t"; if(null==sb) { sb = new StringBuilder(); - } + } sb.append("GLDebugEvent[ id "); - toHexString(sb, dbgId) + toHexString(sb, dbgId) .append(crtab).append("type ").append(getDbgTypeString(dbgType)) .append(crtab).append("severity ").append(getDbgSeverityString(dbgSeverity)) .append(crtab).append("source ").append(getDbgSourceString(dbgSource)) @@ -199,46 +199,46 @@ public class GLDebugMessage { sb.append(crtab).append("source ").append(source.getGLVersion()).append(" - hash 0x").append(Integer.toHexString(source.hashCode())); } sb.append("]"); - return sb; + return sb; } public String toString() { return toString(null).toString(); } - + public static String getDbgSourceString(int dbgSource) { switch(dbgSource) { case GL2GL3.GL_DEBUG_SOURCE_API: return "GL API"; - case GL2GL3.GL_DEBUG_SOURCE_SHADER_COMPILER: return "GLSL or extension compiler"; - case GL2GL3.GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "Native Windowing binding"; + case GL2GL3.GL_DEBUG_SOURCE_SHADER_COMPILER: return "GLSL or extension compiler"; + case GL2GL3.GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "Native Windowing binding"; case GL2GL3.GL_DEBUG_SOURCE_THIRD_PARTY: return "Third party"; case GL2GL3.GL_DEBUG_SOURCE_APPLICATION: return "Application"; case GL2GL3.GL_DEBUG_SOURCE_OTHER: return "generic"; default: return "Unknown (" + toHexString(dbgSource) + ")"; } } - + public static String getDbgTypeString(int dbgType) { switch(dbgType) { case GL2GL3.GL_DEBUG_TYPE_ERROR: return "Error"; - case GL2GL3.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "Warning: marked for deprecation"; + case GL2GL3.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "Warning: marked for deprecation"; case GL2GL3.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "Warning: undefined behavior"; - case GL2GL3.GL_DEBUG_TYPE_PERFORMANCE: return "Warning: implementation dependent performance"; - case GL2GL3.GL_DEBUG_TYPE_PORTABILITY: return "Warning: vendor-specific extension use"; - case GL2GL3.GL_DEBUG_TYPE_OTHER: return "Warning: generic"; + case GL2GL3.GL_DEBUG_TYPE_PERFORMANCE: return "Warning: implementation dependent performance"; + case GL2GL3.GL_DEBUG_TYPE_PORTABILITY: return "Warning: vendor-specific extension use"; + case GL2GL3.GL_DEBUG_TYPE_OTHER: return "Warning: generic"; default: return "Unknown (" + toHexString(dbgType) + ")"; } } - + public static String getDbgSeverityString(int dbgSeverity) { switch(dbgSeverity) { - case GL2GL3.GL_DEBUG_SEVERITY_HIGH: return "High: dangerous undefined behavior"; - case GL2GL3.GL_DEBUG_SEVERITY_MEDIUM: return "Medium: Severe performance/deprecation/other warnings"; - case GL2GL3.GL_DEBUG_SEVERITY_LOW: return "Low: Performance warnings (redundancy/undefined)"; + case GL2GL3.GL_DEBUG_SEVERITY_HIGH: return "High: dangerous undefined behavior"; + case GL2GL3.GL_DEBUG_SEVERITY_MEDIUM: return "Medium: Severe performance/deprecation/other warnings"; + case GL2GL3.GL_DEBUG_SEVERITY_LOW: return "Low: Performance warnings (redundancy/undefined)"; default: return "Unknown (" + toHexString(dbgSeverity) + ")"; } } - + public static StringBuilder toHexString(StringBuilder sb, int i) { if(null==sb) { sb = new StringBuilder(); @@ -247,6 +247,6 @@ public class GLDebugMessage { } public static String toHexString(int i) { return "0x"+Integer.toHexString(i); - } - + } + } diff --git a/src/jogl/classes/javax/media/opengl/GLDrawable.java b/src/jogl/classes/javax/media/opengl/GLDrawable.java index 46fa923ad..5a032db29 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawable.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawable.java @@ -73,13 +73,13 @@ public interface GLDrawable { *

            *

            * End users do not need to call this method; it is not necessary to - * call setRealized on a {@link GLAutoDrawable} + * call setRealized on a {@link GLAutoDrawable} * as these perform the appropriate calls on their underlying GLDrawables internally. *

            *

            * Developers implementing new OpenGL components for various window * toolkits need to call this method against GLDrawables obtained - * from the GLDrawableFactory via the + * from the GLDrawableFactory via the * {@link GLDrawableFactory#createGLDrawable(NativeSurface)} method. * It must typically be * called with an argument of true when the component @@ -89,7 +89,7 @@ public interface GLDrawable { * the addNotify method and with an argument of * false in the removeNotify method. *

            - *

            + *

            * GLDrawable implementations should handle multiple * cycles of setRealized(true) / * setRealized(false) calls. Most, if not all, Java @@ -104,7 +104,7 @@ public interface GLDrawable { * associated resources as the component becomes realized and * unrealized, respectively. *

            - *

            + *

            * With an argument of true, * the minimum implementation shall call * {@link NativeSurface#lockSurface() NativeSurface's lockSurface()} and if successful: @@ -117,7 +117,7 @@ public interface GLDrawable { * ensures resolving the window/surface handles, and the drawable's {@link GLCapabilities} * might have changed. *

            - *

            + *

            * Calling this method has no other effects. For example, if * removeNotify is called on a Canvas implementation * for which a GLDrawable has been created, it is also necessary to @@ -130,7 +130,7 @@ public interface GLDrawable { */ public void setRealized(boolean realized); - /** + /** * Returns true if this drawable is realized, otherwise true. *

            * A drawable can be realized and unrealized via {@link #setRealized(boolean)}. @@ -146,19 +146,19 @@ public interface GLDrawable { public int getHeight(); /** - * Returns true if the drawable is rendered in + * Returns true if the drawable is rendered in * OpenGL's coordinate system, origin at bottom left. * Otherwise returns false, i.e. origin at top left. *

            * Default impl. is true, i.e. OpenGL coordinate system. - *

            + *

            *

            * Currently only MS-Windows bitmap offscreen drawable uses a non OpenGL orientation and hence returns false.
            * This removes the need of a vertical flip when used in AWT or Windows applications. *

            */ public boolean isGLOriented(); - + /** Swaps the front and back buffers of this drawable. For {@link GLAutoDrawable} implementations, when automatic buffer swapping is enabled (as is the default), this method is called @@ -191,11 +191,11 @@ public interface GLDrawable { public NativeSurface getNativeSurface(); /** - * Returns the GL drawable handle, + * Returns the GL drawable handle, * guaranteed to be valid after {@link #setRealized(boolean) realization} * and while it's {@link NativeSurface surface} is being {@link NativeSurface#lockSurface() locked}. *

            - * It is usually identical to the underlying windowing toolkit {@link NativeSurface surface}'s + * It is usually identical to the underlying windowing toolkit {@link NativeSurface surface}'s * {@link javax.media.nativewindow.NativeSurface#getSurfaceHandle() handle} * or an intermediate layer to suite GL, e.g. an EGL surface. *

            diff --git a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java index 7c3c42e45..e486e2bfd 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -83,7 +83,7 @@ import jogamp.opengl.Debug; during the first repaint of the {@link javax.media.opengl.awt.GLCanvas} or {@link javax.media.opengl.awt.GLJPanel} if the capabilities can not be met.
            {@link javax.media.opengl.GLPbuffer} are always - created immediately and their creation will fail with a + created immediately and their creation will fail with a {@link javax.media.opengl.GLException} if errors occur.

            The concrete GLDrawableFactory subclass instantiated by {@link @@ -94,21 +94,21 @@ import jogamp.opengl.Debug; public abstract class GLDrawableFactory { protected static final boolean DEBUG = Debug.debug("GLDrawable"); - - /** - * We have to disable support for ANGLE, the D3D ES2 emulation on Windows provided w/ Firefox and Chrome. + + /** + * We have to disable support for ANGLE, the D3D ES2 emulation on Windows provided w/ Firefox and Chrome. * When run in the mentioned browsers, the eglInitialize(..) implementation crashes. *

            * This can be overridden by explicitly enabling ANGLE on Windows by setting the property * jogl.enable.ANGLE. - *

            + *

            */ protected static final boolean enableANGLE = Debug.isPropertyDefined("jogl.enable.ANGLE", true); - /** + /** * In case no OpenGL ES implementation is required * and if the running platform may have a buggy implementation, - * setting the property jogl.disable.opengles disables querying a possible existing OpenGL ES implementation. + * setting the property jogl.disable.opengles disables querying a possible existing OpenGL ES implementation. */ protected static final boolean disableOpenGLES = Debug.isPropertyDefined("jogl.disable.opengles", true); @@ -117,11 +117,11 @@ public abstract class GLDrawableFactory { private static GLDrawableFactory nativeOSFactory; private static ArrayList glDrawableFactories = new ArrayList(); - + /** * Instantiate singleton factories if available, EGLES1, EGLES2 and the OS native ones. */ - public static final void initSingleton() { + public static final void initSingleton() { if (!isInit) { // volatile: ok synchronized (GLDrawableFactory.class) { if (!isInit) { @@ -130,7 +130,7 @@ public abstract class GLDrawableFactory { } } } - } + } private static final void initSingletonImpl() { NativeWindowFactory.initSingleton(); NativeWindowFactory.addCustomShutdownHook(false /* head */, new Runnable() { @@ -138,7 +138,7 @@ public abstract class GLDrawableFactory { shutdown0(); } }); - + final String nwt = NativeWindowFactory.getNativeWindowType(true); GLDrawableFactory tmp = null; String factoryClassName = Debug.getProperty("jogl.gldrawablefactory.class.name", true); @@ -163,7 +163,7 @@ public abstract class GLDrawableFactory { } try { tmp = (GLDrawableFactory) ReflectionUtil.createInstance(factoryClassName, cl); - } catch (Exception jre) { + } catch (Exception jre) { if (DEBUG || GLProfile.DEBUG) { System.err.println("Info: GLDrawableFactory.static - Native Platform: "+nwt+" - not available: "+factoryClassName); jre.printStackTrace(); @@ -202,7 +202,7 @@ public abstract class GLDrawableFactory { } } } - + private static void shutdown0() { // Following code will _always_ remain in shutdown hook // due to special semantics of native utils, i.e. X11Utils. @@ -228,22 +228,22 @@ public abstract class GLDrawableFactory { } } glDrawableFactories.clear(); - - // both were members of glDrawableFactories and are shutdown already + + // both were members of glDrawableFactories and are shutdown already nativeOSFactory = null; eglFactory = null; } GLContext.shutdown(); } - + protected GLDrawableFactory() { synchronized(glDrawableFactories) { glDrawableFactories.add(this); } } - + protected static String getThreadName() { return Thread.currentThread().getName(); } - + /** Returns true if this factory is complete, i.e. ready to be used. Otherwise return false. */ protected abstract boolean isComplete(); @@ -253,14 +253,14 @@ public abstract class GLDrawableFactory { protected abstract void destroy(); public abstract void resetDisplayGamma(); - + /** * Retrieve the default device {@link AbstractGraphicsDevice#getConnection() connection}, * {@link AbstractGraphicsDevice#getUnitID() unit ID} and {@link AbstractGraphicsDevice#getUniqueID() unique ID name}. for this factory
            * The implementation must return a non null default device, which must not be opened, ie. it's native handle is null. *

            * This method shall return the default device if available - * even if the GLDrawableFactory is not functional and hence not compatible. + * even if the GLDrawableFactory is not functional and hence not compatible. * The latter situation may happen because no native OpenGL implementation is available for the specific implementation. *

            * @return the default shared device for this factory, eg. :0.0 on X11 desktop. @@ -272,7 +272,7 @@ public abstract class GLDrawableFactory { * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be null for the platform's default device. * @return true if the device is compatible with this factory, ie. if it can be used for GLDrawable creation. Otherwise false. * This implies validation whether the implementation is functional. - * + * * @see #getDefaultDevice() */ public abstract boolean getIsDeviceCompatible(AbstractGraphicsDevice device); @@ -287,8 +287,8 @@ public abstract class GLDrawableFactory { System.err.println("Info: "+getClass().getSimpleName()+".validateDevice: using default device : "+device); } } - - // Always validate the device, + + // Always validate the device, // since even the default device may not be used by this factory. if( !getIsDeviceCompatible(device) ) { if (GLProfile.DEBUG) { @@ -300,29 +300,29 @@ public abstract class GLDrawableFactory { } /** - * Validate and start the shared resource runner thread if necessary and + * Validate and start the shared resource runner thread if necessary and * if the implementation uses it. - * + * * @return the shared resource runner thread, if implementation uses it. */ protected abstract Thread getSharedResourceThread(); - + /** * Create the shared resource used internally as a reference for capabilities etc. *

            - * Returns true if a shared resource could be created + * Returns true if a shared resource could be created * for the device {@link AbstractGraphicsDevice#getConnection()}.
            * This does not imply a shared resource is mapped (ie. made persistent), but is available in general
            . *

            * * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be null for the platform's default device. - * @return true if a shared resource could been created, otherwise false. + * @return true if a shared resource could been created, otherwise false. */ protected final boolean createSharedResource(AbstractGraphicsDevice device) { return createSharedResourceImpl(device); - } + } protected abstract boolean createSharedResourceImpl(AbstractGraphicsDevice device); - + /** * Returns true if the quirk exist in the shared resource's context {@link GLRendererQuirks}. *

            @@ -332,7 +332,7 @@ public abstract class GLDrawableFactory { return null != glrq ? glrq.exist(quirk) : false; *

            *

            - * + * * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be null for the platform's default device. * @param quirk the quirk to be tested, e.g. {@link GLRendererQuirks#NoDoubleBufferedPBuffer}. * @throws IllegalArgumentException if the quirk is out of range @@ -343,7 +343,7 @@ public abstract class GLDrawableFactory { final GLRendererQuirks glrq = getRendererQuirks(device); return null != glrq ? glrq.exist(quirk) : false; } - + /** * Returns the shared resource's context {@link GLRendererQuirks}. *

            @@ -358,12 +358,12 @@ public abstract class GLDrawableFactory { * @see GLRendererQuirks */ public abstract GLRendererQuirks getRendererQuirks(AbstractGraphicsDevice device); - + /** * Returns the sole GLDrawableFactory instance for the desktop (X11, WGL, ..) if exist or null */ public static GLDrawableFactory getDesktopFactory() { - GLProfile.initSingleton(); + GLProfile.initSingleton(); return nativeOSFactory; } @@ -371,14 +371,14 @@ public abstract class GLDrawableFactory { * Returns the sole GLDrawableFactory instance for EGL if exist or null */ public static GLDrawableFactory getEGLFactory() { - GLProfile.initSingleton(); + GLProfile.initSingleton(); return eglFactory; } - /** - * Returns the sole GLDrawableFactory instance. - * - * @param glProfile GLProfile to determine the factory type, ie EGLDrawableFactory, + /** + * Returns the sole GLDrawableFactory 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 GLDrawableFactory getFactory(GLProfile glProfile) throws GLException { @@ -387,7 +387,7 @@ public abstract class GLDrawableFactory { protected static GLDrawableFactory getFactoryImpl(String glProfileImplName) throws GLException { if ( GLProfile.usesNativeGLES(glProfileImplName) ) { - if(null!=eglFactory) { + if(null!=eglFactory) { return eglFactory; } } else if(null!=nativeOSFactory) { @@ -446,10 +446,10 @@ public abstract class GLDrawableFactory { * and {@link #canCreateGLPbuffer(AbstractGraphicsDevice, GLProfile) canCreateGLPbuffer(device)} is true. *

            *

            - * If not onscreen and neither FBO nor Pbuffer is available, + * If not onscreen and neither FBO nor Pbuffer is available, * a simple pixmap/bitmap drawable/surface is created, which is unlikely to be hardware accelerated. *

            - * + * * @throws IllegalArgumentException if the passed target is null * @throws GLException if any window system-specific errors caused * the creation of the GLDrawable to fail. @@ -463,12 +463,12 @@ public abstract class GLDrawableFactory { */ public abstract GLDrawable createGLDrawable(NativeSurface target) throws IllegalArgumentException, GLException; - + /** - * Creates a {@link GLDrawable#isRealized() realized} {@link GLOffscreenAutoDrawable} + * Creates a {@link GLDrawable#isRealized() realized} {@link GLOffscreenAutoDrawable} * incl it's offscreen {@link javax.media.nativewindow.NativeSurface} with the given capabilites and dimensions. *

            - * The {@link GLOffscreenAutoDrawable}'s {@link GLDrawable} is {@link GLDrawable#isRealized() realized} + * The {@link GLOffscreenAutoDrawable}'s {@link GLDrawable} is {@link GLDrawable#isRealized() realized} * and it's {@link GLContext} assigned but not yet made current. *

            *

            @@ -485,7 +485,7 @@ public abstract class GLDrawableFactory { * and {@link #canCreateGLPbuffer(AbstractGraphicsDevice, GLProfile) canCreateGLPbuffer(device)} is true. *

            *

            - * If neither FBO nor Pbuffer is available, + * If neither FBO nor Pbuffer is available, * a simple pixmap/bitmap auto drawable is created, which is unlikely to be hardware accelerated. *

            * @@ -498,7 +498,7 @@ public abstract class GLDrawableFactory { * * @throws GLException if any window system-specific errors caused * the creation of the Offscreen to fail. - * + * * @see #createOffscreenDrawable(AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int) */ public abstract GLOffscreenAutoDrawable createOffscreenAutoDrawable(AbstractGraphicsDevice device, @@ -507,7 +507,7 @@ public abstract class GLDrawableFactory { int width, int height, GLContext shareWith) throws GLException; /** - * Creates an {@link GLDrawable#isRealized() unrealized} offscreen {@link GLDrawable} + * Creates an {@link GLDrawable#isRealized() unrealized} offscreen {@link GLDrawable} * incl it's offscreen {@link javax.media.nativewindow.NativeSurface} with the given capabilites and dimensions. *

            * In case the passed {@link GLCapabilitiesImmutable} contains default values, i.e. @@ -523,7 +523,7 @@ public abstract class GLDrawableFactory { * and {@link #canCreateGLPbuffer(AbstractGraphicsDevice, GLProfile) canCreateGLPbuffer(device)} is true. *

            *

            - * If neither FBO nor Pbuffer is available, + * If neither FBO nor Pbuffer is available, * a simple pixmap/bitmap drawable is created, which is unlikely to be hardware accelerated. *

            * @@ -537,7 +537,7 @@ public abstract class GLDrawableFactory { * * @throws GLException if any window system-specific errors caused * the creation of the Offscreen to fail. - * + * * @see #createOffscreenAutoDrawable(AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int, GLContext) */ public abstract GLDrawable createOffscreenDrawable(AbstractGraphicsDevice device, @@ -546,7 +546,7 @@ public abstract class GLDrawableFactory { int width, int height) throws GLException; /** - * Creates an {@link GLDrawable#isRealized() unrealized} dummy {@link GLDrawable}. + * Creates an {@link GLDrawable#isRealized() unrealized} dummy {@link GLDrawable}. * A dummy drawable is not visible on screen and will not be used to render directly to, it maybe on- or offscreen. *

            * It is used to allow the creation of a {@link GLContext} to query information. @@ -558,26 +558,26 @@ public abstract class GLDrawableFactory { * @return the created dummy {@link GLDrawable} */ public abstract GLDrawable createDummyDrawable(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLProfile glp); - + /** - * Creates a proxy {@link NativeSurface} w/ defined surface handle, - * i.e. a {@link jogamp.nativewindow.WrappedSurface} or {@link jogamp.nativewindow.windows.GDISurface} instance. + * Creates a proxy {@link NativeSurface} w/ defined surface handle, + * i.e. a {@link jogamp.nativewindow.WrappedSurface} or {@link jogamp.nativewindow.windows.GDISurface} instance. *

            - * It's {@link AbstractGraphicsConfiguration} is properly set according to the given + * It's {@link AbstractGraphicsConfiguration} is properly set according to the given * windowHandle's native visualID if set or the given {@link GLCapabilitiesImmutable}. *

            *

            * Lifecycle (creation and destruction) of the given surface handle shall be handled by the caller - * via {@link ProxySurface#createNotify()} and {@link ProxySurface#destroyNotify()}. + * via {@link ProxySurface#createNotify()} and {@link ProxySurface#destroyNotify()}. *

            *

            * Such surface can be used to instantiate a GLDrawable. With the help of {@link GLAutoDrawableDelegate} - * you will be able to implement a new native windowing system binding almost on-the-fly, - * see {@link com.jogamp.opengl.swt.GLCanvas}. + * you will be able to implement a new native windowing system binding almost on-the-fly, + * see {@link com.jogamp.opengl.swt.GLCanvas}. *

            - * + * * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be null for the platform's default device. - * Caller has to ensure it is compatible w/ the given windowHandle + * Caller has to ensure it is compatible w/ the given windowHandle * @param screenIdx matching screen index of given windowHandle * @param windowHandle the native window handle * @param caps the requested GLCapabilties @@ -586,15 +586,15 @@ public abstract class GLDrawableFactory { * @return the created {@link ProxySurface} instance w/ defined surface handle. */ public abstract ProxySurface createProxySurface(AbstractGraphicsDevice device, - int screenIdx, - long windowHandle, + int screenIdx, + long windowHandle, GLCapabilitiesImmutable caps, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream); - + /** * Returns true if it is possible to create an framebuffer object (FBO). *

            * FBO feature is implemented in OpenGL, hence it is {@link GLProfile} dependent. - *

            + *

            *

            * FBO support is queried as described in {@link GLContext#hasBasicFBOSupport()}. *

            @@ -607,9 +607,9 @@ public abstract class GLDrawableFactory { /** * Returns true if it is possible to create an pbuffer surface. - *

            - * Some older graphics cards do not have this capability, - * as well as some new GL implementation, i.e. OpenGL 3 core on OSX. + *

            + * Some older graphics cards do not have this capability, + * as well as some new GL implementation, i.e. OpenGL 3 core on OSX. *

            * * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be null for the platform's default device. @@ -637,7 +637,7 @@ public abstract class GLDrawableFactory { * * @throws GLException if any window system-specific errors caused * the creation of the GLPbuffer to fail. - * + * * @deprecated {@link GLPbuffer} is deprecated, use {@link #createOffscreenAutoDrawable(AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int, GLContext)} */ public abstract GLPbuffer createGLPbuffer(AbstractGraphicsDevice device, @@ -648,7 +648,7 @@ public abstract class GLDrawableFactory { GLContext shareWith) throws GLException; - + //---------------------------------------------------------------------- // Methods for interacting with third-party OpenGL libraries diff --git a/src/jogl/classes/javax/media/opengl/GLEventListener.java b/src/jogl/classes/javax/media/opengl/GLEventListener.java index 15fae4a39..c8c3440b5 100644 --- a/src/jogl/classes/javax/media/opengl/GLEventListener.java +++ b/src/jogl/classes/javax/media/opengl/GLEventListener.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ @@ -49,7 +49,7 @@ import java.util.EventListener; 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 per GLContext, such as setup of lights and display lists.

            + initialization per GLContext, 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 @@ -57,7 +57,7 @@ public interface GLEventListener extends EventListener { hierarchy and later added again. */ public void init(GLAutoDrawable drawable); - + /** Notifies the listener to perform the release of all OpenGL resources per GLContext, such as memory buffers and GLSL programs.

            @@ -68,11 +68,11 @@ public interface GLEventListener extends EventListener { Note that this event does not imply the end of life of the application. It could be produced with a followup call to {@link #init(GLAutoDrawable)} - in case the GLContext has been recreated, + in case the GLContext has been recreated, e.g. due to a pixel configuration change in a multihead environment. */ public void dispose(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 diff --git a/src/jogl/classes/javax/media/opengl/GLException.java b/src/jogl/classes/javax/media/opengl/GLException.java index 644042e15..460f17be9 100644 --- a/src/jogl/classes/javax/media/opengl/GLException.java +++ b/src/jogl/classes/javax/media/opengl/GLException.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/javax/media/opengl/GLFBODrawable.java b/src/jogl/classes/javax/media/opengl/GLFBODrawable.java index df38745d5..052b08a4b 100644 --- a/src/jogl/classes/javax/media/opengl/GLFBODrawable.java +++ b/src/jogl/classes/javax/media/opengl/GLFBODrawable.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -33,17 +33,17 @@ import javax.media.nativewindow.NativeWindowException; import com.jogamp.opengl.FBObject; import com.jogamp.opengl.FBObject.TextureAttachment; -/** +/** * Platform-independent {@link GLDrawable} specialization, * exposing {@link FBObject} functionality. * *

            - * A {@link GLFBODrawable} is uninitialized until a {@link GLContext} is bound + * A {@link GLFBODrawable} is uninitialized until a {@link GLContext} is bound * and made current the first time, hence only then it's capabilities fully reflect expectations, * i.e. color, depth, stencil and MSAA bits will be valid only after the first {@link GLContext#makeCurrent() makeCurrent()} call. * On-/offscreen bits are valid after {@link #setRealized(boolean) setRealized(true)}. *

            - * + * *

            * MSAA is used if {@link GLCapabilitiesImmutable#getNumSamples() requested}. *

            @@ -51,7 +51,7 @@ import com.jogamp.opengl.FBObject.TextureAttachment; * Double buffering is used if {@link GLCapabilitiesImmutable#getDoubleBuffered() requested}. *

            *

            - * In MSAA mode, it always uses the implicit 2nd {@link FBObject framebuffer} {@link FBObject#getSamplingSinkFBO() sink}. + * In MSAA mode, it always uses the implicit 2nd {@link FBObject framebuffer} {@link FBObject#getSamplingSinkFBO() sink}. * Hence double buffering is always the case w/ MSAA. *

            *

            @@ -61,7 +61,7 @@ import com.jogamp.opengl.FBObject.TextureAttachment; * This method also allows usage of both textures seperately. *

            *

            - * It would be possible to implement double buffering simply using + * It would be possible to implement double buffering simply using * {@link TextureAttachment}s with one {@link FBObject framebuffer}. * This would require mode selection and hence complicate the API. Besides, it would * not support differentiation of read and write framebuffer and hence not be spec compliant. @@ -71,50 +71,50 @@ import com.jogamp.opengl.FBObject.TextureAttachment; * is performed either in the {@link jogamp.opengl.GLContextImpl#contextMadeCurrent(boolean) context current hook} * or when {@link jogamp.opengl.GLDrawableImpl#swapBuffersImpl(boolean) swapping buffers}, whatever comes first. *

            - */ + */ public interface GLFBODrawable extends GLDrawable { // public enum DoubleBufferMode { NONE, TEXTURE, FBO }; // TODO: Add or remove TEXTURE (only) DoubleBufferMode support - + /** * @return true if initialized, i.e. a {@link GLContext} is bound and made current once, otherwise false. */ public boolean isInitialized(); - + /** * Notify this instance about upstream size change * to reconfigure the {@link FBObject}. - * @param gl GL context object bound to this drawable, will be made current during operation. - * A prev. current context will be make current after operation. + * @param gl GL context object bound to this drawable, will be made current during operation. + * A prev. current context will be make current after operation. * @throws GLException if resize operation failed */ void resetSize(GL gl) throws GLException; - + /** * @return the used texture unit */ int getTextureUnit(); - + /** - * + * * @param unit the texture unit to be used */ void setTextureUnit(int unit); - + /** * Set the number of sample buffers if using MSAA - * - * @param gl GL context object bound to this drawable, will be made current during operation. - * A prev. current context will be make current after operation. + * + * @param gl GL context object bound to this drawable, will be made current during operation. + * A prev. current context will be make current after operation. * @param newSamples new sample size * @throws GLException if resetting the FBO failed */ void setNumSamples(GL gl, int newSamples) throws GLException; - + /** * @return the number of sample buffers if using MSAA, otherwise 0 */ int getNumSamples(); - + /** * Sets the number of buffers (FBO) being used if using {@link GLCapabilities#getDoubleBuffered() double buffering}. *

            @@ -123,22 +123,22 @@ public interface GLFBODrawable extends GLDrawable { *

            * Must be called before {@link #isInitialized() initialization}, otherwise an exception is thrown. *

            - * @return the new number of buffers (FBO) used, maybe different than the requested bufferCount (see above) + * @return the new number of buffers (FBO) used, maybe different than the requested bufferCount (see above) * @throws GLException if already initialized, see {@link #isInitialized()}. */ int setNumBuffers(int bufferCount) throws GLException; - - /** + + /** * @return the number of buffers (FBO) being used. 1 if not using {@link GLCapabilities#getDoubleBuffered() double buffering}, - * otherwise ≥ 2, depending on {@link #setNumBuffers(int)}. + * otherwise ≥ 2, depending on {@link #setNumBuffers(int)}. */ int getNumBuffers(); - + /** - * @return the used {@link DoubleBufferMode} + * @return the used {@link DoubleBufferMode} */ // DoubleBufferMode getDoubleBufferMode(); // TODO: Add or remove TEXTURE (only) DoubleBufferMode support - + /** * Sets the {@link DoubleBufferMode}. Must be called before {@link #isInitialized() initialization}, * otherwise an exception is thrown. @@ -153,11 +153,11 @@ public interface GLFBODrawable extends GLDrawable { * @throws GLException if already initialized, see {@link #isInitialized()}. */ // void setDoubleBufferMode(DoubleBufferMode mode) throws GLException; // TODO: Add or remove TEXTURE (only) DoubleBufferMode support - + /** * If MSAA is being used and {@link GL#GL_FRONT} is requested, - * the internal {@link FBObject} {@link FBObject#getSamplingSinkFBO() sample sink} is being returned. - * + * the internal {@link FBObject} {@link FBObject#getSamplingSinkFBO() sample sink} is being returned. + * * @param bufferName {@link GL#GL_FRONT} and {@link GL#GL_BACK} are valid buffer names * @return the named {@link FBObject} * @throws IllegalArgumentException if an illegal buffer name is being used @@ -167,7 +167,7 @@ public interface GLFBODrawable extends GLDrawable { /** * Returns the named texture buffer. *

            - * If MSAA is being used, only the {@link GL#GL_FRONT} buffer is accessible + * If MSAA is being used, only the {@link GL#GL_FRONT} buffer is accessible * and an exception is being thrown if {@link GL#GL_BACK} is being requested. *

            * @param bufferName {@link GL#GL_FRONT} and {@link GL#GL_BACK} are valid buffer names @@ -176,20 +176,20 @@ public interface GLFBODrawable extends GLDrawable { */ FBObject.TextureAttachment getTextureBuffer(int bufferName) throws IllegalArgumentException; - /** Resizeable {@link GLFBODrawable} specialization */ + /** Resizeable {@link GLFBODrawable} specialization */ public interface Resizeable extends GLFBODrawable { /** * Resize this drawable. *

            * This drawable is being locked during operation. *

            - * @param context the {@link GLContext} bound to this drawable, will be made current during operation - * A prev. current context will be make current after operation. + * @param context the {@link GLContext} bound to this drawable, will be made current during operation + * A prev. current context will be make current after operation. * @param newWidth * @param newHeight * @throws NativeWindowException in case the surface could no be locked * @throws GLException in case an error during the resize operation occurred */ - void setSize(GLContext context, int newWidth, int newHeight) throws NativeWindowException, GLException; + void setSize(GLContext context, int newWidth, int newHeight) throws NativeWindowException, GLException; } } diff --git a/src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java b/src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java index 6fe76a3f4..be90d935f 100644 --- a/src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java +++ b/src/jogl/classes/javax/media/opengl/GLOffscreenAutoDrawable.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -32,7 +32,7 @@ import javax.media.nativewindow.NativeWindowException; import com.jogamp.opengl.FBObject; -/** +/** * Platform-independent {@link GLAutoDrawable} specialization, * exposing offscreen functionality. *

            @@ -41,7 +41,7 @@ import com.jogamp.opengl.FBObject; *

            */ public interface GLOffscreenAutoDrawable extends GLAutoDrawable { - + /** * Resize this auto drawable. * @param newWidth @@ -56,8 +56,8 @@ public interface GLOffscreenAutoDrawable extends GLAutoDrawable { * @see #getUpstreamWidget() */ void setUpstreamWidget(Object newUpstreamWidget); - - /** {@link FBObject} based {@link GLOffscreenAutoDrawable} specialization */ - public interface FBO extends GLOffscreenAutoDrawable, GLFBODrawable { - } + + /** {@link FBObject} based {@link GLOffscreenAutoDrawable} specialization */ + public interface FBO extends GLOffscreenAutoDrawable, GLFBODrawable { + } } diff --git a/src/jogl/classes/javax/media/opengl/GLPbuffer.java b/src/jogl/classes/javax/media/opengl/GLPbuffer.java index 12f57fcd8..f36a4bf29 100644 --- a/src/jogl/classes/javax/media/opengl/GLPbuffer.java +++ b/src/jogl/classes/javax/media/opengl/GLPbuffer.java @@ -46,8 +46,8 @@ package javax.media.opengl; 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 be deprecated in a future release. - - @deprecated Use {@link GLOffscreenAutoDrawable} w/ {@link GLCapabilities#setFBO(boolean)} + + @deprecated Use {@link GLOffscreenAutoDrawable} w/ {@link GLCapabilities#setFBO(boolean)} via {@link GLDrawableFactory#createOffscreenAutoDrawable(javax.media.nativewindow.AbstractGraphicsDevice, GLCapabilitiesImmutable, GLCapabilitiesChooser, int, int, GLContext) GLDrawableFactory.createOffscreenAutoDrawable(..)}. */ public interface GLPbuffer extends GLAutoDrawable { diff --git a/src/jogl/classes/javax/media/opengl/GLPipelineFactory.java b/src/jogl/classes/javax/media/opengl/GLPipelineFactory.java index c6bf26235..d947bada2 100644 --- a/src/jogl/classes/javax/media/opengl/GLPipelineFactory.java +++ b/src/jogl/classes/javax/media/opengl/GLPipelineFactory.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,7 +28,7 @@ * 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. @@ -49,7 +49,7 @@ import jogamp.opengl.*; public class GLPipelineFactory { public static final boolean DEBUG = Debug.debug("GLPipelineFactory"); - /** + /** * Creates a pipelined GL instance using the given downstream downstream * and optional arguments additionalArgs for the constructor. * @@ -66,7 +66,7 @@ public class GLPipelineFactory { * gl = drawable.setGL( GLPipelineFactory.create("javax.media.opengl.Trace", null, gl, new Object[] { System.err } ) ); *
          *

          - * + * *

          * The upstream GL instance is determined as follows: *

            @@ -76,7 +76,7 @@ public class GLPipelineFactory { *
          • For all downstream class and superclass interfaces, do:
          • *
              *
            • If reqInterface is not null and the interface is unequal, continue loop.
            • - *
            • If downstream is not instance of interface, continue loop.
            • + *
            • If downstream is not instance of interface, continue loop.
            • *
            • If upstream class is available use it, end loop.
            • *
            *
          @@ -116,7 +116,7 @@ public class GLPipelineFactory { if(DEBUG) { System.out.println("GLPipelineFactory: "+downstream.getClass().getName() + " is _not_ instance of "+ clazzes[i].getName()); } - continue; // not a compatible one + continue; // not a compatible one } else { if(DEBUG) { System.out.println("GLPipelineFactory: "+downstream.getClass().getName() + " _is_ instance of "+ clazzes[i].getName()); @@ -153,7 +153,7 @@ public class GLPipelineFactory { // throws exception if cstr not found! Constructor cstr = ReflectionUtil.getConstructor(upstreamClazz, cstrArgTypes); Object instance = null; - try { + try { Object[] cstrArgs = new Object[ 1 + ( ( null==additionalArgs ) ? 0 : additionalArgs.length ) ] ; { int i = 0; diff --git a/src/jogl/classes/javax/media/opengl/GLProfile.java b/src/jogl/classes/javax/media/opengl/GLProfile.java index 4a2edc56b..15300e397 100644 --- a/src/jogl/classes/javax/media/opengl/GLProfile.java +++ b/src/jogl/classes/javax/media/opengl/GLProfile.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,7 +29,7 @@ * 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. @@ -66,48 +66,48 @@ import java.util.List; /** * Specifies the the OpenGL profile. - * + * * This class static singleton initialization queries the availability of all OpenGL Profiles * and instantiates singleton GLProfile objects for each available profile. * - * The platform default profile may be used, using {@link GLProfile#GetProfileDefault()}, + * The platform default profile may be used, using {@link GLProfile#GetProfileDefault()}, * or more specialized versions using the other static GetProfile methods. */ public class GLProfile { - + public static final boolean DEBUG = Debug.debug("GLProfile"); - + static { // Also initializes TempJarCache if shall be used. Platform.initSingleton(); } - + /** * Static initialization of JOGL. * *

          * This method shall not need to be called for other reasons than having a defined initialization sequence. *

          - * + * *

          * In case this method is not invoked, GLProfile is initialized implicit by * the first call to {@link #getDefault()}, {@link #get(java.lang.String)}. *

          - * + * *

          - * To initialize JOGL at startup ASAP, this method may be invoked in the main class's + * To initialize JOGL at startup ASAP, this method may be invoked in the main class's * static initializer block, in the static main() method or in the Applet init() method. *

          - * + * *

          * Since JOGL's initialization is complex and involves multi threading, it is not recommended - * to be have it invoked on the AWT EDT thread. In case all JOGL usage is performed + * to be have it invoked on the AWT EDT thread. In case all JOGL usage is performed * on the AWT EDT, invoke this method outside the AWT EDT - see above. *

          - * + * */ public static void initSingleton() { - final boolean justInitialized; + final boolean justInitialized; initLock.lock(); try { if(!initialized) { // volatile: ok @@ -117,13 +117,13 @@ public class GLProfile { System.err.println("GLProfile.initSingleton() - thread "+Thread.currentThread().getName()); Thread.dumpStack(); } - + // run the whole static initialization privileged to speed up, // since this skips checking further access AccessController.doPrivileged(new PrivilegedAction() { public Object run() { Platform.initSingleton(); - + // Performance hack to trigger classloading of the GL classes impl, which makes up to 12%, 800ms down to 700ms new Thread(new Runnable() { public void run() { @@ -132,15 +132,15 @@ public class GLProfile { ReflectionUtil.createInstance(getGLImplBaseClassName(GL4bc)+"Impl", new Class[] { GLProfile.class, GLContextImpl.class }, new Object[] { null, null }, cl); } catch (Throwable t) {} try { - ReflectionUtil.createInstance(getGLImplBaseClassName(GLES3)+"Impl", new Class[] { GLProfile.class, GLContextImpl.class }, new Object[] { null, null }, cl); + ReflectionUtil.createInstance(getGLImplBaseClassName(GLES3)+"Impl", new Class[] { GLProfile.class, GLContextImpl.class }, new Object[] { null, null }, cl); } catch (Throwable t) {} try { - ReflectionUtil.createInstance(getGLImplBaseClassName(GLES1)+"Impl", new Class[] { GLProfile.class, GLContextImpl.class }, new Object[] { null, null }, cl); + ReflectionUtil.createInstance(getGLImplBaseClassName(GLES1)+"Impl", new Class[] { GLProfile.class, GLContextImpl.class }, new Object[] { null, null }, cl); } catch (Throwable t) {} } - }, "GLProfile-GL_Bootstrapping").start(); + }, "GLProfile-GL_Bootstrapping").start(); + - if(TempJarCache.isInitialized()) { final ClassLoader cl = GLProfile.class.getClassLoader(); final String newtFactoryClassName = "com.jogamp.newt.NewtFactory"; @@ -164,13 +164,13 @@ public class GLProfile { if( justInitialized && ( hasGL234Impl || hasGLES1Impl || hasGLES3Impl ) ) { System.err.println(JoglVersion.getDefaultOpenGLInfo(defaultDevice, null, true)); } - } + } } /** * Trigger eager initialization of GLProfiles for the given device, * in case it isn't done yet. - * + * * @throws GLException if no profile for the given device is available. */ public static void initProfiles(AbstractGraphicsDevice device) throws GLException { @@ -194,7 +194,7 @@ public class GLProfile { if(DEBUG) { System.err.println("GLProfile.shutdown() - thread "+Thread.currentThread().getName()); Thread.dumpStack(); - } + } GLDrawableFactory.shutdown(); } } finally { @@ -206,11 +206,11 @@ public class GLProfile { // Query platform available OpenGL implementation // - /** + /** * Returns the availability of a profile on a device. - * + * * @param device a valid AbstractGraphicsDevice, or null for the default device. - * @param profile a valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..), + * @param profile a valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..), * or [ null, GL ] for the default profile. * @return true if the profile is available for the device, otherwise false. */ @@ -221,31 +221,31 @@ public class GLProfile { private static boolean isAvailableImpl(HashMap map, String profile) { return null != map && null != map.get(profile); } - - /** + + /** * Returns the availability of a profile on the default device. - * - * @param profile a valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..), + * + * @param profile a valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..), * or [ null, GL ] for the default profile. * @return true if the profile is available for the default device, otherwise false. */ public static boolean isAvailable(String profile) { return isAvailable(null, profile); } - - /** + + /** * Returns the availability of any profile on the default device. - * + * * @return true if any profile is available for the default device, otherwise false. */ public static boolean isAnyAvailable() { return isAvailable(null, null); } - + public static String glAvailabilityToString(AbstractGraphicsDevice device) { return glAvailabilityToString(device, null).toString(); } - + public static StringBuilder glAvailabilityToString(AbstractGraphicsDevice device, StringBuilder sb) { return glAvailabilityToString(device, sb, null, 0); } @@ -264,19 +264,19 @@ public class GLProfile { final boolean useIndent = null != indent; initSingleton(); - + if(null==device) { device = defaultDevice; } final HashMap map = getProfileMap(device, false); - + if(useIndent) { doIndent(sb, indent, indentCount).append("Native"); indentCount++; doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("GL4bc").append(indent); } else { sb.append("Native[GL4bc "); - } + } avail=isAvailableImpl(map, GL4bc); sb.append(avail); if(avail) { @@ -366,7 +366,7 @@ public class GLProfile { sb.append(", GL4ES3 "); } sb.append(isAvailableImpl(map, GL4ES3)); - + if(useIndent) { doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("GL2ES2").append(indent); } else { @@ -388,7 +388,7 @@ public class GLProfile { } else { sb.append("], Profiles["); } - + if(null != map) { for(Iterator i=map.values().iterator(); i.hasNext(); ) { if(useIndent) { @@ -418,7 +418,7 @@ public class GLProfile { return sb; } - + /** Uses the default device */ public static String glAvailabilityToString() { return glAvailabilityToString(null); @@ -465,11 +465,11 @@ public class GLProfile { /** The intersection of the desktop GL4 and ES3 profile */ public static final String GL4ES3 = "GL4ES3"; - + /** The default profile, used for the device default profile map */ private static final String GL_DEFAULT = "GL_DEFAULT"; - /** + /** * All GL Profiles in the order of default detection. * Desktop compatibility profiles (the one with fixed function pipeline) comes first * from highest to lowest version. @@ -492,7 +492,7 @@ public class GLProfile { * */ public static final String[] GL_PROFILE_LIST_ALL = new String[] { GL4bc, GL3bc, GL2, GL4, GL3, GLES3, GL4ES3, GL2GL3, GLES2, GL2ES2, GLES1, GL2ES1 }; - + /** * Order of maximum profiles. * @@ -526,7 +526,7 @@ public class GLProfile { * */ public static final String[] GL_PROFILE_LIST_MIN = new String[] { GLES1, GLES2, GL2, GLES3, GL3, GL3bc, GL4, GL4bc }; - + /** * Order of minimum original desktop profiles. * @@ -540,7 +540,7 @@ public class GLProfile { * */ public static final String[] GL_PROFILE_LIST_MIN_DESKTOP = new String[] { GL2, GL3bc, GL4bc, GL3, GL4 }; - + /** * Order of maximum fixed function profiles * @@ -582,7 +582,7 @@ public class GLProfile { * */ public static final String[] GL_PROFILE_LIST_MAX_PROGSHADER_CORE = new String[] { GL4, GL3, GLES3, GLES2 }; - + /** Returns a default GLProfile object, reflecting the best for the running platform. * It selects the first of the set {@link GLProfile#GL_PROFILE_LIST_ALL} * and favors hardware acceleration. @@ -597,7 +597,7 @@ public class GLProfile { /** Returns a default GLProfile object, reflecting the best for the running platform. * It selects the first of the set {@link GLProfile#GL_PROFILE_LIST_ALL} * and favors hardware acceleration. - *

          Uses the default device.

          + *

          Uses the default device.

          * @throws GLException if no profile is available for the default device. */ public static GLProfile getDefault() { @@ -617,7 +617,7 @@ public class GLProfile { return get(device, GL_PROFILE_LIST_MAX, favorHardwareRasterizer); } - /** Uses the default device + /** Uses the default device * @throws GLException if no profile is available for the default device. * @see #GL_PROFILE_LIST_MAX */ @@ -640,7 +640,7 @@ public class GLProfile { return get(device, GL_PROFILE_LIST_MIN, favorHardwareRasterizer); } - /** Uses the default device + /** Uses the default device * @throws GLException if no desktop profile is available for the default device. * @see #GL_PROFILE_LIST_MIN */ @@ -664,7 +664,7 @@ public class GLProfile { return get(device, GL_PROFILE_LIST_MAX_FIXEDFUNC, favorHardwareRasterizer); } - /** Uses the default device + /** Uses the default device * @throws GLException if no fixed function profile is available for the default device. * @see #GL_PROFILE_LIST_MAX_FIXEDFUNC */ @@ -687,7 +687,7 @@ public class GLProfile { return get(device, GL_PROFILE_LIST_MAX_PROGSHADER, favorHardwareRasterizer); } - /** Uses the default device + /** Uses the default device * @throws GLException if no programmable profile is available for the default device. * @see #GL_PROFILE_LIST_MAX_PROGSHADER */ @@ -706,11 +706,11 @@ public class GLProfile { */ public static GLProfile getMaxProgrammableCore(AbstractGraphicsDevice device, boolean favorHardwareRasterizer) throws GLException - { + { return get(device, GL_PROFILE_LIST_MAX_PROGSHADER_CORE, favorHardwareRasterizer); } - /** Uses the default device + /** Uses the default device * @throws GLException if no programmable core profile is available for the default device. * @see #GL_PROFILE_LIST_MAX_PROGSHADER_CORE */ @@ -719,8 +719,8 @@ public class GLProfile { { return get(GL_PROFILE_LIST_MAX_PROGSHADER_CORE, favorHardwareRasterizer); } - - /** + + /** * Returns the GL2ES1 profile implementation, hence compatible w/ GL2ES1.
          * It returns: *
          @@ -739,8 +739,8 @@ public class GLProfile {
                   return get(device, GL2ES1).getImpl();
               }
           
          -    /** 
          -     * Calls {@link #getGL2ES1(AbstractGraphicsDevice)} using the default device. 
          +    /**
          +     * Calls {@link #getGL2ES1(AbstractGraphicsDevice)} using the default device.
                * 

          Selection favors hardware rasterizer.

          * @see #getGL2ES1(AbstractGraphicsDevice) */ @@ -750,7 +750,7 @@ public class GLProfile { return get(defaultDevice, GL2ES1).getImpl(); } - /** + /** * Returns the GL2ES2 profile implementation, hence compatible w/ GL2ES2.
          * It returns: *
          @@ -769,8 +769,8 @@ public class GLProfile {
                   return get(device, GL2ES2).getImpl();
               }
           
          -    /** 
          -     * Calls {@link #getGL2ES2(AbstractGraphicsDevice)} using the default device. 
          +    /**
          +     * Calls {@link #getGL2ES2(AbstractGraphicsDevice)} using the default device.
                * 

          Selection favors hardware rasterizer.

          * @see #getGL2ES2(AbstractGraphicsDevice) */ @@ -780,7 +780,7 @@ public class GLProfile { return get(defaultDevice, GL2ES2).getImpl(); } - /** + /** * Returns the GL4ES3 profile implementation, hence compatible w/ GL4ES3.
          * It returns: *
          @@ -799,8 +799,8 @@ public class GLProfile {
                   return get(device, GL4ES3).getImpl();
               }
           
          -    /** 
          -     * Calls {@link #getGL4ES3(AbstractGraphicsDevice)} using the default device. 
          +    /**
          +     * Calls {@link #getGL4ES3(AbstractGraphicsDevice)} using the default device.
                * 

          Selection favors hardware rasterizer.

          * @see #getGL4ES3(AbstractGraphicsDevice) */ @@ -810,7 +810,7 @@ public class GLProfile { return get(defaultDevice, GL4ES3).getImpl(); } - /** + /** * Returns the GL2GL3 profile implementation, hence compatible w/ GL2GL3.
          * It returns: *
          @@ -829,8 +829,8 @@ public class GLProfile {
                   return get(device, GL2GL3).getImpl();
               }
           
          -    /** 
          -     * Calls {@link #getGL2GL3(AbstractGraphicsDevice)} using the default device. 
          +    /**
          +     * Calls {@link #getGL2GL3(AbstractGraphicsDevice)} using the default device.
                * 

          Selection favors hardware rasterizer.

          * @see #getGL2GL3(AbstractGraphicsDevice) */ @@ -846,7 +846,7 @@ public class GLProfile { * the default profile. * * @param device a valid AbstractGraphicsDevice, or null for the default device. - * @param profile a valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..), + * @param profile a valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..), * or [ null, GL ] for the default profile. * @throws GLException if the requested profile is not available for the device. */ @@ -864,8 +864,8 @@ public class GLProfile { return glp; } - /** Uses the default device - * @param profile a valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..), + /** Uses the default device + * @param profile a valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..), * or [ null, GL ] for the default profile. * @throws GLException if the requested profile is not available for the default device. */ @@ -881,14 +881,14 @@ public class GLProfile { * * @param device a valid AbstractGraphicsDevice, or null for the default device. * @param profiles array of valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..) - * @param favorHardwareRasterizer set to true, if hardware rasterizer shall be favored, otherwise false. + * @param favorHardwareRasterizer set to true, if hardware rasterizer shall be favored, otherwise false. * @throws GLException if the non of the requested profiles is available for the device. */ public static GLProfile get(AbstractGraphicsDevice device, String[] profiles, boolean favorHardwareRasterizer) throws GLException { GLProfile glProfileAny = null; - + HashMap map = getProfileMap(device, true); for(int i=0; i GL2, or GL3 -> GL3 + + /** + * return this profiles implementation name, eg. GL2ES2 -> GL2, or GL3 -> GL3 */ public final String getImplName() { return null != profileImpl ? profileImpl.getName() : getName(); @@ -1102,12 +1102,12 @@ public class GLProfile { public final boolean isGLES2() { return GLES2 == profile; } - + /** Indicates whether this profile is capable of GLES3.

          Includes [ GLES3 ].

          */ public final boolean isGLES3() { return GLES3 == profile; } - + /** Indicates whether this profile is capable of GLES.

          Includes [ GLES3, GLES1, GLES2 ].

          */ public final boolean isGLES() { return GLES3 == profile || GLES2 == profile || GLES1 == profile; @@ -1122,21 +1122,21 @@ public class GLProfile { public final boolean isGL2GL3() { return GL2GL3 == profile || isGL3() || isGL2(); } - + /** Indicates whether this profile is capable of GL2ES2.

          Includes [ GL4bc, GL4, GL3bc, GL3, GLES3, GL2, GL2GL3, GL2ES2, GLES2 ].

          */ public final boolean isGL2ES2() { return GL2ES2 == profile || isGLES2() || isGL2GL3(); } - /** + /** * Indicates whether this profile is capable of GL2ES3.

          Includes [ GL4bc, GL4, GL3bc, GL3, GLES3, GL3ES3, GL2, GL2GL3 ].

          - * @see #isGL3ES3() - * @see #isGL2GL3() + * @see #isGL3ES3() + * @see #isGL2GL3() */ public final boolean isGL2ES3() { return isGL3ES3() || isGL2GL3(); } - + /** Indicates whether this profile is capable of GL3ES3.

          Includes [ GL4bc, GL4, GL3bc, GL3, GLES3 ].

          */ public final boolean isGL3ES3() { return isGL4ES3() || isGL3(); @@ -1172,7 +1172,7 @@ public class GLProfile { return usesNativeGLES2() || usesNativeGLES1(); } - /** + /** * General validation if type is a valid GL data type * for the current profile */ @@ -1200,14 +1200,14 @@ public class GLProfile { if( isGL2() ) { return true; } - } + } if(throwException) { throw new GLException("Illegal data type on profile "+this+": "+type); } return false; } - - public boolean isValidArrayDataType(int index, int comps, int type, + + public boolean isValidArrayDataType(int index, int comps, int type, boolean isVertexAttribPointer, boolean throwException) { final String arrayName = getGLArrayName(index); if( isGLES1() ) { @@ -1226,7 +1226,7 @@ public class GLProfile { case GL.GL_FIXED: case GL.GL_FLOAT: break; - default: + default: if(throwException) { throw new GLException("Illegal data type for "+arrayName+" on profile GLES1: "+type); } @@ -1238,7 +1238,7 @@ public class GLProfile { case 3: case 4: break; - default: + default: if(throwException) { throw new GLException("Illegal component number for "+arrayName+" on profile GLES1: "+comps); } @@ -1252,7 +1252,7 @@ public class GLProfile { case GL.GL_FIXED: case GL.GL_FLOAT: break; - default: + default: if(throwException) { throw new GLException("Illegal data type for "+arrayName+" on profile GLES1: "+type); } @@ -1262,7 +1262,7 @@ public class GLProfile { case 0: case 3: break; - default: + default: if(throwException) { throw new GLException("Illegal component number for "+arrayName+" on profile GLES1: "+comps); } @@ -1275,7 +1275,7 @@ public class GLProfile { case GL.GL_FIXED: case GL.GL_FLOAT: break; - default: + default: if(throwException) { throw new GLException("Illegal data type for "+arrayName+" on profile GLES1: "+type); } @@ -1285,7 +1285,7 @@ public class GLProfile { case 0: case 4: break; - default: + default: if(throwException) { throw new GLException("Illegal component number for "+arrayName+" on profile GLES1: "+comps); } @@ -1303,7 +1303,7 @@ public class GLProfile { case GL.GL_FLOAT: case GL.GL_FIXED: break; - default: + default: if(throwException) { throw new GLException("Illegal data type for "+arrayName+" on profile GLES2: "+type); } @@ -1317,7 +1317,7 @@ public class GLProfile { case 3: case 4: break; - default: + default: if(throwException) { throw new GLException("Illegal component number for "+arrayName+" on profile GLES2: "+comps); } @@ -1335,7 +1335,7 @@ public class GLProfile { case javax.media.opengl.GL2ES2.GL_UNSIGNED_INT: case javax.media.opengl.GL2.GL_DOUBLE: break; - default: + default: if(throwException) { throw new GLException("Illegal data type for "+arrayName+" on profile GL2: "+type); } @@ -1348,7 +1348,7 @@ public class GLProfile { case 3: case 4: break; - default: + default: if(throwException) { throw new GLException("Illegal component number for "+arrayName+" on profile GL2: "+comps); } @@ -1363,7 +1363,7 @@ public class GLProfile { case javax.media.opengl.GL2ES2.GL_INT: case javax.media.opengl.GL2.GL_DOUBLE: break; - default: + default: if(throwException) { throw new GLException("Illegal data type for "+arrayName+" on profile GL2: "+type); } @@ -1375,7 +1375,7 @@ public class GLProfile { case 3: case 4: break; - default: + default: if(throwException) { throw new GLException("Illegal component number for "+arrayName+" on profile GL2: "+comps); } @@ -1390,7 +1390,7 @@ public class GLProfile { case javax.media.opengl.GL2ES2.GL_INT: case javax.media.opengl.GL2.GL_DOUBLE: break; - default: + default: if(throwException) { throw new GLException("Illegal data type for "+arrayName+" on profile GL2: "+type); } @@ -1400,7 +1400,7 @@ public class GLProfile { case 0: case 3: break; - default: + default: if(throwException) { throw new GLException("Illegal component number for "+arrayName+" on profile GLES1: "+comps); } @@ -1418,7 +1418,7 @@ public class GLProfile { case javax.media.opengl.GL2ES2.GL_UNSIGNED_INT: case javax.media.opengl.GL2.GL_DOUBLE: break; - default: + default: if(throwException) { throw new GLException("Illegal data type for "+arrayName+" on profile GL2: "+type); } @@ -1429,7 +1429,7 @@ public class GLProfile { case 3: case 4: break; - default: + default: if(throwException) { throw new GLException("Illegal component number for "+arrayName+" on profile GL2: "+comps); } @@ -1443,7 +1443,7 @@ public class GLProfile { case javax.media.opengl.GL2ES2.GL_INT: case javax.media.opengl.GL2.GL_DOUBLE: break; - default: + default: if(throwException) { throw new GLException("Illegal data type for "+arrayName+" on profile GL2: "+type); } @@ -1456,7 +1456,7 @@ public class GLProfile { case 3: case 4: break; - default: + default: if(throwException) { throw new GLException("Illegal component number for "+arrayName+" on profile GL2: "+comps); } @@ -1475,7 +1475,7 @@ public class GLProfile { private static /*final*/ boolean isAWTAvailable; - private static /*final*/ boolean hasDesktopGLFactory; + private static /*final*/ boolean hasDesktopGLFactory; private static /*final*/ boolean hasGL234Impl; private static /*final*/ boolean hasEGLFactory; private static /*final*/ boolean hasGLES3Impl; @@ -1508,11 +1508,11 @@ public class GLProfile { // depends on hasDesktopGLFactory hasGL234Impl = ReflectionUtil.isClassAvailable("jogamp.opengl.gl4.GL4bcImpl", classloader); - + // depends on hasEGLFactory hasGLES1Impl = ReflectionUtil.isClassAvailable("jogamp.opengl.es1.GLES1Impl", classloader); hasGLES3Impl = ReflectionUtil.isClassAvailable("jogamp.opengl.es3.GLES3Impl", classloader); - + // // Iteration of desktop GL availability detection // utilizing the detected GL version in the shared context. @@ -1521,7 +1521,7 @@ public class GLProfile { // which will register at GLContext .. // GLDrawableFactory.initSingleton(); - + Throwable t=null; // if successfull it has a shared dummy drawable and context created try { @@ -1592,14 +1592,14 @@ public class GLProfile { System.err.println("Info: GLProfile.init - EGL GLDrawable factory not available"); } } else { - defaultEGLDevice = eglFactory.getDefaultDevice(); + defaultEGLDevice = eglFactory.getDefaultDevice(); } if( null != defaultDesktopDevice ) { defaultDevice = defaultDesktopDevice; if(DEBUG) { System.err.println("Info: GLProfile.init - Default device is desktop derived: "+defaultDevice); - } + } } else if ( null != defaultEGLDevice ) { defaultDevice = defaultEGLDevice; if(DEBUG) { @@ -1611,12 +1611,12 @@ public class GLProfile { } defaultDevice = null; } - + // we require to initialize the EGL device 1st, if available final boolean addedEGLProfile = null != defaultEGLDevice ? initProfilesForDevice(defaultEGLDevice) : false; - final boolean addedDesktopProfile = null != defaultDesktopDevice ? initProfilesForDevice(defaultDesktopDevice) : false; + final boolean addedDesktopProfile = null != defaultDesktopDevice ? initProfilesForDevice(defaultDesktopDevice) : false; final boolean addedAnyProfile = addedEGLProfile || addedDesktopProfile ; - + if(DEBUG) { System.err.println("GLProfile.init addedAnyProfile "+addedAnyProfile+" (desktop: "+addedDesktopProfile+", egl "+addedEGLProfile+")"); System.err.println("GLProfile.init isAWTAvailable "+isAWTAvailable); @@ -1672,8 +1672,8 @@ public class GLProfile { boolean addedDesktopProfile = false; boolean addedEGLProfile = false; - final boolean deviceIsDesktopCompatible = hasDesktopGLFactory && desktopFactory.getIsDeviceCompatible(device); - + final boolean deviceIsDesktopCompatible = hasDesktopGLFactory && desktopFactory.getIsDeviceCompatible(device); + if( deviceIsDesktopCompatible ) { // 1st pretend we have all Desktop and EGL profiles .. computeProfileMap(device, true /* desktopCtxUndef*/, true /* esCtxUndef */); @@ -1698,9 +1698,9 @@ public class GLProfile { } addedDesktopProfile = computeProfileMap(device, false /* desktopCtxUndef*/, false /* esCtxUndef */); } - + final boolean deviceIsEGLCompatible = hasEGLFactory && eglFactory.getIsDeviceCompatible(device); - + // also test GLES1, GLES2 and GLES3 on desktop, since we have implementations / emulations available. if( deviceIsEGLCompatible && ( hasGLES3Impl || hasGLES1Impl ) ) { // 1st pretend we have all EGL profiles .. @@ -1718,7 +1718,7 @@ public class GLProfile { } if(!eglSharedCtxAvail) { // Remark: On Windows there is a libEGL.dll delivered w/ Chrome 15.0.874.121m and Firefox 8.0.1 - // but it seems even EGL.eglInitialize(eglDisplay, null, null) + // but it seems even EGL.eglInitialize(eglDisplay, null, null) // fails in some scenarios (eg VirtualBox 4.1.6) w/ EGL error 0x3001 (EGL_NOT_INITIALIZED). hasEGLFactory = false; hasGLES3Impl = false; @@ -1993,7 +1993,7 @@ public class GLProfile { return null; } - private static /*final*/ HashMap> deviceConn2ProfileMap = + private static /*final*/ HashMap> deviceConn2ProfileMap = new HashMap>(); /** @@ -2004,22 +2004,22 @@ public class GLProfile { * * @param device the key 'device -> GLProfiles-Map' * @param throwExceptionOnZeroProfile true if GLException shall be thrown in case of no mapped profile, otherwise false. - * @return the GLProfile HashMap if exists, otherwise null + * @return the GLProfile HashMap if exists, otherwise null * @throws GLException if no profile for the given device is available. */ - private static HashMap getProfileMap(AbstractGraphicsDevice device, boolean throwExceptionOnZeroProfile) - throws GLException + private static HashMap getProfileMap(AbstractGraphicsDevice device, boolean throwExceptionOnZeroProfile) + throws GLException { initSingleton(); if(null==defaultDevice) { // avoid NPE and notify of incomplete initialization throw new GLException("No default device available"); } - + if(null==device) { device = defaultDevice; } - + final String deviceKey = device.getUniqueID(); HashMap map = deviceConn2ProfileMap.get(deviceKey); if( null != map ) { diff --git a/src/jogl/classes/javax/media/opengl/GLRunnable.java b/src/jogl/classes/javax/media/opengl/GLRunnable.java index 1ae1c9b22..ad68662ce 100644 --- a/src/jogl/classes/javax/media/opengl/GLRunnable.java +++ b/src/jogl/classes/javax/media/opengl/GLRunnable.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package javax.media.opengl; /** @@ -33,8 +33,8 @@ package javax.media.opengl; * Declares a one-shot OpenGL command usable for injection * via {@link GLAutoDrawable#invoke(boolean, javax.media.opengl.GLRunnable)}.
          * {@link GLAutoDrawable} executes the GLRunnables within it's {@link GLAutoDrawable#display() display()} - * method after all registered {@link GLEventListener}s - * {@link GLEventListener#display(GLAutoDrawable) display(GLAutoDrawable)} + * method after all registered {@link GLEventListener}s + * {@link GLEventListener#display(GLAutoDrawable) display(GLAutoDrawable)} * methods has been called. *

          *

          @@ -44,13 +44,13 @@ package javax.media.opengl; * This might be useful to inject OpenGL commands from an I/O event listener. *

          */ -public interface GLRunnable { +public interface GLRunnable { /** * @param drawable the associated drawable and current context for this call * @return true if the GL [back] framebuffer remains intact by this runnable, otherwise false. * If returning false {@link GLAutoDrawable} will call - * {@link GLEventListener#display(GLAutoDrawable) display(GLAutoDrawable)} - * of all registered {@link GLEventListener}s once more. + * {@link GLEventListener#display(GLAutoDrawable) display(GLAutoDrawable)} + * of all registered {@link GLEventListener}s once more. * @see GLRunnable */ boolean run(GLAutoDrawable drawable); diff --git a/src/jogl/classes/javax/media/opengl/GLRunnable2.java b/src/jogl/classes/javax/media/opengl/GLRunnable2.java index 1598a6215..5f0393257 100644 --- a/src/jogl/classes/javax/media/opengl/GLRunnable2.java +++ b/src/jogl/classes/javax/media/opengl/GLRunnable2.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package javax.media.opengl; /** @@ -33,11 +33,11 @@ package javax.media.opengl; * Declares a one-shot OpenGL command. *

          */ -public interface GLRunnable2 { +public interface GLRunnable2 { /** * @param gl a current GL object * @param args custom arguments - * @return the desired object + * @return the desired object */ T run(GL gl, U args); } diff --git a/src/jogl/classes/javax/media/opengl/GLUniformData.java b/src/jogl/classes/javax/media/opengl/GLUniformData.java index 60d0c58bf..700bba2eb 100644 --- a/src/jogl/classes/javax/media/opengl/GLUniformData.java +++ b/src/jogl/classes/javax/media/opengl/GLUniformData.java @@ -77,16 +77,16 @@ public class GLUniformData { sb = new StringBuilder(); } sb.append("GLUniformData[name ").append(name). - append(", location ").append(location). + append(", location ").append(location). append(", size ").append(rows).append("x").append(columns). - append(", count ").append(count). - append(", data "); + append(", count ").append(count). + append(", data "); if(isMatrix() && data instanceof FloatBuffer) { sb.append("\n"); - final FloatBuffer fb = (FloatBuffer)getBuffer(); + final FloatBuffer fb = (FloatBuffer)getBuffer(); for(int i=0; i @@ -59,12 +59,12 @@ import jogamp.opengl.ThreadingImpl; Due to these limitations, and due to the inherent multithreading in the Java platform (in particular, in the Abstract Window - Toolkit), it is often necessary to limit the multithreading - occurring in the typical application using the OpenGL API. + Toolkit), it is often necessary to limit the multithreading + occurring in the typical application using the OpenGL API.

          - In the current reference implementation, for instance, multithreading + In the current reference implementation, for instance, multithreading has been limited by forcing all OpenGL-related work for GLAutoDrawables on to a single thread. In other words, if an application uses only the @@ -93,9 +93,9 @@ import jogamp.opengl.ThreadingImpl; This class also provides mechanisms for querying whether this internal serialization of OpenGL work is in effect, and a - programmatic way of disabling it. In the current reference - implementation it is enabled by default, although it could be - disabled in the future if OpenGL drivers become more robust on + programmatic way of disabling it. In the current reference + implementation it is enabled by default, although it could be + disabled in the future if OpenGL drivers become more robust on all platforms.

          @@ -113,7 +113,7 @@ import jogamp.opengl.ThreadingImpl; platforms, and also the default behavior older releases) -Djogl.1thread=worker Enable single-threading of OpenGL work on newly-created worker thread (not suitable for Mac OS X or X11 platforms, and risky on Windows in applet environments) -

          +
          */ public class Threading { @@ -121,9 +121,9 @@ public class Threading { /** No reason to ever instantiate this class */ private Threading() {} - /** If an implementation of the javax.media.opengl APIs offers a - multithreading option but the default behavior is single-threading, - this API provides a mechanism for end users to disable single-threading + /** If an implementation of the javax.media.opengl APIs offers a + multithreading option but the default behavior is single-threading, + this API provides a mechanism for end users to disable single-threading in this 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 @@ -133,7 +133,7 @@ public class Threading { GLPbuffer. Currently there is no supported way to re-enable it once disabled, partly to discourage careless use of this method. This method should be called as early as possible in an - application. */ + application. */ public static final void disableSingleThreading() { ThreadingImpl.disableSingleThreading(); } @@ -145,11 +145,11 @@ public class Threading { } /** Indicates whether the current thread is the designated toolkit thread, - if such semantics exists. */ + if such semantics exists. */ public static final boolean isToolkitThread() throws GLException { return ThreadingImpl.isToolkitThread(); } - + /** Indicates whether the current thread is the single thread on which this implementation of the javax.media.opengl APIs performs all of its OpenGL-related work. This method should only @@ -166,12 +166,12 @@ public class Threading { thread (i.e., if isOpenGLThread() 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. + Runnable directly or perform the work inside it. **/ public static final void invokeOnOpenGLThread(boolean wait, Runnable r) throws GLException { ThreadingImpl.invokeOnOpenGLThread(wait, r); } - + /** * If {@link #isSingleThreaded()} and not {@link #isOpenGLThread()} * and the lock is not being hold by this thread, @@ -179,14 +179,14 @@ public class Threading { *

          * Otherwise invoke Runnable r on the current thread. *

          - * - * @param wait set to true for waiting until Runnable r is finished, otherwise false. + * + * @param wait set to true for waiting until Runnable r is finished, otherwise false. * @param r the Runnable to be executed * @param lock optional lock object to be tested * @throws GLException */ public static final void invoke(boolean wait, Runnable r, Object lock) throws GLException { - if ( isSingleThreaded() && !isOpenGLThread() && + if ( isSingleThreaded() && !isOpenGLThread() && ( null == lock || !Thread.holdsLock(lock) ) ) { invokeOnOpenGLThread(wait, r); } else { diff --git a/src/jogl/classes/javax/media/opengl/TraceGL2.java b/src/jogl/classes/javax/media/opengl/TraceGL2.java index 58f5d9f99..c577332e9 100644 --- a/src/jogl/classes/javax/media/opengl/TraceGL2.java +++ b/src/jogl/classes/javax/media/opengl/TraceGL2.java @@ -12,7 +12,7 @@ import java.io.PrintStream; * Sample code which installs this pipeline, manual: *
            *     gl = drawable.setGL(new TraceGL(drawable.getGL(), System.err));
          - * 
          + *
          * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}. *

          */ diff --git a/src/jogl/classes/javax/media/opengl/TraceGL3.java b/src/jogl/classes/javax/media/opengl/TraceGL3.java index 616b31f61..5fccf40c7 100644 --- a/src/jogl/classes/javax/media/opengl/TraceGL3.java +++ b/src/jogl/classes/javax/media/opengl/TraceGL3.java @@ -12,7 +12,7 @@ import java.io.PrintStream; * Sample code which installs this pipeline, manual: *
            *     gl = drawable.setGL(new TraceGL(drawable.getGL(), System.err));
          - * 
          + *
          * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}. *

          */ diff --git a/src/jogl/classes/javax/media/opengl/TraceGL3bc.java b/src/jogl/classes/javax/media/opengl/TraceGL3bc.java index f3761d4d6..84f537f60 100644 --- a/src/jogl/classes/javax/media/opengl/TraceGL3bc.java +++ b/src/jogl/classes/javax/media/opengl/TraceGL3bc.java @@ -12,7 +12,7 @@ import java.io.PrintStream; * Sample code which installs this pipeline, manual: *
            *     gl = drawable.setGL(new TraceGL(drawable.getGL(), System.err));
          - * 
          + * * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}. *

          */ diff --git a/src/jogl/classes/javax/media/opengl/TraceGL4.java b/src/jogl/classes/javax/media/opengl/TraceGL4.java index a12bf0f47..afe2cd9a1 100644 --- a/src/jogl/classes/javax/media/opengl/TraceGL4.java +++ b/src/jogl/classes/javax/media/opengl/TraceGL4.java @@ -12,7 +12,7 @@ import java.io.PrintStream; * Sample code which installs this pipeline, manual: *
            *     gl = drawable.setGL(new TraceGL(drawable.getGL(), System.err));
          - * 
          + * * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}. *

          */ diff --git a/src/jogl/classes/javax/media/opengl/TraceGLES2.java b/src/jogl/classes/javax/media/opengl/TraceGLES2.java index 38d60e3ac..4740e2e72 100644 --- a/src/jogl/classes/javax/media/opengl/TraceGLES2.java +++ b/src/jogl/classes/javax/media/opengl/TraceGLES2.java @@ -12,7 +12,7 @@ import java.io.PrintStream; * Sample code which installs this pipeline, manual: *
            *     gl = drawable.setGL(new TraceGL(drawable.getGL(), System.err));
          - * 
          + * * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}. *

          */ diff --git a/src/jogl/classes/javax/media/opengl/awt/ComponentEvents.java b/src/jogl/classes/javax/media/opengl/awt/ComponentEvents.java index 0c4f63c2d..5feaa5760 100644 --- a/src/jogl/classes/javax/media/opengl/awt/ComponentEvents.java +++ b/src/jogl/classes/javax/media/opengl/awt/ComponentEvents.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 6828beb10..f08fbafe8 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -115,15 +115,15 @@ import jogamp.opengl.awt.AWTTilePainter; of Z-ordering or LayoutManager problems. * *
          Offscreen Layer Remarks
          - * + * * {@link OffscreenLayerOption#setShallUseOffscreenLayer(boolean) setShallUseOffscreenLayer(true)} - * maybe called to use an offscreen drawable (FBO or PBuffer) allowing + * maybe called to use an offscreen drawable (FBO or PBuffer) allowing * the underlying JAWT mechanism to composite the image, if supported. *

          * {@link OffscreenLayerOption#setShallUseOffscreenLayer(boolean) setShallUseOffscreenLayer(true)} * is being called if {@link GLCapabilitiesImmutable#isOnscreen()} is false. *

          - * + * *
          Java2D OpenGL Remarks
          * * To avoid any conflicts with a potential Java2D OpenGL context,
          @@ -274,7 +274,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing public final Object getUpstreamWidget() { return this; } - + @Override public void setShallUseOffscreenLayer(boolean v) { shallUseOffscreenLayer = v; @@ -315,11 +315,11 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing * all platforms since the peer hasn't been created. */ final GraphicsConfiguration gc = super.getGraphicsConfiguration(); - + if( Beans.isDesignTime() ) { return gc; } - + /* * chosen is only non-null on platforms where the GLDrawableFactory * returns a non-null GraphicsConfiguration (in the GLCanvas @@ -431,11 +431,11 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing _lock.unlock(); } } - + private final void setRealizedImpl(boolean realized) { final RecursiveLock _lock = lock; _lock.lock(); - try { + try { final GLDrawable _drawable = drawable; if( null == _drawable || realized == _drawable.isRealized() || realized && ( 0 >= _drawable.getWidth() || 0 >= _drawable.getHeight() ) ) { @@ -448,10 +448,10 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } finally { _lock.unlock(); } - } + } private final Runnable realizeOnEDTAction = new Runnable() { public void run() { setRealizedImpl(true); } }; private final Runnable unrealizeOnEDTAction = new Runnable() { public void run() { setRealizedImpl(false); } }; - + @Override public final void setRealized(boolean realized) { // Make sure drawable realization happens on AWT-EDT and only there. Consider the AWTTree lock! @@ -503,7 +503,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing public void destroy() { destroyImpl( false ); } - + protected void destroyImpl(boolean destroyJAWTWindowAndAWTDevice) { Threading.invoke(true, destroyOnEDTAction, getTreeLock()); if( destroyJAWTWindowAndAWTDevice ) { @@ -553,14 +553,14 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing public void addNotify() { final RecursiveLock _lock = lock; _lock.lock(); - try { + try { final boolean isBeansDesignTime = Beans.isDesignTime(); - + if(DEBUG) { System.err.println(getThreadName()+": Info: addNotify - start, bounds: "+this.getBounds()+", isBeansDesignTime "+isBeansDesignTime); // Thread.dumpStack(); } - + if( isBeansDesignTime ) { super.addNotify(); } else { @@ -576,21 +576,21 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing if(null==awtConfig) { throw new GLException("Error: NULL AWTGraphicsConfiguration"); } - + // before native peer is valid: X11 disableBackgroundErase(); - + // issues getGraphicsConfiguration() and creates the native peer super.addNotify(); - + // after native peer is valid: Windows disableBackgroundErase(); - + createDrawableAndContext( true ); - + // init drawable by paint/display makes the init sequence more equal // for all launch flavors (applet/javaws/..) - // validateGLDrawable(); + // validateGLDrawable(); } awtWindowClosingProtocol.addClosingListener(); @@ -606,7 +606,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing if ( !Beans.isDesignTime() ) { if( createJAWTWindow ) { jawtWindow = (JAWTWindow) NativeWindowFactory.getNativeWindow(this, awtConfig); - jawtWindow.setShallUseOffscreenLayer(shallUseOffscreenLayer); + jawtWindow.setShallUseOffscreenLayer(shallUseOffscreenLayer); } jawtWindow.lockSurface(); try { @@ -617,7 +617,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing jawtWindow.unlockSurface(); } } - } + } private boolean validateGLDrawable() { if( Beans.isDesignTime() || !isDisplayable() ) { @@ -641,7 +641,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } return false; } - + /**

          Overridden to track when this component is removed from a container. Subclasses which override this method must call super.removeNotify() in their removeNotify() method in order to @@ -686,13 +686,13 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing public void reshape(int x, int y, int width, int height) { synchronized (getTreeLock()) { // super.reshape(..) claims tree lock, so we do extend it's lock over reshape super.reshape(x, y, width, height); - + if(DEBUG) { final NativeSurface ns = getNativeSurface(); final long nsH = null != ns ? ns.getSurfaceHandle() : 0; System.err.println("GLCanvas.sizeChanged: ("+getThreadName()+"): "+width+"x"+height+" - surfaceHandle 0x"+Long.toHexString(nsH)); // Thread.dumpStack(); - } + } if( validateGLDrawable() && !printActive ) { final GLDrawableImpl _drawable = drawable; if( ! _drawable.getChosenGLCapabilities().isOnscreen() ) { @@ -701,7 +701,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing try { final GLDrawableImpl _drawableNew = GLDrawableHelper.resizeOffscreenDrawable(_drawable, context, width, height); if(_drawable != _drawableNew) { - // write back + // write back drawable = _drawableNew; } } finally { @@ -723,13 +723,13 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } private volatile boolean printActive = false; - private GLAnimatorControl printAnimator = null; + private GLAnimatorControl printAnimator = null; private GLAutoDrawable printGLAD = null; private AWTTilePainter printAWTTiles = null; - + @Override public void setupPrint(double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight) { - printActive = true; + printActive = true; final int componentCount = isOpaque() ? 3 : 4; final TileRenderer printRenderer = new TileRenderer(); printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, numSamples, tileWidth, tileHeight, DEBUG); @@ -742,14 +742,14 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing if(DEBUG) { System.err.println(getThreadName()+": Info: GLCanvas setupPrint - skipped GL render, drawable not valid yet"); } - printActive = false; + printActive = false; return; // not yet available .. } if( !isVisible() ) { if(DEBUG) { System.err.println(getThreadName()+": Info: GLCanvas setupPrint - skipped GL render, drawable visible"); } - printActive = false; + printActive = false; return; // not yet available .. } sendReshape = false; // clear reshape flag @@ -757,7 +757,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing if( null != printAnimator ) { printAnimator.remove(GLCanvas.this); } - printGLAD = GLCanvas.this; // _not_ default, shall be replaced by offscreen GLAD + printGLAD = GLCanvas.this; // _not_ default, shall be replaced by offscreen GLAD final GLCapabilities caps = (GLCapabilities)getChosenGLCapabilities().cloneMutable(); final int printNumSamples = printAWTTiles.getNumSamples(caps); GLDrawable printDrawable = printGLAD.getDelegatedDrawable(); @@ -783,8 +783,8 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing caps.setNumSamples(printNumSamples); } final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); - printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, - printAWTTiles.customTileWidth != -1 ? printAWTTiles.customTileWidth : DEFAULT_PRINT_TILE_SIZE, + printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, + printAWTTiles.customTileWidth != -1 ? printAWTTiles.customTileWidth : DEFAULT_PRINT_TILE_SIZE, printAWTTiles.customTileHeight != -1 ? printAWTTiles.customTileHeight : DEFAULT_PRINT_TILE_SIZE, null); GLDrawableUtil.swapGLContextAndAllGLEventListener(GLCanvas.this, printGLAD); @@ -801,7 +801,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } } }; - + @Override public void releasePrint() { if( !printActive || null == printGLAD ) { @@ -832,7 +832,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing display(); } }; - + @Override public void print(Graphics graphics) { if( !printActive || null == printGLAD ) { @@ -843,7 +843,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing // we cannot dispatch print on AWT-EDT due to printing internal locking .. } sendReshape = false; // clear reshape flag - + final Graphics2D g2d = (Graphics2D)graphics; try { printAWTTiles.setupGraphics2DAndClipBounds(g2d, getWidth(), getHeight()); @@ -876,7 +876,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing System.err.println("AWT print.X: "+printAWTTiles); } } - + @Override public void addGLEventListener(GLEventListener listener) { helper.addGLEventListener(listener); @@ -906,14 +906,14 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing public void setGLEventListenerInitState(GLEventListener listener, boolean initialized) { helper.setGLEventListenerInitState(listener, initialized); } - + @Override public GLEventListener disposeGLEventListener(GLEventListener listener, boolean remove) { final DisposeGLEventListenerAction r = new DisposeGLEventListenerAction(listener, remove); Threading.invoke(true, r, getTreeLock()); return r.listener; } - + @Override public GLEventListener removeGLEventListener(GLEventListener listener) { return helper.removeGLEventListener(listener); @@ -948,7 +948,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing public boolean invoke(final boolean wait, final List glRunnables) { return helper.invoke(this, wait, glRunnables); } - + @Override public GLContext setContext(GLContext newCtx, boolean destroyPrevCtx) { final RecursiveLock _lock = lock; @@ -967,7 +967,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing public final GLDrawable getDelegatedDrawable() { return drawable; } - + @Override public GLContext getContext() { return context; @@ -1049,7 +1049,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing final GLDrawable _drawable = drawable; return null != _drawable ? _drawable.isGLOriented() : true; } - + @Override public NativeSurface getNativeSurface() { final GLDrawable _drawable = drawable; @@ -1093,7 +1093,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing public void run() { final RecursiveLock _lock = lock; _lock.lock(); - try { + try { final GLAnimatorControl animator = getAnimator(); if(DEBUG) { @@ -1101,7 +1101,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing (null!=context) + ", hasDrawable " + (null!=drawable)+", "+animator); // Thread.dumpStack(); } - + final boolean animatorPaused; if(null!=animator) { // can't remove us from animator for recreational addNotify() @@ -1109,7 +1109,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } else { animatorPaused = false; } - + // OLS will be detached by disposeGL's context destruction below if( null != context ) { if( context.isCreated() ) { @@ -1137,11 +1137,11 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing if(animatorPaused) { animator.resume(); } - + if(DEBUG) { System.err.println(getThreadName()+": dispose() - END, animator "+animator); } - + } finally { _lock.unlock(); } @@ -1170,7 +1170,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } jawtWindow=null; } - + if(null != awtConfig) { final AbstractGraphicsConfiguration aconfig = awtConfig.getNativeGraphicsConfiguration(); final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); @@ -1188,7 +1188,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing awtConfig=null; } }; - + private final Runnable initAction = new Runnable() { @Override public void run() { @@ -1250,7 +1250,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing this.listener = listener; this.remove = remove; } - + @Override public void run() { final RecursiveLock _lock = lock; @@ -1262,7 +1262,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } } }; - + // Disables the AWT's erasing of this Canvas's background on Windows // in Java SE 6. This internal API is not available in previous // releases, but the system property diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java index 1ec0ad7bc..84db62515 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java @@ -129,7 +129,7 @@ import com.jogamp.opengl.util.texture.TextureState;

          In case the above mentioned GLSL vertical-flipping is not performed, - {@link System#arraycopy(Object, int, Object, int, int) System.arraycopy(..)} is used line by line. + {@link System#arraycopy(Object, int, Object, int, int) System.arraycopy(..)} is used line by line. This step causes more CPU load per frame and is not hardware-accelerated.

          @@ -139,8 +139,8 @@ import com.jogamp.opengl.util.texture.TextureState;

          * Please read Java2D OpenGL Remarks. *

          - * -
          FBO / GLSL Vertical Flip
          + * +
          FBO / GLSL Vertical Flip
          The FBO / GLSL code path uses one texture-unit and binds the FBO texture to it's active texture-target, see {@link #setTextureUnit(int)} and {@link #getTextureUnit()}.

          @@ -154,7 +154,7 @@ import com.jogamp.opengl.util.texture.TextureState; Warning (Bug 842): Certain GL states other than viewport and texture (see above) influencing rendering, will also influence the GLSL vertical flip, e.g. {@link GL#glFrontFace(int) glFrontFace}({@link GL#GL_CCW}). It is recommended to reset those states to default when leaving the {@link GLEventListener#display(GLAutoDrawable)} method! - We may change this behavior in the future, i.e. preserve all influencing states. + We may change this behavior in the future, i.e. preserve all influencing states.

          */ @@ -162,23 +162,23 @@ import com.jogamp.opengl.util.texture.TextureState; public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosingProtocol, AWTPrintLifecycle { private static final boolean DEBUG; private static final boolean DEBUG_VIEWPORT; - private static final boolean USE_GLSL_TEXTURE_RASTERIZER; + private static final boolean USE_GLSL_TEXTURE_RASTERIZER; /** Indicates whether the Java 2D OpenGL pipeline is requested by user. */ private static final boolean java2dOGLEnabledByProp; - + /** Indicates whether the Java 2D OpenGL pipeline is enabled, resource-compatible and requested by user. */ private static final boolean useJava2DGLPipeline; - + /** Indicates whether the Java 2D OpenGL pipeline's usage is error free. */ private static boolean java2DGLPipelineOK; - + static { Debug.initSingleton(); DEBUG = Debug.debug("GLJPanel"); DEBUG_VIEWPORT = Debug.isPropertyDefined("jogl.debug.GLJPanel.Viewport", true); USE_GLSL_TEXTURE_RASTERIZER = !Debug.isPropertyDefined("jogl.gljpanel.noglsl", true); - + boolean enabled = Debug.getBooleanProperty("sun.java2d.opengl", false); java2dOGLEnabledByProp = enabled && !Debug.isPropertyDefined("jogl.gljpanel.noogl", true); @@ -201,7 +201,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing System.err.println("GLJPanel: java2DGLPipelineOK "+java2DGLPipelineOK); } } - + private static SingleAWTGLPixelBufferProvider singleAWTGLPixelBufferProvider = null; private static synchronized SingleAWTGLPixelBufferProvider getSingleAWTGLPixelBufferProvider() { if( null == singleAWTGLPixelBufferProvider ) { @@ -209,7 +209,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } return singleAWTGLPixelBufferProvider; } - + private GLDrawableHelper helper = new GLDrawableHelper(); private volatile boolean isInitialized; @@ -236,14 +236,14 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing // Width of the actual GLJPanel: reshapeWidth -> panelWidth -> backend.width private int panelWidth = 0; private int panelHeight = 0; - + // These are always set to (0, 0) except when the Java2D / OpenGL // pipeline is active private int viewportX; private int viewportY; private int requestedTextureUnit = 0; // default - + // The backend in use private volatile Backend backend; @@ -316,7 +316,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing this.factory = GLDrawableFactoryImpl.getFactoryImpl(glProfile); this.chooser = ((chooser != null) ? chooser : new DefaultGLCapabilitiesChooser()); this.shareWith = shareWith; - + this.setFocusable(true); // allow keyboard input! } @@ -336,12 +336,12 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } customPixelBufferProvider = custom; } - + @Override public final Object getUpstreamWidget() { return this; } - + @Override public void display() { if( isVisible() ) { @@ -446,7 +446,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing handleReshape = false; sendReshape = handleReshape(); } - + if( isVisible() ) { updater.setGraphics(g); backend.doPaintComponent(g); @@ -489,7 +489,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing which override this method must call super.reshape() in their reshape() method in order to function properly.

          * - * {@inheritDoc} + * {@inheritDoc} */ @SuppressWarnings("deprecation") @Override @@ -500,7 +500,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing System.err.println(getThreadName()+": GLJPanel.reshape resize"+(printActive?"WithinPrint":"")+" [ panel "+ panelWidth+"x"+panelHeight + ", reshape: " +reshapeWidth+"x"+reshapeHeight + - "] -> "+(printActive?"skipped":"") + width+"x"+height); + "] -> "+(printActive?"skipped":"") + width+"x"+height); } if( !printActive ) { reshapeWidth = width; @@ -510,13 +510,13 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } private volatile boolean printActive = false; - private GLAnimatorControl printAnimator = null; + private GLAnimatorControl printAnimator = null; private GLAutoDrawable printGLAD = null; private AWTTilePainter printAWTTiles = null; - + @Override public void setupPrint(double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight) { - printActive = true; + printActive = true; final int componentCount = isOpaque() ? 3 : 4; final TileRenderer printRenderer = new TileRenderer(); printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, numSamples, tileWidth, tileHeight, DEBUG); @@ -532,14 +532,14 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing if(DEBUG) { System.err.println(getThreadName()+": Info: GLJPanel setupPrint - skipped GL render, drawable not valid yet"); } - printActive = false; + printActive = false; return; // not yet available .. } if( !isVisible() ) { if(DEBUG) { System.err.println(getThreadName()+": Info: GLJPanel setupPrint - skipped GL render, drawable visible"); } - printActive = false; + printActive = false; return; // not yet available .. } sendReshape = false; // clear reshape flag @@ -548,8 +548,8 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing if( null != printAnimator ) { printAnimator.remove(GLJPanel.this); } - - printGLAD = GLJPanel.this; // default: re-use + + printGLAD = GLJPanel.this; // default: re-use final GLCapabilities caps = (GLCapabilities)getChosenGLCapabilities().cloneMutable(); final int printNumSamples = printAWTTiles.getNumSamples(caps); GLDrawable printDrawable = printGLAD.getDelegatedDrawable(); @@ -570,8 +570,8 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing caps.setSampleBuffers(0 < printNumSamples); caps.setNumSamples(printNumSamples); final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); - printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, - printAWTTiles.customTileWidth != -1 ? printAWTTiles.customTileWidth : DEFAULT_PRINT_TILE_SIZE, + printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, + printAWTTiles.customTileWidth != -1 ? printAWTTiles.customTileWidth : DEFAULT_PRINT_TILE_SIZE, printAWTTiles.customTileHeight != -1 ? printAWTTiles.customTileHeight : DEFAULT_PRINT_TILE_SIZE, null); GLDrawableUtil.swapGLContextAndAllGLEventListener(GLJPanel.this, printGLAD); @@ -588,7 +588,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } } }; - + @Override public void releasePrint() { if( !printActive ) { @@ -598,7 +598,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing handleReshape = false; // ditto AWTEDTExecutor.singleton.invoke(getTreeLock(), true /* allowOnNonEDT */, true /* wait */, releasePrintOnEDT); } - + private final Runnable releasePrintOnEDT = new Runnable() { @Override public void run() { @@ -616,7 +616,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing printAnimator.add(GLJPanel.this); printAnimator = null; } - + // trigger reshape, i.e. gl-viewport and -listener - this component might got resized! final int awtWidth = GLJPanel.this.getWidth(); final int awtHeight= GLJPanel.this.getHeight(); @@ -639,7 +639,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing display(); } }; - + @Override public void print(Graphics graphics) { if( !printActive ) { @@ -651,7 +651,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } sendReshape = false; // clear reshape flag handleReshape = false; // ditto - + final Graphics2D g2d = (Graphics2D)graphics; try { printAWTTiles.setupGraphics2DAndClipBounds(g2d, getWidth(), getHeight()); @@ -691,7 +691,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } print(g); } - + @Override public void setOpaque(boolean opaque) { if (backend != null) { @@ -729,7 +729,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing public void setGLEventListenerInitState(GLEventListener listener, boolean initialized) { helper.setGLEventListenerInitState(listener, initialized); } - + @Override public GLEventListener disposeGLEventListener(GLEventListener listener, boolean remove) { final DisposeGLEventListenerAction r = new DisposeGLEventListenerAction(listener, remove); @@ -746,7 +746,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } return r.listener; } - + @Override public GLEventListener removeGLEventListener(GLEventListener listener) { return helper.removeGLEventListener(listener); @@ -781,7 +781,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing public boolean invoke(final boolean wait, final List glRunnables) { return helper.invoke(this, wait, glRunnables); } - + @Override public GLContext createContext(GLContext shareWith) { final Backend b = backend; @@ -821,7 +821,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } return b.getDrawable(); } - + @Override public GLContext getContext() { final Backend b = backend; @@ -918,7 +918,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } return b.getDrawable().isGLOriented(); } - + @Override public GLCapabilitiesImmutable getChosenGLCapabilities() { final Backend b = backend; @@ -956,11 +956,11 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing return factory; } - /** + /** * Returns the used texture unit, i.e. a value of [0..n], or -1 if non used. *

          * If implementation uses a texture-unit, it will be known only after the first initialization, i.e. display call. - *

          + *

          *

          * See FBO / GLSL Vertical Flip. *

          @@ -970,9 +970,9 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing if ( null == b ) { return -1; } - return b.getTextureUnit(); + return b.getTextureUnit(); } - + /** * Allows user to request a texture unit to be used, * must be called before the first initialization, i.e. {@link #display()} call. @@ -982,14 +982,14 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing *

          * See FBO / GLSL Vertical Flip. *

          - * + * * @param v requested texture unit * @see #getTextureUnit() */ public final void setTextureUnit(int v) { requestedTextureUnit = v; } - + //---------------------------------------------------------------------- // Internals only below this point // @@ -1004,7 +1004,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing if (DEBUG) { System.err.println(getThreadName()+": GLJPanel.createAndInitializeBackend: " +panelWidth+"x"+panelHeight + " -> " + reshapeWidth+"x"+reshapeHeight); - } + } // Pull down reshapeWidth and reshapeHeight into panelWidth and // panelHeight eagerly in order to complete initialization, and // force a reshape later @@ -1039,7 +1039,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing private boolean handleReshape() { if (DEBUG) { System.err.println(getThreadName()+": GLJPanel.handleReshape: " +panelWidth+"x"+panelHeight + " -> " + reshapeWidth+"x"+reshapeHeight); - } + } panelWidth = reshapeWidth; panelHeight = reshapeHeight; @@ -1089,7 +1089,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing public void plainPaint(GLAutoDrawable drawable) { helper.display(GLJPanel.this); } - + @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { // This is handled above and dispatched directly to the appropriate context @@ -1148,7 +1148,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing updater.plainPaint(GLJPanel.this); } }; - + private final Runnable paintImmediatelyAction = new Runnable() { @Override public void run() { @@ -1172,7 +1172,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } } }; - + private int getGLInteger(GL gl, int which) { int[] tmp = new int[1]; gl.glGetIntegerv(which, tmp, 0); @@ -1203,7 +1203,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing /** Called when the opacity of the GLJPanel is changed */ public void setOpaque(boolean opaque); - /** + /** * Called to manually create an additional OpenGL context against * this GLJPanel */ @@ -1220,7 +1220,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing /** Returns the used texture unit, i.e. a value of [0..n], or -1 if non used. */ public int getTextureUnit(); - + /** Called to fetch the "real" GLCapabilities for the backend */ public GLCapabilitiesImmutable getChosenGLCapabilities(); @@ -1240,7 +1240,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing */ public boolean preGL(Graphics g); - /** + /** * Called after the OpenGL work is done in init() and display(). * The isDisplay argument indicates whether this was called on * behalf of a call to display() rather than init(). @@ -1262,7 +1262,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing private final boolean useSingletonBuffer; private AWTGLPixelBuffer pixelBuffer; private BufferedImage alignedImage; - + // One of these is used to store the read back pixels before storing // in the BufferedImage protected IntBuffer readBackIntsForCPUVFlip; @@ -1272,10 +1272,10 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing private boolean offscreenIsFBO; private FBObject fboFlipped; private GLSLTextureRaster glslTextureRaster; - + private GLContextImpl offscreenContext; - private boolean flipVertical; - + private boolean flipVertical; + // For saving/restoring of OpenGL state during ReadPixels private final GLPixelStorageModes psm = new GLPixelStorageModes(); @@ -1291,7 +1291,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing useSingletonBuffer = false; } } - + @Override public boolean isUsingOwnLifecycle() { return false; } @@ -1351,11 +1351,11 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } else { fboFlipped = null; glslTextureRaster = null; - } + } offscreenContext.release(); } else { isInitialized = false; - } + } } finally { if( !isInitialized ) { if(null != offscreenContext) { @@ -1376,7 +1376,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing System.err.println(getThreadName()+": OffscreenBackend: destroy() - offscreenContext: "+(null!=offscreenContext)+" - offscreenDrawable: "+(null!=offscreenDrawable)); } if ( null != offscreenContext && offscreenContext.isCreated() ) { - if( GLContext.CONTEXT_NOT_CURRENT < offscreenContext.makeCurrent() ) { + if( GLContext.CONTEXT_NOT_CURRENT < offscreenContext.makeCurrent() ) { try { final GL gl = offscreenContext.getGL(); if(null != glslTextureRaster) { @@ -1394,7 +1394,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing glslTextureRaster = null; fboFlipped = null; offscreenContext = null; - + if (offscreenDrawable != null) { final AbstractGraphicsDevice adevice = offscreenDrawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice(); offscreenDrawable.setRealized(false); @@ -1404,8 +1404,8 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } } offscreenIsFBO = false; - - if( null != readBackIntsForCPUVFlip ) { + + if( null != readBackIntsForCPUVFlip ) { readBackIntsForCPUVFlip.clear(); readBackIntsForCPUVFlip = null; } @@ -1449,10 +1449,10 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing componentCount = 4; alignment = 4; } - - final GLPixelAttributes pixelAttribs = pixelBufferProvider.getAttributes(gl, componentCount); - - if( useSingletonBuffer ) { // attempt to fetch the latest AWTGLPixelBuffer + + final GLPixelAttributes pixelAttribs = pixelBufferProvider.getAttributes(gl, componentCount); + + if( useSingletonBuffer ) { // attempt to fetch the latest AWTGLPixelBuffer pixelBuffer = (AWTGLPixelBuffer) ((SingletonGLPixelBufferProvider)pixelBufferProvider).getSingleBuffer(pixelAttribs); } if( null != pixelBuffer && pixelBuffer.requiresNewBuffer(gl, panelWidth, panelHeight, 0) ) { @@ -1463,7 +1463,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing if ( null == pixelBuffer ) { if (0 >= panelWidth || 0 >= panelHeight ) { return; - } + } pixelBuffer = pixelBufferProvider.allocate(gl, pixelAttribs, panelWidth, panelHeight, 1, true, 0); if(DEBUG) { System.err.println(getThreadName()+": GLJPanel.OffscreenBackend.postGL.0: pixelBufferProvider isSingletonBufferProvider "+useSingletonBuffer+", 0x"+Integer.toHexString(pixelBufferProvider.hashCode())+", "+pixelBufferProvider.getClass().getSimpleName()); @@ -1482,7 +1482,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } } final IntBuffer readBackInts; - + if( !flipVertical || null != glslTextureRaster ) { readBackInts = (IntBuffer) pixelBuffer.buffer; } else { @@ -1494,7 +1494,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing final TextureState usrTexState, fboTexState; final int fboTexUnit = GL.GL_TEXTURE0 + ( offscreenIsFBO ? ((GLFBODrawable)offscreenDrawable).getTextureUnit() : 0 ); - + if( offscreenIsFBO ) { usrTexState = new TextureState(gl, GL.GL_TEXTURE_2D); if( fboTexUnit != usrTexState.getUnit() ) { @@ -1510,9 +1510,9 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing usrTexState = null; fboTexState = null; } - + // Must now copy pixels from offscreen context into surface - + // Save current modes psm.setAlignment(gl, alignment, alignment); if(gl.isGL2ES3()) { @@ -1520,14 +1520,14 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing gl2es3.glPixelStorei(GL2ES3.GL_PACK_ROW_LENGTH, panelWidth); gl2es3.glReadBuffer(gl2es3.getDefaultReadBuffer()); } - + offscreenDrawable.swapBuffers(); - + if(null != glslTextureRaster) { // implies flippedVertical final boolean viewportChange; final int[] usrViewport = new int[] { 0, 0, 0, 0 }; gl.glGetIntegerv(GL.GL_VIEWPORT, usrViewport, 0); - viewportChange = 0 != usrViewport[0] || 0 != usrViewport[1] || + viewportChange = 0 != usrViewport[0] || 0 != usrViewport[1] || offscreenDrawable.getWidth() != usrViewport[2] || offscreenDrawable.getHeight() != usrViewport[3]; if( DEBUG_VIEWPORT ) { System.err.println(getThreadName()+": GLJPanel.OffscreenBackend.postGL: Viewport: change "+viewportChange+ @@ -1536,21 +1536,21 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } if( viewportChange ) { gl.glViewport(0, 0, offscreenDrawable.getWidth(), offscreenDrawable.getHeight()); - } - - // perform vert-flipping via OpenGL/FBO + } + + // perform vert-flipping via OpenGL/FBO final GLFBODrawable fboDrawable = (GLFBODrawable)offscreenDrawable; final FBObject.TextureAttachment fboTex = fboDrawable.getTextureBuffer(GL.GL_FRONT); - + fboFlipped.bind(gl); - + // gl.glActiveTexture(GL.GL_TEXTURE0 + fboDrawable.getTextureUnit()); // implicit by GLFBODrawableImpl: swapBuffers/contextMadeCurent -> swapFBOImpl - gl.glBindTexture(GL.GL_TEXTURE_2D, fboTex.getName()); + gl.glBindTexture(GL.GL_TEXTURE_2D, fboTex.getName()); // gl.glClear(GL.GL_DEPTH_BUFFER_BIT); // fboFlipped runs w/o DEPTH! - + glslTextureRaster.display(gl.getGL2ES2()); gl.glReadPixels(0, 0, panelWidth, panelHeight, pixelAttribs.format, pixelAttribs.type, readBackInts); - + fboFlipped.unbind(gl); if( viewportChange ) { gl.glViewport(usrViewport[0], usrViewport[1], usrViewport[2], usrViewport[3]); @@ -1558,7 +1558,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing fboTexState.restore(gl); } else { gl.glReadPixels(0, 0, panelWidth, panelHeight, pixelAttribs.format, pixelAttribs.type, readBackInts); - + if ( flipVertical ) { // Copy temporary data into raster of BufferedImage for faster // blitting Note that we could avoid this copy in the cases @@ -1586,7 +1586,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing // correctness on all platforms } } - + @Override public int getTextureUnit() { if(null != glslTextureRaster && null != offscreenDrawable) { // implies flippedVertical @@ -1598,16 +1598,16 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing @Override public void doPaintComponent(Graphics g) { helper.invokeGL(offscreenDrawable, offscreenContext, updaterDisplayAction, updaterInitAction); - + if ( null != alignedImage ) { // Draw resulting image in one shot g.drawImage(alignedImage, 0, 0, alignedImage.getWidth(), alignedImage.getHeight(), null); // Null ImageObserver since image data is ready. } } - + @Override public void doPlainPaint() { - helper.invokeGL(offscreenDrawable, offscreenContext, updaterPlainDisplayAction, updaterInitAction); + helper.invokeGL(offscreenDrawable, offscreenContext, updaterPlainDisplayAction, updaterInitAction); } @Override @@ -1616,7 +1616,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing { final GLDrawableImpl _drawableNew = GLDrawableHelper.resizeOffscreenDrawable(_drawable, offscreenContext, panelWidth, panelHeight); if(_drawable != _drawableNew) { - // write back + // write back _drawable = _drawableNew; offscreenDrawable = _drawableNew; } @@ -1626,9 +1626,9 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } panelWidth = _drawable.getWidth(); panelHeight = _drawable.getHeight(); - + if( null != glslTextureRaster ) { - if( GLContext.CONTEXT_NOT_CURRENT < offscreenContext.makeCurrent() ) { + if( GLContext.CONTEXT_NOT_CURRENT < offscreenContext.makeCurrent() ) { try { final GL gl = offscreenContext.getGL(); fboFlipped.reset(gl, _drawable.getWidth(), _drawable.getHeight(), 0, false); @@ -1640,7 +1640,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing } return _drawable.isRealized(); } - + @Override public GLContext createContext(GLContext shareWith) { return (null != offscreenDrawable) ? offscreenDrawable.createContext(shareWith) : null; @@ -1790,7 +1790,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing @Override public int getTextureUnit() { return -1; } - + @Override public GLCapabilitiesImmutable getChosenGLCapabilities() { // FIXME: should do better than this; is it possible to using only platform-independent code? @@ -2114,9 +2114,9 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing @Override public void doPlainPaint() { - helper.invokeGL(joglDrawable, joglContext, updaterPlainDisplayAction, updaterInitAction); + helper.invokeGL(joglDrawable, joglContext, updaterPlainDisplayAction, updaterInitAction); } - + private void captureJ2DState(GL gl, Graphics g) { gl.glGetIntegerv(GL2.GL_DRAW_BUFFER, drawBuffer, 0); gl.glGetIntegerv(GL2.GL_READ_BUFFER, readBuffer, 0); diff --git a/src/jogl/classes/javax/media/opengl/fixedfunc/GLMatrixFunc.java b/src/jogl/classes/javax/media/opengl/fixedfunc/GLMatrixFunc.java index 9fee0a2e2..b4d788329 100644 --- a/src/jogl/classes/javax/media/opengl/fixedfunc/GLMatrixFunc.java +++ b/src/jogl/classes/javax/media/opengl/fixedfunc/GLMatrixFunc.java @@ -58,18 +58,18 @@ public interface GLMatrixFunc { * which is the same behavior than the native JOGL GL impl */ public void glGetFloatv(int pname, java.nio.FloatBuffer params); - + /** * Copy the named matrix to the given storage at offset. * @param pname {@link #GL_MODELVIEW_MATRIX}, {@link #GL_PROJECTION_MATRIX} or {@link #GL_TEXTURE_MATRIX} * @param params storage * @param params_offset storage offset - */ + */ public void glGetFloatv(int pname, float[] params, int params_offset); - + /** * glGetIntegerv - * @param pname {@link #GL_MATRIX_MODE} to receive the current matrix mode + * @param pname {@link #GL_MATRIX_MODE} to receive the current matrix mode * @param params the FloatBuffer's position remains unchanged * which is the same behavior than the native JOGL GL impl */ @@ -89,7 +89,7 @@ public interface GLMatrixFunc { *

          */ public void glPushMatrix(); - + /** * Pop the current matrix from it's stack. * @see #glPushMatrix() @@ -97,19 +97,19 @@ public interface GLMatrixFunc { public void glPopMatrix(); /** - * Load the current matrix with the identity matrix + * Load the current matrix with the identity matrix */ public void glLoadIdentity() ; /** - * Load the current matrix w/ the provided one. + * Load the current matrix w/ the provided one. * @param params the FloatBuffer's position remains unchanged, * which is the same behavior than the native JOGL GL impl */ - public void glLoadMatrixf(java.nio.FloatBuffer m) ; + public void glLoadMatrixf(java.nio.FloatBuffer m) ; /** * Load the current matrix w/ the provided one. - */ + */ public void glLoadMatrixf(float[] m, int m_offset); /** diff --git a/src/jogl/classes/javax/media/opengl/fixedfunc/GLPointerFunc.java b/src/jogl/classes/javax/media/opengl/fixedfunc/GLPointerFunc.java index 786835f4d..4aff24b36 100644 --- a/src/jogl/classes/javax/media/opengl/fixedfunc/GLPointerFunc.java +++ b/src/jogl/classes/javax/media/opengl/fixedfunc/GLPointerFunc.java @@ -31,7 +31,7 @@ package javax.media.opengl.fixedfunc; import javax.media.opengl.*; -public interface GLPointerFunc { +public interface GLPointerFunc { public static final int GL_VERTEX_ARRAY = 0x8074; public static final int GL_NORMAL_ARRAY = 0x8075; public static final int GL_COLOR_ARRAY = 0x8076; diff --git a/src/jogl/classes/javax/media/opengl/fixedfunc/GLPointerFuncUtil.java b/src/jogl/classes/javax/media/opengl/fixedfunc/GLPointerFuncUtil.java index 79ec38e0c..9bd644223 100644 --- a/src/jogl/classes/javax/media/opengl/fixedfunc/GLPointerFuncUtil.java +++ b/src/jogl/classes/javax/media/opengl/fixedfunc/GLPointerFuncUtil.java @@ -28,7 +28,7 @@ package javax.media.opengl.fixedfunc; -public class GLPointerFuncUtil { +public class GLPointerFuncUtil { public static final String mgl_Vertex = "mgl_Vertex"; public static final String mgl_Normal = "mgl_Normal"; public static final String mgl_Color = "mgl_Color"; @@ -37,16 +37,16 @@ public class GLPointerFuncUtil { /** * @param glArrayIndex the fixed function array index - * @return default fixed function array name + * @return default fixed function array name */ public static String getPredefinedArrayIndexName(int glArrayIndex) { return getPredefinedArrayIndexName(glArrayIndex, -1); } - + /** * @param glArrayIndex the fixed function array index - * @param multiTexCoordIndex index for multiTexCoordIndex - * @return default fixed function array name + * @param multiTexCoordIndex index for multiTexCoordIndex + * @return default fixed function array name */ public static String getPredefinedArrayIndexName(int glArrayIndex, int multiTexCoordIndex) { switch(glArrayIndex) { diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/RegionFactory.java b/src/jogl/classes/jogamp/graph/curve/opengl/RegionFactory.java index 1f59b5805..515583b14 100644 --- a/src/jogl/classes/jogamp/graph/curve/opengl/RegionFactory.java +++ b/src/jogl/classes/jogamp/graph/curve/opengl/RegionFactory.java @@ -30,20 +30,20 @@ package jogamp.graph.curve.opengl; import com.jogamp.graph.curve.Region; import com.jogamp.graph.curve.opengl.GLRegion; -/** RegionFactory to create a Context specific Region implementation. - * +/** RegionFactory to create a Context specific Region implementation. + * * @see GLRegion */ public class RegionFactory { - + /** * Create a Region using the passed render mode - * + * *

          In case {@link Region#VBAA_RENDERING_BIT} is being requested the default texture unit * {@link Region#TWO_PASS_DEFAULT_TEXTURE_UNIT} is being used.

          - * + * * @param rs the RenderState to be used - * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, {@link Region#VBAA_RENDERING_BIT} + * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, {@link Region#VBAA_RENDERING_BIT} */ public static GLRegion create(int renderModes) { if( 0 != ( Region.VBAA_RENDERING_BIT & renderModes ) ){ @@ -53,18 +53,18 @@ public class RegionFactory { return new VBORegionSPES2(renderModes); } } - + /** Create a Single Pass Region using the passed render mode - * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, + * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, * {@link Region#VBAA_RENDERING_BIT} * @return */ public static GLRegion createSinglePass(int renderModes) { return new VBORegionSPES2(renderModes); } - + /** Create a Two Pass (VBAA) Region using the passed render mode - * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, + * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, * {@link Region#VBAA_RENDERING_BIT} * @return */ diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java b/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java index 7f5afcd02..22600cb89 100644 --- a/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java +++ b/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java @@ -43,12 +43,12 @@ import com.jogamp.opengl.util.glsl.ShaderState; public class RegionRendererImpl01 extends RegionRenderer { public RegionRendererImpl01(RenderState rs, int renderModes) { super(rs, renderModes); - + } - + protected boolean initShaderProgram(GL2ES2 gl) { final ShaderState st = rs.getShaderState(); - + final ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RegionRendererImpl01.class, "shader", "shader/bin", getVertexShaderName(), true); final ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RegionRendererImpl01.class, "shader", @@ -57,29 +57,29 @@ public class RegionRendererImpl01 extends RegionRenderer { // rsFp.defaultShaderCustomization(gl, true, true); int pos = rsFp.addGLSLVersion(gl); if( gl.isGLES2() ) { - pos = rsFp.insertShaderSource(0, pos, ShaderCode.extOESDerivativesEnable); + pos = rsFp.insertShaderSource(0, pos, ShaderCode.extOESDerivativesEnable); } final String rsFpDefPrecision = getFragmentShaderPrecision(gl); if( null != rsFpDefPrecision ) { rsFp.insertShaderSource(0, pos, rsFpDefPrecision); } - + final ShaderProgram sp = new ShaderProgram(); sp.add(rsVp); sp.add(rsFp); - if( !sp.init(gl) ) { + if( !sp.init(gl) ) { throw new GLException("RegionRenderer: Couldn't init program: "+sp); } - st.attachShaderProgram(gl, sp, false); + st.attachShaderProgram(gl, sp, false); st.bindAttribLocation(gl, AttributeNames.VERTEX_ATTR_IDX, AttributeNames.VERTEX_ATTR_NAME); - st.bindAttribLocation(gl, AttributeNames.TEXCOORD_ATTR_IDX, AttributeNames.TEXCOORD_ATTR_NAME); - + st.bindAttribLocation(gl, AttributeNames.TEXCOORD_ATTR_IDX, AttributeNames.TEXCOORD_ATTR_NAME); + if(!sp.link(gl, System.err)) { throw new GLException("RegionRenderer: Couldn't link program: "+sp); - } + } st.useProgram(gl, true); - + if(DEBUG) { System.err.println("RegionRendererImpl01 initialized: " + Thread.currentThread()+" "+st); } @@ -94,5 +94,5 @@ public class RegionRendererImpl01 extends RegionRenderer { @Override protected void drawImpl(GL2ES2 gl, Region region, float[] position, int[] texSize) { ((GLRegion)region).draw(gl, rs, vp_width, vp_height, texSize); - } + } } diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/RenderStateImpl.java b/src/jogl/classes/jogamp/graph/curve/opengl/RenderStateImpl.java index 51356ca13..8ca29b9f0 100644 --- a/src/jogl/classes/jogamp/graph/curve/opengl/RenderStateImpl.java +++ b/src/jogl/classes/jogamp/graph/curve/opengl/RenderStateImpl.java @@ -38,9 +38,9 @@ import com.jogamp.graph.geom.Vertex; import com.jogamp.opengl.util.PMVMatrix; import com.jogamp.opengl.util.glsl.ShaderState; -public class RenderStateImpl extends RenderState { +public class RenderStateImpl extends RenderState { /** - * weight is equivalent to the + * weight is equivalent to the * global off-curve vertex weight. * TODO: change to per vertex */ @@ -50,7 +50,7 @@ public class RenderStateImpl extends RenderState { public RenderStateImpl(ShaderState st, Vertex.Factory pointFactory, PMVMatrix pmvMatrix) { super(st, pointFactory, pmvMatrix); - + gcu_Weight = new GLUniformData(UniformNames.gcu_Weight, 1.0f); st.ownUniform(gcu_PMVMatrix); gcu_Alpha = new GLUniformData(UniformNames.gcu_Alpha, 1.0f); @@ -60,15 +60,15 @@ public class RenderStateImpl extends RenderState { // gcu_Strength = new GLUniformData(UniformNames.gcu_Strength, 3.0f); // st.ownUniform(gcu_Strength); } - + public RenderStateImpl(ShaderState st, Vertex.Factory pointFactory) { this(st, pointFactory, new PMVMatrix()); } - + public final GLUniformData getWeight() { return gcu_Weight; } public final GLUniformData getAlpha() { return gcu_Alpha; } public final GLUniformData getColorStatic() { return gcu_ColorStatic; } //public final GLUniformData getStrength() { return gcu_Strength; } - - + + } diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/TextRendererImpl01.java b/src/jogl/classes/jogamp/graph/curve/opengl/TextRendererImpl01.java index 81c421371..60758b90b 100644 --- a/src/jogl/classes/jogamp/graph/curve/opengl/TextRendererImpl01.java +++ b/src/jogl/classes/jogamp/graph/curve/opengl/TextRendererImpl01.java @@ -40,11 +40,11 @@ import com.jogamp.opengl.util.glsl.ShaderCode; import com.jogamp.opengl.util.glsl.ShaderProgram; import com.jogamp.opengl.util.glsl.ShaderState; -public class TextRendererImpl01 extends TextRenderer { +public class TextRendererImpl01 extends TextRenderer { public TextRendererImpl01(RenderState rs, int type) { - super(rs, type); + super(rs, type); } - + @Override protected boolean initShaderProgram(GL2ES2 gl){ final ShaderState st = rs.getShaderState(); @@ -63,18 +63,18 @@ public class TextRendererImpl01 extends TextRenderer { if( null != rsFpDefPrecision ) { rsFp.insertShaderSource(0, pos, rsFpDefPrecision); } - + final ShaderProgram sp = new ShaderProgram(); sp.add(rsVp); sp.add(rsFp); - - if( !sp.init(gl) ) { + + if( !sp.init(gl) ) { throw new GLException("RegionRenderer: Couldn't init program: "+sp); } - st.attachShaderProgram(gl, sp, false); + st.attachShaderProgram(gl, sp, false); st.bindAttribLocation(gl, AttributeNames.VERTEX_ATTR_IDX, AttributeNames.VERTEX_ATTR_NAME); - st.bindAttribLocation(gl, AttributeNames.TEXCOORD_ATTR_IDX, AttributeNames.TEXCOORD_ATTR_NAME); - + st.bindAttribLocation(gl, AttributeNames.TEXCOORD_ATTR_IDX, AttributeNames.TEXCOORD_ATTR_NAME); + if(!sp.link(gl, System.err)) { throw new GLException("TextRendererImpl01: Couldn't link program: "+sp); } @@ -82,15 +82,15 @@ public class TextRendererImpl01 extends TextRenderer { if(DEBUG) { System.err.println("TextRendererImpl01 initialized: " + Thread.currentThread()+" "+st); - } + } return true; } - + @Override protected void destroyImpl(GL2ES2 gl) { super.destroyImpl(gl); } - + @Override public void drawString3D(GL2ES2 gl, Font font, String str, float[] position, int fontSize, int[/*1*/] texSize) { if(!isInitialized()){ @@ -101,7 +101,7 @@ public class TextRendererImpl01 extends TextRenderer { glyphString = createString(gl, font, fontSize, str); addCachedGlyphString(gl, font, str, fontSize, glyphString); } - + glyphString.renderString3D(gl, rs, vp_width, vp_height, texSize); } } diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java index 85d3ad5a7..86c0db8c6 100644 --- a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java +++ b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java @@ -30,7 +30,7 @@ package jogamp.graph.curve.opengl; import java.nio.FloatBuffer; import javax.media.opengl.GL2ES2; -// FIXME: Subsume GL2GL3.GL_DRAW_FRAMEBUFFER -> GL2ES2.GL_DRAW_FRAMEBUFFER ! +// FIXME: Subsume GL2GL3.GL_DRAW_FRAMEBUFFER -> GL2ES2.GL_DRAW_FRAMEBUFFER ! import javax.media.opengl.GL; import javax.media.opengl.GLUniformData; import javax.media.opengl.fixedfunc.GLMatrixFunc; @@ -58,90 +58,90 @@ public class VBORegion2PES2 extends GLRegion { private GLArrayDataServer verticeFboAttr; private GLArrayDataServer texCoordFboAttr; private GLArrayDataServer indicesFbo; - - + + private FBObject fbo; private TextureAttachment texA; private PMVMatrix fboPMVMatrix; GLUniformData mgl_fboPMVMatrix; - + private int tex_width_c = 0; private int tex_height_c = 0; - GLUniformData mgl_ActiveTexture; + GLUniformData mgl_ActiveTexture; GLUniformData mgl_TextureSize; // if GLSL < 1.30 - + public VBORegion2PES2(int renderModes, int textureEngine) { super(renderModes); fboPMVMatrix = new PMVMatrix(); - mgl_fboPMVMatrix = new GLUniformData(UniformNames.gcu_PMVMatrix, 4, 4, fboPMVMatrix.glGetPMvMatrixf()); - mgl_ActiveTexture = new GLUniformData(UniformNames.gcu_TextureUnit, textureEngine); + mgl_fboPMVMatrix = new GLUniformData(UniformNames.gcu_PMVMatrix, 4, 4, fboPMVMatrix.glGetPMvMatrixf()); + mgl_ActiveTexture = new GLUniformData(UniformNames.gcu_TextureUnit, textureEngine); } - + public void update(GL2ES2 gl, RenderState rs) { if(!isDirty()) { - return; + return; } if(null == indicesFbo) { final int initialElementCount = 256; final ShaderState st = rs.getShaderState(); - - indicesFbo = GLArrayDataServer.createData(3, GL2ES2.GL_SHORT, initialElementCount, GL.GL_STATIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER); + + indicesFbo = GLArrayDataServer.createData(3, GL2ES2.GL_SHORT, initialElementCount, GL.GL_STATIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER); indicesFbo.puts((short) 0); indicesFbo.puts((short) 1); indicesFbo.puts((short) 3); indicesFbo.puts((short) 1); indicesFbo.puts((short) 2); indicesFbo.puts((short) 3); indicesFbo.seal(true); - - texCoordFboAttr = GLArrayDataServer.createGLSL(AttributeNames.TEXCOORD_ATTR_NAME, 2, GL2ES2.GL_FLOAT, + + texCoordFboAttr = GLArrayDataServer.createGLSL(AttributeNames.TEXCOORD_ATTR_NAME, 2, GL2ES2.GL_FLOAT, false, initialElementCount, GL.GL_STATIC_DRAW); st.ownAttribute(texCoordFboAttr, true); - texCoordFboAttr.putf(5); texCoordFboAttr.putf(5); - texCoordFboAttr.putf(5); texCoordFboAttr.putf(6); - texCoordFboAttr.putf(6); texCoordFboAttr.putf(6); - texCoordFboAttr.putf(6); texCoordFboAttr.putf(5); + texCoordFboAttr.putf(5); texCoordFboAttr.putf(5); + texCoordFboAttr.putf(5); texCoordFboAttr.putf(6); + texCoordFboAttr.putf(6); texCoordFboAttr.putf(6); + texCoordFboAttr.putf(6); texCoordFboAttr.putf(5); texCoordFboAttr.seal(true); - - verticeFboAttr = GLArrayDataServer.createGLSL(AttributeNames.VERTEX_ATTR_NAME, 3, GL2ES2.GL_FLOAT, - false, initialElementCount, GL.GL_STATIC_DRAW); + + verticeFboAttr = GLArrayDataServer.createGLSL(AttributeNames.VERTEX_ATTR_NAME, 3, GL2ES2.GL_FLOAT, + false, initialElementCount, GL.GL_STATIC_DRAW); st.ownAttribute(verticeFboAttr, true); - - - indicesTxt = GLArrayDataServer.createData(3, GL2ES2.GL_SHORT, initialElementCount, GL.GL_STATIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER); - - verticeTxtAttr = GLArrayDataServer.createGLSL(AttributeNames.VERTEX_ATTR_NAME, 3, GL2ES2.GL_FLOAT, + + + indicesTxt = GLArrayDataServer.createData(3, GL2ES2.GL_SHORT, initialElementCount, GL.GL_STATIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER); + + verticeTxtAttr = GLArrayDataServer.createGLSL(AttributeNames.VERTEX_ATTR_NAME, 3, GL2ES2.GL_FLOAT, false, initialElementCount, GL.GL_STATIC_DRAW); st.ownAttribute(verticeTxtAttr, true); - - texCoordTxtAttr = GLArrayDataServer.createGLSL(AttributeNames.TEXCOORD_ATTR_NAME, 2, GL2ES2.GL_FLOAT, + + texCoordTxtAttr = GLArrayDataServer.createGLSL(AttributeNames.TEXCOORD_ATTR_NAME, 2, GL2ES2.GL_FLOAT, false, initialElementCount, GL.GL_STATIC_DRAW); st.ownAttribute(texCoordTxtAttr, true); - + if(DEBUG_INSTANCE) { System.err.println("VBORegion2PES2 Create: " + this); - } + } } // process triangles indicesTxt.seal(gl, false); - indicesTxt.rewind(); + indicesTxt.rewind(); for(int i=0; i maxTexSize[0]) { texWidth[0] = maxTexSize[0]; // clip to max - write-back user value! } - renderRegion2FBO(gl, rs, texWidth); + renderRegion2FBO(gl, rs, texWidth); } // System.out.println("Scale: " + matrix.glGetMatrixf().get(1+4*3) +" " + matrix.glGetMatrixf().get(2+4*3)); renderFBO(gl, rs, vp_width, vp_height); } } - + private void renderFBO(GL2ES2 gl, RenderState rs, int width, int hight) { final ShaderState st = rs.getShaderState(); - - gl.glViewport(0, 0, width, hight); - st.uniform(gl, mgl_ActiveTexture); + + gl.glViewport(0, 0, width, hight); + st.uniform(gl, mgl_ActiveTexture); gl.glActiveTexture(GL.GL_TEXTURE0 + mgl_ActiveTexture.intValue()); - fbo.use(gl, texA); - verticeFboAttr.enableBuffer(gl, true); - texCoordFboAttr.enableBuffer(gl, true); + fbo.use(gl, texA); + verticeFboAttr.enableBuffer(gl, true); + texCoordFboAttr.enableBuffer(gl, true); indicesFbo.bindBuffer(gl, true); // keeps VBO binding - + gl.glDrawElements(GL2ES2.GL_TRIANGLES, indicesFbo.getElementCount() * indicesFbo.getComponentCount(), GL2ES2.GL_UNSIGNED_SHORT, 0); - - indicesFbo.bindBuffer(gl, false); + + indicesFbo.bindBuffer(gl, false); texCoordFboAttr.enableBuffer(gl, false); - verticeFboAttr.enableBuffer(gl, false); + verticeFboAttr.enableBuffer(gl, false); fbo.unuse(gl); - + // setback: gl.glActiveTexture(currentActiveTextureEngine[0]); } - + private void renderRegion2FBO(GL2ES2 gl, RenderState rs, int[/*1*/] texWidth) { final ShaderState st = rs.getShaderState(); - + if(0>=texWidth[0]) { throw new IllegalArgumentException("texWidth must be greater than 0: "+texWidth[0]); } - + tex_width_c = texWidth[0]; tex_height_c = (int) ( ( ( tex_width_c * box.getHeight() ) / box.getWidth() ) + 0.5f ); - + // System.out.println("FBO Size: "+texWidth[0]+" -> "+tex_width_c+"x"+tex_height_c); // System.out.println("FBO Scale: " + m.glGetMatrixf().get(0) +" " + m.glGetMatrixf().get(5)); - + if(null != fbo && fbo.getWidth() != tex_width_c && fbo.getHeight() != tex_height_c ) { fbo.reset(gl, tex_width_c, tex_height_c); } - - if(null == fbo) { + + if(null == fbo) { fbo = new FBObject(); - fbo.reset(gl, tex_width_c, tex_height_c); + fbo.reset(gl, tex_width_c, tex_height_c); // FIXME: shall not use bilinear, due to own AA ? However, w/o bilinear result is not smooth texA = fbo.attachTexture2D(gl, 0, true, GL2ES2.GL_LINEAR, GL2ES2.GL_LINEAR, GL2ES2.GL_CLAMP_TO_EDGE, GL2ES2.GL_CLAMP_TO_EDGE); // texA = fbo.attachTexture2D(gl, 0, GL2ES2.GL_NEAREST, GL2ES2.GL_NEAREST, GL2ES2.GL_CLAMP_TO_EDGE, GL2ES2.GL_CLAMP_TO_EDGE); @@ -260,18 +260,18 @@ public class VBORegion2PES2 extends GLRegion { } else { fbo.bind(gl); } - + //render texture gl.glViewport(0, 0, tex_width_c, tex_height_c); st.uniform(gl, mgl_fboPMVMatrix); // use orthogonal matrix - + gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glClear(GL2ES2.GL_COLOR_BUFFER_BIT | GL2ES2.GL_DEPTH_BUFFER_BIT); renderRegion(gl); fbo.unbind(gl); - + st.uniform(gl, rs.getPMVMatrix()); // switch back to real PMV matrix - + // if( !gl.isGL3() ) { // GLSL < 1.30 if(null == mgl_TextureSize) { @@ -281,21 +281,21 @@ public class VBORegion2PES2 extends GLRegion { texSize.put(0, (float)fbo.getWidth()); texSize.put(1, (float)fbo.getHeight()); st.uniform(gl, mgl_TextureSize); - //} + //} } - + private void renderRegion(GL2ES2 gl) { - verticeTxtAttr.enableBuffer(gl, true); + verticeTxtAttr.enableBuffer(gl, true); texCoordTxtAttr.enableBuffer(gl, true); indicesTxt.bindBuffer(gl, true); // keeps VBO binding - + gl.glDrawElements(GL2ES2.GL_TRIANGLES, indicesTxt.getElementCount() * indicesTxt.getComponentCount(), GL2ES2.GL_UNSIGNED_SHORT, 0); - - indicesTxt.bindBuffer(gl, false); + + indicesTxt.bindBuffer(gl, false); texCoordTxtAttr.enableBuffer(gl, false); - verticeTxtAttr.enableBuffer(gl, false); + verticeTxtAttr.enableBuffer(gl, false); } - + public void destroy(GL2ES2 gl, RenderState rs) { if(DEBUG_INSTANCE) { System.err.println("VBORegion2PES2 Destroy: " + this); @@ -305,7 +305,7 @@ public class VBORegion2PES2 extends GLRegion { fbo.destroy(gl); fbo = null; texA = null; - } + } if(null != verticeTxtAttr) { st.ownAttribute(verticeTxtAttr, false); verticeTxtAttr.destroy(gl); @@ -335,6 +335,6 @@ public class VBORegion2PES2 extends GLRegion { indicesFbo = null; } triangles.clear(); - vertices.clear(); - } + vertices.clear(); + } } diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java index 0cba444ad..0a867b45c 100644 --- a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java +++ b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java @@ -44,13 +44,13 @@ public class VBORegionSPES2 extends GLRegion { private GLArrayDataServer texCoordAttr = null; private GLArrayDataServer indices = null; - protected VBORegionSPES2(int renderModes) { + protected VBORegionSPES2(int renderModes) { super(renderModes); } protected void update(GL2ES2 gl, RenderState rs) { if(!isDirty()) { - return; + return; } if(null == indices) { @@ -59,11 +59,11 @@ public class VBORegionSPES2 extends GLRegion { indices = GLArrayDataServer.createData(3, GL2ES2.GL_SHORT, initialElementCount, GL.GL_STATIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER); - verticeAttr = GLArrayDataServer.createGLSL(AttributeNames.VERTEX_ATTR_NAME, 3, GL2ES2.GL_FLOAT, - false, initialElementCount, GL.GL_STATIC_DRAW); + verticeAttr = GLArrayDataServer.createGLSL(AttributeNames.VERTEX_ATTR_NAME, 3, GL2ES2.GL_FLOAT, + false, initialElementCount, GL.GL_STATIC_DRAW); st.ownAttribute(verticeAttr, true); - texCoordAttr = GLArrayDataServer.createGLSL(AttributeNames.TEXCOORD_ATTR_NAME, 2, GL2ES2.GL_FLOAT, + texCoordAttr = GLArrayDataServer.createGLSL(AttributeNames.TEXCOORD_ATTR_NAME, 2, GL2ES2.GL_FLOAT, false, initialElementCount, GL.GL_STATIC_DRAW); st.ownAttribute(texCoordAttr, true); @@ -74,7 +74,7 @@ public class VBORegionSPES2 extends GLRegion { // process triangles indices.seal(gl, false); - indices.rewind(); + indices.rewind(); for(int i=0; i loops; private ArrayList vertices; - + private ArrayList triangles; private int maxTriID = 0; - + /** Constructor for a new Delaunay triangulator */ public CDTriangulator2D() { reset(); } - + /** Reset the triangulation to initial state * Clearing cached data */ @@ -71,14 +71,14 @@ public class CDTriangulator2D implements Triangulator{ triangles = new ArrayList(3); loops = new ArrayList(); } - + public void addCurve(Outline polyline) { Loop loop = null; - + if(!loops.isEmpty()) { loop = getContainerLoop(polyline); } - + if(loop == null) { GraphOutline outline = new GraphOutline(polyline); GraphOutline innerPoly = extractBoundaryTriangles(outline, false); @@ -92,8 +92,8 @@ public class CDTriangulator2D implements Triangulator{ loop.addConstraintCurve(innerPoly); } } - - public ArrayList generate() { + + public ArrayList generate() { for(int i=0;i vertices = polyline.getVertices(); for(int i=0; i < loops.size(); i++) { diff --git a/src/jogl/classes/jogamp/graph/curve/tess/GraphOutline.java b/src/jogl/classes/jogamp/graph/curve/tess/GraphOutline.java index c8251af15..2e8d4f58f 100644 --- a/src/jogl/classes/jogamp/graph/curve/tess/GraphOutline.java +++ b/src/jogl/classes/jogamp/graph/curve/tess/GraphOutline.java @@ -35,13 +35,13 @@ import com.jogamp.graph.geom.Vertex; public class GraphOutline { final private Outline outline; final private ArrayList controlpoints = new ArrayList(3); - + public GraphOutline(){ this.outline = new Outline(); } - + /**Create a control polyline of control vertices - * the curve pieces can be identified by onCurve flag + * the curve pieces can be identified by onCurve flag * of each cp the control polyline is open by default */ public GraphOutline(Outline ol){ @@ -59,7 +59,7 @@ public class GraphOutline { public ArrayList getGraphPoint() { return controlpoints; } - + public ArrayList getVertices() { return outline.getVertices(); } @@ -68,5 +68,5 @@ public class GraphOutline { controlpoints.add(v); outline.addVertex(v.getPoint()); } - + } diff --git a/src/jogl/classes/jogamp/graph/curve/tess/GraphVertex.java b/src/jogl/classes/jogamp/graph/curve/tess/GraphVertex.java index 52d02baa5..1ef1d8c7f 100644 --- a/src/jogl/classes/jogamp/graph/curve/tess/GraphVertex.java +++ b/src/jogl/classes/jogamp/graph/curve/tess/GraphVertex.java @@ -35,7 +35,7 @@ public class GraphVertex { private Vertex point; private ArrayList edges = null; private boolean boundaryContained = false; - + public GraphVertex(Vertex point) { this.point = point; } @@ -43,15 +43,15 @@ public class GraphVertex { public Vertex getPoint() { return point; } - + public float getX(){ return point.getX(); } - + public float getY(){ return point.getY(); } - + public float getZ(){ return point.getZ(); } @@ -70,7 +70,7 @@ public class GraphVertex { public void setEdges(ArrayList edges) { this.edges = edges; } - + public void addEdge(HEdge edge){ if(edges == null){ edges = new ArrayList(); @@ -112,7 +112,7 @@ public class GraphVertex { } return null; } - + public boolean isBoundaryContained() { return boundaryContained; } diff --git a/src/jogl/classes/jogamp/graph/curve/tess/HEdge.java b/src/jogl/classes/jogamp/graph/curve/tess/HEdge.java index 4d29a81f3..acaa3d708 100644 --- a/src/jogl/classes/jogamp/graph/curve/tess/HEdge.java +++ b/src/jogl/classes/jogamp/graph/curve/tess/HEdge.java @@ -35,14 +35,14 @@ public class HEdge { public static int BOUNDARY = 3; public static int INNER = 1; public static int HOLE = 2; - + private GraphVertex vert; private HEdge prev = null; private HEdge next = null; private HEdge sibling = null; private int type = BOUNDARY; private Triangle triangle = null; - + public HEdge(GraphVertex vert, int type) { this.vert = vert; this.type = type; @@ -112,19 +112,19 @@ public class HEdge { public void setTriangle(Triangle triangle) { this.triangle = triangle; } - + public static void connect(HEdge first, HEdge next){ first.setNext(next); next.setPrev(first); } - + public static void makeSiblings(HEdge first, HEdge second){ first.setSibling(second); second.setSibling(first); } - + public boolean vertexOnCurveVertex(){ return vert.getPoint().isOnCurve(); } - + } diff --git a/src/jogl/classes/jogamp/graph/curve/tess/Loop.java b/src/jogl/classes/jogamp/graph/curve/tess/Loop.java index 651179062..c1dafc0d1 100644 --- a/src/jogl/classes/jogamp/graph/curve/tess/Loop.java +++ b/src/jogl/classes/jogamp/graph/curve/tess/Loop.java @@ -51,7 +51,7 @@ public class Loop { public Triangle cut(boolean delaunay){ if(isSimplex()){ - Triangle t = new Triangle(root.getGraphPoint().getPoint(), root.getNext().getGraphPoint().getPoint(), + Triangle t = new Triangle(root.getGraphPoint().getPoint(), root.getNext().getGraphPoint().getPoint(), root.getNext().getNext().getGraphPoint().getPoint()); t.setVerticesBoundary(checkVerticesBoundary(root)); return t; @@ -103,20 +103,20 @@ public class Loop { throw new IllegalArgumentException("outline's vertices < 3: " + vertices.size()); } final VectorUtil.Winding hasWinding = VectorUtil.getWinding( - vertices.get(0).getPoint(), + vertices.get(0).getPoint(), vertices.get(1).getPoint(), vertices.get(2).getPoint()); //FIXME: handle case when vertices come inverted - Rami // skips inversion CW -> CCW final boolean invert = hasWinding != reqWinding && reqWinding == VectorUtil.Winding.CW; - + final int max; final int edgeType = reqWinding == VectorUtil.Winding.CCW ? HEdge.BOUNDARY : HEdge.HOLE ; int index; HEdge firstEdge = null; HEdge lastEdge = null; - + if(!invert) { max = vertices.size(); index = 0; @@ -160,7 +160,7 @@ public class Loop { public void addConstraintCurve(GraphOutline polyline) { // GraphOutline outline = new GraphOutline(polyline); /**needed to generate vertex references.*/ - initFromPolyline(polyline, VectorUtil.Winding.CW); + initFromPolyline(polyline, VectorUtil.Winding.CW); GraphVertex v3 = locateClosestVertex(polyline); HEdge v3Edge = v3.findBoundEdge(); @@ -180,9 +180,9 @@ public class Loop { HEdge.connect(crossEdgeSib, root); } - /** Locates the vertex and update the loops root - * to have (root + vertex) as closest pair - * @param polyline the control polyline + /** Locates the vertex and update the loops root + * to have (root + vertex) as closest pair + * @param polyline the control polyline * to search for closestvertices * @return the vertex that is closest to the newly set root Hedge. */ @@ -205,7 +205,7 @@ public class Loop { for (GraphVertex vert:vertices){ if(vert == v || vert == nextV || vert == cand) continue; - inValid = VectorUtil.inCircle(v.getPoint(), nextV.getPoint(), + inValid = VectorUtil.inCircle(v.getPoint(), nextV.getPoint(), cand.getPoint(), vert.getPoint()); if(inValid){ break; @@ -243,8 +243,8 @@ public class Loop { Vertex cand = candEdge.getGraphPoint().getPoint(); HEdge e = candEdge.getNext(); while (e != candEdge){ - if(e.getGraphPoint() == root.getGraphPoint() - || e.getGraphPoint() == next.getGraphPoint() + if(e.getGraphPoint() == root.getGraphPoint() + || e.getGraphPoint() == next.getGraphPoint() || e.getGraphPoint().getPoint() == cand){ e = e.getNext(); continue; @@ -311,15 +311,15 @@ public class Loop { (v.getX() < (v2.getX() - v1.getX()) * (v.getY() - v1.getY()) / (v2.getY() - v1.getY()) + v1.getX()) ){ inside = !inside; } - + current = next; next = current.getNext(); - + } while(current != root); - + return inside; } - + public int computeLoopSize(){ int size = 0; HEdge e = root; diff --git a/src/jogl/classes/jogamp/graph/curve/text/GlyphShape.java b/src/jogl/classes/jogamp/graph/curve/text/GlyphShape.java index 751a7e7ac..ff46c3338 100644 --- a/src/jogl/classes/jogamp/graph/curve/text/GlyphShape.java +++ b/src/jogl/classes/jogamp/graph/curve/text/GlyphShape.java @@ -37,17 +37,17 @@ import com.jogamp.graph.curve.OutlineShape; import com.jogamp.opengl.math.Quaternion; public class GlyphShape { - + private Quaternion quat= null; private OutlineShape shape = null; - + /** Create a new Glyph shape * based on Parametric curve control polyline */ public GlyphShape(Vertex.Factory factory){ shape = new OutlineShape(factory); } - + /** Create a new GlyphShape from a {@link OutlineShape} * @param factory vertex impl factory {@link Factory} * @param shape {@link OutlineShape} representation of the Glyph @@ -57,24 +57,24 @@ public class GlyphShape { this.shape = shape; this.shape.transformOutlines(OutlineShape.VerticesState.QUADRATIC_NURBS); } - + public final Vertex.Factory vertexFactory() { return shape.vertexFactory(); } - + public OutlineShape getShape() { return shape; } - + public int getNumVertices() { return shape.getVertices().size(); } - + /** Get the rotational Quaternion attached to this Shape * @return the Quaternion Object */ public Quaternion getQuat() { return quat; } - + /** Set the Quaternion that shall defien the rotation * of this shape. * @param quat @@ -82,7 +82,7 @@ public class GlyphShape { public void setQuat(Quaternion quat) { this.quat = quat; } - + /** Triangluate the glyph shape * @return ArrayList of triangles which define this shape */ @@ -95,5 +95,5 @@ public class GlyphShape { */ public ArrayList getVertices(){ return shape.getVertices(); - } + } } diff --git a/src/jogl/classes/jogamp/graph/curve/text/GlyphString.java b/src/jogl/classes/jogamp/graph/curve/text/GlyphString.java index cc850b823..2284ab669 100644 --- a/src/jogl/classes/jogamp/graph/curve/text/GlyphString.java +++ b/src/jogl/classes/jogamp/graph/curve/text/GlyphString.java @@ -52,51 +52,51 @@ public class GlyphString { *

          The actual font size shall be accomplished by the GL PMV matrix.

          */ public static final int STATIC_FONT_SIZE = 10; - + private ArrayList glyphs = new ArrayList(); private CharSequence str; private String fontname; private GLRegion region; - + private SVertex origin = new SVertex(); /** *

          Uses {@link #STATIC_FONT_SIZE}.

          *

          No caching is performed.

          - * + * * @param shape is not null, add all {@link GlyphShape}'s {@link Outline} to this instance. * @param vertexFactory vertex impl factory {@link Factory} - * @param font the target {@link Font} + * @param font the target {@link Font} * @param str string text * @return the created {@link GlyphString} instance */ public static GlyphString createString(OutlineShape shape, Factory vertexFactory, Font font, String str) { - return createString(shape, vertexFactory, font, STATIC_FONT_SIZE, str); + return createString(shape, vertexFactory, font, STATIC_FONT_SIZE, str); } - + /** *

          No caching is performed.

          - * + * * @param shape is not null, add all {@link GlyphShape}'s {@link Outline} to this instance. * @param vertexFactory vertex impl factory {@link Factory} - * @param font the target {@link Font} + * @param font the target {@link Font} * @param fontSize font size * @param str string text * @return the created {@link GlyphString} instance */ public static GlyphString createString(OutlineShape shape, Factory vertexFactory, Font font, int fontSize, String str) { ArrayList shapes = ((FontInt)font).getOutlineShapes(str, fontSize, vertexFactory); - + GlyphString glyphString = new GlyphString(font.getName(Font.NAME_UNIQUNAME), str); glyphString.createfromOutlineShapes(vertexFactory, shapes); if(null != shape) { for(int i=0; i vertexFactory, ArrayList shapes) { final int numGlyps = shapes.size(); @@ -126,31 +126,31 @@ public class GlyphString { continue; } GlyphShape glyphShape = new GlyphShape(vertexFactory, shapes.get(index)); - + if(glyphShape.getNumVertices() < 3) { continue; - } + } addGlyphShape(glyphShape); } } - - + + /** Generate a OGL Region to represent this Object. * @param gl the current gl object * @param rs the current attached RenderState - * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, {@link Region#VBAA_RENDERING_BIT} + * @param renderModes bit-field of modes, e.g. {@link Region#VARIABLE_CURVE_WEIGHT_BIT}, {@link Region#VBAA_RENDERING_BIT} */ public GLRegion createRegion(GL2ES2 gl, int renderModes){ region = RegionFactory.create(renderModes); // region.setFlipped(true); - + int numVertices = region.getNumVertices(); - + for(int i=0; i< glyphs.size(); i++) { final GlyphShape glyph = glyphs.get(i); ArrayList gtris = glyph.triangulate(); region.addTriangles(gtris); - + final ArrayList gVertices = glyph.getVertices(); for(int j=0; j getOutlineShapes(CharSequence string, float pixelSize, Factory vertexFactory); diff --git a/src/jogl/classes/jogamp/graph/font/JavaFontLoader.java b/src/jogl/classes/jogamp/graph/font/JavaFontLoader.java index 3736c5f13..5978e937d 100644 --- a/src/jogl/classes/jogamp/graph/font/JavaFontLoader.java +++ b/src/jogl/classes/jogamp/graph/font/JavaFontLoader.java @@ -40,16 +40,16 @@ import com.jogamp.graph.font.FontSet; import com.jogamp.graph.font.FontFactory; public class JavaFontLoader implements FontSet { - - // FIXME: Add cache size to limit memory usage + + // FIXME: Add cache size to limit memory usage private static final IntObjectHashMap fontMap = new IntObjectHashMap(); - + private static final FontSet fontLoader = new JavaFontLoader(); public static FontSet get() { return fontLoader; } - + final static String availableFontFileNames[] = { /* 00 */ "LucidaBrightRegular.ttf", @@ -61,9 +61,9 @@ public class JavaFontLoader implements FontSet { /* 06 */ "LucidaTypewriterRegular.ttf", /* 07 */ "LucidaTypewriterBold.ttf", }; - + final String javaFontPath; - + private JavaFontLoader() { final String javaHome = AccessController.doPrivileged(new PrivilegedAction() { public String run() { @@ -80,11 +80,11 @@ public class JavaFontLoader implements FontSet { static boolean is(int bits, int bit) { return 0 != ( bits & bit ) ; } - + public Font getDefault() throws IOException { - return get(FAMILY_REGULAR, 0) ; // Sans Serif Regular + return get(FAMILY_REGULAR, 0) ; // Sans Serif Regular } - + public Font get(int family, int style) throws IOException { Font font = (Font)fontMap.get( ( family << 8 ) | style ); if (font != null) { @@ -92,8 +92,8 @@ public class JavaFontLoader implements FontSet { } // 1st process Sans Serif (2 fonts) - if( is(style, STYLE_SERIF) ) { - if( is(style, STYLE_BOLD) ) { + if( is(style, STYLE_SERIF) ) { + if( is(style, STYLE_BOLD) ) { font = abspath(availableFontFileNames[5], family, style); } else { font = abspath(availableFontFileNames[4], family, style); @@ -103,53 +103,53 @@ public class JavaFontLoader implements FontSet { } return font; } - + // Serif Fonts .. switch (family) { case FAMILY_LIGHT: case FAMILY_MEDIUM: case FAMILY_CONDENSED: case FAMILY_REGULAR: - if( is(style, STYLE_BOLD) ) { - if( is(style, STYLE_ITALIC) ) { + if( is(style, STYLE_BOLD) ) { + if( is(style, STYLE_ITALIC) ) { font = abspath(availableFontFileNames[3], family, style); } else { font = abspath(availableFontFileNames[2], family, style); } - } else if( is(style, STYLE_ITALIC) ) { + } else if( is(style, STYLE_ITALIC) ) { font = abspath(availableFontFileNames[1], family, style); } else { font = abspath(availableFontFileNames[0], family, style); } break; - + case FAMILY_MONOSPACED: - if( is(style, STYLE_BOLD) ) { + if( is(style, STYLE_BOLD) ) { font = abspath(availableFontFileNames[7], family, style); } else { font = abspath(availableFontFileNames[6], family, style); } - break; + break; } return font; } - + Font abspath(String fname, int family, int style) throws IOException { if(null == javaFontPath) { throw new GLException("java font path undefined"); } final String err = "Problem loading font "+fname+", file "+javaFontPath+fname ; - + try { final Font f = FontFactory.get( new File(javaFontPath+fname) ); if(null != f) { fontMap.put( ( family << 8 ) | style, f ); return f; } - throw new IOException (err); + throw new IOException (err); } catch (IOException ioe) { - throw new IOException(err, ioe); + throw new IOException(err, ioe); } - } + } } diff --git a/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java b/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java index c4c580290..254583739 100644 --- a/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java +++ b/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java @@ -39,23 +39,23 @@ import com.jogamp.graph.font.FontFactory; import java.net.URLConnection; public class UbuntuFontLoader implements FontSet { - - // FIXME: Add cache size to limit memory usage + + // FIXME: Add cache size to limit memory usage private static final IntObjectHashMap fontMap = new IntObjectHashMap(); - - private static final String relPath = "fonts/ubuntu/" ; - + + private static final String relPath = "fonts/ubuntu/" ; + private static final FontSet fontLoader = new UbuntuFontLoader(); public static final FontSet get() { return fontLoader; } - + final static String availableFontFileNames[] = { /* 00 */ "Ubuntu-R.ttf", // regular /* 01 */ "Ubuntu-RI.ttf", // regular italic - /* 02 */ "Ubuntu-B.ttf", // bold + /* 02 */ "Ubuntu-B.ttf", // bold /* 03 */ "Ubuntu-BI.ttf", // bold italic /* 04 */ "Ubuntu-L.ttf", // light /* 05 */ "Ubuntu-LI.ttf", // light italic @@ -63,18 +63,18 @@ public class UbuntuFontLoader implements FontSet { /* 07 */ "Ubuntu-MI.ttf", // medium italic }; - + private UbuntuFontLoader() { } static boolean is(int bits, int bit) { return 0 != ( bits & bit ) ; } - + public Font getDefault() throws IOException { - return get(FAMILY_REGULAR, 0) ; // Sans Serif Regular + return get(FAMILY_REGULAR, 0) ; // Sans Serif Regular } - + public Font get(int family, int style) throws IOException { Font font = (Font)fontMap.get( ( family << 8 ) | style ); if (font != null) { @@ -97,7 +97,7 @@ public class UbuntuFontLoader implements FontSet { font = abspath(availableFontFileNames[0], family, style); } break; - + case FAMILY_LIGHT: if( is(style, STYLE_ITALIC) ) { font = abspath(availableFontFileNames[5], family, style); @@ -105,19 +105,19 @@ public class UbuntuFontLoader implements FontSet { font = abspath(availableFontFileNames[4], family, style); } break; - + case FAMILY_MEDIUM: if( is(style, STYLE_ITALIC) ) { font = abspath(availableFontFileNames[6], family, style); } else { font = abspath(availableFontFileNames[7], family, style); } - break; + break; } return font; } - + Font abspath(String fname, int family, int style) throws IOException { final String err = "Problem loading font "+fname+", stream "+relPath+fname; try { @@ -129,10 +129,10 @@ public class UbuntuFontLoader implements FontSet { if(null != f) { fontMap.put( ( family << 8 ) | style, f ); return f; - } + } throw new IOException(err); } catch(IOException ioe) { - throw new IOException(err, ioe); + throw new IOException(err, ioe); } - } + } } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFont.java b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFont.java index 0441bf836..ba6c72650 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFont.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFont.java @@ -51,20 +51,20 @@ import com.jogamp.opengl.math.geom.AABBox; class TypecastFont implements FontInt { static final boolean DEBUG = false; - + final OTFontCollection fontset; final OTFont font; TypecastHMetrics metrics; final CmapFormat cmapFormat; int cmapentries; - - // FIXME: Add cache size to limit memory usage ?? - IntObjectHashMap char2Glyph; + + // FIXME: Add cache size to limit memory usage ?? + IntObjectHashMap char2Glyph; public TypecastFont(OTFontCollection fontset) { this.fontset = fontset; this.font = fontset.getFont(0); - + // FIXME: Generic attempt to find the best CmapTable, // which is assumed to be the one with the most entries (stupid 'eh?) CmapTable cmapTable = font.getCmapTable(); @@ -77,14 +77,14 @@ class TypecastFont implements FontInt { int pidx = cmapIdxEntry.getPlatformId(); CmapFormat cf = cmapIdxEntry.getFormat(); if(DEBUG) { - System.err.println("CmapFormat["+i+"]: platform " + pidx + + System.err.println("CmapFormat["+i+"]: platform " + pidx + ", encoding "+cmapIdxEntry.getEncodingId() + ": "+cf); } - if( _cmapFormatP[pidx] == null || + if( _cmapFormatP[pidx] == null || _cmapFormatP[pidx].getLength() < cf.getLength() ) { _cmapFormatP[pidx] = cf; if( cf.getLength() > platformLength ) { - platformLength = cf.getLength() ; + platformLength = cf.getLength() ; platform = pidx; encoding = cmapIdxEntry.getEncodingId(); } @@ -93,10 +93,10 @@ class TypecastFont implements FontInt { if(0 <= platform) { cmapFormat = _cmapFormatP[platform]; if(DEBUG) { - System.err.println("Selected CmapFormat: platform " + platform + + System.err.println("Selected CmapFormat: platform " + platform + ", encoding "+encoding + ": "+cmapFormat); } - } else { + } else { CmapFormat _cmapFormat = null; /*if(null == _cmapFormat) { platform = ID.platformMacintosh; @@ -127,14 +127,14 @@ class TypecastFont implements FontInt { cmapentries = 0; for (int i = 0; i < cmapFormat.getRangeCount(); ++i) { CmapFormat.Range range = cmapFormat.getRange(i); - cmapentries += range.getEndCode() - range.getStartCode() + 1; // end included - } + cmapentries += range.getEndCode() - range.getStartCode() + 1; // end included + } if(DEBUG) { System.err.println("font direction hint: "+font.getHeadTable().getFontDirectionHint()); System.err.println("num glyphs: "+font.getNumGlyphs()); System.err.println("num cmap entries: "+cmapentries); System.err.println("num cmap ranges: "+cmapFormat.getRangeCount()); - + for (int i = 0; i < cmapFormat.getRangeCount(); ++i) { CmapFormat.Range range = cmapFormat.getRange(i); for (int j = range.getStartCode(); j <= range.getEndCode(); ++j) { @@ -147,7 +147,7 @@ class TypecastFont implements FontInt { } char2Glyph = new IntObjectHashMap(cmapentries + cmapentries/4); } - + public StringBuilder getName(StringBuilder sb, int nameIndex) { return font.getName(nameIndex, sb); } @@ -161,12 +161,12 @@ class TypecastFont implements FontInt { sb = getName(sb, Font.NAME_FAMILY).append("-"); getName(sb, Font.NAME_SUBFAMILY); return sb; - } + } public float getAdvanceWidth(int i, float pixelSize) { - return font.getHmtxTable().getAdvanceWidth(i) * metrics.getScale(pixelSize); + return font.getHmtxTable().getAdvanceWidth(i) * metrics.getScale(pixelSize); } - + public Metrics getMetrics() { if (metrics == null) { metrics = new TypecastHMetrics(this); @@ -175,7 +175,7 @@ class TypecastFont implements FontInt { } public Glyph getGlyph(char symbol) { - TypecastGlyph result = (TypecastGlyph) char2Glyph.get(symbol); + TypecastGlyph result = (TypecastGlyph) char2Glyph.get(symbol); if (null == result) { // final short code = (short) char2Code.get(symbol); short code = (short) cmapFormat.mapCharCode(symbol); @@ -187,7 +187,7 @@ class TypecastFont implements FontInt { default: code = Glyph.ID_UNKNOWN; } } - + jogamp.graph.font.typecast.ot.OTGlyph glyph = font.getGlyph(code); if(null == glyph) { glyph = font.getGlyph(Glyph.ID_UNKNOWN); @@ -200,25 +200,25 @@ class TypecastFont implements FontInt { if(DEBUG) { System.err.println("New glyph: " + (int)symbol + " ( " + (char)symbol +" ) -> " + code + ", contours " + glyph.getPointCount() + ": " + path); } - final HdmxTable hdmx = font.getHdmxTable(); + final HdmxTable hdmx = font.getHdmxTable(); if (null!= result && null != hdmx) { /*if(DEBUG) { System.err.println("hdmx "+hdmx); }*/ for (int i=0; i getOutlineShapes(CharSequence string, float pixelSize, Factory vertexFactory) { AffineTransform transform = new AffineTransform(vertexFactory); return TypecastRenderer.getOutlineShapes(this, string, pixelSize, transform, vertexFactory); @@ -238,7 +238,7 @@ class TypecastFont implements FontInt { } } - return (int)(width + 0.5f); + return (int)(width + 0.5f); } public float getStringHeight(CharSequence string, float pixelSize) { @@ -254,7 +254,7 @@ class TypecastFont implements FontInt { height = (int)Math.ceil(Math.max(bbox.getHeight(), height)); } } - return height; + return height; } public AABBox getStringBounds(CharSequence string, float pixelSize) { @@ -284,17 +284,17 @@ class TypecastFont implements FontInt { totalHeight -= advanceY; totalWidth = Math.max(curLineWidth, totalWidth); } - return new AABBox(0, 0, 0, totalWidth, totalHeight,0); + return new AABBox(0, 0, 0, totalWidth, totalHeight,0); } final public int getNumGlyphs() { return font.getNumGlyphs(); } - + public boolean isPrintableChar( char c ) { return FontFactory.isPrintableChar(c); } - + public String toString() { return getFullFamilyName(null).toString(); } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java index 8479c08ca..77b5a9aa9 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java @@ -46,7 +46,7 @@ public class TypecastFontConstructor implements FontConstructor { public Font create(final File ffile) throws IOException { Object o = AccessController.doPrivileged(new PrivilegedAction() { public Object run() { - OTFontCollection fontset; + OTFontCollection fontset; try { fontset = OTFontCollection.create(ffile); return new TypecastFont(fontset); @@ -63,14 +63,14 @@ public class TypecastFontConstructor implements FontConstructor { } throw new InternalError("Unexpected Object: "+o); } - + public Font create(final URLConnection fconn) throws IOException { return AccessController.doPrivileged(new PrivilegedAction() { public Font run() { File tf = null; int len=0; Font f = null; - try { + try { tf = IOUtil.createTempFile( "jogl.font", ".ttf", false); len = IOUtil.copyURLConn2File(fconn, tf); if(len==0) { @@ -84,7 +84,7 @@ public class TypecastFontConstructor implements FontConstructor { } return f; } - }); + }); } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/TypecastGlyph.java b/src/jogl/classes/jogamp/graph/font/typecast/TypecastGlyph.java index 1205c6539..476b3fd4e 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/TypecastGlyph.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/TypecastGlyph.java @@ -40,45 +40,45 @@ public class TypecastGlyph implements FontInt.GlyphInt { public class Advance { final Font font; - final float advance; - HashMap size2advance = new HashMap(); - + final float advance; + HashMap size2advance = new HashMap(); + public Advance(Font font, float advance) { this.font = font; this.advance = advance; } - + public void reset() { size2advance.clear(); } - + public float getScale(float pixelSize) { return this.font.getMetrics().getScale(pixelSize); } - + public void add(float advance, float size) { size2advance.put(size, advance); } - + public float get(float size, boolean useFrationalMetrics) { Float fo = size2advance.get(size); - if(null == fo) { + if(null == fo) { float value = (this.advance * getScale(size)); if (useFrationalMetrics == false) { //value = (float)Math.ceil(value); // value = (int)value; - value = (int) ( value + 0.5f ) ; // TODO: check + value = (int) ( value + 0.5f ) ; // TODO: check } size2advance.put(size, value); return value; } return fo.floatValue(); } - + public String toString() { return "\nAdvance:"+ @@ -86,147 +86,147 @@ public class TypecastGlyph implements FontInt.GlyphInt { "\n advances: \n"+size2advance; } } - + public class Metrics { AABBox bbox; Advance advance; - + public Metrics(Font font, AABBox bbox, float advance) { this.bbox = bbox; this.advance = new Advance(font, advance); } - + public void reset() { advance.reset(); } - + public float getScale(float pixelSize) { return this.advance.getScale(pixelSize); } - + public AABBox getBBox() { return this.bbox; } - + public void addAdvance(float advance, float size) { this.advance.add(advance, size); } - + public float getAdvance(float size, boolean useFrationalMetrics) { return this.advance.get(size, useFrationalMetrics); } - + public String toString() { return "\nMetrics:"+ "\n bbox: "+this.bbox+ this.advance; } - } + } public static final short INVALID_ID = (short)((1 << 16) - 1); public static final short MAX_ID = (short)((1 << 16) - 2); - + private final Font font; - + char symbol; short id; int advance; Metrics metrics; - + protected Path2D path; // in EM units protected Path2D pathSized; protected float numberSized; - + protected TypecastGlyph(Font font, char symbol) { this.font = font; this.symbol = symbol; } - + protected TypecastGlyph(Font font, char symbol, short id, AABBox bbox, int advance, Path2D path) { this.font = font; this.symbol = symbol; this.advance = advance; - + init(id, bbox, advance); - + this.path = path; this.pathSized = null; this.numberSized = 0.0f; } - + void init(short id, AABBox bbox, int advance) { this.id = id; this.advance = advance; this.metrics = new Metrics(this.font, bbox, this.advance); } - + public void reset(Path2D path) { this.path = path; this.metrics.reset(); } - + public Font getFont() { return this.font; } - + public char getSymbol() { return this.symbol; } - + AABBox getBBoxUnsized() { return this.metrics.getBBox(); } - + public AABBox getBBox() { return this.metrics.getBBox(); } - + public Metrics getMetrics() { return this.metrics; } - + public short getID() { return this.id; } - + public float getScale(float pixelSize) { return this.metrics.getScale(pixelSize); } - + public AABBox getBBox(float pixelSize) { final float size = getScale(pixelSize); AABBox newBox = getBBox().clone(); newBox.scale(size); - return newBox; + return newBox; } - + protected void addAdvance(float advance, float size) { this.metrics.addAdvance(advance, size); } - + public float getAdvance(float pixelSize, boolean useFrationalMetrics) { return this.metrics.getAdvance(pixelSize, useFrationalMetrics); } - + public Path2D getPath() { return this.path; } - + public Path2D getPath(float pixelSize) { final float size = getScale(pixelSize); - + if (this.numberSized != size) { this.numberSized = size; this.pathSized = AffineTransform.getScaleInstance(null, size, size).createTransformedShape(getPath()); - } + } return this.pathSized; - } + } } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/TypecastHMetrics.java b/src/jogl/classes/jogamp/graph/font/typecast/TypecastHMetrics.java index f170f5819..a6ce58ae2 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/TypecastHMetrics.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/TypecastHMetrics.java @@ -35,7 +35,7 @@ import com.jogamp.opengl.math.geom.AABBox; class TypecastHMetrics implements Metrics { private final TypecastFont fontImpl; - + // HeadTable private final HeadTable headTable; private final float unitsPerEM_Inv; @@ -44,23 +44,23 @@ class TypecastHMetrics implements Metrics { private final HheaTable hheaTable; // VheaTable (for horizontal fonts) // private final VheaTable vheaTable; - + public TypecastHMetrics(TypecastFont fontImpl) { this.fontImpl = fontImpl; headTable = this.fontImpl.font.getHeadTable(); - hheaTable = this.fontImpl.font.getHheaTable(); + hheaTable = this.fontImpl.font.getHheaTable(); // vheaTable = this.fontImpl.font.getVheaTable(); unitsPerEM_Inv = 1.0f / ( (float) headTable.getUnitsPerEm() ); - + int maxWidth = headTable.getXMax() - headTable.getXMin(); - int maxHeight = headTable.getYMax() - headTable.getYMin(); + int maxHeight = headTable.getYMax() - headTable.getYMin(); float lowx= headTable.getXMin(); float lowy = -(headTable.getYMin()+maxHeight); float highx = lowx + maxWidth; float highy = lowy + maxHeight; bbox = new AABBox(lowx, lowy, 0, highx, highy, 0); // invert } - + public final float getAscent(float pixelSize) { return getScale(pixelSize) * -hheaTable.getAscender(); // invert } @@ -78,7 +78,7 @@ class TypecastHMetrics implements Metrics { } public final AABBox getBBox(float pixelSize) { AABBox res = new AABBox(bbox.getLow(), bbox.getHigh()); - res.scale(getScale(pixelSize)); + res.scale(getScale(pixelSize)); return res; } } \ No newline at end of file diff --git a/src/jogl/classes/jogamp/graph/font/typecast/TypecastRenderer.java b/src/jogl/classes/jogamp/graph/font/typecast/TypecastRenderer.java index f155345aa..127e260ca 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/TypecastRenderer.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/TypecastRenderer.java @@ -43,14 +43,14 @@ import com.jogamp.graph.geom.Vertex; import com.jogamp.graph.geom.Vertex.Factory; /** - * Factory to build a {@link com.jogamp.graph.geom.Path2D Path2D} from - * {@link jogamp.graph.font.typecast.ot.OTGlyph Glyph}s. + * Factory to build a {@link com.jogamp.graph.geom.Path2D Path2D} from + * {@link jogamp.graph.font.typecast.ot.OTGlyph Glyph}s. */ public class TypecastRenderer { - private static void getPaths(TypecastFont font, + private static void getPaths(TypecastFont font, CharSequence string, float pixelSize, AffineTransform transform, Path2D[] p) - { + { if (string == null) { return; } @@ -79,14 +79,14 @@ public class TypecastRenderer { } else if (character == ' ') { advanceTotal += font.getAdvanceWidth(Glyph.ID_SPACE, pixelSize); continue; - } + } Glyph glyph = font.getGlyph(character); Path2D gp = ((GlyphInt)glyph).getPath(); float scale = metrics.getScale(pixelSize); t.translate(advanceTotal, y); t.scale(scale, scale); p[i].append(gp.iterator(t), false); - advanceTotal += glyph.getAdvance(pixelSize, true); + advanceTotal += glyph.getAdvance(pixelSize, true); } } @@ -119,19 +119,19 @@ public class TypecastRenderer { case PathIterator.SEG_MOVETO: shape.closeLastOutline(); shape.addEmptyOutline(); - shape.addVertex(0, vertexFactory.create(coords, 0, 2, true)); + shape.addVertex(0, vertexFactory.create(coords, 0, 2, true)); break; case PathIterator.SEG_LINETO: - shape.addVertex(0, vertexFactory.create(coords, 0, 2, true)); + shape.addVertex(0, vertexFactory.create(coords, 0, 2, true)); break; case PathIterator.SEG_QUADTO: shape.addVertex(0, vertexFactory.create(coords, 0, 2, false)); - shape.addVertex(0, vertexFactory.create(coords, 2, 2, true)); + shape.addVertex(0, vertexFactory.create(coords, 2, 2, true)); break; case PathIterator.SEG_CUBICTO: shape.addVertex(0, vertexFactory.create(coords, 0, 2, false)); shape.addVertex(0, vertexFactory.create(coords, 2, 2, false)); - shape.addVertex(0, vertexFactory.create(coords, 4, 2, true)); + shape.addVertex(0, vertexFactory.create(coords, 4, 2, true)); break; case PathIterator.SEG_CLOSE: shape.closeLastOutline(); @@ -184,12 +184,12 @@ public class TypecastRenderer { if (point_plus1.onCurve) { // s = new Line2D.Float(point.x, point.y, point_plus1.x, point_plus1.y); gp.lineTo( point_plus1.x, point_plus1.y ); - offset++; + offset++; } else { if (point_plus2.onCurve) { // s = new QuadCurve2D.Float( point.x, point.y, point_plus1.x, point_plus1.y, point_plus2.x, point_plus2.y); gp.quadTo(point_plus1.x, point_plus1.y, point_plus2.x, point_plus2.y); - offset+=2; + offset+=2; } else { // s = new QuadCurve2D.Float(point.x,point.y,point_plus1.x,point_plus1.y, // midValue(point_plus1.x, point_plus2.x), midValue(point_plus1.y, point_plus2.y)); @@ -210,7 +210,7 @@ public class TypecastRenderer { // midValue(point.x, point_plus1.x), midValue(point.y, point_plus1.y)); //gp.curve3(midValue(point.x, point_plus1.x), midValue(point.y, point_plus1.y), point.x, point.y); gp.quadTo(point.x, point.y, midValue(point.x, point_plus1.x), midValue(point.y, point_plus1.y)); - offset++; + offset++; } } } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/Disassembler.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/Disassembler.java index b5535758d..8b685659e 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/Disassembler.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/Disassembler.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/Fixed.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/Fixed.java index ece0aae4b..0a4786f82 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/Fixed.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/Fixed.java @@ -840,11 +840,11 @@ public class Fixed { } return n; } - + public static float floatValue(long fixed) { return (fixed >> 16) + (float)(fixed & 0xffff) / 0x10000; } - + public static float roundedFloatValue(long fixed, int decimalPlaces) { int factor = 10 * decimalPlaces; return (float)((int)(floatValue(fixed) * factor)) / factor; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/Mnemonic.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/Mnemonic.java index 6b3dc1f6f..d6c9da268 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/Mnemonic.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/Mnemonic.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFont.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFont.java index 8c14b7302..8fc4be92d 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFont.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFont.java @@ -104,10 +104,10 @@ public class OTFont { public StringBuilder getName(int nameIndex, StringBuilder sb) { if(null == sb) { sb = new StringBuilder(); - } + } return _name.getRecordsRecordString(sb, nameIndex); } - + public StringBuilder getAllNames(StringBuilder sb, String separator) { if(null != _name) { if(null == sb) { @@ -117,9 +117,9 @@ public class OTFont { _name.getRecord(i).getRecordString(sb).append(separator); } } - return sb; + return sb; } - + public Table getTable(int tableType) { for (int i = 0; i < _tables.length; i++) { if ((_tables[i] != null) && (_tables[i].getType() == tableType)) { @@ -132,31 +132,31 @@ public class OTFont { public Os2Table getOS2Table() { return _os2; } - + public CmapTable getCmapTable() { return _cmap; } - + public HeadTable getHeadTable() { return _head; } - + public HheaTable getHheaTable() { return _hhea; } - + public HdmxTable getHdmxTable() { return _hdmx; } - + public HmtxTable getHmtxTable() { return _hmtx; } - + public LocaTable getLocaTable() { return _loca; } - + public MaxpTable getMaxpTable() { return _maxp; } @@ -186,8 +186,8 @@ public class OTFont { } public OTGlyph getGlyph(int i) { - - final GlyfDescript _glyfDescr = _glyf.getDescription(i); + + final GlyfDescript _glyfDescr = _glyf.getDescription(i); return (null != _glyfDescr) ? new OTGlyph( _glyfDescr, @@ -195,11 +195,11 @@ public class OTFont { _hmtx.getAdvanceWidth(i)) : null; } - + public TableDirectory getTableDirectory() { return _tableDirectory; } - + private Table readTable( DataInputStream dis, int tablesOrigin, @@ -228,13 +228,13 @@ public class OTFont { DataInputStream dis, int directoryOffset, int tablesOrigin) throws IOException { - + // Load the table directory dis.reset(); dis.skip(directoryOffset); _tableDirectory = new TableDirectory(dis); _tables = new Table[_tableDirectory.getNumTables()]; - + // Load some prerequisite tables _head = (HeadTable) readTable(dis, tablesOrigin, Table.head); _hhea = (HheaTable) readTable(dis, tablesOrigin, Table.hhea); @@ -252,7 +252,7 @@ public class OTFont { if (_vhea != null) { _tables[index++] = _vhea; } - + // Load all other tables for (int i = 0; i < _tableDirectory.getNumTables(); i++) { DirectoryEntry entry = _tableDirectory.getEntry(i); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFontCollection.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFontCollection.java index 4a041604d..c79380f16 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFontCollection.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFontCollection.java @@ -75,11 +75,11 @@ public class OTFontCollection { public OTFont getFont(int i) { return _fonts[i]; } - + public int getFontCount() { return _fonts.length; } - + public TTCHeader getTtcHeader() { return _ttcHeader; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/OTGlyph.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/OTGlyph.java index 244ab400a..e0d652bd4 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/OTGlyph.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/OTGlyph.java @@ -102,10 +102,10 @@ public class OTGlyph { } } - public AABBox getBBox() { - return _bbox; + public AABBox getBBox() { + return _bbox; } - + public int getAdvanceWidth() { return _advanceWidth; } @@ -163,7 +163,7 @@ public class OTGlyph { // Append the origin and advanceWidth points (n & n+1) // _points[gd.getPointCount()] = new Point(0, 0, true, true); // _points[gd.getPointCount()+1] = new Point(_advanceWidth, 0, true, true); - + _bbox = new AABBox(gd.getXMinimum(), gd.getYMinimum(), 0, gd.getXMaximum(), gd.getYMaximum(), 0); } } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceData.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceData.java index 433ff6051..7a5b0c4d2 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceData.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceData.java @@ -31,7 +31,7 @@ import java.io.IOException; public class ResourceData { private byte[] data; - + /** Creates new ResourceData */ public ResourceData(DataInput di) throws IOException { int dataLen = di.readInt(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceFile.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceFile.java index 2ada22c82..468ab2e1c 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceFile.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceFile.java @@ -33,14 +33,14 @@ public class ResourceFile { private ResourceHeader header; private ResourceMap map; - + /** Creates new Resource */ public ResourceFile(RandomAccessFile raf) throws IOException { // Read header at the beginning of the file raf.seek(0); header = new ResourceHeader(raf); - + // Seek to the map offset and read the map raf.seek(header.getMapOffset()); map = new ResourceMap(raf); @@ -53,18 +53,18 @@ public class ResourceFile { public static void main(String[] args) { try { //RandomAccessFile raf = new RandomAccessFile("/Library/Fonts/GillSans.dfont", "r"); - + // Tests loading a font from a resource fork on Mac OS X RandomAccessFile raf = new RandomAccessFile("/Library/Fonts/Georgia/..namedfork/rsrc", "r"); ResourceFile resource = new ResourceFile(raf); for (int i = 0; i < resource.getResourceMap().getResourceTypeCount(); i++) { System.out.println(resource.getResourceMap().getResourceType(i).getTypeAsString()); } - + // Get the first 'sfnt' resource ResourceType type = resource.getResourceMap().getResourceType("sfnt"); ResourceReference reference = type.getReference(0); - + type = resource.getResourceMap().getResourceType("FOND"); for (int i = 0; i < type.getCount(); ++i) { reference = type.getReference(i); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceHeader.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceHeader.java index 8f5224632..de13b116f 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceHeader.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceHeader.java @@ -46,15 +46,15 @@ public class ResourceHeader { public int getDataOffset() { return dataOffset; } - + public int getMapOffset() { return mapOffset; } - + public int getDataLength() { return dataLen; } - + public int getMapLength() { return mapLen; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceMap.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceMap.java index 96ba06087..d348c645e 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceMap.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceMap.java @@ -35,7 +35,7 @@ public class ResourceMap { private int fileReferenceNumber; private int attributes; private ResourceType[] types; - + /** Creates new ResourceMap */ public ResourceMap(DataInput di) throws IOException { di.readFully(headerCopy); @@ -45,18 +45,18 @@ public class ResourceMap { int typeOffset = di.readUnsignedShort(); int nameOffset = di.readUnsignedShort(); int typeCount = di.readUnsignedShort() + 1; - + // Read types types = new ResourceType[typeCount]; for (int i = 0; i < typeCount; i++) { types[i] = new ResourceType(di); } - + // Read the references for (int i = 0; i < typeCount; i++) { types[i].readRefs(di); } - + // Read the names for (int i = 0; i < typeCount; i++) { types[i].readNames(di); @@ -76,7 +76,7 @@ public class ResourceMap { public ResourceType getResourceType(int i) { return types[i]; } - + public int getResourceTypeCount() { return types.length; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceReference.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceReference.java index fd7ec46b2..9d1534821 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceReference.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceReference.java @@ -36,7 +36,7 @@ public class ResourceReference { private int dataOffset; private int handle; private String name; - + /** Creates new ResourceReference */ protected ResourceReference(DataInput di) throws IOException { id = di.readUnsignedShort(); @@ -58,23 +58,23 @@ public class ResourceReference { public int getId() { return id; } - + public short getNameOffset() { return nameOffset; } - + public short getAttributes() { return attributes; } - + public int getDataOffset() { return dataOffset; } - + public int getHandle() { return handle; } - + public String getName() { return name; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceType.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceType.java index 1c7e24c0f..2ad002e6a 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceType.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceType.java @@ -34,7 +34,7 @@ public class ResourceType { private int count; private int offset; private ResourceReference[] references; - + /** Creates new ResourceType */ protected ResourceType(DataInput di) throws IOException { type = di.readInt(); @@ -42,7 +42,7 @@ public class ResourceType { offset = di.readUnsignedShort(); references = new ResourceReference[count]; } - + protected void readRefs(DataInput di) throws IOException { for (int i = 0; i < count; i++) { references[i] = new ResourceReference(di); @@ -58,7 +58,7 @@ public class ResourceType { public int getType() { return type; } - + public String getTypeAsString() { return new StringBuilder() .append((char)((type>>24)&0xff)) @@ -67,11 +67,11 @@ public class ResourceType { .append((char)((type)&0xff)) .toString(); } - + public int getCount() { return count; } - + public int getOffset() { return offset; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java index ed615eb72..b6626a9cc 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java @@ -31,18 +31,18 @@ import java.io.IOException; * @author David Schweinsberg */ public class BaseTable implements Table { - + private abstract class BaseCoord { public abstract int getBaseCoordFormat(); - + public abstract short getCoordinate(); } - + private class BaseCoordFormat1 extends BaseCoord { private short _coordinate; - + protected BaseCoordFormat1(DataInput di) throws IOException { _coordinate = di.readShort(); } @@ -50,19 +50,19 @@ public class BaseTable implements Table { public int getBaseCoordFormat() { return 1; } - + public short getCoordinate() { return _coordinate; } - + } - + private class BaseCoordFormat2 extends BaseCoord { private short _coordinate; private int _referenceGlyph; private int _baseCoordPoint; - + protected BaseCoordFormat2(DataInput di) throws IOException { _coordinate = di.readShort(); _referenceGlyph = di.readUnsignedShort(); @@ -72,18 +72,18 @@ public class BaseTable implements Table { public int getBaseCoordFormat() { return 2; } - + public short getCoordinate() { return _coordinate; } - + } - + private class BaseCoordFormat3 extends BaseCoord { private short _coordinate; private int _deviceTableOffset; - + protected BaseCoordFormat3(DataInput di) throws IOException { _coordinate = di.readShort(); _deviceTableOffset = di.readUnsignedShort(); @@ -92,33 +92,33 @@ public class BaseTable implements Table { public int getBaseCoordFormat() { return 2; } - + public short getCoordinate() { return _coordinate; } - + } - + private class FeatMinMaxRecord { - + private int _tag; private int _minCoordOffset; private int _maxCoordOffset; - + protected FeatMinMaxRecord(DataInput di) throws IOException { _tag = di.readInt(); _minCoordOffset = di.readUnsignedShort(); _maxCoordOffset = di.readUnsignedShort(); } } - + private class MinMax { - + private int _minCoordOffset; private int _maxCoordOffset; private int _featMinMaxCount; private FeatMinMaxRecord[] _featMinMaxRecord; - + protected MinMax(int minMaxOffset) throws IOException { DataInput di = getDataInputForOffset(minMaxOffset); _minCoordOffset = di.readUnsignedShort(); @@ -130,14 +130,14 @@ public class BaseTable implements Table { } } } - + private class BaseValues { - + private int _defaultIndex; private int _baseCoordCount; private int[] _baseCoordOffset; private BaseCoord[] _baseCoords; - + protected BaseValues(int baseValuesOffset) throws IOException { DataInput di = getDataInputForOffset(baseValuesOffset); _defaultIndex = di.readUnsignedShort(); @@ -163,12 +163,12 @@ public class BaseTable implements Table { } } } - + private class BaseLangSysRecord { - + private int _baseLangSysTag; private int _minMaxOffset; - + protected BaseLangSysRecord(DataInput di) throws IOException { _baseLangSysTag = di.readInt(); _minMaxOffset = di.readUnsignedShort(); @@ -177,14 +177,14 @@ public class BaseTable implements Table { public int getBaseLangSysTag() { return _baseLangSysTag; } - + public int getMinMaxOffset() { return _minMaxOffset; } } - + private class BaseScript { - + private int _thisOffset; private int _baseValuesOffset; private int _defaultMinMaxOffset; @@ -192,7 +192,7 @@ public class BaseTable implements Table { private BaseLangSysRecord[] _baseLangSysRecord; private BaseValues _baseValues; private MinMax[] _minMax; - + protected BaseScript(int baseScriptOffset) throws IOException { _thisOffset = baseScriptOffset; DataInput di = getDataInputForOffset(baseScriptOffset); @@ -231,9 +231,9 @@ public class BaseTable implements Table { return sb.toString(); } } - + private class BaseScriptRecord { - + private int _baseScriptTag; private int _baseScriptOffset; @@ -245,19 +245,19 @@ public class BaseTable implements Table { public int getBaseScriptTag() { return _baseScriptTag; } - + public int getBaseScriptOffset() { return _baseScriptOffset; } } - + private class BaseScriptList { - + private int _thisOffset; private int _baseScriptCount; private BaseScriptRecord[] _baseScriptRecord; private BaseScript[] _baseScripts; - + protected BaseScriptList(int baseScriptListOffset) throws IOException { _thisOffset = baseScriptListOffset; DataInput di = getDataInputForOffset(baseScriptListOffset); @@ -288,13 +288,13 @@ public class BaseTable implements Table { return sb.toString(); } } - + private class BaseTagList { - + private int _thisOffset; private int _baseTagCount; private int[] _baselineTag; - + protected BaseTagList(int baseTagListOffset) throws IOException { _thisOffset = baseTagListOffset; DataInput di = getDataInputForOffset(baseTagListOffset); @@ -315,9 +315,9 @@ public class BaseTable implements Table { return sb.toString(); } } - + private class Axis { - + private int _thisOffset; private int _baseTagListOffset; private int _baseScriptListOffset; @@ -348,7 +348,7 @@ public class BaseTable implements Table { .toString(); } } - + private DirectoryEntry _de; private int _version; private int _horizAxisOffset; @@ -375,25 +375,25 @@ public class BaseTable implements Table { if (_vertAxisOffset != 0) { _vertAxis = new Axis(_vertAxisOffset); } - + // Let go of the buffer _buf = null; } - + private DataInput getDataInputForOffset(int offset) { return new DataInputStream(new ByteArrayInputStream( _buf, offset, _de.getLength() - offset)); } - + // private String valueAsShortHex(int value) { // return String.format("%1$4x", value); // } -// +// // private String valueAsLongHex(int value) { // return String.format("%1$8x", value); // } - + static protected String tagAsString(int tag) { char[] c = new char[4]; c[0] = (char)((tag >> 24) & 0xff); @@ -402,7 +402,7 @@ public class BaseTable implements Table { c[3] = (char)(tag & 0xff); return String.valueOf(c); } - + public int getType() { return BASE; } @@ -422,7 +422,7 @@ public class BaseTable implements Table { } return sb.toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java index 966f6e17b..62486fb7f 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java @@ -36,13 +36,13 @@ import java.util.Hashtable; * @author David Schweinsberg */ public class CffTable implements Table { - + public class Dict { - + private Dictionary _entries = new Hashtable(); private int[] _data; private int _index; - + protected Dict(int[] data, int offset, int length) { _data = data; _index = offset; @@ -50,11 +50,11 @@ public class CffTable implements Table { addKeyAndValueEntry(); } } - + public Object getValue(int key) { return _entries.get(key); } - + private boolean addKeyAndValueEntry() { ArrayList operands = new ArrayList(); Object operand = null; @@ -74,7 +74,7 @@ public class CffTable implements Table { } return true; } - + private boolean isOperandAtIndex() { int b0 = _data[_index]; if ((32 <= b0 && b0 <= 254) @@ -97,31 +97,31 @@ public class CffTable implements Table { private Object nextOperand() { int b0 = _data[_index]; if (32 <= b0 && b0 <= 246) { - + // 1 byte integer ++_index; return new Integer(b0 - 139); } else if (247 <= b0 && b0 <= 250) { - + // 2 byte integer int b1 = _data[_index + 1]; _index += 2; return new Integer((b0 - 247) * 256 + b1 + 108); } else if (251 <= b0 && b0 <= 254) { - + // 2 byte integer int b1 = _data[_index + 1]; _index += 2; return new Integer(-(b0 - 251) * 256 - b1 - 108); } else if (b0 == 28) { - + // 3 byte integer int b1 = _data[_index + 1]; int b2 = _data[_index + 2]; _index += 3; return new Integer(b1 << 8 | b2); } else if (b0 == 29) { - + // 5 byte integer int b1 = _data[_index + 1]; int b2 = _data[_index + 2]; @@ -130,7 +130,7 @@ public class CffTable implements Table { _index += 5; return new Integer(b1 << 24 | b2 << 16 | b3 << 8 | b4); } else if (b0 == 30) { - + // Real number StringBuilder fString = new StringBuilder(); int nibble1 = 0; @@ -142,13 +142,13 @@ public class CffTable implements Table { ++_index; fString.append(decodeRealNibble(nibble1)); fString.append(decodeRealNibble(nibble2)); - } + } return new Float(fString.toString()); } else { return null; } } - + private String decodeRealNibble(int nibble) { if (nibble < 0xa) { return Integer.toString(nibble); @@ -163,7 +163,7 @@ public class CffTable implements Table { } return ""; } - + public String toString() { StringBuilder sb = new StringBuilder(); Enumeration keys = _entries.keys(); @@ -179,14 +179,14 @@ public class CffTable implements Table { return sb.toString(); } } - + public class Index { - + private int _count; private int _offSize; private int[] _offset; private int[] _data; - + protected Index(DataInput di) throws IOException { _count = di.readUnsignedShort(); _offset = new int[_count + 1]; @@ -203,19 +203,19 @@ public class CffTable implements Table { _data[i] = di.readUnsignedByte(); } } - + public int getCount() { return _count; } - + public int getOffset(int index) { return _offset[index]; } - + public int getDataLength() { return _offset[_offset.length - 1] - 1; } - + public int[] getData() { return _data; } @@ -241,13 +241,13 @@ public class CffTable implements Table { return sb.toString(); } } - + public class TopDictIndex extends Index { protected TopDictIndex(DataInput di) throws IOException { super(di); } - + public Dict getTopDict(int index) { int offset = getOffset(index) - 1; int len = getOffset(index + 1) - offset - 1; @@ -262,13 +262,13 @@ public class CffTable implements Table { return sb.toString(); } } - + public class NameIndex extends Index { protected NameIndex(DataInput di) throws IOException { super(di); } - + public String getName(int index) { String name = null; int offset = getOffset(index) - 1; @@ -286,7 +286,7 @@ public class CffTable implements Table { } return name; } - + public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < getCount(); ++i) { @@ -301,7 +301,7 @@ public class CffTable implements Table { protected StringIndex(DataInput di) throws IOException { super(di); } - + public String getString(int index) { if (index < CffStandardStrings.standardStrings.length) { return CffStandardStrings.standardStrings[index]; @@ -320,7 +320,7 @@ public class CffTable implements Table { return sb.toString(); } } - + public String toString() { int nonStandardBase = CffStandardStrings.standardStrings.length; StringBuilder sb = new StringBuilder(); @@ -331,12 +331,12 @@ public class CffTable implements Table { return sb.toString(); } } - + private class CharsetRange { - + private int _first; private int _left; - + public int getFirst() { return _first; } @@ -344,7 +344,7 @@ public class CffTable implements Table { protected void setFirst(int first) { _first = first; } - + public int getLeft() { return _left; } @@ -355,39 +355,39 @@ public class CffTable implements Table { } private class CharsetRange1 extends CharsetRange { - + protected CharsetRange1(DataInput di) throws IOException { setFirst(di.readUnsignedShort()); setLeft(di.readUnsignedByte()); } } - + private class CharsetRange2 extends CharsetRange { - + protected CharsetRange2(DataInput di) throws IOException { setFirst(di.readUnsignedShort()); setLeft(di.readUnsignedShort()); } } - + private abstract class Charset { - + public abstract int getFormat(); - + public abstract int getSID(int gid); } - + private class CharsetFormat0 extends Charset { - + private int[] _glyph; - + protected CharsetFormat0(DataInput di, int glyphCount) throws IOException { _glyph = new int[glyphCount - 1]; // minus 1 because .notdef is omitted for (int i = 0; i < glyphCount - 1; ++i) { _glyph[i] = di.readUnsignedShort(); } } - + public int getFormat() { return 0; } @@ -399,11 +399,11 @@ public class CffTable implements Table { return _glyph[gid - 1]; } } - + private class CharsetFormat1 extends Charset { - + private ArrayList _charsetRanges = new ArrayList(); - + protected CharsetFormat1(DataInput di, int glyphCount) throws IOException { int glyphsCovered = glyphCount - 1; // minus 1 because .notdef is omitted while (glyphsCovered > 0) { @@ -421,7 +421,7 @@ public class CffTable implements Table { if (gid == 0) { return 0; } - + // Count through the ranges to find the one of interest int count = 0; for (CharsetRange range : _charsetRanges) { @@ -436,9 +436,9 @@ public class CffTable implements Table { } private class CharsetFormat2 extends Charset { - + private ArrayList _charsetRanges = new ArrayList(); - + protected CharsetFormat2(DataInput di, int glyphCount) throws IOException { int glyphsCovered = glyphCount - 1; // minus 1 because .notdef is omitted while (glyphsCovered > 0) { @@ -456,7 +456,7 @@ public class CffTable implements Table { if (gid == 0) { return 0; } - + // Count through the ranges to find the one of interest int count = 0; for (CharsetRange range : _charsetRanges) { @@ -469,7 +469,7 @@ public class CffTable implements Table { return 0; } } - + private DirectoryEntry _de; private int _major; private int _minor; @@ -499,24 +499,24 @@ public class CffTable implements Table { _minor = di2.readUnsignedByte(); _hdrSize = di2.readUnsignedByte(); _offSize = di2.readUnsignedByte(); - + // Name INDEX di2 = getDataInputForOffset(_hdrSize); _nameIndex = new NameIndex(di2); - + // Top DICT INDEX _topDictIndex = new TopDictIndex(di2); // String INDEX _stringIndex = new StringIndex(di2); - + // Global Subr INDEX _globalSubrIndex = new Index(di2); - + // Encodings go here -- but since this is an OpenType font will this // not always be a CIDFont? In which case there are no encodings // within the CFF data. - + // Load each of the fonts _charStringsIndexArray = new Index[_topDictIndex.getCount()]; _charsets = new Charset[_topDictIndex.getCount()]; @@ -530,7 +530,7 @@ public class CffTable implements Table { di2 = getDataInputForOffset(charStringsOffset); _charStringsIndexArray[i] = new Index(di2); int glyphCount = _charStringsIndexArray[i].getCount(); - + // Charsets Integer charsetOffset = (Integer) _topDictIndex.getTopDict(i).getValue(15); di2 = getDataInputForOffset(charsetOffset); @@ -563,7 +563,7 @@ public class CffTable implements Table { } } } - + private DataInput getDataInputForOffset(int offset) { return new DataInputStream(new ByteArrayInputStream( _buf, offset, @@ -573,7 +573,7 @@ public class CffTable implements Table { public NameIndex getNameIndex() { return _nameIndex; } - + public Charset getCharset(int fontIndex) { return _charsets[fontIndex]; } @@ -581,7 +581,7 @@ public class CffTable implements Table { public Charstring getCharstring(int fontIndex, int gid) { return _charstringsArray[fontIndex][gid]; } - + public int getCharstringCount(int fontIndex) { return _charstringsArray[fontIndex].length; } @@ -607,7 +607,7 @@ public class CffTable implements Table { } return sb.toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Charstring.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Charstring.java index d411d1e00..01e2d4934 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Charstring.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Charstring.java @@ -28,6 +28,6 @@ package jogamp.graph.font.typecast.ot.table; public abstract class Charstring { public abstract int getIndex(); - + public abstract String getName(); } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java index 9c40a0e5e..93ff60988 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java @@ -28,7 +28,7 @@ import jogamp.graph.font.typecast.ot.table.CffTable; * @author David Schweinsberg */ public class CharstringType2 extends Charstring { - + private static final String[] _oneByteOperators = { "-Reserved-", "hstem", @@ -105,7 +105,7 @@ public class CharstringType2 extends Charstring { "flex1", "-Reserved-" }; - + private int _index; private String _name; private int[] _data; @@ -132,7 +132,7 @@ public class CharstringType2 extends Charstring { _localSubrIndex = localSubrIndex; _globalSubrIndex = globalSubrIndex; } - + public int getIndex() { return _index; } @@ -140,7 +140,7 @@ public class CharstringType2 extends Charstring { public String getName() { return _name; } - + private void disassemble(StringBuilder sb) { Number operand = null; while (isOperandAtIndex()) { @@ -151,7 +151,7 @@ public class CharstringType2 extends Charstring { String mnemonic; if (operator == 12) { operator = nextByte(); - + // Check we're not exceeding the upper limit of our mnemonics if (operator > 38) { operator = 38; @@ -162,7 +162,7 @@ public class CharstringType2 extends Charstring { } sb.append(mnemonic); } - + public void resetIP() { _ip = _offset; } @@ -214,15 +214,15 @@ public class CharstringType2 extends Charstring { return null; } } - + public int nextByte() { return _data[_ip++]; } - + public boolean moreBytes() { return _ip < _offset + _length; } - + public String toString() { StringBuilder sb = new StringBuilder(); resetIP(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDef.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDef.java index 4c2f3decb..21698c76b 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDef.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDef.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat1.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat1.java index 0c99ad66a..1079aeed4 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat1.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat1.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat2.java index 5b7c4d655..59bc7b329 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat2.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat2.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java index 7ce531cd9..62ce5ae4c 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java @@ -58,21 +58,21 @@ import java.io.IOException; * @author David Schweinsberg */ public abstract class CmapFormat { - + public class Range { - + private int _startCode; private int _endCode; - + protected Range(int startCode, int endCode) { _startCode = startCode; _endCode = endCode; } - + public int getStartCode() { return _startCode; } - + public int getEndCode() { return _endCode; } @@ -116,12 +116,12 @@ public abstract class CmapFormat { } public abstract int getRangeCount(); - + public abstract Range getRange(int index) throws ArrayIndexOutOfBoundsException; public abstract int mapCharCode(int charCode); - + public String toString() { return new StringBuilder() .append("format: ") diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat0.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat0.java index e374f82d2..2093158bd 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat0.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat0.java @@ -74,7 +74,7 @@ public class CmapFormat0 extends CmapFormat { public int getRangeCount() { return 1; } - + public Range getRange(int index) throws ArrayIndexOutOfBoundsException { if (index != 0) { throw new ArrayIndexOutOfBoundsException(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat2.java index 319d8c0d0..222c93852 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat2.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat2.java @@ -67,7 +67,7 @@ public class CmapFormat2 extends CmapFormat { int _idRangeOffset; int _arrayIndex; } - + private int[] _subHeaderKeys = new int[256]; private SubHeader[] _subHeaders; private int[] _glyphIndexArray; @@ -75,9 +75,9 @@ public class CmapFormat2 extends CmapFormat { protected CmapFormat2(DataInput di) throws IOException { super(di); _format = 2; - + int pos = 6; - + // Read the subheader keys, noting the highest value, as this will // determine the number of subheaders to read. int highest = 0; @@ -88,7 +88,7 @@ public class CmapFormat2 extends CmapFormat { } int subHeaderCount = highest / 8 + 1; _subHeaders = new SubHeader[subHeaderCount]; - + // Read the subheaders, once again noting the highest glyphIndexArray // index range. int indexArrayOffset = 8 * subHeaderCount + 518; @@ -99,18 +99,18 @@ public class CmapFormat2 extends CmapFormat { sh._entryCount = di.readUnsignedShort(); sh._idDelta = di.readShort(); sh._idRangeOffset = di.readUnsignedShort(); - + // Calculate the offset into the _glyphIndexArray pos += 8; sh._arrayIndex = (pos - 2 + sh._idRangeOffset - indexArrayOffset) / 2; - + // What is the highest range within the glyphIndexArray? highest = Math.max(highest, sh._arrayIndex + sh._entryCount); - + _subHeaders[i] = sh; } - + // Read the glyphIndexArray _glyphIndexArray = new int[highest]; for (int i = 0; i < _glyphIndexArray.length; ++i) { @@ -121,12 +121,12 @@ public class CmapFormat2 extends CmapFormat { public int getRangeCount() { return _subHeaders.length; } - + public Range getRange(int index) throws ArrayIndexOutOfBoundsException { if (index < 0 || index >= _subHeaders.length) { throw new ArrayIndexOutOfBoundsException(); } - + // Find the high-byte (if any) int highByte = 0; if (index != 0) { @@ -137,7 +137,7 @@ public class CmapFormat2 extends CmapFormat { } } } - + return new Range( highByte | _subHeaders[index]._firstCode, highByte | (_subHeaders[index]._firstCode + @@ -145,7 +145,7 @@ public class CmapFormat2 extends CmapFormat { } public int mapCharCode(int charCode) { - + // Get the appropriate subheader int index = 0; int highByte = charCode >> 8; @@ -153,14 +153,14 @@ public class CmapFormat2 extends CmapFormat { index = _subHeaderKeys[highByte] / 8; } SubHeader sh = _subHeaders[index]; - + // Is the charCode out-of-range? int lowByte = charCode & 0xff; if (lowByte < sh._firstCode || lowByte >= (sh._firstCode + sh._entryCount)) { return 0; } - + // Now calculate the glyph index int glyphIndex = _glyphIndexArray[sh._arrayIndex + (lowByte - sh._firstCode)]; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java index c09bdc8c3..ef65867af 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java @@ -102,7 +102,7 @@ public class CmapFormat4 extends CmapFormat { for (int i = 0; i < count; i++) { _glyphIdArray[i] = di.readUnsignedShort(); } // + 2*count (8*segCount + 2*count + 18) - + // Are there any padding bytes we need to consume? // int leftover = length - (8*segCount + 2*count + 18); // if (leftover > 0) { @@ -113,7 +113,7 @@ public class CmapFormat4 extends CmapFormat { public int getRangeCount() { return _segCount; } - + public Range getRange(int index) throws ArrayIndexOutOfBoundsException { if (index < 0 || index >= _segCount) { throw new ArrayIndexOutOfBoundsException(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat6.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat6.java index a58531d11..a22e33244 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat6.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat6.java @@ -67,7 +67,7 @@ public class CmapFormat6 extends CmapFormat { protected CmapFormat6(DataInput di) throws IOException { super(di); _format = 6; - + // HACK: As this is not yet implemented, we need to skip over the bytes // we should be consuming //di.skipBytes(_length - 4); @@ -76,7 +76,7 @@ public class CmapFormat6 extends CmapFormat { public int getRangeCount() { return 0; } - + public Range getRange(int index) throws ArrayIndexOutOfBoundsException { throw new ArrayIndexOutOfBoundsException(); } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormatUnknown.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormatUnknown.java index 83366b593..3544b6f62 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormatUnknown.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormatUnknown.java @@ -30,12 +30,12 @@ import java.io.IOException; * @version $Id: CmapFormatUnknown.java,v 1.1 2004-12-21 10:21:23 davidsch Exp $ */ public class CmapFormatUnknown extends CmapFormat { - + /** Creates a new instance of CmapFormatUnknown */ protected CmapFormatUnknown(int format, DataInput di) throws IOException { super(di); _format = format; - + // We don't know how to handle this data, so we'll just skip over it di.skipBytes(_length - 4); } @@ -43,7 +43,7 @@ public class CmapFormatUnknown extends CmapFormat { public int getRangeCount() { return 0; } - + public Range getRange(int index) throws ArrayIndexOutOfBoundsException { throw new ArrayIndexOutOfBoundsException(); } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java index 85fdf7225..47f6c470d 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java @@ -85,7 +85,7 @@ public class CmapIndexEntry implements Comparable { public CmapFormat getFormat() { return _format; } - + public void setFormat(CmapFormat format) { _format = format; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java index 0050fdd8e..016efa093 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java @@ -94,7 +94,7 @@ public class CmapTable implements Table { } else if (_entries[i].getOffset() > bytesRead) { di.skipBytes(_entries[i].getOffset() - (int) bytesRead); } else if (_entries[i].getOffset() != bytesRead) { - + // Something is amiss throw new IOException(); } @@ -109,15 +109,15 @@ public class CmapTable implements Table { public int getVersion() { return _version; } - + public int getNumTables() { return _numTables; } - + public CmapIndexEntry getCmapIndexEntry(int i) { return _entries[i]; } - + public CmapFormat getCmapFormat(short platformId, short encodingId) { // Find the requested format @@ -148,7 +148,7 @@ public class CmapTable implements Table { // } return sb.toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Coverage.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Coverage.java index e85fadb5e..4f526f51d 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Coverage.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Coverage.java @@ -68,7 +68,7 @@ public abstract class Coverage { * can't be found. */ public abstract int findGlyph(int glyphId); - + protected static Coverage read(DataInput di) throws IOException { Coverage c = null; int format = di.readUnsignedShort(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java index 963163584..867ef1823 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -47,7 +47,7 @@ public class CvtTable implements Table { } return sb.toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -57,5 +57,5 @@ public class CvtTable implements Table { public DirectoryEntry getDirectoryEntry() { return de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Device.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Device.java index 6b4af6908..5451f4502 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Device.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Device.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java index c98f03fe9..7abcec0ce 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java @@ -70,7 +70,7 @@ public class DirectoryEntry implements Cloneable { _offset = di.readInt(); _length = di.readInt(); } - + public Object clone() { try { return super.clone(); @@ -103,7 +103,7 @@ public class DirectoryEntry implements Cloneable { .append((char)((_tag)&0xff)) .toString(); } - + public String toString() { return new StringBuilder() .append("'").append(getTagAsString()) diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigEntry.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigEntry.java index 4b41f451d..4a09a4c34 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigEntry.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigEntry.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -21,7 +21,7 @@ public class DsigEntry { private int format; private int length; private int offset; - + /** Creates new DsigEntry */ protected DsigEntry(DataInput di) throws IOException { format = di.readInt(); @@ -32,11 +32,11 @@ public class DsigEntry { public int getFormat() { return format; } - + public int getLength() { return length; } - + public int getOffset() { return offset; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java index e2784f9e6..f25c595d0 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -48,7 +48,7 @@ public class DsigTable implements Table { public int getType() { return DSIG; } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -58,7 +58,7 @@ public class DsigTable implements Table { public DirectoryEntry getDirectoryEntry() { return de; } - + public String toString() { StringBuilder sb = new StringBuilder().append("DSIG\n"); for (int i = 0; i < numSigs; i++) { diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureList.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureList.java index 3cfb54a38..fdedca94a 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureList.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureList.java @@ -66,11 +66,11 @@ public class FeatureList { /** Creates new FeatureList */ public FeatureList(DataInputStream dis, int offset) throws IOException { - + // Ensure we're in the right place dis.reset(); dis.skipBytes(offset); - + // Start reading _featureCount = dis.readUnsignedShort(); _featureRecords = new FeatureRecord[_featureCount]; @@ -88,11 +88,11 @@ public class FeatureList { public int getFeatureCount() { return _featureCount; } - + public FeatureRecord getFeatureRecord(int i) { return _featureRecords[i]; } - + public Feature getFeature(int i) { return _features[i]; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureRecord.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureRecord.java index eb610814b..1da74f4d5 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureRecord.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureRecord.java @@ -72,7 +72,7 @@ public class FeatureRecord { public int getTag() { return _tag; } - + public int getOffset() { return _offset; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FpgmTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FpgmTable.java index 9a6000156..b662265d9 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FpgmTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FpgmTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -33,7 +33,7 @@ public class FpgmTable extends Program implements Table { public String toString() { return Disassembler.disassemble(getInstructions(), 0); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -43,5 +43,5 @@ public class FpgmTable extends Program implements Table { public DirectoryEntry getDirectoryEntry() { return de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java index 2748406df..cf4afa88e 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -20,10 +20,10 @@ public class GaspRange { public static final int GASP_GRIDFIT = 1; public static final int GASP_DOGRAY = 2; - + private int rangeMaxPPEM; private int rangeGaspBehavior; - + /** Creates new GaspRange */ protected GaspRange(DataInput di) throws IOException { rangeMaxPPEM = di.readUnsignedShort(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java index a83db5bff..45498eda1 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -22,7 +22,7 @@ public class GaspTable implements Table { private int version; private int numRanges; private GaspRange[] gaspRange; - + /** Creates new GaspTable */ protected GaspTable(DirectoryEntry de, DataInput di) throws IOException { this.de = (DirectoryEntry) de.clone(); @@ -49,7 +49,7 @@ public class GaspTable implements Table { } return sb.toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -59,5 +59,5 @@ public class GaspTable implements Table { public DirectoryEntry getDirectoryEntry() { return de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfCompositeDescript.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfCompositeDescript.java index 4cf254198..50f62ed62 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfCompositeDescript.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfCompositeDescript.java @@ -73,7 +73,7 @@ public class GlyfCompositeDescript extends GlyfDescript { int glyphIndex, DataInput di) throws IOException { super(parentTable, glyphIndex, (short) -1, di); - + // Get all of the composite components GlyfCompositeComp comp; int firstIndex = 0; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java index a9342a434..a7e2e7b69 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java @@ -111,7 +111,7 @@ public abstract class GlyfDescript extends Program implements GlyphDescription { public short getYMinimum() { return _yMin; } - + public String toString() { return new StringBuilder() .append(" numberOfContours: ").append(_numberOfContours) diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java index c11d2d8ff..f67162cff 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java @@ -73,7 +73,7 @@ public class GlyfSimpleDescript extends GlyfDescript { short numberOfContours, DataInput di) throws IOException { super(parentTable, glyphIndex, numberOfContours, di); - + // Simple glyph description _endPtsOfContours = new int[numberOfContours]; for (int i = 0; i < numberOfContours; i++) { @@ -184,7 +184,7 @@ public class GlyfSimpleDescript extends GlyfDescript { System.out.println("error: array index out of bounds"); } } - + public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfTable.java index 22fdd8886..34a8218d9 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfTable.java @@ -71,12 +71,12 @@ public class GlyfTable implements Table { LocaTable loca) throws IOException { _de = (DirectoryEntry) de.clone(); _descript = new GlyfDescript[maxp.getNumGlyphs()]; - + // Buffer the whole table so we can randomly access it byte[] buf = new byte[de.getLength()]; di.readFully(buf); ByteArrayInputStream bais = new ByteArrayInputStream(buf); - + // Process all the simple glyphs for (int i = 0; i < maxp.getNumGlyphs(); i++) { int len = loca.getOffset(i + 1) - loca.getOffset(i); @@ -119,7 +119,7 @@ public class GlyfTable implements Table { public int getType() { return glyf; } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyphDescription.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyphDescription.java index 106e17917..025778dfc 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyphDescription.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyphDescription.java @@ -56,29 +56,29 @@ package jogamp.graph.font.typecast.ot.table; * @author David Schweinsberg */ public interface GlyphDescription { - + public int getGlyphIndex(); - + public int getEndPtOfContours(int i); - + public byte getFlags(int i); - + public short getXCoordinate(int i); - + public short getYCoordinate(int i); - + public short getXMaximum(); - + public short getXMinimum(); - + public short getYMaximum(); - + public short getYMinimum(); - + public boolean isComposite(); - + public int getPointCount(); - + public int getContourCount(); // public int getComponentIndex(int c); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GposTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GposTable.java index 91a62362a..9a367412d 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GposTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GposTable.java @@ -48,7 +48,7 @@ public class GposTable implements Table { public int getType() { return GPOS; } - + public String toString() { return "GPOS"; } @@ -62,5 +62,5 @@ public class GposTable implements Table { public DirectoryEntry getDirectoryEntry() { return _de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GsubTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GsubTable.java index c002de374..0351c903d 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GsubTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GsubTable.java @@ -66,10 +66,10 @@ public class GsubTable implements Table, LookupSubtableFactory { private ScriptList _scriptList; private FeatureList _featureList; private LookupList _lookupList; - + protected GsubTable(DirectoryEntry de, DataInput di) throws IOException { _de = (DirectoryEntry) de.clone(); - + // Load into a temporary buffer, and create another input stream byte[] buf = new byte[de.getLength()]; di.readFully(buf); @@ -86,17 +86,17 @@ public class GsubTable implements Table, LookupSubtableFactory { // Feature List _featureList = new FeatureList(dis, featureListOffset); - + // Lookup List _lookupList = new LookupList(dis, lookupListOffset, this); } /** - * 1 - Single - Replace one glyph with one glyph - * 2 - Multiple - Replace one glyph with more than one glyph - * 3 - Alternate - Replace one glyph with one of many glyphs - * 4 - Ligature - Replace multiple glyphs with one glyph - * 5 - Context - Replace one or more glyphs in context + * 1 - Single - Replace one glyph with one glyph + * 2 - Multiple - Replace one glyph with more than one glyph + * 3 - Alternate - Replace one glyph with one of many glyphs + * 4 - Ligature - Replace multiple glyphs with one glyph + * 5 - Context - Replace one or more glyphs in context * 6 - Chaining - Context Replace one or more glyphs in chained context */ public LookupSubtable read( @@ -167,7 +167,7 @@ public class GsubTable implements Table, LookupSubtableFactory { } return "Unknown"; } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -177,5 +177,5 @@ public class GsubTable implements Table, LookupSubtableFactory { public DirectoryEntry getDirectoryEntry() { return _de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java index 5b1fa2020..42f9bf0d0 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java @@ -30,9 +30,9 @@ import java.io.IOException; * @version $Id: HdmxTable.java,v 1.2 2007-07-26 11:12:30 davidsch Exp $ */ public class HdmxTable implements Table { - + public class DeviceRecord { - + private short _pixelSize; private short _maxWidth; private short[] _widths; @@ -49,11 +49,11 @@ public class HdmxTable implements Table { public short getPixelSize() { return _pixelSize; } - + public short getMaxWidth() { return _maxWidth; } - + public short[] getWidths() { return _widths; } @@ -61,9 +61,9 @@ public class HdmxTable implements Table { public short getWidth(int glyphidx) { return _widths[glyphidx]; } - + } - + private DirectoryEntry _de; private int _version; private short _numRecords; @@ -78,7 +78,7 @@ public class HdmxTable implements Table { _numRecords = di.readShort(); _sizeDeviceRecords = di.readInt(); _records = new DeviceRecord[_numRecords]; - + // Read the device records for (int i = 0; i < _numRecords; ++i) { _records[i] = new DeviceRecord(maxp.getNumGlyphs(), di); @@ -88,15 +88,15 @@ public class HdmxTable implements Table { public int getNumberOfRecords() { return _numRecords; } - + public DeviceRecord getRecord(int i) { return _records[i]; } - + public int getType() { return hdmx; } - + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'hdmx' Table - Horizontal Device Metrics\n----------------------------------------\n"); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java index 9d7fe4251..cf7c58449 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java @@ -192,7 +192,7 @@ public class HeadTable implements Table { .append("\n glyphDataFormat: ").append(_glyphDataFormat) .toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -202,5 +202,5 @@ public class HeadTable implements Table { public DirectoryEntry getDirectoryEntry() { return _de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java index 20a21e4d9..0278929f1 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -122,7 +122,7 @@ public class HheaTable implements Table { .append("\n numOf_LongHorMetrics: ").append(numberOfHMetrics) .toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -132,5 +132,5 @@ public class HheaTable implements Table { public DirectoryEntry getDirectoryEntry() { return de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ID.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ID.java index 9fd66e728..eed8c1841 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ID.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ID.java @@ -38,7 +38,7 @@ public abstract class ID { public static final short encodingUnicode11Semantics = 1; public static final short encodingISO10646Semantics = 2; public static final short encodingUnicode20Semantics = 3; - + // Microsoft Encoding IDs // public static final short encodingUndefined = 0; // public static final short encodingUGL = 1; @@ -203,7 +203,7 @@ public abstract class ID { public static String getEncodingName(short platformId, short encodingId) { if (platformId == platformUnicode) { - + // Unicode specific encodings switch (encodingId) { case encodingUnicode10Semantics: return "Unicode 1.0 semantics"; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtable.java index 7a4cccba2..04fd646a7 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -21,7 +21,7 @@ public abstract class KernSubtable { /** Creates new KernSubtable */ protected KernSubtable() { } - + public abstract int getKerningPairCount(); public abstract KerningPair getKerningPair(int i); @@ -32,7 +32,7 @@ public abstract class KernSubtable { int length = di.readUnsignedShort(); int coverage = di.readUnsignedShort(); int format = coverage >> 8; - + switch (format) { case 0: table = new KernSubtableFormat0(di); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat0.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat0.java index b55bef6d5..89e6f9f11 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat0.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat0.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -17,7 +17,7 @@ import java.io.IOException; * @version $Id: KernSubtableFormat0.java,v 1.1.1.1 2004-12-05 23:14:48 davidsch Exp $ */ public class KernSubtableFormat0 extends KernSubtable { - + private int nPairs; private int searchRange; private int entrySelector; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat2.java index 60d584ca6..6f5e1f5e8 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat2.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat2.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernTable.java index 70aee70d2..1d526865a 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -17,7 +17,7 @@ import java.io.IOException; * @version $Id: KernTable.java,v 1.1.1.1 2004-12-05 23:14:48 davidsch Exp $ */ public class KernTable implements Table { - + private DirectoryEntry de; private int version; private int nTables; @@ -37,7 +37,7 @@ public class KernTable implements Table { public int getSubtableCount() { return nTables; } - + public KernSubtable getSubtable(int i) { return tables[i]; } @@ -58,5 +58,5 @@ public class KernTable implements Table { public DirectoryEntry getDirectoryEntry() { return de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KerningPair.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KerningPair.java index ce7cebc97..52f82cc85 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KerningPair.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KerningPair.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSys.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSys.java index 6759208f5..1ab112a78 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSys.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSys.java @@ -64,7 +64,7 @@ public class LangSys { private int _reqFeatureIndex; private int _featureCount; private int[] _featureIndex; - + /** Creates new LangSys */ protected LangSys(DataInput di) throws IOException { _lookupOrder = di.readUnsignedShort(); @@ -75,19 +75,19 @@ public class LangSys { _featureIndex[i] = di.readUnsignedShort(); } } - + public int getLookupOrder() { return _lookupOrder; } - + public int getReqFeatureIndex() { return _reqFeatureIndex; } - + public int getFeatureCount() { return _featureCount; } - + public int getFeatureIndex(int i) { return _featureIndex[i]; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSysRecord.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSysRecord.java index 9511f66ba..f3befe3b6 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSysRecord.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSysRecord.java @@ -62,7 +62,7 @@ public class LangSysRecord { private int _tag; private int _offset; - + /** Creates new LangSysRecord */ public LangSysRecord(DataInput di) throws IOException { _tag = di.readInt(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Ligature.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Ligature.java index d3e2ad5cd..de862a983 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Ligature.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Ligature.java @@ -73,11 +73,11 @@ public class Ligature { _components[i] = di.readUnsignedShort(); } } - + public int getGlyphCount() { return _compCount; } - + public int getGlyphId(int i) { return (i == 0) ? _ligGlyph : _components[i-1]; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LigatureSubstFormat1.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LigatureSubstFormat1.java index a0f42662c..cad5e106a 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LigatureSubstFormat1.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LigatureSubstFormat1.java @@ -91,5 +91,5 @@ public class LigatureSubstFormat1 extends LigatureSubst { public String getTypeAsString() { return "LigatureSubstFormat1"; - } + } } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java index 5eb7c5856..ce0862eea 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -64,7 +64,7 @@ public class LocaTable implements Table { } return sb.toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Lookup.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Lookup.java index 2899c24d9..6496c3791 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Lookup.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Lookup.java @@ -79,7 +79,7 @@ public class Lookup { // Ensure we're in the right place dis.reset(); dis.skipBytes(offset); - + // Start reading _type = dis.readUnsignedShort(); _flag = dis.readUnsignedShort(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LookupList.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LookupList.java index a3b71b639..e70a932e4 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LookupList.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LookupList.java @@ -67,11 +67,11 @@ public class LookupList { /** Creates new LookupList */ public LookupList(DataInputStream dis, int offset, LookupSubtableFactory factory) throws IOException { - + // Ensure we're in the right place dis.reset(); dis.skipBytes(offset); - + // Start reading _lookupCount = dis.readUnsignedShort(); _lookupOffsets = new int[_lookupCount]; @@ -87,11 +87,11 @@ public class LookupList { public int getLookupCount() { return _lookupCount; } - + public int getLookupOffset(int i) { return _lookupOffsets[i]; } - + public Lookup getLookup(int i) { return _lookups[i]; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LookupSubtableFactory.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LookupSubtableFactory.java index cb4d28d2c..ca67df7fb 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LookupSubtableFactory.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LookupSubtableFactory.java @@ -47,13 +47,13 @@ Apache Software Foundation, please see . */ - + package jogamp.graph.font.typecast.ot.table; import java.io.DataInputStream; import java.io.IOException; -/** +/** * * @author David Schweinsberg * @version $Id: LookupSubtableFactory.java,v 1.2 2007-01-24 09:47:46 davidsch Exp $ diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java index ace3d38b5..9b0c8e6b4 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -22,7 +22,7 @@ public class LtshTable implements Table { private int version; private int numGlyphs; private int[] yPels; - + /** Creates new LtshTable */ protected LtshTable(DirectoryEntry de, DataInput di) throws IOException { this.de = (DirectoryEntry) de.clone(); @@ -41,7 +41,7 @@ public class LtshTable implements Table { public int getType() { return LTSH; } - + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'LTSH' Table - Linear Threshold Table\n-------------------------------------") @@ -54,7 +54,7 @@ public class LtshTable implements Table { } return sb.toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -64,5 +64,5 @@ public class LtshTable implements Table { public DirectoryEntry getDirectoryEntry() { return de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java index 0e8ec44c7..5ab6b51ca 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -39,7 +39,7 @@ public class MaxpTable implements Table { protected MaxpTable(DirectoryEntry de, DataInput di) throws IOException { this.de = (DirectoryEntry) de.clone(); versionNumber = di.readInt(); - + // CFF fonts use version 0.5, TrueType fonts use version 1.0 if (versionNumber == 0x00005000) { numGlyphs = di.readUnsignedShort(); @@ -149,7 +149,7 @@ public class MaxpTable implements Table { } return sb.toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -159,5 +159,5 @@ public class MaxpTable implements Table { public DirectoryEntry getDirectoryEntry() { return de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java index 268d6cfca..9f9822986 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java @@ -75,19 +75,19 @@ public class NameRecord { _stringLength = di.readShort(); _stringOffset = di.readShort(); } - + public short getEncodingId() { return _encodingId; } - + public short getLanguageId() { return _languageId; } - + public short getNameId() { return _nameId; } - + public short getPlatformId() { return _platformId; } @@ -101,7 +101,7 @@ public class NameRecord { StringBuilder sb = new StringBuilder(); di.skipBytes(_stringOffset); if (_platformId == ID.platformUnicode) { - + // Unicode (big-endian) for (int i = 0; i < _stringLength/2; i++) { sb.append(di.readChar()); @@ -113,13 +113,13 @@ public class NameRecord { sb.append((char) di.readByte()); } } else if (_platformId == ID.platformISO) { - + // ISO encoding, ASCII for (int i = 0; i < _stringLength; i++) { sb.append((char) di.readByte()); } } else if (_platformId == ID.platformMicrosoft) { - + // Microsoft encoding, Unicode char c; for (int i = 0; i < _stringLength/2; i++) { @@ -132,7 +132,7 @@ public class NameRecord { public String toString() { StringBuilder sb = new StringBuilder(); - + sb.append(" Platform ID: ").append(_platformId) .append("\n Specific ID: ").append(_encodingId) .append("\n Language ID: ").append(_languageId) @@ -140,7 +140,7 @@ public class NameRecord { .append("\n Length: ").append(_stringLength) .append("\n Offset: ").append(_stringOffset) .append("\n\n").append(_record); - + return sb.toString(); } } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameTable.java index 6daf2ad60..5b7a17d3b 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameTable.java @@ -68,25 +68,25 @@ public class NameTable implements Table { private short _numberOfNameRecords; private short _stringStorageOffset; private NameRecord[] _records; - + protected NameTable(DirectoryEntry de, DataInput di) throws IOException { _de = (DirectoryEntry) de.clone(); _formatSelector = di.readShort(); _numberOfNameRecords = di.readShort(); _stringStorageOffset = di.readShort(); _records = new NameRecord[_numberOfNameRecords]; - + // Load the records, which contain the encoding information and string // offsets for (int i = 0; i < _numberOfNameRecords; i++) { _records[i] = new NameRecord(di); } - + // Load the string data into a buffer so the records can copy out the // bits they are interested in byte[] buffer = new byte[_de.getLength() - _stringStorageOffset]; di.readFully(buffer); - + // Now let the records get their hands on them for (int i = 0; i < _numberOfNameRecords; i++) { _records[i].loadString( @@ -98,7 +98,7 @@ public class NameTable implements Table { return _numberOfNameRecords; } - + public NameRecord getRecord(int i) { if(_numberOfNameRecords > i) { return _records[i]; @@ -133,7 +133,7 @@ public class NameTable implements Table { public int getType() { return name; } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -143,5 +143,5 @@ public class NameTable implements Table { public DirectoryEntry getDirectoryEntry() { return _de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java index f4fa76e81..9dfbceb99 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java @@ -134,7 +134,7 @@ public class Os2Table implements Table { _usWinDescent = di.readUnsignedShort(); _ulCodePageRange1 = di.readInt(); _ulCodePageRange2 = di.readInt(); - + // OpenType 1.3 if (_version == 2) { _sxHeight = di.readShort(); @@ -276,19 +276,19 @@ public class Os2Table implements Table { public short getXHeight() { return _sxHeight; } - + public short getCapHeight() { return _sCapHeight; } - + public int getDefaultChar() { return _usDefaultChar; } - + public int getBreakChar() { return _usBreakChar; } - + public int getMaxContext() { return _usMaxContext; } @@ -335,7 +335,7 @@ public class Os2Table implements Table { .append("\n CodePage Range 2( Bits 32- 63 ): ").append(Integer.toHexString(_ulCodePageRange2).toUpperCase()) .toString(); } - + private String getVendorIDAsString() { return new StringBuilder() .append((char)((_achVendorID>>24)&0xff)) @@ -344,7 +344,7 @@ public class Os2Table implements Table { .append((char)((_achVendorID)&0xff)) .toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java index 6127140d1..1f6c5a1dd 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -42,11 +42,11 @@ public class Panose { public byte getFamilyType() { return bFamilyType; } - + public byte getSerifStyle() { return bSerifStyle; } - + public byte getWeight() { return bWeight; } @@ -54,31 +54,31 @@ public class Panose { public byte getProportion() { return bProportion; } - + public byte getContrast() { return bContrast; } - + public byte getStrokeVariation() { return bStrokeVariation; } - + public byte getArmStyle() { return bArmStyle; } - + public byte getLetterForm() { return bLetterform; } - + public byte getMidline() { return bMidline; } - + public byte getXHeight() { return bXHeight; } - + public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.valueOf(bFamilyType)).append(" ") diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java index f9dcf2ce7..6ed9b2b9c 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -68,7 +68,7 @@ public class PcltTable implements Table { public int getType() { return PCLT; } - + public String toString() { return new StringBuilder() .append("'PCLT' Table - Printer Command Language Table\n---------------------------------------------") @@ -91,7 +91,7 @@ public class PcltTable implements Table { .append("\n reserved: ").append(reserved) .toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -101,5 +101,5 @@ public class PcltTable implements Table { public DirectoryEntry getDirectoryEntry() { return de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java index c913b4c71..46f1ac088 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -294,7 +294,7 @@ public class PostTable implements Table { private int maxMemType42; private int minMemType1; private int maxMemType1; - + // v2 private int numGlyphs; private int[] glyphNameIndex; @@ -312,7 +312,7 @@ public class PostTable implements Table { maxMemType42 = di.readInt(); minMemType1 = di.readInt(); maxMemType1 = di.readInt(); - + if (version == 0x00020000) { numGlyphs = di.readUnsignedShort(); glyphNameIndex = new int[numGlyphs]; @@ -366,7 +366,7 @@ public class PostTable implements Table { return false; } } - + /** Get the table type, as a table directory value. * @return The table type */ @@ -409,7 +409,7 @@ public class PostTable implements Table { } return sb.toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -419,5 +419,5 @@ public class PostTable implements Table { public DirectoryEntry getDirectoryEntry() { return de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PrepTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PrepTable.java index aac10c539..2046d7fe4 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PrepTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PrepTable.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -33,7 +33,7 @@ public class PrepTable extends Program implements Table { public String toString() { return Disassembler.disassemble(getInstructions(), 0); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a @@ -43,5 +43,5 @@ public class PrepTable extends Program implements Table { public DirectoryEntry getDirectoryEntry() { return de; } - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Program.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Program.java index 28c148c2b..e3beabef8 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Program.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Program.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/RangeRecord.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/RangeRecord.java index 72d703bb4..40ddf4215 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/RangeRecord.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/RangeRecord.java @@ -75,7 +75,7 @@ public class RangeRecord { public boolean isInRange(int glyphId) { return (_start <= glyphId && glyphId <= _end); } - + public int getCoverageIndex(int glyphId) { if (isInRange(glyphId)) { return _startCoverageIndex + glyphId - _start; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Script.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Script.java index eb534b5dd..04781a8f9 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Script.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Script.java @@ -65,14 +65,14 @@ public class Script { private LangSysRecord[] _langSysRecords; private LangSys _defaultLangSys; private LangSys[] _langSys; - + /** Creates new ScriptTable */ protected Script(DataInputStream dis, int offset) throws IOException { // Ensure we're in the right place dis.reset(); dis.skipBytes(offset); - + // Start reading _defaultLangSysOffset = dis.readUnsignedShort(); _langSysCount = dis.readUnsignedShort(); @@ -102,7 +102,7 @@ public class Script { public int getLangSysCount() { return _langSysCount; } - + public LangSysRecord getLangSysRecord(int i) { return _langSysRecords[i]; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptList.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptList.java index 4af62b0ee..18589b712 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptList.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptList.java @@ -63,14 +63,14 @@ public class ScriptList { private int _scriptCount = 0; private ScriptRecord[] _scriptRecords; private Script[] _scripts; - + /** Creates new ScriptList */ protected ScriptList(DataInputStream dis, int offset) throws IOException { - + // Ensure we're in the right place dis.reset(); dis.skipBytes(offset); - + // Start reading _scriptCount = dis.readUnsignedShort(); _scriptRecords = new ScriptRecord[_scriptCount]; @@ -86,15 +86,15 @@ public class ScriptList { public int getScriptCount() { return _scriptCount; } - + public ScriptRecord getScriptRecord(int i) { return _scriptRecords[i]; } - + public Script getScript(int i) { return _scripts[i]; } - + public Script findScript(String tag) { if (tag.length() != 4) { return null; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptRecord.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptRecord.java index 5da0608dd..183ca2ffd 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptRecord.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptRecord.java @@ -62,7 +62,7 @@ public class ScriptRecord { private int _tag; private int _offset; - + /** Creates new ScriptRecord */ protected ScriptRecord(DataInput di) throws IOException { _tag = di.readInt(); @@ -72,7 +72,7 @@ public class ScriptRecord { public int getTag() { return _tag; } - + public int getOffset() { return _offset; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java index 5a5de119f..15f0cd04f 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -22,7 +22,7 @@ public class SignatureBlock { private int reserved2; private int signatureLen; private byte[] signature; - + /** Creates new SignatureBlock */ protected SignatureBlock(DataInput di) throws IOException { reserved1 = di.readUnsignedShort(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubst.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubst.java index 8c56a740f..e31281f2e 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubst.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubst.java @@ -63,7 +63,7 @@ public abstract class SingleSubst extends LookupSubtable { public abstract int getFormat(); public abstract int substitute(int glyphId); - + public static SingleSubst read(DataInputStream dis, int offset) throws IOException { SingleSubst s = null; dis.reset(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat1.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat1.java index 99b85f35c..a8df78504 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat1.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat1.java @@ -84,7 +84,7 @@ public class SingleSubstFormat1 extends SingleSubst { } return glyphId; } - + public String getTypeAsString() { return "SingleSubstFormat1"; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat2.java index cd3b6d147..2e47b2924 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat2.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat2.java @@ -92,6 +92,6 @@ public class SingleSubstFormat2 extends SingleSubst { public String getTypeAsString() { return "SingleSubstFormat2"; - } + } } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TTCHeader.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TTCHeader.java index b801517f8..f7c7d99b5 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TTCHeader.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TTCHeader.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -17,7 +17,7 @@ import java.io.IOException; * @author David Schweinsberg */ public class TTCHeader { - + public static final int ttcf = 0x74746366; private int ttcTag; @@ -47,7 +47,7 @@ public class TTCHeader { public int getDirectoryCount() { return directoryCount; } - + public int getTableDirectory(int i) { return tableDirectory[i]; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Table.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Table.java index 624f47bef..30fd2f457 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Table.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Table.java @@ -1,9 +1,9 @@ /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * - * ------------------------------------------------------------------------- * - * This software is published under the terms of the Apache Software License * - * version 1.1, a copy of which has been included with this distribution in * - * the LICENSE file. * + * ------------------------------------------------------------------------- * + * This software is published under the terms of the Apache Software License * + * version 1.1, a copy of which has been included with this distribution in * + * the LICENSE file. * *****************************************************************************/ package jogamp.graph.font.typecast.ot.table; @@ -51,7 +51,7 @@ public interface Table { public static final int vmtx = 0x766d7478; // Vertical Metrics public static final String notAvailable = "n/a"; - + /** * Get the table type, as a table directory value. * @return The table type @@ -65,5 +65,5 @@ public interface Table { * @return A directory entry */ public DirectoryEntry getDirectoryEntry(); - + } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java index bacc26d30..8c5678088 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java @@ -112,7 +112,7 @@ public class TableDirectory { public int getVersion() { return _version; } - + public String toString() { StringBuilder sb = new StringBuilder() .append("Offset Table\n------ -----") diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableException.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableException.java index 7749ea856..65aa84bff 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableException.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableException.java @@ -26,7 +26,7 @@ package jogamp.graph.font.typecast.ot.table; * @version $Id: TableException.java,v 1.1.1.1 2004-12-05 23:15:00 davidsch Exp $ */ public class TableException extends java.lang.Exception { - + private static final long serialVersionUID = 1L; /** @@ -34,8 +34,8 @@ public class TableException extends java.lang.Exception { */ public TableException() { } - - + + /** * Constructs an instance of TableException with the specified detail message. * @param msg the detail message. diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableFactory.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableFactory.java index 998ce08e3..956d1aecd 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableFactory.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableFactory.java @@ -47,7 +47,7 @@ Apache Software Foundation, please see . */ - + package jogamp.graph.font.typecast.ot.table; import java.io.DataInputStream; @@ -56,7 +56,7 @@ import java.io.IOException; import jogamp.graph.font.typecast.ot.OTFont; import jogamp.graph.font.typecast.ot.OTFontCollection; -/** +/** * * @version $Id: TableFactory.java,v 1.7 2007-02-05 12:39:51 davidsch Exp $ * @author David Schweinsberg @@ -69,7 +69,7 @@ public class TableFactory { DirectoryEntry de, DataInputStream dis) throws IOException { Table t = null; - + // First, if we have a font collection, look for the table there if (fc != null) { t = fc.getTable(de); @@ -77,7 +77,7 @@ public class TableFactory { return t; } } - + // Create the table switch (de.getTag()) { case Table.BASE: @@ -175,7 +175,7 @@ public class TableFactory { t = new VmtxTable(de, dis, font.getVheaTable(), font.getMaxpTable()); break; } - + // If we have a font collection, add this table to it if ((fc != null) && (t != null)) { fc.addTable(t); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java index 80579f5cd..28f9aa6e3 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java @@ -31,12 +31,12 @@ import java.io.IOException; public class VdmxTable implements Table { private class Ratio { - + private byte _bCharSet; private byte _xRatio; private byte _yStartRatio; private byte _yEndRatio; - + protected Ratio(DataInput di) throws IOException { _bCharSet = di.readByte(); _xRatio = di.readByte(); @@ -47,26 +47,26 @@ public class VdmxTable implements Table { public byte getBCharSet() { return _bCharSet; } - + public byte getXRatio() { return _xRatio; } - + public byte getYStartRatio() { return _yStartRatio; } - + public byte getYEndRatio() { return _yEndRatio; } } - + private class VTableRecord { - + private int _yPelHeight; private short _yMax; private short _yMin; - + protected VTableRecord(DataInput di) throws IOException { _yPelHeight = di.readUnsignedShort(); _yMax = di.readShort(); @@ -76,23 +76,23 @@ public class VdmxTable implements Table { public int getYPelHeight() { return _yPelHeight; } - + public short getYMax() { return _yMax; } - + public short getYMin() { return _yMin; } } - + private class Group { - + private int _recs; private int _startsz; private int _endsz; private VTableRecord[] _entry; - + protected Group(DataInput di) throws IOException { _recs = di.readUnsignedShort(); _startsz = di.readUnsignedByte(); @@ -106,20 +106,20 @@ public class VdmxTable implements Table { public int getRecs() { return _recs; } - + public int getStartSZ() { return _startsz; } - + public int getEndSZ() { return _endsz; } - + public VTableRecord[] getEntry() { return _entry; } } - + private DirectoryEntry _de; private int _version; private int _numRecs; @@ -127,7 +127,7 @@ public class VdmxTable implements Table { private Ratio[] _ratRange; private int _offset[]; private Group[] _groups; - + /** Creates a new instance of VdmxTable */ protected VdmxTable(DirectoryEntry de, DataInput di) throws IOException { _de = (DirectoryEntry) de.clone(); @@ -147,11 +147,11 @@ public class VdmxTable implements Table { _groups[i] = new Group(di); } } - + public int getType() { return VDMX; } - + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'VDMX' Table - Precomputed Vertical Device Metrics\n") diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java index 19c91765b..f42da119b 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java @@ -135,7 +135,7 @@ public class VheaTable implements Table { .append("\n numOf_LongVerMetrics: ").append(_numberOfLongVerMetrics) .toString(); } - + /** * Get a directory entry for this table. This uniquely identifies the * table in collections where there may be more than one instance of a diff --git a/src/jogl/classes/jogamp/graph/font/typecast/t2/T2Interpreter.java b/src/jogl/classes/jogamp/graph/font/typecast/t2/T2Interpreter.java index 887f8c34f..181ec7e10 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/t2/T2Interpreter.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/t2/T2Interpreter.java @@ -34,23 +34,23 @@ import jogamp.graph.font.typecast.ot.table.CharstringType2; * @version $Id: T2Interpreter.java,v 1.2 2007-07-26 11:10:18 davidsch Exp $ */ public class T2Interpreter { - + private static final int ARGUMENT_STACK_LIMIT = 48; private static final int SUBR_STACK_LIMIT = 10; private static final int TRANSIENT_ARRAY_ELEMENT_COUNT = 32; - + private Number[] _argStack = new Number[ARGUMENT_STACK_LIMIT]; private int _argStackIndex = 0; private int[] _subrStack = new int[SUBR_STACK_LIMIT]; private int _subrStackIndex = 0; private Number[] _transientArray = new Number[TRANSIENT_ARRAY_ELEMENT_COUNT]; - + private ArrayList _points; /** Creates a new instance of T2Interpreter */ public T2Interpreter() { } - + /** * Moves the current point to a position at the relative coordinates * (dx1, dy1). @@ -72,7 +72,7 @@ public class T2Interpreter { Point lastPoint = getLastPoint(); moveTo(lastPoint.x + dx1, lastPoint.y); } - + /** * Moves the current point dy1 units in the vertical direction. */ @@ -82,7 +82,7 @@ public class T2Interpreter { Point lastPoint = getLastPoint(); moveTo(lastPoint.x, lastPoint.y + dy1); } - + /** * Appends a line from the current point to a position at the * relative coordinates dxa, dya. Additional rlineto operations are @@ -103,7 +103,7 @@ public class T2Interpreter { } clearArg(); } - + /** * Appends a horizontal line of length dx1 to the current point. * With an odd number of arguments, subsequent argument pairs @@ -130,7 +130,7 @@ public class T2Interpreter { } clearArg(); } - + /** * Appends a vertical line of length dy1 to the current point. With * an odd number of arguments, subsequent argument pairs are @@ -157,7 +157,7 @@ public class T2Interpreter { } clearArg(); } - + /** * Appends a Bezier curve, defined by dxa...dyc, to the current * point. For each subsequent set of six arguments, an additional @@ -194,7 +194,7 @@ public class T2Interpreter { } clearArg(); } - + /** * Appends one or more Bezier curves, as described by the * dxa...dxc set of arguments, to the current point. For each curve, @@ -230,7 +230,7 @@ public class T2Interpreter { } clearArg(); } - + /** * Appends one or more Bezier curves to the current point. The * tangent for the first Bezier must be horizontal, and the second @@ -327,13 +327,13 @@ public class T2Interpreter { int yf = ye + dyf[i]; curveTo(xa, ya, xb, yb, xc, yc); curveTo(xd, yd, xe, ye, xf, yf); - + // What on earth do we do with dx1, dx2, dy2 and dy3? } } clearArg(); } - + /** * Is equivalent to one rrcurveto for each set of six arguments * dxa...dyc, followed by exactly one rlineto using the dxd, dyd @@ -373,7 +373,7 @@ public class T2Interpreter { lineTo(xc + dxd, yc + dyd); clearArg(); } - + /** * Is equivalent to one rlineto for each pair of arguments beyond * the six arguments dxb...dyd needed for the one rrcurveto @@ -411,7 +411,7 @@ public class T2Interpreter { curveTo(xb, yb, xc, yc, xd, yd); clearArg(); } - + /** * Appends one or more Bezier curves to the current point, where * the first tangent is vertical and the second tangent is horizontal. @@ -465,7 +465,7 @@ public class T2Interpreter { } clearArg(); } - + /** * Appends one or more curves to the current point. If the argument * count is a multiple of four, the curve starts and ends vertical. If @@ -473,10 +473,10 @@ public class T2Interpreter { * vertical tangent. */ private void _vvcurveto() { - + clearArg(); } - + /** * Causes two Bezier curves, as described by the arguments (as * shown in Figure 2 below), to be rendered as a straight line when @@ -485,10 +485,10 @@ public class T2Interpreter { * pixels. */ private void _flex() { - + clearArg(); } - + /** * Causes the two curves described by the arguments dx1...dx6 to * be rendered as a straight line when the flex depth is less than @@ -496,10 +496,10 @@ public class T2Interpreter { * flex depth is greater than or equal to 0.5 device pixels. */ private void _hflex() { - + clearArg(); } - + /** * Causes the two curves described by the arguments to be * rendered as a straight line when the flex depth is less than 0.5 @@ -507,10 +507,10 @@ public class T2Interpreter { * than or equal to 0.5 device pixels. */ private void _hflex1() { - + clearArg(); } - + /** * Causes the two curves described by the arguments to be * rendered as a straight line when the flex depth is less than 0.5 @@ -518,10 +518,10 @@ public class T2Interpreter { * than or equal to 0.5 device pixels. */ private void _flex1() { - + clearArg(); } - + /** * Finishes a charstring outline definition, and must be the * last operator in a character's outline. @@ -530,37 +530,37 @@ public class T2Interpreter { endContour(); clearArg(); } - + private void _hstem() { - + clearArg(); } - + private void _vstem() { - + clearArg(); } - + private void _hstemhm() { - + clearArg(); } - + private void _vstemhm() { - + clearArg(); } - + private void _hintmask() { - + clearArg(); } - + private void _cntrmask() { - + clearArg(); } - + /** * Returns the absolute value of num. */ @@ -568,7 +568,7 @@ public class T2Interpreter { double num = popArg().doubleValue(); pushArg(Math.abs(num)); } - + /** * Returns the sum of the two numbers num1 and num2. */ @@ -577,7 +577,7 @@ public class T2Interpreter { double num1 = popArg().doubleValue(); pushArg(num1 + num2); } - + /** * Returns the result of subtracting num2 from num1. */ @@ -586,7 +586,7 @@ public class T2Interpreter { double num1 = popArg().doubleValue(); pushArg(num1 - num2); } - + /** * Returns the quotient of num1 divided by num2. The result is * undefined if overflow occurs and is zero for underflow. @@ -596,7 +596,7 @@ public class T2Interpreter { double num1 = popArg().doubleValue(); pushArg(num1 / num2); } - + /** * Returns the negative of num. */ @@ -604,7 +604,7 @@ public class T2Interpreter { double num = popArg().doubleValue(); pushArg(-num); } - + /** * Returns a pseudo random number num2 in the range (0,1], that * is, greater than zero and less than or equal to one. @@ -612,7 +612,7 @@ public class T2Interpreter { private void _random() { pushArg(1.0 - Math.random()); } - + /** * Returns the product of num1 and num2. If overflow occurs, the * result is undefined, and zero is returned for underflow. @@ -622,7 +622,7 @@ public class T2Interpreter { double num1 = popArg().doubleValue(); pushArg(num1 * num2); } - + /** * Returns the square root of num. If num is negative, the result is * undefined. @@ -631,14 +631,14 @@ public class T2Interpreter { double num = popArg().doubleValue(); pushArg(Math.sqrt(num)); } - + /** * Removes the top element num from the Type 2 argument stack. */ private void _drop() { popArg(); } - + /** * Exchanges the top two elements on the argument stack. */ @@ -648,7 +648,7 @@ public class T2Interpreter { pushArg(num2); pushArg(num1); } - + /** * Retrieves the element i from the top of the argument stack and * pushes a copy of that element onto that stack. If i is negative, @@ -666,7 +666,7 @@ public class T2Interpreter { } pushArg(nums[i]); } - + /** * Performs a circular shift of the elements num(Nx1) ... num0 on * the argument stack by the amount J. Positive J indicates upward @@ -685,7 +685,7 @@ public class T2Interpreter { pushArg(nums[(n + i + j) % n]); } } - + /** * Duplicates the top element on the argument stack. */ @@ -694,7 +694,7 @@ public class T2Interpreter { pushArg(any); pushArg(any); } - + /** * Stores val into the transient array at the location given by i. */ @@ -703,7 +703,7 @@ public class T2Interpreter { Number val = popArg(); _transientArray[i] = val; } - + /** * Retrieves the value stored in the transient array at the location * given by i and pushes the value onto the argument stack. If get @@ -714,7 +714,7 @@ public class T2Interpreter { int i = popArg().intValue(); pushArg(_transientArray[i]); } - + /** * Puts a 1 on the stack if num1 and num2 are both non-zero, and * puts a 0 on the stack if either argument is zero. @@ -724,7 +724,7 @@ public class T2Interpreter { double num1 = popArg().doubleValue(); pushArg((num1!=0.0) && (num2!=0.0) ? 1 : 0); } - + /** * Puts a 1 on the stack if either num1 or num2 are non-zero, and * puts a 0 on the stack if both arguments are zero. @@ -734,7 +734,7 @@ public class T2Interpreter { double num1 = popArg().doubleValue(); pushArg((num1!=0.0) || (num2!=0.0) ? 1 : 0); } - + /** * Returns a 0 if num1 is non-zero; returns a 1 if num1 is zero. */ @@ -742,7 +742,7 @@ public class T2Interpreter { double num1 = popArg().doubleValue(); pushArg((num1!=0.0) ? 0 : 1); } - + /** * Puts a 1 on the stack if num1 equals num2, otherwise a 0 (zero) * is put on the stack. @@ -752,7 +752,7 @@ public class T2Interpreter { double num1 = popArg().doubleValue(); pushArg(num1 == num2 ? 1 : 0); } - + /** * Leaves the value s1 on the stack if v1 ? v2, or leaves s2 on the * stack if v1 > v2. The value of s1 and s2 is usually the biased @@ -765,7 +765,7 @@ public class T2Interpreter { Number s1 = popArg(); pushArg(v1 <= v2 ? s1 : s2); } - + /** * Calls a charstring subroutine with index subr# (actually the subr * number plus the subroutine bias number, as described in section @@ -777,25 +777,25 @@ public class T2Interpreter { * Calling an undefined subr (gsubr) has undefined results. */ private void _callsubr() { - + } - + /** * Operates in the same manner as callsubr except that it calls a * global subroutine. */ private void _callgsubr() { - + } - + /** * Returns from either a local or global charstring subroutine, and * continues execution after the corresponding call(g)subr. */ private void _return() { - + } - + public Point[] execute(CharstringType2 cs) { _points = new ArrayList(); cs.resetIP(); @@ -975,7 +975,7 @@ public class T2Interpreter { private int getArgCount() { return _argStackIndex; } - + /** * Pop a value off the argument stack */ @@ -989,7 +989,7 @@ public class T2Interpreter { private void pushArg(Number n) { _argStack[_argStackIndex++] = n; } - + /** * Pop a value off the subroutine stack */ @@ -1003,14 +1003,14 @@ public class T2Interpreter { private void pushSubr(int n) { _subrStack[_subrStackIndex++] = n; } - + /** * Clear the argument stack */ private void clearArg() { _argStackIndex = 0; } - + private Point getLastPoint() { int size = _points.size(); if (size > 0) { @@ -1019,22 +1019,22 @@ public class T2Interpreter { return new Point(0, 0, true, false); } } - + private void moveTo(int x, int y) { endContour(); _points.add(new Point(x, y, true, false)); } - + private void lineTo(int x, int y) { _points.add(new Point(x, y, true, false)); } - + private void curveTo(int cx1, int cy1, int cx2, int cy2, int x, int y) { _points.add(new Point(cx1, cy1, false, false)); _points.add(new Point(cx2, cy2, false, false)); _points.add(new Point(x, y, true, false)); } - + private void endContour() { Point lastPoint = getLastPoint(); if (lastPoint != null) { diff --git a/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Interpreter.java b/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Interpreter.java index a659a7003..2bb5cec0c 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Interpreter.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Interpreter.java @@ -570,7 +570,7 @@ public class Interpreter { private void _mps() { push(0); } - + private void _msirp(short param) { pop(); pop(); @@ -1190,7 +1190,7 @@ public class Interpreter { while (ip < ((ip & 0xffff0000) | parser.getISLength(ip >> 16))) { short opcode = parser.getOpcode(ip); if (inFuncDef) { - + // We're within a function definition, so don't execute the code if (opcode == Mnemonic.ENDF) { inFuncDef = false; diff --git a/src/jogl/classes/jogamp/graph/geom/plane/AffineTransform.java b/src/jogl/classes/jogamp/graph/geom/plane/AffineTransform.java index 0fd174cda..32e2b6a39 100644 --- a/src/jogl/classes/jogamp/graph/geom/plane/AffineTransform.java +++ b/src/jogl/classes/jogamp/graph/geom/plane/AffineTransform.java @@ -33,7 +33,7 @@ public class AffineTransform implements Cloneable, Serializable { private static final long serialVersionUID = 1330973210523860834L; static final String determinantIsZero = "Determinant is zero"; - + public static final int TYPE_IDENTITY = 0; public static final int TYPE_TRANSLATION = 1; public static final int TYPE_UNIFORM_SCALE = 2; @@ -49,14 +49,14 @@ public class AffineTransform implements Cloneable, Serializable { * The TYPE_UNKNOWN is an initial type value */ static final int TYPE_UNKNOWN = -1; - + /** - * The min value equivalent to zero. If absolute value less then ZERO it considered as zero. + * The min value equivalent to zero. If absolute value less then ZERO it considered as zero. */ static final float ZERO = (float) 1E-10; - + private final Vertex.Factory pointFactory; - + /** * The values of transformation matrix */ @@ -68,7 +68,7 @@ public class AffineTransform implements Cloneable, Serializable { float m12; /** - * The transformation type + * The transformation type */ transient int type; @@ -123,20 +123,20 @@ public class AffineTransform implements Cloneable, Serializable { /* * Method returns type of affine transformation. - * + * * Transform matrix is * m00 m01 m02 * m10 m11 m12 - * - * According analytic geometry new basis vectors are (m00, m01) and (m10, m11), - * translation vector is (m02, m12). Original basis vectors are (1, 0) and (0, 1). - * Type transformations classification: + * + * According analytic geometry new basis vectors are (m00, m01) and (m10, m11), + * translation vector is (m02, m12). Original basis vectors are (1, 0) and (0, 1). + * Type transformations classification: * TYPE_IDENTITY - new basis equals original one and zero translation - * TYPE_TRANSLATION - translation vector isn't zero + * TYPE_TRANSLATION - translation vector isn't zero * TYPE_UNIFORM_SCALE - vectors length of new basis equals - * TYPE_GENERAL_SCALE - vectors length of new basis doesn't equal + * TYPE_GENERAL_SCALE - vectors length of new basis doesn't equal * TYPE_FLIP - new basis vector orientation differ from original one - * TYPE_QUADRANT_ROTATION - new basis is rotated by 90, 180, 270, or 360 degrees + * TYPE_QUADRANT_ROTATION - new basis is rotated by 90, 180, 270, or 360 degrees * TYPE_GENERAL_ROTATION - new basis is rotated by arbitrary angle * TYPE_GENERAL_TRANSFORM - transformation can't be inversed */ @@ -322,7 +322,7 @@ public class AffineTransform implements Cloneable, Serializable { } public static AffineTransform getShearInstance(Vertex.Factory factory, float shx, float shy) { - AffineTransform t = new AffineTransform(factory); + AffineTransform t = new AffineTransform(factory); t.setToShear(shx, shy); return t; } @@ -359,13 +359,13 @@ public class AffineTransform implements Cloneable, Serializable { concatenate(AffineTransform.getRotateInstance(pointFactory, angle, px, py)); } - /** + /** * Multiply matrix of two AffineTransform objects. * The first argument's {@link Vertex.Factory} is being used. - * + * * @param t1 - the AffineTransform object is a multiplicand * @param t2 - the AffineTransform object is a multiplier - * @return an AffineTransform object that is a result of t1 multiplied by matrix t2. + * @return an AffineTransform object that is a result of t1 multiplied by matrix t2. */ AffineTransform multiply(AffineTransform t1, AffineTransform t2) { return new AffineTransform(t1.pointFactory, @@ -415,7 +415,7 @@ public class AffineTransform implements Cloneable, Serializable { public void transform(Vertex[] src, int srcOff, Vertex[] dst, int dstOff, int length) { while (--length >= 0) { - Vertex srcPoint = src[srcOff++]; + Vertex srcPoint = src[srcOff++]; float x = srcPoint.getX(); float y = srcPoint.getY(); Vertex dstPoint = dst[dstOff]; @@ -426,7 +426,7 @@ public class AffineTransform implements Cloneable, Serializable { dst[dstOff++] = dstPoint; } } - + public void transform(float[] src, int srcOff, float[] dst, int dstOff, int length) { int step = 2; if (src == dst && srcOff < dstOff && dstOff < srcOff + length * 2) { @@ -443,7 +443,7 @@ public class AffineTransform implements Cloneable, Serializable { dstOff += step; } } - + public Vertex deltaTransform(Vertex src, Vertex dst) { if (dst == null) { dst = pointFactory.create(); @@ -486,7 +486,7 @@ public class AffineTransform implements Cloneable, Serializable { { float det = getDeterminant(); if (FloatUtil.abs(det) < ZERO) { - throw new NoninvertibleTransformException(determinantIsZero); + throw new NoninvertibleTransformException(determinantIsZero); } while (--length >= 0) { @@ -554,7 +554,7 @@ public class AffineTransform implements Cloneable, Serializable { return false; } - + /** * Write AffineTrasform object to the output steam. * @param stream - the output stream @@ -564,12 +564,12 @@ public class AffineTransform implements Cloneable, Serializable { stream.defaultWriteObject(); } - + /** * Read AffineTransform object from the input stream * @param stream - the input steam * @throws IOException - if there are I/O errors while reading from the input strem - * @throws ClassNotFoundException - if class could not be found + * @throws ClassNotFoundException - if class could not be found */ private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); diff --git a/src/jogl/classes/jogamp/graph/geom/plane/Crossing.java b/src/jogl/classes/jogamp/graph/geom/plane/Crossing.java index cd4ee2a91..4ee0c250d 100644 --- a/src/jogl/classes/jogamp/graph/geom/plane/Crossing.java +++ b/src/jogl/classes/jogamp/graph/geom/plane/Crossing.java @@ -29,17 +29,17 @@ public class Crossing { * Allowable tolerance for bounds comparison */ static final float DELTA = (float) 1E-5; - + /** * If roots have distance less then ROOT_DELTA they are double */ static final float ROOT_DELTA = (float) 1E-10; - + /** * Rectangle cross segment */ public static final int CROSSING = 255; - + /** * Unknown crossing result */ @@ -130,8 +130,8 @@ public class Crossing { } /** - * Excludes float roots. Roots are float if they lies enough close with each other. - * @param res - the roots + * Excludes float roots. Roots are float if they lies enough close with each other. + * @param res - the roots * @param rc - the roots count * @return new roots count */ @@ -384,12 +384,12 @@ public class Crossing { // START if (x == x1) { - return x1 < x2 ? 0 : -1; + return x1 < x2 ? 0 : -1; } - + // END if (x == x2) { - return x1 < x2 ? 1 : 0; + return x1 < x2 ? 1 : 0; } // INSIDE-DOWN @@ -493,10 +493,10 @@ public class Crossing { } break; default: - throw new IllegalArgumentException("Unhandled Segment Type: "+segmentType); + throw new IllegalArgumentException("Unhandled Segment Type: "+segmentType); } - - // checks if the point (x,y) is the vertex of shape with PathIterator p + + // checks if the point (x,y) is the vertex of shape with PathIterator p if (x == cx && y == cy) { cross = 0; cy = my; @@ -554,9 +554,9 @@ public class Crossing { } } } - + /** - * Returns are bounds intersect or not intersect rectangle + * Returns are bounds intersect or not intersect rectangle */ static int crossBound(float bound[], int bc, float py1, float py2) { diff --git a/src/jogl/classes/jogamp/graph/geom/plane/Path2D.java b/src/jogl/classes/jogamp/graph/geom/plane/Path2D.java index 945eeceeb..c1ee17a4b 100644 --- a/src/jogl/classes/jogamp/graph/geom/plane/Path2D.java +++ b/src/jogl/classes/jogamp/graph/geom/plane/Path2D.java @@ -33,12 +33,12 @@ public final class Path2D implements Cloneable { static final String invalidWindingRuleValue = "Invalid winding rule value"; static final String iteratorOutOfBounds = "Iterator out of bounds"; - + /** * The buffers size */ private static final int BUFFER_SIZE = 10; - + /** * The buffers capacity */ @@ -48,24 +48,24 @@ public final class Path2D implements Cloneable { * The point's types buffer */ byte[] types; - + /** * The points buffer */ float[] points; - + /** * The point's type buffer size */ int typeSize; - + /** * The points buffer size */ int pointSize; - + /** - * The path rule + * The path rule */ int rule; @@ -80,7 +80,7 @@ public final class Path2D implements Cloneable { 0}; // CLOSE /* - * GeneralPath path iterator + * GeneralPath path iterator */ class Iterator implements PathIterator { @@ -88,17 +88,17 @@ public final class Path2D implements Cloneable { * The current cursor position in types buffer */ int typeIndex; - + /** * The current cursor position in points buffer */ int pointIndex; - + /** * The source GeneralPath object */ Path2D p; - + /** * The path iterator transformation */ @@ -183,7 +183,7 @@ public final class Path2D implements Cloneable { } /** - * Checks points and types buffer size to add pointCount points. If necessary realloc buffers to enlarge size. + * Checks points and types buffer size to add pointCount points. If necessary realloc buffers to enlarge size. * @param pointCount - the point count to be added in buffer */ void checkBuf(int pointCount, boolean checkMove) { @@ -244,18 +244,18 @@ public final class Path2D implements Cloneable { final public int size() { return typeSize; } - + final public boolean isClosed() { return typeSize > 0 && types[typeSize - 1] == PathIterator.SEG_CLOSE ; } - + public void closePath() { if (!isClosed()) { checkBuf(0, true); types[typeSize++] = PathIterator.SEG_CLOSE; } } - + public String toString() { return "[size "+size()+", closed "+isClosed()+"]"; } @@ -295,7 +295,7 @@ public final class Path2D implements Cloneable { closePath(); break; default: - throw new IllegalArgumentException("Unhandled Segment Type: "+segmentType); + throw new IllegalArgumentException("Unhandled Segment Type: "+segmentType); } path.next(); connect = false; @@ -366,9 +366,9 @@ public final class Path2D implements Cloneable { } /** - * Checks cross count according to path rule to define is it point inside shape or not. + * Checks cross count according to path rule to define is it point inside shape or not. * @param cross - the point cross count - * @return true if point is inside path, or false otherwise + * @return true if point is inside path, or false otherwise */ boolean isInside(int cross) { if (rule == WIND_NON_ZERO) { @@ -396,7 +396,7 @@ public final class Path2D implements Cloneable { } public boolean contains(AABBox r) { - return contains(r.getMinX(), r.getMinY(), r.getWidth(), r.getHeight()); + return contains(r.getMinX(), r.getMinY(), r.getWidth(), r.getHeight()); } public boolean intersects(AABBox r) { @@ -404,9 +404,9 @@ public final class Path2D implements Cloneable { } public PathIterator iterator() { - return new Iterator(this); + return new Iterator(this); } - + public PathIterator iterator(AffineTransform t) { return new Iterator(this, t); } diff --git a/src/jogl/classes/jogamp/opengl/Debug.java b/src/jogl/classes/jogamp/opengl/Debug.java index b88a09b71..74892d894 100644 --- a/src/jogl/classes/jogamp/opengl/Debug.java +++ b/src/jogl/classes/jogamp/opengl/Debug.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -51,14 +51,14 @@ public class Debug extends PropertyAccess { // Some common properties private static final boolean verbose; private static final boolean debugAll; - + static { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { PropertyAccess.addTrustedPrefix("jogl."); return null; } } ); - + verbose = isPropertyDefined("jogl.verbose", true); debugAll = isPropertyDefined("jogl.debug", true); if (verbose) { @@ -68,7 +68,7 @@ public class Debug extends PropertyAccess { System.err.println("JOGL implementation vendor " + p.getImplementationVendor()); } } - + /** Ensures static init block has been issues, i.e. if calling through to {@link PropertyAccess#isPropertyDefined(String, boolean)}. */ public static final void initSingleton() {} diff --git a/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLibraryBundleInfo.java index ef9477a31..578f416b7 100644 --- a/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLibraryBundleInfo.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl; import java.util.List; @@ -47,11 +47,11 @@ public abstract class DesktopGLDynamicLibraryBundleInfo extends GLDynamicLibrary public final List getGlueLibNames() { return glueLibNames; } - + @Override public final boolean useToolGetProcAdressFirst(String funcName) { return true; } - + } diff --git a/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLookupHelper.java b/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLookupHelper.java index 8eb3468ed..a1023acd2 100644 --- a/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLookupHelper.java +++ b/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLookupHelper.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl; import com.jogamp.common.os.NativeLibrary; diff --git a/src/jogl/classes/jogamp/opengl/ExtensionAvailabilityCache.java b/src/jogl/classes/jogamp/opengl/ExtensionAvailabilityCache.java index 94acf93b0..b8bcd2e78 100644 --- a/src/jogl/classes/jogamp/opengl/ExtensionAvailabilityCache.java +++ b/src/jogl/classes/jogamp/opengl/ExtensionAvailabilityCache.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -59,7 +59,7 @@ final class ExtensionAvailabilityCache { } /** - * Flush the cache. + * Flush the cache. */ final void flush() { @@ -87,7 +87,7 @@ final class ExtensionAvailabilityCache { validateInitialization(); return availableExtensionCache.size(); } - + final boolean isExtensionAvailable(String glExtensionName) { validateInitialization(); return availableExtensionCache.contains(glExtensionName); @@ -97,7 +97,7 @@ final class ExtensionAvailabilityCache { validateInitialization(); return glXExtensionCount; } - + final String getPlatformExtensionsString() { validateInitialization(); return glXExtensions; @@ -107,7 +107,7 @@ final class ExtensionAvailabilityCache { validateInitialization(); return glExtensionCount; } - + final String getGLExtensionsString() { validateInitialization(); if(DEBUG) { @@ -151,7 +151,7 @@ final class ExtensionAvailabilityCache { ", use "+ ( useGetStringi ? "glGetStringi" : "glGetString" ) ); } - HashSet glExtensionSet = new HashSet(gl.isGLES() ? 50 : 320); // far less gl extension expected on mobile + HashSet glExtensionSet = new HashSet(gl.isGLES() ? 50 : 320); // far less gl extension expected on mobile if(useGetStringi) { GL2GL3 gl2gl3 = gl.getGL2GL3(); final int count; @@ -163,7 +163,7 @@ final class ExtensionAvailabilityCache { StringBuilder sb = new StringBuilder(); for (int i = 0; i < count; i++) { if(i > 0) { - sb.append(" "); + sb.append(" "); } final String ext = gl2gl3.glGetStringi(GL.GL_EXTENSIONS, i); glExtensionSet.add(ext); @@ -185,7 +185,7 @@ final class ExtensionAvailabilityCache { } } } - glExtensionCount = glExtensionSet.size(); + glExtensionCount = glExtensionSet.size(); if (DEBUG) { System.err.println(getThreadName() + ":ExtensionAvailabilityCache: GL_EXTENSIONS: "+glExtensionCount+ ", used "+ ( useGetStringi ? "glGetStringi" : "glGetString" ) ); @@ -193,17 +193,17 @@ final class ExtensionAvailabilityCache { // Platform Extensions HashSet glXExtensionSet = new HashSet(50); - { - // unify platform extension .. might have duplicates + { + // unify platform extension .. might have duplicates StringTokenizer tok = new StringTokenizer(context.getPlatformExtensionsStringImpl().toString()); while (tok.hasMoreTokens()) { - glXExtensionSet.add(tok.nextToken().trim()); + glXExtensionSet.add(tok.nextToken().trim()); } final StringBuilder sb = new StringBuilder(); for(Iterator iter = glXExtensionSet.iterator(); iter.hasNext(); ) { sb.append(iter.next()); if(iter.hasNext()) { - sb.append(" "); + sb.append(" "); } } glXExtensions = sb.toString(); @@ -222,7 +222,7 @@ final class ExtensionAvailabilityCache { final int ctxOptions = context.getCtxOptions(); final VersionNumber version = context.getGLVersionNumber(); int major[] = new int[] { version.getMajor() }; - int minor[] = new int[] { version.getMinor() }; + int minor[] = new int[] { version.getMinor() }; while (GLContext.isValidGLVersion(ctxOptions, major[0], minor[0])) { final String GL_XX_VERSION = ( context.isGLES() ? "GL_ES_VERSION_" : "GL_VERSION_" ) + major[0] + "_" + minor[0]; availableExtensionCache.add(GL_XX_VERSION); diff --git a/src/jogl/classes/jogamp/opengl/FPSCounterImpl.java b/src/jogl/classes/jogamp/opengl/FPSCounterImpl.java index b74ac9f41..c96f7db32 100644 --- a/src/jogl/classes/jogamp/opengl/FPSCounterImpl.java +++ b/src/jogl/classes/jogamp/opengl/FPSCounterImpl.java @@ -41,39 +41,39 @@ public class FPSCounterImpl implements FPSCounter { private long fpsStartTime, fpsLastUpdateTime, fpsLastPeriod, fpsTotalDuration; private int fpsTotalFrames; private float fpsLast, fpsTotal; - + /** Creates a disabled instance */ public FPSCounterImpl() { setUpdateFPSFrames(0, null); } - + /** * Increases total frame count and updates values if feature is enabled and * update interval is reached.
          - * + * * Shall be called by actual FPSCounter implementing renderer, after display a new frame. - * + * */ public final synchronized void tickFPS() { fpsTotalFrames++; if(fpsUpdateFramesInterval>0 && fpsTotalFrames%fpsUpdateFramesInterval == 0) { final long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); fpsLastPeriod = now - fpsLastUpdateTime; - fpsLastPeriod = Math.max(fpsLastPeriod, 1); // div 0 - fpsLast = ( (float)fpsUpdateFramesInterval * 1000f ) / ( (float) fpsLastPeriod ) ; - + fpsLastPeriod = Math.max(fpsLastPeriod, 1); // div 0 + fpsLast = ( (float)fpsUpdateFramesInterval * 1000f ) / ( (float) fpsLastPeriod ) ; + fpsTotalDuration = now - fpsStartTime; fpsTotalDuration = Math.max(fpsTotalDuration, 1); // div 0 fpsTotal= ( (float)fpsTotalFrames * 1000f ) / ( (float) fpsTotalDuration ) ; - + if(null != fpsOutputStream) { fpsOutputStream.println(toString()); } - + fpsLastUpdateTime = now; } } - + public StringBuilder toString(StringBuilder sb) { if(null==sb) { sb = new StringBuilder(); @@ -81,22 +81,22 @@ public class FPSCounterImpl implements FPSCounter { String fpsLastS = String.valueOf(fpsLast); fpsLastS = fpsLastS.substring(0, fpsLastS.indexOf('.') + 2); String fpsTotalS = String.valueOf(fpsTotal); - fpsTotalS = fpsTotalS.substring(0, fpsTotalS.indexOf('.') + 2); + fpsTotalS = fpsTotalS.substring(0, fpsTotalS.indexOf('.') + 2); sb.append(fpsTotalDuration/1000 +" s: "+ fpsUpdateFramesInterval+" f / "+ fpsLastPeriod+" ms, " + fpsLastS+" fps, "+ fpsLastPeriod/fpsUpdateFramesInterval+" ms/f; "+ "total: "+ fpsTotalFrames+" f, "+ fpsTotalS+ " fps, "+ fpsTotalDuration/fpsTotalFrames+" ms/f"); return sb; } - + public String toString() { return toString(null).toString(); } - + public final synchronized void setUpdateFPSFrames(int frames, PrintStream out) { fpsUpdateFramesInterval = frames; fpsOutputStream = out; resetFPSCounter(); } - + public final synchronized void resetFPSCounter() { fpsStartTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // overwrite startTime to real init one fpsLastUpdateTime = fpsStartTime; @@ -109,9 +109,9 @@ public class FPSCounterImpl implements FPSCounter { public final synchronized int getUpdateFPSFrames() { return fpsUpdateFramesInterval; } - - public final synchronized long getFPSStartTime() { - return fpsStartTime; + + public final synchronized long getFPSStartTime() { + return fpsStartTime; } public final synchronized long getLastFPSUpdateTime() { @@ -121,20 +121,20 @@ public class FPSCounterImpl implements FPSCounter { public final synchronized long getLastFPSPeriod() { return fpsLastPeriod; } - + public final synchronized float getLastFPS() { return fpsLast; } - - public final synchronized int getTotalFPSFrames() { - return fpsTotalFrames; + + public final synchronized int getTotalFPSFrames() { + return fpsTotalFrames; } - public final synchronized long getTotalFPSDuration() { - return fpsTotalDuration; + public final synchronized long getTotalFPSDuration() { + return fpsTotalDuration; } - + public final synchronized float getTotalFPS() { return fpsTotal; - } + } } diff --git a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java index f8b453555..bb2983399 100644 --- a/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java +++ b/src/jogl/classes/jogamp/opengl/GLAutoDrawableBase.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl; import java.io.PrintStream; @@ -56,7 +56,7 @@ import com.jogamp.opengl.GLStateKeeper; /** * Abstract common code for GLAutoDrawable implementations. - * + * * @see GLAutoDrawable * @see GLAutoDrawableDelegate * @see GLPBufferImpl @@ -64,10 +64,10 @@ import com.jogamp.opengl.GLStateKeeper; */ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeeper, FPSCounter { public static final boolean DEBUG = GLDrawableImpl.DEBUG; - + protected final GLDrawableHelper helper = new GLDrawableHelper(); protected final FPSCounterImpl fpsCounter = new FPSCounterImpl(); - + protected volatile GLDrawableImpl drawable; // volatile: avoid locking for read-only access protected GLContextImpl context; protected boolean preserveGLELSAtDestroy; @@ -79,9 +79,9 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe protected volatile boolean sendDestroy = false; // volatile: maybe written by WindowManager thread w/o locking /** - * @param drawable upstream {@link GLDrawableImpl} instance, + * @param drawable upstream {@link GLDrawableImpl} instance, * may be null for lazy initialization - * @param context upstream {@link GLContextImpl} instance, + * @param context upstream {@link GLContextImpl} instance, * may not have been made current (created) yet, * may not be associated w/ drawable yet, * may be null for lazy initialization @@ -100,19 +100,19 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe if(null != context && null != drawable) { context.setGLDrawable(drawable, false); } - resetFPSCounter(); + resetFPSCounter(); } - - /** Returns the recursive lock object of the upstream implementation, which synchronizes multithreaded access on top of {@link NativeSurface#lockSurface()}. */ + + /** Returns the recursive lock object of the upstream implementation, which synchronizes multithreaded access on top of {@link NativeSurface#lockSurface()}. */ protected abstract RecursiveLock getLock(); @Override public final GLStateKeeper.Listener setGLStateKeeperListener(Listener l) { final GLStateKeeper.Listener pre = glStateKeeperListener; glStateKeeperListener = l; - return pre; + return pre; } - + @Override public final boolean preserveGLStateAtDestroy(boolean value) { final boolean res = isGLStatePreservationSupported() ? true : false; @@ -125,10 +125,10 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe } return res; } - + @Override public boolean isGLStatePreservationSupported() { return false; } - + @Override public final GLEventListenerState getPreservedGLState() { return glels; @@ -140,20 +140,20 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe glels = null; return r; } - + /** * Pulls the {@link GLEventListenerState} from this {@link GLAutoDrawable}. - * + * * @return true if the {@link GLEventListenerState} is pulled successfully from this {@link GLAutoDrawable}, * otherwise false. - * + * * @throws IllegalStateException if the {@link GLEventListenerState} is already pulled - * + * * @see #pushGLEventListenerState() */ protected final boolean pullGLEventListenerState() throws IllegalStateException { if( null != glels ) { - throw new IllegalStateException("GLEventListenerState already pulled"); + throw new IllegalStateException("GLEventListenerState already pulled"); } if( null != context && context.isCreated() ) { if( null!= glStateKeeperListener) { @@ -164,14 +164,14 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe } return false; } - + /** * Pushes a previously {@link #pullGLEventListenerState() pulled} {@link GLEventListenerState} to this {@link GLAutoDrawable}. - * - * @return true if the {@link GLEventListenerState} was previously {@link #pullGLEventListenerState() pulled} + * + * @return true if the {@link GLEventListenerState} was previously {@link #pullGLEventListenerState() pulled} * and is pushed successfully to this {@link GLAutoDrawable}, * otherwise false. - * + * * @see #pullGLEventListenerState() */ protected final boolean pushGLEventListenerState() { @@ -180,12 +180,12 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe glels = null; if( null!= glStateKeeperListener) { glStateKeeperListener.glStateRestored(this); - } + } return true; } - return false; + return false; } - + /** Default implementation to handle repaint events from the windowing system */ protected final void defaultWindowRepaintOp() { final GLDrawable _drawable = drawable; @@ -195,7 +195,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe } } } - + /** Default implementation to handle resize events from the windowing system. All required locks are being claimed. */ protected final void defaultWindowResizedOp(int newWidth, int newHeight) throws NativeWindowException, GLException { GLDrawableImpl _drawable = drawable; @@ -210,7 +210,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe try { final GLDrawableImpl _drawableNew = GLDrawableHelper.resizeOffscreenDrawable(_drawable, context, newWidth, newHeight); if(_drawable != _drawableNew) { - // write back + // write back _drawable = _drawableNew; drawable = _drawableNew; } @@ -226,15 +226,15 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe } } } - - /** + + /** * Default implementation to handle destroy notifications from the windowing system. - * + * *

          - * If the {@link NativeSurface} does not implement {@link WindowClosingProtocol} + * If the {@link NativeSurface} does not implement {@link WindowClosingProtocol} * or {@link WindowClosingMode#DISPOSE_ON_CLOSE} is enabled (default), * a thread safe destruction is being induced. - *

          + *

          */ protected final void defaultWindowDestroyNotifyOp() { final NativeSurface ns = getNativeSurface(); @@ -243,22 +243,22 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe shallClose = WindowClosingMode.DISPOSE_ON_CLOSE == ((WindowClosingProtocol)ns).getDefaultCloseOperation(); } else { shallClose = true; - } + } if( shallClose ) { destroyAvoidAwareOfLocking(); - } + } } /** - * Calls {@link #destroy()} + * Calls {@link #destroy()} * directly if the following requirements are met: *
            - *
          • An {@link GLAnimatorControl} is bound (see {@link #getAnimator()}) and running on another thread. + *
          • An {@link GLAnimatorControl} is bound (see {@link #getAnimator()}) and running on another thread. * Here we pause the animation while issuing the destruction.
          • *
          • Surface is not locked by another thread (considered anonymous).
          • *
          *

          - * Otherwise destroy is being flagged to be called within the next + * Otherwise destroy is being flagged to be called within the next * call of display(). *

          *

          @@ -270,9 +270,9 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe */ protected final void destroyAvoidAwareOfLocking() { final NativeSurface ns = getNativeSurface(); - + final GLAnimatorControl ctrl = helper.getAnimator(); - + // Is an animator thread perform rendering? if ( helper.isAnimatorStartedOnOtherThread() ) { // Pause animations before initiating safe destroy. @@ -292,7 +292,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe destroy(); } } - + /** * Calls {@link #destroyImplInLock()} while claiming the lock. */ @@ -305,7 +305,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe lock.unlock(); } } - + /** * Default implementation to destroys the drawable and context of this GLAutoDrawable: *

            @@ -323,7 +323,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe pullGLEventListenerState(); } if( null != context ) { - if( context.isCreated() ) { + if( context.isCreated() ) { // Catch dispose GLExceptions by GLEventListener, just 'print' them // so we can continue with the destruction. try { @@ -341,9 +341,9 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe if( ownsDevice ) { device.close(); } - } + } } - + public final void defaultSwapBuffers() throws GLException { final RecursiveLock _lock = getLock(); _lock.lock(); @@ -359,7 +359,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe // // GLAutoDrawable // - + protected final Runnable defaultInitAction = new Runnable() { @Override public final void run() { @@ -397,7 +397,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe _lock.unlock(); } } - + protected final GLEventListener defaultDisposeGLEventListener(GLEventListener listener, boolean remove) { final RecursiveLock _lock = getLock(); _lock.lock(); @@ -405,14 +405,14 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe return helper.disposeGLEventListener(GLAutoDrawableBase.this, drawable, context, listener, remove); } finally { _lock.unlock(); - } + } } - + @Override public final GLDrawable getDelegatedDrawable() { return drawable; } - + @Override public final GLContext getContext() { return context; @@ -458,7 +458,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe @Override public final void addGLEventListener(int index, GLEventListener listener) throws IndexOutOfBoundsException { - helper.addGLEventListener(index, listener); + helper.addGLEventListener(index, listener); } @Override @@ -480,21 +480,21 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe public void setGLEventListenerInitState(GLEventListener listener, boolean initialized) { helper.setGLEventListenerInitState(listener, initialized); } - + @Override public GLEventListener disposeGLEventListener(GLEventListener listener, boolean remove) { return defaultDisposeGLEventListener(listener, remove); } - + @Override public final GLEventListener removeGLEventListener(GLEventListener listener) { - return helper.removeGLEventListener(listener); + return helper.removeGLEventListener(listener); } - + @Override public final void setAnimator(GLAnimatorControl animatorControl) throws GLException { - helper.setAnimator(animatorControl); + helper.setAnimator(animatorControl); } @Override @@ -511,20 +511,20 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe public final Thread getExclusiveContextThread() { return helper.getExclusiveContextThread(); } - + @Override public final boolean invoke(boolean wait, GLRunnable glRunnable) { - return helper.invoke(this, wait, glRunnable); + return helper.invoke(this, wait, glRunnable); } @Override public boolean invoke(final boolean wait, final List glRunnables) { return helper.invoke(this, wait, glRunnables); } - + @Override public final void setAutoSwapBufferMode(boolean enable) { - helper.setAutoSwapBufferMode(enable); + helper.setAutoSwapBufferMode(enable); } @Override @@ -534,7 +534,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe @Override public final void setContextCreationFlags(int flags) { - additionalCtxCreationFlags = flags; + additionalCtxCreationFlags = flags; final GLContext _context = context; if(null != _context) { _context.setContextCreationFlags(additionalCtxCreationFlags); @@ -549,7 +549,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe // // FPSCounter // - + @Override public final void setUpdateFPSFrames(int frames, PrintStream out) { fpsCounter.setUpdateFPSFrames(frames, out); @@ -599,11 +599,11 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe public final float getTotalFPS() { return fpsCounter.getTotalFPS(); } - + // // GLDrawable delegation // - + @Override public final GLContext createContext(final GLContext shareWith) { final RecursiveLock lock = getLock(); @@ -624,10 +624,10 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe public final void setRealized(boolean realized) { final RecursiveLock _lock = getLock(); _lock.lock(); - try { + try { final GLDrawable _drawable = drawable; if( null == _drawable || realized && ( 0 >= _drawable.getWidth() || 0 >= _drawable.getHeight() ) ) { - return; + return; } _drawable.setRealized(realized); if( realized && _drawable.isRealized() ) { @@ -637,7 +637,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe _lock.unlock(); } } - + @Override public final boolean isRealized() { final GLDrawable _drawable = drawable; @@ -661,7 +661,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe final GLDrawable _drawable = drawable; return null != _drawable ? _drawable.isGLOriented() : true; } - + @Override public final GLCapabilitiesImmutable getChosenGLCapabilities() { final GLDrawable _drawable = drawable; @@ -685,7 +685,7 @@ public abstract class GLAutoDrawableBase implements GLAutoDrawable, GLStateKeepe final GLDrawable _drawable = drawable; return null != _drawable ? _drawable.getHandle() : 0; } - + protected static String getThreadName() { return Thread.currentThread().getName(); } @Override diff --git a/src/jogl/classes/jogamp/opengl/GLBufferSizeTracker.java b/src/jogl/classes/jogamp/opengl/GLBufferSizeTracker.java index 17646cc7b..73a864304 100644 --- a/src/jogl/classes/jogamp/opengl/GLBufferSizeTracker.java +++ b/src/jogl/classes/jogamp/opengl/GLBufferSizeTracker.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2006 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 @@ -29,11 +29,11 @@ * 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. */ @@ -93,7 +93,7 @@ public class GLBufferSizeTracker { Debug.initSingleton(); DEBUG = Debug.isPropertyDefined("jogl.debug.GLBufferSizeTracker", true); } - + // Map from buffer names to sizes. // Note: should probably have some way of shrinking this map, but // can't just make it a WeakHashMap because nobody holds on to the @@ -102,7 +102,7 @@ public class GLBufferSizeTracker { // pattern of buffer objects indicates that the fact that this map // never shrinks is probably not that bad. private IntLongHashMap bufferSizeMap; - + public GLBufferSizeTracker() { bufferSizeMap = new IntLongHashMap(); bufferSizeMap.setKeyNotFoundValue(0xFFFFFFFFFFFFFFFFL); diff --git a/src/jogl/classes/jogamp/opengl/GLBufferStateTracker.java b/src/jogl/classes/jogamp/opengl/GLBufferStateTracker.java index f14d16ec4..cd9eea287 100644 --- a/src/jogl/classes/jogamp/opengl/GLBufferStateTracker.java +++ b/src/jogl/classes/jogamp/opengl/GLBufferStateTracker.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2006 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 @@ -29,11 +29,11 @@ * 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. */ @@ -50,7 +50,7 @@ import com.jogamp.common.util.IntIntHashMap; * This class is used to verify that e.g. the vertex * buffer object extension is in use when the glVertexPointer variant * taking a long as argument is called.

            - * + * * Note that because the enumerated value used for the binding of a * buffer object (e.g. GL_ARRAY_BUFFER) is different than that used to * query the binding using glGetIntegerv (e.g. @@ -77,16 +77,16 @@ import com.jogamp.common.util.IntIntHashMap; public class GLBufferStateTracker { protected static final boolean DEBUG; - + static { Debug.initSingleton(); DEBUG = Debug.isPropertyDefined("jogl.debug.GLBufferStateTracker", true); } - + // Maps binding targets to buffer objects. A null value indicates // that the binding is unknown. A zero value indicates that it is - // known that no buffer is bound to the target, according to the - // OpenGL specifications. + // known that no buffer is bound to the target, according to the + // OpenGL specifications. // http://www.opengl.org/sdk/docs/man/xhtml/glBindBuffer.xml private IntIntHashMap bindingMap; @@ -108,7 +108,7 @@ public class GLBufferStateTracker { public final void setBoundBufferObject(int target, int value) { bindingMap.put(target, value); if (DEBUG) { - System.err.println("GLBufferStateTracker.setBoundBufferObject() target 0x" + + System.err.println("GLBufferStateTracker.setBoundBufferObject() target 0x" + Integer.toHexString(target) + " -> mapped bound buffer 0x" + Integer.toHexString(value)); // Thread.dumpStack(); @@ -146,7 +146,7 @@ public class GLBufferStateTracker { value = 0; } if (DEBUG) { - System.err.println("GLBufferStateTracker.getBoundBufferObject() glerr[pre 0x"+Integer.toHexString(glerrPre)+", post 0x"+Integer.toHexString(glerrPost)+"], [queried value]: target 0x" + + System.err.println("GLBufferStateTracker.getBoundBufferObject() glerr[pre 0x"+Integer.toHexString(glerrPre)+", post 0x"+Integer.toHexString(glerrPost)+"], [queried value]: target 0x" + Integer.toHexString(target) + " / query 0x"+Integer.toHexString(queryTarget)+ " -> mapped bound buffer 0x" + Integer.toHexString(value)); } @@ -156,7 +156,7 @@ public class GLBufferStateTracker { return 0; } if (DEBUG) { - System.err.println("GLBufferStateTracker.getBoundBufferObject() [mapped value]: target 0x" + + System.err.println("GLBufferStateTracker.getBoundBufferObject() [mapped value]: target 0x" + Integer.toHexString(target) + " -> mapped bound buffer 0x" + Integer.toHexString(value)); } diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index 7f9f20a21..7c3a5922b 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -106,14 +106,14 @@ public abstract class GLContextImpl extends GLContext { private final GLStateTracker glStateTracker = new GLStateTracker(); private GLDebugMessageHandler glDebugHandler = null; private final int[] boundFBOTarget = new int[] { 0, 0 }; // { draw, read } - private int defaultVAO = 0; - + private int defaultVAO = 0; + protected GLDrawableImpl drawable; protected GLDrawableImpl drawableRead; - + private volatile boolean pixelDataEvaluated; private int /* pixelDataInternalFormat, */ pixelDataFormat, pixelDataType; - + protected GL gl; protected static final Object mappedContextTypeObjectLock; @@ -161,7 +161,7 @@ public abstract class GLContextImpl extends GLContext { glStateTracker.setEnabled(false); glStateTracker.clearStates(); } - + @Override protected void resetStates(boolean isInit) { if( !isInit ) { @@ -177,12 +177,12 @@ public abstract class GLContextImpl extends GLContext { glRenderer = glVendor; glRendererLowerCase = glRenderer; glVersion = glVendor; - + if (boundFBOTarget != null) { // boundFBOTarget[0] = 0; // draw boundFBOTarget[1] = 0; // read } - + pixelDataEvaluated = false; super.resetStates(isInit); @@ -190,7 +190,7 @@ public abstract class GLContextImpl extends GLContext { @Override public final GLDrawable setGLReadDrawable(GLDrawable read) { - if(!isGLReadDrawableAvailable()) { + if(!isGLReadDrawableAvailable()) { throw new GLException("Setting read drawable feature not available"); } final boolean lockHeld = lock.isOwner(Thread.currentThread()); @@ -220,7 +220,7 @@ public abstract class GLContextImpl extends GLContext { final Thread currentThread = Thread.currentThread(); if( lock.isLockedByOtherThread() ) { throw new GLException("GLContext current by other thread "+lock.getOwner().getName()+", operation not allowed on this thread "+currentThread.getName()); - } + } final boolean lockHeld = lock.isOwner(currentThread); if( lockHeld && lock.getHoldCount() > 1 ) { // would need to makeCurrent * holdCount @@ -272,7 +272,7 @@ public abstract class GLContextImpl extends GLContext { } return _gl; } - + @Override public final GL getGL() { return gl; @@ -314,7 +314,7 @@ public abstract class GLContextImpl extends GLContext { @Override public void release() throws GLException { release(false); - } + } private void release(boolean inDestruction) throws GLException { if( TRACE_SWITCH ) { System.err.println(getThreadName() +": GLContext.ContextSwitch[release.0]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+", inDestruction: "+inDestruction+", "+lock); @@ -332,7 +332,7 @@ public abstract class GLContextImpl extends GLContext { } throw new GLException(msg); } - + Throwable drawableContextMadeCurrentException = null; final boolean actualRelease = ( inDestruction || lock.getHoldCount() == 1 ) && 0 != contextHandle; try { @@ -365,7 +365,7 @@ public abstract class GLContextImpl extends GLContext { if(null != drawableContextMadeCurrentException) { throw new GLException("GLContext.release(false) during GLDrawableImpl.contextMadeCurrent(this, false)", drawableContextMadeCurrentException); } - + } private Throwable lastCtxReleaseStack = null; protected abstract void releaseImpl() throws GLException; @@ -518,21 +518,21 @@ public abstract class GLContextImpl extends GLContext { public final int makeCurrent() throws GLException { return makeCurrent(false); } - + protected final int makeCurrent(boolean forceDrawableAssociation) throws GLException { if( TRACE_SWITCH ) { System.err.println(getThreadName() +": GLContext.ContextSwitch[makeCurrent.0]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+" - "+lock); - } + } // Note: the surface is locked within [makeCurrent .. swap .. release] final int lockRes = drawable.lockSurface(); if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { if( DEBUG_TRACE_SWITCH ) { - System.err.println(getThreadName() +": GLContext.ContextSwitch[makeCurrent.X1]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+" - Surface Not Ready - CONTEXT_NOT_CURRENT - "+lock); + System.err.println(getThreadName() +": GLContext.ContextSwitch[makeCurrent.X1]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+" - Surface Not Ready - CONTEXT_NOT_CURRENT - "+lock); } return CONTEXT_NOT_CURRENT; } - + boolean unlockResources = true; // Must be cleared if successful, otherwise finally block will release context and/or surface! int res = CONTEXT_NOT_CURRENT; try { @@ -552,7 +552,7 @@ public abstract class GLContextImpl extends GLContext { drawableUpdatedNotify(); unlockResources = false; // success if( TRACE_SWITCH ) { - System.err.println(getThreadName() +": GLContext.ContextSwitch[makeCurrent.X2]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+" - keep - CONTEXT_CURRENT - "+lock); + System.err.println(getThreadName() +": GLContext.ContextSwitch[makeCurrent.X2]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+" - keep - CONTEXT_CURRENT - "+lock); } return CONTEXT_CURRENT; } else { @@ -561,7 +561,7 @@ public abstract class GLContextImpl extends GLContext { } res = makeCurrentWithinLock(lockRes); unlockResources = CONTEXT_NOT_CURRENT == res; // success ? - + /** * FIXME: refactor dependence on Java 2D / JOGL bridge if ( tracker != null && res == CONTEXT_CURRENT_NEW ) { @@ -608,16 +608,16 @@ public abstract class GLContextImpl extends GLContext { if(TRACE_GL) { gl = gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Trace", null, gl, new Object[] { System.err } ) ); } - + forceDrawableAssociation = true; } - + if( forceDrawableAssociation ) { associateDrawable(true); } - + contextMadeCurrent(true); - + /* FIXME: refactor dependence on Java 2D / JOGL bridge // Try cleaning up any stale server-side OpenGL objects @@ -629,10 +629,10 @@ public abstract class GLContextImpl extends GLContext { } if( TRACE_SWITCH ) { System.err.println(getThreadName() +": GLContext.ContextSwitch[makeCurrent.X3]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+" - switch - "+makeCurrentResultToString(res)+" - stateTracker.on "+glStateTracker.isEnabled()+" - "+lock); - } + } return res; } - + private final int makeCurrentWithinLock(int surfaceLockRes) throws GLException { if (!isCreated()) { if( 0 >= drawable.getWidth() || 0 >= drawable.getHeight() ) { @@ -683,7 +683,7 @@ public abstract class GLContextImpl extends GLContext { final AbstractGraphicsConfiguration config = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice device = config.getScreen().getDevice(); - // Non ARB desktop profiles may not have been registered + // Non ARB desktop profiles may not have been registered if( !GLContext.getAvailableGLVersionsSet(device) ) { // not yet set if( 0 == ( ctxOptions & GLContext.CTX_PROFILE_ES) ) { // not ES profile final int reqMajor; @@ -701,10 +701,10 @@ public abstract class GLContextImpl extends GLContext { GLContext.mapAvailableGLVersion(device, reqMajor, reqProfile, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); GLContext.setAvailableGLVersionsSet(device); - + if (DEBUG) { System.err.println(getThreadName() + ": createContextOLD-MapVersionsAvailable HAVE: " + device+" -> "+reqMajor+"."+reqProfile+ " -> "+getGLVersion()); - } + } } } } @@ -717,17 +717,17 @@ public abstract class GLContextImpl extends GLContext { protected abstract void makeCurrentImpl() throws GLException; /** - * Calls {@link GLDrawableImpl#associateContext(GLContext, boolean)} - */ - protected void associateDrawable(boolean bound) { - drawable.associateContext(this, bound); + * Calls {@link GLDrawableImpl#associateContext(GLContext, boolean)} + */ + protected void associateDrawable(boolean bound) { + drawable.associateContext(this, bound); } - + /** - * Calls {@link GLDrawableImpl#contextMadeCurrent(GLContext, boolean)} - */ + * Calls {@link GLDrawableImpl#contextMadeCurrent(GLContext, boolean)} + */ protected void contextMadeCurrent(boolean current) { - drawable.contextMadeCurrent(this, current); + drawable.contextMadeCurrent(this, current); } /** @@ -827,7 +827,7 @@ public abstract class GLContextImpl extends GLContext { final GLCapabilitiesImmutable glCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); final int[] reqMajorCTP = new int[] { 0, 0 }; getRequestMajorAndCompat(glCaps.getGLProfile(), reqMajorCTP); - + int _major[] = { 0 }; int _minor[] = { 0 }; int _ctp[] = { 0 }; @@ -842,7 +842,7 @@ public abstract class GLContextImpl extends GLContext { } return _ctx; } - + private final boolean mapGLVersions(AbstractGraphicsDevice device) { synchronized (GLContext.deviceVersionAvailable) { final long t0 = ( DEBUG ) ? System.nanoTime() : 0; @@ -854,7 +854,7 @@ public abstract class GLContextImpl extends GLContext { boolean hasGL4 = false; boolean hasGL3 = false; boolean hasES3 = false; - + // Even w/ PROFILE_ALIASING, try to use true core GL profiles // ensuring proper user behavior across platforms due to different feature sets! // @@ -863,7 +863,7 @@ public abstract class GLContextImpl extends GLContext { success |= hasGL4; if(hasGL4) { // Map all lower compatible profiles: GL3 - GLContext.mapAvailableGLVersion(device, 3, CTX_PROFILE_CORE, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); + GLContext.mapAvailableGLVersion(device, 3, CTX_PROFILE_CORE, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); if(PROFILE_ALIASING) { hasGL3 = true; } @@ -874,7 +874,7 @@ public abstract class GLContextImpl extends GLContext { hasGL3 = createContextARBMapVersionsAvailable(3, CTX_PROFILE_CORE); // GL3 success |= hasGL3; if(hasGL3) { - resetStates(false); // clean this context states, since creation was temporary + resetStates(false); // clean this context states, since creation was temporary } } if(!hasGL4bc) { @@ -919,14 +919,14 @@ public abstract class GLContextImpl extends GLContext { hasGL2 = createContextARBMapVersionsAvailable(2, CTX_PROFILE_COMPAT); // GL2 success |= hasGL2; if(hasGL2) { - resetStates(false); // clean this context states, since creation was temporary + resetStates(false); // clean this context states, since creation was temporary } } if(!hasES3) { hasES3 = createContextARBMapVersionsAvailable(3, CTX_PROFILE_ES); // ES3 success |= hasES3; if(hasES3) { - resetStates(false); // clean this context states, since creation was temporary + resetStates(false); // clean this context states, since creation was temporary } } if(success) { @@ -935,7 +935,7 @@ public abstract class GLContextImpl extends GLContext { if(DEBUG) { final long t1 = System.nanoTime(); System.err.println("GLContextImpl.mapGLVersions: "+device+", profileAliasing: "+PROFILE_ALIASING+", total "+(t1-t0)/1e6 +"ms"); - System.err.println(GLContext.dumpAvailableGLVersions(null).toString()); + System.err.println(GLContext.dumpAvailableGLVersions(null).toString()); } } else if (DEBUG) { System.err.println(getThreadName() + ": createContextARB-MapVersions NONE for :"+device); @@ -944,9 +944,9 @@ public abstract class GLContextImpl extends GLContext { } } - /** + /** * Note: Since context creation is temporary, caller need to issue {@link #resetStates(boolean)}, if creation was successful, i.e. returns true. - * This method does not reset the states, allowing the caller to utilize the state variables. + * This method does not reset the states, allowing the caller to utilize the state variables. **/ private final boolean createContextARBMapVersionsAvailable(int reqMajor, int reqProfile) { long _context; @@ -1059,7 +1059,7 @@ public abstract class GLContextImpl extends GLContext { if ( 0 == ctp ) { throw new GLException("Invalid GL Version "+major+"."+minor+", ctp "+toHexString(ctp)); } - + if (!GLContext.isValidGLVersion(ctp, major, minor)) { throw new GLException("Invalid GL Version "+major+"."+minor+", ctp "+toHexString(ctp)); } @@ -1080,10 +1080,10 @@ public abstract class GLContextImpl extends GLContext { if( ctxGLSLVersion.isZero() ) { ctxGLSLVersion = getStaticGLSLVersionNumber(major, minor, ctxOptions); } - } + } } } - + //---------------------------------------------------------------------- // Helpers for various context implementations // @@ -1107,8 +1107,8 @@ public abstract class GLContextImpl extends GLContext { */ return gl; } - - /** + + /** * Finalizes GL instance initialization after this context has been initialized. *

            * Method calls 'void finalizeInit()' of instance 'gl' as retrieved by reflection, if exist. @@ -1138,7 +1138,7 @@ public abstract class GLContextImpl extends GLContext { * ie for GLXExt, EGLExt, .. */ public abstract ProcAddressTable getPlatformExtProcAddressTable(); - + /** * Part of GL_NV_vertex_array_range. *

            @@ -1154,7 +1154,7 @@ public abstract class GLContextImpl extends GLContext { * Provides platform-independent access to the wglFreeMemoryNV / * glXFreeMemoryNV. *

            - */ + */ public abstract void glFreeMemoryNV(ByteBuffer pointer); /** Maps the given "platform-independent" function name to a real function @@ -1195,7 +1195,7 @@ public abstract class GLContextImpl extends GLContext { } } ); } - + private final boolean initGLRendererAndGLVersionStrings() { final GLDynamicLookupHelper glDynLookupHelper = getDrawableImpl().getGLDynamicLookupHelper(); final long _glGetString = glDynLookupHelper.dynamicLookupFunction("glGetString"); @@ -1215,7 +1215,7 @@ public abstract class GLContextImpl extends GLContext { return false; } glVendor = _glVendor; - + final String _glRenderer = glGetStringInt(GL.GL_RENDERER, _glGetString); if(null == _glRenderer) { if(DEBUG) { @@ -1226,7 +1226,7 @@ public abstract class GLContextImpl extends GLContext { } glRenderer = _glRenderer; glRendererLowerCase = glRenderer.toLowerCase(); - + final String _glVersion = glGetStringInt(GL.GL_VERSION, _glGetString); if(null == _glVersion) { // FIXME @@ -1237,7 +1237,7 @@ public abstract class GLContextImpl extends GLContext { return false; } glVersion = _glVersion; - + return true; } } @@ -1251,7 +1251,7 @@ public abstract class GLContextImpl extends GLContext { minor[0] = 0; } } - + /** * Returns null if version string is invalid, otherwise a valid instance. *

            @@ -1278,7 +1278,7 @@ public abstract class GLContextImpl extends GLContext { * version for given arrays. *

            * If the GL query fails, major will be zero. - *

            + *

            *

            * Note: Non ARB ctx is limited to GL 3.0. *

            @@ -1292,20 +1292,20 @@ public abstract class GLContextImpl extends GLContext { if(DEBUG) { Thread.dumpStack(); } - return false; + return false; } else { glGetIntegervInt(GL2GL3.GL_MAJOR_VERSION, glIntMajor, 0, _glGetIntegerv); glGetIntegervInt(GL2GL3.GL_MINOR_VERSION, glIntMinor, 0, _glGetIntegerv); limitNonARBContextVersion(glIntMajor, glIntMinor, ctp); - return true; + return true; } } - + protected final int getCtxOptions() { return ctxOptions; } - + /** * Sets the OpenGL implementation class and * the cache of which GL functions are available for calling through this @@ -1325,8 +1325,8 @@ public abstract class GLContextImpl extends GLContext { *
          • be greater or equal than the requested major.minor version, and
          • *
          • match the ctxProfileBits
          • *
          , otherwise method aborts and returns false. - * @return returns true if successful, otherwise false. See strictMatch. - * If false is returned, no data has been cached or mapped, i.e. ProcAddressTable, Extensions, Version, etc. + * @return returns true if successful, otherwise false. See strictMatch. + * If false is returned, no data has been cached or mapped, i.e. ProcAddressTable, Extensions, Version, etc. * @see #setContextVersion * @see javax.media.opengl.GLContext#CTX_OPTION_ANY * @see javax.media.opengl.GLContext#CTX_PROFILE_COMPAT @@ -1340,7 +1340,7 @@ public abstract class GLContextImpl extends GLContext { if ( 0 < major && !GLContext.isValidGLVersion(ctxProfileBits, major, minor) ) { throw new GLException("Invalid GL Version Request "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); } - + if(null==this.gl || !verifyInstance(gl.getGLProfile(), "Impl", this.gl)) { setGL( createGL( getGLDrawable().getGLProfile() ) ); } @@ -1348,7 +1348,7 @@ public abstract class GLContextImpl extends GLContext { final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); - + { final boolean initGLRendererAndGLVersionStringsOK = initGLRendererAndGLVersionStrings(); if( !initGLRendererAndGLVersionStringsOK ) { @@ -1367,7 +1367,7 @@ public abstract class GLContextImpl extends GLContext { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Given "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); } } - + // // Validate GL version either by GL-Integer or GL-String // @@ -1377,8 +1377,8 @@ public abstract class GLContextImpl extends GLContext { boolean versionValidated = false; boolean versionGL3IntFailed = false; { - // Validate the requested version w/ the GL-version from an integer query. - final int[] glIntMajor = new int[] { 0 }, glIntMinor = new int[] { 0 }; + // Validate the requested version w/ the GL-version from an integer query. + final int[] glIntMajor = new int[] { 0 }, glIntMinor = new int[] { 0 }; final boolean getGLIntVersionOK = getGLIntVersion(glIntMajor, glIntMinor, ctxProfileBits); if( !getGLIntVersionOK ) { final String errMsg = "Fetching GL Integer Version failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null); @@ -1392,14 +1392,14 @@ public abstract class GLContextImpl extends GLContext { // unusable GL context - non query mode - hard fail! throw new GLException(errMsg); } - } + } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (Int): "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); } - + // Only validate if a valid int version was fetched, otherwise cont. w/ version-string method -> 3.0 > Version || Version > MAX! if ( GLContext.isValidGLVersion(ctxProfileBits, glIntMajor[0], glIntMinor[0]) ) { - if( glIntMajor[0] "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); @@ -1415,13 +1415,13 @@ public abstract class GLContextImpl extends GLContext { } } if( !versionValidated ) { - // Validate the requested version w/ the GL-version from the version string. + // Validate the requested version w/ the GL-version from the version string. final VersionNumber setGLVersionNumber = new VersionNumber(major, minor, 0); final VersionNumber strGLVersionNumber = getGLVersionNumber(ctxProfileBits, glVersion); if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (String): "+glVersion+", "+strGLVersionNumber); } - + // Only validate if a valid string version was fetched -> MIN > Version || Version > MAX! if( null != strGLVersionNumber ) { if( strGLVersionNumber.compareTo(setGLVersionNumber) < 0 || 0 == major ) { @@ -1438,7 +1438,7 @@ public abstract class GLContextImpl extends GLContext { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL3 version Int failed, String: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+strGLVersionNumber); } - return false; + return false; } versionValidated = true; } @@ -1447,27 +1447,27 @@ public abstract class GLContextImpl extends GLContext { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, No GL version validation possible: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion); } - return false; + return false; } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: post version verification "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+", strictMatch "+strictMatch+", versionValidated "+versionValidated+", versionGL3IntFailed "+versionGL3IntFailed); } - + if( 2 > major ) { // there is no ES2/3-compat for a profile w/ major < 2 ctxProfileBits &= ~ ( GLContext.CTX_IMPL_ES2_COMPAT | GLContext.CTX_IMPL_ES3_COMPAT ) ; } - + final VersionNumberString vendorVersion = GLVersionNumber.createVendorVersion(glVersion); - + setRendererQuirks(adevice, major, minor, ctxProfileBits, vendorVersion); - + if( strictMatch && glRendererQuirks.exist(GLRendererQuirks.GLNonCompliant) ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL is not compliant: "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)+", "+glRenderer); } return false; } - + if(!isCurrentContextHardwareRasterizer()) { ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT; } @@ -1529,7 +1529,7 @@ public abstract class GLContextImpl extends GLContext { } } } - + if( 0 != ( CTX_PROFILE_ES & ctxProfileBits ) ) { if( major >= 3 ) { ctxProfileBits |= CTX_IMPL_ES3_COMPAT | CTX_IMPL_ES2_COMPAT ; @@ -1550,45 +1550,45 @@ public abstract class GLContextImpl extends GLContext { } else if( hasFBOImpl(major, ctxProfileBits, extensionAvailability) ) { ctxProfileBits |= CTX_IMPL_FBO; } - + if( ( 0 != ( CTX_PROFILE_ES & ctxProfileBits ) && major == 1 ) || isExtensionAvailable(GLExtensions.OES_single_precision) ) { ctxProfileBits |= CTX_IMPL_FP32_COMPAT_API; } - + if(FORCE_NO_FBO_SUPPORT) { ctxProfileBits &= ~CTX_IMPL_FBO ; - } - + } + // // Set GL Version (complete w/ version string) // setContextVersion(major, minor, ctxProfileBits, vendorVersion, true); - + finalizeInit(gl); - + setDefaultSwapInterval(); - + final int glErrX = gl.glGetError(); // clear GL error, maybe caused by above operations - + if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: OK "+contextFQN+" - "+GLContext.getGLVersion(ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions, null)+" - glErr "+toHexString(glErrX)); } return true; } - + private final void setRendererQuirks(final AbstractGraphicsDevice adevice, int major, int minor, int ctp, final VersionNumberString vendorVersion) { int[] quirks = new int[GLRendererQuirks.COUNT + 1]; // + 1 ( NoFullFBOSupport ) int i = 0; - + final String MesaSP = "Mesa "; - // final String MesaRendererAMDsp = " AMD "; - // final String MesaRendererIntelsp = "Intel(R)"; + // final String MesaRendererAMDsp = " AMD "; + // final String MesaRendererIntelsp = "Intel(R)"; final boolean hwAccel = 0 == ( ctp & GLContext.CTX_IMPL_ACCEL_SOFT ); final boolean compatCtx = 0 != ( ctp & GLContext.CTX_PROFILE_COMPAT ); final boolean isDriverMesa = glRenderer.contains(MesaSP) || glRenderer.contains("Gallium "); final boolean isDriverATICatalyst = !isDriverMesa && ( glVendor.contains("ATI Technologies") || glRenderer.startsWith("ATI ") ); final boolean isDriverNVIDIAGeForce = !isDriverMesa && ( glVendor.contains("NVIDIA Corporation") || glRenderer.contains("NVIDIA ") ); - + // // OS related quirks // @@ -1603,7 +1603,7 @@ public abstract class GLContextImpl extends GLContext { } quirks[i++] = quirk; } - + if( isDriverNVIDIAGeForce ) { final VersionNumber osxVersionNVFlushClean = new VersionNumber(10,7,3); // < OSX 10.7.3 w/ NV needs glFlush if( Platform.getOSVersionNumber().compareTo(osxVersionNVFlushClean) < 0 ) { @@ -1622,7 +1622,7 @@ public abstract class GLContextImpl extends GLContext { quirks[i++] = quirk; } } - } else if( Platform.getOSType() == Platform.OSType.WINDOWS ) { + } else if( Platform.getOSType() == Platform.OSType.WINDOWS ) { // // WINDOWS // @@ -1633,28 +1633,28 @@ public abstract class GLContextImpl extends GLContext { } quirks[i++] = quirk; } - + if( isDriverATICatalyst ) { - final VersionNumber winXPVersionNumber = new VersionNumber ( 5, 1, 0); - final VersionNumber amdSafeMobilityVersion = new VersionNumber(12, 102, 3); - + final VersionNumber winXPVersionNumber = new VersionNumber ( 5, 1, 0); + final VersionNumber amdSafeMobilityVersion = new VersionNumber(12, 102, 3); + if ( vendorVersion.compareTo(amdSafeMobilityVersion) < 0 ) { // includes: vendorVersion.isZero() final int quirk = GLRendererQuirks.NeedCurrCtx4ARBCreateContext; if(DEBUG) { System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: OS "+Platform.getOSType()+", [Vendor "+glVendor+" or Renderer "+glRenderer+"], driverVersion "+vendorVersion); } - quirks[i++] = quirk; + quirks[i++] = quirk; } - + if( Platform.getOSVersionNumber().compareTo(winXPVersionNumber) <= 0 ) { final int quirk = GLRendererQuirks.NeedCurrCtx4ARBPixFmtQueries; if(DEBUG) { System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: OS-Version "+Platform.getOSType()+" "+Platform.getOSVersionNumber()+", [Vendor "+glVendor+" or Renderer "+glRenderer+"]"); } - quirks[i++] = quirk; + quirks[i++] = quirk; } } - } else if( Platform.OSType.ANDROID == Platform.getOSType() ) { + } else if( Platform.OSType.ANDROID == Platform.getOSType() ) { // // ANDROID // @@ -1667,7 +1667,7 @@ public abstract class GLContextImpl extends GLContext { quirks[i++] = quirk; } } - + // // Windowing Toolkit related quirks // @@ -1704,8 +1704,8 @@ public abstract class GLContextImpl extends GLContext { } } } - - + + // // RENDERER related quirks // @@ -1735,8 +1735,8 @@ public abstract class GLContextImpl extends GLContext { } if( Platform.getOSType() == Platform.OSType.WINDOWS && glRenderer.contains("SVGA3D") ) { - final VersionNumber mesaSafeFBOVersion = new VersionNumber(8, 0, 0); - if ( vendorVersion.compareTo(mesaSafeFBOVersion) < 0 ) { // includes: vendorVersion.isZero() + final VersionNumber mesaSafeFBOVersion = new VersionNumber(8, 0, 0); + if ( vendorVersion.compareTo(mesaSafeFBOVersion) < 0 ) { // includes: vendorVersion.isZero() final int quirk = GLRendererQuirks.NoFullFBOSupport; if(DEBUG) { System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: OS "+Platform.getOSType() + " / Renderer " + glRenderer + " / Mesa-Version "+vendorVersion); @@ -1745,7 +1745,7 @@ public abstract class GLContextImpl extends GLContext { } } } - + // // Property related quirks // @@ -1754,28 +1754,28 @@ public abstract class GLContextImpl extends GLContext { if(DEBUG) { System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: property"); } - quirks[i++] = quirk; + quirks[i++] = quirk; } - + glRendererQuirks = new GLRendererQuirks(quirks, 0, i); } - + private static final boolean hasFBOImpl(int major, int ctp, ExtensionAvailabilityCache extCache) { return ( 0 != (ctp & CTX_PROFILE_ES) && major >= 2 ) || // ES >= 2.0 - - major >= 3 || // any >= 3.0 GL ctx - + + major >= 3 || // any >= 3.0 GL ctx + ( null != extCache && - + extCache.isExtensionAvailable(GLExtensions.ARB_ES2_compatibility) || // ES 2.0 compatible - + extCache.isExtensionAvailable(GLExtensions.ARB_framebuffer_object) || // ARB_framebuffer_object - + extCache.isExtensionAvailable(GLExtensions.EXT_framebuffer_object) || // EXT_framebuffer_object - - extCache.isExtensionAvailable(GLExtensions.OES_framebuffer_object) ) ; // OES_framebuffer_object excluded + + extCache.isExtensionAvailable(GLExtensions.OES_framebuffer_object) ) ; // OES_framebuffer_object excluded } - + private final void removeCachedVersion(int major, int minor, int ctxProfileBits) { if(!isCurrentContextHardwareRasterizer()) { ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT; @@ -1932,7 +1932,7 @@ public abstract class GLContextImpl extends GLContext { evalPixelDataType(); return pixelDataFormat; } - + private final void evalPixelDataType() { if(!pixelDataEvaluated) { synchronized(this) { @@ -1946,14 +1946,14 @@ public abstract class GLContextImpl extends GLContext { } else */ if( isGLES2Compatible() || isExtensionAvailable(GLExtensions.OES_read_format) ) { final int[] glImplColorReadVals = new int[] { 0, 0 }; gl.glGetIntegerv(GL.GL_IMPLEMENTATION_COLOR_READ_FORMAT, glImplColorReadVals, 0); - gl.glGetIntegerv(GL.GL_IMPLEMENTATION_COLOR_READ_TYPE, glImplColorReadVals, 1); + gl.glGetIntegerv(GL.GL_IMPLEMENTATION_COLOR_READ_TYPE, glImplColorReadVals, 1); // pixelDataInternalFormat = (4 == components) ? GL.GL_RGBA : GL.GL_RGB; pixelDataFormat = glImplColorReadVals[0]; pixelDataType = glImplColorReadVals[1]; ok = 0 != pixelDataFormat && 0 != pixelDataType; } if( !ok ) { - // RGBA read is safe for all GL profiles + // RGBA read is safe for all GL profiles // pixelDataInternalFormat = (4 == components) ? GL.GL_RGBA : GL.GL_RGB; pixelDataFormat=GL.GL_RGBA; pixelDataType = GL.GL_UNSIGNED_BYTE; @@ -1984,54 +1984,54 @@ public abstract class GLContextImpl extends GLContext { public final GLStateTracker getGLStateTracker() { return glStateTracker; } - + //--------------------------------------------------------------------------- // Helpers for context optimization where the last context is left // current on the OpenGL worker thread // - /** + /** * Returns true if the given thread is owner, otherwise false. *

          * Method exists merely for code validation of {@link #isCurrent()}. - *

          + *

          */ public final boolean isOwner(Thread thread) { return lock.isOwner(thread); } - - /** + + /** * Returns true if there are other threads waiting for this GLContext to {@link #makeCurrent()}, otherwise false. *

          * Since method does not perform any synchronization, accurate result are returned if lock is hold - only. - *

          + *

          */ public final boolean hasWaiters() { return lock.getQueueLength()>0; } - - /** + + /** * Returns the number of hold locks. See {@link RecursiveLock#getHoldCount()} for semantics. *

          * Since method does not perform any synchronization, accurate result are returned if lock is hold - only. - *

          + *

          */ public final int getLockCount() { return lock.getHoldCount(); } - + //--------------------------------------------------------------------------- // Special FBO hook // - + /** * Tracks {@link GL#GL_FRAMEBUFFER}, {@link GL2GL3#GL_DRAW_FRAMEBUFFER} and {@link GL2GL3#GL_READ_FRAMEBUFFER} * to be returned via {@link #getBoundFramebuffer(int)}. - * + * *

          Invoked by {@link GL#glBindFramebuffer(int, int)}.

          - * - *

          Assumes valid framebufferName range of [0..{@link Integer#MAX_VALUE}]

          - * + * + *

          Assumes valid framebufferName range of [0..{@link Integer#MAX_VALUE}]

          + * *

          Does not throw an exception if target is unknown or framebufferName invalid.

          */ public final void setBoundFramebuffer(int target, int framebufferName) { @@ -2064,14 +2064,14 @@ public abstract class GLContextImpl extends GLContext { throw new InternalError("Invalid FBO target name: "+toHexString(target)); } } - + @Override - public final int getDefaultDrawFramebuffer() { return drawable.getDefaultDrawFramebuffer(); } + public final int getDefaultDrawFramebuffer() { return drawable.getDefaultDrawFramebuffer(); } @Override - public final int getDefaultReadFramebuffer() { return drawable.getDefaultReadFramebuffer(); } + public final int getDefaultReadFramebuffer() { return drawable.getDefaultReadFramebuffer(); } @Override public final int getDefaultReadBuffer() { return drawable.getDefaultReadBuffer(gl); } - + //--------------------------------------------------------------------------- // GL_ARB_debug_output, GL_AMD_debug_output helpers // @@ -2090,7 +2090,7 @@ public abstract class GLContextImpl extends GLContext { public final int getContextCreationFlags() { return additionalCtxCreationFlags; } - + @Override public final void setContextCreationFlags(int flags) { if(!isCreated()) { @@ -2160,7 +2160,7 @@ public abstract class GLContextImpl extends GLContext { /** Internal bootstraping glGetString(GL_RENDERER) */ private static native String glGetStringInt(int name, long procAddress); - + /** Internal bootstraping glGetIntegerv(..) for version */ private static native void glGetIntegervInt(int pname, int[] params, int params_offset, long procAddress); } diff --git a/src/jogl/classes/jogamp/opengl/GLContextShareSet.java b/src/jogl/classes/jogamp/opengl/GLContextShareSet.java index b7acc0dff..70ade34b7 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextShareSet.java +++ b/src/jogl/classes/jogamp/opengl/GLContextShareSet.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2011 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 @@ -29,11 +29,11 @@ * 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. */ @@ -55,7 +55,7 @@ import javax.media.opengl.GLException; public class GLContextShareSet { private static final boolean DEBUG = GLContextImpl.DEBUG; - + // This class is implemented using a HashMap which maps from all shared contexts // to a share set, containing all shared contexts itself. @@ -74,17 +74,17 @@ public class GLContextShareSet { } else { destroyedShares.put(ctx, dummyValue); } - } + } } public Set getCreatedShares() { return createdShares.keySet(); } - + public Set getDestroyedShares() { return destroyedShares.keySet(); } - + public GLContext getCreatedShare(GLContext ignore) { for (Iterator iter = createdShares.keySet().iterator(); iter.hasNext(); ) { GLContext ctx = iter.next(); @@ -133,9 +133,9 @@ public class GLContextShareSet { addEntry(share1, share); addEntry(share2, share); if (DEBUG) { - System.err.println("GLContextShareSet: registereSharing: 1: " + + System.err.println("GLContextShareSet: registereSharing: 1: " + toHexString(share1.getHandle()) + ", 2: " + toHexString(share2.getHandle())); - } + } } public static synchronized void unregisterSharing(GLContext lastContext) { @@ -155,9 +155,9 @@ public class GLContextShareSet { throw new GLException("Last context's share set contains no destroyed context"); } if (DEBUG) { - System.err.println("GLContextShareSet: unregisterSharing: " + + System.err.println("GLContextShareSet: unregisterSharing: " + toHexString(lastContext.getHandle())+", entries: "+s.size()); - } + } for(Iterator iter = s.iterator() ; iter.hasNext() ; ) { GLContext ctx = iter.next(); if(null == removeEntry(ctx)) { @@ -165,7 +165,7 @@ public class GLContextShareSet { } } } - + private static synchronized Set getCreatedSharedImpl(GLContext context) { if (context == null) { throw new IllegalArgumentException("context is null"); @@ -174,9 +174,9 @@ public class GLContextShareSet { if (share != null) { return share.getCreatedShares(); } - return null; + return null; } - + public static synchronized boolean isShared(GLContext context) { if (context == null) { throw new IllegalArgumentException("context is null"); @@ -184,12 +184,12 @@ public class GLContextShareSet { final ShareSet share = entryFor(context); return share != null; } - + public static synchronized boolean hasCreatedSharedLeft(GLContext context) { final Set s = getCreatedSharedImpl(context); return null != s && s.size()>0 ; } - + /** currently not used .. public static synchronized Set getCreatedShared(GLContext context) { final Set s = getCreatedSharedImpl(context); @@ -198,7 +198,7 @@ public class GLContextShareSet { } return s; } - + public static synchronized Set getDestroyedShared(GLContext context) { if (context == null) { throw new IllegalArgumentException("context is null"); @@ -209,7 +209,7 @@ public class GLContextShareSet { } return share.getDestroyedShares(); } */ - + public static synchronized GLContext getShareContext(GLContext contextToCreate) { ShareSet share = entryFor(contextToCreate); if (share == null) { @@ -262,7 +262,7 @@ public class GLContextShareSet { //---------------------------------------------------------------------- // Internals only below this point - + private static ShareSet entryFor(GLContext context) { return (ShareSet) shareMap.get(context); @@ -276,8 +276,8 @@ public class GLContextShareSet { private static ShareSet removeEntry(GLContext context) { return (ShareSet) shareMap.remove(context); } - + protected static String toHexString(long hex) { return "0x" + Long.toHexString(hex); - } + } } diff --git a/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java b/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java index 9ecaca75d..b770f3b05 100644 --- a/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java +++ b/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java @@ -44,57 +44,57 @@ import com.jogamp.opengl.GLExtensions; /** * The GLDebugMessageHandler, handling GL_ARB_debug_output or GL_AMD_debug_output * debug messages.
          - * + * *

          An instance must be bound to the current thread's GLContext to achieve thread safety.

          - * - *

          A native callback function is registered at {@link #enable(boolean) enable(true)}, - * which forwards received messages to the added {@link GLDebugListener} directly. + * + *

          A native callback function is registered at {@link #enable(boolean) enable(true)}, + * which forwards received messages to the added {@link GLDebugListener} directly. * Hence the {@link GLDebugListener#messageSent(GLDebugMessage)} implementation shall * return as fast as possible.

          - * + * *

          In case no GL_ARB_debug_output is available, but GL_AMD_debug_output, * the messages are translated to ARB {@link GLDebugMessage}, using {@link GLDebugMessage#translateAMDEvent(javax.media.opengl.GLContext, long, int, int, int, String)}.

          */ public class GLDebugMessageHandler { private static final boolean DEBUG = Debug.debug("GLDebugMessageHandler"); - + private static final int EXT_ARB = 1; - private static final int EXT_AMD = 2; - + private static final int EXT_AMD = 2; + static { if ( !initIDs0() ) { throw new NativeWindowException("Failed to initialize GLDebugMessageHandler jmethodIDs"); - } + } } - - private final GLContextImpl ctx; + + private final GLContextImpl ctx; private final ListenerSyncedImplStub listenerImpl; - + // licefycle: init - EOL private String extName; private int extType; private long glDebugMessageCallbackProcAddress; - private boolean extAvailable; + private boolean extAvailable; private boolean synchronous; - + // licefycle: enable - disable/EOL private long handle; - + /** * @param ctx the associated GLContext * @param glDebugExtension chosen extension to use */ - public GLDebugMessageHandler(GLContextImpl ctx) { + public GLDebugMessageHandler(GLContextImpl ctx) { this.ctx = ctx; - this.listenerImpl = new ListenerSyncedImplStub(); + this.listenerImpl = new ListenerSyncedImplStub(); this.glDebugMessageCallbackProcAddress = 0; this.extName = null; this.extType = 0; - this.extAvailable = false; + this.extAvailable = false; this.handle = 0; this.synchronous = true; } - + public void init(boolean enable) { if(DEBUG) { System.err.println("GLDebugMessageHandler.init("+enable+")"); @@ -106,13 +106,13 @@ public class GLDebugMessageHandler { System.err.println("GLDebugMessageHandler.init("+enable+") .. n/a"); } } - + private final long getAddressFor(final ProcAddressTable table, final String functionName) { return AccessController.doPrivileged(new PrivilegedAction() { public Long run() { try { return Long.valueOf( table.getAddressFor(functionName) ); - } catch (IllegalArgumentException iae) { + } catch (IllegalArgumentException iae) { return Long.valueOf(0); } } @@ -124,12 +124,12 @@ public class GLDebugMessageHandler { if( isAvailable()) { return; } - + if( !ctx.isGLDebugEnabled() ) { if(DEBUG) { System.err.println("GLDebugMessageHandler: GL DEBUG not set in ARB ctx options: "+ctx.getGLVersion()); } - return; + return; } if(Platform.OS_TYPE == Platform.OSType.WINDOWS && Platform.is32Bit()) { // Currently buggy, ie. throws an exception after leaving the native callback. @@ -149,93 +149,93 @@ public class GLDebugMessageHandler { if(DEBUG) { System.err.println("GLDebugMessageHandler: Using extension: <"+extName+">"); } - + if(0 == extType) { if(DEBUG) { System.err.println("GLDebugMessageHandler: No extension available! "+ctx.getGLVersion()); System.err.println("GL_EXTENSIONS "+ctx.getGLExtensionCount()); - System.err.println(ctx.getGLExtensionsString()); + System.err.println(ctx.getGLExtensionsString()); } return; } - + final ProcAddressTable procAddressTable = ctx.getGLProcAddressTable(); if( !ctx.isGLES1() && !ctx.isGLES2() ) { switch(extType) { - case EXT_ARB: + case EXT_ARB: glDebugMessageCallbackProcAddress = getAddressFor(procAddressTable, "glDebugMessageCallbackARB"); break; - case EXT_AMD: + case EXT_AMD: glDebugMessageCallbackProcAddress = getAddressFor(procAddressTable, "glDebugMessageCallbackAMD"); break; } } else { glDebugMessageCallbackProcAddress = 0; if(DEBUG) { - System.err.println("Non desktop context not supported"); - } + System.err.println("Non desktop context not supported"); + } } extAvailable = 0 < extType && null != extName && 0 != glDebugMessageCallbackProcAddress; - + if(DEBUG) { System.err.println("GLDebugMessageHandler: extAvailable: "+extAvailable+", glDebugMessageCallback* : 0x"+Long.toHexString(glDebugMessageCallbackProcAddress)); } - + if(!extAvailable) { glDebugMessageCallbackProcAddress = 0; } - + handle = 0; } public final boolean isAvailable() { return extAvailable; } - + /** - * @return The extension implementing the GLDebugMessage feature, - * either {@link #GL_ARB_debug_output} or {@link #GL_AMD_debug_output}. - * If unavailable null is returned. + * @return The extension implementing the GLDebugMessage feature, + * either {@link #GL_ARB_debug_output} or {@link #GL_AMD_debug_output}. + * If unavailable null is returned. */ public final String getExtension() { return extName; } - + public final boolean isExtensionARB() { return extName == GLExtensions.ARB_debug_output; } - + public final boolean isExtensionAMD() { return extName == GLExtensions.AMD_debug_output; } - + /** - * @see javax.media.opengl.GLContext#isGLDebugSynchronous() + * @see javax.media.opengl.GLContext#isGLDebugSynchronous() */ public final boolean isSynchronous() { return synchronous; } - + /** - * @see javax.media.opengl.GLContext#setGLDebugSynchronous(boolean) + * @see javax.media.opengl.GLContext#setGLDebugSynchronous(boolean) */ public final void setSynchronous(boolean synchronous) { this.synchronous = synchronous; if( isEnabled() ) { setSynchronousImpl(); } - } + } private final void setSynchronousImpl() { if(isExtensionARB()) { if(synchronous) { ctx.getGL().glEnable(GL2GL3.GL_DEBUG_OUTPUT_SYNCHRONOUS); } else { ctx.getGL().glDisable(GL2GL3.GL_DEBUG_OUTPUT_SYNCHRONOUS); - } + } if(DEBUG) { System.err.println("GLDebugMessageHandler: synchronous "+synchronous); } } } - + /** - * @see javax.media.opengl.GLContext#enableGLDebugMessage(boolean) + * @see javax.media.opengl.GLContext#enableGLDebugMessage(boolean) */ public final void enable(boolean enable) throws GLException { ctx.validateCurrent(); @@ -243,7 +243,7 @@ public class GLDebugMessageHandler { return; } enableImpl(enable); - } + } final void enableImpl(boolean enable) throws GLException { if(enable) { if(0 == handle) { @@ -257,19 +257,19 @@ public class GLDebugMessageHandler { if(0 != handle) { unregister0(glDebugMessageCallbackProcAddress, handle); handle = 0; - } + } } if(DEBUG) { System.err.println("GLDebugMessageHandler: enable("+enable+") -> 0x" + Long.toHexString(handle)); } } - + public final boolean isEnabled() { return 0 != handle; } - public final int listenerSize() { - return listenerImpl.size(); + public final int listenerSize() { + return listenerImpl.size(); } - + public final void addListener(GLDebugListener listener) { listenerImpl.addListener(-1, listener); } @@ -277,11 +277,11 @@ public class GLDebugMessageHandler { public final void addListener(int index, GLDebugListener listener) { listenerImpl.addListener(index, listener); } - + public final void removeListener(GLDebugListener listener) { listenerImpl.removeListener(listener); } - + private final void sendMessage(GLDebugMessage msg) { synchronized(listenerImpl) { if(DEBUG) { @@ -293,10 +293,10 @@ public class GLDebugMessageHandler { } } } - + public static class StdErrGLDebugListener implements GLDebugListener { boolean threadDump; - + public StdErrGLDebugListener(boolean threadDump) { this.threadDump = threadDump; } @@ -305,13 +305,13 @@ public class GLDebugMessageHandler { if(threadDump) { Thread.dumpStack(); } - } + } } - + // // native -> java // - + protected final void glDebugMessageARB(int source, int type, int id, int severity, String msg) { final GLDebugMessage event = new GLDebugMessage(ctx, System.currentTimeMillis(), source, type, id, severity, msg); sendMessage(event); @@ -321,11 +321,11 @@ public class GLDebugMessageHandler { final GLDebugMessage event = GLDebugMessage.translateAMDEvent(ctx, System.currentTimeMillis(), id, category, severity, msg); sendMessage(event); } - + // // java -> native - // - + // + private static native boolean initIDs0(); private native long register0(long glDebugMessageCallbackProcAddress, int extType); private native void unregister0(long glDebugMessageCallbackProcAddress, long handle); diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java index f5ceb8058..1e4cb38fa 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java @@ -95,14 +95,14 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { } } catch (GLException gle) { if(DEBUG) { - System.err.println("Catched Exception on thread "+getThreadName()); + System.err.println("Catched Exception on thread "+getThreadName()); gle.printStackTrace(); } } return null; } protected abstract SharedResourceRunner.Resource getOrCreateSharedResourceImpl(AbstractGraphicsDevice device); - + /** * Returns the shared context mapped to the device {@link AbstractGraphicsDevice#getConnection()}, * either a pre-existing or newly created, or null if creation failed or not supported.
          @@ -176,7 +176,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(target, true); if(null != ols) { final GLCapabilitiesImmutable chosenCapsMod = GLGraphicsConfigurationUtil.fixOffscreenGLCapabilities(chosenCaps, this, adevice); - + // layered surface -> Offscreen/[FBO|PBuffer] if( !chosenCapsMod.isFBO() && !chosenCapsMod.isPBuffer() ) { throw new GLException("Neither FBO nor Pbuffer is available for "+chosenCapsMod+", "+target); @@ -193,10 +193,10 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { } if( ! ( target instanceof MutableSurface ) ) { throw new IllegalArgumentException("Passed NativeSurface must implement SurfaceChangeable for offscreen layered surface: "+target); - } + } if( chosenCapsMod.isFBO() ) { result = createFBODrawableImpl(target, chosenCapsMod, 0); - } else { + } else { result = createOffscreenDrawableImpl(target); } } else if(chosenCaps.isOnscreen()) { @@ -217,7 +217,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { throw new IllegalArgumentException("Passed NativeSurface must implement MutableSurface for offscreen: "+target); } if( chosenCaps.isFBO() && isFBOAvailable ) { - // need to hook-up a native dummy surface since source may not have & use minimum GLCapabilities for it w/ same profile + // need to hook-up a native dummy surface since source may not have & use minimum GLCapabilities for it w/ same profile final ProxySurface dummySurface = createDummySurfaceImpl(adevice, false, new GLCapabilities(chosenCaps.getGLProfile()), (GLCapabilitiesImmutable)config.getRequestedCapabilities(), null, 64, 64); dummySurface.setUpstreamSurfaceHook(new DelegatedUpstreamSurfaceHookWithSurfaceSize(dummySurface.getUpstreamSurfaceHook(), target)); result = createFBODrawableImpl(dummySurface, chosenCaps, 0); @@ -245,7 +245,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { // // PBuffer Offscreen GLAutoDrawable construction // - + @Override public abstract boolean canCreateGLPbuffer(AbstractGraphicsDevice device, GLProfile glp); @@ -271,7 +271,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { GLDrawableImpl drawable = null; device.lock(); try { - drawable = createOffscreenDrawableImpl( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, + drawable = createOffscreenDrawableImpl( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, new UpstreamSurfaceHookMutableSize(width, height) ) ); if(null != drawable) { drawable.setRealized(true); @@ -294,9 +294,9 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { if(null == device) { throw new GLException("No shared device for requested: "+deviceReq); } - return GLContext.isFBOAvailable(device, glp); + return GLContext.isFBOAvailable(device, glp); } - + @Override public final GLOffscreenAutoDrawable createOffscreenAutoDrawable(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable capsRequested, @@ -311,7 +311,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { } return new GLOffscreenAutoDrawableImpl( drawable, context, null, null); } - + @Override public final GLDrawable createOffscreenDrawable(AbstractGraphicsDevice deviceReq, GLCapabilitiesImmutable capsRequested, @@ -324,18 +324,18 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { 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 + // 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, + } + return createOffscreenDrawableImpl( createMutableSurfaceImpl(device, true, capsChosen, capsRequested, chooser, new UpstreamSurfaceHookMutableSize(width, height) ) ); } finally { device.unlock(); @@ -343,7 +343,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { } @Override - public final GLDrawable createDummyDrawable(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLProfile glp) { + public final GLDrawable createDummyDrawable(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLProfile glp) { final AbstractGraphicsDevice device = createNewDevice ? getOrCreateSharedDevice(deviceReq) : deviceReq; if(null == device) { throw new GLException("No shared device for requested: "+deviceReq+", createNewDevice "+createNewDevice); @@ -357,14 +357,14 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { device.unlock(); } } - - /** Creates a platform independent unrealized FBO offscreen GLDrawable */ + + /** Creates a platform independent unrealized FBO offscreen GLDrawable */ protected final 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 */ + + /** Creates a platform dependent unrealized offscreen pbuffer/pixmap GLDrawable instance */ protected abstract GLDrawableImpl createOffscreenDrawableImpl(NativeSurface target) ; /** @@ -381,10 +381,10 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { * @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 + * @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, + protected abstract ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice device, boolean createNewDevice, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook); @@ -399,7 +399,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { * @param deviceReq which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared device to be used, may be null for the platform's default device. * @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. + * @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 @@ -419,7 +419,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { device.unlock(); } } - + /** * A dummy surface is not visible on screen and will not be used to render directly to, * it maybe on- or offscreen. @@ -433,22 +433,22 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { * @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. + * @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, + 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, + public ProxySurface createProxySurface(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { final AbstractGraphicsDevice device = getOrCreateSharedDevice(deviceReq); if(null == device) { @@ -473,7 +473,7 @@ public abstract class GLDrawableFactoryImpl extends GLDrawableFactory { *

          * @param upstream TODO */ - protected abstract ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, + protected abstract ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream); //--------------------------------------------------------------------------- diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java index 5418fbaf3..2cf384fd7 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -63,12 +63,12 @@ import javax.media.opengl.GLRunnable; public class GLDrawableHelper { /** true if property jogl.debug.GLDrawable.PerfStats is defined. */ private static final boolean PERF_STATS; - + static { Debug.initSingleton(); PERF_STATS = Debug.isPropertyDefined("jogl.debug.GLDrawable.PerfStats", true); } - + protected static final boolean DEBUG = GLDrawableImpl.DEBUG; private final Object listenersLock = new Object(); private final ArrayList listeners = new ArrayList(); @@ -120,7 +120,7 @@ public class GLDrawableHelper { /** Limit release calls of {@link #forceNativeRelease(GLContext)} to {@value}. */ private static final int MAX_RELEASE_ITER = 512; - + /** * Since GLContext's {@link GLContext#makeCurrent()} and {@link GLContext#release()} * is recursive, a call to {@link GLContext#release()} may not natively release the context. @@ -138,36 +138,36 @@ public class GLDrawableHelper { System.err.println("GLDrawableHelper.forceNativeRelease() #"+releaseCount+" -- currentThread "+Thread.currentThread()+" -> "+GLContext.getCurrent()); } } while( MAX_RELEASE_ITER > releaseCount && ctx.isCurrent() ); - + if( ctx.isCurrent() ) { throw new GLException("Context still current after "+MAX_RELEASE_ITER+" releases: "+ctx); } } - + /** * Switch {@link GLContext} / {@link GLDrawable} association. *

          * The oldCtx will be destroyed if destroyPrevCtx is true, - * otherwise dis-associate oldCtx from drawable + * otherwise dis-associate oldCtx from drawable * via {@link GLContext#setGLDrawable(GLDrawable, boolean) oldCtx.setGLDrawable(null, true);}. *

          *

          - * Re-associate newCtx with drawable + * Re-associate newCtx with drawable * via {@link GLContext#setGLDrawable(GLDrawable, boolean) newCtx.setGLDrawable(drawable, true);}. *

          - *

          + *

          * If the old or new context was current on this thread, it is being released before switching the drawable. *

          *

          * No locking is being performed on the drawable, caller is required to take care of it. *

          - * + * * @param drawable the drawable which context is changed * @param oldCtx the old context, maybe null. * @param destroyOldCtx if true, destroy the oldCtx * @param newCtx the new context, maybe null for dis-association. * @param newCtxCreationFlags additional creation flags if newCtx is not null and not been created yet, see {@link GLContext#setContextCreationFlags(int)} - * + * * @see GLAutoDrawable#setContext(GLContext, boolean) */ public static final void switchContext(GLDrawable drawable, GLContext oldCtx, boolean destroyOldCtx, GLContext newCtx, int newCtxCreationFlags) { @@ -178,16 +178,16 @@ public class GLDrawableHelper { oldCtx.setGLDrawable(null, true); // dis-associate old pair } } - + if(null!=newCtx) { newCtx.setContextCreationFlags(newCtxCreationFlags); - newCtx.setGLDrawable(drawable, true); // re-associate new pair + newCtx.setGLDrawable(drawable, true); // re-associate new pair } } - + /** * If the drawable is not realized, OP is a NOP. - *
            + *
              *
            • release context if current
            • *
            • destroy old drawable
            • *
            • create new drawable
            • @@ -197,12 +197,12 @@ public class GLDrawableHelper { *

              * Locking is performed via {@link GLContext#makeCurrent()} on the passed context. *

              - * + * * @param drawable * @param context maybe null * @return the new drawable */ - public static final GLDrawableImpl recreateGLDrawable(GLDrawableImpl drawable, GLContext context) { + public static final GLDrawableImpl recreateGLDrawable(GLDrawableImpl drawable, GLContext context) { if( ! drawable.isRealized() ) { return drawable; } @@ -210,7 +210,7 @@ public class GLDrawableHelper { final GLDrawableFactory factory = drawable.getFactory(); final NativeSurface surface = drawable.getNativeSurface(); final ProxySurface proxySurface = (surface instanceof ProxySurface) ? (ProxySurface)surface : null; - + if( null != context ) { // Ensure to sync GL command stream if( currentContext != context ) { @@ -219,7 +219,7 @@ public class GLDrawableHelper { context.getGL().glFinish(); context.setGLDrawable(null, true); // dis-associate } - + if(null != proxySurface) { proxySurface.enableUpstreamSurfaceHookLifecycle(false); } @@ -236,18 +236,18 @@ public class GLDrawableHelper { if(null != context) { context.setGLDrawable(drawable, true); // re-association } - + if( null != currentContext ) { currentContext.makeCurrent(); } return drawable; } - + /** * Performs resize operation on the given drawable, assuming it is offscreen. *

              * The {@link GLDrawableImpl}'s {@link NativeSurface} is being locked during operation. - * In case the holder is an auto drawable or similar, it's lock shall be claimed by the caller. + * In case the holder is an auto drawable or similar, it's lock shall be claimed by the caller. *

              *

              * May recreate the drawable via {@link #recreateGLDrawable(GLDrawableImpl, GLContext)} @@ -257,10 +257,10 @@ public class GLDrawableHelper { * FBO drawables are resized w/o drawable destruction. *

              *

              - * Offscreen resize operation is validated w/ drawable size in the end. + * Offscreen resize operation is validated w/ drawable size in the end. * An exception is thrown if not successful. *

              - * + * * @param drawable * @param context * @param newWidth the new width, it's minimum is capped to 1 @@ -270,7 +270,7 @@ public class GLDrawableHelper { * @throws GLException may be thrown a resize operation */ public static final GLDrawableImpl resizeOffscreenDrawable(GLDrawableImpl drawable, GLContext context, int newWidth, int newHeight) - throws NativeWindowException, GLException + throws NativeWindowException, GLException { if(drawable.getChosenGLCapabilities().isOnscreen()) { throw new NativeWindowException("Drawable is not offscreen: "+drawable); @@ -288,7 +288,7 @@ public class GLDrawableHelper { } if(0>=newWidth) { newWidth = 1; validateSize=false; } if(0>=newHeight) { newHeight = 1; validateSize=false; } - // propagate new size + // propagate new size if(ns instanceof ProxySurface) { final ProxySurface ps = (ProxySurface) ns; final UpstreamSurfaceHook ush = ps.getUpstreamSurfaceHook(); @@ -301,7 +301,7 @@ public class GLDrawableHelper { System.err.println("GLDrawableHelper.resizeOffscreenDrawable: Drawable's offscreen surface n.a. ProxySurface, but "+ns.getClass().getName()+": "+ns); } if(drawable instanceof GLFBODrawable) { - if( null != context && context.isCreated() ) { + if( null != context && context.isCreated() ) { ((GLFBODrawable) drawable).resetSize(context.getGL()); } } else { @@ -315,7 +315,7 @@ public class GLDrawableHelper { } return drawable; } - + public final void addGLEventListener(GLEventListener listener) { addGLEventListener(-1, listener); } @@ -328,14 +328,14 @@ public class GLDrawableHelper { // GLEventListener may be added after context is created, // hence we earmark initialization for the next display call. listenersToBeInit.add(listener); - + listeners.add(index, listener); } } /** * Note that no {@link GLEventListener#dispose(GLAutoDrawable)} call is being issued - * due to the lack of a current context. + * due to the lack of a current context. * Consider calling {@link #disposeGLEventListener(GLAutoDrawable, GLDrawable, GLContext, GLEventListener)}. * @return the removed listener, or null if listener was not added */ @@ -356,11 +356,11 @@ public class GLDrawableHelper { return listener; } } - + public final int getGLEventListenerCount() { synchronized(listenersLock) { return listeners.size(); - } + } } public final GLEventListener getGLEventListener(int index) throws IndexOutOfBoundsException { @@ -371,13 +371,13 @@ public class GLDrawableHelper { return listeners.get(index); } } - + public final boolean getGLEventListenerInitState(GLEventListener listener) { synchronized(listenersLock) { return !listenersToBeInit.contains(listener); } } - + public final void setGLEventListenerInitState(GLEventListener listener, boolean initialized) { synchronized(listenersLock) { if(initialized) { @@ -387,16 +387,16 @@ public class GLDrawableHelper { } } } - + /** - * Disposes the given {@link GLEventListener} via {@link GLEventListener#dispose(GLAutoDrawable)} + * Disposes the given {@link GLEventListener} via {@link GLEventListener#dispose(GLAutoDrawable)} * if it has been initialized and added to this queue. *

              * If remove is true, the {@link GLEventListener} is removed from this drawable queue before disposal, * otherwise marked uninitialized. *

              *

              - * Please consider using {@link #disposeGLEventListener(GLAutoDrawable, GLDrawable, GLContext, GLEventListener)} + * Please consider using {@link #disposeGLEventListener(GLAutoDrawable, GLDrawable, GLContext, GLEventListener)} * for correctness, i.e. encapsulating all calls w/ makeCurrent etc. *

              * @param autoDrawable @@ -405,9 +405,9 @@ public class GLDrawableHelper { */ public final GLEventListener disposeGLEventListener(GLAutoDrawable autoDrawable, GLEventListener listener, boolean remove) { synchronized(listenersLock) { - if( remove ) { + if( remove ) { if( listeners.remove(listener) ) { - if( !listenersToBeInit.remove(listener) ) { + if( !listenersToBeInit.remove(listener) ) { listener.dispose(autoDrawable); } return listener; @@ -417,12 +417,12 @@ public class GLDrawableHelper { listener.dispose(autoDrawable); listenersToBeInit.add(listener); return listener; - } + } } } return null; } - + /** * Disposes all added initialized {@link GLEventListener}s via {@link GLEventListener#dispose(GLAutoDrawable)}. *

              @@ -456,20 +456,20 @@ public class GLDrawableHelper { listenersToBeInit.add(listener); disposeCount++; } - } + } } } return disposeCount; } /** - * Principal helper method which runs {@link #disposeGLEventListener(GLAutoDrawable, GLEventListener, boolean)} + * Principal helper method which runs {@link #disposeGLEventListener(GLAutoDrawable, GLEventListener, boolean)} * with the context made current. *

              - * If an {@link GLAnimatorControl} is being attached and the current thread is different + * If an {@link GLAnimatorControl} is being attached and the current thread is different * than {@link GLAnimatorControl#getThread() the animator's thread}, it is paused during the operation. *

              - * + * * @param autoDrawable * @param context * @param listener @@ -477,7 +477,7 @@ public class GLDrawableHelper { */ public final GLEventListener disposeGLEventListener(final GLAutoDrawable autoDrawable, final GLDrawable drawable, - final GLContext context, + final GLContext context, final GLEventListener listener, final boolean remove) { synchronized(listenersLock) { @@ -485,7 +485,7 @@ public class GLDrawableHelper { if( listenersToBeInit.contains(listener) ) { if( remove ) { listenersToBeInit.remove(listener); - return listeners.remove(listener) ? listener : null; + return listeners.remove(listener) ? listener : null; } return null; } @@ -498,21 +498,21 @@ public class GLDrawableHelper { } }; invokeGL(drawable, context, action, nop); - + if(isPaused) { animatorCtrl.resume(); } return res[0]; } - + /** - * Principal helper method which runs {@link #disposeAllGLEventListener(GLAutoDrawable, boolean)} + * Principal helper method which runs {@link #disposeAllGLEventListener(GLAutoDrawable, boolean)} * with the context made current. *

              - * If an {@link GLAnimatorControl} is being attached and the current thread is different + * If an {@link GLAnimatorControl} is being attached and the current thread is different * than {@link GLAnimatorControl#getThread() the animator's thread}, it is paused during the operation. *

              - * + * * @param autoDrawable * @param context * @param remove @@ -521,21 +521,21 @@ public class GLDrawableHelper { final GLDrawable drawable, final GLContext context, final boolean remove) { - + final boolean isPaused = isAnimatorAnimatingOnOtherThread() && animatorCtrl.pause(); - + final Runnable action = new Runnable() { public void run() { disposeAllGLEventListener(autoDrawable, remove); } }; invokeGL(drawable, context, action, nop); - + if(isPaused) { animatorCtrl.resume(); } } - + private final void init(GLEventListener l, GLAutoDrawable drawable, boolean sendReshape, boolean setViewport) { l.init(drawable); if(sendReshape) { @@ -543,8 +543,8 @@ public class GLDrawableHelper { } } - /** - * The default init action to be called once after ctx is being created @ 1st makeCurrent(). + /** + * The default init action to be called once after ctx is being created @ 1st makeCurrent(). * @param sendReshape set to true if the subsequent display call won't reshape, otherwise false to avoid double reshape. **/ public final void init(GLAutoDrawable drawable, boolean sendReshape) { @@ -554,7 +554,7 @@ public class GLDrawableHelper { if( listenerCount > 0 ) { for (int i=0; i < listenerCount; i++) { final GLEventListener listener = _listeners.get(i) ; - + // If make ctx current, 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 it must be called unconditional, always. @@ -571,7 +571,7 @@ public class GLDrawableHelper { public final void display(GLAutoDrawable drawable) { displayImpl(drawable); if( glRunnables.size()>0 && !execGLRunnables(drawable) ) { // glRunnables volatile OK; execGL.. only executed if size > 0 - displayImpl(drawable); + displayImpl(drawable); } } private final void displayImpl(GLAutoDrawable drawable) { @@ -580,7 +580,7 @@ public class GLDrawableHelper { final int listenerCount = _listeners.size(); for (int i=0; i < listenerCount; i++) { final GLEventListener listener = _listeners.get(i) ; - // GLEventListener may need to be init, + // GLEventListener may need to be init, // in case this one is added after the realization of the GLAutoDrawable if( listenersToBeInit.remove(listener) ) { init( listener, drawable, true /* sendReshape */, listenersToBeInit.size() + 1 == listenerCount /* setViewport if 1st init */ ); @@ -589,11 +589,11 @@ public class GLDrawableHelper { } } } - + private final void reshape(GLEventListener listener, GLAutoDrawable drawable, int x, int y, int width, int height, boolean setViewport, boolean checkInit) { if(checkInit) { - // GLEventListener may need to be init, + // GLEventListener may need to be init, // in case this one is added after the realization of the GLAutoDrawable synchronized(listenersLock) { if( listenersToBeInit.remove(listener) ) { @@ -627,7 +627,7 @@ public class GLDrawableHelper { _glRunnables = null; } } - + if(null!=_glRunnables) { for (int i=0; i < _glRunnables.size(); i++) { res = _glRunnables.get(i).run(drawable) && res; @@ -648,7 +648,7 @@ public class GLDrawableHelper { _glRunnables = null; } } - + if(null!=_glRunnables) { for (int i=0; i < _glRunnables.size(); i++) { _glRunnables.get(i).flush(); @@ -656,7 +656,7 @@ public class GLDrawableHelper { } } } - + public final void setAnimator(GLAnimatorControl animator) throws GLException { synchronized(glRunnablesLock) { if(animatorCtrl!=animator && null!=animator && null!=animatorCtrl) { @@ -693,7 +693,7 @@ public class GLDrawableHelper { * If wait is true the call blocks until the glRunnable * has been executed.

              *

              - * If wait is true and + * If wait is true and * {@link GLDrawable#isRealized()} returns false or {@link GLAutoDrawable#getContext()} returns null, * the call is ignored and returns false.
              * This helps avoiding deadlocking the caller. @@ -709,7 +709,7 @@ public class GLDrawableHelper { wait && ( !drawable.isRealized() || null==drawable.getContext() ) ) { return false; } - + GLRunnableTask rTask = null; Object rTaskLock = new Object(); Throwable throwable = null; @@ -743,13 +743,13 @@ public class GLDrawableHelper { } return true; } - + public final boolean invoke(GLAutoDrawable drawable, boolean wait, List newGLRunnables) { if( null == newGLRunnables || newGLRunnables.size() == 0 || null == drawable || wait && ( !drawable.isRealized() || null==drawable.getContext() ) ) { return false; } - + final int count = newGLRunnables.size(); GLRunnableTask rTask = null; Object rTaskLock = new Object(); @@ -785,18 +785,18 @@ public class GLDrawableHelper { } } } - return true; + return true; } public final void enqueue(GLRunnable glRunnable) { if( null == glRunnable) { return; - } + } synchronized(glRunnablesLock) { glRunnables.add( new GLRunnableTask(glRunnable, null, false) ); } } - + public final void setAutoSwapBufferMode(boolean enable) { autoSwapBufferMode = enable; } @@ -812,17 +812,17 @@ public class GLDrawableHelper { /** * Dedicates this instance's {@link GLContext} to the given thread.
              * The thread will exclusively claim the {@link GLContext} via {@link #display()} and not release it - * until {@link #destroy()} or setExclusiveContextThread(null) has been called. + * until {@link #destroy()} or setExclusiveContextThread(null) has been called. *

              * Default non-exclusive behavior is requested via setExclusiveContextThread(null), - * which will cause the next call of {@link #display()} on the exclusive thread to - * release the {@link GLContext}. Only after it's async release, {@link #getExclusiveContextThread()} + * which will cause the next call of {@link #display()} on the exclusive thread to + * release the {@link GLContext}. Only after it's async release, {@link #getExclusiveContextThread()} * will return null. *

              *

              * To release a previous made exclusive thread, a user issues setExclusiveContextThread(null) - * and may poll {@link #getExclusiveContextThread()} until it returns null, - * while the exclusive thread is still running. + * and may poll {@link #getExclusiveContextThread()} until it returns null, + * while the exclusive thread is still running. *

              *

              * Note: Setting a new exclusive thread without properly releasing a previous one @@ -833,7 +833,7 @@ public class GLDrawableHelper { * and spare redundant context switches. *

              * @param t the exclusive thread to claim the context, or null for default operation. - * @return previous exclusive context thread + * @return previous exclusive context thread * @throws GLException If an exclusive thread is still active but a new one is attempted to be set */ public final Thread setExclusiveContextThread(Thread t, GLContext context) throws GLException { @@ -857,7 +857,7 @@ public class GLDrawableHelper { ex.printStackTrace(); throw new GLException(ex); } - } + } exclusiveContextThread = t; } if (DEBUG) { @@ -865,14 +865,14 @@ public class GLDrawableHelper { } return oldExclusiveContextThread; } - + /** - * @see #setExclusiveContextThread(Thread, GLContext) + * @see #setExclusiveContextThread(Thread, GLContext) */ public final Thread getExclusiveContextThread() { return exclusiveContextThread; } - + private static final ThreadLocal perThreadInitAction = new ThreadLocal(); /** Principal helper method which runs a Runnable with the context @@ -904,15 +904,15 @@ public class GLDrawableHelper { } if(PERF_STATS) { - invokeGLImplStats(drawable, context, runnable, initAction); + invokeGLImplStats(drawable, context, runnable, initAction); } else { invokeGLImpl(drawable, context, runnable, initAction); } } - /** - * Principal helper method which runs - * {@link #disposeAllGLEventListener(GLAutoDrawable, boolean) disposeAllGLEventListener(autoDrawable, false)} + /** + * Principal helper method which runs + * {@link #disposeAllGLEventListener(GLAutoDrawable, boolean) disposeAllGLEventListener(autoDrawable, false)} * with the context made current. *

              * If destroyContext is true the context is destroyed in the end while holding the lock. @@ -940,7 +940,7 @@ public class GLDrawableHelper { } } - int res; + int res; try { res = context.makeCurrent(); if (GLContext.CONTEXT_NOT_CURRENT != res) { @@ -975,7 +975,7 @@ public class GLDrawableHelper { private final void invokeGLImpl(final GLDrawable drawable, final GLContext context, final Runnable runnable, - final Runnable initAction) { + final Runnable initAction) { final Thread currentThread = Thread.currentThread(); // Exclusive Cases: @@ -1013,7 +1013,7 @@ public class GLDrawableHelper { lastContext.release(); } } - + try { final boolean releaseContext; if( GLContext.CONTEXT_NOT_CURRENT == res ) { @@ -1110,7 +1110,7 @@ public class GLDrawableHelper { long tdX = 0; // release boolean ctxClaimed = false; boolean ctxReleased = false; - boolean ctxDestroyed = false; + boolean ctxDestroyed = false; try { final boolean releaseContext; if( GLContext.CONTEXT_NOT_CURRENT == res ) { @@ -1129,7 +1129,7 @@ public class GLDrawableHelper { } initAction.run(); } - tdR = System.currentTimeMillis(); + tdR = System.currentTimeMillis(); tdA = tdR - t0; // makeCurrent runnable.run(); tdS = System.currentTimeMillis(); @@ -1172,5 +1172,5 @@ public class GLDrawableHelper { } protected static String getThreadName() { return Thread.currentThread().getName(); } - + } diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java index e1088da29..a79a3cf25 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java @@ -53,11 +53,11 @@ import javax.media.opengl.GLProfile; public abstract class GLDrawableImpl implements GLDrawable { protected static final boolean DEBUG = GLDrawableFactoryImpl.DEBUG; - + protected GLDrawableImpl(GLDrawableFactory factory, NativeSurface comp, boolean realized) { this(factory, comp, (GLCapabilitiesImmutable) comp.getGraphicsConfiguration().getRequestedCapabilities(), realized); } - + protected GLDrawableImpl(GLDrawableFactory factory, NativeSurface comp, GLCapabilitiesImmutable requestedCapabilities, boolean realized) { this.factory = factory; this.surface = comp; @@ -100,20 +100,20 @@ public abstract class GLDrawableImpl implements GLDrawable { } } finally { unlockSurface(); - } + } surface.surfaceUpdated(this, surface, System.currentTimeMillis()); } - + /** * Platform and implementation depending surface swap. *

              The surface is locked.

              *

              - * If doubleBuffered is true, + * If doubleBuffered is true, * an actual platform dependent surface swap shall be executed. *

              *

              - * If doubleBuffered is false, - * {@link GL#glFlush()} has been called already and + * If doubleBuffered is false, + * {@link GL#glFlush()} has been called already and * the implementation may execute implementation specific code. *

              * @param doubleBuffered indicates whether double buffering is enabled, see above. @@ -143,19 +143,19 @@ public abstract class GLDrawableImpl implements GLDrawable { return surface; } - /** + /** * called with locked surface @ setRealized(false) or @ lockSurface(..) when surface changed *

              * Must be paired w/ {@link #createHandle()}. - *

              + *

              */ protected void destroyHandle() {} - /** + /** * called with locked surface @ setRealized(true) or @ lockSurface(..) when surface changed *

              * Must be paired w/ {@link #destroyHandle()}. - *

              + *

              */ protected void createHandle() {} @@ -213,16 +213,16 @@ public abstract class GLDrawableImpl implements GLDrawable { System.err.println(getThreadName() + ": setRealized: "+getClass().getName()+" "+this.realized+" == "+realizedArg); } } - + /** - * Platform specific realization of drawable + * Platform specific realization of drawable */ protected abstract void setRealizedImpl(); /** * Callback for special implementations, allowing *
                - *
              • to associate bound context to this drawable (bound == true) + *
              • to associate bound context to this drawable (bound == true) * or to remove such association (bound == false).
              • *
              • to trigger GLContext/GLDrawable related lifecycle: construct, destroy.
              • *
              @@ -239,8 +239,8 @@ public abstract class GLDrawableImpl implements GLDrawable { * @param bound if true create an association, otherwise remove it */ protected void associateContext(GLContext ctx, boolean bound) { } - - /** + + /** * Callback for special implementations, allowing GLContext to trigger GL related lifecycle: makeCurrent, release. *

              * If current is true, the context has just been made current. @@ -252,13 +252,13 @@ public abstract class GLDrawableImpl implements GLDrawable { * Being called by {@link GLContextImpl#contextMadeCurrent(boolean)}. *

              * @see #associateContext(GLContext, boolean) - */ + */ protected void contextMadeCurrent(GLContext glc, boolean current) { } /** Callback for special implementations, allowing GLContext to fetch a custom default render framebuffer. Defaults to zero.*/ protected int getDefaultDrawFramebuffer() { return 0; } /** Callback for special implementations, allowing GLContext to fetch a custom default read framebuffer. Defaults to zero. */ - protected int getDefaultReadFramebuffer() { return 0; } + protected int getDefaultReadFramebuffer() { return 0; } /** Callback for special implementations, allowing GLContext to fetch a custom default read buffer of current framebuffer. */ protected int getDefaultReadBuffer(GL gl) { if(gl.isGLES() || getChosenGLCapabilities().getDoubleBuffered()) { @@ -266,9 +266,9 @@ public abstract class GLDrawableImpl implements GLDrawable { // Note-2: ES3 only supports GL_BACK, GL_NONE or GL_COLOR_ATTACHMENT0+i return GL.GL_BACK; } - return GL.GL_FRONT ; + return GL.GL_FRONT ; } - + @Override public final boolean isRealized() { return realized; @@ -286,22 +286,22 @@ public abstract class GLDrawableImpl implements GLDrawable { @Override public boolean isGLOriented() { - return true; + return true; } - - /** + + /** * {@link NativeSurface#lockSurface() Locks} the underlying windowing toolkit's {@link NativeSurface surface}. *

              * If drawable is {@link #setRealized(boolean) realized}, - * the {@link #getHandle() drawable handle} is valid after successfully {@link NativeSurface#lockSurface() locking} + * the {@link #getHandle() drawable handle} is valid after successfully {@link NativeSurface#lockSurface() locking} * it's {@link NativeSurface surface} until being {@link #unlockSurface() unlocked}. *

              *

              - * In case the {@link NativeSurface surface} has changed as indicated by it's + * In case the {@link NativeSurface surface} has changed as indicated by it's * {@link NativeSurface#lockSurface() lock} result {@link NativeSurface#LOCK_SURFACE_CHANGED}, - * the implementation is required to update this information as needed within it's implementation. + * the implementation is required to update this information as needed within it's implementation. *

              - * + * * @see NativeSurface#lockSurface() * @see #getHandle() */ @@ -312,7 +312,7 @@ public abstract class GLDrawableImpl implements GLDrawable { final long _handle1 = getHandle(); destroyHandle(); createHandle(); - final long _handle2 = getHandle(); + final long _handle2 = getHandle(); if(DEBUG) { if( _handle1 != _handle2) { System.err.println(getThreadName() + ": Drawable handle changed: "+toHexString(_handle1)+" -> "+toHexString(_handle2)); @@ -320,14 +320,14 @@ public abstract class GLDrawableImpl implements GLDrawable { } } return lockRes; - + } - /** + /** * {@link NativeSurface#unlockSurface() Unlocks} the underlying windowing toolkit {@link NativeSurface surface}, * which may render the {@link #getHandle() drawable handle} invalid. - * - * @see NativeSurface#unlockSurface() + * + * @see NativeSurface#unlockSurface() * @see #getHandle() */ public final void unlockSurface() { diff --git a/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java index 8ba9f617b..640e181ae 100644 --- a/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl; import com.jogamp.common.os.DynamicLibraryBundle; @@ -36,7 +36,7 @@ public abstract class GLDynamicLibraryBundleInfo implements DynamicLibraryBundle protected GLDynamicLibraryBundleInfo() { } - /** + /** * Returns true, * since we might load a desktop GL library and allow symbol access to subsequent libs. *

              @@ -47,19 +47,19 @@ public abstract class GLDynamicLibraryBundleInfo implements DynamicLibraryBundle *

              */ public final boolean shallLinkGlobal() { return true; } - + /** * {@inheritDoc} *

              * Returns false. *

              - */ + */ @Override public boolean shallLookupGlobal() { return false; } @Override public final RunnableExecutor getLibLoaderExecutor() { return DynamicLibraryBundle.getDefaultRunnableExecutor(); - } + } } diff --git a/src/jogl/classes/jogamp/opengl/GLDynamicLookupHelper.java b/src/jogl/classes/jogamp/opengl/GLDynamicLookupHelper.java index 1ed73f15e..421f06205 100644 --- a/src/jogl/classes/jogamp/opengl/GLDynamicLookupHelper.java +++ b/src/jogl/classes/jogamp/opengl/GLDynamicLookupHelper.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl; import com.jogamp.common.os.DynamicLibraryBundle; diff --git a/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java index f2248b388..ab318927c 100644 --- a/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java @@ -26,11 +26,11 @@ import com.jogamp.opengl.JoglVersion; * to initialize the {@link FBObject} instance. *

              *

              - * It utilizes the context current hook {@link #contextMadeCurrent(GLContext, boolean) contextMadeCurrent(context, true)} + * It utilizes the context current hook {@link #contextMadeCurrent(GLContext, boolean) contextMadeCurrent(context, true)} * to {@link FBObject#bind(GL) bind} the FBO. *

              * See {@link GLFBODrawable} for double buffering details. - * + * * @see GLDrawableImpl#contextRealized(GLContext, boolean) * @see GLDrawableImpl#contextMadeCurrent(GLContext, boolean) * @see GLDrawableImpl#getDefaultDrawFramebuffer() @@ -39,21 +39,21 @@ import com.jogamp.opengl.JoglVersion; public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { protected static final boolean DEBUG; protected static final boolean DEBUG_SWAP; - + static { Debug.initSingleton(); DEBUG = GLDrawableImpl.DEBUG || Debug.debug("FBObject"); DEBUG_SWAP = DEBUG || Debug.isPropertyDefined("jogl.debug.FBObject.Swap", true); } - + private final GLDrawableImpl parent; private GLCapabilitiesImmutable origParentChosenCaps; - + private boolean initialized; private int texUnit; private int samples; private boolean fboResetQuirk; - + private FBObject[] fbos; private int fboIBack; // points to GL_BACK buffer private int fboIFront; // points to GL_FRONT buffer @@ -64,19 +64,19 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { private boolean fboSwapped; /** dump fboResetQuirk info only once pre ClassLoader and only in DEBUG mode */ - private static volatile boolean resetQuirkInfoDumped = false; - + private static volatile boolean resetQuirkInfoDumped = false; + /** number of FBOs for double buffering. TODO: Possible to configure! */ - private static final int bufferCount = 2; - + private static final int bufferCount = 2; + // private DoubleBufferMode doubleBufferMode; // TODO: Add or remove TEXTURE (only) DoubleBufferMode support - + private SwapBufferContext swapBufferContext; - + public static interface SwapBufferContext { public void swapBuffers(boolean doubleBuffered); } - + /** * @param factory * @param parent @@ -84,7 +84,7 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { * @param fboCaps the requested FBO capabilities * @param textureUnit */ - protected GLFBODrawableImpl(GLDrawableFactoryImpl factory, GLDrawableImpl parent, NativeSurface surface, + protected GLFBODrawableImpl(GLDrawableFactoryImpl factory, GLDrawableImpl parent, NativeSurface surface, GLCapabilitiesImmutable fboCaps, int textureUnit) { super(factory, surface, fboCaps, false); this.initialized = false; @@ -94,13 +94,13 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { this.texUnit = textureUnit; this.samples = fboCaps.getNumSamples(); fboResetQuirk = false; - + // default .. // TODO: Add or remove TEXTURE (only) DoubleBufferMode support // this.doubleBufferMode = ( samples > 0 || fboCaps.getDoubleBuffered() ) ? DoubleBufferMode.FBO : DoubleBufferMode.NONE ; - + this.swapBufferContext = null; } - + private final void initialize(boolean realize, GL gl) { if( !initialized && !realize ) { if( DEBUG ) { @@ -114,7 +114,7 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { } if(realize) { final GLCapabilities chosenFBOCaps = (GLCapabilities) getChosenGLCapabilities(); // cloned at setRealized(true) - + final int maxSamples = gl.getMaxRenderbufferSamples(); { final int newSamples = samples <= maxSamples ? samples : maxSamples; @@ -123,7 +123,7 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { } samples = newSamples; } - + final int fbosN; if(samples > 0) { fbosN = 1; @@ -136,7 +136,7 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { fbos = new FBObject[fbosN]; fboIBack = 0; // head fboIFront = fbos.length - 1; // tail - + for(int i=0; i "+newSamples+"/"+maxSamples); } @@ -297,11 +297,11 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { System.err.println("GLFBODrawableImpl.reset(newSamples "+newSamples+"): END "+this); } } - + // // GLDrawable // - + @Override public final GLContext createContext(GLContext shareWith) { final GLContext ctx = parent.createContext(shareWith); @@ -312,7 +312,7 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { // // GLDrawableImpl // - + @Override public final GLDynamicLookupHelper getGLDynamicLookupHelper() { return parent.getGLDynamicLookupHelper(); @@ -320,13 +320,13 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { @Override protected final int getDefaultDrawFramebuffer() { return initialized ? fbos[fboIBack].getWriteFramebuffer() : 0; } - + @Override protected final int getDefaultReadFramebuffer() { return initialized ? fbos[fboIFront].getReadFramebuffer() : 0; } @Override protected final int getDefaultReadBuffer(GL gl) { return initialized ? fbos[fboIFront].getDefaultReadBuffer() : GL.GL_COLOR_ATTACHMENT0 ; } - + @Override protected final void setRealizedImpl() { final MutableGraphicsConfiguration msConfig = (MutableGraphicsConfiguration) surface.getGraphicsConfiguration(); @@ -341,12 +341,12 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { parent.setRealized(false); } } - + @Override protected void associateContext(GLContext glc, boolean bound) { - initialize(bound, glc.getGL()); + initialize(bound, glc.getGL()); } - + @Override protected final void contextMadeCurrent(GLContext glc, boolean current) { final GL gl = glc.getGL(); @@ -367,7 +367,7 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { } } } - + @Override protected void swapBuffersImpl(boolean doubleBuffered) { final GLContext ctx = GLContext.getCurrent(); @@ -389,7 +389,7 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { swapFBOImplPost(ctx); } } - + private final void swapFBOImplPost(GLContext glc) { // Safely reset the previous front FBO - after completing propagating swap if(0 <= pendingFBOReset) { @@ -398,18 +398,18 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { pendingFBOReset = -1; } } - + private final void swapFBOImpl(GLContext glc) { final GL gl = glc.getGL(); fbos[fboIBack].markUnbound(); // fast path, use(gl,..) is called below - + if(DEBUG) { int _fboIFront = ( fboIFront + 1 ) % fbos.length; if(_fboIFront != fboIBack) { throw new InternalError("XXX: "+_fboIFront+"!="+fboIBack); } } fboIFront = fboIBack; fboIBack = ( fboIBack + 1 ) % fbos.length; - + final Colorbuffer colorbuffer = samples > 0 ? fbos[fboIFront].getSamplingSink() : fbos[fboIFront].getColorbuffer(0); final TextureAttachment texAttachment; if(colorbuffer instanceof TextureAttachment) { @@ -423,12 +423,12 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { } gl.glActiveTexture(GL.GL_TEXTURE0 + texUnit); fbos[fboIFront].use(gl, texAttachment); - - /* Included in above use command: + + /* Included in above use command: gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, fbos[fboIBack].getDrawFramebuffer()); gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, fbos[fboIFront].getReadFramebuffer()); } */ - + if(DEBUG_SWAP) { System.err.println("Post FBO swap(X): fboI back "+fboIBack+", front "+fboIFront+", num "+fbos.length); } @@ -436,62 +436,62 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { // // GLFBODrawable - // - + // + @Override public final boolean isInitialized() { return initialized; } - + @Override public final void resetSize(GL gl) throws GLException { reset(gl, samples); - } - + } + @Override public final int getTextureUnit() { return texUnit; } - + @Override public final void setTextureUnit(int u) { texUnit = u; } - + @Override public final int getNumSamples() { return samples; } - + @Override public void setNumSamples(GL gl, int newSamples) throws GLException { if(samples != newSamples) { reset(gl, newSamples); } } - + @Override public final int setNumBuffers(int bufferCount) throws GLException { // FIXME: Implement return bufferCount; } - + @Override public final int getNumBuffers() { return bufferCount; } - + /** // TODO: Add or remove TEXTURE (only) DoubleBufferMode support @Override public final DoubleBufferMode getDoubleBufferMode() { return doubleBufferMode; } - + @Override public final void setDoubleBufferMode(DoubleBufferMode mode) throws GLException { if(initialized) { throw new GLException("Not allowed past initialization: "+this); - } + } final GLCapabilitiesImmutable caps = (GLCapabilitiesImmutable) surface.getGraphicsConfiguration().getChosenCapabilities(); if(0 == samples && caps.getDoubleBuffered() && DoubleBufferMode.NONE != mode) { doubleBufferMode = mode; } } */ - + @Override public FBObject getFBObject(int bufferName) throws IllegalArgumentException { if(!initialized) { @@ -509,12 +509,12 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { case GL.GL_BACK: res = fbos[fboIBack]; break; - default: + default: throw new IllegalArgumentException(illegalBufferName+toHexString(bufferName)); - } - return res; + } + return res; } - + @Override public final TextureAttachment getTextureBuffer(int bufferName) throws IllegalArgumentException { if(!initialized) { @@ -536,13 +536,13 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { res = (TextureAttachment) fbos[fboIBack].getColorbuffer(0); } break; - default: + default: throw new IllegalArgumentException(illegalBufferName+toHexString(bufferName)); - } - return res; + } + return res; } private static final String illegalBufferName = "Only GL_FRONT and GL_BACK buffer are allowed, passed "; - + @Override public String toString() { return getClass().getSimpleName()+"[Initialized "+initialized+", realized "+isRealized()+", texUnit "+texUnit+", samples "+samples+ @@ -555,13 +555,13 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { ",\n\tSurface "+getNativeSurface()+ "]"; } - + public static class ResizeableImpl extends GLFBODrawableImpl implements GLFBODrawable.Resizeable { - protected ResizeableImpl(GLDrawableFactoryImpl factory, GLDrawableImpl parent, ProxySurface surface, + protected ResizeableImpl(GLDrawableFactoryImpl factory, GLDrawableImpl parent, ProxySurface surface, GLCapabilitiesImmutable fboCaps, int textureUnit) { super(factory, parent, surface, fboCaps, textureUnit); } - + @Override public final void setSize(GLContext context, int newWidth, int newHeight) throws NativeWindowException, GLException { if(DEBUG) { @@ -572,7 +572,7 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { throw new NativeWindowException("Could not lock surface: "+this); } try { - // propagate new size + // propagate new size final ProxySurface ps = (ProxySurface) getNativeSurface(); final UpstreamSurfaceHook ush = ps.getUpstreamSurfaceHook(); if(ush instanceof UpstreamSurfaceHook.MutableSize) { diff --git a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java index d54da4d28..702fb77de 100644 --- a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java +++ b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java @@ -85,12 +85,12 @@ public class GLGraphicsConfigurationUtil { } if(isFBO) { winattrbits |= FBO_BIT; - } + } if(isPBuffer ){ winattrbits |= PBUFFER_BIT; - } + } if(isBitmap) { - winattrbits |= BITMAP_BIT; + winattrbits |= BITMAP_BIT; } return winattrbits; } @@ -110,7 +110,7 @@ public class GLGraphicsConfigurationUtil { } else if(isPBuffer ){ winattrbits = PBUFFER_BIT; } else if(isBitmap) { - winattrbits = BITMAP_BIT; + winattrbits = BITMAP_BIT; } else { throw new InternalError("Empty bitmask"); } @@ -136,9 +136,9 @@ public class GLGraphicsConfigurationUtil { caps.setHardwareAccelerated(false); } - return caps; + return caps; } - + /** * Fixes the requested {@link GLCapabilitiesImmutable} according to on- and offscreen usage. *

              @@ -150,17 +150,17 @@ public class GLGraphicsConfigurationUtil { * @param device the device on which the drawable will be created, maybe null for the {@link GLDrawableFactory#getDefaultDevice() default device}. * @return either the given requested {@link GLCapabilitiesImmutable} instance if no modifications were required, or a modified {@link GLCapabilitiesImmutable} instance. */ - public static GLCapabilitiesImmutable fixGLCapabilities(GLCapabilitiesImmutable capsRequested, + public static GLCapabilitiesImmutable fixGLCapabilities(GLCapabilitiesImmutable capsRequested, GLDrawableFactory factory, AbstractGraphicsDevice device) { if( !capsRequested.isOnscreen() ) { return fixOffscreenGLCapabilities(capsRequested, factory, device); } return capsRequested; } - + public static GLCapabilitiesImmutable fixOnscreenGLCapabilities(GLCapabilitiesImmutable capsRequested) { - if( !capsRequested.isOnscreen() || capsRequested.isFBO() || capsRequested.isPBuffer() || capsRequested.isBitmap() ) { + if( !capsRequested.isOnscreen() || capsRequested.isFBO() || capsRequested.isPBuffer() || capsRequested.isBitmap() ) { // fix caps .. final GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); caps2.setBitmap (false); @@ -174,7 +174,7 @@ public class GLGraphicsConfigurationUtil { public static GLCapabilitiesImmutable fixOffscreenBitOnly(GLCapabilitiesImmutable capsRequested) { - if( capsRequested.isOnscreen() ) { + if( capsRequested.isOnscreen() ) { // fix caps .. final GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); caps2.setOnscreen(false); @@ -182,7 +182,7 @@ public class GLGraphicsConfigurationUtil { } return capsRequested; } - + /** * Fixes the requested {@link GLCapabilitiesImmutable} according to: *

                @@ -203,15 +203,15 @@ public class GLGraphicsConfigurationUtil { final GLProfile glp = capsRequested.getGLProfile(); final boolean fboAvailable = GLContext.isFBOAvailable(device, glp); final boolean pbufferAvailable = factory.canCreateGLPbuffer(device, glp); - + final GLRendererQuirks glrq = factory.getRendererQuirks(device); final boolean bitmapAvailable; final boolean doubleBufferAvailable; - + if(null != glrq) { bitmapAvailable = !glrq.exist(GLRendererQuirks.NoOffscreenBitmap); if( capsRequested.getDoubleBuffered() && - ( capsRequested.isPBuffer() && glrq.exist(GLRendererQuirks.NoDoubleBufferedPBuffer) ) || + ( capsRequested.isPBuffer() && glrq.exist(GLRendererQuirks.NoDoubleBufferedPBuffer) ) || ( capsRequested.isBitmap() && glrq.exist(GLRendererQuirks.NoDoubleBufferedBitmap) ) ) { doubleBufferAvailable = false; } else { @@ -221,25 +221,25 @@ public class GLGraphicsConfigurationUtil { bitmapAvailable = true; doubleBufferAvailable = true; } - - final boolean auto = !( fboAvailable && capsRequested.isFBO() ) && - !( pbufferAvailable && capsRequested.isPBuffer() ) && + + final boolean auto = !( fboAvailable && capsRequested.isFBO() ) && + !( pbufferAvailable && capsRequested.isPBuffer() ) && !( bitmapAvailable && capsRequested.isBitmap() ) ; final boolean useFBO = fboAvailable && ( auto || capsRequested.isFBO() ) ; final boolean usePbuffer = !useFBO && pbufferAvailable && ( auto || capsRequested.isPBuffer() ) ; final boolean useBitmap = !useFBO && !usePbuffer && bitmapAvailable && ( auto || capsRequested.isBitmap() ) ; - + if( capsRequested.isOnscreen() || - useFBO != capsRequested.isFBO() || - usePbuffer != capsRequested.isPBuffer() || + useFBO != capsRequested.isFBO() || + usePbuffer != capsRequested.isPBuffer() || useBitmap != capsRequested.isBitmap() || !doubleBufferAvailable && capsRequested.getDoubleBuffered() ) { // fix caps .. final GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); caps2.setOnscreen(false); - caps2.setFBO( useFBO ); + caps2.setFBO( useFBO ); caps2.setPBuffer( usePbuffer ); caps2.setBitmap( useBitmap ); if( !doubleBufferAvailable ) { @@ -253,8 +253,8 @@ public class GLGraphicsConfigurationUtil { public static GLCapabilitiesImmutable fixGLPBufferGLCapabilities(GLCapabilitiesImmutable capsRequested) { if( capsRequested.isOnscreen() || - !capsRequested.isPBuffer() || - capsRequested.isFBO() ) + !capsRequested.isPBuffer() || + capsRequested.isFBO() ) { // fix caps .. final GLCapabilities caps2 = (GLCapabilities) capsRequested.cloneMutable(); @@ -277,7 +277,7 @@ public class GLGraphicsConfigurationUtil { } return capsRequested; } - + /** Fix double buffered setting */ public static GLCapabilitiesImmutable fixDoubleBufferedGLCapabilities(GLCapabilitiesImmutable capsRequested, boolean doubleBuffered) { @@ -288,7 +288,7 @@ public class GLGraphicsConfigurationUtil { } return capsRequested; } - + public static GLCapabilitiesImmutable clipRGBAGLCapabilities(GLCapabilitiesImmutable caps, boolean allowRGB555, boolean allowAlpha) { final int iR = caps.getRedBits(); @@ -305,21 +305,21 @@ public class GLGraphicsConfigurationUtil { caps2.setGreenBits(oG); caps2.setBlueBits(oB); caps2.setAlphaBits(oA); - return caps2; + return caps2; } return caps; } - + public static int clipColor(final int compIn, final boolean allowRGB555) { final int compOut; if( 5 < compIn || !allowRGB555 ) { - compOut = 8; + compOut = 8; } else { compOut = 5; - } + } return compOut; } - + public static GLCapabilitiesImmutable fixGLProfile(GLCapabilitiesImmutable caps, GLProfile glp) { if( caps.getGLProfile() != glp ) { diff --git a/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java index 6d9116303..a22454d60 100644 --- a/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -42,10 +42,10 @@ import com.jogamp.opengl.GLAutoDrawableDelegate; import jogamp.opengl.GLFBODrawableImpl; public class GLOffscreenAutoDrawableImpl extends GLAutoDrawableDelegate implements GLOffscreenAutoDrawable { - + /** * @param drawable a valid {@link GLDrawable}, may not be {@link GLDrawable#isRealized() realized} yet. - * @param context a valid {@link GLContext}, + * @param context a valid {@link GLContext}, * may not have been made current (created) yet, * may not be associated w/ drawable yet, * may be null for lazy initialization @@ -55,16 +55,16 @@ public class GLOffscreenAutoDrawableImpl extends GLAutoDrawableDelegate implemen public GLOffscreenAutoDrawableImpl(GLDrawable drawable, GLContext context, Object upstreamWidget, RecursiveLock lock) { super(drawable, context, upstreamWidget, true, lock); } - + @Override public void setSize(int newWidth, int newHeight) throws NativeWindowException, GLException { this.defaultWindowResizedOp(newWidth, newHeight); } - - public static class FBOImpl extends GLOffscreenAutoDrawableImpl implements GLOffscreenAutoDrawable.FBO { + + public static class FBOImpl extends GLOffscreenAutoDrawableImpl implements GLOffscreenAutoDrawable.FBO { /** * @param drawable a valid {@link GLDrawable}, may not be {@link GLDrawable#isRealized() realized} yet. - * @param context a valid {@link GLContext}, + * @param context a valid {@link GLContext}, * may not have been made current (created) yet, * may not be associated w/ drawable yet, * may be null for lazy initialization @@ -74,7 +74,7 @@ public class GLOffscreenAutoDrawableImpl extends GLAutoDrawableDelegate implemen public FBOImpl(GLFBODrawableImpl drawable, GLContext context, Object upstreamWidget, RecursiveLock lock) { super(drawable, context, upstreamWidget, lock); } - + @Override public boolean isInitialized() { return ((GLFBODrawableImpl)drawable).isInitialized(); @@ -84,7 +84,7 @@ public class GLOffscreenAutoDrawableImpl extends GLAutoDrawableDelegate implemen public final int getTextureUnit() { return ((GLFBODrawableImpl)drawable).getTextureUnit(); } - + @Override public final void setTextureUnit(int unit) { ((GLFBODrawableImpl)drawable).setTextureUnit(unit); @@ -94,23 +94,23 @@ public class GLOffscreenAutoDrawableImpl extends GLAutoDrawableDelegate implemen public final int getNumSamples() { return ((GLFBODrawableImpl)drawable).getNumSamples(); } - + @Override public final void setNumSamples(GL gl, int newSamples) throws GLException { ((GLFBODrawableImpl)drawable).setNumSamples(gl, newSamples); windowRepaintOp(); } - + @Override public final int setNumBuffers(int bufferCount) throws GLException { return ((GLFBODrawableImpl)drawable).setNumBuffers(bufferCount); } - + @Override public final int getNumBuffers() { return ((GLFBODrawableImpl)drawable).getNumBuffers(); } - + /** // TODO: Add or remove TEXTURE (only) DoubleBufferMode support @Override public DoubleBufferMode getDoubleBufferMode() { @@ -119,14 +119,14 @@ public class GLOffscreenAutoDrawableImpl extends GLAutoDrawableDelegate implemen @Override public void setDoubleBufferMode(DoubleBufferMode mode) throws GLException { - ((GLFBODrawableImpl)drawable).setDoubleBufferMode(mode); + ((GLFBODrawableImpl)drawable).setDoubleBufferMode(mode); } */ - + @Override - public final FBObject getFBObject(int bufferName) { + public final FBObject getFBObject(int bufferName) { return ((GLFBODrawableImpl)drawable).getFBObject(bufferName); } - + public final FBObject.TextureAttachment getTextureBuffer(int bufferName) { return ((GLFBODrawableImpl)drawable).getTextureBuffer(bufferName); } @@ -134,6 +134,6 @@ public class GLOffscreenAutoDrawableImpl extends GLAutoDrawableDelegate implemen @Override public void resetSize(GL gl) throws GLException { ((GLFBODrawableImpl)drawable).resetSize(gl); - } + } } } diff --git a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java index b8841d6e2..c32957b86 100644 --- a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java @@ -51,7 +51,7 @@ import com.jogamp.common.util.locks.RecursiveLock; public class GLPbufferImpl extends GLAutoDrawableBase implements GLPbuffer { public GLPbufferImpl(GLDrawableImpl pbufferDrawable, GLContextImpl pbufferContext) { - super(pbufferDrawable, pbufferContext, true); // drawable := pbufferDrawable, context := pbufferContext + super(pbufferDrawable, pbufferContext, true); // drawable := pbufferDrawable, context := pbufferContext } // @@ -60,26 +60,26 @@ public class GLPbufferImpl extends GLAutoDrawableBase implements GLPbuffer { // // GLDrawable delegation - // - + // + @Override public final void swapBuffers() throws GLException { defaultSwapBuffers(); } - + // // GLAutoDrawable completion // private final RecursiveLock lock = LockFactory.createRecursiveLock(); // instance wide lock - + @Override protected final RecursiveLock getLock() { return lock; } - + @Override public final Object getUpstreamWidget() { return null; } - + @Override public void destroy() { defaultDestroy(); @@ -92,7 +92,7 @@ public class GLPbufferImpl extends GLAutoDrawableBase implements GLPbuffer { @Override public final void display() { - final RecursiveLock _lock = lock; + final RecursiveLock _lock = lock; _lock.lock(); // sync: context/drawable could been recreated/destroyed while animating try { if( null != context ) { diff --git a/src/jogl/classes/jogamp/opengl/GLRunnableTask.java b/src/jogl/classes/jogamp/opengl/GLRunnableTask.java index 244a3fd79..2238d49bc 100644 --- a/src/jogl/classes/jogamp/opengl/GLRunnableTask.java +++ b/src/jogl/classes/jogamp/opengl/GLRunnableTask.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl; import javax.media.opengl.GLRunnable; @@ -86,41 +86,41 @@ public class GLRunnableTask implements GLRunnable { } return res; } - - /** + + /** * Simply flush this task and notify a waiting executor. * The executor which might have been blocked until notified * will be unblocked and the task removed from the queue. - * + * * @see #isFlushed() * @see #isInQueue() - */ + */ public void flush() { if(!isExecuted() && null != notifyObject) { synchronized (notifyObject) { isFlushed=true; - notifyObject.notifyAll(); + notifyObject.notifyAll(); } } } - + /** * @return !{@link #isExecuted()} && !{@link #isFlushed()} */ public boolean isInQueue() { return !isExecuted && !isFlushed; } - + /** * @return whether this task has been executed. * @see #isInQueue() */ public boolean isExecuted() { return isExecuted; } - + /** * @return whether this task has been flushed. * @see #isInQueue() */ public boolean isFlushed() { return isFlushed; } - + public Throwable getThrowable() { return runnableException; } } diff --git a/src/jogl/classes/jogamp/opengl/GLStateTracker.java b/src/jogl/classes/jogamp/opengl/GLStateTracker.java index 01c3716e0..307fd0a15 100644 --- a/src/jogl/classes/jogamp/opengl/GLStateTracker.java +++ b/src/jogl/classes/jogamp/opengl/GLStateTracker.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2006 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 @@ -28,11 +28,11 @@ * 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. */ @@ -53,47 +53,47 @@ import java.util.ArrayList; * Currently supported states: PixelStorei */ public class GLStateTracker { - - /** Minimum value of MAX_CLIENT_ATTRIB_STACK_DEPTH */ + + /** Minimum value of MAX_CLIENT_ATTRIB_STACK_DEPTH */ public static final int MIN_CLIENT_ATTRIB_STACK_DEPTH = 16; - + /** static size of pixel state map */ static final int PIXEL_STATE_MAP_SIZE = 16; /** avoid rehash of static size pixel state map */ static final int PIXEL_STATE_MAP_CAPACITY = 32; - + private volatile boolean enabled = true; private IntIntHashMap pixelStateMap; private final ArrayList stack; - + private static class SavedState { /** * Empty pixel-store state - */ + */ private IntIntHashMap pixelStateMap; - + /** * set (client) pixel-store state, deep copy - */ + */ private final void setPixelStateMap(IntIntHashMap pixelStateMap) { this.pixelStateMap = (IntIntHashMap) pixelStateMap.clone(); } - + /** * get (client) pixel-store state, return reference - */ + */ private final IntIntHashMap getPixelStateMap() { return pixelStateMap; } } - - public GLStateTracker() { + + public GLStateTracker() { pixelStateMap = new IntIntHashMap(PIXEL_STATE_MAP_CAPACITY, 0.75f); pixelStateMap.setKeyNotFoundValue(0xFFFFFFFF); resetStates(); - + stack = new ArrayList(MIN_CLIENT_ATTRIB_STACK_DEPTH); } @@ -102,18 +102,18 @@ public class GLStateTracker { } public final void setEnabled(boolean on) { - enabled = on; + enabled = on; } public final boolean isEnabled() { return enabled; } - /** @return true if found in our map, otherwise false, + /** @return true if found in our map, otherwise false, * which forces the caller to query GL. */ public final boolean getInt(int pname, int[] params, int params_offset) { if(enabled) { - final int value = pixelStateMap.get(pname); + final int value = pixelStateMap.get(pname); if(0xFFFFFFFF != value) { params[params_offset] = value; return true; @@ -122,7 +122,7 @@ public class GLStateTracker { return false; } - /** @return true if found in our map, otherwise false, + /** @return true if found in our map, otherwise false, * which forces the caller to query GL. */ public final boolean getInt(int pname, IntBuffer params, int dummy) { if(enabled) { @@ -158,7 +158,7 @@ public class GLStateTracker { throw new GLException("stack contains no elements"); } SavedState state = stack.remove(stack.size()-1); // pop - + if(null==state) { throw new GLException("null stack element (remaining stack size "+stack.size()+")"); } @@ -166,7 +166,7 @@ public class GLStateTracker { if ( null != state.getPixelStateMap() ) { // use pulled client pixel-store state from stack pixelStateMap = state.getPixelStateMap(); - } // else: empty-slot, not pushed by GL_CLIENT_PIXEL_STORE_BIT + } // else: empty-slot, not pushed by GL_CLIENT_PIXEL_STORE_BIT } } diff --git a/src/jogl/classes/jogamp/opengl/GLVersionNumber.java b/src/jogl/classes/jogamp/opengl/GLVersionNumber.java index e4187b35b..431c1a387 100644 --- a/src/jogl/classes/jogamp/opengl/GLVersionNumber.java +++ b/src/jogl/classes/jogamp/opengl/GLVersionNumber.java @@ -43,9 +43,9 @@ public class GLVersionNumber extends VersionNumberString { super(val[0], val[1], val[2], strEnd, state, versionString); this.valid = valid; } - + private static java.util.regex.Pattern getUnderscorePattern() { - if( null == _Pattern ) { // volatile dbl-checked-locking OK + if( null == _Pattern ) { // volatile dbl-checked-locking OK synchronized( VersionNumber.class ) { if( null == _Pattern ) { _Pattern = getVersionNumberPattern("_"); @@ -55,7 +55,7 @@ public class GLVersionNumber extends VersionNumberString { return _Pattern; } private static volatile java.util.regex.Pattern _Pattern = null; - + public static final GLVersionNumber create(String versionString) { int[] val = new int[] { 0, 0, 0 }; int strEnd = 0; @@ -73,7 +73,7 @@ public class GLVersionNumber extends VersionNumberString { strEnd = version.endOfStringMatch(); val[0] = version.getMajor(); val[1] = version.getMinor(); - state = (short) ( ( version.hasMajor() ? VersionNumber.HAS_MAJOR : (short)0 ) | + state = (short) ( ( version.hasMajor() ? VersionNumber.HAS_MAJOR : (short)0 ) | ( version.hasMinor() ? VersionNumber.HAS_MINOR : (short)0 ) ); valid = version.hasMajor() && version.hasMinor(); // Requires at least a defined major and minor version component! } catch (Exception e) { @@ -82,16 +82,16 @@ public class GLVersionNumber extends VersionNumberString { val[0] = 1; val[1] = 0; } - } + } return new GLVersionNumber(val, strEnd, state, versionString, valid); } public final boolean isValid() { return valid; } - - /** - * Returns the optional vendor version at the end of the + + /** + * Returns the optional vendor version at the end of the * GL_VERSION string if exists, otherwise the {@link VersionNumberString#zeroVersion zero version} instance. *
                      *   2.1 Mesa 7.0.3-rc2 -> 7.0.3 (7.0.3-rc2)
                @@ -105,14 +105,14 @@ public class GLVersionNumber extends VersionNumberString {
                         if (versionString == null || versionString.length() <= 0) {
                             return null;
                         }
                -        
                +
                         // Skip the 1st GL version
                         String str;
                         {
                             final GLVersionNumber glv = create(versionString);
                             str = versionString.substring(glv.endOfStringMatch()).trim();
                         }
                -        
                +
                         while ( str.length() > 0 ) {
                             final VersionNumberString version = new VersionNumberString(str, getDefaultVersionNumberPattern());
                             final int eosm = version.endOfStringMatch();
                diff --git a/src/jogl/classes/jogamp/opengl/GLWorkerThread.java b/src/jogl/classes/jogamp/opengl/GLWorkerThread.java
                index 112dfcb64..979c6dc0a 100644
                --- a/src/jogl/classes/jogamp/opengl/GLWorkerThread.java
                +++ b/src/jogl/classes/jogamp/opengl/GLWorkerThread.java
                @@ -1,21 +1,21 @@
                 /*
                  * Copyright (c) 2006 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
                @@ -28,11 +28,11 @@
                  * 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.
                  */
                @@ -67,7 +67,7 @@ public class GLWorkerThread {
                   private static volatile Runnable work;
                   // Queue of Runnables to be asynchronously invoked
                   private static List queue = new ArrayList();
                -  
                +
                   /** Should only be called by Threading class if creation of the
                       GLWorkerThread was requested via the opengl.1thread system
                       property. 
                @@ -149,7 +149,7 @@ public class GLWorkerThread { } } - public static void invoke(boolean wait, Runnable runnable) + public static void invoke(boolean wait, Runnable runnable) throws InvocationTargetException, InterruptedException { if(wait) { invokeAndWait(runnable); @@ -157,7 +157,7 @@ public class GLWorkerThread { invokeLater(runnable); } } - + public static void invokeAndWait(Runnable runnable) throws InvocationTargetException, InterruptedException { if (!started) { @@ -220,7 +220,7 @@ public class GLWorkerThread { } protected static String getThreadName() { return Thread.currentThread().getName(); } - + static class WorkerRunnable implements Runnable { public void run() { // Notify starting thread that we're ready @@ -244,7 +244,7 @@ public class GLWorkerThread { break; } } - + if (shouldTerminate) { lock.notifyAll(); thread = null; diff --git a/src/jogl/classes/jogamp/opengl/GLXExtensions.java b/src/jogl/classes/jogamp/opengl/GLXExtensions.java index 36c6c4665..9325c6f68 100644 --- a/src/jogl/classes/jogamp/opengl/GLXExtensions.java +++ b/src/jogl/classes/jogamp/opengl/GLXExtensions.java @@ -28,9 +28,9 @@ package jogamp.opengl; /** - * Class holding GLX/WGL/.. extension strings, commonly used by JOGL's implementation. + * Class holding GLX/WGL/.. extension strings, commonly used by JOGL's implementation. */ -public class GLXExtensions { +public class GLXExtensions { public static final String GLX_MESA_swap_control = "GLX_MESA_swap_control"; public static final String GLX_SGI_swap_control = "GLX_SGI_swap_control"; public static final String GLX_NV_swap_group = "GLX_NV_swap_group"; diff --git a/src/jogl/classes/jogamp/opengl/ListenerSyncedImplStub.java b/src/jogl/classes/jogamp/opengl/ListenerSyncedImplStub.java index 1cde551be..a64a2f5cd 100644 --- a/src/jogl/classes/jogamp/opengl/ListenerSyncedImplStub.java +++ b/src/jogl/classes/jogamp/opengl/ListenerSyncedImplStub.java @@ -33,9 +33,9 @@ import java.util.ArrayList; /** * Simple locked listener implementation stub to be used for listener handler, * synchronized on it's instance. - * + * *

                Utilizing simple locking via synchronized.

                - * + * * @param The listener type */ public class ListenerSyncedImplStub { @@ -48,7 +48,7 @@ public class ListenerSyncedImplStub { public synchronized final void reset() { listeners = new ArrayList(); } - + public synchronized final void destroy() { listeners.clear(); listeners = null; @@ -57,7 +57,7 @@ public class ListenerSyncedImplStub { public synchronized final int size() { return listeners.size(); } - + public synchronized final void addListener(E listener) { addListener(-1, listener); } @@ -68,12 +68,12 @@ public class ListenerSyncedImplStub { } listeners.add(index, listener); } - + public synchronized final void removeListener(E listener) { listeners.remove(listener); } public final ArrayList getListeners() { return listeners; - } + } } diff --git a/src/jogl/classes/jogamp/opengl/ProjectFloat.java b/src/jogl/classes/jogamp/opengl/ProjectFloat.java index 439ddc76e..d4fd1c935 100644 --- a/src/jogl/classes/jogamp/opengl/ProjectFloat.java +++ b/src/jogl/classes/jogamp/opengl/ProjectFloat.java @@ -6,9 +6,9 @@ ** 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 @@ -24,13 +24,13 @@ ** except that Section 2.2 and 11 are omitted. Any differences between ** the Alternative License and the SGI License are offered solely by Sun ** and not by SGI. -** +** ** 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 @@ -45,34 +45,34 @@ ** $Header$ */ -/* +/* * 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 + * modification, are permitted provided that the following conditions are * met: - * - * * Redistributions of source code must retain the above copyright + * + * * 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 + * * 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 + * 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 + * 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. */ @@ -80,22 +80,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2011 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 @@ -108,7 +108,7 @@ * 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. @@ -129,14 +129,14 @@ import com.jogamp.opengl.math.FloatUtil; *

                * Created 11-jan-2004 *

                - * + * * @author Erik Duijs * @author Kenneth Russell * @author Sven Gothel */ public class ProjectFloat { public static final int getRequiredFloatBufferSize() { return 1*16; } - + // Note that we have cloned parts of the implementation in order to // support incoming Buffers. The reason for this is to avoid loading // non-direct buffer subclasses unnecessarily, because doing so can @@ -162,22 +162,22 @@ public class ProjectFloat { public ProjectFloat() { this(true); } - + public ProjectFloat(boolean useBackingArray) { - this(useBackingArray ? null : Buffers.newDirectByteBuffer(getRequiredFloatBufferSize() * Buffers.SIZEOF_FLOAT), - useBackingArray ? new float[getRequiredFloatBufferSize()] : null, + this(useBackingArray ? null : Buffers.newDirectByteBuffer(getRequiredFloatBufferSize() * Buffers.SIZEOF_FLOAT), + useBackingArray ? new float[getRequiredFloatBufferSize()] : null, 0); } /** * @param floatBuffer source buffer, may be ByteBuffer (recommended) or FloatBuffer or null. - * If used, shall be ≥ {@link #getRequiredFloatBufferSize()} + floatOffset. + * If used, shall be ≥ {@link #getRequiredFloatBufferSize()} + floatOffset. * Buffer's position is ignored and floatPos is being used. * @param floatArray source float array or null. * If used, size shall be ≥ {@link #getRequiredFloatBufferSize()} + floatOffset. * @param floatOffset Offset for either of the given sources (buffer or array) */ - public ProjectFloat(Buffer floatBuffer, float[] floatArray, int floatOffset) { + public ProjectFloat(Buffer floatBuffer, float[] floatArray, int floatOffset) { matrixBuf = Buffers.slice2Float(floatBuffer, floatArray, floatOffset, 16); } @@ -259,7 +259,7 @@ public class ProjectFloat { /** * @param src * @param inverse - * + * * @return */ public boolean gluInvertMatrixf(FloatBuffer src, FloatBuffer inverse) { @@ -268,7 +268,7 @@ public class ProjectFloat { final int srcPos = src.position(); final int invPos = inverse.position(); - + final float[][] temp = tempInvertMatrix; for (i = 0; i < 4; i++) { @@ -297,7 +297,7 @@ public class ProjectFloat { t = temp[i][k]; temp[i][k] = temp[swap][k]; temp[swap][k] = t; - + t = inverse.get(i*4+k + invPos); inverse.put(i*4+k + invPos, inverse.get(swap*4+k + invPos)); inverse.put(swap*4+k + invPos, t); @@ -335,7 +335,7 @@ public class ProjectFloat { /** * Method gluOrtho2D. - * + * * @param left * @param right * @param bottom @@ -347,7 +347,7 @@ public class ProjectFloat { /** * Method gluPerspective. - * + * * @param fovy * @param aspect * @param zNear @@ -380,7 +380,7 @@ public class ProjectFloat { /** * Method gluLookAt - * + * * @param eyex * @param eyey * @param eyez @@ -436,7 +436,7 @@ public class ProjectFloat { /** * Map object coordinates to window coordinates. - * + * * @param objx * @param objy * @param objz @@ -444,7 +444,7 @@ public class ProjectFloat { * @param projMatrix * @param viewport * @param win_pos - * + * * @return */ public boolean gluProject(float objx, float objy, float objz, @@ -518,13 +518,13 @@ public class ProjectFloat { win_pos[0+win_pos_offset] = in[0] * viewport[2+viewport_offset] + viewport[0+viewport_offset]; win_pos[1+win_pos_offset] = in[1] * viewport[3+viewport_offset] + viewport[1+viewport_offset]; win_pos[2+win_pos_offset] = in[2]; - + return true; } - + /** * Map object coordinates to window coordinates. - * + * * @param objx * @param objy * @param objz @@ -532,7 +532,7 @@ public class ProjectFloat { * @param projMatrix * @param viewport * @param win_pos - * + * * @return */ public boolean gluProject(float objx, float objy, float objz, @@ -576,7 +576,7 @@ public class ProjectFloat { /** * Map window coordinates to object coordinates. - * + * * @param winx * @param winy * @param winz @@ -584,7 +584,7 @@ public class ProjectFloat { * @param projMatrix * @param viewport * @param obj_pos - * + * * @return */ public boolean gluUnProject(float winx, float winy, float winz, @@ -633,7 +633,7 @@ public class ProjectFloat { /** * Map window coordinates to object coordinates. - * + * * @param winx * @param winy * @param winz @@ -646,7 +646,7 @@ public class ProjectFloat { * @return */ public boolean gluUnProject(float winx, float winy, float winz, - FloatBuffer modelMatrix, + FloatBuffer modelMatrix, FloatBuffer projMatrix, int[] viewport, int viewport_offset, float[] obj_pos, int obj_pos_offset) { @@ -674,7 +674,7 @@ public class ProjectFloat { in[2] = in[2] * 2 - 1; FloatUtil.multMatrixVecf(matrixBuf, in, out); - + if (out[3] == 0.0) { return false; } @@ -687,10 +687,10 @@ public class ProjectFloat { return true; } - + /** * Map window coordinates to object coordinates. - * + * * @param winx * @param winy * @param winz @@ -698,11 +698,11 @@ public class ProjectFloat { * @param projMatrix * @param viewport * @param obj_pos - * + * * @return */ public boolean gluUnProject(float winx, float winy, float winz, - FloatBuffer modelMatrix, + FloatBuffer modelMatrix, FloatBuffer projMatrix, IntBuffer viewport, FloatBuffer obj_pos) { @@ -722,7 +722,7 @@ public class ProjectFloat { // Map x and y from window coordinates final int vPos = viewport.position(); - final int oPos = obj_pos.position(); + final int oPos = obj_pos.position(); in[0] = (in[0] - viewport.get(0+vPos)) / viewport.get(2+vPos); in[1] = (in[1] - viewport.get(1+vPos)) / viewport.get(3+vPos); @@ -749,7 +749,7 @@ public class ProjectFloat { /** * Map window coordinates to object coordinates. - * + * * @param winx * @param winy * @param winz @@ -760,7 +760,7 @@ public class ProjectFloat { * @param near * @param far * @param obj_pos - * + * * @return */ public boolean gluUnProject4(float winx, @@ -815,7 +815,7 @@ public class ProjectFloat { /** * Map window coordinates to object coordinates. - * + * * @param winx * @param winy * @param winz @@ -826,7 +826,7 @@ public class ProjectFloat { * @param near * @param far * @param obj_pos - * + * * @return */ public boolean gluUnProject4(float winx, @@ -857,7 +857,7 @@ public class ProjectFloat { in[0] = (in[0] - viewport.get(0+vPos)) / viewport.get(2+vPos); in[1] = (in[1] - viewport.get(1+vPos)) / viewport.get(3+vPos); in[2] = (in[2] - near) / (far - near); - + // Map to range -1 to 1 in[0] = in[0] * 2 - 1; in[1] = in[1] * 2 - 1; @@ -873,14 +873,14 @@ public class ProjectFloat { obj_pos.put(0+oPos, out[0]); obj_pos.put(1+oPos, out[1]); obj_pos.put(2+oPos, out[2]); - obj_pos.put(3+oPos, out[3]); + obj_pos.put(3+oPos, out[3]); return true; } /** * Method gluPickMatrix - * + * * @param x * @param y * @param deltaX @@ -907,7 +907,7 @@ public class ProjectFloat { /** * Method gluPickMatrix - * + * * @param x * @param y * @param deltaX diff --git a/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java b/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java index e5f5ee09a..eddb36975 100644 --- a/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java +++ b/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java @@ -52,30 +52,30 @@ public class SharedResourceRunner implements Runnable { *

                * Called within synchronized block. *

                - * @param connection for creation a {@link AbstractGraphicsDevice} instance. - * @return true if the device supports all protocols required for the implementation, otherwise false. + * @param connection for creation a {@link AbstractGraphicsDevice} instance. + * @return true if the device supports all protocols required for the implementation, otherwise false. */ boolean isDeviceSupported(String connection); - + /** *

                * Called within synchronized block. *

                - * @param connection for creation a {@link AbstractGraphicsDevice} instance. - * @return A new shared resource instance + * @param connection for creation a {@link AbstractGraphicsDevice} instance. + * @return A new shared resource instance */ Resource createSharedResource(String connection); - - /** Called within synchronized block. */ + + /** Called within synchronized block. */ void releaseSharedResource(Resource shared); - /** Called within synchronized block. */ + /** Called within synchronized block. */ void clear(); - /** Called within synchronized block. */ + /** Called within synchronized block. */ Resource mapPut(String connection, Resource resource); - /** Called within synchronized block. */ + /** Called within synchronized block. */ Resource mapGet(String connection); - /** Called within synchronized block. */ + /** Called within synchronized block. */ Collection mapValues(); } @@ -103,7 +103,7 @@ public class SharedResourceRunner implements Runnable { this.impl = impl; resetState(); } - + private void resetState() { // synchronized call devicesTried.clear(); thread = null; @@ -114,12 +114,12 @@ public class SharedResourceRunner implements Runnable { releaseConnection = null; } - /** + /** * Start the shared resource runner thread, if not running. *

                * Validate the thread upfront and release all related resource if it was killed. *

                - * + * * @return the shared resource runner thread. */ public Thread start() { @@ -132,7 +132,7 @@ public class SharedResourceRunner implements Runnable { releaseSharedResources(); thread = null; running = false; - } + } if( null == thread ) { if (DEBUG) { System.err.println("SharedResourceRunner.start() - start new Thread - "+getThreadName()); @@ -150,7 +150,7 @@ public class SharedResourceRunner implements Runnable { } return thread; } - + public void stop() { synchronized (this) { if(null != thread) { @@ -160,7 +160,7 @@ public class SharedResourceRunner implements Runnable { synchronized (this) { shouldRelease = true; this.notifyAll(); - + while (running) { try { this.wait(); @@ -170,7 +170,7 @@ public class SharedResourceRunner implements Runnable { } } } - + public SharedResourceRunner.Resource getOrCreateShared(AbstractGraphicsDevice device) { SharedResourceRunner.Resource sr = null; if(null != device) { @@ -203,7 +203,7 @@ public class SharedResourceRunner implements Runnable { if(null != device) { synchronized (this) { final String connection = device.getConnection(); - sr = impl.mapGet(connection); + sr = impl.mapGet(connection); if (null != sr) { removeDeviceTried(connection); if (DEBUG) { @@ -261,7 +261,7 @@ public class SharedResourceRunner implements Runnable { synchronized (this) { running = true; - + while (!shouldRelease) { try { // wait for stop or init @@ -271,7 +271,7 @@ public class SharedResourceRunner implements Runnable { } notifyAll(); this.wait(); - } catch (InterruptedException ex) { + } catch (InterruptedException ex) { shouldRelease = true; if(DEBUG) { System.err.println("SharedResourceRunner.run(): INTERRUPTED - "+threadName); @@ -311,7 +311,7 @@ public class SharedResourceRunner implements Runnable { } catch (Exception e) { e.printStackTrace(); } - } + } } } initConnection = null; diff --git a/src/jogl/classes/jogamp/opengl/ThreadingImpl.java b/src/jogl/classes/jogamp/opengl/ThreadingImpl.java index d55a2c976..6ffe46b36 100644 --- a/src/jogl/classes/jogamp/opengl/ThreadingImpl.java +++ b/src/jogl/classes/jogamp/opengl/ThreadingImpl.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2009 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.opengl; @@ -49,14 +49,14 @@ import com.jogamp.common.util.ReflectionUtil; public class ThreadingImpl { public enum Mode { - MT(0), ST_AWT(1), ST_WORKER(2); - + MT(0), ST_AWT(1), ST_WORKER(2); + public final int id; Mode(int id){ this.id = id; } - } + } protected static final boolean DEBUG = Debug.debug("Threading"); @@ -68,7 +68,7 @@ public class ThreadingImpl { private static boolean _isX11; private static final ToolkitThreadingPlugin threadingPlugin; - + static { threadingPlugin = AccessController.doPrivileged(new PrivilegedAction() { @@ -94,7 +94,7 @@ public class ThreadingImpl { // default setting singleThreaded = true; mode = ( hasAWT ? Mode.ST_AWT : Mode.ST_WORKER ); - + if (singleThreadProp != null) { if (singleThreadProp.equals("true") || singleThreadProp.equals("auto")) { @@ -113,7 +113,7 @@ public class ThreadingImpl { throw new RuntimeException("Unsupported value for property jogl.1thread: "+singleThreadProp+", should be [true/auto, worker, awt or false]"); } } - + ToolkitThreadingPlugin threadingPlugin=null; if(hasAWT) { // try to fetch the AWTThreadingPlugin @@ -139,9 +139,9 @@ public class ThreadingImpl { public static boolean isX11() { return _isX11; } public static Mode getMode() { return mode; } - /** If an implementation of the javax.media.opengl APIs offers a - multithreading option but the default behavior is single-threading, - this API provides a mechanism for end users to disable single-threading + /** If an implementation of the javax.media.opengl APIs offers a + multithreading option but the default behavior is single-threading, + this API provides a mechanism for end users to disable single-threading in this 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 @@ -151,7 +151,7 @@ public class ThreadingImpl { GLPbuffer. Currently there is no supported way to re-enable it once disabled, partly to discourage careless use of this method. This method should be called as early as possible in an - application. */ + application. */ public static final void disableSingleThreading() { singleThreaded = false; if (Debug.verbose()) { @@ -183,7 +183,7 @@ public class ThreadingImpl { throw new InternalError("Illegal single-threading mode " + mode); } } - + public static final boolean isToolkitThread() throws GLException { if(null!=threadingPlugin) { return threadingPlugin.isToolkitThread(); @@ -215,7 +215,7 @@ public class ThreadingImpl { throw new InternalError("Illegal single-threading mode " + mode); } } - + public static final void invokeOnWorkerThread(boolean wait, Runnable r) throws GLException { GLWorkerThread.start(); // singleton start via volatile-dbl-checked-locking try { @@ -224,6 +224,6 @@ public class ThreadingImpl { throw new GLException(e.getTargetException()); } catch (InterruptedException e) { throw new GLException(e); - } + } } } diff --git a/src/jogl/classes/jogamp/opengl/ToolkitThreadingPlugin.java b/src/jogl/classes/jogamp/opengl/ToolkitThreadingPlugin.java index 22972953a..06fb0fe91 100644 --- a/src/jogl/classes/jogamp/opengl/ToolkitThreadingPlugin.java +++ b/src/jogl/classes/jogamp/opengl/ToolkitThreadingPlugin.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2012 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 @@ -29,11 +29,11 @@ * 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. */ @@ -46,7 +46,7 @@ public interface ToolkitThreadingPlugin { /** Indicates whether the current thread is the designated toolkit thread, if such semantics exists. */ public boolean isToolkitThread() throws GLException; - + /** Indicates whether the current thread is the thread on which this implementation of the javax.media.opengl APIs performs all of its OpenGL-related work. This method should only diff --git a/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java b/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java index 56f00b370..cd1bb45c9 100644 --- a/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java +++ b/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -57,7 +57,7 @@ public class AWTThreadingPlugin implements ToolkitThreadingPlugin { public final boolean isToolkitThread() throws GLException { return EventQueue.isDispatchThread(); } - + public final boolean isOpenGLThread() throws GLException { switch (ThreadingImpl.getMode()) { case ST_AWT: diff --git a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java index 9bdceff48..5faee1307 100644 --- a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java +++ b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -67,19 +67,19 @@ import com.jogamp.opengl.util.awt.AWTGLPixelBuffer.AWTGLPixelBufferProvider; */ public class AWTTilePainter { private static final boolean DEBUG_TILES = Debug.debug("TileRenderer.PNG"); - + public final TileRenderer renderer; public final int componentCount; public final double scaleMatX, scaleMatY; public final int customTileWidth, customTileHeight, customNumSamples; public final boolean verbose; - + public boolean flipVertical; private AWTGLPixelBuffer tBuffer = null; private BufferedImage vFlipImage = null; private Graphics2D g2d = null; - private AffineTransform saveAT = null; - + private AffineTransform saveAT = null; + public static void dumpHintsAndScale(Graphics2D g2d) { final RenderingHints rHints = g2d.getRenderingHints(); final Set> rEntries = rHints.entrySet(); @@ -92,13 +92,13 @@ public class AWTTilePainter { if( null != aTrans ) { System.err.println(" type "+aTrans.getType()); System.err.println(" scale "+aTrans.getScaleX()+" x "+aTrans.getScaleY()); - System.err.println(" move "+aTrans.getTranslateX()+" x "+aTrans.getTranslateY()); + System.err.println(" move "+aTrans.getTranslateX()+" x "+aTrans.getTranslateY()); System.err.println(" mat "+aTrans); } else { System.err.println(" null transform"); } } - + /** * @return resulting number of samples by comparing w/ {@link #customNumSamples} and the caps-config, 0 if disabled */ @@ -114,12 +114,12 @@ public class AWTTilePainter { return caps.getNumSamples(); } } - - /** + + /** * Assumes a configured {@link TileRenderer}, i.e. * an {@link TileRenderer#attachAutoDrawable(GLAutoDrawable) attached} * {@link GLAutoDrawable} with {@link TileRenderer#setTileSize(int, int, int) set tile size}. - *

                + *

                * Sets the renderer to {@link TileRenderer#TR_TOP_TO_BOTTOM} row order. *

                *

                @@ -129,7 +129,7 @@ public class AWTTilePainter { * @param componentCount * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels - * @param numSamples custom multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param numSamples custom multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples * @param tileWidth custom tile width for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. * @param tileHeight custom tile height for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. * @param verbose @@ -146,13 +146,13 @@ public class AWTTilePainter { this.verbose = verbose; this.flipVertical = true; } - + public String toString() { return renderer.toString(); } - + public void setIsGLOriented(boolean v) { flipVertical = v; } - + private static Rectangle2D getClipBounds2D(Graphics2D g) { final Shape shape = g.getClip(); return null != shape ? shape.getBounds2D() : null; @@ -170,7 +170,7 @@ public class AWTTilePainter { } return new Rectangle2D.Double(x, y, width, height); } - + /** * Caches the {@link Graphics2D} instance for rendering. *

                @@ -201,9 +201,9 @@ public class AWTTilePainter { final Rectangle2D dClipOrigR = getClipBounds2D(g2d); final Rectangle2D dClipOrig = clipNegative(dClipOrigR); final Rectangle2D dImageSizeOrig = new Rectangle2D.Double(0, 0, width, height); - + // Retrieve scaled image-size and clip-bounds - // Note: Clip bounds lie within image-size! + // Note: Clip bounds lie within image-size! final Rectangle2D dImageSizeScaled, dClipScaled; { final AffineTransform scaledATI; @@ -230,10 +230,10 @@ public class AWTTilePainter { // GL y-offset is lower-left origin, AWT y-offset upper-left. scaledYOffset = iClipScaled.y; renderer.setTileOffset(iClipScaled.x, iImageSizeScaled.height - ( iClipScaled.y + clipH )); - + // Scale actual Grahics2D matrix g2d.scale(scaleMatX, scaleMatY); - + if( verbose ) { System.err.println("AWT print.0: image "+dImageSizeOrig + " -> " + dImageSizeScaled + " -> " + iImageSizeScaled); System.err.println("AWT print.0: clip "+dClipOrigR + " -> " + dClipOrig + " -> " + dClipScaled + " -> " + iClipScaled); @@ -241,12 +241,12 @@ public class AWTTilePainter { } } private int scaledYOffset; - + /** See {@ #setupGraphics2DAndClipBounds(Graphics2D)}. */ - public void resetGraphics2D() { + public void resetGraphics2D() { g2d.setTransform(saveAT); } - + /** * Disposes resources and {@link TileRenderer#detachAutoDrawable() detaches} * the {@link TileRenderer}'s {@link GLAutoDrawable}. @@ -263,7 +263,7 @@ public class AWTTilePainter { vFlipImage = null; } } - + final GLEventListener preTileGLEL = new GLEventListener() { @Override public void init(GLAutoDrawable drawable) {} @@ -275,7 +275,7 @@ public class AWTTilePainter { if( null == tBuffer ) { final int tWidth = renderer.getParam(TileRenderer.TR_TILE_WIDTH); final int tHeight = renderer.getParam(TileRenderer.TR_TILE_HEIGHT); - final AWTGLPixelBufferProvider printBufferProvider = new AWTGLPixelBufferProvider( true /* allowRowStride */ ); + final AWTGLPixelBufferProvider printBufferProvider = new AWTGLPixelBufferProvider( true /* allowRowStride */ ); final GLPixelAttributes pixelAttribs = printBufferProvider.getAttributes(gl, componentCount); tBuffer = printBufferProvider.allocate(gl, pixelAttribs, tWidth, tHeight, 1, true, 0); renderer.setTileBuffer(tBuffer); @@ -300,7 +300,7 @@ public class AWTTilePainter { @Override public void dispose(GLAutoDrawable drawable) {} @Override - public void display(GLAutoDrawable drawable) { + public void display(GLAutoDrawable drawable) { final DimensionImmutable cis = renderer.getClippedImageSize(); final int tWidth = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_WIDTH); final int tHeight = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_HEIGHT); @@ -309,26 +309,26 @@ public class AWTTilePainter { final int imgYOff = flipVertical ? 0 : renderer.getParam(TileRenderer.TR_TILE_HEIGHT) - tHeight; // imgYOff will be cut-off via sub-image final int pX = renderer.getParam(TileRendererBase.TR_CURRENT_TILE_X_POS); // tileX == pX final int pY = cis.getHeight() - ( tY - tYOff + tHeight ) + scaledYOffset; - + // Copy temporary data into raster of BufferedImage for faster // blitting Note that we could avoid this copy in the cases // where !offscreenDrawable.isGLOriented(), // but that's the software rendering path which is very slow anyway. final BufferedImage dstImage; if( DEBUG_TILES ) { - final String fname = String.format("file_%03d_0_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png", - _counter, + final String fname = String.format("file_%03d_0_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png", + _counter, renderer.getParam(TileRenderer.TR_CURRENT_COLUMN), renderer.getParam(TileRenderer.TR_CURRENT_ROW), tWidth, tHeight, pX, tY, tYOff, pX, pY).replace(' ', '_'); System.err.println("XXX file "+fname); - final File fout = new File(fname); + final File fout = new File(fname); try { ImageIO.write(tBuffer.image, "png", fout); } catch (IOException e) { e.printStackTrace(); } - } + } if( flipVertical ) { final BufferedImage srcImage = tBuffer.image; dstImage = vFlipImage; @@ -347,20 +347,20 @@ public class AWTTilePainter { dstImage = tBuffer.image; } if( DEBUG_TILES ) { - final String fname = String.format("file_%03d_1_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png", - _counter, + final String fname = String.format("file_%03d_1_tile_[%02d][%02d]_sz_%03dx%03d_pos0_%03d_%03d_yOff_%03d_pos1_%03d_%03d.png", + _counter, renderer.getParam(TileRenderer.TR_CURRENT_COLUMN), renderer.getParam(TileRenderer.TR_CURRENT_ROW), tWidth, tHeight, pX, tY, tYOff, pX, pY).replace(' ', '_'); System.err.println("XXX file "+fname); - final File fout = new File(fname); + final File fout = new File(fname); try { ImageIO.write(dstImage, "png", fout); } catch (IOException e) { e.printStackTrace(); } _counter++; - } + } // Draw resulting image in one shot final BufferedImage outImage = dstImage.getSubimage(0, imgYOff, tWidth, tHeight); final boolean drawDone = g2d.drawImage(outImage, pX, pY, null); // Null ImageObserver since image data is ready. diff --git a/src/jogl/classes/jogamp/opengl/awt/AWTUtil.java b/src/jogl/classes/jogamp/opengl/awt/AWTUtil.java index e15e538c2..dc286ca59 100644 --- a/src/jogl/classes/jogamp/opengl/awt/AWTUtil.java +++ b/src/jogl/classes/jogamp/opengl/awt/AWTUtil.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,7 +29,7 @@ * 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. @@ -85,7 +85,7 @@ public class AWTUtil { NativeWindowFactory.getAWTToolkitLock().lock(); } } catch (Exception e) { j2dOk=false; } - } + } if(!j2dOk) { NativeWindowFactory.getAWTToolkitLock().lock(); } @@ -108,7 +108,7 @@ public class AWTUtil { NativeWindowFactory.getAWTToolkitLock().unlock(); } } catch (Exception e) { j2dOk=false; } - } + } if(!j2dOk) { NativeWindowFactory.getAWTToolkitLock().unlock(); } diff --git a/src/jogl/classes/jogamp/opengl/awt/Java2D.java b/src/jogl/classes/jogamp/opengl/awt/Java2D.java index edf9e89f8..7a8ddf0b4 100644 --- a/src/jogl/classes/jogamp/opengl/awt/Java2D.java +++ b/src/jogl/classes/jogamp/opengl/awt/Java2D.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2003-2005 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 @@ -28,11 +28,11 @@ * 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. */ @@ -144,7 +144,7 @@ public class Java2D { } else { if (DEBUG) { System.err.println("Java2D support disabled: by Property "+java2dOGLDisabledByProp+", by OS "+java2dOGLDisabledByOS); - } + } cfg = null; cfgName = "nil"; } @@ -154,8 +154,8 @@ public class Java2D { System.err.println("Java2D support: default GraphicsConfiguration = " + cfgName); } isOGLPipelineActive = cfgName.startsWith("sun.java2d.opengl"); - isOGLPipelineResourceCompatible = isOGLPipelineActive; - + isOGLPipelineResourceCompatible = isOGLPipelineActive; + if (isOGLPipelineActive) { try { // Try to get methods we need to integrate @@ -179,19 +179,19 @@ public class Java2D { Integer.TYPE }); getOGLViewportMethod.setAccessible(true); - + getOGLScissorBoxMethod = utils.getDeclaredMethod("getOGLScissorBox", new Class[] { Graphics.class }); getOGLScissorBoxMethod.setAccessible(true); - + getOGLSurfaceIdentifierMethod = utils.getDeclaredMethod("getOGLSurfaceIdentifier", new Class[] { Graphics.class }); getOGLSurfaceIdentifierMethod.setAccessible(true); - + // Try to get additional methods required for proper FBO support fbObjectSupportInitialized = true; try { @@ -201,7 +201,7 @@ public class Java2D { Runnable.class }); invokeWithOGLSharedContextCurrentMethod.setAccessible(true); - + getOGLSurfaceTypeMethod = utils.getDeclaredMethod("getOGLSurfaceType", new Class[] { Graphics.class @@ -214,7 +214,7 @@ public class Java2D { System.err.println("Info: Disabling Java2D/JOGL FBO support"); } } - + // Try to get an additional method for FBO support in recent Mustang builds try { getOGLTextureTypeMethod = utils.getDeclaredMethod("getOGLTextureType", @@ -228,7 +228,7 @@ public class Java2D { System.err.println("Info: GL_ARB_texture_rectangle FBO support disabled"); } } - + // Try to set up APIs for enabling the bridge on OS X, // where it isn't possible to create generalized // external GLDrawables @@ -244,7 +244,7 @@ public class Java2D { if (cglSurfaceData != null) { // FIXME: for now, assume that FBO support is not enabled on OS X fbObjectSupportInitialized = false; - + // We need to find these methods in order to make the bridge work on OS X createOGLContextOnSurfaceMethod = cglSurfaceData.getDeclaredMethod("createOGLContextOnSurface", new Class[] { @@ -252,14 +252,14 @@ public class Java2D { Long.TYPE }); createOGLContextOnSurfaceMethod.setAccessible(true); - + makeOGLContextCurrentOnSurfaceMethod = cglSurfaceData.getDeclaredMethod("makeOGLContextCurrentOnSurface", new Class[] { Graphics.class, Long.TYPE }); makeOGLContextCurrentOnSurfaceMethod.setAccessible(true); - + destroyOGLContextMethod = cglSurfaceData.getDeclaredMethod("destroyOGLContext", new Class[] { Long.TYPE @@ -273,7 +273,7 @@ public class Java2D { System.err.println("Info: Disabling Java2D/JOGL integration"); } isOGLPipelineActive = false; - isOGLPipelineResourceCompatible = false; + isOGLPipelineResourceCompatible = false; } } } catch (HeadlessException e) { @@ -297,7 +297,7 @@ public class Java2D { public static boolean isOGLPipelineActive() { return isOGLPipelineActive; } - + public static boolean isOGLPipelineResourceCompatible() { return isOGLPipelineResourceCompatible; } @@ -317,7 +317,7 @@ public class Java2D { throw (InternalError) new InternalError().initCause(e); } } - + /** Makes current the OpenGL context associated with the passed Graphics object and runs the given Runnable on the Queue Flushing Thread in one atomic action. */ @@ -556,7 +556,7 @@ public class Java2D { throw new GLException("Java2D OpenGL pipeline not active"); } } - + private static void checkCompatible() { if ( !isOGLPipelineResourceCompatible() ) { throw new GLException("Java2D OpenGL pipeline not resource compatible"); diff --git a/src/jogl/classes/jogamp/opengl/awt/VersionApplet.java b/src/jogl/classes/jogamp/opengl/awt/VersionApplet.java index 55fb3f9a2..a29d1e6aa 100644 --- a/src/jogl/classes/jogamp/opengl/awt/VersionApplet.java +++ b/src/jogl/classes/jogamp/opengl/awt/VersionApplet.java @@ -42,7 +42,7 @@ public class VersionApplet extends Applet { va.init(); frame.add(va, BorderLayout.CENTER); frame.validate(); - + frame.setVisible(true); va.start(); } @@ -68,7 +68,7 @@ public class VersionApplet extends Applet { if(null != canvas) { return; } setEnabled(true); - + GLProfile glp = GLProfile.getDefault(); GLCapabilities glcaps = new GLCapabilities(glp); @@ -87,7 +87,7 @@ public class VersionApplet extends Applet { /* s = NativeWindowVersion.getInstance().toString(); System.err.println(s); - tareaVersion.append(NativeWindowVersion.getInstance().toString()); + tareaVersion.append(NativeWindowVersion.getInstance().toString()); */ s = JoglVersion.getInstance().toString(); diff --git a/src/jogl/classes/jogamp/opengl/egl/DesktopES2DynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/DesktopES2DynamicLibraryBundleInfo.java index 3d59d1d53..1179e2b7f 100644 --- a/src/jogl/classes/jogamp/opengl/egl/DesktopES2DynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/egl/DesktopES2DynamicLibraryBundleInfo.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl.egl; import java.util.*; @@ -60,12 +60,12 @@ public final class DesktopES2DynamicLibraryBundleInfo extends GLDynamicLibraryBu public final boolean useToolGetProcAdressFirst(String funcName) { return true; } - + public final List> getToolLibNames() { final List> libsList = new ArrayList>(); final List libsGL = new ArrayList(); - - // Be aware that on DRI systems, eg ATI fglrx, etc, + + // Be aware that on DRI systems, eg ATI fglrx, etc, // you have to set LIBGL_DRIVERS_PATH env variable. // Eg on Ubuntu 64bit systems this is: // export LIBGL_DRIVERS_PATH=/usr/lib/fglrx/dri:/usr/lib32/fglrx/dri @@ -82,15 +82,15 @@ public final class DesktopES2DynamicLibraryBundleInfo extends GLDynamicLibraryBu // OSX (guess ES2 on OSX will never happen) libsGL.add("/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib"); - + // last but not least .. the generic one libsGL.add("GL"); - + libsList.add(libsGL); return libsList; - } - + } + public final List getGlueLibNames() { return glueLibNames; - } + } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLContext.java b/src/jogl/classes/jogamp/opengl/egl/EGLContext.java index 179cb7504..3de910369 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLContext.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLContext.java @@ -115,7 +115,7 @@ public class EGLContext extends GLContextImpl { if (EGL.eglGetCurrentContext() != contextHandle) { final long dpy = drawable.getNativeSurface().getDisplayHandle(); if (!EGL.eglMakeCurrent(dpy, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) { - throw new GLException("Error making context " + toHexString(contextHandle) + + throw new GLException("Error making context " + toHexString(contextHandle) + " current on Thread " + getThreadName() + " with display " + toHexString(dpy) + ", drawableWrite " + toHexString(drawable.getHandle()) + @@ -128,7 +128,7 @@ public class EGLContext extends GLContextImpl { @Override protected void releaseImpl() throws GLException { if (!EGL.eglMakeCurrent(drawable.getNativeSurface().getDisplayHandle(), EGL.EGL_NO_SURFACE, EGL.EGL_NO_SURFACE, EGL.EGL_NO_CONTEXT)) { - throw new GLException("Error freeing OpenGL context " + toHexString(contextHandle) + + throw new GLException("Error freeing OpenGL context " + toHexString(contextHandle) + ": error code " + toHexString(EGL.eglGetError())); } } @@ -138,7 +138,7 @@ public class EGLContext extends GLContextImpl { if (!EGL.eglDestroyContext(drawable.getNativeSurface().getDisplayHandle(), contextHandle)) { final int eglError = EGL.eglGetError(); if(EGL.EGL_SUCCESS != eglError) { /* oops, Mesa EGL impl. may return false, but has no EGL error */ - throw new GLException("Error destroying OpenGL context " + toHexString(contextHandle) + + throw new GLException("Error destroying OpenGL context " + toHexString(contextHandle) + ": error code " + toHexString(eglError)); } } @@ -285,11 +285,11 @@ public class EGLContext extends GLContextImpl { // // Accessible .. // - + /* pp */ void mapCurrentAvailableGLVersion(AbstractGraphicsDevice device) { mapStaticGLVersion(device, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); } - /* pp */ int getContextOptions() { return ctxOptions; } + /* pp */ int getContextOptions() { return ctxOptions; } /* pp */ static void mapStaticGLESVersion(AbstractGraphicsDevice device, GLCapabilitiesImmutable caps) { final GLProfile glp = caps.getGLProfile(); final int[] reqMajorCTP = new int[2]; @@ -305,7 +305,7 @@ public class EGLContext extends GLContextImpl { reqMajorCTP[1] |= GLContext.CTX_IMPL_ACCEL_SOFT; } mapStaticGLVersion(device, reqMajorCTP[0], 0, reqMajorCTP[1]); - } + } /* pp */ static void mapStaticGLESVersion(AbstractGraphicsDevice device, final int major) { int ctp = GLContext.CTX_PROFILE_ES; if( major >= 3 ) { @@ -324,20 +324,20 @@ public class EGLContext extends GLContextImpl { if(! ( device instanceof EGLGraphicsDevice ) ) { final EGLGraphicsDevice eglDevice = new EGLGraphicsDevice(device.getHandle(), EGL.EGL_NO_DISPLAY, device.getConnection(), device.getUnitID(), null); GLContext.mapAvailableGLVersion(eglDevice, reqMajor, reqProfile, major, minor, ctp); - } + } } } protected static String getGLVersion(int major, int minor, int ctp, String gl_version) { return GLContext.getGLVersion(major, minor, ctp, gl_version); } - + protected static boolean getAvailableGLVersionsSet(AbstractGraphicsDevice device) { return GLContext.getAvailableGLVersionsSet(device); } protected static void setAvailableGLVersionsSet(AbstractGraphicsDevice device) { GLContext.setAvailableGLVersionsSet(device); } - + protected static String toHexString(int hex) { return GLContext.toHexString(hex); } @@ -358,7 +358,7 @@ public class EGLContext extends GLContextImpl { public final ByteBuffer glAllocateMemoryNV(int size, float readFrequency, float writeFrequency, float priority) { throw new GLException("Should not call this"); } - + @Override public final void glFreeMemoryNV(ByteBuffer pointer) { throw new GLException("Should not call this"); diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java index f2efb0479..89f34432d 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -41,8 +41,8 @@ import jogamp.opengl.Debug; import com.jogamp.common.util.LongObjectHashMap; import com.jogamp.nativewindow.egl.EGLGraphicsDevice; -/** - * This implementation provides recursive calls to +/** + * This implementation provides recursive calls to * {@link EGL#eglInitialize(long, IntBuffer, IntBuffer)} and {@link EGL#eglTerminate(long)}, * where eglInitialize(..) is issued only for the 1st call per eglDisplay * and eglTerminate(..) is issued only for the last call. @@ -53,30 +53,30 @@ import com.jogamp.nativewindow.egl.EGLGraphicsDevice; */ public class EGLDisplayUtil { protected static final boolean DEBUG = Debug.debug("EGLDisplayUtil"); - + private static class DpyCounter { final long eglDisplay; final Throwable createdStack; int refCount; - + private DpyCounter(long eglDisplay) { this.eglDisplay = eglDisplay; this.refCount = 0; this.createdStack = DEBUG ? new Throwable() : null; } - + public String toString() { return "EGLDisplay[0x"+Long.toHexString(eglDisplay)+": refCnt "+refCount+"]"; } } static final LongObjectHashMap eglDisplayCounter; - + static { eglDisplayCounter = new LongObjectHashMap(); eglDisplayCounter.setKeyNotFoundValue(null); } - /** + /** * @return number of unclosed EGL Displays.
                */ public static int shutdown(boolean verbose) { @@ -91,7 +91,7 @@ public class EGLDisplayUtil { } return eglDisplayCounter.size(); } - + public static void dumpOpenDisplayConnections() { System.err.println("EGLDisplayUtil: Open EGL Display Connections: "+eglDisplayCounter.size()); int i=0; @@ -104,7 +104,7 @@ public class EGLDisplayUtil { } } } - + public static long eglGetDisplay(long nativeDisplay_id) { final long eglDisplay = EGL.eglGetDisplay(nativeDisplay_id); if(DEBUG) { @@ -114,16 +114,16 @@ public class EGLDisplayUtil { } return eglDisplay; } - + /** * @param eglDisplay * @param major * @param minor * @return true if the eglDisplay is valid and it's reference counter becomes one and {@link EGL#eglInitialize(long, IntBuffer, IntBuffer)} was successful, otherwise false - * + * * @see EGL#eglInitialize(long, IntBuffer, IntBuffer) */ - public static synchronized boolean eglInitialize(long eglDisplay, IntBuffer major, IntBuffer minor) { + public static synchronized boolean eglInitialize(long eglDisplay, IntBuffer major, IntBuffer minor) { if( EGL.EGL_NO_DISPLAY == eglDisplay) { return false; } @@ -157,16 +157,16 @@ public class EGLDisplayUtil { } return res; } - + /** * @param nativeDisplayID * @param eglDisplay array of size 1 holding return value if successful, otherwise {@link EGL#EGL_NO_DISPLAY}. - * @param eglErr array of size 1 holding the EGL error value as retrieved by {@link EGL#eglGetError()} if not successful. + * @param eglErr array of size 1 holding the EGL error value as retrieved by {@link EGL#eglGetError()} if not successful. * @param major * @param minor - * @return {@link EGL#EGL_SUCCESS} if successful, otherwise {@link EGL#EGL_BAD_DISPLAY} if {@link #eglGetDisplay(long)} failed + * @return {@link EGL#EGL_SUCCESS} if successful, otherwise {@link EGL#EGL_BAD_DISPLAY} if {@link #eglGetDisplay(long)} failed * or {@link EGL#EGL_NOT_INITIALIZED} if {@link #eglInitialize(long, IntBuffer, IntBuffer)} failed. - * + * * @see #eglGetDisplay(long) * @see #eglInitialize(long, IntBuffer, IntBuffer) */ @@ -184,7 +184,7 @@ public class EGLDisplayUtil { eglDisplay[0] = _eglDisplay; return EGL.EGL_SUCCESS; } - + /** * @param nativeDisplayID in/out array of size 1, passing the requested nativeVisualID, may return a different revised nativeVisualID handle * @return the initialized EGL display ID @@ -209,7 +209,7 @@ public class EGLDisplayUtil { } throw new GLException("Failed to created/initialize EGL display incl. fallback default: native "+EGLContext.toHexString(nativeDisplayID[0])+", error "+EGLContext.toHexString(eglRes)+"/"+EGLContext.toHexString(eglError[0])); } - + /** * @param eglDisplay the EGL display handle * @return true if the eglDisplay is valid and it's reference counter becomes zero and {@link EGL#eglTerminate(long)} was successful, otherwise false @@ -218,7 +218,7 @@ public class EGLDisplayUtil { if( EGL.EGL_NO_DISPLAY == eglDisplay) { return false; } - final boolean res; + final boolean res; final int refCnt; final DpyCounter d; { @@ -237,7 +237,7 @@ public class EGLDisplayUtil { } else { if(0 < refCnt) { // no negative refCount d.refCount = refCnt; - } + } res = true; } if(DEBUG) { @@ -246,7 +246,7 @@ public class EGLDisplayUtil { } return res; } - + public static final EGLGraphicsDevice.EGLDisplayLifecycleCallback eglLifecycleCallback = new EGLGraphicsDevice.EGLDisplayLifecycleCallback() { public long eglGetAndInitDisplay(long[] nativeDisplayID) { return eglGetDisplayAndInitialize(nativeDisplayID); @@ -255,25 +255,25 @@ public class EGLDisplayUtil { EGLDisplayUtil.eglTerminate(eglDisplayHandle); } }; - + /** * @param nativeDisplayID * @param connection * @param unitID - * @return an initialized EGLGraphicsDevice + * @return an initialized EGLGraphicsDevice * @throws GLException if {@link EGL#eglGetDisplay(long)} or {@link EGL#eglInitialize(long, int[], int, int[], int)} fails - * @see EGLGraphicsDevice#EGLGraphicsDevice(long, long, String, int, com.jogamp.nativewindow.egl.EGLGraphicsDevice.EGLDisplayLifecycleCallback) + * @see EGLGraphicsDevice#EGLGraphicsDevice(long, long, String, int, com.jogamp.nativewindow.egl.EGLGraphicsDevice.EGLDisplayLifecycleCallback) */ public static EGLGraphicsDevice eglCreateEGLGraphicsDevice(long nativeDisplayID, String connection, int unitID) { final EGLGraphicsDevice eglDisplay = new EGLGraphicsDevice(nativeDisplayID, EGL.EGL_NO_DISPLAY, connection, unitID, eglLifecycleCallback); eglDisplay.open(); return eglDisplay; } - + /** * @param surface - * @return an initialized EGLGraphicsDevice - * @throws GLException if {@link EGL#eglGetDisplay(long)} or {@link EGL#eglInitialize(long, int[], int, int[], int)} fails incl fallback + * @return an initialized EGLGraphicsDevice + * @throws GLException if {@link EGL#eglGetDisplay(long)} or {@link EGL#eglInitialize(long, int[], int, int[], int)} fails incl fallback */ public static EGLGraphicsDevice eglCreateEGLGraphicsDevice(NativeSurface surface) { final long nativeDisplayID; diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java index 2edf26145..bf269c548 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java @@ -59,15 +59,15 @@ public abstract class EGLDrawable extends GLDrawableImpl { @Override public abstract GLContext createContext(GLContext shareWith); - protected abstract long createSurface(EGLGraphicsConfiguration config, int width, int height, long nativeSurfaceHandle); + protected abstract long createSurface(EGLGraphicsConfiguration config, int width, int height, long nativeSurfaceHandle); private final long createEGLSurface() { final EGLWrappedSurface eglws = (EGLWrappedSurface) surface; - final EGLGraphicsConfiguration eglConfig = (EGLGraphicsConfiguration) eglws.getGraphicsConfiguration(); + final EGLGraphicsConfiguration eglConfig = (EGLGraphicsConfiguration) eglws.getGraphicsConfiguration(); final NativeSurface upstreamSurface = eglws.getUpstreamSurface(); - + long eglSurface = createSurface(eglConfig, eglws.getWidth(), eglws.getHeight(), upstreamSurface.getSurfaceHandle()); - + int eglError0; if (EGL.EGL_NO_SURFACE == eglSurface) { eglError0 = EGL.eglGetError(); @@ -104,7 +104,7 @@ public abstract class EGLDrawable extends GLDrawableImpl { final EGLWrappedSurface eglws = (EGLWrappedSurface) surface; if(DEBUG) { System.err.println(getThreadName() + ": createHandle of "+eglws); - } + } if( eglws.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { if( EGL.EGL_NO_SURFACE != eglws.getSurfaceHandle() ) { throw new InternalError("Set surface but claimed to be invalid: "+eglws); @@ -114,12 +114,12 @@ public abstract class EGLDrawable extends GLDrawableImpl { throw new InternalError("Nil surface but claimed to be valid: "+eglws); } } - - protected void destroyHandle() { + + protected void destroyHandle() { final EGLWrappedSurface eglws = (EGLWrappedSurface) surface; if(DEBUG) { System.err.println(getThreadName() + ": destroyHandle of "+eglws); - } + } if( EGL.EGL_NO_SURFACE == eglws.getSurfaceHandle() ) { throw new InternalError("Nil surface but claimed to be valid: "+eglws); } @@ -134,7 +134,7 @@ public abstract class EGLDrawable extends GLDrawableImpl { if( 0 == surfaceHandle ) { return false; } - final IntBuffer val = Buffers.newDirectIntBuffer(1); + final IntBuffer val = Buffers.newDirectIntBuffer(1); final boolean eglSurfaceValid = EGL.eglQuerySurface(eglDisplayHandle, surfaceHandle, EGL.EGL_CONFIG_ID, val); if( !eglSurfaceValid ) { final int eglErr = EGL.eglGetError(); @@ -144,7 +144,7 @@ public abstract class EGLDrawable extends GLDrawableImpl { } return eglSurfaceValid; } - + @Override protected final void setRealizedImpl() { if(DEBUG) { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index 5d99e3eba..a0d896e3a 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -83,14 +83,14 @@ import com.jogamp.opengl.GLRendererQuirks; public class EGLDrawableFactory extends GLDrawableFactoryImpl { protected static final boolean DEBUG = GLDrawableFactoryImpl.DEBUG; // allow package access - + /* package */ static final boolean QUERY_EGL_ES_NATIVE_TK; - + static { Debug.initSingleton(); QUERY_EGL_ES_NATIVE_TK = Debug.isPropertyDefined("jogl.debug.EGLDrawableFactory.QueryNativeTK", true); } - + private static GLDynamicLookupHelper eglES1DynamicLookupHelper = null; private static GLDynamicLookupHelper eglES2DynamicLookupHelper = null; @@ -109,7 +109,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { dl.isFunctionAvailable("glEnableClientState") && dl.isFunctionAvailable("glColorPointer"); } - + public EGLDrawableFactory() { super(); @@ -189,10 +189,10 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } else { if( isANGLE && ( DEBUG || GLProfile.DEBUG ) ) { System.err.println("Info: EGLDrawableFactory.init - EGL/ES2 ANGLE enabled"); - } + } sharedMap = new HashMap(); sharedMapCreateAttempt = new HashSet(); - + // FIXME: Following triggers eglInitialize(..) which crashed on Windows w/ Chrome/Angle, FF/Angle! defaultDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); } @@ -204,8 +204,8 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { protected final boolean isComplete() { return null != sharedMap; // null != eglES2DynamicLookupHelper || null != eglES1DynamicLookupHelper; } - - + + @Override protected final void destroy() { if(null != sharedMap) { @@ -247,7 +247,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { EGLGraphicsConfigurationFactory.unregisterFactory(); EGLDisplayUtil.shutdown(DEBUG); } - + private void dumpMap() { synchronized(sharedMap) { System.err.println("EGLDrawableFactory.map "+sharedMap.size()); @@ -265,7 +265,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } private HashMap sharedMap = null; - private HashSet sharedMapCreateAttempt = null; + private HashSet sharedMapCreateAttempt = null; private EGLGraphicsDevice defaultDevice = null; private SharedResource defaultSharedResource = null; private boolean isANGLE = false; @@ -286,9 +286,9 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { private final boolean hasPBufferES1; private final boolean hasPBufferES3ES2; - SharedResource(EGLGraphicsDevice dev, - boolean wasContextES1Created, boolean hasPBufferES1, GLRendererQuirks rendererQuirksES1, int ctpES1, - boolean wasContextES2Created, boolean wasContextES3Created, + SharedResource(EGLGraphicsDevice dev, + boolean wasContextES1Created, boolean hasPBufferES1, GLRendererQuirks rendererQuirksES1, int ctpES1, + boolean wasContextES2Created, boolean wasContextES3Created, boolean hasPBufferES3ES2, GLRendererQuirks rendererQuirksES3ES2, int ctpES3ES2) { this.device = dev; // this.contextES1 = ctxES1; @@ -296,7 +296,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { this.hasPBufferES1= hasPBufferES1; this.rendererQuirksES1 = rendererQuirksES1; this.ctpES1 = ctpES1; - + // this.contextES2 = ctxES2; // this.contextES3 = ctxES3; this.wasES2ContextCreated = wasContextES2Created; @@ -314,7 +314,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { // final EGLContext getContextES1() { return contextES1; } // final EGLContext getContextES2() { return contextES2; } // final EGLContext getContextES3() { return contextES3; } - + @Override public AbstractGraphicsScreen getScreen() { return null; @@ -329,7 +329,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } @Override public GLRendererQuirks getRendererQuirks() { - return null != rendererQuirksES3ES2 ? rendererQuirksES3ES2 : rendererQuirksES1 ; + return null != rendererQuirksES3ES2 ? rendererQuirksES3ES2 : rendererQuirksES1 ; } } @@ -359,18 +359,18 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } return new ArrayList(0); } - - private boolean mapAvailableEGLESConfig(AbstractGraphicsDevice adevice, int esProfile, + + private boolean mapAvailableEGLESConfig(AbstractGraphicsDevice adevice, int esProfile, boolean[] hasPBuffer, GLRendererQuirks[] rendererQuirks, int[] ctp) { final String profileString; switch( esProfile ) { case 3: - profileString = GLProfile.GLES3; break; + profileString = GLProfile.GLES3; break; case 2: - profileString = GLProfile.GLES2; break; - case 1: + profileString = GLProfile.GLES2; break; + case 1: profileString = GLProfile.GLES1; break; - default: + default: throw new GLException("Invalid ES profile number "+esProfile); } if ( !GLProfile.isAvailable(adevice, profileString) ) { @@ -394,23 +394,23 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { ProxySurface upstreamSurface = null; // X11, GLX, .. boolean success = false; boolean deviceFromUpstreamSurface = false; - try { + try { final GLCapabilities reqCapsAny = new GLCapabilities(glp); reqCapsAny.setRedBits(5); reqCapsAny.setGreenBits(5); reqCapsAny.setBlueBits(5); reqCapsAny.setAlphaBits(0); reqCapsAny.setDoubleBuffered(false); - + if( mapsADeviceToDefaultDevice ) { // In this branch, any non EGL device is mapped to EGL default shared resources (default behavior). - // Only one default shared resource instance is ever be created. + // Only one default shared resource instance is ever be created. final GLCapabilitiesImmutable reqCapsPBuffer = GLGraphicsConfigurationUtil.fixGLPBufferGLCapabilities(reqCapsAny); final List availablePBufferCapsL = getAvailableEGLConfigs(defaultDevice, reqCapsPBuffer); hasPBuffer[0] = availablePBufferCapsL.size() > 0; - + // 1st case: adevice is not the EGL default device, map default shared resources if( adevice != defaultDevice ) { if(null == defaultSharedResource) { return false; - } + } switch(esProfile) { case 3: if( !defaultSharedResource.wasES3ContextCreated ) { @@ -419,14 +419,14 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { rendererQuirks[0] = defaultSharedResource.rendererQuirksES3ES2; ctp[0] = defaultSharedResource.ctpES3ES2; break; - case 2: + case 2: if( !defaultSharedResource.wasES2ContextCreated ) { return false; } rendererQuirks[0] = defaultSharedResource.rendererQuirksES3ES2; ctp[0] = defaultSharedResource.ctpES3ES2; break; - case 1: + case 1: if( !defaultSharedResource.wasES1ContextCreated ) { return false; } @@ -437,11 +437,11 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { EGLContext.mapStaticGLVersion(adevice, esProfile, 0, ctp[0]); return true; } - + // attempt to created the default shared resources .. - + eglDevice = defaultDevice; // reuse - + if( hasPBuffer[0] ) { // 2nd case create defaultDevice shared resource using pbuffer surface surface = createDummySurfaceImpl(eglDevice, false, reqCapsPBuffer, reqCapsPBuffer, null, 64, 64); // egl pbuffer offscreen @@ -459,15 +459,15 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { if(DEBUG) { System.err.println("EGLDrawableFactory.mapAvailableEGLESConfig() no pbuffer config available, detected !pbuffer config: "+success); EGLGraphicsConfigurationFactory.printCaps("!PBufferCaps", capsAnyL, System.err); - } - } + } + } } else { - // 4th case always creates a true mapping of given device to EGL + // 4th case always creates a true mapping of given device to EGL surface = desktopFactory.createDummySurface(adevice, reqCapsAny, null, 64, 64); // X11, WGL, .. dummy window upstreamSurface = ( surface instanceof ProxySurface ) ? (ProxySurface)surface : null ; if(null != upstreamSurface) { upstreamSurface.createNotify(); - } + } eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface); deviceFromUpstreamSurface = true; hasPBuffer[0] = true; @@ -482,7 +482,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { context.makeCurrent(); // could cause exception if(context.isCurrent()) { final String glVersion = context.getGL().glGetString(GL.GL_VERSION); - if(null != glVersion) { + if(null != glVersion) { context.mapCurrentAvailableGLVersion(eglDevice); if(eglDevice != adevice) { context.mapCurrentAvailableGLVersion(adevice); @@ -493,7 +493,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } else { // Oops .. something is wrong if(DEBUG) { - System.err.println("EGLDrawableFactory.mapAvailableEGLESConfig: "+eglDevice+", "+context.getGLVersion()+" - VERSION is null, dropping availability!"); + System.err.println("EGLDrawableFactory.mapAvailableEGLESConfig: "+eglDevice+", "+context.getGLVersion()+" - VERSION is null, dropping availability!"); } } } @@ -510,7 +510,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } } catch (Throwable t) { if(DEBUG) { - System.err.println("Catched Exception on thread "+getThreadName()); + System.err.println("Catched Exception on thread "+getThreadName()); t.printStackTrace(); } success = false; @@ -518,7 +518,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { if(eglDevice == defaultDevice) { if(null != upstreamSurface) { upstreamSurface.destroyNotify(); - } + } } else if( deviceFromUpstreamSurface ) { if(null != eglDevice) { eglDevice.close(); @@ -529,7 +529,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } else { if(null != upstreamSurface) { upstreamSurface.destroyNotify(); - } + } if(null != eglDevice) { eglDevice.close(); } @@ -553,9 +553,9 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } return false; } - } + } } - + @Override protected final SharedResource getOrCreateSharedResourceImpl(AbstractGraphicsDevice adevice) { if(null == sharedMap) { // null == eglES1DynamicLookupHelper && null == eglES2DynamicLookupHelper @@ -571,27 +571,27 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { dumpMap(); throw new InternalError("defaultSharedResource already exist: "+defaultSharedResource); } - defaultSharedResource = createEGLSharedResourceImpl(defaultDevice); + defaultSharedResource = createEGLSharedResourceImpl(defaultDevice); } - + final String key = adevice.getUniqueID(); if( defaultDevice.getUniqueID().equals(key) ) { return defaultSharedResource; } else { - if( null == defaultSharedResource) { // defaultDevice must be initialized before host-device + if( null == defaultSharedResource) { // defaultDevice must be initialized before host-device dumpMap(); - throw new InternalError("defaultSharedResource does not exist"); + throw new InternalError("defaultSharedResource does not exist"); } final SharedResource[] existing = new SharedResource[] { null }; if ( !needsToCreateSharedResource(key, existing) ) { return existing[0]; - } + } return createEGLSharedResourceImpl(adevice); } } - + private SharedResource createEGLSharedResourceImpl(AbstractGraphicsDevice adevice) { - final boolean madeCurrentES1; + final boolean madeCurrentES1; final boolean madeCurrentES2; final boolean madeCurrentES3; boolean[] hasPBufferES1 = new boolean[] { false }; @@ -602,12 +602,12 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { GLRendererQuirks[] rendererQuirksES3ES2 = new GLRendererQuirks[] { null }; int[] ctpES1 = new int[] { -1 }; int[] ctpES3ES2 = new int[] { -1 }; - - + + if (DEBUG) { System.err.println("EGLDrawableFactory.createShared(): device "+adevice); } - + if( null != eglES1DynamicLookupHelper ) { madeCurrentES1 = mapAvailableEGLESConfig(adevice, 1, hasPBufferES1, rendererQuirksES1, ctpES1); } else { @@ -625,10 +625,10 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { madeCurrentES2 = false; madeCurrentES3 = false; } - + if( !EGLContext.getAvailableGLVersionsSet(adevice) ) { // Even though we override the non EGL native mapping intentionally, - // avoid exception due to double 'set' - carefull exception of the rule. + // avoid exception due to double 'set' - carefull exception of the rule. EGLContext.setAvailableGLVersionsSet(adevice); } if( hasX11 ) { @@ -637,7 +637,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } final SharedResource sr = new SharedResource(defaultDevice, madeCurrentES1, hasPBufferES1[0], rendererQuirksES1[0], ctpES1[0], madeCurrentES2, madeCurrentES3, hasPBufferES3ES2[0], rendererQuirksES3ES2[0], ctpES3ES2[0]); - + synchronized(sharedMap) { sharedMap.put(adevice.getUniqueID(), sr); } @@ -650,7 +650,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } return sr; } - + private void handleDontCloseX11DisplayQuirk(GLRendererQuirks quirks) { if( null != quirks && quirks.exist( GLRendererQuirks.DontCloseX11Display ) ) { jogamp.nativewindow.x11.X11Util.markAllDisplaysUnclosable(); @@ -692,7 +692,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } return new EGLOnscreenDrawable(this, EGLWrappedSurface.get(target)); } - + @Override protected GLDrawableImpl createOffscreenDrawableImpl(NativeSurface target) { if (target == null) { @@ -715,8 +715,8 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } @Override - protected ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, - GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, + protected ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final boolean ownDevice; final EGLGraphicsDevice device; @@ -732,21 +732,21 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { final DefaultGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); final EGLGraphicsConfiguration config = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED, false); if(null == config) { - throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); - } + throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); + } return new WrappedSurface(config, 0, upstreamHook, ownDevice); } - + @Override - public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable chosenCaps, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { - chosenCaps = GLGraphicsConfigurationUtil.fixOffscreenBitOnly(chosenCaps); // complete validation in EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(..) above + chosenCaps = GLGraphicsConfigurationUtil.fixOffscreenBitOnly(chosenCaps); // complete validation in EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(..) above return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, new EGLDummyUpstreamSurfaceHook(width, height)); } - + /** - * @param ms {@link MutableSurface} which dimensions and config are being used to create the pbuffer surface. - * It will also hold the resulting pbuffer surface handle. + * @param ms {@link MutableSurface} which dimensions and config are being used to create the pbuffer surface. + * It will also hold the resulting pbuffer surface handle. * @param useTexture * @return the passed {@link MutableSurface} which now has the EGL pbuffer surface set as it's handle */ diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java b/src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java index 162e7166a..eb6578ec5 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDummyUpstreamSurfaceHook.java @@ -9,17 +9,17 @@ import com.jogamp.nativewindow.egl.EGLGraphicsDevice; public class EGLDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize { /** - * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, - * not the actual dummy surface width. + * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, + * not the actual dummy surface width. * The latter is platform specific and small - * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, + * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, * not the actual dummy surface height, * The latter is platform specific and small */ public EGLDummyUpstreamSurfaceHook(int width, int height) { super(width, height); } - + @Override public final void create(ProxySurface s) { final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) s.getGraphicsConfiguration().getScreen().getDevice(); @@ -31,14 +31,14 @@ public class EGLDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize } if( EGL.EGL_NO_SURFACE == s.getSurfaceHandle() ) { s.setSurfaceHandle( EGLDrawableFactory.createPBufferSurfaceImpl((EGLGraphicsConfiguration)s.getGraphicsConfiguration(), 64, 64, false) ); - s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); } s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); } finally { eglDevice.unlock(); } } - + @Override public final void destroy(ProxySurface s) { if( s.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java index 778f0cb38..ac880ebc0 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl.egl; import com.jogamp.common.os.AndroidVersion; @@ -52,7 +52,7 @@ public abstract class EGLDynamicLibraryBundleInfo extends GLDynamicLibraryBundle super(); } - /** + /** * Returns true on Android, * and false otherwise. */ @@ -65,7 +65,7 @@ public abstract class EGLDynamicLibraryBundleInfo extends GLDynamicLibraryBundle // default behavior for other platforms return false; } - + @Override public final List getToolGetProcAddressFuncNameList() { List res = new ArrayList(); @@ -87,26 +87,26 @@ public abstract class EGLDynamicLibraryBundleInfo extends GLDynamicLibraryBundle return true; } } - + protected final List getEGLLibNamesList() { List eglLibNames = new ArrayList(); - - // this is the default EGL lib name, according to the spec + + // this is the default EGL lib name, according to the spec eglLibNames.add("libEGL.so.1"); - + // try these as well, if spec fails eglLibNames.add("libEGL.so"); eglLibNames.add("EGL"); - - // for windows distributions using the 'unlike' lib prefix, + + // for windows distributions using the 'unlike' lib prefix, // where our tool does not add it. eglLibNames.add("libEGL"); - + return eglLibNames; } @Override public final List getGlueLibNames() { return glueLibNames; - } + } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java index dd3d6faea..9ffcea864 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl.egl; import java.util.*; @@ -39,29 +39,29 @@ public final class EGLES1DynamicLibraryBundleInfo extends EGLDynamicLibraryBundl final List> libsList = new ArrayList>(); { final List libsGL = new ArrayList(); - - // this is the default lib name, according to the spec + + // this is the default lib name, according to the spec libsGL.add("libGLESv1_CM.so.2"); - + // try these as well, if spec fails libsGL.add("libGLESv1_CM.so"); - libsGL.add("GLESv1_CM"); + libsGL.add("GLESv1_CM"); // alternative names libsGL.add("GLES_CM"); libsGL.add("GLES_CL"); - - // for windows distributions using the 'unlike' lib prefix, + + // for windows distributions using the 'unlike' lib prefix, // where our tool does not add it. libsGL.add("libGLESv1_CM"); libsGL.add("libGLES_CM"); libsGL.add("libGLES_CL"); - + libsList.add(libsGL); } libsList.add(getEGLLibNamesList()); - + return libsList; - } + } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java index 0d20fd4e8..de1f0a42e 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,17 +20,17 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl.egl; import java.util.*; -/** +/** *

                * Covering ES3 and ES2. *

                @@ -44,12 +44,12 @@ public final class EGLES2DynamicLibraryBundleInfo extends EGLDynamicLibraryBundl final List> libsList = new ArrayList>(); { final List libsGL = new ArrayList(); - - // ES3: This is the default lib name, according to the spec + + // ES3: This is the default lib name, according to the spec libsGL.add("libGLESv3.so.3"); - + // ES3: Try these as well, if spec fails - libsGL.add("libGLESv3.so"); + libsGL.add("libGLESv3.so"); libsGL.add("GLESv3"); // ES3: Alternative names @@ -59,12 +59,12 @@ public final class EGLES2DynamicLibraryBundleInfo extends EGLDynamicLibraryBundl // where our tool does not add it. libsGL.add("libGLESv3"); libsGL.add("libGLES30"); - - // ES2: This is the default lib name, according to the spec + + // ES2: This is the default lib name, according to the spec libsGL.add("libGLESv2.so.2"); - + // ES2: Try these as well, if spec fails - libsGL.add("libGLESv2.so"); + libsGL.add("libGLESv2.so"); libsGL.add("GLESv2"); // ES2: Alternative names @@ -75,14 +75,14 @@ public final class EGLES2DynamicLibraryBundleInfo extends EGLDynamicLibraryBundl // where our tool does not add it. libsGL.add("libGLESv2"); libsGL.add("libGLESv2_CM"); - libsGL.add("libGLES20"); - + libsGL.add("libGLES20"); + libsList.add(libsGL); } libsList.add(getEGLLibNamesList()); - + return libsList; - } - + } + } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java index b1ffe608e..f3592c150 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -57,7 +57,7 @@ import com.jogamp.nativewindow.MutableGraphicsConfiguration; import com.jogamp.nativewindow.egl.EGLGraphicsDevice; public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable { - + public final long getNativeConfig() { return ((EGLGLCapabilities)capabilitiesChosen).getEGLConfig(); } @@ -66,7 +66,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple return ((EGLGLCapabilities)capabilitiesChosen).getEGLConfigID(); } - EGLGraphicsConfiguration(AbstractGraphicsScreen absScreen, + EGLGraphicsConfiguration(AbstractGraphicsScreen absScreen, EGLGLCapabilities capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser) { super(absScreen, capsChosen, capsRequested); this.chooser = chooser; @@ -77,7 +77,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple * @param absScreen * @param eglConfigID {@link EGL#EGL_CONFIG_ID} for which the config is being created for. * @return - * @throws GLException if invalid EGL display. + * @throws GLException if invalid EGL display. */ public static EGLGraphicsConfiguration create(GLCapabilitiesImmutable capsRequested, AbstractGraphicsScreen absScreen, int eglConfigID) { final AbstractGraphicsDevice absDevice = absScreen.getDevice(); @@ -101,9 +101,9 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple public Object clone() { return super.clone(); } - + void updateGraphicsConfiguration() { - CapabilitiesImmutable capsChosen = getChosenCapabilities(); + CapabilitiesImmutable capsChosen = getChosenCapabilities(); EGLGraphicsConfiguration newConfig = (EGLGraphicsConfiguration) GraphicsConfigurationFactory.getFactory(getScreen().getDevice(), capsChosen).chooseGraphicsConfiguration( capsChosen, getRequestedCapabilities(), chooser, getScreen(), VisualIDHolder.VID_UNDEFINED); @@ -140,7 +140,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple return false; } final IntBuffer val = Buffers.newDirectIntBuffer(1); - + // get the configID if(!EGL.eglGetConfigAttrib(display, config, EGL.EGL_CONFIG_ID, val)) { final int eglErr = EGL.eglGetError(); @@ -169,7 +169,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple } if ( 0 != ( _stype & EGL.EGL_PBUFFER_BIT ) ) { val |= GLGraphicsConfigurationUtil.PBUFFER_BIT | - GLGraphicsConfigurationUtil.FBO_BIT; + GLGraphicsConfigurationUtil.FBO_BIT; } return val; } @@ -189,7 +189,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple final int cfgID; final int rType; final int visualID; - + // get the configID if(!EGL.eglGetConfigAttrib(display, config, EGL.EGL_CONFIG_ID, val)) { if(DEBUG) { @@ -199,7 +199,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple return null; } cfgID = val.get(0); - + if(!EGL.eglGetConfigAttrib(display, config, EGL.EGL_RENDERABLE_TYPE, val)) { if(DEBUG) { System.err.println("EGL couldn't retrieve EGL_RENDERABLE_TYPE for config "+toHexString(config)+", error "+toHexString(EGL.eglGetError())); @@ -213,8 +213,8 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple } else { visualID = VisualIDHolder.VID_UNDEFINED; } - - EGLGLCapabilities caps = null; + + EGLGLCapabilities caps = null; try { if(null == glp) { glp = EGLGLCapabilities.getCompatible(device, rType); @@ -232,8 +232,8 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple System.err.println("config "+toHexString(config)+": "+gle); } return null; - } - + } + if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_CONFIG_CAVEAT, val)) { if( EGL.EGL_SLOW_CONFIG == val.get(0) ) { caps.setHardwareAccelerated(false); @@ -244,11 +244,11 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple caps.setNumSamples(val.get(0)); } if(!caps.getSampleBuffers()) { - // try NV_coverage_sample extension + // try NV_coverage_sample extension if(EGL.eglGetConfigAttrib(display, config, EGLExt.EGL_COVERAGE_BUFFERS_NV, val)) { if(val.get(0)>0 && EGL.eglGetConfigAttrib(display, config, EGLExt.EGL_COVERAGE_SAMPLES_NV, val)) { - caps.setSampleExtension(GLGraphicsConfigurationUtil.NV_coverage_sample); + caps.setSampleExtension(GLGraphicsConfigurationUtil.NV_coverage_sample); caps.setSampleBuffers(true); caps.setNumSamples(val.get(0)); } @@ -269,7 +269,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_TRANSPARENT_BLUE_VALUE, val)) { caps.setTransparentBlueValue(val.get(0)==EGL.EGL_DONT_CARE?-1:val.get(0)); } - /** Not defined in EGL + /** Not defined in EGL if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_TRANSPARENT_ALPHA_VALUE, val)) { caps.setTransparentAlphaValue(val.get(0)==EGL.EGL_DONT_CARE?-1:val.get(0)); } */ @@ -294,16 +294,16 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple caps.setDepthBits(val.get(0)); } - // Since the passed GLProfile may be null, + // Since the passed GLProfile may be null, // we use EGL_RENDERABLE_TYPE derived profile as created in the EGLGLCapabilities constructor. - final int availableTypeBits = EGLConfigDrawableTypeBits(device, config); + final int availableTypeBits = EGLConfigDrawableTypeBits(device, config); final int drawableTypeBits = winattrmask & availableTypeBits; if( 0 == drawableTypeBits ) { return null; } - - return (EGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, caps); + + return (EGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, caps); } public static IntBuffer GLCapabilities2AttribList(GLCapabilitiesImmutable caps) { @@ -313,7 +313,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple attrs.put(idx++, EGL.EGL_SURFACE_TYPE); final int surfaceType; if( caps.isOnscreen() ) { - surfaceType = EGL.EGL_WINDOW_BIT; + surfaceType = EGL.EGL_WINDOW_BIT; } else if( caps.isFBO() ) { surfaceType = EGL.EGL_PBUFFER_BIT; // native replacement! } else if( caps.isPBuffer() ) { @@ -338,7 +338,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple attrs.put(idx++, EGL.EGL_ALPHA_SIZE); attrs.put(idx++, caps.getAlphaBits()); } - + if(caps.getStencilBits()>0) { attrs.put(idx++, EGL.EGL_STENCIL_SIZE); attrs.put(idx++, caps.getStencilBits()); @@ -382,7 +382,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple attrs.put(idx++, caps.getTransparentAlphaValue()>=0?caps.getTransparentAlphaValue():EGL.EGL_DONT_CARE; */ } - // 28 + // 28 attrs.put(idx++, EGL.EGL_RENDERABLE_TYPE); if(caps.getGLProfile().usesNativeGLES1()) { attrs.put(idx++, EGL.EGL_OPENGL_ES_BIT); diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java index b44e08500..5764a6178 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -75,10 +75,10 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact static GraphicsConfigurationFactory nativeGraphicsConfigurationFactory = null; static GraphicsConfigurationFactory kdeglGraphicsConfigurationFactory = null; static GraphicsConfigurationFactory fallbackGraphicsConfigurationFactory = null; - + static void registerFactory() { GraphicsConfigurationFactory eglFactory = new EGLGraphicsConfigurationFactory(); - + // become the pre-selector for X11/.. to match the native visual id w/ EGL, if native ES is selected final String nwType = NativeWindowFactory.getNativeWindowType(false); if(NativeWindowFactory.TYPE_X11 == nwType) { @@ -86,32 +86,32 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(null != nativeGraphicsConfigurationFactory) { fallbackGraphicsConfigurationFactory = nativeGraphicsConfigurationFactory; } else { - fallbackGraphicsConfigurationFactory = GraphicsConfigurationFactory.getFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, CapabilitiesImmutable.class); + fallbackGraphicsConfigurationFactory = GraphicsConfigurationFactory.getFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, CapabilitiesImmutable.class); } } /* else if(NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false)) { nativeGraphicsConfigurationFactory = GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.windows.WindowsGraphicsDevice.class, eglFactory); - } else if(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false)) { + } else if(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false)) { } */ - + // become the selector for KD/EGL .. - kdeglGraphicsConfigurationFactory = GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.egl.EGLGraphicsDevice.class, GLCapabilitiesImmutable.class, eglFactory); + kdeglGraphicsConfigurationFactory = GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.egl.EGLGraphicsDevice.class, GLCapabilitiesImmutable.class, eglFactory); } - + static void unregisterFactory() { final String nwType = NativeWindowFactory.getNativeWindowType(false); if(NativeWindowFactory.TYPE_X11 == nwType) { - GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, GLCapabilitiesImmutable.class, nativeGraphicsConfigurationFactory); + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, GLCapabilitiesImmutable.class, nativeGraphicsConfigurationFactory); } /* else if(NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false)) { GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.windows.WindowsGraphicsDevice.class, nativeGraphicsConfigurationFactory); - } else if(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false)) { + } else if(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false)) { } */ nativeGraphicsConfigurationFactory = null; fallbackGraphicsConfigurationFactory = null; - + GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.egl.EGLGraphicsDevice.class, GLCapabilitiesImmutable.class, kdeglGraphicsConfigurationFactory); kdeglGraphicsConfigurationFactory = null; } - + private EGLGraphicsConfigurationFactory() { } @@ -139,21 +139,21 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact AbstractGraphicsDevice absDevice = absScreen.getDevice(); if(null==absDevice) { throw new GLException("Null AbstractGraphicsDevice"); - } - + } + AbstractGraphicsConfiguration cfg = null; - + if( absDevice instanceof EGLGraphicsDevice ) { cfg = chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable) capsChosen, (GLCapabilitiesImmutable) capsRequested, (GLCapabilitiesChooser) chooser, - absScreen, nativeVisualID, false); + absScreen, nativeVisualID, false); } else { - // handle non native cases (X11, ..) + // handle non native cases (X11, ..) if(null == fallbackGraphicsConfigurationFactory) { throw new InternalError("Native fallback GraphicsConfigurationFactory is null, but call issued for device: "+absDevice+" of type "+absDevice.getClass().getSimpleName()); } - + if(glCapsChosen.getGLProfile().usesNativeGLES()) { if(DEBUG) { System.err.println("EGLGraphicsConfigurationFactory.choose..: Handle native device "+absDevice.getClass().getSimpleName()); @@ -175,7 +175,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact System.err.println("EGLGraphicsConfigurationFactory.choose..: Delegate to "+fallbackGraphicsConfigurationFactory.getClass().getSimpleName()); } cfg = fallbackGraphicsConfigurationFactory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, absScreen, nativeVisualID); - } + } } return cfg; } @@ -219,7 +219,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact public static EGLGraphicsConfiguration chooseGraphicsConfigurationStatic(GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsReq, GLCapabilitiesChooser chooser, - AbstractGraphicsScreen absScreen, int nativeVisualID, + AbstractGraphicsScreen absScreen, int nativeVisualID, boolean forceTransparentFlag) { if (capsChosen == null) { capsChosen = new GLCapabilities(null); @@ -232,7 +232,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(null==absDevice) { throw new GLException("Null AbstractGraphicsDevice"); } - + final EGLGraphicsDevice eglDevice; final boolean ownEGLDisplay; if( absDevice instanceof EGLGraphicsDevice ) { @@ -253,7 +253,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact if(DEBUG) { System.err.println("eglChooseConfig failed with given capabilities "+capsChosen); } - + // Last try .. add a fixed embedded profile [ATI, Nokia, Intel, ..] // // rgb888 - d16, s4 @@ -268,7 +268,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact fixedCaps.setOnscreen(false); fixedCaps.setPBuffer(capsChosen.isPBuffer()); fixedCaps.setFBO(capsChosen.isFBO()); - } + } if(DEBUG) { System.err.println("trying fixed caps (1): "+fixedCaps); } @@ -286,7 +286,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact fixedCaps.setOnscreen(false); fixedCaps.setPBuffer(capsChosen.isPBuffer()); fixedCaps.setFBO(capsChosen.isFBO()); - } + } if(DEBUG) { System.err.println("trying fixed caps (2): "+fixedCaps); } @@ -306,7 +306,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact fixedCaps.setOnscreen(false); fixedCaps.setPBuffer(capsChosen.isPBuffer()); fixedCaps.setFBO(capsChosen.isFBO()); - } + } if(DEBUG) { System.err.println("trying fixed caps (3): "+fixedCaps); } @@ -322,8 +322,8 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact return res; } - - static EGLGraphicsConfiguration eglChooseConfig(EGLGraphicsDevice device, + + static EGLGraphicsConfiguration eglChooseConfig(EGLGraphicsDevice device, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, @@ -354,7 +354,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact final IntBuffer attrs = EGLGraphicsConfiguration.GLCapabilities2AttribList(capsChosen); PointerBuffer configs = PointerBuffer.allocateDirect(numConfigs.get(0)); - // 1st choice: get GLCapabilities based on users GLCapabilities + // 1st choice: get GLCapabilities based on users GLCapabilities // setting recommendedIndex as preferred choice // skipped if nativeVisualID is given if( VisualIDHolder.VID_UNDEFINED != nativeVisualID || !EGL.eglChooseConfig(eglDisplay, attrs, configs, configs.capacity(), numConfigs) ) { @@ -387,7 +387,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact throw new GLException("EGLGraphicsConfiguration.eglChooseConfig: #2 Get all configs (eglGetConfigs) call failed, error "+toHexString(EGL.eglGetError())); } if (numConfigs.get(0) > 0) { - availableCaps = eglConfigs2GLCaps(device, glp, configs, numConfigs.get(0), winattrmask, forceTransparentFlag); + availableCaps = eglConfigs2GLCaps(device, glp, configs, numConfigs.get(0), winattrmask, forceTransparentFlag); } } @@ -400,7 +400,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact } return null; } - + if(DEBUG) { System.err.println("EGLGraphicsConfiguration.eglChooseConfig: got configs: "+availableCaps.size()); for(int i=0; i this "+surface.getClass().getSimpleName()+" ): "; - System.err.println(dbgPrefix+this); + System.err.println(dbgPrefix+this); } else { dbgPrefix = null; } - + if(upstreamSurface instanceof ProxySurface) { - // propagate createNotify(..) so upstreamSurface will be created + // propagate createNotify(..) so upstreamSurface will be created ((ProxySurface)upstreamSurface).createNotify(); } - + // lock upstreamSurface, so it can be used in case EGLDisplay is derived from it! if(NativeSurface.LOCK_SURFACE_NOT_READY >= upstreamSurface.lockSurface()) { throw new GLException("Could not lock: "+upstreamSurface); @@ -73,16 +73,16 @@ public class EGLUpstreamSurfaceHook implements UpstreamSurfaceHook.MutableSize { evalUpstreamSurface(dbgPrefix, surface); } finally { upstreamSurface.unlockSurface(); - } + } } - + private final void evalUpstreamSurface(String dbgPrefix, ProxySurface surface) { // // evaluate nature of upstreamSurface, may create EGL instances if required // - + boolean isEGLSurfaceValid = true; // assume yes - + final EGLGraphicsDevice eglDevice; final AbstractGraphicsConfiguration aConfig; { @@ -92,14 +92,14 @@ public class EGLUpstreamSurfaceHook implements UpstreamSurfaceHook.MutableSize { System.err.println(dbgPrefix+"SurfaceDevice: "+surfaceDevice.getClass().getSimpleName()+", hash 0x"+Integer.toHexString(surfaceDevice.hashCode())+", "+surfaceDevice); System.err.println(dbgPrefix+"SurfaceConfig: "+surfaceConfig.getClass().getSimpleName()+", hash 0x"+Integer.toHexString(surfaceConfig.hashCode())+", "+surfaceConfig); } - - final AbstractGraphicsConfiguration upstreamConfig = upstreamSurface.getGraphicsConfiguration(); + + final AbstractGraphicsConfiguration upstreamConfig = upstreamSurface.getGraphicsConfiguration(); final AbstractGraphicsDevice upstreamDevice = upstreamConfig.getScreen().getDevice(); if(DEBUG) { System.err.println(dbgPrefix+"UpstreamDevice: "+upstreamDevice.getClass().getSimpleName()+", hash 0x"+Integer.toHexString(upstreamDevice.hashCode())+", "+upstreamDevice); System.err.println(dbgPrefix+"UpstreamConfig: "+upstreamConfig.getClass().getSimpleName()+", hash 0x"+Integer.toHexString(upstreamConfig.hashCode())+", "+upstreamConfig); } - + if( surfaceDevice instanceof EGLGraphicsDevice ) { eglDevice = (EGLGraphicsDevice) surfaceDevice; aConfig = surfaceConfig; @@ -129,13 +129,13 @@ public class EGLUpstreamSurfaceHook implements UpstreamSurfaceHook.MutableSize { surface.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); } } - + final GLCapabilitiesImmutable capsRequested = (GLCapabilitiesImmutable) aConfig.getRequestedCapabilities(); final EGLGraphicsConfiguration eglConfig; if( aConfig instanceof EGLGraphicsConfiguration ) { // Config is already in EGL type - reuse .. final EGLGLCapabilities capsChosen = (EGLGLCapabilities) aConfig.getChosenCapabilities(); - if( !isEGLSurfaceValid || !EGLGraphicsConfiguration.isEGLConfigValid(eglDevice.getHandle(), capsChosen.getEGLConfig()) ) { + if( !isEGLSurfaceValid || !EGLGraphicsConfiguration.isEGLConfigValid(eglDevice.getHandle(), capsChosen.getEGLConfig()) ) { // 'refresh' the native EGLConfig handle capsChosen.setEGLConfig(EGLGraphicsConfiguration.EGLConfigId2EGLConfig(eglDevice.getHandle(), capsChosen.getEGLConfigID())); if( 0 == capsChosen.getEGLConfig() ) { @@ -166,7 +166,7 @@ public class EGLUpstreamSurfaceHook implements UpstreamSurfaceHook.MutableSize { isEGLSurfaceValid = false; } surface.setGraphicsConfiguration(eglConfig); - + if(isEGLSurfaceValid) { isEGLSurfaceValid = EGLDrawable.isValidEGLSurface(eglDevice.getHandle(), upstreamSurface.getSurfaceHandle()); } @@ -182,15 +182,15 @@ public class EGLUpstreamSurfaceHook implements UpstreamSurfaceHook.MutableSize { if(DEBUG) { System.err.println(dbgPrefix+"Fin: EGL surface n/a - TBD: "+upstreamSurface); } - } + } } @Override public final void destroy(ProxySurface surface) { if(EGLDrawableFactory.DEBUG) { - System.err.println("EGLUpstreamSurfaceHook.destroy("+surface.getClass().getSimpleName()+"): "+this); + System.err.println("EGLUpstreamSurfaceHook.destroy("+surface.getClass().getSimpleName()+"): "+this); } - surface.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + surface.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); if(upstreamSurface instanceof ProxySurface) { ((ProxySurface)upstreamSurface).destroyNotify(); } @@ -205,7 +205,7 @@ public class EGLUpstreamSurfaceHook implements UpstreamSurfaceHook.MutableSize { public final int getHeight(ProxySurface s) { return upstreamSurface.getHeight(); } - + @Override public String toString() { final String us_s = null != upstreamSurface ? ( upstreamSurface.getClass().getName() + ": 0x" + Long.toHexString(upstreamSurface.getSurfaceHandle()) ) : "nil"; diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java b/src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java index f816151c7..e6d43d957 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLWrappedSurface.java @@ -19,16 +19,16 @@ public class EGLWrappedSurface extends WrappedSurface { } return new EGLWrappedSurface(surface); } - + public EGLWrappedSurface(NativeSurface surface) { super(surface.getGraphicsConfiguration(), EGL.EGL_NO_SURFACE, new EGLUpstreamSurfaceHook(surface), false /* tbd in UpstreamSurfaceHook */); if(EGLDrawableFactory.DEBUG) { - System.err.println("EGLWrappedSurface.ctor(): "+this); + System.err.println("EGLWrappedSurface.ctor(): "+this); } } @Override - public final NativeSurface getUpstreamSurface() { - return ((EGLUpstreamSurfaceHook)super.getUpstreamSurfaceHook()).getUpstreamSurface(); - } + public final NativeSurface getUpstreamSurface() { + return ((EGLUpstreamSurfaceHook)super.getUpstreamSurfaceHook()).getUpstreamSurface(); + } } diff --git a/src/jogl/classes/jogamp/opengl/gl2/ProjectDouble.java b/src/jogl/classes/jogamp/opengl/gl2/ProjectDouble.java index 9165dbc4b..a4aa1c7c5 100644 --- a/src/jogl/classes/jogamp/opengl/gl2/ProjectDouble.java +++ b/src/jogl/classes/jogamp/opengl/gl2/ProjectDouble.java @@ -6,9 +6,9 @@ ** 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 @@ -24,13 +24,13 @@ ** except that Section 2.2 and 11 are omitted. Any differences between ** the Alternative License and the SGI License are offered solely by Sun ** and not by SGI. -** +** ** 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 @@ -45,56 +45,56 @@ ** $Header$ */ -/* +/* * 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 + * modification, are permitted provided that the following conditions are * met: - * - * * Redistributions of source code must retain the above copyright + * + * * 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 + * * 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 + * 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 + * 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. */ /* * 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 @@ -107,7 +107,7 @@ * 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. @@ -125,7 +125,7 @@ import com.jogamp.common.nio.Buffers; *

                *

                * Created 11-jan-2004 - * + * * @author Erik Duijs * @author Kenneth Russell */ @@ -155,7 +155,7 @@ public class ProjectDouble { private final double[] forward = new double[3]; private final double[] side = new double[3]; private final double[] up = new double[3]; - + // Buffer-based implementation private DoubleBuffer locbuf; private final DoubleBuffer matrixBuf; @@ -227,7 +227,7 @@ public class ProjectDouble { /** * Method __gluMultMatrixVecd - * + * * @param matrix * @param in * @param out @@ -244,7 +244,7 @@ public class ProjectDouble { /** * Method __gluMultMatrixVecd - * + * * @param matrix * @param in * @param out @@ -265,7 +265,7 @@ public class ProjectDouble { /** * @param src * @param inverse - * + * * @return */ private boolean __gluInvertMatrixd(double[] src, double[] inverse) { @@ -335,7 +335,7 @@ public class ProjectDouble { /** * @param src * @param inverse - * + * * @return */ private boolean __gluInvertMatrixd(DoubleBuffer src, DoubleBuffer inverse) { @@ -525,7 +525,7 @@ public class ProjectDouble { /** * Method gluOrtho2D. - * + * * @param left * @param right * @param bottom @@ -537,7 +537,7 @@ public class ProjectDouble { /** * Method gluPerspective. - * + * * @param fovy * @param aspect * @param zNear @@ -570,7 +570,7 @@ public class ProjectDouble { /** * Method gluLookAt - * + * * @param eyex * @param eyey * @param eyez @@ -631,7 +631,7 @@ public class ProjectDouble { /** * Method gluProject - * + * * @param objx * @param objy * @param objz @@ -639,7 +639,7 @@ public class ProjectDouble { * @param projMatrix * @param viewport * @param win_pos - * + * * @return */ public boolean gluProject(double objx, @@ -685,7 +685,7 @@ public class ProjectDouble { /** * Method gluProject - * + * * @param objx * @param objy * @param objz @@ -693,7 +693,7 @@ public class ProjectDouble { * @param projMatrix * @param viewport * @param win_pos - * + * * @return */ public boolean gluProject(double objx, @@ -738,7 +738,7 @@ public class ProjectDouble { /** * Method gluUnproject - * + * * @param winx * @param winy * @param winz @@ -746,7 +746,7 @@ public class ProjectDouble { * @param projMatrix * @param viewport * @param obj_pos - * + * * @return */ public boolean gluUnProject(double winx, @@ -799,7 +799,7 @@ public class ProjectDouble { /** * Method gluUnproject - * + * * @param winx * @param winy * @param winz @@ -807,7 +807,7 @@ public class ProjectDouble { * @param projMatrix * @param viewport * @param obj_pos - * + * * @return */ public boolean gluUnProject(double winx, @@ -858,7 +858,7 @@ public class ProjectDouble { /** * Method gluUnproject4 - * + * * @param winx * @param winy * @param winz @@ -869,7 +869,7 @@ public class ProjectDouble { * @param near * @param far * @param obj_pos - * + * * @return */ public boolean gluUnProject4(double winx, @@ -923,7 +923,7 @@ public class ProjectDouble { /** * Method gluUnproject4 - * + * * @param winx * @param winy * @param winz @@ -934,7 +934,7 @@ public class ProjectDouble { * @param near * @param far * @param obj_pos - * + * * @return */ public boolean gluUnProject4(double winx, @@ -987,7 +987,7 @@ public class ProjectDouble { /** * Method gluPickMatrix - * + * * @param x * @param y * @param deltaX @@ -1014,7 +1014,7 @@ public class ProjectDouble { /** * Method gluPickMatrix - * + * * @param x * @param y * @param deltaX diff --git a/src/jogl/classes/jogamp/opengl/glu/GLUquadricImpl.java b/src/jogl/classes/jogamp/opengl/glu/GLUquadricImpl.java index 7cd7da53e..b4383c2e6 100644 --- a/src/jogl/classes/jogamp/opengl/glu/GLUquadricImpl.java +++ b/src/jogl/classes/jogamp/opengl/glu/GLUquadricImpl.java @@ -6,15 +6,15 @@ ** 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. -** +** ** NOTE: The Original Code (as defined below) has been licensed to Sun ** Microsystems, Inc. ("Sun") under the SGI Free Software License B ** (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ ** 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 @@ -45,56 +45,56 @@ ** $Header$ */ -/* +/* * 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 + * modification, are permitted provided that the following conditions are * met: - * - * * Redistributions of source code must retain the above copyright + * + * * 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 + * * 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 + * 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 + * 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. */ /* * 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 @@ -107,7 +107,7 @@ * 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. @@ -124,8 +124,8 @@ import com.jogamp.opengl.util.glsl.ShaderState; /** * GLUquadricImpl.java - * - * + * + * * Created 22-dec-2003 (originally Quadric.java) * @author Erik Duijs * @author Kenneth Russell, Sven Gothel @@ -197,19 +197,19 @@ public class GLUquadricImpl implements GLUquadric { ImmModeSink res = immModeSink; if(useGLSL) { if(null != shaderState) { - immModeSink = ImmModeSink.createGLSL (32, - 3, GL.GL_FLOAT, // vertex + immModeSink = ImmModeSink.createGLSL (32, + 3, GL.GL_FLOAT, // vertex 0, GL.GL_FLOAT, // color USE_NORM?3:0, normalType, // normal USE_TEXT?2:0, GL.GL_FLOAT, // texCoords GL.GL_STATIC_DRAW, shaderState); } else { - immModeSink = ImmModeSink.createGLSL (32, - 3, GL.GL_FLOAT, // vertex + immModeSink = ImmModeSink.createGLSL (32, + 3, GL.GL_FLOAT, // vertex 0, GL.GL_FLOAT, // color USE_NORM?3:0, normalType, // normal USE_TEXT?2:0, GL.GL_FLOAT, // texCoords - GL.GL_STATIC_DRAW, shaderProgram); + GL.GL_STATIC_DRAW, shaderProgram); } } else { immModeSink = ImmModeSink.createFixed(32, @@ -229,7 +229,7 @@ public class GLUquadricImpl implements GLUquadric { } /** - * specifies the draw style for quadrics. + * specifies the draw style for quadrics. * * The legal values are as follows: * @@ -243,7 +243,7 @@ public class GLUquadricImpl implements GLUquadric { * separating coplanar faces will not be drawn. * * GLU.POINT: Quadrics are rendered as a set of points. - * + * * @param drawStyle The drawStyle to set */ public void setDrawStyle(int drawStyle) { @@ -260,7 +260,7 @@ public class GLUquadricImpl implements GLUquadric { * * GLU.SMOOTH: One normal is generated for every vertex of a quadric. This * is the default. - * + * * @param normals The normals to set */ public void setNormals(int normals) { @@ -277,7 +277,7 @@ public class GLUquadricImpl implements GLUquadric { * * Note that the interpretation of outward and inward depends on the quadric * being drawn. - * + * * @param orientation The orientation to set */ public void setOrientation(int orientation) { @@ -292,7 +292,7 @@ public class GLUquadricImpl implements GLUquadric { * * The manner in which texture coordinates are generated depends upon the * specific quadric rendered. - * + * * @param textureFlag The textureFlag to set */ public void setTextureFlag(boolean textureFlag) { @@ -512,10 +512,10 @@ public class GLUquadricImpl implements GLUquadric { glNormal3f(gl, 0.0f, 0.0f, -1.0f); } } - + da = 2.0f * PI / slices; dr = (outerRadius - innerRadius) / loops; - + switch (drawStyle) { case GLU.GLU_FILL: { @@ -648,18 +648,18 @@ public class GLUquadricImpl implements GLUquadric { * through startAngle + sweepAngle is included (where 0 degrees is along * the +y axis, 90 degrees along the +x axis, 180 along the -y axis, and * 270 along the -x axis). - * + * * The partial disk has a radius of outerRadius, and contains a concentric * circular hole with a radius of innerRadius. If innerRadius is zero, then * no hole is generated. The partial disk is subdivided around the z axis * into slices (like pizza slices), and also about the z axis into rings * (as specified by slices and loops, respectively). - * + * * With respect to orientation, the +z side of the partial disk is * considered to be outside (see gluQuadricOrientation). This means that if * the orientation is set to GLU.GLU_OUTSIDE, then any normals generated point * along the +z axis. Otherwise, they point along the -z axis. - * + * * If texturing is turned on (with gluQuadricTexture), texture coordinates * are generated linearly such that where r=outerRadius, the value at (r, 0, 0) * is (1, 0.5), at (0, r, 0) it is (0.5, 1), at (-r, 0, 0) it is (0, 0.5), @@ -1204,7 +1204,7 @@ public class GLUquadricImpl implements GLUquadric { */ private void normal3f(GL gl, float x, float y, float z) { float mag; - + mag = (float)Math.sqrt(x * x + y * y + z * z); if (mag > 0.00001F) { x /= mag; diff --git a/src/jogl/classes/jogamp/opengl/glu/Glue.java b/src/jogl/classes/jogamp/opengl/glu/Glue.java index 636d17f29..2ad3d8c89 100644 --- a/src/jogl/classes/jogamp/opengl/glu/Glue.java +++ b/src/jogl/classes/jogamp/opengl/glu/Glue.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -89,15 +89,15 @@ public class Glue { "null control point reference", "duplicate point on piecewise linear trimming curve" } ; - + /** Creates a new instance of Glue */ public Glue() { } - + public static String __gluNURBSErrorString( int errno ) { return( __gluNurbsErrors[ errno ] ); } - + private static String[] __gluTessErrors = { " ", "gluTessBeginPolygon() must precede a gluTessEndPolygon", @@ -107,7 +107,7 @@ public class Glue { "a coordinate is too large", "need combine callback" }; - + public static String __gluTessErrorString( int errno ) { return( __gluTessErrors[ errno ] ); } diff --git a/src/jogl/classes/jogamp/opengl/glu/error/Error.java b/src/jogl/classes/jogamp/opengl/glu/error/Error.java index 2f49db9a4..ffb8d9471 100644 --- a/src/jogl/classes/jogamp/opengl/glu/error/Error.java +++ b/src/jogl/classes/jogamp/opengl/glu/error/Error.java @@ -6,9 +6,9 @@ * 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 @@ -24,13 +24,13 @@ * except that Section 2.2 and 11 are omitted. Any differences between * the Alternative License and the SGI License are offered solely by Sun * and not by SGI. - * + * * 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 @@ -53,7 +53,7 @@ import jogamp.opengl.glu.Glue; * @author Administrator */ public class Error { - + private static String[] glErrorStrings = { "invalid enumerant", "invalid value", @@ -63,7 +63,7 @@ public class Error { "out of memory", "invalid framebuffer operation" }; - + private static String[] gluErrorStrings = { "invalid enumerant", "invalid value", @@ -71,11 +71,11 @@ public class Error { "", "invalid operation" }; - + /** Creates a new instance of Error */ public Error() { } - + public static String gluErrorString( int errorCode ) { if( errorCode == 0 ) { return( "no error" ); diff --git a/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2CurveEvaluator.java b/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2CurveEvaluator.java index 2ef4468e5..f57c2310f 100644 --- a/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2CurveEvaluator.java +++ b/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2CurveEvaluator.java @@ -48,7 +48,7 @@ import javax.media.opengl.glu.gl2.GLUgl2; class GL2CurveEvaluator implements CurveEvaluator { /** - * Output triangles (for callback) or render curve + * Output triangles (for callback) or render curve */ private boolean output_triangles; diff --git a/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GLUgl2nurbsImpl.java b/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GLUgl2nurbsImpl.java index 58b565484..f83b3a805 100644 --- a/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GLUgl2nurbsImpl.java +++ b/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GLUgl2nurbsImpl.java @@ -43,9 +43,9 @@ import javax.media.opengl.glu.GLUnurbs; /** * Base object for working with NURBS curves and surfaces - * + * * @author Tomas Hrasky - * + * */ public class GLUgl2nurbsImpl implements GLUnurbs { @@ -272,7 +272,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Sets domain distance for dom.dist. sampling in u direction - * + * * @param d * distance */ @@ -283,7 +283,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Sets domain distance for dom.dist. sampling in v direction - * + * * @param d * distance */ @@ -303,7 +303,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Calls a method with given name and passes argumet - * + * * @param name * name of a method to be called * @param arg @@ -329,7 +329,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Calls a method with given name - * + * * @param name * name of a method to be called */ @@ -349,7 +349,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Begins a NURBS curve - * + * * @param o_curve * curve object */ @@ -381,7 +381,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Begins new surface - * + * * @param o_surface * surface object */ @@ -503,7 +503,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Method for handling error codes - * + * * @param i * error code */ @@ -539,7 +539,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Make a NURBS curve - * + * * @param nknots * number of knots in knot vector * @param knot @@ -587,7 +587,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Check knot vector specification - * + * * @param knots * knot vector * @param msg @@ -607,7 +607,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Draw a curve - * + * * @param o_nurbscurve * NURBS curve object */ @@ -660,7 +660,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Draw NURBS surface - * + * * @param o_nurbssurface * NURBS surface object */ @@ -704,7 +704,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Define a map of given properties - * + * * @param type * map type * @param rational @@ -719,7 +719,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Set NURBS property - * + * * @param type * property type * @param tag @@ -744,7 +744,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Set parameters of existing property - * + * * @param prop * property */ @@ -755,7 +755,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Set given property to rendering hints - * + * * @param prop * property to be set */ @@ -767,7 +767,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Sets wheteher we use domain distance sampling - * + * * @param i * domain distance sampling flag */ @@ -805,7 +805,7 @@ public class GLUgl2nurbsImpl implements GLUnurbs { /** * Make NURBS surface - * + * * @param sknot_count * number of knots in s direction * @param sknot diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/BuildMipmap.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/BuildMipmap.java index f5fe17a7b..81a99beab 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/BuildMipmap.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/BuildMipmap.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -64,7 +64,7 @@ public class BuildMipmap { /** Creates a new instance of BuildMipmap */ public BuildMipmap() { } - + public static int gluBuild1DMipmapLevelsCore( GL gl, int target, int internalFormat, int width, int widthPowerOf2, int format, int type, int userLevel, int baseLevel, int maxLevel, ByteBuffer data ) { @@ -78,34 +78,34 @@ public class BuildMipmap { int maxsize; int cmpts; PixelStorageModes psm = new PixelStorageModes(); - + assert( Mipmap.checkMipmapArgs( internalFormat, format, type ) == 0 ); assert( width >= 1 ); - + newwidth = widthPowerOf2; levels = Mipmap.computeLog( newwidth ); - + levels += userLevel; - + Mipmap.retrieveStoreModes( gl, psm ); try { - newImage = Buffers.newDirectByteBuffer( Mipmap.image_size( width, 1, format, + newImage = Buffers.newDirectByteBuffer( Mipmap.image_size( width, 1, format, GL2.GL_UNSIGNED_SHORT ) ).asShortBuffer(); } catch( OutOfMemoryError ome ) { return( GLU.GLU_OUT_OF_MEMORY ); } newImage_width = width; - + Image.fill_image( psm, width, 1, format, type, Mipmap.is_index( format ), data, newImage ); cmpts = Mipmap.elements_per_group( format, type ); gl.glPixelStorei( GL2.GL_UNPACK_ALIGNMENT, 2 ); gl.glPixelStorei( GL2.GL_UNPACK_SKIP_ROWS, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_SKIP_PIXELS, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_ROW_LENGTH, 0 ); - + // if swap_bytes was set, swapping occurred in fill_image gl.glPixelStorei( GL2.GL_UNPACK_SWAP_BYTES, GL2.GL_FALSE ); - + for( level = userLevel; level <= levels; level++ ) { if( newImage_width == newwidth ) { // user newimage for this level @@ -132,10 +132,10 @@ public class BuildMipmap { imageTemp = otherImage; otherImage = newImage; newImage = imageTemp; - + newImage_width = newwidth; if( baseLevel <= level && level <= maxLevel ) { - gl.getGL2().glTexImage1D( target, level, internalFormat, newImage_width, 0, + gl.getGL2().glTexImage1D( target, level, internalFormat, newImage_width, 0, format, GL2.GL_UNSIGNED_SHORT, newImage ); } } @@ -148,10 +148,10 @@ public class BuildMipmap { gl.glPixelStorei( GL2.GL_UNPACK_SKIP_PIXELS, psm.getUnpackSkipPixels() ); gl.glPixelStorei( GL2.GL_UNPACK_ROW_LENGTH, psm.getUnpackRowLength() ); gl.glPixelStorei( GL2.GL_UNPACK_SWAP_BYTES, (psm.getUnpackSwapBytes() ? 1 : 0) ); - + return( 0 ); } - + public static int bitmapBuild2DMipmaps( GL gl, int target, int internalFormat, int width, int height, int format, int type, ByteBuffer data ) { int newwidth[] = new int[1]; @@ -166,37 +166,37 @@ public class BuildMipmap { int maxsize; int cmpts; PixelStorageModes psm = new PixelStorageModes(); - + Mipmap.retrieveStoreModes( gl, psm ); - + Mipmap.closestFit( gl, target, width, height, internalFormat, format, type, newwidth, newheight ); - + levels = Mipmap.computeLog( newwidth[0] ); level = Mipmap.computeLog( newheight[0] ); if( level > levels ) { levels = level; } - + try { - newImage = Buffers.newDirectByteBuffer( Mipmap.image_size( width, height, + newImage = Buffers.newDirectByteBuffer( Mipmap.image_size( width, height, format, GL2.GL_UNSIGNED_SHORT ) ).asShortBuffer(); } catch( OutOfMemoryError ome ) { return( GLU.GLU_OUT_OF_MEMORY ); } newImage_width = width; newImage_height = height; - + Image.fill_image( psm, width, height, format, type, Mipmap.is_index( format ), data, newImage ); - + cmpts = Mipmap.elements_per_group( format, type ); gl.glPixelStorei( GL2.GL_UNPACK_ALIGNMENT, 2 ); gl.glPixelStorei( GL2.GL_UNPACK_SKIP_ROWS, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_SKIP_PIXELS, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_ROW_LENGTH, 0 ); - + // if swap_bytes is set, swapping occurred in fill_image gl.glPixelStorei( GL2.GL_UNPACK_SWAP_BYTES, GL2.GL_FALSE ); - + for( level = 0; level < levels; level++ ) { if( newImage_width == newwidth[0] && newImage_height == newheight[0] ) { newImage.rewind(); @@ -216,13 +216,13 @@ public class BuildMipmap { return( GLU.GLU_OUT_OF_MEMORY ); } } - ScaleInternal.scale_internal( cmpts, newImage_width, newImage_height, + ScaleInternal.scale_internal( cmpts, newImage_width, newImage_height, newImage, newwidth[0], newheight[0], otherImage ); // swap newImage and otherImage tempImage = otherImage; otherImage = newImage; newImage = tempImage; - + newImage_width = newwidth[0]; newImage_height = newheight[0]; newImage.rewind(); @@ -241,10 +241,10 @@ public class BuildMipmap { gl.glPixelStorei( GL2.GL_UNPACK_SKIP_PIXELS, psm.getUnpackSkipPixels() ); gl.glPixelStorei( GL2.GL_UNPACK_ROW_LENGTH, psm.getUnpackRowLength() ); gl.glPixelStorei( GL2.GL_UNPACK_SWAP_BYTES, (psm.getUnpackSwapBytes() ? 1 : 0) ); - + return( 0 ); } - + public static int gluBuild2DMipmapLevelsCore( GL gl, int target, int internalFormat, int width, int height, int widthPowerOf2, int heightPowerOf2, int format, int type, int userLevel, int baseLevel, int maxLevel, @@ -263,19 +263,19 @@ public class BuildMipmap { int maxsize; int cmpts; int mark=-1; - + boolean myswap_bytes; int groups_per_line, element_size, group_size; int rowsize, padding; PixelStorageModes psm = new PixelStorageModes(); - + assert( Mipmap.checkMipmapArgs( internalFormat, format, type ) == 0 ); assert( width >= 1 && height >= 1 ); - + if( type == GL2.GL_BITMAP ) { return( bitmapBuild2DMipmaps( gl, target, internalFormat, width, height, format, type, data ) ); } - + newwidth = widthPowerOf2; newheight = heightPowerOf2; levels = Mipmap.computeLog( newwidth ); @@ -283,9 +283,9 @@ public class BuildMipmap { if( level > levels ) { levels = level; } - + levels += userLevel; - + Mipmap.retrieveStoreModes( gl, psm ); myswap_bytes = psm.getUnpackSwapBytes(); cmpts = Mipmap.elements_per_group( format, type ); @@ -294,28 +294,28 @@ public class BuildMipmap { } else { groups_per_line = width; } - + element_size = Mipmap.bytes_per_element( type ); group_size = element_size * cmpts; if( element_size == 1 ) { myswap_bytes = false; } - + rowsize = groups_per_line * group_size; padding = ( rowsize % psm.getUnpackAlignment() ); if( padding != 0 ) { rowsize += psm.getUnpackAlignment() - padding; } - + mark = psm.getUnpackSkipRows() * rowsize + psm.getUnpackSkipPixels() * group_size; data.position( mark ); - + gl.glPixelStorei( GL2.GL_UNPACK_SKIP_ROWS, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_SKIP_PIXELS, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_ROW_LENGTH, 0 ); - + level = userLevel; - + // already power of two square if( width == newwidth && height == newheight ) { // use usersImage for level userLevel @@ -333,7 +333,7 @@ public class BuildMipmap { } int nextWidth = newwidth / 2; int nextHeight = newheight / 2; - + // clamp to 1 if( nextWidth < 1 ) { nextWidth = 1; @@ -342,7 +342,7 @@ public class BuildMipmap { nextHeight = 1; } memReq = Mipmap.image_size( nextWidth, nextHeight, format, type ); - + try { switch( type ) { case( GL2.GL_UNSIGNED_BYTE ): @@ -452,7 +452,7 @@ public class BuildMipmap { if( newheight < 1 ) { newheight = 1; } - + myswap_bytes = false; rowsize = newwidth * group_size; memReq = Mipmap.image_size( newwidth, newheight, format, type ); @@ -498,7 +498,7 @@ public class BuildMipmap { level = userLevel + 1; } else { // user's image is not nice powerof2 size square memReq = Mipmap.image_size( newwidth, newheight, format, type ); - try { + try { switch( type ) { case( GL2.GL_UNSIGNED_BYTE ): case( GL2.GL_BYTE ): @@ -535,15 +535,15 @@ public class BuildMipmap { data.position( mark ); switch( type ) { case( GL2.GL_UNSIGNED_BYTE ): - ScaleInternal.scale_internal_ubyte( cmpts, width, height, data, + ScaleInternal.scale_internal_ubyte( cmpts, width, height, data, newwidth, newheight, dstImage, element_size, rowsize, group_size ); break; case( GL2.GL_BYTE ): - ScaleInternal.scale_internal_byte( cmpts, width, height, data, newwidth, + ScaleInternal.scale_internal_byte( cmpts, width, height, data, newwidth, newheight, dstImage, element_size, rowsize, group_size ); break; case( GL2.GL_UNSIGNED_SHORT ): - ScaleInternal.scale_internal_ushort( cmpts, width, height, data, newwidth, + ScaleInternal.scale_internal_ushort( cmpts, width, height, data, newwidth, newheight, dstImage.asShortBuffer(), element_size, rowsize, group_size, myswap_bytes ); break; case( GL2.GL_SHORT ): @@ -620,7 +620,7 @@ public class BuildMipmap { tempImage = srcImage; srcImage = dstImage; dstImage = tempImage; - + if( levels != 0 ) { // use as little memory as possible int nextWidth = newwidth / 2; int nextHeight = newheight / 2; @@ -630,7 +630,7 @@ public class BuildMipmap { if( nextHeight < 1 ) { nextHeight = 1; } - + memReq = Mipmap.image_size( nextWidth, nextHeight, format, type ); try { switch( type ) { @@ -670,7 +670,7 @@ public class BuildMipmap { // level userLevel is in srcImage; nothing saved yet level = userLevel; } - + gl.glPixelStorei( GL2.GL_UNPACK_SWAP_BYTES, GL2.GL_FALSE ); if( baseLevel <= level && level <= maxLevel ) { srcImage.rewind(); @@ -685,7 +685,7 @@ public class BuildMipmap { } } } - + level++; // update current level for the loop for( ; level <= levels; level++ ) { srcImage.rewind(); @@ -754,12 +754,12 @@ public class BuildMipmap { assert( false ); break; } - + // swap dstImage and srcImage tempImage = srcImage; srcImage = dstImage; dstImage = tempImage; - + if( newwidth > 1 ) { newwidth /= 2; rowsize /= 2; @@ -769,7 +769,7 @@ public class BuildMipmap { } // compute amount to pad per row if any int rowPad = rowsize % psm.getUnpackAlignment(); - + // should row be padded if( rowPad == 0 ) { // call teximage with srcImage untouched since its not padded @@ -792,7 +792,7 @@ public class BuildMipmap { int ii, jj; int dstTrav; int srcTrav; - + // allocate new image for mipmap of size newRowLength x newheight ByteBuffer newMipmapImage = null; try { @@ -813,7 +813,7 @@ public class BuildMipmap { newMipmapImage.put( srcImage.get() ); } } - + // and use this new image for mipmapping instead if( baseLevel <= level && level <= maxLevel ) { newMipmapImage.rewind(); @@ -833,10 +833,10 @@ public class BuildMipmap { gl.glPixelStorei( GL2.GL_UNPACK_SKIP_PIXELS, psm.getUnpackSkipPixels() ); gl.glPixelStorei( GL2.GL_UNPACK_ROW_LENGTH, psm.getUnpackRowLength() ); gl.glPixelStorei( GL2.GL_UNPACK_SWAP_BYTES, (psm.getUnpackSwapBytes() ? 1 : 0) ); - + return( 0 ); } - + public static int fastBuild2DMipmaps( GL gl, PixelStorageModes psm, int target, int components, int width, int height, int format, int type, ByteBuffer data ) { int[] newwidth = new int[1]; @@ -850,22 +850,22 @@ public class BuildMipmap { int memReq; int maxsize; int cmpts; - - Mipmap.closestFit( gl, target, width, height, components, format, type, newwidth, + + Mipmap.closestFit( gl, target, width, height, components, format, type, newwidth, newheight ); - + levels = Mipmap.computeLog( newwidth[0] ); level = Mipmap.computeLog( newheight[0] ); if( level > levels ) { levels = level; } - + cmpts = Mipmap.elements_per_group( format, type ); - + otherImage = null; // No need to copy the user data if its packed correctly. // Make sure that later routines don't change that data. - + if( psm.getUnpackSkipRows() == 0 && psm.getUnpackSkipPixels() == 0 ) { newImage = data; newImage_width = width; @@ -878,7 +878,7 @@ public class BuildMipmap { int iter; int iter2; int i, j; - + try { newImage = Buffers.newDirectByteBuffer( Mipmap.image_size(width, height, format, GL2.GL_UNSIGNED_BYTE ) ); } catch( OutOfMemoryError err ) { @@ -896,7 +896,7 @@ public class BuildMipmap { rowsize = group_per_line * cmpts; elements_per_line = width * cmpts; start = psm.getUnpackSkipRows() * rowsize + psm.getUnpackSkipPixels() * cmpts; - + for( i = 0; i < height; i++ ) { iter = start; data.position( iter ); @@ -906,13 +906,13 @@ public class BuildMipmap { start += rowsize; } } - + gl.glPixelStorei( GL2.GL_UNPACK_ALIGNMENT, 1 ); gl.glPixelStorei( GL2.GL_UNPACK_SKIP_ROWS, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_SKIP_PIXELS, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_ROW_LENGTH, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_SWAP_BYTES, GL2.GL_FALSE ); - + for( level = 0; level <= levels; level++ ) { if( newImage_width == newwidth[0] && newImage_height == newheight[0] ) { // use newImage for this level @@ -937,7 +937,7 @@ public class BuildMipmap { imageTemp = otherImage; otherImage = newImage; newImage = imageTemp; - + newImage_width = newwidth[0]; newImage_height = newheight[0]; newImage.rewind(); @@ -956,10 +956,10 @@ public class BuildMipmap { gl.glPixelStorei( GL2.GL_UNPACK_SKIP_PIXELS, psm.getUnpackSkipPixels() ); gl.glPixelStorei( GL2.GL_UNPACK_ROW_LENGTH, psm.getUnpackRowLength() ); gl.glPixelStorei( GL2.GL_UNPACK_SWAP_BYTES, ( psm.getUnpackSwapBytes() ? 1 : 0 ) ) ; - + return( 0 ); } - + public static int gluBuild3DMipmapLevelsCore( GL gl, int target, int internalFormat, int width, int height, int depth, int widthPowerOf2, int heightPowerOf2, int depthPowerOf2, int format, int type, int userLevel, int baseLevel, @@ -977,19 +977,19 @@ public class BuildMipmap { int maxSize; int cmpts; int mark=-1; - + boolean myswapBytes; int groupsPerLine, elementSize, groupSize; int rowsPerImage, imageSize; int rowSize, padding; PixelStorageModes psm = new PixelStorageModes(); - + assert( Mipmap.checkMipmapArgs( internalFormat, format, type ) == 0 ); assert( width >= 1 && height >= 1 && depth >= 1 ); assert( type != GL2.GL_BITMAP ); - + srcImage = dstImage = null; - + newWidth = widthPowerOf2; newHeight = heightPowerOf2; newDepth = depthPowerOf2; @@ -1002,9 +1002,9 @@ public class BuildMipmap { if( level > levels ) { levels = level; } - + levels += userLevel; - + Mipmap.retrieveStoreModes3D( gl, psm ); myswapBytes = psm.getUnpackSwapBytes(); cmpts = Mipmap.elements_per_group( format, type ); @@ -1013,42 +1013,42 @@ public class BuildMipmap { } else { groupsPerLine = width; } - + elementSize = Mipmap.bytes_per_element( type ); groupSize = elementSize * cmpts; if( elementSize == 1 ) { myswapBytes = false; } - + // 3dstuff if( psm.getUnpackImageHeight() > 0 ) { rowsPerImage = psm.getUnpackImageHeight(); } else { rowsPerImage = height; } - + rowSize = groupsPerLine * groupSize; padding = ( rowSize % psm.getUnpackAlignment() ); if( padding != 0 ) { rowSize += psm.getUnpackAlignment() - padding; } - + imageSize = rowsPerImage * rowSize; - + usersImage = ByteBuffer.wrap(data.array()); mark = psm.getUnpackSkipRows() * rowSize + psm.getUnpackSkipPixels() * groupSize + psm.getUnpackSkipImages() * imageSize; usersImage.position( mark ); - + gl.glPixelStorei( GL2.GL_UNPACK_SKIP_ROWS, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_SKIP_PIXELS, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_ROW_LENGTH, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_SKIP_IMAGES, 0 ); gl.glPixelStorei( GL2.GL_UNPACK_IMAGE_HEIGHT, 0 ); - + level = userLevel; - + if( width == newWidth && height == newHeight && depth == newDepth ) { // use usersImage for level userlevel if( baseLevel <= level && level <= maxLevel ) { @@ -1068,7 +1068,7 @@ public class BuildMipmap { int nextWidth = newWidth / 2; int nextHeight = newHeight / 2; int nextDepth = newDepth / 2; - + // clamp to one if( nextWidth < 1 ) { nextWidth = 1; @@ -1116,13 +1116,13 @@ public class BuildMipmap { gl.glPixelStorei( GL2.GL_UNPACK_IMAGE_HEIGHT, psm.getUnpackImageHeight() ); return( GLU.GLU_OUT_OF_MEMORY ); } - + if( dstImage != null ) { switch( type ) { case( GL2.GL_UNSIGNED_BYTE ): if( depth > 1 ) { HalveImage.halveImage3D( cmpts, new ExtractUByte(), width, height, depth, - usersImage, dstImage, elementSize, + usersImage, dstImage, elementSize, groupSize, rowSize, imageSize, myswapBytes ); } else { HalveImage.halveImage_ubyte( cmpts, width, height, usersImage, @@ -1145,7 +1145,7 @@ public class BuildMipmap { usersImage, dstImage, elementSize, groupSize, rowSize, imageSize, myswapBytes ); } else { - HalveImage.halveImage_ushort( cmpts, width, height, usersImage, + HalveImage.halveImage_ushort( cmpts, width, height, usersImage, dstImage.asShortBuffer(), elementSize, rowSize, groupSize, myswapBytes ); } break; @@ -1257,7 +1257,7 @@ public class BuildMipmap { if( newDepth < 1 ) { newDepth = 1; } - + myswapBytes = false; rowSize = newWidth * groupSize; imageSize = rowSize * newHeight; @@ -1302,7 +1302,7 @@ public class BuildMipmap { gl.glPixelStorei( GL2.GL_UNPACK_IMAGE_HEIGHT, psm.getUnpackImageHeight() ); return( GLU.GLU_OUT_OF_MEMORY ); } - + // level userLevel + 1 is in srcImage; level userLevel already saved level = userLevel + 1; } else { @@ -1343,10 +1343,10 @@ public class BuildMipmap { gl.glPixelStorei( GL2.GL_UNPACK_IMAGE_HEIGHT, psm.getUnpackImageHeight() ); return( GLU.GLU_OUT_OF_MEMORY ); } - + ScaleInternal.gluScaleImage3D( gl, format, width, height, depth, type, usersImage, newWidth, newHeight, newDepth, type, dstImage ); - + myswapBytes = false; rowSize = newWidth * groupSize; imageSize = rowSize * newHeight; @@ -1354,7 +1354,7 @@ public class BuildMipmap { tempImage = srcImage; srcImage = dstImage; dstImage = tempImage; - + if( levels != 0 ) { int nextWidth = newWidth / 2; int nextHeight = newHeight / 2; @@ -1409,7 +1409,7 @@ public class BuildMipmap { // level userLevel is in srcImage; nothing saved yet level = userLevel; } - + gl.glPixelStorei( GL2.GL_UNPACK_SWAP_BYTES, GL2.GL_FALSE ); if( baseLevel <= level && level <= maxLevel ) { usersImage.position( mark ); @@ -1541,11 +1541,11 @@ public class BuildMipmap { assert( false ); break; } - + tempImage = srcImage; srcImage = dstImage; dstImage = tempImage; - + if( newWidth > 1 ) { newWidth /= 2; rowSize /= 2; diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract.java index a564269fb..0eee9bf32 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1010102.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1010102.java index 10ea1d729..5269024b4 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1010102.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1010102.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,42 +51,42 @@ import java.nio.ByteBuffer; * @author Administrator */ public class Extract1010102 implements Extract { - + /** Creates a new instance of Extract1010102 */ public Extract1010102() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { long uint = 0; - + if( isSwap ) { uint = 0x00000000FFFFFFFF & Mipmap.GLU_SWAP_4_BYTES( packedPixel.getInt() ); } else { uint = 0x00000000FFFFFFFF & packedPixel.getInt(); } - + // 11111111,11000000,00000000,00000000 == 0xFFC00000 // 00000000,00111111,11110000,00000000 == 0x003F0000 // 00000000,00000000,00001111,11111100 == 0x00000FFC // 00000000,00000000,00000000,00000011 == 0x00000003 - + extractComponents[0] = (float)( ( uint & 0xFFC00000 ) >> 22 ) / 1023.0f; extractComponents[1] = (float)( ( uint & 0x003FF000 ) >> 12 ) / 1023.0f; extractComponents[2] = (float)( ( uint & 0x00000FFC ) >> 2 ) / 1023.0f; extractComponents[3] = (float)( ( uint & 0x00000003 ) ) / 3.0f; } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 // 00000000,11110000 == 0x00F0 // 00000000,00001111 == 0x000F - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); assert( 0.0f <= shoveComponents[3] && shoveComponents[3] <= 1.0f ); - + // due to limited precision, need to round before shoving long uint = (((int)((shoveComponents[0] * 1023) + 0.5f) << 22) & 0xFFC00000 ); uint |= (((int)((shoveComponents[1] * 1023) + 0.5f) << 12) & 0x003FF000 ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1555rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1555rev.java index 1234da5f8..6982931d3 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1555rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1555rev.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,42 +51,42 @@ import java.nio.ByteBuffer; * @author Administrator */ public class Extract1555rev implements Extract { - + /** Creates a new instance of Extract1555rev */ public Extract1555rev() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; - + if( isSwap ) { ushort = 0x0000FFFF & Mipmap.GLU_SWAP_2_BYTES( packedPixel.getShort() ); } else { ushort = 0x0000FFFF & packedPixel.getShort(); } - + // 00000000,00011111 == 0x001F // 00000011,11100000 == 0x03E0 // 01111100,00000000 == 0x7C00 // 10000000,00000000 == 0x8000 - + extractComponents[0] = (float)( ( ushort & 0x001F ) ) / 31.0f; extractComponents[1] = (float)( ( ushort & 0x003E ) >> 5 ) / 31.0f; extractComponents[2] = (float)( ( ushort & 0x7C00 ) >> 10) / 31.0f; extractComponents[3] = (float)( ( ushort & 0x8000 ) >> 15); } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 00000000,00011111 == 0x001F // 00000011,11100000 == 0x03E0 // 01111100,00000000 == 0x7C00 // 10000000,00000000 == 0x8000 - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); assert( 0.0f <= shoveComponents[3] && shoveComponents[3] <= 1.0f ); - + // due to limited precision, need to round before shoving int ushort = (((int)((shoveComponents[0] * 31) + 0.5f) ) & 0x0000001F ); ushort |= (((int)((shoveComponents[1] * 31) + 0.5f) << 5) & 0x000003E0 ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract2101010rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract2101010rev.java index 226254f99..1c7db6218 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract2101010rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract2101010rev.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,42 +51,42 @@ import java.nio.ByteBuffer; * @author Administrator */ public class Extract2101010rev implements Extract { - + /** Creates a new instance of Extract2101010 */ public Extract2101010rev() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { long uint = 0; - + if( isSwap ) { uint = 0x00000000FFFFFFFF & Mipmap.GLU_SWAP_4_BYTES( packedPixel.getInt() ); } else { uint = 0x00000000FFFFFFFF & packedPixel.getInt(); } - + // 11111111,11000000,00000000,00000000 == 0xFFC00000 // 00000000,00111111,11110000,00000000 == 0x003F0000 // 00000000,00000000,00001111,11111100 == 0x00000FFC // 00000000,00000000,00000000,00000011 == 0x00000003 - + extractComponents[0] = (float)( ( uint & 0x000003FF ) ) / 1023.0f; extractComponents[1] = (float)( ( uint & 0x000FFC00 ) >> 10 ) / 1023.0f; extractComponents[2] = (float)( ( uint & 0x3FF00000 ) >> 20 ) / 1023.0f; extractComponents[3] = (float)( ( uint & 0xC0000000 ) >> 30 ) / 3.0f; } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 // 00000000,11110000 == 0x00F0 // 00000000,00001111 == 0x000F - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); assert( 0.0f <= shoveComponents[3] && shoveComponents[3] <= 1.0f ); - + // due to limited precision, need to round before shoving long uint = (((int)((shoveComponents[0] * 1023) + 0.5f) ) & 0x000003FF ); uint |= (((int)((shoveComponents[1] * 1023) + 0.5f) << 10) & 0x000FFC00 ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract233rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract233rev.java index 9fa2a3a54..672c86c32 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract233rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract233rev.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,11 +51,11 @@ import java.nio.ByteBuffer; * @author Administrator */ public class Extract233rev implements Extract { - + /** Creates a new instance of Extract223rev */ public Extract233rev() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { // 11100000 == 0xe0 // 00011100 == 0x1c @@ -65,16 +65,16 @@ public class Extract233rev implements Extract { extractComponents[1] = (float)((ubyte & 0x38) >> 3) / 7.0f; extractComponents[2] = (float)((ubyte & 0xC0) >> 6) / 3.0f; } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11100000 == 0xE0 // 00011100 == 0x1C // 00000011 == 0x03 - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); - + // due to limited precision, need to round before shoving byte b = (byte)( ( (int)( ( shoveComponents[0] * 7 ) + 0.5f ) ) & 0x07 ); b |= (byte)( ( (int)( ( shoveComponents[1] * 7 ) + 0.5f ) << 3 ) & 0x38 ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract332.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract332.java index 92d141be5..6cdbc5cb0 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract332.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract332.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,11 +51,11 @@ import java.nio.ByteBuffer; * @author Administrator */ public class Extract332 implements Extract { - + /** Creates a new instance of Extract332 */ public Extract332() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { // 11100000 == 0xe0 // 00011100 == 0x1c @@ -65,16 +65,16 @@ public class Extract332 implements Extract { extractComponents[1] = (float)((ubyte & 0x1c) >> 2) / 7.0f; extractComponents[2] = (float)((ubyte & 0x03)) / 3.0f; } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11100000 == 0xE0 // 00011100 == 0x1C // 00000011 == 0x03 - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); - + // due to limited precision, need to round before shoving byte b = (byte)( ( (int)( ( shoveComponents[0] * 7 ) + 0.5f ) << 5 ) & 0xE0 ); b |= (byte)( ( (int)( ( shoveComponents[1] * 7 ) + 0.5f ) << 2 ) & 0x1C ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444.java index af99d154c..b36b9fb82 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,41 +51,41 @@ import java.nio.*; * @author Administrator */ public class Extract4444 implements Extract { - + /** Creates a new instance of Extract4444 */ public Extract4444() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; - + if( isSwap ) { ushort = 0x0000FFFF & Mipmap.GLU_SWAP_2_BYTES( packedPixel.getShort() ); } else { ushort = 0x0000FFFF & packedPixel.getShort(); } - + // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 // 00000000,11110000 == 0x00F0 // 00000000,00001111 == 0x000F - + extractComponents[0] = (float)( ( ushort & 0xF000 ) >> 12 ) / 15.0f; extractComponents[1] = (float)( ( ushort & 0x0F00 ) >> 8 ) / 15.0f; extractComponents[2] = (float)( ( ushort & 0x00F0 ) >> 4 ) / 15.0f; extractComponents[3] = (float)( ( ushort & 0x000F ) ) / 15.0f; } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 // 00000000,11110000 == 0x00F0 // 00000000,00001111 == 0x000F - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); - + // due to limited precision, need to round before shoving int ushort = (((int)((shoveComponents[0] * 15) + 0.5f) << 12) & 0x0000F000 ); ushort |= (((int)((shoveComponents[1] * 15) + 0.5f) << 8) & 0x00000F00 ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444rev.java index e5bce60d8..b7a3ed55f 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444rev.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,42 +51,42 @@ import java.nio.*; * @author Administrator */ public class Extract4444rev implements Extract { - + /** Creates a new instance of Extract4444rev */ public Extract4444rev() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; - + if( isSwap ) { ushort = 0x0000FFFF & Mipmap.GLU_SWAP_2_BYTES( packedPixel.getShort() ); } else { ushort = 0x0000FFFF & packedPixel.getShort(); } - + // 00000000,00001111 == 0x000F // 00000000,11110000 == 0x00F0 // 00001111,00000000 == 0x0F00 // 11110000,00000000 == 0xF000 - + extractComponents[0] = (float)( ( ushort & 0x000F ) ) / 15.0f; extractComponents[1] = (float)( ( ushort & 0x00F0 ) >> 4 ) / 15.0f; extractComponents[2] = (float)( ( ushort & 0x0F00 ) >> 8 ) / 15.0f; extractComponents[3] = (float)( ( ushort & 0xF000 ) >> 12 ) / 15.0f; } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 // 00000000,11110000 == 0x00F0 // 00000000,00001111 == 0x000F - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); assert( 0.0f <= shoveComponents[3] && shoveComponents[3] <= 1.0f ); - + // due to limited precision, need to round before shoving int ushort = (((int)((shoveComponents[0] * 15) + 0.5f) ) & 0x0000000F ); ushort |= (((int)((shoveComponents[1] * 15) + 0.5f) << 4) & 0x000000F0 ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract5551.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract5551.java index 5c383103e..4dc566b25 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract5551.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract5551.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,42 +51,42 @@ import java.nio.*; * @author Administrator */ public class Extract5551 implements Extract { - + /** Creates a new instance of Extract5551 */ public Extract5551() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; - + if( isSwap ) { ushort = 0x0000FFFF & Mipmap.GLU_SWAP_2_BYTES( packedPixel.getShort() ); } else { ushort = 0x0000FFFF & packedPixel.getShort(); } - + // 11111000,00000000 == 0xF800 // 00000111,11000000 == 0x07C0 // 00000000,00111110 == 0x003E // 00000000,00000001 == 0x0001 - + extractComponents[0] = (float)( ( ushort & 0xF800 ) >> 11 ) / 31.0f; extractComponents[1] = (float)( ( ushort & 0x00F0 ) >> 6 ) / 31.0f; extractComponents[2] = (float)( ( ushort & 0x0F00 ) >> 1 ) / 31.0f; extractComponents[3] = (float)( ( ushort & 0xF000 ) ); } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 // 00000000,11110000 == 0x00F0 // 00000000,00001111 == 0x000F - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); assert( 0.0f <= shoveComponents[3] && shoveComponents[3] <= 1.0f ); - + // due to limited precision, need to round before shoving int ushort = (((int)((shoveComponents[0] * 31) + 0.5f) << 11) & 0x0000F800 ); ushort |= (((int)((shoveComponents[1] * 31) + 0.5f) << 6) & 0x000007C0 ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565.java index f6193dd2d..e198e46d4 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,38 +51,38 @@ import java.nio.*; * @author Administrator */ public class Extract565 implements Extract { - + /** Creates a new instance of Extract565 */ public Extract565() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; - + if( isSwap ) { ushort = 0x0000FFFF & Mipmap.GLU_SWAP_2_BYTES( packedPixel.getShort() ); } else { ushort = 0x0000FFFF & packedPixel.getShort(); } - + // 11111000,00000000 == 0xF800 // 00000111,11100000 == 0x07E0 // 00000000,00111111 == 0x001F - + extractComponents[0] = (float)( ( ushort & 0xF800 ) >> 11 ) / 31.0f; extractComponents[1] = (float)( ( ushort & 0x07E0 ) >> 5 ) / 63.0f; extractComponents[2] = (float)( ( ushort & 0x001F ) ) / 31.0f; } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11111000,00000000 == 0xF800 // 00000111,11100000 == 0x07E0 // 00000000,00111111 == 0x001F - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); - + // due to limited precision, need to round before shoving int ushort = (((int)((shoveComponents[0] * 31) + 0.5f) << 11) & 0x0000F800 ); ushort |= (((int)((shoveComponents[1] * 63) + 0.5f) << 5) & 0x000007E0 ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565rev.java index 2e455adfa..fe19540ee 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565rev.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,38 +51,38 @@ import java.nio.*; * @author Administrator */ public class Extract565rev implements Extract { - + /** Creates a new instance of Extract565rev */ public Extract565rev() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; - + if( isSwap ) { ushort = 0x0000FFFF & Mipmap.GLU_SWAP_2_BYTES( packedPixel.getShort() ); } else { ushort = 0x0000FFFF & packedPixel.getShort(); } - + // 00000000,00011111 == 0x001F // 00000111,11100000 == 0x07E0 // 11111000,00000000 == 0xF800 - + extractComponents[0] = (float)( ( ushort & 0x001F ) ) / 31.0f; extractComponents[1] = (float)( ( ushort & 0x07E0 ) >> 5 ) / 63.0f; extractComponents[2] = (float)( ( ushort & 0xF800 ) >> 11 ) / 31.0f; } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 00000000,00111111 == 0x001F // 00000111,11100000 == 0x07E0 // 11111000,00000000 == 0xF800 - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); - + // due to limited precision, need to round before shoving int ushort = (((int)((shoveComponents[0] * 31) + 0.5f) ) & 0x0000001F ); ushort |= (((int)((shoveComponents[1] * 63) + 0.5f) << 5) & 0x000007E0 ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888.java index 137fa3c21..4602f2af9 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,42 +51,42 @@ import java.nio.*; * @author Administrator */ public class Extract8888 implements Extract { - + /** Creates a new instance of Extract8888 */ public Extract8888() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { long uint = 0; - + if( isSwap ) { uint = 0x00000000FFFFFFFF & Mipmap.GLU_SWAP_4_BYTES( packedPixel.getInt() ); } else { uint = 0x00000000FFFFFFFF & packedPixel.getInt(); } - + // 11111000,00000000 == 0xF800 // 00000111,11000000 == 0x07C0 // 00000000,00111110 == 0x003E // 00000000,00000001 == 0x0001 - + extractComponents[0] = (float)( ( uint & 0xFF000000 ) >> 24 ) / 255.0f; extractComponents[1] = (float)( ( uint & 0x00FF0000 ) >> 16 ) / 255.0f; extractComponents[2] = (float)( ( uint & 0x0000FF00 ) >> 8 ) / 255.0f; extractComponents[3] = (float)( ( uint & 0x000000FF ) ) / 255.0f; } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 // 00000000,11110000 == 0x00F0 // 00000000,00001111 == 0x000F - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); assert( 0.0f <= shoveComponents[3] && shoveComponents[3] <= 1.0f ); - + // due to limited precision, need to round before shoving long uint = (((int)((shoveComponents[0] * 255) + 0.5f) << 24) & 0xFF000000 ); uint |= (((int)((shoveComponents[1] * 255) + 0.5f) << 16) & 0x00FF0000 ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888rev.java index 2ac942c84..373cb102a 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888rev.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,42 +51,42 @@ import java.nio.*; * @author Administrator */ public class Extract8888rev implements Extract { - + /** Creates a new instance of Extract8888rev */ public Extract8888rev() { } - + public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { long uint = 0; - + if( isSwap ) { uint = 0x00000000FFFFFFFF & Mipmap.GLU_SWAP_4_BYTES( packedPixel.getInt() ); } else { uint = 0x00000000FFFFFFFF & packedPixel.getInt(); } - + // 11111000,00000000 == 0xF800 // 00000111,11000000 == 0x07C0 // 00000000,00111110 == 0x003E // 00000000,00000001 == 0x0001 - + extractComponents[0] = (float)( ( uint & 0x000000FF ) ) / 255.0f; extractComponents[1] = (float)( ( uint & 0x0000FF00 ) >> 8 ) / 255.0f; extractComponents[2] = (float)( ( uint & 0x00FF0000 ) >> 16 ) / 255.0f; extractComponents[3] = (float)( ( uint & 0xFF000000 ) >> 24 ) / 255.0f; } - + public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 // 00000000,11110000 == 0x00F0 // 00000000,00001111 == 0x000F - + assert( 0.0f <= shoveComponents[0] && shoveComponents[0] <= 1.0f ); assert( 0.0f <= shoveComponents[1] && shoveComponents[1] <= 1.0f ); assert( 0.0f <= shoveComponents[2] && shoveComponents[2] <= 1.0f ); assert( 0.0f <= shoveComponents[3] && shoveComponents[3] <= 1.0f ); - + // due to limited precision, need to round before shoving long uint = (((int)((shoveComponents[0] * 255) + 0.5f) ) & 0x000000FF ); uint |= (((int)((shoveComponents[1] * 255) + 0.5f) << 8) & 0x0000FF00 ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractFloat.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractFloat.java index 52c2191b9..ac0f2f290 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractFloat.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractFloat.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,11 +51,11 @@ import java.nio.*; * @author Administrator */ public class ExtractFloat implements ExtractPrimitive { - + /** Creates a new instance of ExtractFloat */ public ExtractFloat() { } - + public double extract( boolean isSwap, ByteBuffer data ) { float f = 0; if( isSwap ) { @@ -66,7 +66,7 @@ public class ExtractFloat implements ExtractPrimitive { assert( f <= 1.0f ); return( f ); } - + public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < 1.0); data.asFloatBuffer().put( index, (float)value ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractPrimitive.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractPrimitive.java index 926096649..a44fb9508 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractPrimitive.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractPrimitive.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSByte.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSByte.java index 2e1a9a0a6..399386e30 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSByte.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSByte.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,17 +51,17 @@ import java.nio.ByteBuffer; * @author Administrator */ public class ExtractSByte implements ExtractPrimitive { - + /** Creates a new instance of ExtractUByte */ public ExtractSByte() { } - + public double extract( boolean isSwap, ByteBuffer sbyte ) { byte b = sbyte.get(); assert( b <= 127 ); return( b ); } - + public void shove( double value, int index, ByteBuffer data ) { data.position( index ); data.put( (byte)value ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSInt.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSInt.java index ca80747c4..be3fb3092 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSInt.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSInt.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,11 +51,11 @@ import java.nio.*; * @author Administrator */ public class ExtractSInt implements ExtractPrimitive { - + /** Creates a new instance of ExtractSInt */ public ExtractSInt() { } - + public double extract( boolean isSwap, ByteBuffer uint ) { int i = 0; if( isSwap ) { @@ -66,7 +66,7 @@ public class ExtractSInt implements ExtractPrimitive { assert( i <= 0x7FFFFFFF ); return( i ); } - + public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < Integer.MAX_VALUE); IntBuffer ib = data.asIntBuffer(); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSShort.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSShort.java index 979c3b449..1e123c9b4 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSShort.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSShort.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,11 +51,11 @@ import java.nio.*; * @author Administrator */ public class ExtractSShort implements ExtractPrimitive { - + /** Creates a new instance of ExtractSShort */ public ExtractSShort() { } - + public double extract( boolean isSwap, ByteBuffer ushort ) { short s = 0; if( isSwap ) { @@ -66,7 +66,7 @@ public class ExtractSShort implements ExtractPrimitive { assert( s <= 32767 ); return( s ); } - + public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < 32768.0); ShortBuffer sb = data.asShortBuffer(); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUByte.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUByte.java index 4d14212ab..26ca5cd40 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUByte.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUByte.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,17 +51,17 @@ import java.nio.ByteBuffer; * @author Administrator */ public class ExtractUByte implements ExtractPrimitive { - + /** Creates a new instance of ExtractUByte */ public ExtractUByte() { } - + public double extract( boolean isSwap, ByteBuffer ubyte ) { int i = 0x000000FF & ubyte.get(); assert( i <= 255 ); return( i ); } - + public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < 256.0); data.position( index ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUInt.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUInt.java index c088ca301..8c94c89fc 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUInt.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUInt.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,11 +51,11 @@ import java.nio.*; * @author Administrator */ public class ExtractUInt implements ExtractPrimitive { - + /** Creates a new instance of ExtractUInt */ public ExtractUInt() { } - + public double extract( boolean isSwap, ByteBuffer uint ) { long i = 0; if( isSwap ) { @@ -66,7 +66,7 @@ public class ExtractUInt implements ExtractPrimitive { assert( i <= 0xFFFFFFFF ); return( i ); } - + public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < 0xFFFFFFFF); IntBuffer ib = data.asIntBuffer(); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUShort.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUShort.java index 81db60f0f..55115c6f7 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUShort.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUShort.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,11 +51,11 @@ import java.nio.*; * @author Administrator */ public class ExtractUShort implements ExtractPrimitive { - + /** Creates a new instance of ExtracUShort */ public ExtractUShort() { } - + public double extract( boolean isSwap, ByteBuffer ushort ) { int i = 0; if( isSwap ) { @@ -66,7 +66,7 @@ public class ExtractUShort implements ExtractPrimitive { assert( i <= 65535 ); return( i ); } - + public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < 65536.0); ShortBuffer sb = data.asShortBuffer(); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/HalveImage.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/HalveImage.java index 7549044ba..184c5fda8 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/HalveImage.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/HalveImage.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -52,11 +52,11 @@ import java.nio.*; * @author Administrator */ public class HalveImage { - + private static final int BOX2 = 2; private static final int BOX4 = 4; private static final int BOX8 = 8; - + public static void halveImage( int components, int width, int height, ShortBuffer datain, ShortBuffer dataout ) { int i, j, k; @@ -64,11 +64,11 @@ public class HalveImage { int delta; int t = 0; short temp = 0; - + newwidth = width / 2; newheight = height /2; delta = width * components; - + // Piece of cake for( i = 0; i < newheight; i++ ) { for( j = 0; j < newwidth; j++ ) { @@ -91,7 +91,7 @@ public class HalveImage { t += delta; } } - + public static void halveImage_ubyte( int components, int width, int height, ByteBuffer datain, ByteBuffer dataout, int element_size, int ysize, int group_size ) { @@ -99,19 +99,19 @@ public class HalveImage { int newwidth, newheight; int s; int t; - + // Handle case where there is only 1 column/row if( width == 1 || height == 1 ) { assert( !( width == 1 && height == 1 ) ); // can't be 1x1 halve1Dimage_ubyte( components, width, height, datain, dataout, element_size, ysize, group_size ); return; } - + newwidth = width / 2; newheight = height / 2; s = 0; t = 0; - + int temp = 0; // piece of cake for( i = 0; i < newheight; i++ ) { @@ -133,9 +133,9 @@ public class HalveImage { t += ysize; } } - + public static void halve1Dimage_ubyte( int components, int width, int height, - ByteBuffer datain, ByteBuffer dataout, + ByteBuffer datain, ByteBuffer dataout, int element_size, int ysize, int group_size ) { int halfWidth = width / 2; int halfHeight = height / 2; @@ -143,14 +143,14 @@ public class HalveImage { int dest = 0; int jj; int temp = 0; - + assert( width == 1 || height == 1 ); // Must be 1D assert( width != height ); // can't be square - + if( height == 1 ) { // 1 row assert( width != 1 ); // widthxheight can't be 1x1 halfHeight = 1; - + for( jj = 0; jj < halfWidth; jj++ ) { int kk; for( kk = 0; kk < components; kk++ ) { @@ -161,7 +161,7 @@ public class HalveImage { temp /= 2; dataout.put( (byte)temp ); /* - dataout.setByte( (byte)(((0x000000FF & datain.setIndexInBytes(src).getByte()) + + dataout.setByte( (byte)(((0x000000FF & datain.setIndexInBytes(src).getByte()) + (0x000000FF & datain.setIndexInBytes( src + group_size ).getByte())) / 2 ) ); */ src += element_size; @@ -188,7 +188,7 @@ public class HalveImage { temp /= 2; dataout.put( (byte)temp ); /* - dataout.setByte( (byte)(((0x000000FF & datain.setIndexInBytes(src).getByte()) + + dataout.setByte( (byte)(((0x000000FF & datain.setIndexInBytes(src).getByte()) + (0x000000FF & datain.setIndexInBytes(src + ysize).getByte()) ) / 2 ) ); */ src += element_size; @@ -202,7 +202,7 @@ public class HalveImage { assert( src == ysize * height ); assert( dest == components * element_size * halfWidth * halfHeight ); } - + public static void halveImage_byte( int components, int width, int height, ByteBuffer datain, ByteBuffer dataout, int element_size, int ysize, int group_size ) { @@ -211,7 +211,7 @@ public class HalveImage { int s = 0; int t = 0; byte temp = (byte)0; - + // handle case where there is only 1 column if( width == 1 || height == 1 ) { assert( !( width == 1 && height == 1 ) ); @@ -219,10 +219,10 @@ public class HalveImage { ysize, group_size ); return; } - + newwidth = width / 2; newheight = height / 2; - + for( i = 0; i < newheight; i++ ) { for( j = 0; j < newwidth; j++ ) { for( k = 0; k < components; k++ ) { @@ -244,7 +244,7 @@ public class HalveImage { t += ysize; } } - + public static void halve1Dimage_byte( int components, int width, int height, ByteBuffer datain, ByteBuffer dataout, int element_size, int ysize, int group_size ) { @@ -254,14 +254,14 @@ public class HalveImage { int dest = 0; int jj; byte temp = (byte)0; - + assert( width == 1 || height == 1 ); // must be 1D assert( width != height ); // can't be square - + if( height == 1 ) { // 1 row assert( width != 1 ); // widthxheight can't be 1 halfHeight = 1; - + for( jj = 0; jj < halfWidth; jj++ ) { int kk; for( kk = 0; kk < components; kk++ ) { @@ -284,7 +284,7 @@ public class HalveImage { halfWidth = 1; // one vertical column with possible pad bytes per row // average two at a time - + for( jj = 0; jj < halfHeight; jj++ ) { int kk; for( kk = 0; kk < components; kk++ ) { @@ -303,7 +303,7 @@ public class HalveImage { } assert( dest == components * element_size * halfWidth * halfHeight ); } - + public static void halveImage_ushort( int components, int width, int height, ByteBuffer datain, ShortBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { @@ -319,10 +319,10 @@ public class HalveImage { ysize, group_size, myswap_bytes ); return; } - + newwidth = width / 2; newheight = height / 2; - + // Piece of cake if( !myswap_bytes ) { for( i = 0; i < newheight; i++ ) { @@ -364,7 +364,7 @@ public class HalveImage { } } } - + public static void halve1Dimage_ushort( int components, int width, int height, ByteBuffer datain, ShortBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { @@ -373,14 +373,14 @@ public class HalveImage { int src = 0; int dest = 0; int jj; - + assert( width == 1 || height == 1 ); // must be 1D assert( width != height ); // can't be square - + if( height == 1 ) { // 1 row assert( width != 1 ); // widthxheight can't be 1 halfHeight = 1; - + for( jj = 0; jj < halfWidth; jj++ ) { int kk; for( kk = 0; kk < halfHeight; kk++ ) { @@ -410,7 +410,7 @@ public class HalveImage { halfWidth = 1; // one vertical column with possible pad bytes per row // average two at a time - + for( jj = 0; jj < halfHeight; jj++ ) { int kk; for( kk = 0; kk < components; kk++ ) { @@ -437,7 +437,7 @@ public class HalveImage { } assert( dest == components * element_size * halfWidth * halfHeight ); } - + public static void halveImage_short( int components, int width, int height, ByteBuffer datain, ShortBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { @@ -453,10 +453,10 @@ public class HalveImage { ysize, group_size, myswap_bytes ); return; } - + newwidth = width / 2; newheight = height / 2; - + // Piece of cake if( !myswap_bytes ) { for( i = 0; i < newheight; i++ ) { @@ -504,7 +504,7 @@ public class HalveImage { } } } - + public static void halve1Dimage_short( int components, int width, int height, ByteBuffer datain, ShortBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { @@ -513,14 +513,14 @@ public class HalveImage { int src = 0; int dest = 0; int jj; - + assert( width == 1 || height == 1 ); // must be 1D assert( width != height ); // can't be square - + if( height == 1 ) { // 1 row assert( width != 1 ); // can't be 1x1 halfHeight = 1; - + for( jj = 0; jj < halfWidth; jj++ ) { int kk; for( kk = 0; kk < components; kk++ ) { @@ -550,7 +550,7 @@ public class HalveImage { halfWidth = 1; // one vertical column with possible pad bytes per row // average two at a time - + for( jj = 0; jj < halfHeight; jj++ ) { int kk; for( kk = 0; kk < components; kk++ ) { @@ -577,7 +577,7 @@ public class HalveImage { } assert( dest == ( components * element_size * halfWidth * halfHeight ) ); } - + public static void halveImage_uint( int components, int width, int height, ByteBuffer datain, IntBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { @@ -586,7 +586,7 @@ public class HalveImage { int s = 0; int t = 0; double temp = 0; - + // handle case where there is only 1 column/row if( width == 1 || height == 1 ) { assert( !( width == 1 && height == 1 ) ); // can't be 1x1 @@ -594,10 +594,10 @@ public class HalveImage { ysize, group_size, myswap_bytes ); return; } - + newwidth = width / 2; newheight = height / 2; - + // Piece of cake if( !myswap_bytes ) { for( i = 0; i < newheight; i++ ) { @@ -643,7 +643,7 @@ public class HalveImage { } } } - + public static void halve1Dimage_uint( int components, int width, int height, ByteBuffer datain, IntBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { @@ -652,14 +652,14 @@ public class HalveImage { int src = 0; int dest = 0; int jj; - + assert( width == 1 || height == 1 ); // must be 1D assert( width != height ); // can't be square - + if( height == 1 ) { // 1 row assert( width != 1 ); // widthxheight can't be 1 halfHeight = 1; - + for( jj = 0; jj < halfWidth; jj++ ) { int kk; for( kk = 0; kk < halfHeight; kk++ ) { @@ -689,7 +689,7 @@ public class HalveImage { halfWidth = 1; // one vertical column with possible pad bytes per row // average two at a time - + for( jj = 0; jj < halfHeight; jj++ ) { int kk; for( kk = 0; kk < components; kk++ ) { @@ -716,7 +716,7 @@ public class HalveImage { } assert( dest == components * element_size * halfWidth * halfHeight ); } - + public static void halveImage_int( int components, int width, int height, ByteBuffer datain, IntBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { @@ -725,7 +725,7 @@ public class HalveImage { int s = 0; int t = 0; int temp = 0; - + // handle case where there is only 1 column/row if( width == 1 || height == 1 ) { assert( !( width == 1 && height == 1 ) ); // can't be 1x1 @@ -733,10 +733,10 @@ public class HalveImage { ysize, group_size, myswap_bytes ); return; } - + newwidth = width / 2; newheight = height / 2; - + // Piece of cake if( !myswap_bytes ) { for( i = 0; i < newheight; i++ ) { @@ -785,7 +785,7 @@ public class HalveImage { } } } - + public static void halve1Dimage_int( int components, int width, int height, ByteBuffer datain, IntBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { @@ -794,14 +794,14 @@ public class HalveImage { int src = 0; int dest = 0; int jj; - + assert( width == 1 || height == 1 ); // must be 1D assert( width != height ); // can't be square - + if( height == 1 ) { // 1 row assert( width != 1 ); // can't be 1x1 halfHeight = 1; - + for( jj = 0; jj < halfWidth; jj++ ) { int kk; for( kk = 0; kk < components; kk++ ) { @@ -831,7 +831,7 @@ public class HalveImage { halfWidth = 1; // one vertical column with possible pad bytes per row // average two at a time - + for( jj = 0; jj < halfHeight; jj++ ) { int kk; for( kk = 0; kk < components; kk++ ) { @@ -858,7 +858,7 @@ public class HalveImage { } assert( dest == ( components * element_size * halfWidth * halfHeight ) ); } - + public static void halveImage_float( int components, int width, int height, ByteBuffer datain, FloatBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { @@ -874,10 +874,10 @@ public class HalveImage { ysize, group_size, myswap_bytes ); return; } - + newwidth = width / 2; newheight = height / 2; - + // Piece of cake if( !myswap_bytes ) { for( i = 0; i < newheight; i++ ) { @@ -920,7 +920,7 @@ public class HalveImage { } } } - + public static void halve1Dimage_float( int components, int width, int height, ByteBuffer datain, FloatBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { @@ -929,14 +929,14 @@ public class HalveImage { int src = 0; int dest = 0; int jj; - + assert( width == 1 || height == 1 ); // must be 1D assert( width != height ); // can't be square - + if( height == 1 ) { // 1 row assert( width != 1 ); // can't be 1x1 halfHeight = 1; - + for( jj = 0; jj < halfWidth; jj++ ) { int kk; for( kk = 0; kk < components; kk++ ) { @@ -966,7 +966,7 @@ public class HalveImage { halfWidth = 1; // one vertical column with possible pad bytes per row // average two at a time - + for( jj = 0; jj < halfHeight; jj++ ) { int kk; for( kk = 0; kk < components; kk++ ) { @@ -993,9 +993,9 @@ public class HalveImage { } assert( dest == ( components * element_size * halfWidth * halfHeight ) ); } - - public static void halveImagePackedPixel( int components, Extract extract, int width, - int height, ByteBuffer datain, ByteBuffer dataout, + + public static void halveImagePackedPixel( int components, Extract extract, int width, + int height, ByteBuffer datain, ByteBuffer dataout, int pixelSizeInBytes, int rowSizeInBytes, boolean isSwap ) { if( width == 1 || height == 1 ) { assert( !( width == 1 && height == 1 ) ); @@ -1004,19 +1004,19 @@ public class HalveImage { return; } int ii, jj; - + int halfWidth = width / 2; int halfHeight = height / 2; int src = 0; int padBytes = rowSizeInBytes - ( width * pixelSizeInBytes ); int outIndex = 0; - + for( ii = 0; ii < halfHeight; ii++ ) { for( jj = 0; jj < halfWidth; jj++ ) { float totals[] = new float[4]; float extractTotals[][] = new float[BOX4][4]; int cc; - + datain.position( src ); extract.extract( isSwap, datain, extractTotals[0] ); datain.position( src + pixelSizeInBytes ); @@ -1045,7 +1045,7 @@ public class HalveImage { assert( src == rowSizeInBytes * height ); assert( outIndex == halfWidth * halfHeight ); } - + public static void halve1DimagePackedPixel( int components, Extract extract, int width, int height, ByteBuffer datain, ByteBuffer dataout, int pixelSizeInBytes, int rowSizeInBytes, boolean isSwap ) { @@ -1053,23 +1053,23 @@ public class HalveImage { int halfHeight = height / 2; int src = 0; int jj; - + assert( width == 1 || height == 1 ); assert( width != height ); - + if( height == 1 ) { int outIndex = 0; - + assert( width != 1 ); halfHeight = 1; - + // one horizontal row with possible pad bytes - + for( jj = 0; jj < halfWidth; jj++ ) { float[] totals = new float[4]; float[][] extractTotals = new float[BOX2][4]; int cc; - + datain.position( src ); extract.extract( isSwap, datain, extractTotals[0] ); datain.position( src + pixelSizeInBytes ); @@ -1090,17 +1090,17 @@ public class HalveImage { } int padBytes = rowSizeInBytes - ( width * pixelSizeInBytes ); src += padBytes; - + assert( src == rowSizeInBytes ); assert( outIndex == halfWidth * halfHeight ); } else if( width == 1 ) { int outIndex = 0; - + assert( height != 1 ); halfWidth = 1; // one vertical volumn with possible pad bytes per row // average two at a time - + for( jj = 0; jj < halfHeight; jj++ ) { float[] totals = new float[4]; float[][] extractTotals = new float[BOX2][4]; @@ -1128,7 +1128,7 @@ public class HalveImage { assert( outIndex == halfWidth * halfHeight ); } } - + public static void halveImagePackedPixelSlice( int components, Extract extract, int width, int height, int depth, ByteBuffer dataIn, ByteBuffer dataOut, int pixelSizeInBytes, int rowSizeInBytes, @@ -1140,26 +1140,26 @@ public class HalveImage { int src = 0; int padBytes = rowSizeInBytes - ( width * pixelSizeInBytes ); int outIndex = 0; - + assert( (width == 1 || height == 1) && depth >= 2 ); - + if( width == height ) { assert( width == 1 && height == 1 ); assert( depth >= 2 ); - + for( ii = 0; ii < halfDepth; ii++ ) { float totals[] = new float[4]; float extractTotals[][] = new float[BOX2][4]; int cc; - + dataIn.position( src ); extract.extract( isSwap, dataIn, extractTotals[0] ); dataIn.position( src + imageSizeInBytes ); extract.extract( isSwap, dataIn, extractTotals[1] ); - + for( cc = 0; cc < components; cc++ ) { int kk; - + // average only 2 pixels since a column totals[cc]= 0.0f; for( kk = 0; kk < BOX2; kk++ ) { @@ -1167,7 +1167,7 @@ public class HalveImage { } totals[cc] /= BOX2; } // for cc - + extract.shove( totals, outIndex, dataOut ); outIndex++; // skip over to next group of 2 @@ -1175,13 +1175,13 @@ public class HalveImage { } // for ii } else if( height == 1 ) { assert( width != 1 ); - + for( ii = 0; ii < halfDepth; ii++ ) { for( jj = 0; jj < halfWidth; jj++ ) { float totals[] = new float[4]; float extractTotals[][] = new float[BOX4][4]; int cc; - + dataIn.position( src ); extract.extract( isSwap, dataIn, extractTotals[0] ); dataIn.position( src + pixelSizeInBytes ); @@ -1190,10 +1190,10 @@ public class HalveImage { extract.extract( isSwap, dataIn, extractTotals[2] ); dataIn.position( src + pixelSizeInBytes + imageSizeInBytes ); extract.extract( isSwap, dataIn, extractTotals[3] ); - + for( cc = 0; cc < components; cc++ ) { int kk; - + // grab 4 pixels to average totals[cc] = 0.0f; for( kk = 0; kk < BOX4; kk++ ) { @@ -1209,13 +1209,13 @@ public class HalveImage { } } else if( width == 1 ) { assert( height != 1 ); - + for( ii = 0; ii < halfDepth; ii++ ) { for( jj = 0; jj < halfWidth; jj++ ) { float totals[] = new float[4]; float extractTotals[][] = new float[BOX4][4]; int cc; - + dataIn.position( src ); extract.extract( isSwap, dataIn, extractTotals[0] ); dataIn.position( src + rowSizeInBytes ); @@ -1224,10 +1224,10 @@ public class HalveImage { extract.extract( isSwap, dataIn, extractTotals[2] ); dataIn.position( src + rowSizeInBytes + imageSizeInBytes ); extract.extract( isSwap, dataIn, extractTotals[3] ); - + for( cc = 0; cc < components; cc++ ) { int kk; - + // grab 4 pixels to average totals[cc] = 0.0f; for( kk = 0; kk < BOX4; kk++ ) { @@ -1243,7 +1243,7 @@ public class HalveImage { } } } - + public static void halveImageSlice( int components, ExtractPrimitive extract, int width, int height, int depth, ByteBuffer dataIn, ByteBuffer dataOut, int elementSizeInBytes, int groupSizeInBytes, int rowSizeInBytes, @@ -1255,25 +1255,25 @@ public class HalveImage { int src = 0; int padBytes = rowSizeInBytes - ( width * groupSizeInBytes ); int outIndex = 0; - + assert( (width == 1 || height == 1) && depth >= 2 ); - + if( width == height ) { assert( width == 1 && height == 1 ); assert( depth >= 2 ); - + for( ii = 0; ii < halfDepth; ii++ ) { int cc; for( cc = 0; cc < components; cc++ ) { double[] totals = new double[4]; double[][] extractTotals = new double[BOX2][4]; int kk; - + dataIn.position( src ); extractTotals[0][cc] = extract.extract( isSwap, dataIn ); dataIn.position( src + imageSizeInBytes ); extractTotals[1][cc] = extract.extract( isSwap, dataIn ); - + // average 2 pixels since only a column totals[cc] = 0.0f; // totals[red] = extractTotals[0][red] + extractTotals[1][red]; @@ -1282,7 +1282,7 @@ public class HalveImage { totals[cc] += extractTotals[kk][cc]; } totals[cc] /= (double)BOX2; - + extract.shove( totals[cc], outIndex, dataOut ); outIndex++; src += elementSizeInBytes; @@ -1290,12 +1290,12 @@ public class HalveImage { // skip over next group of 2 src += rowSizeInBytes; } // for ii - + assert( src == rowSizeInBytes * height * depth ); assert( outIndex == halfDepth * components ); } else if( height == 1 ) { assert( width != 1 ); - + for( ii = 0; ii < halfDepth; ii++ ) { for( jj = 0; jj < halfWidth; jj++ ) { int cc; @@ -1303,7 +1303,7 @@ public class HalveImage { int kk; double totals[] = new double[4]; double extractTotals[][] = new double[BOX4][4]; - + dataIn.position( src ); extractTotals[0][cc] = extract.extract( isSwap, dataIn ); dataIn.position( src + groupSizeInBytes ); @@ -1312,7 +1312,7 @@ public class HalveImage { extractTotals[2][cc] = extract.extract( isSwap, dataIn ); dataIn.position( src + imageSizeInBytes + groupSizeInBytes ); extractTotals[3][cc] = extract.extract( isSwap, dataIn ); - + // grab 4 pixels to average totals[cc] = 0.0f; // totals[red] = extractTotals[0][red] + extractTotals[1][red] + @@ -1322,7 +1322,7 @@ public class HalveImage { totals[cc] += extractTotals[kk][cc]; } totals[cc] /= (double)BOX4; - + extract.shove( totals[cc], outIndex, dataOut ); outIndex++; src += elementSizeInBytes; @@ -1337,7 +1337,7 @@ public class HalveImage { assert( outIndex == halfWidth * halfDepth * components ); } else if( width == 1 ) { assert( height != 1 ); - + for( ii = 0; ii < halfDepth; ii++ ) { for( jj = 0; jj < halfHeight; jj++ ) { int cc; @@ -1345,7 +1345,7 @@ public class HalveImage { int kk; double totals[] = new double[4]; double extractTotals[][] = new double[BOX4][4]; - + dataIn.position( src ); extractTotals[0][cc] = extract.extract( isSwap, dataIn ); dataIn.position( src + rowSizeInBytes ); @@ -1354,8 +1354,8 @@ public class HalveImage { extractTotals[2][cc] = extract.extract( isSwap, dataIn ); dataIn.position( src + imageSizeInBytes + groupSizeInBytes ); extractTotals[3][cc] = extract.extract( isSwap, dataIn ); - - + + // grab 4 pixels to average totals[cc] = 0.0f; // totals[red] = extractTotals[0][red] + extractTotals[1][red] + @@ -1365,7 +1365,7 @@ public class HalveImage { totals[cc] += extractTotals[kk][cc]; } totals[cc] /= (double)BOX4; - + extract.shove( totals[cc], outIndex, dataOut ); outIndex++; src += elementSizeInBytes; @@ -1380,32 +1380,32 @@ public class HalveImage { assert( outIndex == halfWidth * halfDepth * components ); } } - + public static void halveImage3D( int components, ExtractPrimitive extract, int width, int height, int depth, ByteBuffer dataIn, ByteBuffer dataOut, int elementSizeInBytes, int groupSizeInBytes, int rowSizeInBytes, int imageSizeInBytes, boolean isSwap ) { assert( depth > 1 ); - + // horizontal/vertical/onecolumn slice viewed from top if( width == 1 || height == 1 ) { assert( 1 <= depth ); - + halveImageSlice( components, extract, width, height, depth, dataIn, dataOut, elementSizeInBytes, groupSizeInBytes, rowSizeInBytes, imageSizeInBytes, isSwap ); return; } - + int ii, jj, dd; - + int halfWidth = width / 2; int halfHeight = height / 2; int halfDepth = depth / 2; int src = 0; int padBytes = rowSizeInBytes - ( width * groupSizeInBytes ); int outIndex = 0; - + for( dd = 0; dd < halfDepth; dd++ ) { for( ii = 0; ii < halfHeight; ii++ ) { for( jj = 0; jj < halfWidth; jj++ ) { @@ -1414,7 +1414,7 @@ public class HalveImage { int kk; double totals[] = new double[4]; double extractTotals[][] = new double[BOX8][4]; - + dataIn.position( src ); extractTotals[0][cc] = extract.extract( isSwap, dataIn ); dataIn.position( src + groupSizeInBytes ); @@ -1431,17 +1431,17 @@ public class HalveImage { extractTotals[6][cc] = extract.extract( isSwap, dataIn ); dataIn.position( src + rowSizeInBytes + imageSizeInBytes + groupSizeInBytes ); extractTotals[7][cc] = extract.extract( isSwap, dataIn ); - + totals[cc] = 0.0f; - + for( kk = 0; kk < BOX8; kk++ ) { totals[cc] += extractTotals[kk][cc]; } totals[cc] /= (double)BOX8; - + extract.shove( totals[cc], outIndex, dataOut ); outIndex++; - + src += elementSizeInBytes; } // for cc // skip over to next square of 4 @@ -1456,40 +1456,40 @@ public class HalveImage { assert( src == rowSizeInBytes * height * depth ); assert( outIndex == halfWidth * halfHeight * halfDepth * components ); } - + public static void halveImagePackedPixel3D( int components, Extract extract, - int width, int height, int depth, ByteBuffer dataIn, + int width, int height, int depth, ByteBuffer dataIn, ByteBuffer dataOut, int pixelSizeInBytes, int rowSizeInBytes, int imageSizeInBytes, boolean isSwap ) { if( depth == 1 ) { assert( 1 <= width && 1 <= height ); - + halveImagePackedPixel( components, extract, width, height, dataIn, dataOut, pixelSizeInBytes, rowSizeInBytes, isSwap ); return; } else if( width == 1 || height == 1 ) { // a horizontal or vertical slice viewed from top assert( 1 <= depth ); - + halveImagePackedPixelSlice( components, extract, width, height, depth, dataIn, dataOut, pixelSizeInBytes, rowSizeInBytes, imageSizeInBytes, isSwap ); return; } int ii, jj, dd; - + int halfWidth = width / 2; int halfHeight = height / 2; int halfDepth = depth / 2; int src = 0; int padBytes = rowSizeInBytes - ( width * pixelSizeInBytes ); int outIndex = 0; - + for( dd = 0; dd < halfDepth; dd++ ) { for( ii = 0; ii < halfHeight; ii++ ) { for( jj = 0; jj < halfWidth; jj++ ) { float totals[] = new float[4]; // 4 is max components float extractTotals[][] = new float[BOX8][4]; int cc; - + dataIn.position( src ); extract.extract( isSwap, dataIn, extractTotals[0] ); dataIn.position( src + pixelSizeInBytes ); @@ -1506,7 +1506,7 @@ public class HalveImage { extract.extract( isSwap, dataIn, extractTotals[6] ); dataIn.position( src + rowSizeInBytes + pixelSizeInBytes + imageSizeInBytes ); extract.extract( isSwap, dataIn, extractTotals[7] ); - + for( cc = 0; cc < components; cc++ ) { int kk; // grab 8 pixels to average diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Image.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Image.java index b610ce86b..18f814dde 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Image.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Image.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -53,18 +53,18 @@ import java.nio.*; * @author Administrator */ public class Image { - + /** Creates a new instance of Image */ public Image() { } - + public static short getShortFromByteArray( byte[] array, int index ) { short s; s = (short)(array[index] << 8 ); s |= (short)(0x00FF & array[index+1]); return( s ); } - + public static int getIntFromByteArray( byte[] array, int index ) { int i; i = ( array[index] << 24 ) & 0xFF000000; @@ -73,12 +73,12 @@ public class Image { i |= ( array[index+3] ) & 0x000000FF; return( i ); } - + public static float getFloatFromByteArray( byte[] array, int index ) { int i = getIntFromByteArray( array, index ); return( Float.intBitsToFloat(i) ); } - + /* * Extract array from user's data applying all pixel store modes. * The internal format used is an array of unsigned shorts. @@ -98,7 +98,7 @@ public class Image { int iter2; int i, j, k; boolean myswap_bytes; - + // Create a Extract interface object Extract extract = null; switch( type ) { @@ -139,7 +139,7 @@ public class Image { extract = new Extract2101010rev(); break; } - + myswap_bytes = psm.getUnpackSwapBytes(); components = Mipmap.elements_per_group( format, type ); if( psm.getUnpackRowLength() > 0 ) { @@ -147,12 +147,12 @@ public class Image { } else { groups_per_line = width; } - + // All formats except GL_BITMAP fall out trivially if( type == GL2.GL_BITMAP ) { int bit_offset; int current_bit; - + rowsize = ( groups_per_line * components + 7 ) / 8; padding = ( rowsize % psm.getUnpackAlignment() ); if( padding != 0 ) { @@ -200,7 +200,7 @@ public class Image { if( element_size == 1 ) { myswap_bytes = false; } - + rowsize = groups_per_line * group_size; padding = ( rowsize % psm.getUnpackAlignment() ); if( padding != 0 ) { @@ -208,7 +208,7 @@ public class Image { } start = psm.getUnpackSkipRows() * rowsize + psm.getUnpackSkipPixels() * group_size; elements_per_line = width * components; - + iter2 = 0; for( i = 0; i < height; i++ ) { iter = start; @@ -364,7 +364,7 @@ public class Image { // want iter pointing at start, not within, row for assertion purposes iter = start; } // for i - + // iterators should be one byte past end if( !Mipmap.isTypePackedPixel( type ) ) { assert( iter2 == ( width * height * components ) ); @@ -374,16 +374,16 @@ public class Image { assert( iter == ( rowsize * height + psm.getUnpackSkipRows() * rowsize + psm.getUnpackSkipPixels() * group_size ) ); } } - + /* * Insert array into user's data applying all pixel store modes. * Theinternal format is an array of unsigned shorts. * empty_image() because it is the opposet of fill_image(). */ - public static void empty_image( PixelStorageModes psm, int width, int height, - int format, int type, boolean index_format, + public static void empty_image( PixelStorageModes psm, int width, int height, + int format, int type, boolean index_format, ShortBuffer oldimage, ByteBuffer userdata ) { - + int components; int element_size; int rowsize; @@ -396,7 +396,7 @@ public class Image { int iter2; int i, j, k; boolean myswap_bytes; - + // Create a Extract interface object Extract extract = null; switch( type ) { @@ -437,7 +437,7 @@ public class Image { extract = new Extract2101010rev(); break; } - + myswap_bytes = psm.getPackSwapBytes(); components = Mipmap.elements_per_group( format, type ); if( psm.getPackRowLength() > 0 ) { @@ -445,12 +445,12 @@ public class Image { } else { groups_per_line = width; } - + // all formats except GL_BITMAP fall out trivially if( type == GL2.GL_BITMAP ) { int bit_offset; int current_bit; - + rowsize = ( groups_per_line * components + 7 ) / 8; padding = ( rowsize % psm.getPackAlignment() ); if( padding != 0 ) { @@ -472,7 +472,7 @@ public class Image { current_bit = 0; } } - + if( current_bit != 0 ) { if( psm.getPackLsbFirst() ) { userdata.put( iter, (byte)( ( userdata.get( iter ) | ( 1 << bit_offset ) ) ) ); @@ -488,7 +488,7 @@ public class Image { userdata.put( iter, (byte)( ( userdata.get( iter ) & ~( 7 - bit_offset ) ) ) ); } } - + bit_offset++; if( bit_offset == 8 ) { bit_offset = 0; @@ -500,13 +500,13 @@ public class Image { } } else { float shoveComponents[] = new float[4]; - + element_size = Mipmap.bytes_per_element( type ); group_size = element_size * components; if( element_size == 1 ) { myswap_bytes = false; } - + rowsize = groups_per_line * group_size; padding = ( rowsize % psm.getPackAlignment() ); if( padding != 0 ) { @@ -514,13 +514,13 @@ public class Image { } start = psm.getPackSkipRows() * rowsize + psm.getPackSkipPixels() * group_size; elements_per_line = width * components; - + iter2 = 0; for( i = 0; i < height; i++ ) { iter = start; for( j = 0; j < elements_per_line; j++ ) { Type_Widget widget = new Type_Widget(); - + switch( type ) { case( GL2.GL_UNSIGNED_BYTE_3_3_2 ): for( k = 0; k < 3; k++ ) { @@ -799,7 +799,7 @@ public class Image { assert( iter == rowsize * height + psm.getPackSkipRows() * rowsize + psm.getPackSkipPixels() * group_size ); } } - + public static void fillImage3D( PixelStorageModes psm, int width, int height, int depth, int format, int type, boolean indexFormat, ByteBuffer userImage, ShortBuffer newImage ) { @@ -819,7 +819,7 @@ public class Image { int ww, hh, dd, k; Type_Widget widget = new Type_Widget(); float extractComponents[] = new float[4]; - + // Create a Extract interface object Extract extract = null; switch( type ) { @@ -860,7 +860,7 @@ public class Image { extract = new Extract2101010rev(); break; } - + myswapBytes = psm.getUnpackSwapBytes(); components = Mipmap.elements_per_group( format, type ); if( psm.getUnpackRowLength() > 0 ) { @@ -873,7 +873,7 @@ public class Image { if( elementSize == 1 ) { myswapBytes = false; } - + // 3dstuff begin if( psm.getUnpackImageHeight() > 0 ) { rowsPerImage = psm.getUnpackImageHeight(); @@ -881,27 +881,27 @@ public class Image { rowsPerImage = height; } // 3dstuff end - + rowSize = groupsPerLine * groupSize; padding = rowSize % psm.getUnpackAlignment(); if( padding != 0 ) { rowSize += psm.getUnpackAlignment() - padding; } - + imageSize = rowsPerImage * rowSize; // 3dstuff - - start = psm.getUnpackSkipRows() * rowSize + - psm.getUnpackSkipPixels() * groupSize + + + start = psm.getUnpackSkipRows() * rowSize + + psm.getUnpackSkipPixels() * groupSize + psm.getUnpackSkipImages() * imageSize; elementsPerLine = width * components; - + iter2 = 0; for( dd = 0; dd < depth; dd++ ) { rowStart = start; for( hh = 0; hh < height; hh++ ) { iter = rowStart; for( ww = 0; ww < elementsPerLine; ww++ ) { - + switch( type ) { case( GL2.GL_UNSIGNED_BYTE ): if( indexFormat ) { @@ -1063,18 +1063,18 @@ public class Image { } // for hh start += imageSize; }// for dd - + // iterators should be one byte past end if( !Mipmap.isTypePackedPixel( type ) ) { assert( iter2 == width * height * depth * components ); } else { assert( iter2 == width * height * depth * Mipmap.elements_per_group( format, 0 ) ); } - assert( iter == rowSize * height * depth + psm.getUnpackSkipRows() * rowSize + + assert( iter == rowSize * height * depth + psm.getUnpackSkipRows() * rowSize + psm.getUnpackSkipPixels() * groupSize + psm.getUnpackSkipImages() * imageSize ); } - + public static void emptyImage3D( PixelStorageModes psm, int width, int height, int depth, int format, int type, boolean indexFormat, ShortBuffer oldImage, ByteBuffer userImage ) { boolean myswapBytes; @@ -1092,7 +1092,7 @@ public class Image { int imageSize; Type_Widget widget = new Type_Widget(); float[] shoveComponents = new float[4]; - + // Create a Extract interface object Extract extract = null; switch( type ) { @@ -1133,9 +1133,9 @@ public class Image { extract = new Extract2101010rev(); break; } - + iter = 0; - + myswapBytes = psm.getPackSwapBytes(); components = Mipmap.elements_per_group( format, type ); if( psm.getPackRowLength() > 0 ) { @@ -1143,44 +1143,44 @@ public class Image { } else { groupsPerLine = width; } - + elementSize = Mipmap.bytes_per_element( type ); groupSize = elementSize * components; if( elementSize == 1 ) { myswapBytes = false; } - + // 3dstuff begin if( psm.getPackImageHeight() > 0 ) { rowsPerImage = psm.getPackImageHeight(); } else { rowsPerImage = height; } - + // 3dstuff end - + rowSize = groupsPerLine * groupSize; padding = rowSize % psm.getPackAlignment(); if( padding != 0 ) { rowSize += psm.getPackAlignment() - padding; } - + imageSize = rowsPerImage * rowSize; - + start = psm.getPackSkipRows() * rowSize + psm.getPackSkipPixels() * groupSize + psm.getPackSkipImages() * imageSize; elementsPerLine = width * components; - + iter2 = 0; for( dd = 0; dd < depth; dd++ ) { rowStart = start; - + for( ii = 0; ii < height; ii++ ) { iter = rowStart; - + for( jj = 0; jj < elementsPerLine; jj++ ) { - + switch( type ) { case( GL2.GL_UNSIGNED_BYTE ): if( indexFormat ) { @@ -1392,20 +1392,20 @@ public class Image { default: assert( false ); } - + iter += elementSize; } // for jj rowStart += rowSize; } // for ii start += imageSize; } // for dd - + if( !Mipmap.isTypePackedPixel( type ) ) { assert( iter2 == width * height * depth * components ); } else { assert( iter2 == width * height * depth * Mipmap.elements_per_group( format, 0 ) ); } - assert( iter == rowSize * height * depth + + assert( iter == rowSize * height * depth + psm.getUnpackSkipRows() * rowSize + psm.getUnpackSkipPixels() * groupSize + psm.getUnpackSkipImages() * imageSize ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Mipmap.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Mipmap.java index b74d0a6b8..938873ec5 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Mipmap.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Mipmap.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -57,11 +57,11 @@ import com.jogamp.common.nio.Buffers; * @author Administrator */ public class Mipmap { - + /** Creates a new instance of Mipmap */ public Mipmap() { } - + public static int computeLog( int value ) { int i = 0; // Error @@ -79,7 +79,7 @@ public class Mipmap { i++; } } - + /* Compute the nearest power of 2 number. This algorithm is a little strange * but it works quite well. */ @@ -99,7 +99,7 @@ public class Mipmap { i *= 2; } } - + public static short GLU_SWAP_2_BYTES( short s ) { byte b = 0; b = (byte)( s >>> 8 ); @@ -107,7 +107,7 @@ public class Mipmap { s = (short)( s | (0x00FF & b) ); return( s ); } - + public static int GLU_SWAP_4_BYTES( int i ) { int t = i << 24; t |= 0x00FF0000 & ( i << 8 ); @@ -115,13 +115,13 @@ public class Mipmap { t |= 0x000000FF & ( i >>> 24 ); return( t ); } - + public static float GLU_SWAP_4_BYTES( float f ) { int i = Float.floatToRawIntBits( f ); float temp = Float.intBitsToFloat( i ); return( temp ); } - + public static int checkMipmapArgs( int internalFormat, int format, int type ) { if( !legalFormat( format ) || !legalType( type ) ) { return( GLU.GLU_INVALID_ENUM ); @@ -134,7 +134,7 @@ public class Mipmap { } return( 0 ); } - + public static boolean legalFormat( int format ) { switch( format ) { case( GL2.GL_COLOR_INDEX ): @@ -155,7 +155,7 @@ public class Mipmap { return( false ); } } - + public static boolean legalType( int type ) { switch( type ) { case( GL2.GL_BITMAP ): @@ -183,10 +183,10 @@ public class Mipmap { return( false ); } } - + public static boolean isTypePackedPixel( int type ) { assert( legalType( type ) ); - + if( type == GL2GL3.GL_UNSIGNED_BYTE_3_3_2 || type == GL2GL3.GL_UNSIGNED_BYTE_2_3_3_REV || type == GL2GL3.GL_UNSIGNED_SHORT_5_6_5 || @@ -203,20 +203,20 @@ public class Mipmap { } return( false ); } - + public static boolean isLegalFormatForPackedPixelType( int format, int type ) { // if not a packed pixel type then return true if( isTypePackedPixel( type ) ) { return( true ); } - + // 3_3_2/2_3_3_REV & 5_6_5/5_6_5_REV are only compatible with RGB if( (type == GL2GL3.GL_UNSIGNED_BYTE_3_3_2 || type == GL2GL3.GL_UNSIGNED_BYTE_2_3_3_REV || type == GL2GL3.GL_UNSIGNED_SHORT_5_6_5 || type == GL2GL3.GL_UNSIGNED_SHORT_5_6_5_REV ) & format != GL2GL3.GL_RGB ) { return( false ); } - + // 4_4_4_4/4_4_4_4_REV & 5_5_5_1/1_5_5_5_REV & 8_8_8_8/8_8_8_8_REV & // 10_10_10_2/2_10_10_10_REV are only campatible with RGBA, BGRA & ARGB_EXT if( ( type == GL2GL3.GL_UNSIGNED_SHORT_4_4_4_4 || @@ -232,7 +232,7 @@ public class Mipmap { } return( true ); } - + public static boolean isLegalLevels( int userLevel, int baseLevel, int maxLevel, int totalLevels ) { if( (baseLevel < 0) || (baseLevel < userLevel) || (maxLevel < baseLevel) || @@ -241,7 +241,7 @@ public class Mipmap { } return( true ); } - + /* Given user requested textures size, determine if it fits. If it doesn't then * halve both sides and make the determination again until it does fit ( for * IR only ). @@ -257,7 +257,7 @@ public class Mipmap { int heightPowerOf2 = nearestPower( height ); int[] proxyWidth = new int[1]; boolean noProxyTextures = false; - + // Some drivers (in particular, ATI's) seem to set a GL error // when proxy textures are used even though this is in violation // of the spec. Guard against this and interactions with the @@ -268,20 +268,20 @@ public class Mipmap { int widthAtLevelOne = ( ( width > 1 ) ? (widthPowerOf2 >> 1) : widthPowerOf2 ); int heightAtLevelOne = ( ( height > 1 ) ? (heightPowerOf2 >> 1) : heightPowerOf2 ); int proxyTarget; - + assert( widthAtLevelOne > 0 ); assert( heightAtLevelOne > 0 ); - + // does width x height at level 1 & all their mipmaps fit? if( target == GL2GL3.GL_TEXTURE_2D || target == GL2GL3.GL_PROXY_TEXTURE_2D ) { proxyTarget = GL2GL3.GL_PROXY_TEXTURE_2D; gl.glTexImage2D( proxyTarget, 1, internalFormat, widthAtLevelOne, heightAtLevelOne, 0, format, type, null ); - } else if( (target == GL2GL3.GL_TEXTURE_CUBE_MAP_POSITIVE_X) || - (target == GL2GL3.GL_TEXTURE_CUBE_MAP_NEGATIVE_X) || - (target == GL2GL3.GL_TEXTURE_CUBE_MAP_POSITIVE_Y) || - (target == GL2GL3.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) || - (target == GL2GL3.GL_TEXTURE_CUBE_MAP_POSITIVE_Z) || + } else if( (target == GL2GL3.GL_TEXTURE_CUBE_MAP_POSITIVE_X) || + (target == GL2GL3.GL_TEXTURE_CUBE_MAP_NEGATIVE_X) || + (target == GL2GL3.GL_TEXTURE_CUBE_MAP_POSITIVE_Y) || + (target == GL2GL3.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) || + (target == GL2GL3.GL_TEXTURE_CUBE_MAP_POSITIVE_Z) || (target == GL2GL3.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) ) { proxyTarget = GL2GL3.GL_PROXY_TEXTURE_CUBE_MAP; gl.glTexImage2D( proxyTarget, 1, internalFormat, widthAtLevelOne, @@ -289,7 +289,7 @@ public class Mipmap { } else { assert( target == GL2GL3.GL_TEXTURE_1D || target == GL2GL3.GL_PROXY_TEXTURE_1D ); proxyTarget = GL2GL3.GL_PROXY_TEXTURE_1D; - gl.getGL2GL3().glTexImage1D( proxyTarget, 1, internalFormat, widthAtLevelOne, + gl.getGL2GL3().glTexImage1D( proxyTarget, 1, internalFormat, widthAtLevelOne, 0, format, type, null ); } if(gl.isGL2GL3()) { @@ -336,15 +336,15 @@ public class Mipmap { newHeight[0] = maxsize[0]; } } - - public static void closestFit3D( GL gl, int target, int width, int height, int depth, + + public static void closestFit3D( GL gl, int target, int width, int height, int depth, int internalFormat, int format, int type, int[] newWidth, int[] newHeight, int[] newDepth ) { int widthPowerOf2 = nearestPower( width ); int heightPowerOf2 = nearestPower( height ); int depthPowerOf2 = nearestPower( depth ); int[] proxyWidth = new int[1]; - + do { // compute level 1 width & height & depth, clamping each at 1 int widthAtLevelOne = (widthPowerOf2 > 1) ? widthPowerOf2 >> 1 : widthPowerOf2; @@ -354,7 +354,7 @@ public class Mipmap { assert( widthAtLevelOne > 0 ); assert( heightAtLevelOne > 0 ); assert( depthAtLevelOne > 0 ); - + // does width x height x depth at level 1 & all their mipmaps fit? if( target == GL2GL3.GL_TEXTURE_3D || target == GL2GL3.GL_PROXY_TEXTURE_3D ) { proxyTarget = GL2GL3.GL_PROXY_TEXTURE_3D; @@ -378,16 +378,16 @@ public class Mipmap { } } while( proxyWidth[0] == 0 ); // loop must terminate - + // return the width & height at level 0 that fits newWidth[0] = widthPowerOf2; newHeight[0] = heightPowerOf2; newDepth[0] = depthPowerOf2; } - + public static int elements_per_group( int format, int type ) { // Return the number of elements per grtoup of a specified gromat - + // If the type is packedpixels then answer is 1 if( type == GL2GL3.GL_UNSIGNED_BYTE_3_3_2 || type == GL2GL3.GL_UNSIGNED_BYTE_2_3_3_REV || @@ -403,7 +403,7 @@ public class Mipmap { type == GL2GL3.GL_UNSIGNED_INT_2_10_10_10_REV ) { return( 1 ); } - + // Types are not packed pixels so get elements per group switch( format ) { case( GL2GL3.GL_RGB ): @@ -418,10 +418,10 @@ public class Mipmap { return( 1 ); } } - + public static int bytes_per_element( int type ) { // return the number of bytes per element, based on the element type - + switch( type ) { case( GL2.GL_BITMAP ): case( GL2GL3.GL_BYTE ): @@ -450,17 +450,17 @@ public class Mipmap { return( 4 ); } } - + public static boolean is_index( int format ) { return( format == GL2.GL_COLOR_INDEX || format == GL2GL3.GL_STENCIL_INDEX ); } - + /* Compute memory required for internal packed array of data of given type and format. */ - + public static int image_size( int width, int height, int format, int type ) { int bytes_per_row; int components; - + assert( width > 0 ); assert( height > 0 ); components = elements_per_group( format, type ); @@ -471,17 +471,17 @@ public class Mipmap { } return( bytes_per_row * height * components ); } - + public static int imageSize3D( int width, int height, int depth, int format, int type ) { int components = elements_per_group( format, type ); int bytes_per_row = bytes_per_element( type ) * width; - + assert( width > 0 && height > 0 && depth > 0 ); assert( type != GL2.GL_BITMAP ); - + return( bytes_per_row * height * depth * components ); } - + public static void retrieveStoreModes( GL gl, PixelStorageModes psm ) { int[] a = new int[1]; gl.glGetIntegerv( GL2GL3.GL_UNPACK_ALIGNMENT, a, 0); @@ -496,7 +496,7 @@ public class Mipmap { psm.setUnpackLsbFirst( ( a[0] == 1 ) ); gl.glGetIntegerv( GL2GL3.GL_UNPACK_SWAP_BYTES, a, 0); psm.setUnpackSwapBytes( ( a[0] == 1 ) ); - + gl.glGetIntegerv( GL2GL3.GL_PACK_ALIGNMENT, a, 0); psm.setPackAlignment( a[0] ); gl.glGetIntegerv( GL2GL3.GL_PACK_ROW_LENGTH, a, 0); @@ -510,7 +510,7 @@ public class Mipmap { gl.glGetIntegerv( GL2GL3.GL_PACK_SWAP_BYTES, a, 0); psm.setPackSwapBytes( ( a[0] == 1 ) ); } - + public static void retrieveStoreModes3D( GL gl, PixelStorageModes psm ) { int[] a = new int[1]; gl.glGetIntegerv( GL2GL3.GL_UNPACK_ALIGNMENT, a, 0); @@ -529,7 +529,7 @@ public class Mipmap { psm.setUnpackSkipImages( a[0] ); gl.glGetIntegerv( GL2GL3.GL_UNPACK_IMAGE_HEIGHT, a, 0); psm.setUnpackImageHeight( a[0] ); - + gl.glGetIntegerv( GL2GL3.GL_PACK_ALIGNMENT, a, 0); psm.setPackAlignment( a[0] ); gl.glGetIntegerv( GL2GL3.GL_PACK_ROW_LENGTH, a, 0); @@ -547,9 +547,9 @@ public class Mipmap { gl.glGetIntegerv( GL2GL3.GL_PACK_IMAGE_HEIGHT, a, 0 ); psm.setPackImageHeight( a[0] ); } - - public static int gluScaleImage( GL gl, int format, int widthin, int heightin, - int typein, ByteBuffer datain, int widthout, int heightout, + + public static int gluScaleImage( GL gl, int format, int widthin, int heightin, + int typein, ByteBuffer datain, int widthout, int heightout, int typeout, ByteBuffer dataout ) { int datainPos = datain.position(); int dataoutPos = dataout.position(); @@ -559,7 +559,7 @@ public class Mipmap { ByteBuffer beforeimage; ByteBuffer afterimage; PixelStorageModes psm = new PixelStorageModes(); - + if( (widthin == 0) || (heightin == 0) || (widthout == 0) || (heightout == 0) ) { return( 0 ); } @@ -580,20 +580,20 @@ public class Mipmap { if( beforeimage == null || afterimage == null ) { return( GLU.GLU_OUT_OF_MEMORY ); } - + retrieveStoreModes( gl, psm ); Image.fill_image( psm, widthin, heightin, format, typein, is_index( format ), datain, beforeimage.asShortBuffer() ); components = elements_per_group( format, 0 ); ScaleInternal.scale_internal( components, widthin, heightin, beforeimage.asShortBuffer(), widthout, heightout, afterimage.asShortBuffer() ); Image.empty_image( psm, widthout, heightout, format, typeout, is_index( format ), afterimage.asShortBuffer(), dataout ); - + return( 0 ); } finally { datain.position(datainPos); dataout.position(dataoutPos); } } - + public static int gluBuild1DMipmapLevels( GL gl, int target, int internalFormat, int width, int format, int type, int userLevel, int baseLevel, int maxLevel, ByteBuffer data ) { @@ -601,30 +601,30 @@ public class Mipmap { try { int levels; - + int rc = checkMipmapArgs( internalFormat, format, type ); if( rc != 0 ) { return( rc ); } - + if( width < 1 ) { return( GLU.GLU_INVALID_VALUE ); } - + levels = computeLog( width ); - + levels += userLevel; if( !isLegalLevels( userLevel, baseLevel, maxLevel, levels ) ) { return( GLU.GLU_INVALID_VALUE ); } - + return( BuildMipmap.gluBuild1DMipmapLevelsCore( gl, target, internalFormat, width, width, format, type, userLevel, baseLevel, maxLevel, data ) ); } finally { data.position(dataPos); } } - + public static int gluBuild1DMipmaps( GL gl, int target, int internalFormat, int width, int format, int type, ByteBuffer data ) { int dataPos = data.position(); @@ -633,54 +633,54 @@ public class Mipmap { int[] widthPowerOf2 = new int[1]; int levels; int[] dummy = new int[1]; - + int rc = checkMipmapArgs( internalFormat, format, type ); if( rc != 0 ) { return( rc ); } - + if( width < 1 ) { return( GLU.GLU_INVALID_VALUE ); } - + closestFit( gl, target, width, 1, internalFormat, format, type, widthPowerOf2, dummy ); levels = computeLog( widthPowerOf2[0] ); - - return( BuildMipmap.gluBuild1DMipmapLevelsCore( gl, target, internalFormat, + + return( BuildMipmap.gluBuild1DMipmapLevelsCore( gl, target, internalFormat, width, widthPowerOf2[0], format, type, 0, 0, levels, data ) ); } finally { data.position(dataPos); } } - + public static int gluBuild2DMipmapLevels( GL gl, int target, int internalFormat, int width, int height, int format, int type, int userLevel, int baseLevel, int maxLevel, Object data ) { int dataPos = 0; int level, levels; - + int rc = checkMipmapArgs( internalFormat, format, type ); if( rc != 0 ) { return( rc ); } - + if( width < 1 || height < 1 ) { return( GLU.GLU_INVALID_VALUE ); } - + levels = computeLog( width ); level = computeLog( height ); if( level > levels ) { levels = level; } - + levels += userLevel; if( !isLegalLevels( userLevel, baseLevel, maxLevel, levels ) ) { return( GLU.GLU_INVALID_VALUE ); } - + //PointerWrapper pointer = PointerWrapperFactory.getPointerWrapper( data ); ByteBuffer buffer = null; if( data instanceof ByteBuffer ) { @@ -706,7 +706,7 @@ public class Mipmap { FloatBuffer fb = buffer.asFloatBuffer(); fb.put( array ); } - + try { return( BuildMipmap.gluBuild2DMipmapLevelsCore( gl, target, internalFormat, width, height, width, height, format, type, userLevel, baseLevel, @@ -716,7 +716,7 @@ public class Mipmap { } } - + public static int gluBuild2DMipmaps( GL gl, int target, int internalFormat, int width, int height, int format, int type, Object data ) { int dataPos = 0; @@ -724,25 +724,25 @@ public class Mipmap { int[] widthPowerOf2 = new int[1]; int[] heightPowerOf2 = new int[1]; int level, levels; - + int rc = checkMipmapArgs( internalFormat, format, type ); if( rc != 0 ) { return( rc ); } - + if( width < 1 || height < 1 ) { return( GLU.GLU_INVALID_VALUE ); } - - closestFit( gl, target, width, height, internalFormat, format, type, + + closestFit( gl, target, width, height, internalFormat, format, type, widthPowerOf2, heightPowerOf2 ); - + levels = computeLog( widthPowerOf2[0] ); level = computeLog( heightPowerOf2[0] ); if( level > levels ) { levels = level; } - + //PointerWrapper pointer = PointerWrapperFactory.getPointerWrapper( data ); ByteBuffer buffer = null; if( data instanceof ByteBuffer ) { @@ -768,17 +768,17 @@ public class Mipmap { FloatBuffer fb = buffer.asFloatBuffer(); fb.put( array ); } - + try { - return( BuildMipmap.gluBuild2DMipmapLevelsCore( gl, target, internalFormat, - width, height, widthPowerOf2[0], heightPowerOf2[0], format, type, 0, + return( BuildMipmap.gluBuild2DMipmapLevelsCore( gl, target, internalFormat, + width, height, widthPowerOf2[0], heightPowerOf2[0], format, type, 0, 0, levels, buffer ) ); } finally { buffer.position(dataPos); } } - - + + public static int gluBuild3DMipmaps( GL gl, int target, int internalFormat, int width, int height, int depth, int format, int type, ByteBuffer data ) { int dataPos = data.position(); @@ -788,23 +788,23 @@ public class Mipmap { int[] heightPowerOf2 = new int[1]; int[] depthPowerOf2 = new int[1]; int level, levels; - + int rc = checkMipmapArgs( internalFormat, format, type ); if( rc != 0 ) { return( rc ); } - + if( width < 1 || height < 1 || depth < 1 ) { return( GLU.GLU_INVALID_VALUE ); } - + if( type == GL2.GL_BITMAP ) { return( GLU.GLU_INVALID_ENUM ); } - + closestFit3D( gl, target, width, height, depth, internalFormat, format, type, widthPowerOf2, heightPowerOf2, depthPowerOf2 ); - + levels = computeLog( widthPowerOf2[0] ); level = computeLog( heightPowerOf2[0] ); if( level > levels ) { @@ -814,7 +814,7 @@ public class Mipmap { if( level > levels ) { levels = level; } - + return( BuildMipmap.gluBuild3DMipmapLevelsCore( gl, target, internalFormat, width, height, depth, widthPowerOf2[0], heightPowerOf2[0], depthPowerOf2[0], format, type, 0, 0, levels, data ) ); @@ -822,27 +822,27 @@ public class Mipmap { data.position(dataPos); } } - + public static int gluBuild3DMipmapLevels( GL gl, int target, int internalFormat, int width, int height, int depth, int format, int type, int userLevel, int baseLevel, int maxLevel, ByteBuffer data ) { int dataPos = data.position(); try { int level, levels; - + int rc = checkMipmapArgs( internalFormat, format, type ); if( rc != 0 ) { return( rc ); } - + if( width < 1 || height < 1 || depth < 1 ) { return( GLU.GLU_INVALID_VALUE ); } - + if( type == GL2.GL_BITMAP ) { return( GLU.GLU_INVALID_ENUM ); } - + levels = computeLog( width ); level = computeLog( height ); if( level > levels ) { @@ -852,12 +852,12 @@ public class Mipmap { if( level > levels ) { levels = level; } - + levels += userLevel; if( !isLegalLevels( userLevel, baseLevel, maxLevel, levels ) ) { return( GLU.GLU_INVALID_VALUE ); } - + return( BuildMipmap.gluBuild3DMipmapLevelsCore( gl, target, internalFormat, width, height, depth, width, height, depth, format, type, userLevel, baseLevel, maxLevel, data ) ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/PixelStorageModes.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/PixelStorageModes.java index 0b1af8323..7eb98db35 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/PixelStorageModes.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/PixelStorageModes.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -129,7 +129,7 @@ public class PixelStorageModes { * Holds value of property unpackImageHeight. */ private int unpackImageHeight; - + /** Creates a new instance of PixelStorageModes */ public PixelStorageModes() { } @@ -421,6 +421,6 @@ public class PixelStorageModes { this.unpackImageHeight = unpackImageHeight; } - - + + } diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ScaleInternal.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ScaleInternal.java index 9c95ae304..9aca1fb03 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ScaleInternal.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ScaleInternal.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -55,9 +55,9 @@ import com.jogamp.common.nio.Buffers; * @author Administrator */ public class ScaleInternal { - + public static final float UINT_MAX = (float)(0x00000000FFFFFFFF); - + public static void scale_internal( int components, int widthin, int heightin, ShortBuffer datain, int widthout, int heightout, ShortBuffer dataout ) { float x, lowx, highx, convx, halfconvx; @@ -69,7 +69,7 @@ public class ScaleInternal { float area; int i, j, k, yint, xint, xindex, yindex; int temp; - + if( (widthin == (widthout * 2)) && (heightin == (heightout * 2)) ) { HalveImage.halveImage( components, widthin, heightin, datain, dataout ); return; @@ -101,7 +101,7 @@ public class ScaleInternal { // data. totals[0] = totals[1] = totals[2] = totals[3] = 0.0f; area = 0.0f; - + y = lowy; yint = (int)Math.floor( y ); while( y < highy ) { @@ -111,10 +111,10 @@ public class ScaleInternal { } else { ypercent = yint + 1 - y; } - + x = lowx; xint = (int)Math.floor( x ); - + while( x < highx ) { xindex = ( xint + widthin ) % widthin; if( highx < xint + 1 ) { @@ -122,21 +122,21 @@ public class ScaleInternal { } else { xpercent = xint + 1 - x; } - + percent = xpercent * ypercent; area += percent; temp = ( xindex + ( yindex * widthin) ) * components; for( k = 0; k < components; k++ ) { - totals[k] += datain.get( temp + k ) * percent; + totals[k] += datain.get( temp + k ) * percent; } - + xint++; x = xint; } yint++; y = yint; } - + temp = ( j + ( i * widthout ) ) * components; for( k = 0; k < components; k++ ) { // totals[] should be rounded in the case of enlarging an RGB @@ -146,9 +146,9 @@ public class ScaleInternal { } } } - + public static void scale_internal_ubyte( int components, int widthin, int heightin, - ByteBuffer datain, int widthout, int heightout, + ByteBuffer datain, int widthout, int heightout, ByteBuffer dataout, int element_size, int ysize, int group_size ) { float x, convx; float y, convy; @@ -157,11 +157,11 @@ public class ScaleInternal { float[] totals = new float[4]; float area; int i, j, k, xindex; - + int temp, temp0; int temp_index; int outindex; - + int lowx_int, highx_int, lowy_int, highy_int; float x_percent, y_percent; float lowx_float, highx_float, lowy_float, highy_float; @@ -169,9 +169,9 @@ public class ScaleInternal { int convy_int, convx_int; int l, m; int left, right; - + if( (widthin == (widthout * 2)) && (heightin == (heightout * 2)) ) { - HalveImage.halveImage_ubyte( components, widthin, heightin, datain, dataout, + HalveImage.halveImage_ubyte( components, widthin, heightin, datain, dataout, element_size, ysize, group_size ); return; } @@ -181,14 +181,14 @@ public class ScaleInternal { convy_float = convy - convy_int; convx_int = (int)Math.floor( convx ); convx_float = convx - convx_int; - + area = convx * convy; - + lowy_int = 0; lowy_float = 0.0f; highy_int = convy_int; highy_float = convy_float; - + for( i = 0; i < heightout; i++ ) { // Clamp here to be sure we don't read beyond input buffer. if (highy_int >= heightin) @@ -204,19 +204,19 @@ public class ScaleInternal { highx_int = convx_int; highx_float = convx_float; } - + for( j = 0; j < widthout; j++ ) { - + // Ok, now apply box filter to box that goes from (lowx, lowy) // to (highx, highy) on input data into this pixel on output // data. totals[0] = totals[1] = totals[2] = totals[3] = 0.0f; - + // caulate the value for pixels in the 1st row xindex = lowx_int * group_size; if( ( highy_int > lowy_int ) && ( highx_int > lowx_int ) ) { - + y_percent = 1 - lowy_float; temp = xindex + lowy_int * ysize; percent = y_percent * ( 1 - lowx_float ); @@ -239,7 +239,7 @@ public class ScaleInternal { datain.position( temp_index ); totals[k] += ( 0x000000FF & datain.get() ) * percent; } - + // calculate the value for pixels in the last row y_percent = highy_float; percent = y_percent * ( 1 - lowx_float ); @@ -261,7 +261,7 @@ public class ScaleInternal { datain.position( temp_index ); totals[k] += ( 0x000000FF & datain.get() ) * percent; } - + // calculate the value for the pixels in the 1st and last column for( m = lowy_int + 1; m < highy_int; m++ ) { left += ysize; @@ -339,7 +339,7 @@ public class ScaleInternal { } temp0 += ysize; } - + outindex = ( j + ( i * widthout ) ) * components; for( k = 0; k < components; k++ ) { dataout.position( outindex + k ); @@ -371,9 +371,9 @@ public class ScaleInternal { } } } - + public static void scale_internal_byte( int components, int widthin, int heightin, - ByteBuffer datain, int widthout, int heightout, + ByteBuffer datain, int widthout, int heightout, ByteBuffer dataout, int element_size, int ysize, int group_size ) { float x, convx; @@ -383,11 +383,11 @@ public class ScaleInternal { float[] totals = new float[4]; float area; int i, j, k, xindex; - + int temp, temp0; int temp_index; int outindex; - + int lowx_int, highx_int, lowy_int, highy_int; float x_percent, y_percent; float lowx_float, highx_float, lowy_float, highy_float; @@ -395,9 +395,9 @@ public class ScaleInternal { int convy_int, convx_int; int l, m; int left, right; - + if( (widthin == (widthout * 2)) && (heightin == (heightout * 2)) ) { - HalveImage.halveImage_byte( components, widthin, heightin, datain, dataout, + HalveImage.halveImage_byte( components, widthin, heightin, datain, dataout, element_size, ysize, group_size ); return; } @@ -407,14 +407,14 @@ public class ScaleInternal { convy_float = convy - convy_int; convx_int = (int)Math.floor( convx ); convx_float = convx - convx_int; - + area = convx * convy; - + lowy_int = 0; lowy_float = 0.0f; highy_int = convy_int; highy_float = convy_float; - + for( i = 0; i < heightout; i++ ) { // Clamp here to be sure we don't read beyond input buffer. if (highy_int >= heightin) @@ -430,18 +430,18 @@ public class ScaleInternal { highx_int = convx_int; highx_float = convx_float; } - + for( j = 0; j < widthout; j++ ) { - + // Ok, now apply box filter to box that goes from (lowx, lowy) // to (highx, highy) on input data into this pixel on output // data. totals[0] = totals[1] = totals[2] = totals[3] = 0.0f; - + // caulate the value for pixels in the 1st row xindex = lowx_int * group_size; if( ( highy_int > lowy_int ) && ( highx_int > lowx_int ) ) { - + y_percent = 1 - lowy_float; temp = xindex + lowy_int * ysize; percent = y_percent * ( 1 - lowx_float ); @@ -464,7 +464,7 @@ public class ScaleInternal { datain.position( temp_index ); totals[k] += datain.get() * percent; } - + // calculate the value for pixels in the last row y_percent = highy_float; percent = y_percent * ( 1 - lowx_float ); @@ -486,7 +486,7 @@ public class ScaleInternal { datain.position( temp_index ); totals[k] += datain.get() * percent; } - + // calculate the value for the pixels in the 1st and last column for( m = lowy_int + 1; m < highy_int; m++ ) { left += ysize; @@ -550,7 +550,7 @@ public class ScaleInternal { totals[k] += datain.get() * percent; } } - + // this is for the pixels in the body temp0 = xindex + group_size + ( lowy_int + 1 ) * ysize; for( m = lowy_int + 1; m < highy_int; m++ ) { @@ -564,7 +564,7 @@ public class ScaleInternal { } temp0 += ysize; } - + outindex = ( j + ( i * widthout ) ) * components; for( k = 0; k < components; k++ ) { dataout.position( outindex + k ); @@ -596,10 +596,10 @@ public class ScaleInternal { } } } - + public static void scale_internal_ushort( int components, int widthin, int heightin, - ByteBuffer datain, int widthout, int heightout, - ShortBuffer dataout, int element_size, int ysize, + ByteBuffer datain, int widthout, int heightout, + ShortBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { float x, convx; float y, convy; @@ -608,11 +608,11 @@ public class ScaleInternal { float[] totals = new float[4]; float area; int i, j, k, xindex; - + int temp, temp0; int temp_index; int outindex; - + int lowx_int, highx_int, lowy_int, highy_int; float x_percent, y_percent; float lowx_float, highx_float, lowy_float, highy_float; @@ -620,9 +620,9 @@ public class ScaleInternal { int convy_int, convx_int; int l, m; int left, right; - + if( (widthin == (widthout * 2)) && (heightin == (heightout * 2)) ) { - HalveImage.halveImage_ushort( components, widthin, heightin, datain, dataout, + HalveImage.halveImage_ushort( components, widthin, heightin, datain, dataout, element_size, ysize, group_size, myswap_bytes ); return; } @@ -632,14 +632,14 @@ public class ScaleInternal { convy_float = convy - convy_int; convx_int = (int)Math.floor( convx ); convx_float = convx - convx_int; - + area = convx * convy; - + lowy_int = 0; lowy_float = 0.0f; highy_int = convy_int; highy_float = convy_float; - + for( i = 0; i < heightout; i++ ) { // Clamp here to be sure we don't read beyond input buffer. if (highy_int >= heightin) @@ -655,18 +655,18 @@ public class ScaleInternal { highx_int = convx_int; highx_float = convx_float; } - + for( j = 0; j < widthout; j++ ) { - + // Ok, now apply box filter to box that goes from (lowx, lowy) // to (highx, highy) on input data into this pixel on output // data. totals[0] = totals[1] = totals[2] = totals[3] = 0.0f; - + // caulate the value for pixels in the 1st row xindex = lowx_int * group_size; if( ( highy_int > lowy_int ) && ( highx_int > lowx_int ) ) { - + y_percent = 1 - lowy_float; temp = xindex + lowy_int * ysize; percent = y_percent * ( 1 - lowx_float ); @@ -701,7 +701,7 @@ public class ScaleInternal { totals[k] += ( 0x0000FFFF & datain.getShort()) * percent; } } - + // calculate the value for pixels in the last row y_percent = highy_float; percent = y_percent * ( 1 - lowx_float ); @@ -735,7 +735,7 @@ public class ScaleInternal { totals[k] += ( 0x0000FFFF & datain.getShort()) * percent; } } - + // calculate the value for the pixels in the 1st and last column for( m = lowy_int + 1; m < highy_int; m++ ) { left += ysize; @@ -834,7 +834,7 @@ public class ScaleInternal { } } } - + // this is for the pixels in the body temp0 = xindex + group_size + ( lowy_int + 1 ) * ysize; for( m = lowy_int + 1; m < highy_int; m++ ) { @@ -852,7 +852,7 @@ public class ScaleInternal { } temp0 += ysize; } - + outindex = ( j + ( i * widthout ) ) * components; for( k = 0; k < components; k++ ) { dataout.position( outindex + k ); @@ -884,10 +884,10 @@ public class ScaleInternal { } } } - + public static void scale_internal_short( int components, int widthin, int heightin, ByteBuffer datain, int widthout, int heightout, - ShortBuffer dataout, int element_size, int ysize, + ShortBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { float x, convx; float y, convy; @@ -896,11 +896,11 @@ public class ScaleInternal { float[] totals = new float[4]; float area; int i, j, k, xindex; - + int temp, temp0; int temp_index; int outindex; - + int lowx_int, highx_int, lowy_int, highy_int; float x_percent, y_percent; float lowx_float, highx_float, lowy_float, highy_float; @@ -908,11 +908,11 @@ public class ScaleInternal { int convy_int, convx_int; int l, m; int left, right; - + int swapbuf; // unsigned buffer - + if( (widthin == (widthout * 2)) && (heightin == (heightout * 2)) ) { - HalveImage.halveImage_short( components, widthin, heightin, datain, dataout, + HalveImage.halveImage_short( components, widthin, heightin, datain, dataout, element_size, ysize, group_size, myswap_bytes ); return; } @@ -922,14 +922,14 @@ public class ScaleInternal { convy_float = convy - convy_int; convx_int = (int)Math.floor( convx ); convx_float = convx - convx_int; - + area = convx * convy; - + lowy_int = 0; lowy_float = 0.0f; highy_int = convy_int; highy_float = convy_float; - + for( i = 0; i < heightout; i++ ) { // Clamp here to be sure we don't read beyond input buffer. if (highy_int >= heightin) @@ -945,18 +945,18 @@ public class ScaleInternal { highx_int = convx_int; highx_float = convx_float; } - + for( j = 0; j < widthout; j++ ) { - + // Ok, now apply box filter to box that goes from (lowx, lowy) // to (highx, highy) on input data into this pixel on output // data. totals[0] = totals[1] = totals[2] = totals[3] = 0.0f; - + // caulate the value for pixels in the 1st row xindex = lowx_int * group_size; if( ( highy_int > lowy_int ) && ( highx_int > lowx_int ) ) { - + y_percent = 1 - lowy_float; temp = xindex + lowy_int * ysize; percent = y_percent * ( 1 - lowx_float ); @@ -994,7 +994,7 @@ public class ScaleInternal { totals[k] += datain.getShort() * percent; } } - + // calculate the value for pixels in the last row y_percent = highy_float; percent = y_percent * ( 1 - lowx_float ); @@ -1031,7 +1031,7 @@ public class ScaleInternal { totals[k] += datain.getShort() * percent; } } - + // calculate the value for the pixels in the 1st and last column for( m = lowy_int + 1; m < highy_int; m++ ) { left += ysize; @@ -1137,7 +1137,7 @@ public class ScaleInternal { } } } - + // this is for the pixels in the body temp0 = xindex + group_size + ( lowy_int + 1 ) * ysize; for( m = lowy_int + 1; m < highy_int; m++ ) { @@ -1156,7 +1156,7 @@ public class ScaleInternal { } temp0 += ysize; } - + outindex = ( j + ( i * widthout ) ) * components; for( k = 0; k < components; k++ ) { dataout.position( outindex + k ); @@ -1188,10 +1188,10 @@ public class ScaleInternal { } } } - + public static void scale_internal_uint( int components, int widthin, int heightin, - ByteBuffer datain, int widthout, int heightout, - IntBuffer dataout, int element_size, int ysize, + ByteBuffer datain, int widthout, int heightout, + IntBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { float x, convx; float y, convy; @@ -1200,11 +1200,11 @@ public class ScaleInternal { float[] totals = new float[4]; float area; int i, j, k, xindex; - + int temp, temp0; int temp_index; int outindex; - + int lowx_int, highx_int, lowy_int, highy_int; float x_percent, y_percent; float lowx_float, highx_float, lowy_float, highy_float; @@ -1212,9 +1212,9 @@ public class ScaleInternal { int convy_int, convx_int; int l, m; int left, right; - + if( (widthin == (widthout * 2)) && (heightin == (heightout * 2)) ) { - HalveImage.halveImage_uint( components, widthin, heightin, datain, dataout, + HalveImage.halveImage_uint( components, widthin, heightin, datain, dataout, element_size, ysize, group_size, myswap_bytes ); return; } @@ -1224,14 +1224,14 @@ public class ScaleInternal { convy_float = convy - convy_int; convx_int = (int)Math.floor( convx ); convx_float = convx - convx_int; - + area = convx * convy; - + lowy_int = 0; lowy_float = 0.0f; highy_int = convy_int; highy_float = convy_float; - + for( i = 0; i < heightout; i++ ) { // Clamp here to be sure we don't read beyond input buffer. if (highy_int >= heightin) @@ -1247,18 +1247,18 @@ public class ScaleInternal { highx_int = convx_int; highx_float = convx_float; } - + for( j = 0; j < widthout; j++ ) { - + // Ok, now apply box filter to box that goes from (lowx, lowy) // to (highx, highy) on input data into this pixel on output // data. totals[0] = totals[1] = totals[2] = totals[3] = 0.0f; - + // caulate the value for pixels in the 1st row xindex = lowx_int * group_size; if( ( highy_int > lowy_int ) && ( highx_int > lowx_int ) ) { - + y_percent = 1 - lowy_float; temp = xindex + lowy_int * ysize; percent = y_percent * ( 1 - lowx_float ); @@ -1293,7 +1293,7 @@ public class ScaleInternal { totals[k] += (0x00000000FFFFFFFF & datain.getInt()) * percent; } } - + // calculate the value for pixels in the last row y_percent = highy_float; percent = y_percent * ( 1 - lowx_float ); @@ -1327,7 +1327,7 @@ public class ScaleInternal { totals[k] += (0x00000000FFFFFFFF & datain.getInt()) * percent; } } - + // calculate the value for the pixels in the 1st and last column for( m = lowy_int + 1; m < highy_int; m++ ) { left += ysize; @@ -1427,7 +1427,7 @@ public class ScaleInternal { } } } - + // this is for the pixels in the body temp0 = xindex + group_size + ( lowy_int + 1 ) * ysize; for( m = lowy_int + 1; m < highy_int; m++ ) { @@ -1445,7 +1445,7 @@ public class ScaleInternal { } temp0 += ysize; } - + outindex = ( j + ( i * widthout ) ) * components; float value = 0.0f; for( k = 0; k < components; k++ ) { @@ -1483,10 +1483,10 @@ public class ScaleInternal { } } } - + public static void scale_internal_int( int components, int widthin, int heightin, - ByteBuffer datain, int widthout, int heightout, - IntBuffer dataout, int element_size, int ysize, + ByteBuffer datain, int widthout, int heightout, + IntBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { float x, convx; float y, convy; @@ -1495,11 +1495,11 @@ public class ScaleInternal { float[] totals = new float[4]; float area; int i, j, k, xindex; - + int temp, temp0; int temp_index; int outindex; - + int lowx_int, highx_int, lowy_int, highy_int; float x_percent, y_percent; float lowx_float, highx_float, lowy_float, highy_float; @@ -1507,11 +1507,11 @@ public class ScaleInternal { int convy_int, convx_int; int l, m; int left, right; - + long swapbuf; // unsigned buffer - + if( (widthin == (widthout * 2)) && (heightin == (heightout * 2)) ) { - HalveImage.halveImage_int( components, widthin, heightin, datain, dataout, + HalveImage.halveImage_int( components, widthin, heightin, datain, dataout, element_size, ysize, group_size, myswap_bytes ); return; } @@ -1521,14 +1521,14 @@ public class ScaleInternal { convy_float = convy - convy_int; convx_int = (int)Math.floor( convx ); convx_float = convx - convx_int; - + area = convx * convy; - + lowy_int = 0; lowy_float = 0.0f; highy_int = convy_int; highy_float = convy_float; - + for( i = 0; i < heightout; i++ ) { // Clamp here to be sure we don't read beyond input buffer. if (highy_int >= heightin) @@ -1544,18 +1544,18 @@ public class ScaleInternal { highx_int = convx_int; highx_float = convx_float; } - + for( j = 0; j < widthout; j++ ) { - + // Ok, now apply box filter to box that goes from (lowx, lowy) // to (highx, highy) on input data into this pixel on output // data. totals[0] = totals[1] = totals[2] = totals[3] = 0.0f; - + // caulate the value for pixels in the 1st row xindex = lowx_int * group_size; if( ( highy_int > lowy_int ) && ( highx_int > lowx_int ) ) { - + y_percent = 1 - lowy_float; temp = xindex + lowy_int * ysize; percent = y_percent * ( 1 - lowx_float ); @@ -1593,7 +1593,7 @@ public class ScaleInternal { totals[k] += datain.getInt() * percent; } } - + // calculate the value for pixels in the last row y_percent = highy_float; percent = y_percent * ( 1 - lowx_float ); @@ -1630,7 +1630,7 @@ public class ScaleInternal { totals[k] += datain.getInt() * percent; } } - + // calculate the value for the pixels in the 1st and last column for( m = lowy_int + 1; m < highy_int; m++ ) { left += ysize; @@ -1736,7 +1736,7 @@ public class ScaleInternal { } } } - + // this is for the pixels in the body temp0 = xindex + group_size + ( lowy_int + 1 ) * ysize; for( m = lowy_int + 1; m < highy_int; m++ ) { @@ -1755,7 +1755,7 @@ public class ScaleInternal { } temp0 += ysize; } - + outindex = ( j + ( i * widthout ) ) * components; for( k = 0; k < components; k++ ) { dataout.position( outindex + k ); @@ -1787,10 +1787,10 @@ public class ScaleInternal { } } } - + public static void scale_internal_float( int components, int widthin, int heightin, - ByteBuffer datain, int widthout, int heightout, - FloatBuffer dataout, int element_size, int ysize, + ByteBuffer datain, int widthout, int heightout, + FloatBuffer dataout, int element_size, int ysize, int group_size, boolean myswap_bytes ) { float x, convx; float y, convy; @@ -1799,11 +1799,11 @@ public class ScaleInternal { float[] totals = new float[4]; float area; int i, j, k, xindex; - + int temp, temp0; int temp_index; int outindex; - + int lowx_int, highx_int, lowy_int, highy_int; float x_percent, y_percent; float lowx_float, highx_float, lowy_float, highy_float; @@ -1811,11 +1811,11 @@ public class ScaleInternal { int convy_int, convx_int; int l, m; int left, right; - + float swapbuf; // unsigned buffer - + if( (widthin == (widthout * 2)) && (heightin == (heightout * 2)) ) { - HalveImage.halveImage_float( components, widthin, heightin, datain, dataout, + HalveImage.halveImage_float( components, widthin, heightin, datain, dataout, element_size, ysize, group_size, myswap_bytes ); return; } @@ -1825,14 +1825,14 @@ public class ScaleInternal { convy_float = convy - convy_int; convx_int = (int)Math.floor( convx ); convx_float = convx - convx_int; - + area = convx * convy; - + lowy_int = 0; lowy_float = 0.0f; highy_int = convy_int; highy_float = convy_float; - + for( i = 0; i < heightout; i++ ) { // Clamp here to be sure we don't read beyond input buffer. if (highy_int >= heightin) @@ -1848,18 +1848,18 @@ public class ScaleInternal { highx_int = convx_int; highx_float = convx_float; } - + for( j = 0; j < widthout; j++ ) { - + // Ok, now apply box filter to box that goes from (lowx, lowy) // to (highx, highy) on input data into this pixel on output // data. totals[0] = totals[1] = totals[2] = totals[3] = 0.0f; - + // caulate the value for pixels in the 1st row xindex = lowx_int * group_size; if( ( highy_int > lowy_int ) && ( highx_int > lowx_int ) ) { - + y_percent = 1 - lowy_float; temp = xindex + lowy_int * ysize; percent = y_percent * ( 1 - lowx_float ); @@ -1897,7 +1897,7 @@ public class ScaleInternal { totals[k] += datain.getFloat() * percent; } } - + // calculate the value for pixels in the last row y_percent = highy_float; percent = y_percent * ( 1 - lowx_float ); @@ -1934,7 +1934,7 @@ public class ScaleInternal { totals[k] += datain.getFloat() * percent; } } - + // calculate the value for the pixels in the 1st and last column for( m = lowy_int + 1; m < highy_int; m++ ) { left += ysize; @@ -2040,7 +2040,7 @@ public class ScaleInternal { } } } - + // this is for the pixels in the body temp0 = xindex + group_size + ( lowy_int + 1 ) * ysize; for( m = lowy_int + 1; m < highy_int; m++ ) { @@ -2059,7 +2059,7 @@ public class ScaleInternal { } temp0 += ysize; } - + outindex = ( j + ( i * widthout ) ) * components; for( k = 0; k < components; k++ ) { dataout.position( outindex + k ); @@ -2091,28 +2091,28 @@ public class ScaleInternal { } } } - - public static void scaleInternalPackedPixel( int components, Extract extract, + + public static void scaleInternalPackedPixel( int components, Extract extract, int widthIn, int heightIn, ByteBuffer dataIn, int widthOut, int heightOut, ByteBuffer dataOut, int pixelSizeInBytes, int rowSizeInBytes, boolean isSwap ) { float x, convx; float y, convy; float percent; - + // max components in a format is 4, so float[] totals = new float[4]; float[] extractTotals = new float[4]; float[] extractMoreTotals = new float[4]; float[] shoveTotals = new float[4]; - + float area; int i, j, k, xindex; - + int temp, temp0; int temp_index; int outIndex = 0; - + int lowx_int, highx_int, lowy_int, highy_int; float x_percent, y_percent; float lowx_float, highx_float, lowy_float, highy_float; @@ -2120,7 +2120,7 @@ public class ScaleInternal { int convy_int, convx_int; int l, m; int left, right; - + if( widthIn == widthOut * 2 && heightIn == heightOut * 2 ) { HalveImage.halveImagePackedPixel( components, extract, widthIn, heightIn, dataIn, dataOut, pixelSizeInBytes, rowSizeInBytes, isSwap ); @@ -2132,14 +2132,14 @@ public class ScaleInternal { convy_float = convy - convy_int; convx_int = (int)Math.floor( convx ); convx_float = convx - convx_int; - + area = convx * convy; - + lowy_int = 0; lowy_float = 0.0f; highy_int = convy_int; highy_float = convx_float; - + for( i = 0; i < heightOut; i++ ) { // Clamp here to be sure we don't read beyond input buffer. if (highy_int >= heightIn) @@ -2148,16 +2148,16 @@ public class ScaleInternal { lowx_float = 0.0f; highx_int = convx_int; highx_float = convx_float; - + for( j = 0; j < widthOut; j++ ) { // ok now apply box filter to box that goes from( lowx, lowy ) // to ( highx, highy ) on input data into this pixel on output data totals[0] = totals[1] = totals[2] = totals[3] = 0.0f; - + // calculate that value for pixels in the 1st row xindex = lowx_int * pixelSizeInBytes; if( (highy_int > lowy_int) && (highx_int > lowx_int) ) { - + y_percent = 1 - lowy_float; temp = xindex + lowy_int * rowSizeInBytes; percent = y_percent * ( 1 - lowx_float ); @@ -2184,7 +2184,7 @@ public class ScaleInternal { totals[k] += extractTotals[k] * percent; } // calculate the value for pixels in the last row - + y_percent = highy_float; percent = y_percent * ( 1 - lowx_float ); temp = xindex + highy_int * rowSizeInBytes; @@ -2207,7 +2207,7 @@ public class ScaleInternal { for( k = 0; k < components; k++ ) { totals[k] += extractTotals[k] * percent; } - + // calculate the value for pixels in the 1st and last column for( m = lowy_int + 1; m < highy_int; m++ ) { left += rowSizeInBytes; @@ -2277,7 +2277,7 @@ public class ScaleInternal { totals[k] += extractTotals[k] * percent; } } - + // this is for the pixels in the body temp0 = xindex + pixelSizeInBytes + ( lowy_int + 1 ) * rowSizeInBytes; for( m = lowy_int + 1; m < highy_int; m++ ) { @@ -2292,7 +2292,7 @@ public class ScaleInternal { } temp0 += rowSizeInBytes; } - + outIndex = ( j + ( i * widthOut ) ); for( k = 0; k < components; k++ ) { shoveTotals[k] = totals[k] / area; @@ -2325,7 +2325,7 @@ public class ScaleInternal { } assert( outIndex == ( widthOut * heightOut - 1) ); } - + public static void scaleInternal3D( int components, int widthIn, int heightIn, int depthIn, ShortBuffer dataIn, int widthOut, int heightOut, int depthOut, ShortBuffer dataOut ) { @@ -2339,9 +2339,9 @@ public class ScaleInternal { float volume; int i, j, d, k, zint, yint, xint, xindex, yindex, zindex; int temp; - + lowy = highy = lowx = highx = 0.0f; - + convz = (float)depthIn / depthOut; convy = (float)heightIn / heightOut; convx = (float)widthIn / widthOut; @@ -2375,13 +2375,13 @@ public class ScaleInternal { highz = x + 0.5f; lowz = x - 0.5f; } - + // Ok, now apply box filter to box that goes from ( lowx, lowy, lowz ) // to ( highx, highy, highz ) on input data into this pixel on output data - + totals[0] = totals[1] = totals[2] = totals[3] = 0.0f; volume = 0.0f; - + z = lowz; zint = (int)(Math.floor( z ) ); while( z < highz ) { @@ -2391,7 +2391,7 @@ public class ScaleInternal { } else { zpercent = zint + 1 - z; } - + y = lowy; yint = (int)(Math.floor( y ) ); while( y < highy ) { @@ -2401,10 +2401,10 @@ public class ScaleInternal { } else { ypercent = yint + 1 - y; } - + x = lowx; xint = (int)(Math.floor( x ) ); - + while( x < highx ) { xindex = (xint + widthIn ) % widthIn; if( highx < xint + 1 ) { @@ -2412,10 +2412,10 @@ public class ScaleInternal { } else { xpercent = xint + 1 - x; } - + percent = xpercent * ypercent * zpercent; volume += percent; - + temp = (xindex + ( yindex *widthIn) + (zindex * widthIn *heightIn)) * components; for( k = 0; k < components; k++ ) { assert( 0 <= (temp+k) && (temp+k) < (widthIn * heightIn * depthIn * components) ); @@ -2430,7 +2430,7 @@ public class ScaleInternal { zint++; z = zint; } // while z - + temp = ( j + ( i * widthOut ) + (d * widthOut * heightOut ) ) * components; for( k = 0; k < components; k++ ) { // totals should be rounded in the case of enlarging an rgb ramp when the type is 332 or 4444 @@ -2441,48 +2441,48 @@ public class ScaleInternal { } } } - - public static int gluScaleImage3D( GL gl, int format, int widthIn, int heightIn, - int depthIn, int typeIn, ByteBuffer dataIn, int widthOut, int heightOut, + + public static int gluScaleImage3D( GL gl, int format, int widthIn, int heightIn, + int depthIn, int typeIn, ByteBuffer dataIn, int widthOut, int heightOut, int depthOut, int typeOut, ByteBuffer dataOut ) { int components; ShortBuffer beforeImage, afterImage; PixelStorageModes psm = new PixelStorageModes(); - + if( widthIn == 0 || heightIn == 0 || depthIn == 0 || widthOut == 0 || heightOut == 0 || depthOut == 0 ) { return( 0 ); } - + if( widthIn < 0 || heightIn < 0 || depthIn < 0 || widthOut < 0 || heightOut < 0 || depthOut < 0 ) { return( GLU.GLU_INVALID_VALUE ); } - - if( !Mipmap.legalFormat(format) || !Mipmap.legalType(typeIn) || + + if( !Mipmap.legalFormat(format) || !Mipmap.legalType(typeIn) || !Mipmap.legalType(typeOut) || typeIn == GL2.GL_BITMAP || typeOut == GL2.GL_BITMAP ) { return( GLU.GLU_INVALID_ENUM ); } - + if( !Mipmap.isLegalFormatForPackedPixelType( format, typeIn ) ) { return( GLU.GLU_INVALID_OPERATION ); } - + if( !Mipmap.isLegalFormatForPackedPixelType( format, typeOut ) ) { return( GLU.GLU_INVALID_OPERATION ); } - + try { - beforeImage = Buffers.newDirectByteBuffer( Mipmap.imageSize3D( widthIn, + beforeImage = Buffers.newDirectByteBuffer( Mipmap.imageSize3D( widthIn, heightIn, depthIn, format, GL2.GL_UNSIGNED_SHORT ) ).asShortBuffer(); - afterImage = Buffers.newDirectByteBuffer( Mipmap.imageSize3D( widthIn, + afterImage = Buffers.newDirectByteBuffer( Mipmap.imageSize3D( widthIn, heightIn, depthIn, format, GL2.GL_UNSIGNED_SHORT ) ).asShortBuffer(); } catch( OutOfMemoryError err ) { return( GLU.GLU_OUT_OF_MEMORY ); } Mipmap.retrieveStoreModes3D( gl, psm ); - + Image.fillImage3D( psm, widthIn, heightIn, depthIn, format, typeIn, Mipmap.is_index( format ), dataIn, beforeImage ); components = Mipmap.elements_per_group( format, 0 ); @@ -2490,7 +2490,7 @@ public class ScaleInternal { beforeImage, widthOut, heightOut, depthOut, afterImage ); Image.emptyImage3D( psm, widthOut, heightOut, depthOut, format, typeOut, Mipmap.is_index( format ), afterImage, dataOut ); - + return( 0 ); } } diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Type_Widget.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Type_Widget.java index 38113f601..dc401880d 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Type_Widget.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Type_Widget.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,176 +51,176 @@ import java.nio.*; * @author Administrator */ public class Type_Widget { - + ByteBuffer buffer; - + /** Creates a new instance of Type_Widget */ public Type_Widget() { // can't make this direct, because JVM doesn't allocate small direct buffers efficiently // see https://jogamp.org/bugzilla/show_bug.cgi?id=463 for details buffer = ByteBuffer.allocate( 4 ); } - + public void setUB0( byte b ) { buffer.position( 0 ); buffer.put( b ); } - + public byte getUB0() { buffer.position( 0 ); return( buffer.get() ); } - + public void setUB1( byte b ) { buffer.position( 1 ); buffer.put( b ); } - + public byte getUB1() { buffer.position( 1 ); return( buffer.get() ); } - + public void setUB2( byte b ) { buffer.position( 2 ); buffer.put( b ); } - + public byte getUB2() { buffer.position( 2 ); return( buffer.get() ); } - + public void setUB3( byte b ) { buffer.position( 3 ); buffer.put( b ); } - + public byte getUB3() { buffer.position( 3 ); return( buffer.get() ); } - + public void setUS0( short s ) { buffer.position( 0 ); buffer.putShort( s ); } - + public short getUS0() { buffer.position( 0 ); return( buffer.getShort() ); } - + public void setUS1( short s ) { buffer.position( 2 ); buffer.putShort( s ); } - + public short getUS1() { buffer.position( 2 ); return( buffer.getShort() ); } - + public void setUI( int i ) { buffer.position( 0 ); buffer.putInt( i ); } - + public int getUI() { buffer.position( 0 ); return( buffer.getInt() ); } - + public void setB0( byte b ) { buffer.position( 0 ); buffer.put( b ); } - + public byte getB0() { buffer.position( 0 ); return( buffer.get() ); } - + public void setB1( byte b ) { buffer.position( 1 ); buffer.put( b ); } - + public byte getB1() { buffer.position( 1 ); return( buffer.get() ); } - + public void setB2( byte b ) { buffer.position( 2 ); buffer.put( b ); } - + public byte getB2() { buffer.position( 2 ); return( buffer.get() ); } - + public void setB3( byte b ) { buffer.position( 3 ); buffer.put( b ); } - + public byte getB3() { buffer.position( 3 ); return( buffer.get() ); } - + public void setS0( short s ) { buffer.position( 0 ); buffer.putShort( s ); } - + public short getS0() { buffer.position( 0 ); return( buffer.getShort() ); } - + public void setS1( short s ) { buffer.position( 2 ); buffer.putShort( s ); } - + public short getS1() { buffer.position( 2 ); return( buffer.getShort() ); } - + public void setI( int i ) { buffer.position( 0 ); buffer.putInt( i ); } - + public int getI() { buffer.position( 0 ); return( buffer.getInt() ); } - + public void setF( float f ) { buffer.position( 0 ); buffer.putFloat( f ); } - + public float getF() { buffer.position( 0 ); return( buffer.getFloat() ); } - + public ByteBuffer getBuffer() { buffer.rewind(); return( buffer ); } - + public static void main( String args[] ) { Type_Widget t = new Type_Widget(); t.setI( 1000000 ); - + System.out.println("int: " + Integer.toHexString( t.getI() ) ); - + } } diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Arc.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Arc.java index 422f8d4df..df2b9a147 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Arc.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Arc.java @@ -72,7 +72,7 @@ public class Arc { /** * Makes new arc at specified side - * + * * @param side * which side doeas this arc form */ @@ -86,7 +86,7 @@ public class Arc { /** * Sets side the arc is at - * + * * @param side * arc side */ @@ -104,7 +104,7 @@ public class Arc { type &= ~(0x7 << 8); } - // this one replaces enum arc_side + // this one replaces enum arc_side /** * Side not specified */ @@ -147,7 +147,7 @@ public class Arc { /** * Appends arc to the list - * + * * @param jarc * arc to be append * @return this @@ -169,7 +169,7 @@ public class Arc { /** * Unused - * + * * @return true */ public boolean check() { @@ -187,7 +187,7 @@ public class Arc { /** * Returns tail of linked list coords - * + * * @return tail coords */ public float[] tail() { @@ -197,7 +197,7 @@ public class Arc { /** * Returns head of linked list coords - * + * * @return head coords */ public float[] head() { @@ -207,7 +207,7 @@ public class Arc { /** * Returns whether arc is marked with arc_tag - * + * * @return is arc marked with arc_tag */ public boolean ismarked() { @@ -241,7 +241,7 @@ public class Arc { /** * Returns whether arc is marked tail - * + * * @return is tail */ public boolean getitail() { diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/ArcSdirSorter.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/ArcSdirSorter.java index f4ad70193..c299b10af 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/ArcSdirSorter.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/ArcSdirSorter.java @@ -44,7 +44,7 @@ public class ArcSdirSorter { /** * Makes new ArcSdirSorter with Subdivider * @param subdivider subdivider - */ + */ public ArcSdirSorter(Subdivider subdivider) { //TODO // System.out.println("TODO arcsdirsorter.constructor"); diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/ArcTdirSorter.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/ArcTdirSorter.java index be72c53d2..1a584c396 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/ArcTdirSorter.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/ArcTdirSorter.java @@ -43,7 +43,7 @@ public class ArcTdirSorter { /** * Makes new ArcSdirSorter with Subdivider * @param subdivider subdivider - */ + */ public ArcTdirSorter(Subdivider subdivider) { // TODO Auto-generated constructor stub // System.out.println("TODO arcTsorter.konstruktor"); diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Backend.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Backend.java index 610a19556..3e974247b 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Backend.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Backend.java @@ -67,7 +67,7 @@ public abstract class Backend { protected SurfaceEvaluator surfaceEvaluator; /** - * Makes new backend + * Makes new backend */ public Backend() { // curveEvaluator = new OpenGLCurveEvaluator(); diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Bin.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Bin.java index df8b16ab5..17437ef01 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Bin.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Bin.java @@ -143,7 +143,7 @@ public class Bin { /** * Returns next arc in linked list * @return next arc - * + * */ private Arc nextarc() { // DONE diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Breakpt.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Breakpt.java index f45571dac..f84640d28 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Breakpt.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Breakpt.java @@ -36,9 +36,9 @@ package jogamp.opengl.glu.nurbs; /** * Class holding break point parameters - * + * * @author Tomas Hrasky - * + * */ public class Breakpt { diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfArcs.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfArcs.java index aaa8cb5f2..b67764c30 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfArcs.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfArcs.java @@ -2,9 +2,9 @@ package jogamp.opengl.glu.nurbs; /** * Class replacing C language pointer - * + * * @author Tomas Hrasky - * + * */ public class CArrayOfArcs { /** @@ -24,7 +24,7 @@ public class CArrayOfArcs { /** * Makes new CArray - * + * * @param array * underlaying array * @param pointer @@ -38,7 +38,7 @@ public class CArrayOfArcs { /** * Makes new CArray from other CArray - * + * * @param carray * reference array */ @@ -50,7 +50,7 @@ public class CArrayOfArcs { /** * Makes new CArray with pointer set to 0 - * + * * @param ctlarray * underlaying array */ @@ -61,7 +61,7 @@ public class CArrayOfArcs { /** * Returns element at pointer - * + * * @return element at pointer */ public Arc get() { @@ -78,7 +78,7 @@ public class CArrayOfArcs { /** * Sets element at pointer - * + * * @param f * desired value */ @@ -89,7 +89,7 @@ public class CArrayOfArcs { /** * Returns array element at specified index - * + * * @param i * array index * @return element at index @@ -100,7 +100,7 @@ public class CArrayOfArcs { /** * Returns array element at specified index relatively to pointer - * + * * @param i * relative index * @return element at relative index @@ -111,7 +111,7 @@ public class CArrayOfArcs { /** * Sets value of element at specified index relatively to pointer - * + * * @param i * relative index * @param value @@ -123,7 +123,7 @@ public class CArrayOfArcs { /** * Lessens pointer by value - * + * * @param i * lessen by */ @@ -134,7 +134,7 @@ public class CArrayOfArcs { /** * Returns pointer value - * + * * @return pointer value */ public int getPointer() { @@ -143,7 +143,7 @@ public class CArrayOfArcs { /** * Sets ponter value - * + * * @param pointer * pointer value to be set */ @@ -156,7 +156,7 @@ public class CArrayOfArcs { /** * Raises pointer by value - * + * * @param i * raise by */ @@ -175,7 +175,7 @@ public class CArrayOfArcs { /** * Returns underlaying array - * + * * @return underlaying array */ public Arc[] getArray() { @@ -184,7 +184,7 @@ public class CArrayOfArcs { /** * Sets underlaying array - * + * * @param array * underlaying array */ diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfBreakpts.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfBreakpts.java index 5112b07fc..b5f588960 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfBreakpts.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfBreakpts.java @@ -2,9 +2,9 @@ package jogamp.opengl.glu.nurbs; /** * Class replacing C language pointer - * + * * @author Tomas Hrasky - * + * */ public class CArrayOfBreakpts { /** @@ -19,7 +19,7 @@ public class CArrayOfBreakpts { /** * Makes new CArray - * + * * @param array * underlaying array * @param pointer @@ -32,7 +32,7 @@ public class CArrayOfBreakpts { /** * Makes new CArray from other CArray - * + * * @param carray * reference array */ @@ -43,7 +43,7 @@ public class CArrayOfBreakpts { /** * Returns element at pointer - * + * * @return element at pointer */ public Breakpt get() { @@ -59,7 +59,7 @@ public class CArrayOfBreakpts { /** * Sets element at pointer - * + * * @param f * desired value */ @@ -70,7 +70,7 @@ public class CArrayOfBreakpts { /** * Returns array element at specified index - * + * * @param i * array index * @return element at index @@ -81,7 +81,7 @@ public class CArrayOfBreakpts { /** * Lessens pointer by value - * + * * @param i * lessen by */ @@ -92,7 +92,7 @@ public class CArrayOfBreakpts { /** * Returns pointer value - * + * * @return pointer value */ public int getPointer() { @@ -101,7 +101,7 @@ public class CArrayOfBreakpts { /** * Sets ponter value - * + * * @param pointer * pointer value to be set */ @@ -111,7 +111,7 @@ public class CArrayOfBreakpts { /** * Raises pointer by value - * + * * @param i * raise by */ diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfFloats.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfFloats.java index 39ef841ec..d9e4d0ff1 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfFloats.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfFloats.java @@ -2,9 +2,9 @@ package jogamp.opengl.glu.nurbs; /** * Class replacing C language pointer - * + * * @author Tomas Hrasky - * + * */ public class CArrayOfFloats { @@ -25,7 +25,7 @@ public class CArrayOfFloats { /** * Makes new CArray - * + * * @param array * underlaying array * @param pointer @@ -39,7 +39,7 @@ public class CArrayOfFloats { /** * Makes new CArray from other CArray - * + * * @param carray * reference array */ @@ -51,7 +51,7 @@ public class CArrayOfFloats { /** * Makes new CArray with pointer set to 0 - * + * * @param ctlarray * underlaying array */ @@ -62,7 +62,7 @@ public class CArrayOfFloats { /** * Returns element at pointer - * + * * @return element at pointer */ public float get() { @@ -79,7 +79,7 @@ public class CArrayOfFloats { /** * Sets element at pointer - * + * * @param f * desired value */ @@ -90,7 +90,7 @@ public class CArrayOfFloats { /** * Returns array element at specified index - * + * * @param i * array index * @return element at index @@ -101,7 +101,7 @@ public class CArrayOfFloats { /** * Returns array element at specified index relatively to pointer - * + * * @param i * relative index * @return element at relative index @@ -112,7 +112,7 @@ public class CArrayOfFloats { /** * Sets value of element at specified index relatively to pointer - * + * * @param i * relative index * @param value @@ -124,7 +124,7 @@ public class CArrayOfFloats { /** * Lessens pointer by value - * + * * @param i * lessen by */ @@ -135,7 +135,7 @@ public class CArrayOfFloats { /** * Returns pointer value - * + * * @return pointer value */ public int getPointer() { @@ -144,7 +144,7 @@ public class CArrayOfFloats { /** * Sets ponter value - * + * * @param pointer * pointer value to be set */ @@ -157,7 +157,7 @@ public class CArrayOfFloats { /** * Raises pointer by value - * + * * @param i * raise by */ @@ -176,7 +176,7 @@ public class CArrayOfFloats { /** * Returns underlaying array - * + * * @return underlaying array */ public float[] getArray() { @@ -185,7 +185,7 @@ public class CArrayOfFloats { /** * Sets underlaying array - * + * * @param array * underlaying array */ diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfQuiltspecs.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfQuiltspecs.java index 4b21f2d50..e7bbac16a 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfQuiltspecs.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/CArrayOfQuiltspecs.java @@ -2,9 +2,9 @@ package jogamp.opengl.glu.nurbs; /** * Class replacing C language pointer - * + * * @author Tomas Hrasky - * + * */ public class CArrayOfQuiltspecs { /** @@ -19,7 +19,7 @@ public class CArrayOfQuiltspecs { /** * Makes new CArray - * + * * @param array * underlaying array * @param pointer @@ -32,7 +32,7 @@ public class CArrayOfQuiltspecs { /** * Makes new CArray from other CArray - * + * * @param carray * reference array */ @@ -43,7 +43,7 @@ public class CArrayOfQuiltspecs { /** * Makes new CArray with pointer set to 0 - * + * * @param array * underlaying array */ @@ -54,7 +54,7 @@ public class CArrayOfQuiltspecs { /** * Returns element at pointer - * + * * @return element at pointer */ public Quiltspec get() { @@ -70,7 +70,7 @@ public class CArrayOfQuiltspecs { /** * Sets element at pointer - * + * * @param f * desired value */ @@ -81,7 +81,7 @@ public class CArrayOfQuiltspecs { /** * Returns array element at specified index - * + * * @param i * array index * @return element at index @@ -92,7 +92,7 @@ public class CArrayOfQuiltspecs { /** * Lessens pointer by value - * + * * @param i * lessen by */ @@ -103,7 +103,7 @@ public class CArrayOfQuiltspecs { /** * Returns pointer value - * + * * @return pointer value */ public int getPointer() { @@ -112,7 +112,7 @@ public class CArrayOfQuiltspecs { /** * Sets ponter value - * + * * @param pointer * pointer value to be set */ @@ -122,7 +122,7 @@ public class CArrayOfQuiltspecs { /** * Raises pointer by value - * + * * @param i * raise by */ @@ -141,7 +141,7 @@ public class CArrayOfQuiltspecs { /** * Returns underlaying array - * + * * @return underlaying array */ public Quiltspec[] getArray() { @@ -150,7 +150,7 @@ public class CArrayOfQuiltspecs { /** * Sets underlaying array - * + * * @param array * underlaying array */ diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Curve.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Curve.java index 786781723..ea3a3d14e 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Curve.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Curve.java @@ -103,7 +103,7 @@ public class Curve { /** * Makes new Curve - * + * * @param geo * @param pta * @param ptb @@ -143,7 +143,7 @@ public class Curve { range[0] = qs.get().breakpoints[qs.get().index]; range[1] = qs.get().breakpoints[qs.get().index + 1]; range[2] = range[1] - range[0]; - // TODO it is necessary to solve problem with "this" pointer here + // TODO it is necessary to solve problem with "this" pointer here if (range[0] != pta[0]) { // System.out.println("TODO curve.Curve-range0"); // Curve lower=new Curve(this,pta,0); @@ -229,7 +229,7 @@ public class Curve { /** * Tells whether curve needs subdivision - * + * * @return curve needs subdivison */ public boolean needsSamplingSubdivision() { diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Flist.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Flist.java index 6983691d9..f9c4c2d6f 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Flist.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Flist.java @@ -45,12 +45,12 @@ public class Flist { /** * Data elements end index - * + * */ public int end; /** - *Data elements start index + *Data elements start index */ public int start; @@ -80,7 +80,7 @@ public class Flist { } /** - * Removes duplicate array elemnts + * Removes duplicate array elemnts */ public void filter() { // INFO the aim of this method is to remove duplicates from array diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Knotspec.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Knotspec.java index 114832a1c..1dcf393a9 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Knotspec.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Knotspec.java @@ -36,9 +36,9 @@ package jogamp.opengl.glu.nurbs; /** * Knot vector specification - * + * * @author Tomas Hrasky - * + * */ public class Knotspec { @@ -314,7 +314,7 @@ public class Knotspec { /** * Copies control points - * + * * @param _inpt * input control points * @param _outpt @@ -346,7 +346,7 @@ public class Knotspec { /** * Copies one control point to other - * + * * @param topt * source control point * @param frompt @@ -374,7 +374,7 @@ public class Knotspec { /** * Inserts a knot - * + * * @param _p * inserted knot */ @@ -402,7 +402,7 @@ public class Knotspec { } } - } else {//code for curve + } else {//code for curve if (this.equals(kspectotrans)) { insert(p); } else { @@ -428,7 +428,7 @@ public class Knotspec { /** * Inserts a knot and computes new control points - * + * * @param p * inserted knot */ @@ -490,7 +490,7 @@ public class Knotspec { /** * Copies one control point to another - * + * * @param topt * source ctrl point * @param frompt @@ -519,7 +519,7 @@ public class Knotspec { /** * Computes new control point - * + * * @param x * first point * @param y @@ -549,7 +549,7 @@ public class Knotspec { * z.getRelative(0))); break; default: - //no need of default - see previous method and its case statement + //no need of default - see previous method and its case statement // System.out.println("TODO pt_oo_sum default"); break; } diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Knotvector.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Knotvector.java index aac4dfc52..571f44f06 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Knotvector.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Knotvector.java @@ -36,9 +36,9 @@ package jogamp.opengl.glu.nurbs; /** * Knot vector used in curve specification - * + * * @author Tomas Hrasky - * + * */ public class Knotvector { @@ -75,7 +75,7 @@ public class Knotvector { /** * Makes new knotvector - * + * * @param nknots * number of knots * @param stride @@ -92,7 +92,7 @@ public class Knotvector { /** * Initializes knotvector - * + * * @param nknots * number of knots * @param stride @@ -116,7 +116,7 @@ public class Knotvector { /** * Validates knot vector parameters - * + * * @return knot vector validity */ public int validate() { @@ -154,7 +154,7 @@ public class Knotvector { /** * Show specified message - * + * * @param msg * message to be shown */ @@ -166,7 +166,7 @@ public class Knotvector { /** * Compares two knots for equality - * + * * @param a * first knot * @param b diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Mapdesc.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Mapdesc.java index bd5d2db98..86638a827 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Mapdesc.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Mapdesc.java @@ -112,7 +112,7 @@ public class Mapdesc { float clampfactor; /** - * Value of N_MINSAVINGS property + * Value of N_MINSAVINGS property */ private float minsavings; @@ -162,7 +162,7 @@ public class Mapdesc { private float[] bboxsize; /** - * Makes new mapdesc + * Makes new mapdesc * @param type map type * @param rational is rational * @param ncoords number of control points coords @@ -318,7 +318,7 @@ public class Mapdesc { } /** - * Tells whether map is culling + * Tells whether map is culling * @return is map culling */ public boolean isCulling() { @@ -327,7 +327,7 @@ public class Mapdesc { } /** - * Tells whether map is constantly sampling + * Tells whether map is constantly sampling * @return is map constant sampling */ public boolean isConstantSampling() { @@ -335,7 +335,7 @@ public class Mapdesc { } /** - * Tells whether map is domain sampling + * Tells whether map is domain sampling * @return is map domain sampling */ public boolean isDomainSampling() { @@ -343,7 +343,7 @@ public class Mapdesc { } /** - * Returns property of specified tag value + * Returns property of specified tag value * @param tag property tag * @return property value */ diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/O_nurbscurve.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/O_nurbscurve.java index 05c89ebcf..a686da696 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/O_nurbscurve.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/O_nurbscurve.java @@ -68,7 +68,7 @@ public class O_nurbscurve { /** * Makes new O_nurbscurve - * @param realType type of curve + * @param realType type of curve */ public O_nurbscurve(int realType) { // DONE diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Patchlist.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Patchlist.java index f1e499a28..8c2922565 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Patchlist.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Patchlist.java @@ -52,7 +52,7 @@ public class Patchlist { private Patch patch; /** - * Makes new list of patches + * Makes new list of patches * @param quilts list of quilts * @param pta low border * @param ptb high border diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Property.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Property.java index 25b4dc441..79f36ce43 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Property.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Property.java @@ -36,9 +36,9 @@ package jogamp.opengl.glu.nurbs; /** * Class representing property - * + * * @author Tomas Hrasky - * + * */ public class Property { @@ -59,7 +59,7 @@ public class Property { /** * Makes new property with given parameters - * + * * @param type * property type * @param tag diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Renderhints.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Renderhints.java index 4729e2421..7c636122f 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Renderhints.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Renderhints.java @@ -35,7 +35,7 @@ package jogamp.opengl.glu.nurbs; */ /** - * Class holding rendering params + * Class holding rendering params * @author Tomas Hrasky * */ diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/Subdivider.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/Subdivider.java index 37774f811..4d8296cca 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/Subdivider.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/Subdivider.java @@ -41,7 +41,7 @@ package jogamp.opengl.glu.nurbs; */ public class Subdivider { /** - * Cull type + * Cull type */ public static final int CULL_TRIVIAL_REJECT = 0; @@ -76,7 +76,7 @@ public class Subdivider { private int subdivisions; /** - * U step when using domain distance sampling + * U step when using domain distance sampling */ private float domain_distance_u_rate; @@ -375,7 +375,7 @@ public class Subdivider { } /** - * Sample + * Sample * @param source * @param patchlist * @param subdivisions diff --git a/src/jogl/classes/jogamp/opengl/glu/nurbs/TrimVertex.java b/src/jogl/classes/jogamp/opengl/glu/nurbs/TrimVertex.java index e88d69709..1025afb7c 100644 --- a/src/jogl/classes/jogamp/opengl/glu/nurbs/TrimVertex.java +++ b/src/jogl/classes/jogamp/opengl/glu/nurbs/TrimVertex.java @@ -36,9 +36,9 @@ package jogamp.opengl.glu.nurbs; /** * Holds vertex used in trim - * + * * @author Tomas Hrasky - * + * */ public class TrimVertex { diff --git a/src/jogl/classes/jogamp/opengl/glu/registry/Registry.java b/src/jogl/classes/jogamp/opengl/glu/registry/Registry.java index 3d669d9bb..9c8523e51 100644 --- a/src/jogl/classes/jogamp/opengl/glu/registry/Registry.java +++ b/src/jogl/classes/jogamp/opengl/glu/registry/Registry.java @@ -6,15 +6,15 @@ * 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. - * + * * NOTE: The Original Code (as defined below) has been licensed to Sun * Microsystems, Inc. ("Sun") under the SGI Free Software License B * (Version 1.1), shown above ("SGI License"). Pursuant to Section @@ -30,7 +30,7 @@ * 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 @@ -51,11 +51,11 @@ import javax.media.opengl.glu.GLU; * @author Administrator */ public class Registry { - + /** Creates a new instance of Registry */ public Registry() { } - + public static String gluGetString(int name) { if( name == GLU.GLU_VERSION ) { return( "1.3" ); @@ -64,7 +64,7 @@ public class Registry { } return( null ); } - + public static boolean gluCheckExtension( String extName, String extString ) { if( extName == null || extString == null ) { return( false ); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 0828d1dc3..5cc4003fe 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -80,7 +80,7 @@ import com.jogamp.opengl.util.glsl.ShaderCode; import com.jogamp.opengl.util.glsl.ShaderProgram; public class MacOSXCGLContext extends GLContextImpl -{ +{ // Abstract interface for implementation of this context (either // NSOpenGL-based or CGL-based) protected interface GLBackendImpl { @@ -140,13 +140,13 @@ public class MacOSXCGLContext extends GLContextImpl } private static final String shaderBasename = "texture01_xxx"; - + private static ShaderProgram createCALayerShader(GL3ES3 gl) { // Create & Link the shader program final ShaderProgram sp = new ShaderProgram(); - final ShaderCode vp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, MacOSXCGLContext.class, + final ShaderCode vp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, MacOSXCGLContext.class, "../../shader", "../../shader/bin", shaderBasename, true); - final ShaderCode fp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, MacOSXCGLContext.class, + final ShaderCode fp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, MacOSXCGLContext.class, "../../shader", "../../shader/bin", shaderBasename, true); vp.defaultShaderCustomization(gl, true, true); fp.defaultShaderCustomization(gl, true, true); @@ -162,7 +162,7 @@ public class MacOSXCGLContext extends GLContextImpl pmvMatrix.glMatrixMode(PMVMatrix.GL_PROJECTION); pmvMatrix.glLoadIdentity(); pmvMatrix.glMatrixMode(PMVMatrix.GL_MODELVIEW); - pmvMatrix.glLoadIdentity(); + pmvMatrix.glLoadIdentity(); final GLUniformData pmvMatrixUniform = new GLUniformData("mgl_PMVMatrix", 4, 4, pmvMatrix.glGetPMvMatrixf()); // P, Mv pmvMatrixUniform.setLocation(gl, sp.program()); gl.glUniform(pmvMatrixUniform); @@ -170,8 +170,8 @@ public class MacOSXCGLContext extends GLContextImpl sp.useProgram(gl, false); return sp; } - - + + private boolean haveSetOpenGLMode = false; private GLBackendType openGLMode = GLBackendType.NSOPENGL; @@ -185,7 +185,7 @@ public class MacOSXCGLContext extends GLContextImpl private long updateHandle = 0; private int lastWidth, lastHeight; - + protected MacOSXCGLContext(GLDrawableImpl drawable, GLContext shareWith) { super(drawable, shareWith); @@ -303,7 +303,7 @@ public class MacOSXCGLContext extends GLContextImpl @Override protected void makeCurrentImpl() throws GLException { /** FIXME: won't work w/ special drawables (like FBO) - check for CGL mode regressions! - * + * if (getOpenGLMode() != ((MacOSXCGLDrawable)drawable).getOpenGLMode()) { setOpenGLMode(((MacOSXCGLDrawable)drawable).getOpenGLMode()); } */ @@ -327,7 +327,7 @@ public class MacOSXCGLContext extends GLContextImpl throw new GLException("Error destroying OpenGL Context: "+this); } } - + private final long getUpdateHandle() { if( 0 == updateHandle ) { lastWidth = -1; @@ -340,7 +340,7 @@ public class MacOSXCGLContext extends GLContextImpl } else { incompleteView = false; } - if(!incompleteView) { + if(!incompleteView) { updateHandle = CGL.updateContextRegister(contextHandle, drawable.getHandle()); if(0 == updateHandle) { throw new InternalError("XXX2"); @@ -350,14 +350,14 @@ public class MacOSXCGLContext extends GLContextImpl } return updateHandle; } - + private final void releaseUpdateHandle() { if ( 0 != updateHandle ) { CGL.updateContextUnregister(updateHandle); updateHandle = 0; - } + } } - + @Override protected void drawableUpdatedNotify() throws GLException { if( drawable.getChosenGLCapabilities().isOnscreen() ) { @@ -376,7 +376,7 @@ public class MacOSXCGLContext extends GLContextImpl } } } - + @Override protected void associateDrawable(boolean bound) { // context stuff depends on drawable stuff @@ -390,12 +390,12 @@ public class MacOSXCGLContext extends GLContextImpl super.associateDrawable(false); // 2) free drawable stuff } } - + /* pp */ void detachPBuffer() { impl.detachPBuffer(); } - + @Override protected void copyImpl(GLContext source, int mask) throws GLException { if( isNSContext() != ((MacOSXCGLContext)source).isNSContext() ) { @@ -429,7 +429,7 @@ public class MacOSXCGLContext extends GLContextImpl // FIXME: apparently the Apple extension doesn't require a custom memory allocator throw new GLException("Not yet implemented"); } - + @Override protected final void updateGLXProcAddressTable() { final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); @@ -520,11 +520,11 @@ public class MacOSXCGLContext extends GLContextImpl private int lastWidth=0, lastHeight=0; // allowing to detect size change private boolean needsSetContextPBuffer = false; private ShaderProgram gl3ShaderProgram = null; - + @Override public boolean isNSContext() { return true; } - + /** Only returns a valid NSView. If !NSView, return null and mark either pbuffer and FBO. */ private long getNSViewHandle(boolean[] isPBuffer, boolean[] isFBO) { final long nsViewHandle; @@ -558,11 +558,11 @@ public class MacOSXCGLContext extends GLContextImpl needsSetContextPBuffer = isPBuffer[0]; return nsViewHandle; } - + @Override public long create(long share, int ctp, int major, int minor) { long ctx = 0; - final NativeSurface surface = drawable.getNativeSurface(); + final NativeSurface surface = drawable.getNativeSurface(); final MacOSXCGLGraphicsConfiguration config = (MacOSXCGLGraphicsConfiguration) surface.getGraphicsConfiguration(); final GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); final long nsViewHandle; @@ -606,7 +606,7 @@ public class MacOSXCGLContext extends GLContextImpl if( !_fixedCaps.isPBuffer() && isPBuffer ) { throw new InternalError("handle is PBuffer, fixedCaps not: "+drawable); } - // determine on-/offscreen caps, since pformat is ambiguous + // determine on-/offscreen caps, since pformat is ambiguous _fixedCaps.setPBuffer( isPBuffer ); // exclusive _fixedCaps.setBitmap( false ); // n/a in our OSX impl. _fixedCaps.setOnscreen( !isFBO && !isPBuffer ); @@ -632,7 +632,7 @@ public class MacOSXCGLContext extends GLContextImpl // Thread.dumpStack(); } config.setChosenCapabilities(fixedCaps); - + final IntBuffer viewNotReady = Buffers.newDirectIntBuffer(1); // Try to allocate a context with this ctx = CGL.createContext(share, nsViewHandle, incompleteView, @@ -665,12 +665,12 @@ public class MacOSXCGLContext extends GLContextImpl *

                * Since NSOpenGLLayer creation requires this context for it's shared context creation, * this method attempts to acquire the surface and context lock with {@link #screenVSyncTimeout}/2 maximum wait time. - * If the surface and context lock could not be acquired, this runnable is being re-queued for later execution. + * If the surface and context lock could not be acquired, this runnable is being re-queued for later execution. *

                *

                * Hence this method blocks the main-thread only for a short period of time. *

                - */ + */ class AttachGLLayerCmd implements Runnable { final OffscreenLayerSurface ols; final long ctx; @@ -685,7 +685,7 @@ public class MacOSXCGLContext extends GLContextImpl long nsOpenGLLayer; /** Synchronized by instance's monitor */ boolean valid; - + AttachGLLayerCmd(OffscreenLayerSurface ols, long ctx, int shaderProgram, long pfmt, long pbuffer, int texID, boolean isOpaque, int width, int height) { this.ols = ols; this.ctx = ctx; @@ -699,23 +699,23 @@ public class MacOSXCGLContext extends GLContextImpl this.valid = false; this.nsOpenGLLayer = 0; } - + public final String contentToString() { return "valid "+valid+", size "+width+"x"+height+", ctx "+toHexString(ctx)+", opaque "+isOpaque+", texID "+texID+", pbuffer "+toHexString(pbuffer)+", nsOpenGLLayer "+toHexString(nsOpenGLLayer); } - + @Override public final String toString() { return "AttachGLLayerCmd["+contentToString()+"]"; } - + @Override public void run() { synchronized(this) { if( !valid ) { try { final int maxwait = screenVSyncTimeout/2000; // TO 1/2 of current screen-vsync in [ms] - final RecursiveLock surfaceLock = ols.getLock(); + final RecursiveLock surfaceLock = ols.getLock(); if( surfaceLock.tryLock( maxwait ) ) { try { if( MacOSXCGLContext.this.lock.tryLock( maxwait ) ) { @@ -752,19 +752,19 @@ public class MacOSXCGLContext extends GLContextImpl } } AttachGLLayerCmd attachGLLayerCmd = null; - + class DetachGLLayerCmd implements Runnable { final AttachGLLayerCmd cmd; - + DetachGLLayerCmd(AttachGLLayerCmd cmd) { this.cmd = cmd; } - + @Override public final String toString() { return "DetachGLLayerCmd["+cmd.contentToString()+"]"; } - + @Override public void run() { synchronized( cmd ) { @@ -777,7 +777,7 @@ public class MacOSXCGLContext extends GLContextImpl ols.detachSurfaceLayer(); } } catch(Throwable t) { - System.err.println("Catched Exception on thread "+getThreadName()); + System.err.println("Catched Exception on thread "+getThreadName()); t.printStackTrace(); } CGL.releaseNSOpenGLLayer(cmd.nsOpenGLLayer); @@ -790,27 +790,27 @@ public class MacOSXCGLContext extends GLContextImpl System.err.println("NSOpenGLLayer.Detach: Skipped "+toHexString(cmd.nsOpenGLLayer)+" - "+getThreadName()); } } - } + } } - + @Override public void associateDrawable(boolean bound) { backingLayerHost = NativeWindowFactory.getOffscreenLayerSurface(drawable.getNativeSurface(), true); - + if(DEBUG) { System.err.println("MaxOSXCGLContext.NSOpenGLImpl.associateDrawable: "+bound+", ctx "+toHexString(contextHandle)+ ", hasBackingLayerHost "+(null!=backingLayerHost)+", attachGLLayerCmd "+attachGLLayerCmd); // Thread.dumpStack(); - } - - if( bound ) { + } + + if( bound ) { if( null != backingLayerHost ) { final GLCapabilitiesImmutable chosenCaps; final long ctx; final int texID; final long pbufferHandle; final int gl3ShaderProgramName; - + // // handled layered surface // @@ -823,8 +823,8 @@ public class MacOSXCGLContext extends GLContextImpl pbufferHandle = 0; fbod.setSwapBufferContext(new GLFBODrawableImpl.SwapBufferContext() { public void swapBuffers(boolean doubleBuffered) { - MacOSXCGLContext.NSOpenGLImpl.this.swapBuffers(); - } } ) ; + MacOSXCGLContext.NSOpenGLImpl.this.swapBuffers(); + } } ) ; } else if( CGL.isNSOpenGLPixelBuffer(drawableHandle) ) { texID = 0; pbufferHandle = drawableHandle; @@ -847,19 +847,19 @@ public class MacOSXCGLContext extends GLContextImpl gl3ShaderProgramName = gl3ShaderProgram.program(); } else { gl3ShaderProgramName = 0; - } - + } + // All CALayer lifecycle ops are deferred on main-thread - attachGLLayerCmd = new AttachGLLayerCmd( - backingLayerHost, ctx, gl3ShaderProgramName, pixelFormat, pbufferHandle, texID, + attachGLLayerCmd = new AttachGLLayerCmd( + backingLayerHost, ctx, gl3ShaderProgramName, pixelFormat, pbufferHandle, texID, chosenCaps.isBackgroundOpaque(), lastWidth, lastHeight ); if(DEBUG) { System.err.println("MaxOSXCGLContext.NSOpenGLImpl.associateDrawable(true): "+attachGLLayerCmd); - } + } OSXUtil.RunOnMainThread(false, attachGLLayerCmd); - } else { // -> null == backingLayerHost + } else { // -> null == backingLayerHost lastWidth = drawable.getWidth(); - lastHeight = drawable.getHeight(); + lastHeight = drawable.getHeight(); boolean[] isPBuffer = { false }; boolean[] isFBO = { false }; CGL.setContextView(contextHandle, getNSViewHandle(isPBuffer, isFBO)); @@ -882,7 +882,7 @@ public class MacOSXCGLContext extends GLContextImpl final DetachGLLayerCmd dCmd = new DetachGLLayerCmd(cmd); if(DEBUG) { System.err.println("MaxOSXCGLContext.NSOpenGLImpl.associateDrawable(false): "+dCmd); - } + } OSXUtil.RunOnMainThread(false, dCmd); if( null != gl3ShaderProgram ) { gl3ShaderProgram.destroy(MacOSXCGLContext.this.gl.getGL3()); @@ -903,11 +903,11 @@ public class MacOSXCGLContext extends GLContextImpl needsSetContextPBuffer = false; CGL.setContextPBuffer(ctx, drawableHandle); if(DEBUG) { - System.err.println("NS.validateDrawableConfig bind pbuffer "+toHexString(drawableHandle)+" -> ctx "+toHexString(ctx)); + System.err.println("NS.validateDrawableConfig bind pbuffer "+toHexString(drawableHandle)+" -> ctx "+toHexString(ctx)); } } } - + /** Returns true if size has been updated, otherwise false (same size). */ private final boolean validateDrawableSizeConfig(long ctx) { final int width = drawable.getWidth(); @@ -916,13 +916,13 @@ public class MacOSXCGLContext extends GLContextImpl lastWidth = drawable.getWidth(); lastHeight = drawable.getHeight(); if(DEBUG) { - System.err.println("NS.validateDrawableConfig size changed"); + System.err.println("NS.validateDrawableConfig size changed"); } return true; } return false; } - + @Override public boolean copyImpl(long src, int mask) { CGL.copyContext(contextHandle, src, mask); @@ -975,7 +975,7 @@ public class MacOSXCGLContext extends GLContextImpl // CGL.setContextPBuffer(contextHandle, 0); // doesn't work, i.e. not taking nil return true; } - + @Override public boolean setSwapInterval(int interval) { final AttachGLLayerCmd cmd = attachGLLayerCmd; @@ -1004,7 +1004,7 @@ public class MacOSXCGLContext extends GLContextImpl if(DEBUG) { System.err.println("CGL setSwapInterval: "+interval); } CGL.setSwapInterval(contextHandle, interval); } - + private int skipSync=0; /** TODO: Remove after discussion private boolean perfIterReset = false; @@ -1014,7 +1014,7 @@ public class MacOSXCGLContext extends GLContextImpl private long frameXS = 0; private long lastFrameStart = 0; */ - + @Override public boolean swapBuffers() { final AttachGLLayerCmd cmd = attachGLLayerCmd; @@ -1026,7 +1026,7 @@ public class MacOSXCGLContext extends GLContextImpl // allowing to update the texture IDs ASAP. skipSync = 10; } - + final boolean res; final int texID; final boolean valid; @@ -1054,19 +1054,19 @@ public class MacOSXCGLContext extends GLContextImpl final long lastFramePeriod0 = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) - lastFrameStart; gl.glFinish(); // Require to finish previous GL rendering to give CALayer proper result final long lastFramePeriod1 = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) - lastFrameStart; - - // If v-sync is disabled, frames will be drawn as quickly as possible w/o delay, + + // If v-sync is disabled, frames will be drawn as quickly as possible w/o delay, // while still synchronizing w/ CALayer. // If v-sync is enabled wait until next swap interval (v-sync). CGL.waitUntilNSOpenGLLayerIsReady(cmd.nsOpenGLLayer, vsyncTimeout); final long lastFramePeriodX = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) - lastFrameStart; - + final long finishGL = lastFramePeriod1 - lastFramePeriod0; final long waitGL = lastFramePeriodX - lastFramePeriod1; finishGLS += finishGL; waitGLS += waitGL; frameXS += lastFramePeriodX; - + System.err.println("XXX["+perfIter+"] TO "+vsyncTimeout/1000+" ms, "+ "lFrame0 "+lastFramePeriod0/1000+" ms, "+ "lFrameX "+lastFramePeriodX/1000+" / "+frameXS/1000+" ~"+(frameXS/perfIter)/1000.0+" ms, "+ @@ -1080,8 +1080,8 @@ public class MacOSXCGLContext extends GLContextImpl // FIXME: IMHO this synchronization should be implicitly performed via 'CGL.flushBuffer(contextHandle)' above, // in case this will be determined a driver bug - use a QUIRK entry in GLRendererQuirks! gl.glFinish(); - - // If v-sync is disabled, frames will be drawn as quickly as possible w/o delay, + + // If v-sync is disabled, frames will be drawn as quickly as possible w/o delay, // while still synchronizing w/ CALayer. // If v-sync is enabled wait until next swap interval (v-sync). CGL.waitUntilNSOpenGLLayerIsReady(cmd.nsOpenGLLayer, vsyncTimeout); @@ -1093,7 +1093,7 @@ public class MacOSXCGLContext extends GLContextImpl CGL.setNSOpenGLLayerNeedsDisplayFBO(cmd.nsOpenGLLayer, texID); } else { // trigger CALayer to update incl. possible surface change (new pbuffer handle) - CGL.setNSOpenGLLayerNeedsDisplayPBuffer(cmd.nsOpenGLLayer, drawable.getHandle()); + CGL.setNSOpenGLLayerNeedsDisplayPBuffer(cmd.nsOpenGLLayer, drawable.getHandle()); } // lastFrameStart = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()); } @@ -1137,8 +1137,8 @@ public class MacOSXCGLContext extends GLContextImpl if (0 != ctx) { GLCapabilities fixedCaps = MacOSXCGLGraphicsConfiguration.CGLPixelFormat2GLCapabilities(pixelFormat); fixedCaps = GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(fixedCaps, chosenCaps.isBackgroundOpaque()); - { // determine on-/offscreen caps, since pformat is ambiguous - fixedCaps.setFBO( false ); // n/a for CGLImpl + { // determine on-/offscreen caps, since pformat is ambiguous + fixedCaps.setFBO( false ); // n/a for CGLImpl fixedCaps.setPBuffer( fixedCaps.isPBuffer() && !chosenCaps.isOnscreen() ); fixedCaps.setBitmap( false ); // n/a in our OSX impl. fixedCaps.setOnscreen( !fixedCaps.isPBuffer() ); @@ -1153,7 +1153,7 @@ public class MacOSXCGLContext extends GLContextImpl if (res != CGL.kCGLNoError) { throw new GLException("Error code " + res + " while attaching context to pbuffer"); } - } + } } } finally { CGL.CGLDestroyPixelFormat(pixelFormat); @@ -1224,7 +1224,7 @@ public class MacOSXCGLContext extends GLContextImpl } */ return true; } - + @Override public boolean setSwapInterval(int interval) { final IntBuffer lval = Buffers.newDirectIntBuffer(1); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java index 4bd7bc994..bb36a7219 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java @@ -105,7 +105,7 @@ public abstract class MacOSXCGLDrawable extends GLDrawableImpl { @Override protected void setRealizedImpl() { } - + @Override protected void associateContext(GLContext ctx, boolean bound) { // NOTE: we need to keep track of the created contexts in order to @@ -123,14 +123,14 @@ public abstract class MacOSXCGLDrawable extends GLDrawableImpl { } else { i++; } - } + } } - } + } } - + @Override protected final void swapBuffersImpl(boolean doubleBuffered) { - if(doubleBuffered) { + if(doubleBuffered) { synchronized (createdContexts) { for(int i=0; i libsGL = new ArrayList(); libsGL.add("/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib"); libsGL.add("GL"); - libsList.add(libsGL); + libsList.add(libsGL); return libsList; } - + @Override public final List getToolGetProcAddressFuncNameList() { - return null; + return null; /** OSX manual says: NSImage use is discouraged List res = new ArrayList(); res.add("GetProcAddress"); // dummy @@ -59,7 +59,7 @@ public final class MacOSXCGLDynamicLibraryBundleInfo extends DesktopGLDynamicLib public final long toolGetProcAddress(long toolGetProcAddressHandle, String funcName) { return 0; /** OSX manual says: NSImage use is discouraged - return CGL.getProcAddress(glFuncName); // manual implementation + return CGL.getProcAddress(glFuncName); // manual implementation */ } } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java index 5eb11c6a4..535c4d2d3 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ @@ -54,7 +54,7 @@ import com.jogamp.nativewindow.MutableGraphicsConfiguration; public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable { - MacOSXCGLGraphicsConfiguration(AbstractGraphicsScreen screen, + MacOSXCGLGraphicsConfiguration(AbstractGraphicsScreen screen, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested) { super(screen, capsChosen, capsRequested); } @@ -71,10 +71,10 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration // MacOSXGraphicsDevice osxDevice = sharedResource.getDevice(); return new ArrayList(0); } - + static final IntBuffer cglInternalAttributeToken = Buffers.newDirectIntBuffer(new int[] { CGL.kCGLPFAOpenGLProfile, // >= lion - CGL.NSOpenGLPFAAccelerated, // query only (prefer accelerated, but allow non accelerated), ignored for createPixelformat + CGL.NSOpenGLPFAAccelerated, // query only (prefer accelerated, but allow non accelerated), ignored for createPixelformat CGL.NSOpenGLPFANoRecovery, CGL.kCGLPFAColorFloat, CGL.NSOpenGLPFAPixelBuffer, @@ -96,13 +96,13 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration for (int idx = 0; idx < len; idx++) { final int attr = attrToken.get(idx+off); switch (attr) { - case CGL.kCGLPFAOpenGLProfile: + case CGL.kCGLPFAOpenGLProfile: ivalues.put(idx, MacOSXCGLContext.GLProfile2CGLOGLProfileValue(ctp, major, minor)); break; case CGL.NSOpenGLPFANoRecovery: ivalues.put(idx, caps.getHardwareAccelerated() ? 1 : 0); break; - + case CGL.kCGLPFAColorFloat: // ivalues.put(idx, ( !caps.isOnscreen() && caps.isPBuffer() && caps.getPbufferFloatingPointBuffers() ) ? 1 : 0); ivalues.put(idx, 0); @@ -160,7 +160,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration if ( !MacOSXCGLContext.isLionOrLater ) { // no OpenGLProfile attrToken.position(1); - } + } final IntBuffer ivalues = GLCapabilities2NSAttribList(attrToken, caps, ctp, major, minor); return CGL.createPixelFormat(attrToken, attrToken.remaining(), ivalues); } @@ -174,7 +174,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration final IntBuffer attrs = Buffers.newDirectIntBuffer(256); int i = 0; if(MacOSXCGLContext.isLionOrLater) { - attrs.put(i++, CGL.kCGLPFAOpenGLProfile); + attrs.put(i++, CGL.kCGLPFAOpenGLProfile); attrs.put(i++, MacOSXCGLContext.GLProfile2CGLOGLProfileValue(ctp, major, minor)); } /** @@ -222,8 +222,8 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration } return fmt.get(0); } - - static GLCapabilities CGLPixelFormat2GLCapabilities(long pixelFormat) { + + static GLCapabilities CGLPixelFormat2GLCapabilities(long pixelFormat) { return PixelFormat2GLCapabilities(null, pixelFormat, false); } @@ -235,7 +235,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration off = 1; } else { off = 0; - } + } attrToken.position(off); final int len = attrToken.remaining(); final IntBuffer ivalues = Buffers.newDirectIntBuffer(len); @@ -243,7 +243,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration // On this platform the pixel format is associated with the // context and not the drawable. However it's a reasonable // approximation to just store the chosen pixel format up in the - // NativeSurface's AbstractGraphicsConfiguration, + // NativeSurface's AbstractGraphicsConfiguration, // since the public API doesn't provide for a different GLCapabilities per context. // Note: These restrictions of the platform's API might be considered as a bug anyways. @@ -253,7 +253,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration } else { CGL.CGLQueryPixelFormat(pixelFormat, attrToken, len, ivalues); } - + if(null == glp && MacOSXCGLContext.isLionOrLater) { // pre-scan for OpenGL Profile for (int i = 0; i < len; i++) { @@ -265,11 +265,11 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration break; case CGL.kCGLOGLPVersion_Legacy: glp = GLProfile.get(GLProfile.GL2); - break; + break; default: throw new RuntimeException("Unhandled OSX OpenGL Profile: 0x"+Integer.toHexString(ivalue)); } - } + } } } if(null == glp) { @@ -284,7 +284,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration case CGL.NSOpenGLPFAAccelerated: caps.setHardwareAccelerated(ivalue != 0); break; - + case CGL.kCGLPFAColorFloat: // caps.setPbufferFloatingPointBuffers(ivalue != 0); break; @@ -346,7 +346,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration } } caps.setAlphaBits(alphaBits); - + return caps; } } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java index 3bbba2c52..e761be7b7 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -56,13 +56,13 @@ public class MacOSXCGLGraphicsConfigurationFactory extends GLGraphicsConfigurati static void registerFactory() { GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice.class, GLCapabilitiesImmutable.class, new MacOSXCGLGraphicsConfigurationFactory()); } - private MacOSXCGLGraphicsConfigurationFactory() { + private MacOSXCGLGraphicsConfigurationFactory() { } protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { - + if (absScreen == null) { throw new IllegalArgumentException("AbstractGraphicsScreen is null"); } @@ -78,7 +78,7 @@ public class MacOSXCGLGraphicsConfigurationFactory extends GLGraphicsConfigurati if (chooser != null && !(chooser instanceof GLCapabilitiesChooser)) { throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilitiesChooser objects"); } - + return chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested, (GLCapabilitiesChooser)chooser, absScreen, false); } @@ -91,7 +91,7 @@ public class MacOSXCGLGraphicsConfigurationFactory extends GLGraphicsConfigurati } final AbstractGraphicsDevice device = absScreen.getDevice(); capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, GLDrawableFactory.getDesktopFactory(), device); - + return new MacOSXCGLGraphicsConfiguration(absScreen, (GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested); } } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java index 4e791cb5f..f6e8b8fa3 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java @@ -90,7 +90,7 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { public GLContext createContext(GLContext shareWith) { return new MacOSXCGLContext(this, shareWith); } - + protected int getTextureTarget() { return pBufferTexTarget; } protected int getTextureWidth() { return pBufferTexWidth; } protected int getTextureHeight() { return pBufferTexHeight; } @@ -101,7 +101,7 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable { if (0 != pBuffer) { synchronized (createdContexts) { for(int i=0; i ref = createdContexts.get(i); + final WeakReference ref = createdContexts.get(i); final MacOSXCGLContext ctx = ref.get(); if (ctx != null) { ctx.detachPBuffer(); diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java index edf9b7c84..c08259665 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -59,7 +59,7 @@ import jogamp.opengl.macosx.cgl.MacOSXCGLGraphicsConfiguration; public class MacOSXAWTCGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFactory { public static void registerFactory() { GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, GLCapabilitiesImmutable.class, new MacOSXAWTCGLGraphicsConfigurationFactory()); - } + } private MacOSXAWTCGLGraphicsConfigurationFactory() { } diff --git a/src/jogl/classes/jogamp/opengl/util/GLArrayHandler.java b/src/jogl/classes/jogamp/opengl/util/GLArrayHandler.java index 1a4ca345b..810a9286b 100644 --- a/src/jogl/classes/jogamp/opengl/util/GLArrayHandler.java +++ b/src/jogl/classes/jogamp/opengl/util/GLArrayHandler.java @@ -37,22 +37,22 @@ import javax.media.opengl.*; */ public interface GLArrayHandler { - + /** - * if bind is true and the data uses VBO, + * if bind is true and the data uses VBO, * the latter will be bound and data written to the GPU if required. *

                * If bind is false and the data uses VBO, * the latter will be unbound. *

                - * + * * @param gl current GL object - * @param bind true if VBO shall be bound and data written, + * @param bind true if VBO shall be bound and data written, * otherwise clear VBO binding. - * @return true if data uses VBO and action was performed, otherwise false + * @return true if data uses VBO and action was performed, otherwise false */ public boolean bindBuffer(GL gl, boolean bind); - + /** * Implementation shall enable or disable the array state. *

                @@ -60,23 +60,23 @@ public interface GLArrayHandler { * implementation shall synchronize the data with the GPU * and associate the data with the array. *

                - * + * * @param gl current GL object * @param enable true if array shall be enabled, otherwise false. - * @param ext extension object allowing passing of an implementation detail + * @param ext extension object allowing passing of an implementation detail */ public void enableState(GL gl, boolean enable, Object ext); - + /** - * Supporting interleaved arrays, where sub handlers may handle + * Supporting interleaved arrays, where sub handlers may handle * the array state and the master handler the buffer consistency. - * + * * @param handler the sub handler * @throws UnsupportedOperationException if this array handler does not support interleaved arrays */ public void addSubHandler(GLArrayHandlerFlat handler) throws UnsupportedOperationException; public void setSubArrayVBOName(int vboName); - + } diff --git a/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerFlat.java b/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerFlat.java index 4a8f40608..179142fee 100644 --- a/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerFlat.java +++ b/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerFlat.java @@ -39,21 +39,21 @@ public interface GLArrayHandlerFlat { /** * Implementation shall associate the data with the array - * + * * @param gl current GL object - * @param ext extension object allowing passing of an implementation detail + * @param ext extension object allowing passing of an implementation detail */ public void syncData(GL gl, Object ext); - + /** * Implementation shall enable or disable the array state. - * + * * @param gl current GL object * @param enable true if array shall be enabled, otherwise false. - * @param ext extension object allowing passing of an implementation detail + * @param ext extension object allowing passing of an implementation detail */ - public void enableState(GL gl, boolean enable, Object ext); - + public void enableState(GL gl, boolean enable, Object ext); + public GLArrayDataWrapper getData(); } diff --git a/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerInterleaved.java b/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerInterleaved.java index 98f711b8e..5f9b25530 100644 --- a/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerInterleaved.java +++ b/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerInterleaved.java @@ -36,8 +36,8 @@ import javax.media.opengl.GL; import com.jogamp.opengl.util.GLArrayDataEditable; /** - * Interleaved fixed function arrays, i.e. where this buffer data - * represents many arrays. + * Interleaved fixed function arrays, i.e. where this buffer data + * represents many arrays. */ public class GLArrayHandlerInterleaved extends GLVBOArrayHandler implements GLArrayHandler { private List subArrays = new ArrayList(); @@ -45,13 +45,13 @@ public class GLArrayHandlerInterleaved extends GLVBOArrayHandler implements GLAr public GLArrayHandlerInterleaved(GLArrayDataEditable ad) { super(ad); } - + public final void setSubArrayVBOName(int vboName) { for(int i=0; i{@link #setTextureTarget(int)} *
              • {@link EGLMediaPlayerImpl#setEGLTexImageAttribs(boolean, boolean)}.
              • *
              - * + * *

              * See {@link GLMediaPlayer}. *

              @@ -75,21 +75,21 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { protected volatile State state; private Object stateLock = new Object(); - + protected int textureCount; protected int textureTarget; protected int textureFormat; - protected int textureInternalFormat; + protected int textureInternalFormat; protected int textureType; protected int texUnit; - - + + protected int[] texMinMagFilter = { GL.GL_NEAREST, GL.GL_NEAREST }; protected int[] texWrapST = { GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE }; - + /** User requested URI stream location. */ protected URI streamLoc = null; - /** + /** * In case {@link #streamLoc} is a {@link GLMediaPlayer#CameraInputScheme}, * {@link #cameraPath} holds the URI's path portion * as parsed in {@link #initStream(URI, int, int, int)}. @@ -98,10 +98,10 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { protected String cameraPath = null; /** Optional camera properties, see {@link #cameraPath}. */ protected Map cameraProps = null; - + protected volatile float playSpeed = 1.0f; protected float audioVolume = 1.0f; - + /** Shall be set by the {@link #initStreamImpl(int, int)} method implementation. */ protected int vid = GLMediaPlayer.STREAM_ID_AUTO; /** Shall be set by the {@link #initStreamImpl(int, int)} method implementation. */ @@ -130,20 +130,20 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { protected String acodec = unknown; /** Shall be set by the {@link #initStreamImpl(int, int)} method implementation. */ protected String vcodec = unknown; - + protected volatile int decodedFrameCount = 0; protected int presentedFrameCount = 0; protected int displayedFrameCount = 0; protected volatile int video_pts_last = 0; - + /** See {@link #getAudioSink()}. Set by implementation if used from within {@link #initStreamImpl(int, int)}! */ protected AudioSink audioSink = null; protected boolean audioSinkPlaySpeedSet = false; - + /** System Clock Reference (SCR) of first audio PTS at start time. */ private long audio_scr_t0 = 0; private boolean audioSCR_reset = true; - + /** System Clock Reference (SCR) of first video frame at start time. */ private long video_scr_t0 = 0; /** System Clock Reference (SCR) PTS offset, i.e. first video PTS at start time. */ @@ -152,7 +152,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { private float video_dpts_cum = 0; /** Cumulative video frames. */ private int video_dpts_count = 0; - /** Number of min frame count required for video cumulative sync. */ + /** Number of min frame count required for video cumulative sync. */ private static final int VIDEO_DPTS_NUM = 20; /** Cumulative coefficient, value {@value}. */ private static final float VIDEO_DPTS_COEFF = 0.7943282f; // (float) Math.exp(Math.log(0.01) / VIDEO_DPTS_NUM); @@ -160,7 +160,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { private static final int VIDEO_DPTS_MAX = 5000; // 5s max diff /** Trigger video PTS reset with given cause as bitfield. */ private boolean videoSCR_reset = false; - + protected TextureFrame[] videoFramesOrig = null; protected Ringbuffer videoFramesFree = null; protected Ringbuffer videoFramesDecoded = null; @@ -177,42 +177,42 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { this.textureTarget=GL.GL_TEXTURE_2D; this.textureFormat = GL.GL_RGBA; this.textureInternalFormat = GL.GL_RGBA; - this.textureType = GL.GL_UNSIGNED_BYTE; + this.textureType = GL.GL_UNSIGNED_BYTE; this.texUnit = 0; this.state = State.Uninitialized; } @Override public final void setTextureUnit(int u) { texUnit = u; } - + @Override public final int getTextureUnit() { return texUnit; } - + @Override public final int getTextureTarget() { return textureTarget; } - + @Override public final int getTextureCount() { return textureCount; } - + protected final void setTextureTarget(int target) { textureTarget=target; } - protected final void setTextureFormat(int internalFormat, int format) { - textureInternalFormat=internalFormat; - textureFormat=format; - } + protected final void setTextureFormat(int internalFormat, int format) { + textureInternalFormat=internalFormat; + textureFormat=format; + } protected final void setTextureType(int t) { textureType=t; } public final void setTextureMinMagFilter(int[] minMagFilter) { texMinMagFilter[0] = minMagFilter[0]; texMinMagFilter[1] = minMagFilter[1];} public final int[] getTextureMinMagFilter() { return texMinMagFilter; } - + public final void setTextureWrapST(int[] wrapST) { texWrapST[0] = wrapST[0]; texWrapST[1] = wrapST[1];} - public final int[] getTextureWrapST() { return texWrapST; } - + public final int[] getTextureWrapST() { return texWrapST; } + private final void checkGLInit() { if(State.Uninitialized == state || State.Initialized == state ) { throw new IllegalStateException("GL not initialized: "+this); - } + } } - + @Override public String getRequiredExtensionsShaderStub() throws IllegalStateException { checkGLInit(); @@ -221,24 +221,24 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } return ""; } - + @Override public String getTextureSampler2DType() throws IllegalStateException { checkGLInit(); switch(textureTarget) { case GL.GL_TEXTURE_2D: - case GL2.GL_TEXTURE_RECTANGLE: + case GL2.GL_TEXTURE_RECTANGLE: return TextureSequence.sampler2D; case GLES2.GL_TEXTURE_EXTERNAL_OES: return TextureSequence.samplerExternalOES; default: - throw new GLException("Unsuported texture target: "+toHexString(textureTarget)); + throw new GLException("Unsuported texture target: "+toHexString(textureTarget)); } } - + /** * {@inheritDoc} - * + * * This implementation simply returns the build-in function name of texture2D, * if not overridden by specialization. */ @@ -247,31 +247,31 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { checkGLInit(); return "texture2D"; } - + /** * {@inheritDoc} - * - * This implementation simply returns an empty string since it's using + * + * This implementation simply returns an empty string since it's using * the build-in function texture2D, * if not overridden by specialization. */ @Override public String getTextureLookupFragmentShaderImpl() throws IllegalStateException { checkGLInit(); - return ""; + return ""; } - + @Override public final int getDecodedFrameCount() { return decodedFrameCount; } - + @Override public final int getPresentedFrameCount() { return presentedFrameCount; } - + @Override public final int getVideoPTS() { return video_pts_last; } - + @Override - public final int getAudioPTS() { + public final int getAudioPTS() { if( State.Uninitialized != state ) { return getAudioPTSImpl(); } @@ -285,10 +285,10 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { return 0; } } - + @Override public final State getState() { return state; } - + @Override public final State play() { synchronized( stateLock ) { @@ -310,7 +310,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } } protected abstract boolean playImpl(); - + @Override public final State pause(boolean flush) { return pauseImpl(flush, 0); @@ -337,7 +337,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } } protected abstract boolean pauseImpl(); - + @Override public final State destroy(GL gl) { return destroyImpl(gl, 0); @@ -354,7 +354,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } } protected abstract void destroyImpl(GL gl); - + @Override public final int seek(int msec) { synchronized( stateLock ) { @@ -383,12 +383,12 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } } protected abstract int seekImpl(int msec); - + @Override public final float getPlaySpeed() { return playSpeed; } - + @Override public final boolean setPlaySpeed(float rate) { synchronized( stateLock ) { @@ -410,18 +410,18 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { return res; } } - /** + /** * Override if not using AudioSink, or AudioSink's {@link AudioSink#setPlaySpeed(float)} is not sufficient! *

              - * AudioSink shall respect !audioSinkPlaySpeedSet to determine data_size + * AudioSink shall respect !audioSinkPlaySpeedSet to determine data_size * at {@link AudioSink#enqueueData(com.jogamp.opengl.util.av.AudioSink.AudioFrame)}. - *

              + *

              */ protected boolean setPlaySpeedImpl(float rate) { if( null != audioSink ) { audioSinkPlaySpeedSet = audioSink.setPlaySpeed(rate); } - // still true, even if audioSink rejects command since we deal w/ video sync + // still true, even if audioSink rejects command since we deal w/ video sync // and AudioSink w/ audioSinkPlaySpeedSet at enqueueData(..). return true; } @@ -431,7 +431,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { getAudioVolumeImpl(); return audioVolume; } - /** + /** * Override if not using AudioSink, or AudioSink's {@link AudioSink#getVolume()} is not sufficient! */ protected void getAudioVolumeImpl() { @@ -439,7 +439,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { audioVolume = audioSink.getVolume(); } } - + @Override public boolean setAudioVolume(float v) { synchronized( stateLock ) { @@ -460,7 +460,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { return res; } } - /** + /** * Override if not using AudioSink, or AudioSink's {@link AudioSink#setVolume(float)} is not sufficient! */ protected boolean setAudioVolumeImpl(float v) { @@ -470,7 +470,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { // still true, even if audioSink rejects command .. return true; } - + @Override public final void initStream(URI streamLoc, int vid, int aid, int reqTextureCount) throws IllegalStateException, IllegalArgumentException { synchronized( stateLock ) { @@ -490,7 +490,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } decodedFrameCount = 0; presentedFrameCount = 0; - displayedFrameCount = 0; + displayedFrameCount = 0; this.streamLoc = streamLoc; // Pre-parse for camera-input scheme @@ -500,7 +500,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { if( null != streamLocScheme && streamLocScheme.equals(CameraInputScheme) ) { final String rawPath = streamLoc.getRawPath(); if( null != rawPath && rawPath.length() > 0 ) { - // cut-off root fwd-slash + // cut-off root fwd-slash cameraPath = rawPath.substring(1); final URIQueryProps props = URIQueryProps.create(streamLoc, ';'); cameraProps = props.getProperties(); @@ -508,7 +508,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { throw new IllegalArgumentException("Camera path is empty: "+streamLoc.toString()); } } - + this.vid = vid; this.aid = aid; if (this.streamLoc != null) { @@ -519,7 +519,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { /** * Implementation shall set the following set of data here * @see #vid - * @see #aid + * @see #aid * @see #width * @see #height * @see #fps @@ -530,7 +530,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { * @see #vcodec */ protected abstract void initStreamImpl(int vid, int aid) throws Exception; - + @Override public final StreamException getStreamException() { synchronized( stateLock ) { @@ -541,26 +541,26 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } } } - + @Override public final void initGL(GL gl) throws IllegalStateException, StreamException, GLException { synchronized( stateLock ) { if(State.Initialized != state ) { throw new IllegalStateException("Stream not in state initialized: "+this); - } + } final StreamException streamInitErr = streamWorker.getStreamErr(); if( null != streamInitErr ) { streamWorker = null; // already terminated! destroy(null); throw streamInitErr; } - try { + try { if( STREAM_ID_NONE != vid ) { removeAllTextureFrames(gl); initGLImpl(gl); if(DEBUG) { System.err.println("initGLImpl.X "+this); - } + } videoFramesOrig = createTexFrames(gl, textureCount); videoFramesFree = new LFRingbuffer(videoFramesOrig); videoFramesDecoded = new LFRingbuffer(TextureFrame[].class, textureCount); @@ -583,7 +583,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } } } - /** + /** * Shall initialize all GL related resources, if not audio-only. *

              * Shall also take care of {@link AudioSink} initialization if appropriate. @@ -593,8 +593,8 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { * @throws GLException */ protected abstract void initGLImpl(GL gl) throws IOException, GLException; - - /** + + /** * Returns the validated number of textures to be handled. *

              * Default is {@link #TEXTURE_COUNT_MIN} minimum textures. @@ -606,7 +606,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { protected int validateTextureCount(int desiredTextureCount) { return desiredTextureCount < TEXTURE_COUNT_MIN ? TEXTURE_COUNT_MIN : desiredTextureCount; } - + protected TextureFrame[] createTexFrames(GL gl, final int count) { final int[] texNames = new int[count]; gl.glGenTextures(count, texNames, 0); @@ -621,7 +621,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { return texFrames; } protected abstract TextureFrame createTexImage(GL gl, int texName); - + protected final Texture createTexImageImpl(GL gl, int texName, int tWidth, int tHeight) { if( 0 > texName ) { throw new RuntimeException("TextureName "+toHexString(texName)+" invalid."); @@ -661,19 +661,19 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } } gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_MIN_FILTER, texMinMagFilter[0]); - gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_MAG_FILTER, texMinMagFilter[1]); + gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_MAG_FILTER, texMinMagFilter[1]); gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_WRAP_S, texWrapST[0]); gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_WRAP_T, texWrapST[1]); - + return com.jogamp.opengl.util.texture.TextureIO.newTexture( texName, textureTarget, tWidth, tHeight, width, height, - !isInGLOrientation); + !isInGLOrientation); } - + protected void destroyTexFrame(GL gl, TextureFrame frame) { - frame.getTexture().destroy(gl); + frame.getTexture().destroy(gl); } @Override @@ -683,7 +683,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } return lastFrame; } - + private final void removeAllTextureFrames(GL gl) { final TextureFrame[] texFrames = videoFramesOrig; videoFramesOrig = null; @@ -699,14 +699,14 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } texFrames[i] = null; } - System.err.println(Thread.currentThread().getName()+"> Clear TexFrame["+i+"]: "+frame+" -> null"); - } + System.err.println(Thread.currentThread().getName()+"> Clear TexFrame["+i+"]: "+frame+" -> null"); + } } } - + protected TextureFrame cachedFrame = null; protected long lastTimeMillis = 0; - + @Override public final TextureFrame getNextTexture(GL gl) throws IllegalStateException { synchronized( stateLock ) { @@ -750,7 +750,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } else { d_apts = 0; } - + final int frame_period_last = video_pts - video_pts_last; // rendering loop interrupted ? if( videoSCR_reset || frame_period_last > frame_duration*10 ) { videoSCR_reset = false; @@ -782,7 +782,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { cachedFrame = nextFrame; nextFrame = null; } else if ( !droppedFrame && dt < -maxVideoDelay && videoFramesDecoded.size() > 0 ) { - // only drop if prev. frame has not been dropped and + // only drop if prev. frame has not been dropped and // frame is too late and one decoded frame is already available. dropFrame = true; } @@ -791,7 +791,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { System.err.println( "AV_: dT "+(currentTimeMillis-lastTimeMillis)+", "+ getPerfStringImpl( video_scr, video_pts, d_vpts, audio_scr, audio_pts, d_apts, - video_dpts_avg_diff ) + + video_dpts_avg_diff ) + ", avg dpy-fps "+avg_dpy_duration+" ms/f, maxD "+maxVideoDelay+" ms, "+_nextFrame+", playCached " + playCached + ", dropFrame "+dropFrame); } } @@ -803,7 +803,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { lastFrame = nextFrame; videoFramesFree.putBlocking(_lastFrame); } - } else if( DEBUG ) { + } else if( DEBUG ) { final int video_pts = lastFrame.getPTS(); final int audio_pts = getAudioPTSImpl(); final int audio_scr = (int) ( ( currentTimeMillis - audio_scr_t0 ) * playSpeed ); @@ -835,25 +835,25 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { * Audio frames, i.e. {@link AudioSink.AudioFrame}, shall be handled in the process. *

              * Video frames shall be ignored, if {@link #getVID()} is {@link #STREAM_ID_NONE}. - *

              + *

              *

              * Audio frames shall be ignored, if {@link #getAID()} is {@link #STREAM_ID_NONE}. *

              *

              * Method may be invoked on the StreamWorker decoding thread. - *

              + *

              *

              * Implementation shall care of OpenGL synchronization as required, e.g. glFinish()/glFlush()! *

              - * @param gl valid and current GL instance, shall be null for audio only. + * @param gl valid and current GL instance, shall be null for audio only. * @param nextFrame the {@link TextureFrame} to store the video PTS and texture data, * shall be null for audio only. * @return the last processed video PTS value, maybe {@link TimeFrameI#INVALID_PTS} if video frame is invalid or n/a. - * Will be {@link TimeFrameI#END_OF_STREAM_PTS} if end of stream reached. + * Will be {@link TimeFrameI#END_OF_STREAM_PTS} if end of stream reached. */ protected abstract int getNextTextureImpl(GL gl, TextureFrame nextFrame); - - /** + + /** * {@inheritDoc} *

              * Note: All {@link AudioSink} operations are performed from {@link GLMediaPlayerImpl}, @@ -866,8 +866,8 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { */ @Override public final AudioSink getAudioSink() { return audioSink; } - - /** + + /** * To be called from implementation at 1st PTS after start * w/ current pts value in milliseconds. * @param audio_scr_t0 @@ -908,10 +908,10 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { private final int getVideoDPTSAvg() { return (int) ( video_dpts_cum * (1.0f - VIDEO_DPTS_COEFF) + 0.5f ); } - + private final void newFrameAvailable(TextureFrame frame, long currentTimeMillis) { decodedFrameCount++; - if( 0 == frame.getDuration() ) { // patch frame duration if not set already + if( 0 == frame.getDuration() ) { // patch frame duration if not set already frame.setDuration( (int) frame_duration ); } synchronized(eventListenersLock) { @@ -920,38 +920,38 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } } } - + class StreamWorker extends Thread { private volatile boolean isRunning = false; private volatile boolean isActive = false; private volatile boolean isBlocked = false; - + private volatile boolean shallPause = true; private volatile boolean shallStop = false; - + private volatile StreamException streamErr = null; private volatile GLContext sharedGLCtx = null; private boolean sharedGLCtxCurrent = false; private GLDrawable dummyDrawable = null; - - /** - * Starts this daemon thread, + + /** + * Starts this daemon thread, * which initializes the stream first via {@link GLMediaPlayerImpl#initStreamImpl(int, int)} first. *

              * After stream initialization, this thread pauses! *

              - **/ + **/ StreamWorker() { setDaemon(true); start(); } - + private void makeCurrent(GLContext ctx) { if( GLContext.CONTEXT_NOT_CURRENT >= ctx.makeCurrent() ) { throw new GLException("Couldn't make ctx current: "+ctx); } } - + private void destroySharedGL() { if( null != sharedGLCtx ) { if( sharedGLCtx.isCreated() ) { @@ -963,16 +963,16 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { gle.printStackTrace(); } } - sharedGLCtx = null; + sharedGLCtx = null; } if( null != dummyDrawable ) { final AbstractGraphicsDevice device = dummyDrawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice(); dummyDrawable.setRealized(false); dummyDrawable = null; device.close(); - } + } } - + public synchronized void initGL(GL gl) { final GLContext glCtx = gl.getContext(); final boolean glCtxCurrent = glCtx.isCurrent(); @@ -1013,7 +1013,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { while( !isActive ) { this.notify(); // wake-up pause-block try { - this.wait(); // wait until resumed + this.wait(); // wait until resumed } catch (InterruptedException e) { e.printStackTrace(); } @@ -1041,12 +1041,12 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } public boolean isRunning() { return isRunning; } public boolean isActive() { return isActive; } - public StreamException getStreamErr() { return streamErr; } - + public StreamException getStreamErr() { return streamErr; } + public void run() { setName(getName()+"-StreamWorker_"+StreamWorkerInstanceId); StreamWorkerInstanceId++; - + synchronized ( this ) { isRunning = true; try { @@ -1061,7 +1061,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { return; // end of thread! } // also initializes width, height, .. etc } - + while( !shallStop ){ if( shallPause ) { synchronized ( this ) { @@ -1100,7 +1100,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } } } - + if( !shallStop ) { TextureFrame nextFrame = null; try { @@ -1121,7 +1121,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { Thread.sleep(STREAM_WORKER_DELAY); } if( !videoFramesDecoded.put(nextFrame) ) { - throw new InternalError("XXX: free "+videoFramesFree+", decoded "+videoFramesDecoded+", "+GLMediaPlayerImpl.this); + throw new InternalError("XXX: free "+videoFramesFree+", decoded "+videoFramesDecoded+", "+GLMediaPlayerImpl.this); } newFrameAvailable(nextFrame, Platform.currentTimeMillis()); nextFrame = null; @@ -1170,10 +1170,10 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { this.notify(); // wake-up doStop() } } - } - static int StreamWorkerInstanceId = 0; + } + static int StreamWorkerInstanceId = 0; private StreamWorker streamWorker = null; - + protected final int addStateEventMask(int event_mask, State newState) { if( state != newState ) { switch( newState ) { @@ -1193,7 +1193,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } return event_mask; } - + protected final void attributesUpdated(int event_mask) { if( 0 != event_mask ) { final long now = Platform.currentTimeMillis(); @@ -1204,7 +1204,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { } } } - + protected final void changeState(int event_mask, State newState) { event_mask = addStateEventMask(event_mask, newState); if( 0 != event_mask ) { @@ -1212,9 +1212,9 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { attributesUpdated( event_mask ); } } - - protected final void updateAttributes(int vid, int aid, int width, int height, int bps_stream, - int bps_video, int bps_audio, float fps, + + protected final void updateAttributes(int vid, int aid, int width, int height, int bps_stream, + int bps_video, int bps_audio, float fps, int videoFrames, int audioFrames, int duration, String vcodec, String acodec) { int event_mask = 0; if( state == State.Uninitialized ) { @@ -1227,19 +1227,19 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { if( this.vid != vid ) { event_mask |= GLMediaEventListener.EVENT_CHANGE_VID; this.vid = vid; - } + } if( STREAM_ID_AUTO == vid ) { vid = STREAM_ID_NONE; } if( this.aid != aid ) { event_mask |= GLMediaEventListener.EVENT_CHANGE_AID; this.aid = aid; - } + } if( this.width != width || this.height != height ) { event_mask |= GLMediaEventListener.EVENT_CHANGE_SIZE; this.width = width; this.height = height; - } + } if( this.fps != fps ) { event_mask |= GLMediaEventListener.EVENT_CHANGE_FPS; this.fps = fps; @@ -1257,7 +1257,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { this.audioFrames = audioFrames; this.duration = duration; } - if( (null!=acodec && acodec.length()>0 && !this.acodec.equals(acodec)) ) { + if( (null!=acodec && acodec.length()>0 && !this.acodec.equals(acodec)) ) { event_mask |= GLMediaEventListener.EVENT_CHANGE_CODEC; this.acodec = acodec; } @@ -1283,7 +1283,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { attributesUpdated(GLMediaEventListener.EVENT_CHANGE_SIZE); } } - + @Override public final URI getURI() { return streamLoc; @@ -1291,10 +1291,10 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { @Override public final int getVID() { return vid; } - + @Override public final int getAID() { return aid; } - + @Override public final String getVideoCodec() { return vcodec; @@ -1309,7 +1309,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { public final int getVideoFrames() { return videoFrames; } - + @Override public final int getAudioFrames() { return audioFrames; @@ -1319,7 +1319,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { public final int getDuration() { return duration; } - + @Override public final long getStreamBitrate() { return bps_stream; @@ -1329,12 +1329,12 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { public final int getVideoBitrate() { return bps_video; } - + @Override public final int getAudioBitrate() { return bps_audio; } - + @Override public final float getFramerate() { return fps; @@ -1344,7 +1344,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { public final boolean isGLOriented() { return isInGLOrientation; } - + @Override public final int getWidth() { return width; @@ -1369,11 +1369,11 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { "Video[id "+vid+", <"+vcodec+">, "+width+"x"+height+", glOrient "+isInGLOrientation+", "+fps+" fps, "+frame_duration+" fdur, "+bps_video+" bps], "+ "Audio[id "+aid+", <"+acodec+">, "+bps_audio+" bps, "+audioFrames+" frames], uri "+loc+camPath+"]"; } - + @Override public final String getPerfString() { final long currentTimeMillis = Platform.currentTimeMillis(); - final int video_scr = video_scr_pts + (int) ( ( currentTimeMillis - video_scr_t0 ) * playSpeed ); + final int video_scr = video_scr_pts + (int) ( ( currentTimeMillis - video_scr_t0 ) * playSpeed ); final int d_vpts = video_pts_last - video_scr; final int audio_scr = (int) ( ( currentTimeMillis - audio_scr_t0 ) * playSpeed ); final int audio_pts = getAudioPTSImpl(); @@ -1383,7 +1383,7 @@ public abstract class GLMediaPlayerImpl implements GLMediaPlayer { private final String getPerfStringImpl(final int video_scr, final int video_pts, final int d_vpts, final int audio_scr, final int audio_pts, final int d_apts, final int video_dpts_avg_diff) { - final float tt = getDuration() / 1000.0f; + final float tt = getDuration() / 1000.0f; final String audioSinkInfo; final AudioSink audioSink = getAudioSink(); if( null != audioSink ) { diff --git a/src/jogl/classes/jogamp/opengl/util/av/JavaSoundAudioSink.java b/src/jogl/classes/jogamp/opengl/util/av/JavaSoundAudioSink.java index 85fab96a4..6e006d9c0 100644 --- a/src/jogl/classes/jogamp/opengl/util/av/JavaSoundAudioSink.java +++ b/src/jogl/classes/jogamp/opengl/util/av/JavaSoundAudioSink.java @@ -22,75 +22,75 @@ public class JavaSoundAudioSink implements AudioSink { public static final int BUFFER_SIZE = 1000; public static final int SAMPLES_PER_BUFFER = BUFFER_SIZE / 2; private static final boolean staticAvailable; - + // Sample time values // public static final double SAMPLE_TIME_IN_SECS = 1.0 / DEFAULT_SAMPLE_RATE; // public static final double BUFFER_TIME_IN_SECS = SAMPLE_TIME_IN_SECS * SAMPLES_PER_BUFFER; - + private javax.sound.sampled.AudioFormat format; private DataLine.Info info; private SourceDataLine auline; private int bufferCount; - private byte [] sampleData = new byte[BUFFER_SIZE]; + private byte [] sampleData = new byte[BUFFER_SIZE]; private boolean initialized = false; private AudioSink.AudioFormat chosenFormat = null; - + private volatile boolean playRequested = false; private float volume = 1.0f; - + static { boolean ok = false; try { AudioSystem.getAudioFileTypes(); ok = true; } catch (Throwable t) { - + } staticAvailable=ok; - } - + } + @Override public String toString() { return "JavaSoundSink[init "+initialized+", dataLine "+info+", source "+auline+", bufferCount "+bufferCount+ ", chosen "+chosenFormat+", jsFormat "+format; } - + @Override public final float getPlaySpeed() { return 1.0f; } // FIXME - + @Override - public final boolean setPlaySpeed(float rate) { - return false; // FIXME + public final boolean setPlaySpeed(float rate) { + return false; // FIXME } - + @Override public final float getVolume() { // FIXME - return volume; + return volume; } - + @Override public final boolean setVolume(float v) { // FIXME volume = v; return true; } - + @Override public AudioSink.AudioFormat getPreferredFormat() { return DefaultFormat; } - + @Override public final int getMaxSupportedChannels() { return 2; } - + @Override public final boolean isSupported(AudioSink.AudioFormat format) { return true; } - + @Override public boolean init(AudioSink.AudioFormat requestedFormat, float frameDuration, int initialQueueSize, int queueGrowAmount, int queueLimit) { if( !staticAvailable ) { @@ -117,12 +117,12 @@ public class JavaSoundAudioSink implements AudioSink { } return true; } - + @Override public boolean isPlaying() { return playRequested && auline.isRunning(); } - + @Override public void play() { if( null != auline ) { @@ -135,7 +135,7 @@ public class JavaSoundAudioSink implements AudioSink { auline.start(); } } - + @Override public void pause() { if( null != auline ) { @@ -143,9 +143,9 @@ public class JavaSoundAudioSink implements AudioSink { auline.stop(); } } - + @Override - public void flush() { + public void flush() { if( null != auline ) { playRequested = false; auline.stop(); @@ -157,17 +157,17 @@ public class JavaSoundAudioSink implements AudioSink { public final int getEnqueuedFrameCount() { return 0; // FIXME } - + @Override public int getFrameCount() { return 1; } - + @Override public int getQueuedFrameCount() { return 0; } - + @Override public boolean isInitialized() { return initialized; @@ -179,7 +179,7 @@ public class JavaSoundAudioSink implements AudioSink { chosenFormat = null; // FIXEM: complete code! } - + @Override public AudioFrame enqueueData(AudioDataFrame audioDataFrame) { int byteSize = audioDataFrame.getByteSize(); @@ -188,7 +188,7 @@ public class JavaSoundAudioSink implements AudioSink { final int p = byteBuffer.position(); byteBuffer.get(bytes, 0, byteSize); byteBuffer.position(p); - + int written = 0; int len; while (byteSize > 0) { @@ -203,27 +203,27 @@ public class JavaSoundAudioSink implements AudioSink { @Override public AudioFrame enqueueData(int pts, ByteBuffer bytes, int byteCount) { return enqueueData(new AudioDataFrame(pts, chosenFormat.getBytesDuration(byteCount), bytes, byteCount)); - } - + } + @Override public int getQueuedByteCount() { return auline.getBufferSize() - auline.available(); } - + @Override public int getFreeFrameCount() { return auline.available(); } - + @Override public int getQueuedTime() { return getQueuedTimeImpl( getQueuedByteCount() ); } private final int getQueuedTimeImpl(int byteCount) { final int bytesPerSample = chosenFormat.sampleSize >>> 3; // /8 - return byteCount / ( chosenFormat.channelCount * bytesPerSample * ( chosenFormat.sampleRate / 1000 ) ); + return byteCount / ( chosenFormat.channelCount * bytesPerSample * ( chosenFormat.sampleRate / 1000 ) ); } @Override - public final int getPTS() { return 0; } // FIXME + public final int getPTS() { return 0; } // FIXME } diff --git a/src/jogl/classes/jogamp/opengl/util/av/NullAudioSink.java b/src/jogl/classes/jogamp/opengl/util/av/NullAudioSink.java index 723bb9dd1..8d3dbdf44 100644 --- a/src/jogl/classes/jogamp/opengl/util/av/NullAudioSink.java +++ b/src/jogl/classes/jogamp/opengl/util/av/NullAudioSink.java @@ -15,32 +15,32 @@ public class NullAudioSink implements AudioSink { private volatile float playSpeed = 1.0f; private volatile boolean playRequested = false; private float volume = 1.0f; - + @Override public final float getPlaySpeed() { return playSpeed; } - + @Override - public final boolean setPlaySpeed(float rate) { + public final boolean setPlaySpeed(float rate) { if( Math.abs(1.0f - rate) < 0.01f ) { rate = 1.0f; } - playSpeed = rate; + playSpeed = rate; return true; } - + @Override public final float getVolume() { // FIXME - return volume; + return volume; } - + @Override public final boolean setVolume(float v) { // FIXME - volume = v; + volume = v; return true; } - + @Override public AudioFormat getPreferredFormat() { return DefaultFormat; @@ -50,73 +50,73 @@ public class NullAudioSink implements AudioSink { public final int getMaxSupportedChannels() { return 8; } - + @Override public final boolean isSupported(AudioFormat format) { return true; } - + @Override public boolean init(AudioFormat requestedFormat, float frameDuration, int initialQueueSize, int queueGrowAmount, int queueLimit) { return true; } - + @Override public boolean isPlaying() { return playRequested; } - + @Override public void play() { playRequested = true; } - + @Override public void pause() { playRequested = false; } - + @Override - public void flush() { + public void flush() { } - + @Override public void destroy() { } - + @Override public final int getEnqueuedFrameCount() { return 0; } - + @Override public int getFrameCount() { return 0; } - + @Override public int getQueuedFrameCount() { return 0; } - + @Override public int getQueuedByteCount() { return 0; } - + @Override public int getQueuedTime() { return 0; } - + @Override public final int getPTS() { return 0; } - + @Override public int getFreeFrameCount() { - return 1; + return 1; } - + @Override public AudioFrame enqueueData(AudioDataFrame audioDataFrame) { return null; @@ -125,5 +125,5 @@ public class NullAudioSink implements AudioSink { @Override public AudioFrame enqueueData(int pts, ByteBuffer bytes, int byteCount) { return null; - } + } } diff --git a/src/jogl/classes/jogamp/opengl/util/av/NullGLMediaPlayer.java b/src/jogl/classes/jogamp/opengl/util/av/NullGLMediaPlayer.java index 1cddaa9cf..840149272 100644 --- a/src/jogl/classes/jogamp/opengl/util/av/NullGLMediaPlayer.java +++ b/src/jogl/classes/jogamp/opengl/util/av/NullGLMediaPlayer.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -54,10 +54,10 @@ public class NullGLMediaPlayer extends GLMediaPlayerImpl { private TextureData texData = null; private int pos_ms = 0; private long pos_start = 0; - + public NullGLMediaPlayer() { super(); - + } @Override @@ -82,16 +82,16 @@ public class NullGLMediaPlayer extends GLMediaPlayerImpl { validatePos(); return pos_ms; } - + @Override protected final int getNextTextureImpl(GL gl, TextureFrame nextFrame) { final int pts = getAudioPTSImpl(); nextFrame.setPTS( pts ); return pts; } - + @Override - protected final int getAudioPTSImpl() { + protected final int getAudioPTSImpl() { pos_ms = (int) ( Platform.currentTimeMillis() - pos_start ); validatePos(); return pos_ms; @@ -102,9 +102,9 @@ public class NullGLMediaPlayer extends GLMediaPlayerImpl { if(null != texData) { texData.destroy(); texData = null; - } + } } - + public final static TextureData createTestTextureData() { TextureData res = null; try { @@ -125,28 +125,28 @@ public class NullGLMediaPlayer extends GLMediaPlayerImpl { buffer.rewind(); res = new TextureData(GLProfile.getGL2ES2(), GL.GL_RGBA, w, h, 0, - GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, false, + GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, false, false, false, buffer, null); } return res; } - + @Override protected final void initStreamImpl(int vid, int aid) throws IOException { texData = createTestTextureData(); final float _fps = 24f; final int _duration = 10*60*1000; // msec final int _totalFrames = (int) ( (_duration/1000)*_fps ); - updateAttributes(0 /* fake */, GLMediaPlayer.STREAM_ID_NONE, - texData.getWidth(), texData.getHeight(), 0, - 0, 0, _fps, + updateAttributes(0 /* fake */, GLMediaPlayer.STREAM_ID_NONE, + texData.getWidth(), texData.getHeight(), 0, + 0, 0, _fps, _totalFrames, 0, _duration, "png-static", null); - } + } @Override protected final void initGLImpl(GL gl) throws IOException, GLException { isInGLOrientation = true; } - + /** * {@inheritDoc} *

              @@ -157,21 +157,21 @@ public class NullGLMediaPlayer extends GLMediaPlayerImpl { protected int validateTextureCount(int desiredTextureCount) { return 2; } - + @Override protected final TextureSequence.TextureFrame createTexImage(GL gl, int texName) { final Texture texture = super.createTexImageImpl(gl, texName, width, height); if(null != texData) { texture.updateImage(gl, texData); - } + } return new TextureSequence.TextureFrame( texture ); } - + @Override protected final void destroyTexFrame(GL gl, TextureSequence.TextureFrame frame) { super.destroyTexFrame(gl, frame); } - + private void validatePos() { boolean considerPausing = false; if( 0 > pos_ms) { diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGDynamicLibraryBundleInfo.java index 146a47ebc..390c20346 100644 --- a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGDynamicLibraryBundleInfo.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl.util.av.impl; import java.security.AccessController; @@ -48,9 +48,9 @@ import com.jogamp.common.util.VersionNumber; */ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { private static final boolean DEBUG = FFMPEGMediaPlayer.DEBUG || DynamicLibraryBundleInfo.DEBUG; - + private static final List glueLibNames = new ArrayList(); // none - + private static final int symbolCount = 65; private static final String[] symbolNames = { "avutil_version", @@ -61,10 +61,10 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { // libavcodec "avcodec_register_all", - "avcodec_close", - "avcodec_string", - "avcodec_find_decoder", - "avcodec_open2", // 53.6.0 (opt) + "avcodec_close", + "avcodec_string", + "avcodec_find_decoder", + "avcodec_open2", // 53.6.0 (opt) "avcodec_alloc_frame", "avcodec_get_frame_defaults", "avcodec_free_frame", // 54.28.0 (opt) @@ -79,10 +79,10 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { "av_init_packet", "av_new_packet", "av_destruct_packet", - "av_free_packet", + "av_free_packet", "avcodec_decode_audio4", // 53.25.0 (opt) /* 27 */ "avcodec_decode_video2", // 52.23.0 - + // libavutil "av_pix_fmt_descriptors", "av_frame_unref", // 55.0.0 (opt) @@ -101,10 +101,10 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { "avformat_alloc_context", "avformat_free_context", // 52.96.0 (opt) "avformat_close_input", // 53.17.0 (opt) - "av_register_all", + "av_register_all", "av_find_input_format", - "avformat_open_input", - "av_dump_format", + "avformat_open_input", + "av_dump_format", "av_read_frame", "av_seek_frame", "avformat_seek_file", // ??? (opt) @@ -115,24 +115,24 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { /* 54 */ "avformat_find_stream_info", // 53.3.0 (opt) // libavdevice -/* 55 */ "avdevice_register_all", // ??? - +/* 55 */ "avdevice_register_all", // ??? + // libavresample "avresample_alloc_context", // 1.0.1 "avresample_open", "avresample_close", "avresample_free", /* 60 */ "avresample_convert", - + // libavresample "av_opt_set_sample_fmt", // actually lavu .. but exist only w/ swresample! "swr_alloc", - "swr_init", + "swr_init", "swr_free", /* 65 */ "swr_convert", }; - + // optional symbol names private static final String[] optionalSymbolNames = { "avformat_seek_file", // ??? (opt) @@ -145,7 +145,7 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { // libavdevice "avdevice_register_all", // 53.0.0 (opt) - + // libavresample "avresample_version", // 1.0.1 "avresample_alloc_context", // 1.0.1 @@ -153,43 +153,43 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { "avresample_close", "avresample_free", "avresample_convert", - + // libavresample "av_opt_set_sample_fmt", // actually lavu .. but exist only w/ swresample! "swresample_version", // 0 "swr_alloc", - "swr_init", + "swr_init", "swr_free", "swr_convert", }; - + private static final long[] symbolAddr = new long[symbolCount]; private static final boolean ready; private static final boolean libsUFCLoaded; private static final boolean avresampleLoaded; // optional private static final boolean swresampleLoaded; // optional private static final boolean avdeviceLoaded; // optional - static final VersionNumber avCodecVersion; + static final VersionNumber avCodecVersion; static final VersionNumber avFormatVersion; static final VersionNumber avUtilVersion; static final VersionNumber avResampleVersion; static final VersionNumber swResampleVersion; private static final FFMPEGNatives natives; - + private static final int LIB_IDX_UTI = 0; private static final int LIB_IDX_FMT = 1; private static final int LIB_IDX_COD = 2; private static final int LIB_IDX_DEV = 3; private static final int LIB_IDX_AVR = 4; private static final int LIB_IDX_SWR = 5; - + static { - // native ffmpeg media player implementation is included in jogl_desktop and jogl_mobile + // native ffmpeg media player implementation is included in jogl_desktop and jogl_mobile GLProfile.initSingleton(); boolean _ready = false; - /** util, format, codec, device, avresample, swresample */ - boolean[] _loaded= new boolean[6]; - /** util, format, codec, avresample, swresample */ + /** util, format, codec, device, avresample, swresample */ + boolean[] _loaded= new boolean[6]; + /** util, format, codec, avresample, swresample */ VersionNumber[] _versions = new VersionNumber[5]; try { _ready = initSymbols(_loaded, _versions); @@ -226,7 +226,7 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { } else { System.err.println("LIB_AV No Version/Native-Impl Match"); natives = null; - } + } if( null != natives && FFMPEGStaticNatives.initIDs0() ) { ready = natives.initSymbols0(symbolAddr, symbolCount); } else { @@ -234,7 +234,7 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { } } } - + static boolean libsLoaded() { return libsUFCLoaded; } static boolean avDeviceLoaded() { return avdeviceLoaded; } static boolean avResampleLoaded() { return avresampleLoaded; } @@ -265,11 +265,11 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { if(symbolNames.length != symbolCount) { throw new InternalError("XXX0 "+symbolNames.length+" != "+symbolCount); } - + // optional symbol name set final Set optionalSymbolNameSet = new HashSet(); optionalSymbolNameSet.addAll(Arrays.asList(optionalSymbolNames)); - + // lookup AccessController.doPrivileged(new PrivilegedAction() { public Object run() { @@ -278,9 +278,9 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { } return null; } } ); - + // validate results - boolean res = true; + boolean res = true; for(int i = 0; i * Returns true. *

              - */ + */ @Override public final boolean shallLookupGlobal() { - return true; + return true; } - + @Override public final List getGlueLibNames() { return glueLibNames; @@ -329,7 +329,7 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { List> libsList = new ArrayList>(); // 6: util, format, codec, device, avresample, swresample - + final List avutil = new ArrayList(); avutil.add("avutil"); // default @@ -337,13 +337,13 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { avutil.add("libavutil.so.52"); // ffmpeg 1.2 + 2 / libav 9 + 10 avutil.add("libavutil.so.51"); // 0.8 avutil.add("libavutil.so.50"); // 0.7 - + avutil.add("avutil-53"); // dummy future proof avutil.add("avutil-52"); // ffmpeg 1.2 + 2 / libav 9 + 10 avutil.add("avutil-51"); // 0.8 avutil.add("avutil-50"); // 0.7 libsList.add(avutil); - + final List avformat = new ArrayList(); avformat.add("avformat"); // default @@ -352,14 +352,14 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { avformat.add("libavformat.so.54"); // ffmpeg 1.2 / libav 9 avformat.add("libavformat.so.53"); // 0.8 avformat.add("libavformat.so.52"); // 0.7 - + avformat.add("avformat-56"); // dummy future proof avformat.add("avformat-55"); // ffmpeg 2 / libav 10 avformat.add("avformat-54"); // ffmpeg 1.2 / libav 9 avformat.add("avformat-53"); // 0.8 - avformat.add("avformat-52"); // 0.7 + avformat.add("avformat-52"); // 0.7 libsList.add(avformat); - + final List avcodec = new ArrayList(); avcodec.add("avcodec"); // default @@ -367,15 +367,15 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { avcodec.add("libavcodec.so.55"); // ffmpeg 2/ libav 10 avcodec.add("libavcodec.so.54"); // ffmpeg 1.2 / libav 9 avcodec.add("libavcodec.so.53"); // 0.8 - avcodec.add("libavcodec.so.52"); // 0.7 - + avcodec.add("libavcodec.so.52"); // 0.7 + avcodec.add("avcodec-56"); // dummy future proof avcodec.add("avcodec-55"); // ffmpeg 2/ libav 10 avcodec.add("avcodec-54"); // ffmpeg 1.2 / libav 9 avcodec.add("avcodec-53"); // 0.8 - avcodec.add("avcodec-52"); // 0.7 + avcodec.add("avcodec-52"); // 0.7 libsList.add(avcodec); - + final List avdevice = new ArrayList(); avdevice.add("avdevice"); // default @@ -383,19 +383,19 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { avdevice.add("libavdevice.so.55"); // ffmpeg 2 avdevice.add("libavdevice.so.54"); // ffmpeg 1.2 / libav 10 avdevice.add("libavdevice.so.53"); // 0.8 && libav 9 - + avdevice.add("avdevice-56"); // dummy future proof avdevice.add("avdevice-55"); // ffmpeg 2 avdevice.add("avdevice-54"); // ffmpeg 1.2 / libav 10 avdevice.add("avdevice-53"); // 0.8 && libav 9 libsList.add(avdevice); - + final List avresample = new ArrayList(); avresample.add("avresample"); // default avresample.add("libavresample.so.2"); // dummy future proof avresample.add("libavresample.so.1"); // libav 9 + 10 - + avresample.add("avresample-2"); // dummy future proof avresample.add("avresample-1"); // libav 9 + 10 libsList.add(avresample); @@ -405,11 +405,11 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { swresample.add("libswresample.so.1"); // dummy future proof swresample.add("libswresample.so.0"); // ffmpeg 1.2 + 2.x - + swresample.add("swresample-1"); // dummy future proof swresample.add("swresample-0"); // ffmpeg 1.2 + 2.x libsList.add(swresample); - + return libsList; } @@ -431,5 +431,5 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { @Override public final RunnableExecutor getLibLoaderExecutor() { return DynamicLibraryBundle.getDefaultRunnableExecutor(); - } + } } diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGMediaPlayer.java b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGMediaPlayer.java index f196ebef1..2abd73181 100644 --- a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGMediaPlayer.java +++ b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGMediaPlayer.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -65,18 +65,18 @@ import jogamp.opengl.util.av.impl.FFMPEGNatives.SampleFormat; * Besides the default BSD/Linux/.. repositories and installations, * precompiled binaries can be found at the * listed location below. - *

              - * + *

              + * *
              Implementation specifics
              *

              - * The decoded video frame is written directly into an OpenGL texture - * on the GPU in it's native format. A custom fragment shader converts - * the native pixelformat to a usable RGB format if required. - * Hence only 1 copy is required before bloating the picture + * The decoded video frame is written directly into an OpenGL texture + * on the GPU in it's native format. A custom fragment shader converts + * the native pixelformat to a usable RGB format if required. + * Hence only 1 copy is required before bloating the picture * from YUV* to RGB, for example. - *

              + *

              *

              - * Implements pixel format conversion to RGB via + * Implements pixel format conversion to RGB via * fragment shader texture-lookup functions: *

                *
              • {@link PixelFormat#YUV420P}
              • @@ -88,10 +88,10 @@ import jogamp.opengl.util.av.impl.FFMPEGNatives.SampleFormat; *
              *

              *

              - * + * *

              Libav Specifics
              *

              - * Utilizes a slim dynamic and native binding to the Lib_av + * Utilizes a slim dynamic and native binding to the Lib_av * libraries: *

                *
              • libavcodec
              • @@ -99,9 +99,9 @@ import jogamp.opengl.util.av.impl.FFMPEGNatives.SampleFormat; *
              • libavutil
              • *
              • libavresample (opt)
              • *
              • libavdevice (opt)
              • - *
              + * *

              - * + * *
              LibAV Compatibility
              *

              * Currently we are binary compatible w/: @@ -115,25 +115,25 @@ import jogamp.opengl.util.av.impl.FFMPEGNatives.SampleFormat; *

              * See http://upstream-tracker.org/versions/libav.html *

              - *

              - * Check tag 'FIXME: Add more planar formats !' + *

              + * Check tag 'FIXME: Add more planar formats !' * here and in the corresponding native code * jogl/src/jogl/native/libav/ffmpeg_impl_template.c *

              - * - * + * + * *
              TODO:
              *

              *

                *
              • better audio synchronization handling? (video is synchronized)
              • - *
              + * *

              - * + * *
              FFMPEG / LibAV Availability
              *

              *

                *
              • GNU/Linux: ffmpeg or libav are deployed in most distributions.
              • - *
              • Windows: + *
              • Windows: *
                  *
                • http://ffmpeg.zeranoe.com/builds/ (ffmpeg) recommended, works w/ dshow
                • *
                • http://win32.libav.org/releases/ (libav)
                • @@ -144,22 +144,22 @@ import jogamp.opengl.util.av.impl.FFMPEGNatives.SampleFormat; * pkt install pkg:/video/ffmpeg * *
                - *

                + *

                */ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { /** POSIX ENOSYS {@value}: Function not implemented. FIXME: Move to GlueGen ?!*/ private static final int ENOSYS = 38; - + // Instance data private static final FFMPEGNatives natives; private static final int avUtilMajorVersionCC; private static final int avFormatMajorVersionCC; - private static final int avCodecMajorVersionCC; + private static final int avCodecMajorVersionCC; private static final int avResampleMajorVersionCC; private static final int swResampleMajorVersionCC; private static final boolean available; - + static { final boolean libAVGood = FFMPEGDynamicLibraryBundleInfo.initSingleton(); final boolean libAVVersionGood; @@ -171,7 +171,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { avUtilMajorVersionCC = natives.getAvUtilMajorVersionCC0(); avResampleMajorVersionCC = natives.getAvResampleMajorVersionCC0(); swResampleMajorVersionCC = natives.getSwResampleMajorVersionCC0(); - } else { + } else { avUtilMajorVersionCC = 0; avFormatMajorVersionCC = 0; avCodecMajorVersionCC = 0; @@ -211,25 +211,25 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { } available = libAVGood && libAVVersionGood && null != natives; } - + public static final boolean isAvailable() { return available; } // // General // - - private long moviePtr = 0; - + + private long moviePtr = 0; + // // Video // - + private String texLookupFuncName = "ffmpegTexture2D"; - private boolean usesTexLookupShader = false; + private boolean usesTexLookupShader = false; private PixelFormat vPixelFmt = null; private int vPlanes = 0; private int vBitsPerPixel = 0; - private int vBytesPerPixelPerPlane = 0; + private int vBytesPerPixelPerPlane = 0; private int texWidth, texHeight; // overall (stuffing planes in one texture) private String singleTexComp = "r"; private GLPixelStorageModes psm; @@ -237,10 +237,10 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { // // Audio // - + private AudioSink.AudioFormat avChosenAudioFormat; private int audioSamplesPerFrameAndChannel = 0; - + public FFMPEGMediaPlayer() { if(!available) { throw new RuntimeException("FFMPEGMediaPlayer not available"); @@ -263,14 +263,14 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { } private final void destroyAudioSink() { final AudioSink _audioSink = audioSink; - if( null != _audioSink ) { + if( null != _audioSink ) { audioSink = null; _audioSink.destroy(); } } - + public static final String dev_video_linux = "/dev/video"; - + @Override protected final void initStreamImpl(int vid, int aid) throws IOException { if(0==moviePtr) { @@ -279,7 +279,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { if(DEBUG) { System.err.println("initStream: p1 "+this); } - + final String streamLocS=IOUtil.decodeFromURI(streamLoc.toString()); destroyAudioSink(); if( GLMediaPlayer.STREAM_ID_NONE == aid ) { @@ -291,7 +291,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { if(DEBUG) { System.err.println("initStream: p2 preferred "+preferredAudioFormat+", "+this); } - + final boolean isCameraInput = null != cameraPath; final String resStreamLocS; // int rw=640, rh=480, rr=15; @@ -314,7 +314,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { case OPENKODE: default: resStreamLocS = streamLocS; // FIXME: ?? - break; + break; } if( null != cameraProps ) { sizes = cameraProps.get(CameraPropSizeS); @@ -362,7 +362,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { if(DEBUG) { System.err.println("initGL: p3 avChosen "+avChosenAudioFormat); } - + if( STREAM_ID_NONE == aid ) { audioSink.destroy(); audioSink = AudioSinkFactory.createNull(); @@ -386,7 +386,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { System.err.println("initGL: p4 chosen "+avChosenAudioFormat); System.err.println("initGL: p4 chosen "+audioSink); } - + if( null != gl && STREAM_ID_NONE != vid ) { int tf, tif=GL.GL_RGBA; // texture format and internal format int tt = GL.GL_UNSIGNED_BYTE; @@ -413,9 +413,9 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { tf = GL2ES2.GL_BGRA; tif=GL.GL_RGBA; break; } else { tf = GL2ES2.GL_RGBA; tif=GL.GL_RGBA; break; - } + } default: throw new RuntimeException("Unsupported bytes-per-pixel / plane "+vBytesPerPixelPerPlane); - } + } setTextureFormat(tif, tf); setTextureType(tt); if(DEBUG) { @@ -423,12 +423,12 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { ", tex "+texWidth+"x"+texHeight+", usesTexLookupShader "+usesTexLookupShader); } } - } + } @Override protected final TextureFrame createTexImage(GL gl, int texName) { return new TextureFrame( createTexImageImpl(gl, texName, texWidth, texHeight) ); } - + /** * @param sampleRate sample rate in Hz (1/s) * @param sampleSize sample size in bits @@ -439,10 +439,10 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { * @param littleEndian true for little-endian, false for big endian * @return */ - + /** * Native callback - * Converts the given libav/ffmpeg values to {@link AudioFormat} and returns {@link AudioSink#isSupported(AudioFormat)}. + * Converts the given libav/ffmpeg values to {@link AudioFormat} and returns {@link AudioSink#isSupported(AudioFormat)}. * @param audioSampleFmt ffmpeg/libav audio-sample-format, see {@link SampleFormat}. * @param audioSampleRate sample rate in Hz (1/s) * @param audioChannels number of channels @@ -456,9 +456,9 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { } return res; } - + /** - * Returns {@link AudioFormat} as converted from the given libav/ffmpeg values. + * Returns {@link AudioFormat} as converted from the given libav/ffmpeg values. * @param audioSampleFmt ffmpeg/libav audio-sample-format, see {@link SampleFormat}. * @param audioSampleRate sample rate in Hz (1/s) * @param audioChannels number of channels @@ -506,7 +506,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { } return new AudioFormat(audioSampleRate, sampleSize, audioChannels, signed, fixedP, planar, true /* littleEndian */); } - + /** * Native callback * @param vid @@ -523,9 +523,9 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { * @param audioChannels * @param audioSamplesPerFrameAndChannel in audio samples per frame and channel */ - void setupFFAttributes(int vid, int pixFmt, int planes, int bitsPerPixel, int bytesPerPixelPerPlane, + void setupFFAttributes(int vid, int pixFmt, int planes, int bitsPerPixel, int bytesPerPixelPerPlane, int tWd0, int tWd1, int tWd2, int vW, int vH, - int aid, int audioSampleFmt, int audioSampleRate, + int aid, int audioSampleFmt, int audioSampleRate, int audioChannels, int audioSamplesPerFrameAndChannel) { // defaults .. vPixelFmt = null; @@ -534,28 +534,28 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { vBytesPerPixelPerPlane = 0; usesTexLookupShader = false; texWidth = 0; texHeight = 0; - + final int[] vTexWidth = { 0, 0, 0 }; // per plane - + if( STREAM_ID_NONE != vid ) { vPixelFmt = PixelFormat.valueOf(pixFmt); vPlanes = planes; vBitsPerPixel = bitsPerPixel; - vBytesPerPixelPerPlane = bytesPerPixelPerPlane; + vBytesPerPixelPerPlane = bytesPerPixelPerPlane; vTexWidth[0] = tWd0; vTexWidth[1] = tWd1; vTexWidth[2] = tWd2; - + switch(vPixelFmt) { case YUVJ420P: case YUV420P: // < planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples) usesTexLookupShader = true; // YUV420P: Adding U+V on right side of fixed height texture, // since width is already aligned by decoder. - // Splitting texture to 4 quadrants: + // Splitting texture to 4 quadrants: // Y covers left top/low quadrant // U on top-right quadrant. // V on low-right quadrant. // Y=w*h, U=w/2*h/2, V=w/2*h/2 - // w*h + 2 ( w/2 * h/2 ) + // w*h + 2 ( w/2 * h/2 ) // w*h + w*h/2 texWidth = vTexWidth[0] + vTexWidth[1]; texHeight = vH; break; @@ -573,27 +573,27 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { case YUYV422: // < packed YUV 4:2:2, 2x 16bpp, Y0 Cb Y1 Cr - stuffed into RGBA half width texture case BGR24: usesTexLookupShader = true; - texWidth = vTexWidth[0]; texHeight = vH; + texWidth = vTexWidth[0]; texHeight = vH; break; - + case RGB24: case ARGB: case RGBA: case ABGR: case BGRA: usesTexLookupShader = false; - texWidth = vTexWidth[0]; texHeight = vH; + texWidth = vTexWidth[0]; texHeight = vH; break; default: // FIXME: Add more formats ! throw new RuntimeException("Unsupported pixelformat: "+vPixelFmt); } } - + // defaults .. final SampleFormat aSampleFmt; avChosenAudioFormat = null;; this.audioSamplesPerFrameAndChannel = 0; - + if( STREAM_ID_NONE != aid ) { aSampleFmt = SampleFormat.valueOf(audioSampleFmt); avChosenAudioFormat = avAudioFormat2Local(aSampleFmt, audioSampleRate, audioChannels); @@ -601,7 +601,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { } else { aSampleFmt = null; } - + if(DEBUG) { System.err.println("audio: id "+aid+", fmt "+aSampleFmt+", "+avChosenAudioFormat+", aFrameSize/fc "+audioSamplesPerFrameAndChannel); System.err.println("video: id "+vid+", fmt "+vW+"x"+vH+", "+vPixelFmt+", planes "+vPlanes+", bpp "+vBitsPerPixel+"/"+vBytesPerPixelPerPlane+", usesTexLookupShader "+usesTexLookupShader); @@ -612,7 +612,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { System.err.println(this.toString()); } } - + /** * Native callback * @param isInGLOrientation @@ -624,13 +624,13 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { * @param tWd1 * @param tWd2 */ - void updateVidAttributes(boolean isInGLOrientation, int pixFmt, int planes, int bitsPerPixel, int bytesPerPixelPerPlane, + void updateVidAttributes(boolean isInGLOrientation, int pixFmt, int planes, int bitsPerPixel, int bytesPerPixelPerPlane, int tWd0, int tWd1, int tWd2, int vW, int vH) { } - + /** * {@inheritDoc} - * + * * If this implementation generates a specialized shader, * it allows the user to override the default function name ffmpegTexture2D. * Otherwise the call is delegated to it's super class. @@ -646,15 +646,15 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { } return texLookupFuncName; } - return super.getTextureLookupFunctionName(desiredFuncName); + return super.getTextureLookupFunctionName(desiredFuncName); } - + /** * {@inheritDoc} - * + * * Depending on the pixelformat, a specific conversion shader is being created, - * e.g. YUV420P to RGB. Otherwise the call is delegated to it's super class. - */ + * e.g. YUV420P to RGB. Otherwise the call is delegated to it's super class. + */ @Override public final String getTextureLookupFragmentShaderImpl() throws IllegalStateException { if(State.Uninitialized == state) { @@ -685,7 +685,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { " return vec4(r, g, b, 1);\n"+ "}\n" ; - + case YUVJ422P: case YUV422P: ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples) return @@ -706,7 +706,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { " return vec4(r, g, b, 1);\n"+ "}\n" ; - + case YUYV422: // < packed YUV 4:2:2, 2 x 16bpp, [Y0 Cb] [Y1 Cr] // Stuffed into RGBA half width texture return @@ -740,9 +740,9 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { default: // FIXME: Add more formats ! throw new InternalError("Add proper mapping of: vPixelFmt "+vPixelFmt+", usesTexLookupShader "+usesTexLookupShader); - } + } } - + @Override public final boolean playImpl() { if(0==moviePtr) { @@ -754,7 +754,7 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { } return true; } - + @Override public final boolean pauseImpl() { if(0==moviePtr) { @@ -780,12 +780,12 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { psm.setUnpackAlignment(gl, 1); // RGBA ? 4 : 1 gl.glActiveTexture(GL.GL_TEXTURE0+getTextureUnit()); } - + @Override protected void postNextTextureImpl(GL gl) { psm.restore(gl); } - + @Override protected final int getNextTextureImpl(GL gl, TextureFrame nextFrame) { if(0==moviePtr) { @@ -806,14 +806,14 @@ public class FFMPEGMediaPlayer extends GLMediaPlayerImpl { nextFrame.setPTS(vPTS); } return vPTS; - } - + } + final void pushSound(ByteBuffer sampleData, int data_size, int audio_pts) { setFirstAudioPTS2SCR( audio_pts ); if( 1.0f == playSpeed || audioSinkPlaySpeedSet ) { audioSink.enqueueData( audio_pts, sampleData, data_size); } } - + } diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGNatives.java b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGNatives.java index 8e08c23fa..bc0865aa9 100644 --- a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGNatives.java +++ b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGNatives.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -30,21 +30,21 @@ package jogamp.opengl.util.av.impl; import com.jogamp.opengl.util.texture.TextureSequence.TextureFrame; interface FFMPEGNatives { - + boolean initSymbols0(long[] symbols, int count); int getAvUtilMajorVersionCC0(); int getAvFormatMajorVersionCC0(); int getAvCodecMajorVersionCC0(); int getAvResampleMajorVersionCC0(); int getSwResampleMajorVersionCC0(); - + long createInstance0(FFMPEGMediaPlayer upstream, boolean verbose); void destroyInstance0(long moviePtr); - + /** * Issues {@link #updateAttributes(int, int, int, int, int, int, int, float, int, int, String, String)} * and {@link #updateAttributes2(int, int, int, int, int, int, int, int, int, int)}. - * + * * @param moviePtr * @param url * @param vid @@ -56,25 +56,25 @@ interface FFMPEGNatives { * @param aPrefSampleRate * @param aPrefChannelCount */ - void setStream0(long moviePtr, String url, boolean isCameraInput, - int vid, String sizes, int vWidth, int vHeight, + void setStream0(long moviePtr, String url, boolean isCameraInput, + int vid, String sizes, int vWidth, int vHeight, int vRate, int aid, int aMaxChannelCount, int aPrefSampleRate); - + void setGLFuncs0(long moviePtr, long procAddrGLTexSubImage2D, long procAddrGLGetError, long procAddrGLFlush, long procAddrGLFinish); - int getVideoPTS0(long moviePtr); - + int getVideoPTS0(long moviePtr); + int getAudioPTS0(long moviePtr); - + /** * @return resulting current video PTS, or {@link TextureFrame#INVALID_PTS} */ int readNextPacket0(long moviePtr, int texTarget, int texFmt, int texType); - + int play0(long moviePtr); int pause0(long moviePtr); int seek0(long moviePtr, int position); - + /** FFMPEG/libAV Audio Sample Format */ public static enum SampleFormat { // NONE = -1, @@ -89,10 +89,10 @@ interface FFMPEGNatives { S32P, ///< signed 32 bits, planar FLTP, ///< float, planar DBLP, ///< double, planar - + COUNT; ///< Number of sample formats. - - /** + + /** * Returns the matching SampleFormat value corresponding to the given SampleFormat's integer ordinal. *
                          *   given:
                @@ -131,7 +131,7 @@ interface FFMPEGNatives {
                         /** planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) */
                         YUV411P,
                         /** Y, 8bpp */
                -        GRAY8,        
                +        GRAY8,
                         /** Y,  1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb */
                         MONOWHITE,
                         /** Y,  1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb */
                @@ -151,57 +151,57 @@ interface FFMPEGNatives {
                         /** packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1 */
                         UYVY422,
                         /** packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3 */
                -        UYYVYY411, 
                +        UYYVYY411,
                         /** packed RGB 3:3:2,  8bpp, (msb)2B 3G 3R(lsb) */
                -        BGR8, 
                +        BGR8,
                         /** packed RGB 1:2:1 bitstream,  4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits */
                -        BGR4, 
                +        BGR4,
                         /** packed RGB 1:2:1,  8bpp, (msb)1B 2G 1R(lsb) */
                -        BGR4_BYTE, 
                +        BGR4_BYTE,
                         /** packed RGB 3:3:2,  8bpp, (msb)2R 3G 3B(lsb) */
                -        RGB8, 
                +        RGB8,
                         /** packed RGB 1:2:1 bitstream,  4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits */
                -        RGB4, 
                +        RGB4,
                         /** packed RGB 1:2:1,  8bpp, (msb)1R 2G 1B(lsb) */
                -        RGB4_BYTE, 
                +        RGB4_BYTE,
                         /** planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V) */
                -        NV12, 
                +        NV12,
                         /** as above, but U and V bytes are swapped */
                -        NV21, 
                +        NV21,
                 
                         /** packed ARGB 8:8:8:8, 32bpp, ARGBARGB... */
                -        ARGB, 
                +        ARGB,
                         /** packed RGBA 8:8:8:8, 32bpp, RGBARGBA... */
                -        RGBA, 
                +        RGBA,
                         /** packed ABGR 8:8:8:8, 32bpp, ABGRABGR... */
                -        ABGR, 
                +        ABGR,
                         /** packed BGRA 8:8:8:8, 32bpp, BGRABGRA... */
                -        BGRA, 
                +        BGRA,
                 
                         /** Y, 16bpp, big-endian */
                -        GRAY16BE,        
                +        GRAY16BE,
                         /** Y        , 16bpp, little-endian */
                -        GRAY16LE,        
                +        GRAY16LE,
                         /** planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples) */
                -        YUV440P, 
                +        YUV440P,
                         /** planar YUV 4:4:0 full scale (JPEG), deprecated in favor of YUV440P and setting color_range */
                -        YUVJ440P, 
                +        YUVJ440P,
                         /** planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples) */
                -        YUVA420P, 
                +        YUVA420P,
                         /** H.264 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers */
                -        VDPAU_H264, 
                +        VDPAU_H264,
                         /** MPEG-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers */
                -        VDPAU_MPEG1, 
                +        VDPAU_MPEG1,
                         /** MPEG-2 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers */
                -        VDPAU_MPEG2, 
                +        VDPAU_MPEG2,
                         /** WMV3 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers */
                -        VDPAU_WMV3, 
                +        VDPAU_WMV3,
                         /** VC-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers */
                -        VDPAU_VC1, 
                +        VDPAU_VC1,
                         /** packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian */
                -        RGB48BE, 
                +        RGB48BE,
                         /** packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian */
                -        RGB48LE, 
                +        RGB48LE,
                 
                         RGB565BE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), big-endian
                         RGB565LE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), little-endian
                @@ -255,7 +255,7 @@ interface FFMPEGNatives {
                         GBRP16LE,  ///< planar GBR 4:4:4 48bpp, little endian
                         COUNT      ///< number of pixel formats in this list
                         ;
                -        /** 
                +        /**
                          * Returns the matching PixelFormat value corresponding to the given PixelFormat's integer ordinal.
                          * 
                          *   given:
                diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGStaticNatives.java b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGStaticNatives.java
                index 01c249313..22a045825 100644
                --- a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGStaticNatives.java
                +++ b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGStaticNatives.java
                @@ -3,14 +3,14 @@
                  *
                  * Redistribution and use in source and binary forms, with or without modification, are
                  * permitted provided that the following conditions are met:
                - * 
                + *
                  *    1. Redistributions of source code must retain the above copyright notice, this list of
                  *       conditions and the following disclaimer.
                - * 
                + *
                  *    2. 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.
                - * 
                + *
                  * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR
                @@ -20,7 +20,7 @@
                  * 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.
                - * 
                + *
                  * The views and conclusions contained in the software and documentation are those of the
                  * authors and should not be interpreted as representing official policies, either expressed
                  * or implied, of JogAmp Community.
                @@ -29,7 +29,7 @@ package jogamp.opengl.util.av.impl;
                 
                 import com.jogamp.common.util.VersionNumber;
                 
                -class FFMPEGStaticNatives {        
                +class FFMPEGStaticNatives {
                     static VersionNumber getAVVersion(int vers) {
                         return new VersionNumber( ( vers >> 16 ) & 0xFF,
                                                   ( vers >>  8 ) & 0xFF,
                diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv08Natives.java b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv08Natives.java
                index 22694888d..4b013c1b3 100644
                --- a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv08Natives.java
                +++ b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv08Natives.java
                @@ -3,14 +3,14 @@
                  *
                  * Redistribution and use in source and binary forms, with or without modification, are
                  * permitted provided that the following conditions are met:
                - * 
                + *
                  *    1. Redistributions of source code must retain the above copyright notice, this list of
                  *       conditions and the following disclaimer.
                - * 
                + *
                  *    2. 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.
                - * 
                + *
                  * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR
                @@ -20,7 +20,7 @@
                  * 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.
                - * 
                + *
                  * The views and conclusions contained in the software and documentation are those of the
                  * authors and should not be interpreted as representing official policies, either expressed
                  * or implied, of JogAmp Community.
                @@ -45,7 +45,7 @@ class FFMPEGv08Natives implements FFMPEGNatives {
                 
                     @Override
                     public native int getSwResampleMajorVersionCC0();
                -    
                +
                     @Override
                     public native long createInstance0(FFMPEGMediaPlayer upstream, boolean verbose);
                 
                diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv09Natives.java b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv09Natives.java
                index 08e19d5e6..d69763287 100644
                --- a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv09Natives.java
                +++ b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv09Natives.java
                @@ -3,14 +3,14 @@
                  *
                  * Redistribution and use in source and binary forms, with or without modification, are
                  * permitted provided that the following conditions are met:
                - * 
                + *
                  *    1. Redistributions of source code must retain the above copyright notice, this list of
                  *       conditions and the following disclaimer.
                - * 
                + *
                  *    2. 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.
                - * 
                + *
                  * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR
                @@ -20,7 +20,7 @@
                  * 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.
                - * 
                + *
                  * The views and conclusions contained in the software and documentation are those of the
                  * authors and should not be interpreted as representing official policies, either expressed
                  * or implied, of JogAmp Community.
                @@ -45,7 +45,7 @@ class FFMPEGv09Natives implements FFMPEGNatives {
                 
                     @Override
                     public native int getSwResampleMajorVersionCC0();
                -    
                +
                     @Override
                     public native long createInstance0(FFMPEGMediaPlayer upstream, boolean verbose);
                 
                diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv10Natives.java b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv10Natives.java
                index 0081743fa..0b5f70d7c 100644
                --- a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv10Natives.java
                +++ b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGv10Natives.java
                @@ -3,14 +3,14 @@
                  *
                  * Redistribution and use in source and binary forms, with or without modification, are
                  * permitted provided that the following conditions are met:
                - * 
                + *
                  *    1. Redistributions of source code must retain the above copyright notice, this list of
                  *       conditions and the following disclaimer.
                - * 
                + *
                  *    2. 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.
                - * 
                + *
                  * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR
                @@ -20,7 +20,7 @@
                  * 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.
                - * 
                + *
                  * The views and conclusions contained in the software and documentation are those of the
                  * authors and should not be interpreted as representing official policies, either expressed
                  * or implied, of JogAmp Community.
                @@ -45,7 +45,7 @@ class FFMPEGv10Natives implements FFMPEGNatives {
                 
                     @Override
                     public native int getSwResampleMajorVersionCC0();
                -    
                +
                     @Override
                     public native long createInstance0(FFMPEGMediaPlayer upstream, boolean verbose);
                 
                diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java b/src/jogl/classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java
                index a5a701a4f..24198703a 100644
                --- a/src/jogl/classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java
                +++ b/src/jogl/classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java
                @@ -3,14 +3,14 @@
                  *
                  * Redistribution and use in source and binary forms, with or without modification, are
                  * permitted provided that the following conditions are met:
                - * 
                + *
                  *    1. Redistributions of source code must retain the above copyright notice, this list of
                  *       conditions and the following disclaimer.
                - * 
                + *
                  *    2. 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.
                - * 
                + *
                  * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR
                @@ -20,7 +20,7 @@
                  * 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.
                - * 
                + *
                  * The views and conclusions contained in the software and documentation are those of the
                  * authors and should not be interpreted as representing official policies, either expressed
                  * or implied, of JogAmp Community.
                @@ -45,19 +45,19 @@ import jogamp.opengl.util.av.EGLMediaPlayerImpl;
                  */
                 public class OMXGLMediaPlayer extends EGLMediaPlayerImpl {
                     static final boolean available;
                -    
                +
                     static {
                         available = false;
                         /** FIXME!
                -        // OMX binding is included in jogl_desktop and jogl_mobile     
                +        // OMX binding is included in jogl_desktop and jogl_mobile
                         GLProfile.initSingleton();
                         available = initIDs0(); */
                     }
                -    
                +
                     public static final boolean isAvailable() { return available; }
                -    
                +
                     protected long moviePtr = 0;
                -    
                +
                     public OMXGLMediaPlayer() {
                         super(TextureType.KHRImage, true);
                         if(!available) {
                @@ -70,21 +70,21 @@ public class OMXGLMediaPlayer extends EGLMediaPlayerImpl {
                         moviePtr = _createInstance();
                         if(0==moviePtr) {
                             throw new GLException("Couldn't create OMXInstance");
                -        }        
                +        }
                     }
                -    
                +
                     @Override
                     protected TextureSequence.TextureFrame createTexImage(GL gl, int texName) {
                         final EGLTextureFrame eglTex = (EGLTextureFrame) super.createTexImage(gl, texName);
                         _setStreamEGLImageTexture2D(moviePtr, texName, eglTex.getImage(), eglTex.getSync());
                         return eglTex;
                     }
                -    
                +
                     @Override
                     protected void destroyTexFrame(GL gl, TextureSequence.TextureFrame imgTex) {
                -        super.destroyTexFrame(gl, imgTex);        
                +        super.destroyTexFrame(gl, imgTex);
                     }
                -    
                +
                     @Override
                     protected void destroyImpl(GL gl) {
                         if (moviePtr != 0) {
                @@ -94,20 +94,20 @@ public class OMXGLMediaPlayer extends EGLMediaPlayerImpl {
                             moviePtr = 0;
                         }
                     }
                -    
                +
                     @Override
                     protected void initStreamImpl(int vid, int aid) throws IOException {
                         if(0==moviePtr) {
                             throw new GLException("OMX native instance null");
                         }
                         if(!streamLoc.getScheme().equals("file")) {
                -            throw new IOException("Only file schemes are allowed: "+streamLoc);            
                +            throw new IOException("Only file schemes are allowed: "+streamLoc);
                         }
                         final String path=streamLoc.getPath();
                         if(DEBUG) {
                             System.out.println("initGLStream: clean path "+path);
                         }
                -    
                +
                         if(DEBUG) {
                             System.out.println("initGLStream: p1 "+this);
                         }
                @@ -121,7 +121,7 @@ public class OMXGLMediaPlayer extends EGLMediaPlayerImpl {
                         // NOP
                         isInGLOrientation = true;
                     }
                -    
                +
                     @Override
                     protected int getAudioPTSImpl() {
                         return 0!=moviePtr ? _getCurrentPosition(moviePtr) : 0;
                @@ -172,8 +172,8 @@ public class OMXGLMediaPlayer extends EGLMediaPlayerImpl {
                         final int nextTex = _getNextTextureID(moviePtr, true);
                         if(0 < nextTex) {
                             // FIXME set pts !
                -            /* FIXME 
                -            final TextureSequence.TextureFrame eglImgTex = 
                +            /* FIXME
                +            final TextureSequence.TextureFrame eglImgTex =
                                     texFrameMap.get(new Integer(_getNextTextureID(moviePtr, blocking)));
                             if(null!=eglImgTex) {
                                 lastTex = eglImgTex;
                @@ -181,7 +181,7 @@ public class OMXGLMediaPlayer extends EGLMediaPlayerImpl {
                         }
                         return 0; // FIXME: return pts
                     }
                -    
                +
                     private String replaceAll(String orig, String search, String repl) {
                         String dest=null;
                         // In case replaceAll / java.util.regex.* is not supported (-> CVM)
                @@ -203,14 +203,14 @@ public class OMXGLMediaPlayer extends EGLMediaPlayerImpl {
                     }
                 
                     private static native boolean initIDs0();
                -    private native long _createInstance();    
                +    private native long _createInstance();
                     private native void _destroyInstance(long moviePtr);
                -    
                +
                     private native void _detachVideoRenderer(long moviePtr); // stop before
                     private native void _attachVideoRenderer(long moviePtr); // detach before
                     private native void _setStream(long moviePtr, int textureNum, String path);
                     private native void _activateStream(long moviePtr);
                -    
                +
                     private native void _setStreamEGLImageTexture2D(long moviePtr, int tex, long image, long sync);
                     private native int  _seek(long moviePtr, int position);
                     private native void _setPlaySpeed(long moviePtr, float rate);
                diff --git a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandler.java b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandler.java
                index 3c468f358..2d74fa532 100644
                --- a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandler.java
                +++ b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandler.java
                @@ -41,23 +41,23 @@ import com.jogamp.opengl.util.GLArrayDataEditable;
                 import com.jogamp.opengl.util.glsl.ShaderState;
                 
                 /**
                - * Used for 1:1 GLSL arrays, i.e. where the buffer data 
                - * represents this array only. 
                + * Used for 1:1 GLSL arrays, i.e. where the buffer data
                + * represents this array only.
                  */
                -public class GLSLArrayHandler extends GLVBOArrayHandler implements GLArrayHandler {    
                -  
                +public class GLSLArrayHandler extends GLVBOArrayHandler implements GLArrayHandler {
                +
                   public GLSLArrayHandler(GLArrayDataEditable ad) {
                     super(ad);
                   }
                -  
                +
                   public final void setSubArrayVBOName(int vboName) {
                       throw new UnsupportedOperationException();
                   }
                -  
                +
                   public final void addSubHandler(GLArrayHandlerFlat handler) {
                       throw new UnsupportedOperationException();
                   }
                -  
                +
                   public final void enableState(GL gl, boolean enable, Object ext) {
                     final GL2ES2 glsl = gl.getGL2ES2();
                     if( null != ext ) {
                @@ -66,12 +66,12 @@ public class GLSLArrayHandler extends GLVBOArrayHandler implements GLArrayHandle
                         enableSimple(glsl, enable);
                     }
                   }
                -  
                +
                   private final void enableShaderState(GL2ES2 glsl, boolean enable, ShaderState st) {
                     if(enable) {
                         /*
                          * This would be the non optimized code path:
                -         * 
                +         *
                         if(ad.isVBO()) {
                             glsl.glBindBuffer(ad.getVBOTarget(), ad.getVBOName());
                             if(!ad.isVBOWritten()) {
                @@ -108,13 +108,13 @@ public class GLSLArrayHandler extends GLVBOArrayHandler implements GLArrayHandle
                         } else if(null!=buffer) {
                             st.vertexAttribPointer(glsl, ad);
                         }
                -        
                +
                         st.enableVertexAttribArray(glsl, ad);
                     } else {
                         st.disableVertexAttribArray(glsl, ad);
                     }
                   }
                -  
                +
                   private final void enableSimple(GL2ES2 glsl, boolean enable) {
                     final int location = ad.getLocation();
                     if( 0 > location ) {
                @@ -123,7 +123,7 @@ public class GLSLArrayHandler extends GLVBOArrayHandler implements GLArrayHandle
                     if(enable) {
                         /*
                          * This would be the non optimized code path:
                -         * 
                +         *
                         if(ad.isVBO()) {
                             glsl.glBindBuffer(ad.getVBOTarget(), ad.getVBOName());
                             if(!ad.isVBOWritten()) {
                diff --git a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerFlat.java b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerFlat.java
                index 855406db3..a5f78b5d6 100644
                --- a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerFlat.java
                +++ b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerFlat.java
                @@ -37,7 +37,7 @@ import com.jogamp.opengl.util.GLArrayDataWrapper;
                 import com.jogamp.opengl.util.glsl.ShaderState;
                 
                 /**
                - * Used for interleaved GLSL arrays, i.e. where the buffer data itself is handled 
                + * Used for interleaved GLSL arrays, i.e. where the buffer data itself is handled
                  * separately and interleaves many arrays.
                  */
                 public class GLSLArrayHandlerFlat implements GLArrayHandlerFlat {
                @@ -50,7 +50,7 @@ public class GLSLArrayHandlerFlat implements GLArrayHandlerFlat {
                   public GLArrayDataWrapper getData() {
                       return ad;
                   }
                -    
                +
                   public final void syncData(GL gl, Object ext) {
                     final GL2ES2 glsl = gl.getGL2ES2();
                     if( null != ext ) {
                @@ -62,7 +62,7 @@ public class GLSLArrayHandlerFlat implements GLArrayHandlerFlat {
                     }
                     /**
                      * Due to probable application VBO switching, this might not make any sense ..
                -     * 
                +     *
                     if(!written) {
                         st.vertexAttribPointer(glsl, ad);
                     } else if(st.getAttribLocation(glsl, ad) >= 0) {
                @@ -94,7 +94,7 @@ public class GLSLArrayHandlerFlat implements GLArrayHandlerFlat {
                             } else {
                                 glsl.glDisableVertexAttribArray(location);
                             }
                -        }        
                +        }
                     }
                -  }  
                +  }
                 }
                diff --git a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerInterleaved.java b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerInterleaved.java
                index c2048d652..bcc146d78 100644
                --- a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerInterleaved.java
                +++ b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerInterleaved.java
                @@ -40,8 +40,8 @@ import jogamp.opengl.util.GLVBOArrayHandler;
                 import com.jogamp.opengl.util.GLArrayDataEditable;
                 
                 /**
                - * Interleaved fixed function arrays, i.e. where this buffer data 
                - * represents many arrays. 
                + * Interleaved fixed function arrays, i.e. where this buffer data
                + * represents many arrays.
                  */
                 public class GLSLArrayHandlerInterleaved extends GLVBOArrayHandler implements GLArrayHandler {
                   private List subArrays = new ArrayList();
                @@ -49,13 +49,13 @@ public class GLSLArrayHandlerInterleaved extends GLVBOArrayHandler implements GL
                   public GLSLArrayHandlerInterleaved(GLArrayDataEditable ad) {
                     super(ad);
                   }
                -  
                +
                   public final void setSubArrayVBOName(int vboName) {
                       for(int i=0; i shaderRootClass, String shaderSrcRoot, String shaderBinRoot,
                                          String vertexColorFile, String vertexColorLightFile,
                                          String fragmentColorFile, String fragmentColorTextureFile) {
                @@ -90,14 +90,14 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                             this.pmvMatrix = new PMVMatrix();
                         }
                 
                -        fixedFunction = new FixedFuncPipeline(this.gl, mode, this.pmvMatrix, shaderRootClass, shaderSrcRoot, 
                +        fixedFunction = new FixedFuncPipeline(this.gl, mode, this.pmvMatrix, shaderRootClass, shaderSrcRoot,
                                                               shaderBinRoot, vertexColorFile, vertexColorLightFile, fragmentColorFile, fragmentColorTextureFile);
                     }
                 
                     public boolean verbose() { return fixedFunction.verbose(); }
                 
                     public void setVerbose(boolean v) { fixedFunction.setVerbose(v); }
                -    
                +
                     public void destroy() {
                         fixedFunction.destroy(gl);
                         fixedFunction = null;
                @@ -111,16 +111,16 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                     public PMVMatrix getMatrix() { return pmvMatrix; }
                 
                     //
                -    // FixedFuncHookIf - hooks 
                +    // FixedFuncHookIf - hooks
                     //
                     public void glDrawArrays(int mode, int first, int count) {
                         fixedFunction.glDrawArrays(gl, mode, first, count);
                     }
                     public void glDrawElements(int mode, int count, int type, java.nio.Buffer indices) {
                -        fixedFunction.glDrawElements(gl, mode, count, type, indices);        
                +        fixedFunction.glDrawElements(gl, mode, count, type, indices);
                     }
                     public void glDrawElements(int mode, int count, int type, long indices_buffer_offset) {
                -        fixedFunction.glDrawElements(gl, mode, count, type, indices_buffer_offset); 
                +        fixedFunction.glDrawElements(gl, mode, count, type, indices_buffer_offset);
                     }
                 
                     public void glActiveTexture(int texture) {
                @@ -136,7 +136,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                         if(fixedFunction.glEnable(cap, false)) {
                             gl.glDisable(cap);
                         }
                -    }    
                +    }
                     public void glGetFloatv(int pname, java.nio.FloatBuffer params) {
                         if(PMVMatrix.isMatrixGetName(pname)) {
                             pmvMatrix.glGetFloatv(pname, params);
                @@ -165,7 +165,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                         }
                         gl.glGetIntegerv(pname, params, params_offset);
                     }
                -    
                +
                     public void glTexEnvi(int target, int pname, int value) {
                         fixedFunction.glTexEnvi(target, pname, value);
                     }
                @@ -179,7 +179,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                         fixedFunction.glBindTexture(target, texture);
                         gl.glBindTexture(target, texture);
                     }
                -    public void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, 
                +    public void glTexImage2D(int target, int level, int internalformat, int width, int height, int border,
                                              int format, int type,  Buffer pixels) {
                         // align internalformat w/ format, an ES2 requirement
                         switch(internalformat) {
                @@ -212,8 +212,8 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                     public  void glPointParameterfv(int pname, java.nio.FloatBuffer params) {
                         fixedFunction.glPointParameterfv(pname, params);
                     }
                -    
                -    // 
                +
                +    //
                     // MatrixIf
                     //
                     public int  glGetMatrixMode() {
                @@ -253,29 +253,29 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                         pmvMatrix.glScalef(x, y, z);
                     }
                     public void glOrtho(double left, double right, double bottom, double top, double near_val, double far_val) {
                -        glOrthof((float) left, (float) right, (float) bottom, (float) top, (float) near_val, (float) far_val); 
                +        glOrthof((float) left, (float) right, (float) bottom, (float) top, (float) near_val, (float) far_val);
                     }
                     public void glOrthof(float left, float right, float bottom, float top, float zNear, float zFar) {
                         pmvMatrix.glOrthof(left, right, bottom, top, zNear, zFar);
                     }
                     public void glFrustum(double left, double right, double bottom, double top, double zNear, double zFar) {
                -        glFrustumf((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar); 
                +        glFrustumf((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar);
                     }
                     public void glFrustumf(float left, float right, float bottom, float top, float zNear, float zFar) {
                         pmvMatrix.glFrustumf(left, right, bottom, top, zNear, zFar);
                     }
                 
                -    // 
                +    //
                     // LightingIf
                     //
                     public void glColor4f(float red, float green, float blue, float alpha) {
                       fixedFunction.glColor4f(gl, red, green, blue, alpha);
                     }
                -    
                +
                     public  void glColor4ub(byte red, byte green, byte blue, byte alpha) {
                -      glColor4f(ValueConv.byte_to_float(red, false), 
                -                ValueConv.byte_to_float(green, false), 
                -                ValueConv.byte_to_float(blue, false), 
                +      glColor4f(ValueConv.byte_to_float(red, false),
                +                ValueConv.byte_to_float(green, false),
                +                ValueConv.byte_to_float(blue, false),
                                 ValueConv.byte_to_float(alpha, false) );
                     }
                     public void glLightfv(int light, int pname, java.nio.FloatBuffer params) {
                @@ -299,17 +299,17 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                     //
                     public void glShadeModel(int mode) {
                       fixedFunction.glShadeModel(gl, mode);
                -    }    
                +    }
                     public  void glAlphaFunc(int func, float ref) {
                         fixedFunction.glAlphaFunc(func, ref);
                     }
                -    
                -    /** ES2 supports CullFace implicit 
                +
                +    /** ES2 supports CullFace implicit
                     public void glCullFace(int faceName) {
                         fixedFunction.glCullFace(faceName);
                         gl.glCullFace(faceName);
                     } */
                -    
                +
                     //
                     // PointerIf
                     //
                @@ -340,7 +340,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                     }
                 
                     public void glVertexPointer(int size, int type, int stride, java.nio.Buffer pointer) {
                -      glVertexPointer(GLArrayDataWrapper.createFixed(GL_VERTEX_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride, 
                +      glVertexPointer(GLArrayDataWrapper.createFixed(GL_VERTEX_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride,
                                                                      pointer, 0, 0, 0, GL.GL_ARRAY_BUFFER));
                     }
                     public void glVertexPointer(int size, int type, int stride, long pointer_buffer_offset) {
                @@ -348,7 +348,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                       if(vboName==0) {
                         throw new GLException("no GL_ARRAY_BUFFER VBO bound");
                       }
                -      glVertexPointer(GLArrayDataWrapper.createFixed(GL_VERTEX_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride, 
                +      glVertexPointer(GLArrayDataWrapper.createFixed(GL_VERTEX_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride,
                                                                      null, vboName, pointer_buffer_offset, GL.GL_STATIC_DRAW, GL.GL_ARRAY_BUFFER));
                     }
                 
                @@ -368,7 +368,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                       fixedFunction.glColorPointer(gl, array);
                     }
                     public void glColorPointer(int size, int type, int stride, java.nio.Buffer pointer) {
                -      glColorPointer(GLArrayDataWrapper.createFixed(GL_COLOR_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride, 
                +      glColorPointer(GLArrayDataWrapper.createFixed(GL_COLOR_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride,
                                                                     pointer, 0, 0, 0, GL.GL_ARRAY_BUFFER));
                     }
                     public void glColorPointer(int size, int type, int stride, long pointer_buffer_offset) {
                @@ -376,7 +376,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                       if(vboName==0) {
                         throw new GLException("no GL_ARRAY_BUFFER VBO bound");
                       }
                -      glColorPointer(GLArrayDataWrapper.createFixed(GL_COLOR_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride, 
                +      glColorPointer(GLArrayDataWrapper.createFixed(GL_COLOR_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride,
                                                                    null, vboName, pointer_buffer_offset, GL.GL_STATIC_DRAW, GL.GL_ARRAY_BUFFER));
                     }
                 
                @@ -399,7 +399,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                       fixedFunction.glNormalPointer(gl, array);
                     }
                     public void glNormalPointer(int type, int stride, java.nio.Buffer pointer) {
                -      glNormalPointer(GLArrayDataWrapper.createFixed(GL_NORMAL_ARRAY, 3, type, GLBuffers.isGLTypeFixedPoint(type), stride, 
                +      glNormalPointer(GLArrayDataWrapper.createFixed(GL_NORMAL_ARRAY, 3, type, GLBuffers.isGLTypeFixedPoint(type), stride,
                                                                      pointer, 0, 0, 0, GL.GL_ARRAY_BUFFER));
                     }
                     public void glNormalPointer(int type, int stride, long pointer_buffer_offset) {
                @@ -407,7 +407,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                       if(vboName==0) {
                         throw new GLException("no GL_ARRAY_BUFFER VBO bound");
                       }
                -      glNormalPointer(GLArrayDataWrapper.createFixed(GL_NORMAL_ARRAY, 3, type, GLBuffers.isGLTypeFixedPoint(type), stride, 
                +      glNormalPointer(GLArrayDataWrapper.createFixed(GL_NORMAL_ARRAY, 3, type, GLBuffers.isGLTypeFixedPoint(type), stride,
                                                                      null, vboName, pointer_buffer_offset, GL.GL_STATIC_DRAW, GL.GL_ARRAY_BUFFER));
                     }
                 
                @@ -428,7 +428,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                     }
                     public void glTexCoordPointer(int size, int type, int stride, java.nio.Buffer pointer) {
                       glTexCoordPointer(
                -        GLArrayDataWrapper.createFixed(GL_TEXTURE_COORD_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride, 
                +        GLArrayDataWrapper.createFixed(GL_TEXTURE_COORD_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride,
                                                        pointer, 0, 0, 0, GL.GL_ARRAY_BUFFER));
                     }
                     public void glTexCoordPointer(int size, int type, int stride, long pointer_buffer_offset) {
                @@ -437,7 +437,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
                         throw new GLException("no GL_ARRAY_BUFFER VBO bound");
                       }
                       glTexCoordPointer(
                -        GLArrayDataWrapper.createFixed(GL_TEXTURE_COORD_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride, 
                +        GLArrayDataWrapper.createFixed(GL_TEXTURE_COORD_ARRAY, size, type, GLBuffers.isGLTypeFixedPoint(type), stride,
                                                        null, vboName, pointer_buffer_offset, GL.GL_STATIC_DRAW, GL.GL_ARRAY_BUFFER) );
                     }
                 
                diff --git a/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java b/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java
                index 5349745ea..187fdb309 100644
                --- a/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java
                +++ b/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java
                @@ -59,25 +59,25 @@ import com.jogamp.opengl.util.glsl.ShaderState;
                 import com.jogamp.opengl.util.glsl.fixedfunc.ShaderSelectionMode;
                 
                 /**
                - * 
                + *
                  * 

                - * Note: Certain GL FFP state values (e.g.: alphaTestFunc and cullFace) - * are mapped to a lower number range so they can be stored in low precision storage, + * Note: Certain GL FFP state values (e.g.: alphaTestFunc and cullFace) + * are mapped to a lower number range so they can be stored in low precision storage, * i.e. in a 'lowp int' (GL ES2). *

                */ public class FixedFuncPipeline { protected static final boolean DEBUG; - + static { Debug.initSingleton(); DEBUG = Debug.isPropertyDefined("jogl.debug.FixedFuncPipeline", true); } - + /** The maximum texture units which could be used, depending on {@link ShaderSelectionMode}. */ public static final int MAX_TEXTURE_UNITS = 8; public static final int MAX_LIGHTS = 8; - + public FixedFuncPipeline(GL2ES2 gl, ShaderSelectionMode mode, PMVMatrix pmvMatrix) { shaderRootClass = FixedFuncPipeline.class; shaderSrcRoot = shaderSrcRootDef; @@ -88,8 +88,8 @@ public class FixedFuncPipeline { fragmentColorTextureFile = fragmentColorTextureFileDef; init(gl, mode, pmvMatrix); } - public FixedFuncPipeline(GL2ES2 gl, ShaderSelectionMode mode, PMVMatrix pmvMatrix, - Class shaderRootClass, String shaderSrcRoot, + public FixedFuncPipeline(GL2ES2 gl, ShaderSelectionMode mode, PMVMatrix pmvMatrix, + Class shaderRootClass, String shaderSrcRoot, String shaderBinRoot, String vertexColorFile, String vertexColorLightFile, String fragmentColorFile, String fragmentColorTextureFile) { @@ -100,9 +100,9 @@ public class FixedFuncPipeline { this.vertexColorLightFile = vertexColorLightFile; this.fragmentColorFile = fragmentColorFile; this.fragmentColorTextureFile = fragmentColorTextureFile; - init(gl, mode, pmvMatrix); + init(gl, mode, pmvMatrix); } - + public ShaderSelectionMode getShaderSelectionMode() { return requestedShaderSelectionMode; } public void setShaderSelectionMode(ShaderSelectionMode mode) { requestedShaderSelectionMode=mode; } public ShaderSelectionMode getCurrentShaderSelectionMode() { return currentShaderSelectionMode; } @@ -153,21 +153,21 @@ public class FixedFuncPipeline { colorStatic.put(1, green); colorStatic.put(2, blue); colorStatic.put(3, alpha); - + shaderState.useProgram(gl, true); - final GLUniformData ud = shaderState.getUniform(mgl_ColorStatic); + final GLUniformData ud = shaderState.getUniform(mgl_ColorStatic); if(null!=ud) { // same data object .. shaderState.uniform(gl, ud); } else { throw new GLException("Failed to update: mgl_ColorStatic"); - } + } } - + // // Arrays / States // - + public void glEnableClientState(GL2ES2 gl, int glArrayIndex) { glToggleClientState(gl, glArrayIndex, true); } @@ -202,7 +202,7 @@ public class FixedFuncPipeline { break; } } - + public void glVertexPointer(GL2ES2 gl, GLArrayData data) { shaderState.useProgram(gl, true); shaderState.vertexAttribPointer(gl, data); @@ -217,14 +217,14 @@ public class FixedFuncPipeline { shaderState.useProgram(gl, true); shaderState.vertexAttribPointer(gl, data); } - + // // MULTI-TEXTURE // /** Enables/Disables the named texture unit (if changed), returns previous state */ private boolean glEnableTexture(boolean enable, int unit) { - final boolean isEnabled = 0 != ( textureEnabledBits & ( 1 << activeTextureUnit ) ); + final boolean isEnabled = 0 != ( textureEnabledBits & ( 1 << activeTextureUnit ) ); if( isEnabled != enable ) { if(enable) { textureEnabledBits |= ( 1 << unit ); @@ -237,7 +237,7 @@ public class FixedFuncPipeline { } return isEnabled; } - + public void glClientActiveTexture(int textureUnit) { textureUnit -= GL.GL_TEXTURE0; if(0 <= textureUnit && textureUnit "+toHexString(ifmt)); } } else { - System.err.println("FixedFuncPipeline: Unimplemented glTexImage2D: target "+toHexString(target)+", internalformat "+toHexString(internalformat)); + System.err.println("FixedFuncPipeline: Unimplemented glTexImage2D: target "+toHexString(target)+", internalformat "+toHexString(internalformat)); } } /* public void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, - int format, int type, long pixels_buffer_offset) { + int format, int type, long pixels_buffer_offset) { textureFormat.put(activeTextureUnit, internalformat); textureFormatDirty = true; }*/ - + public void glTexEnvi(int target, int pname, int value) { if(GL2ES1.GL_TEXTURE_ENV == target && GL2ES1.GL_TEXTURE_ENV_MODE == pname) { final int mode; @@ -351,7 +351,7 @@ public class FixedFuncPipeline { if( value != textureEnvMode.get(activeTextureUnit) ) { textureEnvMode.put(activeTextureUnit, value); textureEnvModeDirty = true; - } + } } public void glGetTexEnviv(int target, int pname, IntBuffer params) { // FIXME System.err.println("FixedFuncPipeline: Unimplemented glGetTexEnviv: target "+toHexString(target)+", pname "+toHexString(pname)); @@ -359,13 +359,13 @@ public class FixedFuncPipeline { public void glGetTexEnviv(int target, int pname, int[] params, int params_offset) { // FIXME System.err.println("FixedFuncPipeline: Unimplemented glGetTexEnviv: target "+toHexString(target)+", pname "+toHexString(pname)); } - + // // Point Sprites // public void glPointSize(float size) { pointParams.put(0, size); - pointParamsDirty = true; + pointParamsDirty = true; } public void glPointParameterf(int pname, float param) { switch(pname) { @@ -379,7 +379,7 @@ public class FixedFuncPipeline { pointParams.put(4+3, param); break; } - pointParamsDirty = true; + pointParamsDirty = true; } public void glPointParameterfv(int pname, float[] params, int params_offset) { switch(pname) { @@ -389,7 +389,7 @@ public class FixedFuncPipeline { pointParams.put(4+2, params[params_offset + 2]); break; } - pointParamsDirty = true; + pointParamsDirty = true; } public void glPointParameterfv(int pname, java.nio.FloatBuffer params) { final int o = params.position(); @@ -400,24 +400,24 @@ public class FixedFuncPipeline { pointParams.put(4+2, params.get(o + 2)); break; } - pointParamsDirty = true; + pointParamsDirty = true; } // private int[] pointTexObj = new int[] { 0 }; - + private void glDrawPoints(GL2ES2 gl, GLRunnable2 glDrawAction, Object args) { if(gl.isGL2GL3()) { gl.glEnable(GL2GL3.GL_VERTEX_PROGRAM_POINT_SIZE); } if(gl.isGL2ES1()) { gl.glEnable(GL2ES1.GL_POINT_SPRITE); - } + } loadShaderPoints(gl); shaderState.attachShaderProgram(gl, shaderProgramPoints, true); validate(gl, false); // sync uniforms glDrawAction.run(gl, args); - + if(gl.isGL2ES1()) { gl.glDisable(GL2ES1.GL_POINT_SPRITE); } @@ -432,17 +432,17 @@ public class FixedFuncPipeline { int[] _args = (int[])args; gl.glDrawArrays(GL.GL_POINTS, _args[0], _args[1]); return null; - } - }; + } + }; private final void glDrawPointArrays(GL2ES2 gl, int first, int count) { - glDrawPoints(gl, glDrawArraysAction, new int[] { first, count }); + glDrawPoints(gl, glDrawArraysAction, new int[] { first, count }); } - + // // Lighting - // + // - public void glLightfv(GL2ES2 gl, int light, int pname, java.nio.FloatBuffer params) { + public void glLightfv(GL2ES2 gl, int light, int pname, java.nio.FloatBuffer params) { shaderState.useProgram(gl, true); light -=GLLightingFunc.GL_LIGHT0; if(0 <= light && light < MAX_LIGHTS) { @@ -536,14 +536,14 @@ public class FixedFuncPipeline { ud.setData(params); shaderState.uniform(gl, ud); } else if(verbose) { - + } } // // Misc States // - + public void glShadeModel(GL2ES2 gl, int mode) { shaderState.useProgram(gl, true); GLUniformData ud = shaderState.getUniform(mgl_ShadeModel); @@ -608,7 +608,7 @@ public class FixedFuncPipeline { _func = 8; break; default: - throw new GLException("glAlphaFunc invalid func: "+toHexString(func)); + throw new GLException("glAlphaFunc invalid func: "+toHexString(func)); } if(0 < _func) { if(0>alphaTestFunc) { @@ -623,7 +623,7 @@ public class FixedFuncPipeline { } /** - * @return false if digested in regard to GL2ES2 spec, + * @return false if digested in regard to GL2ES2 spec, * eg this call must not be passed to an underlying ES2 implementation. * true if this call shall be passed to an underlying GL2ES2/ES2 implementation as well. */ @@ -631,16 +631,16 @@ public class FixedFuncPipeline { switch(cap) { case GL.GL_BLEND: case GL.GL_DEPTH_TEST: - case GL.GL_DITHER: + case GL.GL_DITHER: case GL.GL_POLYGON_OFFSET_FILL: case GL.GL_SAMPLE_ALPHA_TO_COVERAGE: case GL.GL_SAMPLE_COVERAGE: case GL.GL_SCISSOR_TEST: case GL.GL_STENCIL_TEST: return true; - + case GL.GL_CULL_FACE: - /** ES2 supports CullFace implicit + /** ES2 supports CullFace implicit final int _cullFace; if(0>cullFace && enable || 0alphaTestFunc && enable || 0=0; i--) { @@ -776,12 +776,12 @@ public class FixedFuncPipeline { } return n; } - + public void validate(GL2ES2 gl, boolean selectShader) { if( selectShader ) { if( ShaderSelectionMode.AUTO == requestedShaderSelectionMode) { final ShaderSelectionMode newMode; - + // pre-validate shader switch if( 0 != textureEnabledBits ) { if(lightingEnabled) { @@ -808,9 +808,9 @@ public class FixedFuncPipeline { shaderState.useProgram(gl, true); } } - + GLUniformData ud; - if( pmvMatrix.update() ) { + if( pmvMatrix.update() ) { ud = shaderState.getUniform(mgl_PMVMatrix); if(null!=ud) { final FloatBuffer m; @@ -818,7 +818,7 @@ public class FixedFuncPipeline { ShaderSelectionMode.COLOR_LIGHT_PER_VERTEX== currentShaderSelectionMode ) { m = pmvMatrix.glGetPMvMvitMatrixf(); } else { - m = pmvMatrix.glGetPMvMatrixf(); + m = pmvMatrix.glGetPMvMatrixf(); } if(m != ud.getBuffer()) { ud.setData(m); @@ -829,7 +829,7 @@ public class FixedFuncPipeline { throw new GLException("Failed to update: mgl_PMVMatrix"); } } - if(colorVAEnabledDirty) { + if(colorVAEnabledDirty) { ud = shaderState.getUniform(mgl_ColorEnabled); if(null!=ud) { int ca = true == shaderState.isVertexAttribArrayEnabled(GLPointerFuncUtil.mgl_Color) ? 1 : 0 ; @@ -838,7 +838,7 @@ public class FixedFuncPipeline { shaderState.uniform(gl, ud); } } else { - throw new GLException("Failed to update: mgl_ColorEnabled"); + throw new GLException("Failed to update: mgl_ColorEnabled"); } colorVAEnabledDirty = false; } @@ -868,16 +868,16 @@ public class FixedFuncPipeline { if(pointParamsDirty) { ud = shaderState.getUniform(mgl_PointParams); if(null!=ud) { - // same data object + // same data object shaderState.uniform(gl, ud); } pointParamsDirty = false; } - + if(lightsEnabledDirty) { ud = shaderState.getUniform(mgl_LightsEnabled); if(null!=ud) { - // same data object + // same data object shaderState.uniform(gl, ud); } lightsEnabledDirty=false; @@ -886,41 +886,41 @@ public class FixedFuncPipeline { if(textureCoordEnabledDirty) { ud = shaderState.getUniform(mgl_TexCoordEnabled); if(null!=ud) { - // same data object + // same data object shaderState.uniform(gl, ud); } textureCoordEnabledDirty=false; - } + } if(textureEnvModeDirty) { ud = shaderState.getUniform(mgl_TexEnvMode); if(null!=ud) { - // same data object + // same data object shaderState.uniform(gl, ud); } textureEnvModeDirty = false; } - + if(textureFormatDirty) { for(int i = 0; i shaderRootClass; - private final String shaderSrcRoot; + private final String shaderSrcRoot; private final String shaderBinRoot; private final String vertexColorFile; private final String vertexColorLightFile; private final String fragmentColorFile; - private final String fragmentColorTextureFile; + private final String fragmentColorTextureFile; } diff --git a/src/jogl/classes/jogamp/opengl/util/jpeg/JPEGDecoder.java b/src/jogl/classes/jogamp/opengl/util/jpeg/JPEGDecoder.java index 833771dd1..1833a1d87 100644 --- a/src/jogl/classes/jogamp/opengl/util/jpeg/JPEGDecoder.java +++ b/src/jogl/classes/jogamp/opengl/util/jpeg/JPEGDecoder.java @@ -1,16 +1,16 @@ /** * Original JavaScript code from , * ported to Java for JogAmp Community. - * + * * Enhancements: * * InputStream instead of memory buffer * * User provided memory handler - * * Fixed JPEG Component ID/Index mapping + * * Fixed JPEG Component ID/Index mapping * * Color space conversion (YCCK, CMYK -> RGB) * * More error tolerant - * + * * ***************** - * + * * Copyright 2011 notmasteryet * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,21 +24,21 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * ***************** - * + * * Copyright 2013 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: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -48,7 +48,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -70,7 +70,7 @@ import com.jogamp.opengl.util.texture.TextureData; import com.jogamp.opengl.util.texture.TextureData.ColorSpace; /** - * + * *
                  *
                • The JPEG specification can be found in the ITU CCITT Recommendation T.81 * (www.w3.org/Graphics/JPEG/itu-t81.pdf)
                • @@ -89,22 +89,22 @@ public class JPEGDecoder { private static final boolean DEBUG = Debug.debug("JPEGImage"); private static final boolean DEBUG_IN = false; - /** Allows user to hook a {@link ColorSink} to another toolkit to produce {@link TextureData}. */ + /** Allows user to hook a {@link ColorSink} to another toolkit to produce {@link TextureData}. */ public static interface ColorSink { /** * @param width * @param height * @param sourceCS the color-space of the decoded JPEG * @param sourceComponents number of components used for the given source color-space - * @return Either {@link TextureData.ColorSpace#RGB} or {@link TextureData.ColorSpace#YCbCr}. {@link TextureData.ColorSpace#YCCK} and {@link TextureData.ColorSpace#CMYK} will throw an exception! + * @return Either {@link TextureData.ColorSpace#RGB} or {@link TextureData.ColorSpace#YCbCr}. {@link TextureData.ColorSpace#YCCK} and {@link TextureData.ColorSpace#CMYK} will throw an exception! * @throws RuntimeException */ public TextureData.ColorSpace allocate(int width, int height, TextureData.ColorSpace sourceCS, int sourceComponents) throws RuntimeException; public void store2(int x, int y, byte c1, byte c2); public void storeRGB(int x, int y, byte r, byte g, byte b); - public void storeYCbCr(int x, int y, byte Y, byte Cb, byte Cr); + public void storeYCbCr(int x, int y, byte Y, byte Cb, byte Cr); } - + public static class JFIF { final VersionNumber version; final int densityUnits; @@ -138,11 +138,11 @@ public class JPEGDecoder { } else { return null; } - } + } public final String toString() { return "JFIF[ver "+version+", density[units "+densityUnits+", "+xDensity+"x"+yDensity+"], thumb "+thumbWidth+"x"+thumbHeight+"]"; - } + } } public static class Adobe { @@ -151,7 +151,7 @@ public class JPEGDecoder { final short flags1; final short colorCode; final ColorSpace colorSpace; - + private Adobe(final byte[] data) { version = data[6]; flags0 = (short) ( (data[7] << 8) | data[8] ) ; @@ -174,7 +174,7 @@ public class JPEGDecoder { } public final String toString() { return "Adobe[ver "+version+", flags["+toHexString(flags0)+", "+toHexString(flags1)+"], colorSpace/Code "+colorSpace+"/"+toHexString(colorCode)+"]"; - } + } } /** TODO */ public static class EXIF { @@ -189,10 +189,10 @@ public class JPEGDecoder { } else { return null; } - } + } public final String toString() { return "EXIF[]"; - } + } } @SuppressWarnings("serial") @@ -210,7 +210,7 @@ public class JPEGDecoder { } public int getMarker() { return marker; } } - + /** Start of Image */ private static final int M_SOI = 0xFFD8; /** End of Image */ @@ -264,8 +264,8 @@ public class JPEGDecoder { private static final int M_APP15 = 0xFFEF; /** Annotation / Comment */ - private static final int M_ANO = 0xFFFE; - + private static final int M_ANO = 0xFFFE; + static final int[] dctZigZag = new int[] { 0, 1, 8, @@ -323,7 +323,7 @@ public class JPEGDecoder { private final void checkBounds(int idx) { if( 0 > idx || idx >= compCount ) { throw new CodecException("Idx out of bounds "+idx+", "+this); - } + } } public final void validateComponents() { for(int i=0; i= blocksPerColumnForMcu || col >= blocksPerLineForMcu ) { throw new CodecException("Out of bounds given ["+row+"]["+col+"] - "+this); } - return blocks[row][col]; + return blocks[row][col]; } - + public final String toString() { return "CompIn[h "+h+", v "+v+", qttIdx "+qttIdx+", blocks["+blocksPerColumn+", mcu "+blocksPerColumnForMcu+"]["+blocksPerLine+", mcu "+blocksPerLineForMcu+"][64]]"; } @@ -410,7 +410,7 @@ public class JPEGDecoder { /** The decoded components */ class ComponentOut { - private final ArrayList lines; + private final ArrayList lines; final float scaleX; final float scaleY; @@ -419,13 +419,13 @@ public class JPEGDecoder { this.scaleX = scaleX; this.scaleY = scaleY; } - + /** Safely returning a line, if index exceeds number of lines, last line is returned. */ public final byte[] getLine(int i) { final int sz = lines.size(); return lines.get( i < sz ? i : sz - 1); } - + public final String toString() { return "CompOut[lines "+lines.size()+", scale "+scaleX+"x"+scaleY+"]"; } @@ -442,7 +442,7 @@ public class JPEGDecoder { private BufferedInputStream istream; private int _ipos = 0; private int _iposSave = 0; - + private int width = 0; private int height = 0; private JFIF jfif = null; @@ -457,14 +457,14 @@ public class JPEGDecoder { public final int getHeight() { return height; } private final void resetInput(InputStream is) { - if( is instanceof BufferedInputStream ) { + if( is instanceof BufferedInputStream ) { istream = (BufferedInputStream) is; } else { istream = new BufferedInputStream(is); } _ipos = 0; } - + private final void markStream(int readLimit) { istream.mark(readLimit); _iposSave = _ipos; @@ -480,7 +480,7 @@ public class JPEGDecoder { if( -1 < r ) { if(DEBUG_IN) { System.err.println("u8["+_ipos+"]: "+toHexString(r)); } _ipos++; - } else if(DEBUG_IN) { + } else if(DEBUG_IN) { System.err.println("u8["+_ipos+"]: EOS"); } return r; @@ -519,7 +519,7 @@ public class JPEGDecoder { } if(DEBUG_IN) { System.err.println("JPEG.readDataBlock: net-len "+(len-2)+", "+this); dumpData(data, 0, len-2); } return data; - } + } static final void dumpData(byte[] data, int offset, int len) { for(int i=0; i frames = new ArrayList(); // JAU: max 1-frame - + Frame frame = null; int resetInterval = 0; int fileMarker = readUint16(); @@ -614,7 +614,7 @@ public class JPEGDecoder { quantizationTables[tableIdx] = tableData; if( DEBUG ) { System.err.println("JPEG.parse.QTT["+tableIdx+"]: spec "+quantizationTableSpec+", precision "+precisionID+", data "+count+"/"+quantizationTablesLength); - } + } } if(count!=quantizationTablesLength){ throw new CodecException("ERROR: QTT format error [count!=Length]: "+count+"/"+quantizationTablesLength); @@ -660,7 +660,7 @@ public class JPEGDecoder { } break; - case M_DHT: { + case M_DHT: { int count = 0; final int huffmanLength = readUint16(); count+=2; int i=count, codeLengthTotal = 0; @@ -675,7 +675,7 @@ public class JPEGDecoder { for (int j = 0; j < codeLengthSum; j++) { huffmanValues[j] = (byte)readUint8(); count++; } - codeLengthTotal += codeLengthSum; + codeLengthTotal += codeLengthSum; i += 17 + codeLengthSum; final BinObj[] table = ( huffmanTableSpec >> 4 ) == 0 ? huffmanTablesDC : huffmanTablesAC; table[huffmanTableSpec & 0x0F] = buildHuffmanTable(codeLengths, huffmanValues); @@ -699,7 +699,7 @@ public class JPEGDecoder { final int sosLen = readUint16(); count+=2; final int selectorsCount = readUint8(); count++; ArrayList components = new ArrayList(); - if(DEBUG) { System.err.println("JPG.parse.SOS: selectorCount [0.."+(selectorsCount-1)+"]: "+frame); } + if(DEBUG) { System.err.println("JPG.parse.SOS: selectorCount [0.."+(selectorsCount-1)+"]: "+frame); } for (int i = 0; i < selectorsCount; i++) { final int compID = readUint8(); count++; final ComponentIn component = frame.getCompByID(compID); @@ -751,8 +751,8 @@ public class JPEGDecoder { final ComponentIn component = frame.getCompByIndex(i); // System.err.println("JPG.parse.buildComponentData["+i+"]: "+component); // JAU // System.err.println("JPG.parse.buildComponentData["+i+"]: "+frame); // JAU - this.components[i] = new ComponentOut( output.buildComponentData(frame, component), - (float)component.h / (float)frame.maxH, + this.components[i] = new ComponentOut( output.buildComponentData(frame, component), + (float)component.h / (float)frame.maxH, (float)component.v / (float)frame.maxV ); } if(DEBUG) { System.err.println("JPG.parse.X: End of processing input "+this); } @@ -797,7 +797,7 @@ public class JPEGDecoder { final boolean isValue; final BinObj[] tree; final byte b; - + BinObj(byte b) { this.isValue= true; this.b = b; @@ -815,13 +815,13 @@ public class JPEGDecoder { } private BinObj buildHuffmanTable(int[] codeLengths, byte[] values) { - int k = 0; - int length = 16; + int k = 0; + int length = 16; final ArrayList code = new ArrayList(); while (length > 0 && 0==codeLengths[length - 1]) { length--; } - code.add(new BinObjIdxed()); + code.add(new BinObjIdxed()); BinObjIdxed p = code.get(0), q; for (int i = 0; i < length; i++) { for (int j = 0; j < codeLengths[i]; j++) { @@ -959,7 +959,7 @@ public class JPEGDecoder { t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; v6 = t; - + // stage 1 p[0 + row] = v0 + v7; p[7 + row] = v0 - v7; @@ -1066,7 +1066,7 @@ public class JPEGDecoder { private int successiveACState, successiveACNextValue; private int decodeScan(Frame frame, ArrayList components, int resetInterval, - int spectralStart, int spectralEnd, int successivePrev, int successive) throws IOException { + int spectralStart, int spectralEnd, int successivePrev, int successive) throws IOException { // this.precision = frame.precision; // this.samplesPerLine = frame.samplesPerLine; // this.scanLines = frame.scanLines; @@ -1079,7 +1079,7 @@ public class JPEGDecoder { this.spectralStart = spectralStart; this.spectralEnd = spectralEnd; this.successive = successive; - + final int componentsLength = components.size(); final DecoderFunction decodeFn; @@ -1096,7 +1096,7 @@ public class JPEGDecoder { int mcu = 0; int mcuExpected; if (componentsLength == 1) { - final ComponentIn c = components.get(0); + final ComponentIn c = components.get(0); mcuExpected = c.blocksPerLine * c.blocksPerColumn; } else { mcuExpected = mcusPerLine * frame.mcusPerColumn; @@ -1153,14 +1153,14 @@ public class JPEGDecoder { if( marker < 0xFF00 ) { rewindStream(); throw new CodecException("marker not found @ mcu "+mcu+"/"+mcuExpected+", u16: "+toHexString(marker)); - } + } final boolean isRSTx = 0xFFD0 <= marker && marker <= 0xFFD7; // !RSTx if(DEBUG) { System.err.println("JPEG.decodeScan: MCUs "+mcu+"/"+mcuExpected+", u16 "+toHexString(marker)+", RSTx "+isRSTx+", "+frame); } if ( !isRSTx ) { break; // handle !RSTx marker in caller - } + } } return marker; } @@ -1306,7 +1306,7 @@ public class JPEGDecoder { successiveACState = 1; } } else { - // if (s !== 1) { + // if (s !== 1) { if (s != 1) { throw new CodecException("invalid ACn encoding"); } @@ -1380,18 +1380,18 @@ public class JPEGDecoder { int R = Y + ( ( 91881 * Cr ) >> 16 ); if(R<0) R=0; else if(R>255) R=255; - + pixelStorage.storeRGB(x, y, (byte)R, (byte)G, (byte)B); } */ - + public synchronized void getPixel(JPEGDecoder.ColorSink pixelStorage, int width, int height) { final int scaleX = this.width / width, scaleY = this.height / height; final int componentCount = this.components.length; - final ColorSpace sourceCS = ( null != adobe ) ? adobe.colorSpace : ColorSpace.YCbCr; + final ColorSpace sourceCS = ( null != adobe ) ? adobe.colorSpace : ColorSpace.YCbCr; final ColorSpace storageCS = pixelStorage.allocate(width, height, sourceCS, componentCount); if( ColorSpace.RGB != storageCS && ColorSpace.YCbCr != storageCS ) { - throw new IllegalArgumentException("Unsupported storage color space: "+storageCS); + throw new IllegalArgumentException("Unsupported storage color space: "+storageCS); } switch (componentCount) { @@ -1504,7 +1504,7 @@ public class JPEGDecoder { final byte G = clampTo8bit( ( cM * cK ) / 255f ); final byte B = clampTo8bit( ( cY * cK ) / 255f ); pixelStorage.storeRGB(x, y, R, G, B); - } + } } else { // ColorModel.YCCK == sourceCM for (int x = 0; x < width; x++) { final int xs = x * scaleX; @@ -1525,7 +1525,7 @@ public class JPEGDecoder { } } } - } + } break; default: throw new CodecException("Unsupported color model: Space "+sourceCS+", components "+componentCount); diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/FilterType.java b/src/jogl/classes/jogamp/opengl/util/pngj/FilterType.java index 0fffc85b1..5e177b8c3 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/FilterType.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/FilterType.java @@ -4,7 +4,7 @@ import java.util.HashMap; /** * Internal PNG predictor filter, or strategy to select it. - * + * */ public enum FilterType { /** diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/ImageInfo.java b/src/jogl/classes/jogamp/opengl/util/pngj/ImageInfo.java index e62134cd5..ac7b858e1 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/ImageInfo.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/ImageInfo.java @@ -98,7 +98,7 @@ public class ImageInfo { /** * Full constructor - * + * * @param cols * Width in pixels * @param rows diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/ImageLine.java b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLine.java index e34e6a226..906ce6373 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/ImageLine.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLine.java @@ -25,7 +25,7 @@ public class ImageLine { * Except for 'packed' formats (gray/indexed with 1-2-4 bitdepth) each * int is a "sample" (one for channel), (0-255 or 0-65535) in * the corresponding PNG sequence: R G B R G B... or - * R G B A R G B A... + * R G B A R G B A... * or g g g ... or i i i (palette index) *

                  * For bitdepth=1/2/4 , and if samplesUnpacked=false, each value is a PACKED @@ -60,7 +60,7 @@ public class ImageLine { /** * true: each element of the scanline array represents a sample always, even * for internally packed PNG formats - * + * * false: if the original image was of packed type (bit depth less than 8) * we keep samples packed in a single array element */ @@ -74,7 +74,7 @@ public class ImageLine { } /** - * + * * @param imgInfo * Inmutable ImageInfo, basic parameter of the image we are * reading or writing @@ -84,7 +84,7 @@ public class ImageLine { * @param unpackedMode * If true, we use unpacked format, even for packed original * images - * + * */ public ImageLine(ImageInfo imgInfo, SampleType stype, boolean unpackedMode) { this(imgInfo, stype, unpackedMode, null, null); @@ -124,13 +124,13 @@ public class ImageLine { /* * Unpacks scanline (for bitdepth 1-2-4) - * + * * Arrays must be prealocated. src : samplesPerRowPacked dst : samplesPerRow - * + * * This usually works in place (with src==dst and length=samplesPerRow)! - * + * * If not, you should only call this only when necesary (bitdepth <8) - * + * * If scale==true, it scales the value (just a bit shift) towards 0-255. */ static void unpackInplaceInt(final ImageInfo iminfo, final int[] src, final int[] dst, final boolean scale) { @@ -165,15 +165,15 @@ public class ImageLine { /* * Unpacks scanline (for bitdepth 1-2-4) - * + * * Arrays must be prealocated. src : samplesPerRow dst : samplesPerRowPacked - * + * * This usually works in place (with src==dst and length=samplesPerRow)! If not, you should only call this only when * necesary (bitdepth <8) - * + * * The trailing elements are trash - * - * + * + * * If scale==true, it scales the value (just a bit shift) towards 0-255. */ static void packInplaceInt(final ImageInfo iminfo, final int[] src, final int[] dst, final boolean scaled) { @@ -270,7 +270,7 @@ public class ImageLine { /** * Creates a new ImageLine similar to this, but unpacked - * + * * The caller must be sure that the original was really packed */ public ImageLine unpackToNewImageLine() { @@ -284,7 +284,7 @@ public class ImageLine { /** * Creates a new ImageLine similar to this, but packed - * + * * The caller must be sure that the original was really unpacked */ public ImageLine packToNewImageLine() { diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/ImageLineHelper.java b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLineHelper.java index 91516a704..438a69984 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/ImageLineHelper.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLineHelper.java @@ -23,7 +23,7 @@ public class ImageLineHelper { /** * Given an indexed line with a palette, unpacks as a RGB array, or RGBA if * a non nul PngChunkTRNS chunk is passed - * + * * @param line * ImageLine as returned from PngReader * @param pal @@ -143,7 +143,7 @@ public class ImageLineHelper { /** * integer packed R G B only for bitdepth=8! (does not check!) - * + * **/ public static int getPixelRGB8(ImageLine line, int column) { int offset = column * line.channels; @@ -252,7 +252,7 @@ public class ImageLineHelper { * scale==true, it scales the value (just a bit shift) towards 0-255. *

                  * You probably should use {@link ImageLine#unpackToNewImageLine()} - * + * */ public static int[] unpack(ImageInfo imgInfo, int[] src, int[] dst, boolean scale) { int len1 = imgInfo.samplesPerRow; @@ -282,7 +282,7 @@ public class ImageLineHelper { * Packs scanline (for bitdepth 1-2-4) from array into the scanline *

                  * If scale==true, it scales the value (just a bit shift). - * + * * You probably should use {@link ImageLine#packToNewImageLine()} */ public static int[] pack(ImageInfo imgInfo, int[] src, int[] dst, boolean scale) { diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/ImageLines.java b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLines.java index feb50e7b6..fb2cf5910 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/ImageLines.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLines.java @@ -5,7 +5,7 @@ import jogamp.opengl.util.pngj.ImageLine.SampleType; /** * Wraps in a matrix a set of image rows, not necessarily contiguous - but * equispaced. - * + * * The fields mirrors those of {@link ImageLine}, and you can access each row as * a ImageLine backed by the matrix row, see * {@link #getImageLineAtMatrixRow(int)} @@ -28,7 +28,7 @@ public class ImageLines { * Allocates a matrix to store {@code nRows} image rows. See * {@link ImageLine} and {@link PngReader#readRowsInt()} * {@link PngReader#readRowsByte()} - * + * * @param imgInfo * @param stype * @param unpackedMode @@ -77,7 +77,7 @@ public class ImageLines { /** * Converts from matrix row number (0 : nRows-1) to image row number - * + * * @param mrow * Matrix row number * @return Image row number. Invalid only if mrow is invalid @@ -88,7 +88,7 @@ public class ImageLines { /** * Returns a ImageLine is backed by the matrix, no allocation done - * + * * @param mrow * Matrix row, from 0 to nRows This is not necessarily the image * row, see {@link #imageRowToMatrixRow(int)} and diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngHelperInternal.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngHelperInternal.java index a950c6b33..1f598a5de 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/PngHelperInternal.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngHelperInternal.java @@ -49,7 +49,7 @@ public class PngHelperInternal { /** * -1 if eof - * + * * PNG uses "network byte order" */ public static int readInt2(InputStream is) { diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngReader.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngReader.java index e42dd8733..73442e0bb 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/PngReader.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngReader.java @@ -92,13 +92,13 @@ public class PngReader { * Constructs a PngReader from an InputStream. *

                  * See also FileHelper.createPngReader(File f) if available. - * + * * Reads only the signature and first chunk (IDHR) - * + * * @param filenameOrDescription * : Optional, can be a filename or a description. Just for * error/debug messages - * + * */ public PngReader(InputStream inputStream, String filenameOrDescription) { this.filename = filenameOrDescription == null ? "" : filenameOrDescription; @@ -411,7 +411,7 @@ public class PngReader { /** * Determines which ancillary chunks (metada) are to be loaded - * + * * @param chunkLoadBehaviour * {@link ChunkLoadBehaviour} */ @@ -427,7 +427,7 @@ public class PngReader { * replaced by a single dummy-marker IDAT chunk. These might be copied to * the PngWriter *

                  - * + * * @see #getMetadata() */ public ChunksList getChunksList() { @@ -442,7 +442,7 @@ public class PngReader { /** * High level wrapper over chunksList - * + * * @see #getChunksList() */ public PngMetadata getMetadata() { @@ -456,7 +456,7 @@ public class PngReader { * appropiate readRowInt/readRowByte *

                  * In general, specifying the concrete readRowInt/readRowByte is preferrable - * + * * @see #readRowInt(int) {@link #readRowByte(int)} */ public ImageLine readRow(int nrow) { @@ -468,9 +468,9 @@ public class PngReader { /** * Reads the row as INT, storing it in the {@link #imgLine} property and * returning it. - * + * * The row must be greater or equal than the last read row. - * + * * @param nrow * Row number, from 0 to rows-1. Increasing order. * @return ImageLine object, also available as field. Data is in @@ -490,10 +490,10 @@ public class PngReader { /** * Reads the row as BYTES, storing it in the {@link #imgLine} property and * returning it. - * + * * The row must be greater or equal than the last read row. This method * allows to pass the same row that was last read. - * + * * @param nrow * Row number, from 0 to rows-1. Increasing order. * @return ImageLine object, also available as field. Data is in @@ -524,13 +524,13 @@ public class PngReader { *

                  * If the bitdepth is less than 8, the bytes are packed - unless * {@link #unpackedMode} is true. - * + * * @param buffer * Prealocated buffer, or null. * @param nrow * Row number (0 is top). Most be strictly greater than the last * read row. - * + * * @return The scanline in the same passwd buffer if it was allocated, a * newly allocated one otherwise */ @@ -562,13 +562,13 @@ public class PngReader { * {@link #unpackedMode} is true.
                  * If the bitdepth is 16, the least significant byte is lost. *

                  - * + * * @param buffer * Prealocated buffer, or null. * @param nrow * Row number (0 is top). Most be strictly greater than the last * read row. - * + * * @return The scanline in the same passwd buffer if it was allocated, a * newly allocated one otherwise */ @@ -632,9 +632,9 @@ public class PngReader { *

                  * Notice that the columns in the matrix is not the pixel width of the * image, but rather pixels x channels - * + * * @see #readRowInt(int) to read about the format of each row - * + * * @param rowOffset * Number of rows to be skipped * @param nRows @@ -678,7 +678,7 @@ public class PngReader { /** * Same as readRowsInt(0, imgInfo.rows, 1) - * + * * @see #readRowsInt(int, int, int) */ public ImageLines readRowsInt() { @@ -696,10 +696,10 @@ public class PngReader { *

                  * Notice that the columns in the matrix is not the pixel width of the * image, but rather pixels x channels - * + * * @see #readRowByte(int) to read about the format of each row. Notice that * if the bitdepth is 16 this will lose information - * + * * @param rowOffset * Number of rows to be skipped * @param nRows @@ -743,7 +743,7 @@ public class PngReader { /** * Same as readRowsByte(0, imgInfo.rows, 1) - * + * * @see #readRowsByte(int, int, int) */ public ImageLines readRowsByte() { @@ -752,13 +752,13 @@ public class PngReader { /* * For the interlaced case, nrow indicates the subsampled image - the pass must be set already. - * + * * This must be called in strict order, both for interlaced or no interlaced. - * + * * Updates rowNum. - * + * * Leaves raw result in rowb - * + * * Returns bytes actually read (not including the filter byte) */ private int readRowRaw(final int nrow) { @@ -933,7 +933,7 @@ public class PngReader { * scanline will be sample. This implies more processing and memory, but * it's the most efficient option if you intend to read individual pixels.
                  * This option should only be set before start reading. - * + * * @param unPackedMode */ public void setUnpackedMode(boolean unPackedMode) { @@ -951,7 +951,7 @@ public class PngReader { * Tries to reuse the allocated buffers from other already used PngReader * object. This will have no effect if the buffers are smaller than necessary. * It also reuses the inflater. - * + * * @param other A PngReader that has already finished reading pixels. Can be null. */ public void reuseBuffersFrom(PngReader other) { @@ -977,7 +977,7 @@ public class PngReader { /** * Just for testing. TO be called after ending reading, only if * initCrctest() was called before start - * + * * @return CRC of the raw pixels values */ long getCrctestVal() { diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngWriter.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngWriter.java index 3e684a881..2f475aab1 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/PngWriter.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngWriter.java @@ -88,7 +88,7 @@ public class PngWriter { * filters) and queue chunks before start writing the pixels. *

                  * See also FileHelper.createPngWriter() if available. - * + * * @param outputStream * Opened stream for binary writing * @param imgInfo @@ -422,7 +422,7 @@ public class PngWriter { * Should be called when creating an image from another, before starting * writing lines, to copy relevant chunks. *

                  - * + * * @param reader * : PngReader object, already opened. * @param copy_mask @@ -439,7 +439,7 @@ public class PngWriter { * Should be called when creating an image from another, after writing all * lines, before closing the writer, to copy additional chunks. *

                  - * + * * @param reader * : PngReader object, already opened and fully read. * @param copy_mask @@ -455,7 +455,7 @@ public class PngWriter { *

                  * Actually: compressed size = total size of IDAT data , raw size = * uncompressed pixel bytes = rows * (bytesPerRow + 1). - * + * * This must be called after pngw.end() */ public double computeCompressionRatio() { @@ -512,7 +512,7 @@ public class PngWriter { * This must be called just after constructor, before starting writing. *

                  * See also setFilterType() - * + * * @param compLevel * between 0 and 9 (default:6 , recommended: 6 or more) */ @@ -528,7 +528,7 @@ public class PngWriter { * This must be called just after constructor, before starting writing. *

                  * See also setCompLevel() - * + * * @param filterType * One of the five prediction types or strategy to choose it (see * PngFilterType) Recommended values: DEFAULT @@ -542,7 +542,7 @@ public class PngWriter { * Sets maximum size of IDAT fragments. This has little effect on * performance you should rarely call this *

                  - * + * * @param idatMaxSize * default=0 : use defaultSize (32K) */ @@ -572,7 +572,7 @@ public class PngWriter { /** * Writes line, checks that the row number is consistent with that of the * ImageLine See writeRow(int[] newrow, int rown) - * + * * @deprecated Better use writeRow(ImageLine imgline, int rownumber) */ public void writeRow(ImageLine imgline) { @@ -581,9 +581,9 @@ public class PngWriter { /** * Writes line. See writeRow(int[] newrow, int rown) - * + * * The packed flag of the imageline is honoured! - * + * * @see #writeRowInt(int[], int) */ public void writeRow(ImageLine imgline, int rownumber) { @@ -596,7 +596,7 @@ public class PngWriter { /** * Same as writeRow(int[] newrow, int rown), but does not check row number - * + * * @param newrow */ public void writeRow(int[] newrow) { @@ -605,7 +605,7 @@ public class PngWriter { /** * Alias to writeRowInt - * + * * @see #writeRowInt(int[], int) */ public void writeRow(int[] newrow, int rown) { @@ -624,7 +624,7 @@ public class PngWriter { * Warning: the array might be modified in some cases (unpacked row with low * bitdepth) *

                  - * + * * @param newrow * Array of pixel values. Warning: the array size should be exact * (samplesPerRowP) @@ -642,7 +642,7 @@ public class PngWriter { * Same semantics as writeRowInt but using bytes. Each byte is still a * sample. If 16bitdepth, we are passing only the most significant byte (and * hence losing some info) - * + * * @see PngWriter#writeRowInt(int[], int) */ public void writeRowByte(byte[] newrow, int rown) { diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngjException.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngjException.java index 4a45cb5bf..97e24fc73 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/PngjException.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngjException.java @@ -2,9 +2,9 @@ package jogamp.opengl.util.pngj; /** * Generic exception - * + * * @author Hernan J Gonzalez - * + * */ public class PngjException extends RuntimeException { private static final long serialVersionUID = 1L; diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngjExceptionInternal.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngjExceptionInternal.java index c429b893b..5da70de7b 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/PngjExceptionInternal.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngjExceptionInternal.java @@ -3,9 +3,9 @@ package jogamp.opengl.util.pngj; /** * Exception for anomalous internal problems (sort of asserts) that point to * some issue with the library - * + * * @author Hernan J Gonzalez - * + * */ public class PngjExceptionInternal extends RuntimeException { private static final long serialVersionUID = 1L; diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkHelper.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkHelper.java index a995e4481..82abb902d 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkHelper.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkHelper.java @@ -59,7 +59,7 @@ public class ChunkHelper { }; /* - * static auxiliary buffer. any method that uses this should synchronize against this + * static auxiliary buffer. any method that uses this should synchronize against this */ private static byte[] tmpbuffer = new byte[4096]; @@ -136,7 +136,7 @@ public class ChunkHelper { /** * Finds position of null byte in array - * + * * @param b * @return -1 if not found */ @@ -149,7 +149,7 @@ public class ChunkHelper { /** * Decides if a chunk should be loaded, according to a ChunkLoadBehaviour - * + * * @param id * @param behav * @return true/false @@ -208,7 +208,7 @@ public class ChunkHelper { /** * Returns only the chunks that "match" the predicate - * + * * See also trimList() */ public static List filterList(List target, ChunkPredicate predicateKeep) { @@ -223,7 +223,7 @@ public class ChunkHelper { /** * Remove (in place) the chunks that "match" the predicate - * + * * See also filterList */ public static int trimList(List target, ChunkPredicate predicateRemove) { @@ -244,10 +244,10 @@ public class ChunkHelper { * they have same id and (perhaps, if multiple are allowed) if the match * also in some "internal key" (eg: key for string values, palette for sPLT, * etc) - * + * * Notice that the use of this is optional, and that the PNG standard allows * Text chunks that have same key - * + * * @return true if "equivalent" */ public static final boolean equivalent(PngChunk c1, PngChunk c2) { diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkLoadBehaviour.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkLoadBehaviour.java index 82ab3bcf9..1fa00380a 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkLoadBehaviour.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkLoadBehaviour.java @@ -15,7 +15,7 @@ public enum ChunkLoadBehaviour { */ LOAD_CHUNK_KNOWN, /** - * + * * Load chunk if "known" or "safe to copy". */ LOAD_CHUNK_IF_SAFE, diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkPredicate.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkPredicate.java index a750ae34f..4695ccf44 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkPredicate.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkPredicate.java @@ -6,7 +6,7 @@ package jogamp.opengl.util.pngj.chunks; public interface ChunkPredicate { /** * The other chunk matches with this one - * + * * @param chunk * @return true if match */ diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksList.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksList.java index 5ce94ff9f..3e0d03051 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksList.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksList.java @@ -24,7 +24,7 @@ public class ChunksList { /** * All chunks, read (or written) - * + * * But IDAT is a single pseudo chunk without data */ protected List chunks = new ArrayList(); @@ -37,7 +37,7 @@ public class ChunksList { /** * Keys of processed (read or writen) chunks - * + * * @return key:chunk id, val: number of occurrences */ public HashMap getChunksKeys() { @@ -87,7 +87,7 @@ public class ChunksList { /** * All chunks with this ID - * + * * @param id * @return List, empty if none */ @@ -98,7 +98,7 @@ public class ChunksList { /** * If innerid!=null and the chunk is PngChunkTextVar or PngChunkSPLT, it's * filtered by that id - * + * * @param id * @return innerid Only used for text and SPLT chunks * @return List, empty if none @@ -109,7 +109,7 @@ public class ChunksList { /** * Returns only one chunk - * + * * @param id * @return First chunk found, null if not found */ @@ -146,7 +146,7 @@ public class ChunksList { /** * Finds all chunks "equivalent" to this one - * + * * @param c2 * @return Empty if nothing found */ diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksListForWrite.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksListForWrite.java index e76456ad4..3b84ab800 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksListForWrite.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksListForWrite.java @@ -67,7 +67,7 @@ public class ChunksListForWrite extends ChunksList { /** * Remove Chunk: only from queued - * + * * WARNING: this depends on c.equals() implementation, which is * straightforward for SingleChunks. For MultipleChunks, it will normally * check for reference equality! @@ -78,9 +78,9 @@ public class ChunksListForWrite extends ChunksList { /** * Adds chunk to queue - * + * * Does not check for duplicated or anything - * + * * @param c */ public boolean queue(PngChunk c) { diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunk.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunk.java index a45979ec2..6cd86eb98 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunk.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunk.java @@ -248,7 +248,7 @@ public abstract class PngChunk { /** * Creates the physical chunk. This is used when writing (serialization). * Each particular chunk class implements its own logic. - * + * * @return A newly allocated and filled raw chunk */ public abstract ChunkRaw createRawChunk(); diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkBKGD.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkBKGD.java index 4a8502a3d..ea6235432 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkBKGD.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkBKGD.java @@ -70,7 +70,7 @@ public class PngChunkBKGD extends PngChunkSingle { /** * Set gray value (0-255 if bitdept=8) - * + * * @param gray */ public void setGray(int gray) { @@ -87,7 +87,7 @@ public class PngChunkBKGD extends PngChunkSingle { /** * Set pallette index - * + * */ public void setPaletteIndex(int i) { if (!imgInfo.indexed) @@ -103,7 +103,7 @@ public class PngChunkBKGD extends PngChunkSingle { /** * Set rgb values - * + * */ public void setRGB(int r, int g, int b) { if (imgInfo.greyscale || imgInfo.indexed) diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkMultiple.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkMultiple.java index d44250a2f..057f6c25e 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkMultiple.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkMultiple.java @@ -19,9 +19,9 @@ public abstract class PngChunkMultiple extends PngChunk { /** * NOTE: this chunk uses the default Object's equals() hashCode() * implementation. - * + * * This is the right thing to do, normally. - * + * * This is important, eg see ChunkList.removeFromList() */ diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSBIT.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSBIT.java index bc70c6e5e..3a490654a 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSBIT.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSBIT.java @@ -106,7 +106,7 @@ public class PngChunkSBIT extends PngChunkSingle { /** * Set rgb values - * + * */ public void setRGB(int r, int g, int b) { if (imgInfo.greyscale || imgInfo.indexed) diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTRNS.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTRNS.java index b68776477..867e34861 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTRNS.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTRNS.java @@ -82,7 +82,7 @@ public class PngChunkTRNS extends PngChunkSingle { /** * Set rgb values - * + * */ public void setRGB(int r, int g, int b) { if (imgInfo.greyscale || imgInfo.indexed) diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngMetadata.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngMetadata.java index ecf8b98c3..fa3649613 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngMetadata.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngMetadata.java @@ -87,7 +87,7 @@ public class PngMetadata { /** * Creates a time chunk with current time, less secsAgo seconds *

                  - * + * * @return Returns the created-queued chunk, just in case you want to * examine or modify it */ @@ -105,7 +105,7 @@ public class PngMetadata { /** * Creates a time chunk with diven date-time *

                  - * + * * @return Returns the created-queued chunk, just in case you want to * examine or modify it */ @@ -133,7 +133,7 @@ public class PngMetadata { /** * Creates a text chunk and queue it. *

                  - * + * * @param k * : key (latin1) * @param val @@ -201,7 +201,7 @@ public class PngMetadata { /** * Returns the palette chunk, if present - * + * * @return null if not present */ public PngChunkPLTE getPLTE() { @@ -220,7 +220,7 @@ public class PngMetadata { /** * Returns the TRNS chunk, if present - * + * * @return null if not present */ public PngChunkTRNS getTRNS() { diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java index bf2d3fa47..7a4e08d26 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java @@ -58,7 +58,7 @@ public class WGLGLCapabilities extends GLCapabilities { setRedBits(pfd.getCRedBits()); setGreenBits(pfd.getCGreenBits()); setBlueBits(pfd.getCBlueBits()); - setAlphaBits(pfd.getCAlphaBits()); + setAlphaBits(pfd.getCAlphaBits()); setAccumRedBits(pfd.getCAccumRedBits()); setAccumGreenBits(pfd.getCAccumGreenBits()); setAccumBlueBits(pfd.getCAccumBlueBits()); @@ -77,12 +77,12 @@ public class WGLGLCapabilities extends GLCapabilities { return true; } - + public static final String PFD2String(PIXELFORMATDESCRIPTOR pfd, int pfdID) { final int dwFlags = pfd.getDwFlags(); StringBuilder sb = new StringBuilder(); boolean sep = false; - + if( 0 != (GDI.PFD_DRAW_TO_WINDOW & dwFlags ) ) { sep = true; sb.append("window"); @@ -106,7 +106,7 @@ public class WGLGLCapabilities extends GLCapabilities { if( 0 == (GDI.PFD_GENERIC_FORMAT & dwFlags ) || 0 == (GDI.PFD_GENERIC_ACCELERATED & dwFlags ) ) { if(sep) { sb.append(CSEP); } sep=true; sb.append("hw-accel"); - } + } return "PFD[id = "+pfdID+" (0x"+Integer.toHexString(pfdID)+ "), colorBits "+pfd.getCColorBits()+", rgba "+pfd.getCRedBits()+ESEP+pfd.getCGreenBits()+ESEP+pfd.getCBlueBits()+ESEP+pfd.getCAlphaBits()+ ", accum-rgba "+pfd.getCAccumRedBits()+ESEP+pfd.getCAccumGreenBits()+ESEP+pfd.getCAccumBlueBits()+ESEP+pfd.getCAccumAlphaBits()+ diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java index 3e788d286..6454a34b5 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java @@ -33,15 +33,15 @@ import jogamp.opengl.Debug; public class WGLUtil { /** - * Switch to use the wgl variants of {@link jogamp.opengl.windows.wgl.WGL} + * Switch to use the wgl variants of {@link jogamp.opengl.windows.wgl.WGL} * to replace the following 5 GDI based functions (see below). *

                  * Disabled per default. - *

                  + *

                  *

                  * You can enable it by defining the property jogl.windows.useWGLVersionOf5WGLGDIFuncSet. *

                  - * + * * @see jogamp.nativewindow.windows.GDI#ChoosePixelFormat(long, PIXELFORMATDESCRIPTOR) * @see jogamp.nativewindow.windows.GDI#DescribePixelFormat(long, int, int, PIXELFORMATDESCRIPTOR) * @see jogamp.nativewindow.windows.GDI#GetPixelFormat(long) @@ -49,7 +49,7 @@ public class WGLUtil { * @see jogamp.nativewindow.windows.GDI#SwapBuffers(long) */ public static final boolean USE_WGLVersion_Of_5WGLGDIFuncSet; - + static { Debug.initSingleton(); USE_WGLVersion_Of_5WGLGDIFuncSet = Debug.isPropertyDefined("jogl.windows.useWGLVersionOf5WGLGDIFuncSet", true); @@ -63,34 +63,34 @@ public class WGLUtil { return WGL.wglChoosePixelFormat(hdc, pfd); } else { return GDI.ChoosePixelFormat(hdc, pfd); - } + } } public static int DescribePixelFormat(long hdc, int pfdid, int pfdSize, PIXELFORMATDESCRIPTOR pfd) { if(USE_WGLVersion_Of_5WGLGDIFuncSet) { return WGL.wglDescribePixelFormat(hdc, pfdid, pfdSize, pfd); } else { return GDI.DescribePixelFormat(hdc, pfdid, pfdSize, pfd); - } + } } public static int GetPixelFormat(long hdc) { if(USE_WGLVersion_Of_5WGLGDIFuncSet) { return WGL.wglGetPixelFormat(hdc); } else { return GDI.GetPixelFormat(hdc); - } + } } - public static boolean SetPixelFormat(long hdc, int pfdid, PIXELFORMATDESCRIPTOR pfd) { + public static boolean SetPixelFormat(long hdc, int pfdid, PIXELFORMATDESCRIPTOR pfd) { if(USE_WGLVersion_Of_5WGLGDIFuncSet) { return WGL.wglSetPixelFormat(hdc, pfdid, pfd); } else { return GDI.SetPixelFormat(hdc, pfdid, pfd); - } + } } - public static boolean SwapBuffers(long hdc) { + public static boolean SwapBuffers(long hdc) { if(USE_WGLVersion_Of_5WGLGDIFuncSet) { return WGL.wglSwapBuffers(hdc); } else { return GDI.SwapBuffers(hdc); - } + } } } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsBitmapWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsBitmapWGLDrawable.java index 909a017b0..f658a3598 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsBitmapWGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsBitmapWGLDrawable.java @@ -63,7 +63,7 @@ public class WindowsBitmapWGLDrawable extends WindowsWGLDrawable { private WindowsBitmapWGLDrawable(GLDrawableFactory factory, NativeSurface comp) { super(factory, comp, false); } - + protected static WindowsBitmapWGLDrawable create(GLDrawableFactory factory, NativeSurface comp) { final WindowsWGLGraphicsConfiguration config = (WindowsWGLGraphicsConfiguration)comp.getGraphicsConfiguration(); final AbstractGraphicsDevice aDevice = config.getScreen().getDevice(); @@ -102,7 +102,7 @@ public class WindowsBitmapWGLDrawable extends WindowsWGLDrawable { public boolean isGLOriented() { return false; } - + private void createBitmap() { int werr; final NativeSurface ns = getNativeSurface(); diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java index a5893775a..966a8b28a 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java @@ -56,7 +56,7 @@ import jogamp.nativewindow.windows.GDI; import jogamp.opengl.GLContextShareSet; public class WindowsExternalWGLContext extends WindowsWGLContext { - + private WindowsExternalWGLContext(Drawable drawable, long ctx, WindowsWGLGraphicsConfiguration cfg) { super(drawable, null); this.contextHandle = ctx; diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java index 217ca18e8..2e60c682b 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsPbufferWGLDrawable.java @@ -127,7 +127,7 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { } final int winattrPbuffer = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(false /* onscreen */, false /* fbo */, true /* pbuffer */, false /* bitmap */); - + final IntBuffer iattributes = Buffers.newDirectIntBuffer(2*WindowsWGLGraphicsConfiguration.MAX_ATTRIBS); final FloatBuffer fattributes = Buffers.newDirectFloatBuffer(1); int[] floatModeTmp = new int[1]; @@ -162,7 +162,7 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { if (DEBUG) { System.err.println("" + nformats + " suitable pixel formats found"); for (int i = 0; i < nformats; i++) { - WGLGLCapabilities dbgCaps = WindowsWGLGraphicsConfiguration.wglARBPFID2GLCapabilities(sharedResource, device, glProfile, + WGLGLCapabilities dbgCaps = WindowsWGLGraphicsConfiguration.wglARBPFID2GLCapabilities(sharedResource, device, glProfile, sharedHdc, pformats.get(i), winattrPbuffer); System.err.println("pixel format " + pformats.get(i) + " (index " + i + "): " + dbgCaps); } @@ -209,7 +209,7 @@ public class WindowsPbufferWGLDrawable extends WindowsWGLDrawable { // Re-query chosen pixel format { - WGLGLCapabilities newCaps = WindowsWGLGraphicsConfiguration.wglARBPFID2GLCapabilities(sharedResource, device, glProfile, + WGLGLCapabilities newCaps = WindowsWGLGraphicsConfiguration.wglARBPFID2GLCapabilities(sharedResource, device, glProfile, sharedHdc, pfdid, winattrPbuffer); if(null == newCaps) { throw new GLException("pbuffer creation error: unable to re-query chosen PFD ID: " + pfdid + ", hdc " + GLDrawableImpl.toHexString(tmpHdc)); diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java index 3fad22d88..d936308af 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java @@ -280,7 +280,7 @@ public class WindowsWGLContext extends GLContextImpl { if (DEBUG) { System.err.println(getThreadName() + ": createImpl: START "+glCaps+", share "+shareWith); } - + // Windows can set up sharing of display lists after creation time long share; if ( null != shareWith ) { @@ -405,7 +405,7 @@ public class WindowsWGLContext extends GLContextImpl { protected void makeCurrentImpl() throws GLException { if (WGL.wglGetCurrentContext() != contextHandle) { if (!wglMakeContextCurrent(drawable.getHandle(), drawableRead.getHandle(), contextHandle)) { - throw new GLException("Error making context " + toHexString(contextHandle) + + throw new GLException("Error making context " + toHexString(contextHandle) + " current on Thread " + getThreadName() + ", drawableWrite " + toHexString(drawable.getHandle()) + ", drawableRead "+ toHexString(drawableRead.getHandle()) + @@ -563,13 +563,13 @@ public class WindowsWGLContext extends GLContextImpl { } @Override - public final ByteBuffer glAllocateMemoryNV(int size, float readFrequency, float writeFrequency, float priority) { + public final ByteBuffer glAllocateMemoryNV(int size, float readFrequency, float writeFrequency, float priority) { return getWGLExt().wglAllocateMemoryNV(size, readFrequency, writeFrequency, priority); } - + @Override public final void glFreeMemoryNV(ByteBuffer pointer) { getWGLExt().wglFreeMemoryNV(pointer); } - + } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java index 741e671eb..66071cbe1 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java @@ -52,12 +52,12 @@ import jogamp.opengl.GLDynamicLookupHelper; public abstract class WindowsWGLDrawable extends GLDrawableImpl { private static final boolean PROFILING; - + static { Debug.initSingleton(); PROFILING = Debug.isPropertyDefined("jogl.debug.GLDrawable.profiling", true); } - + private static final int PROFILING_TICKS = 200; private int profilingSwapBuffersTicks; private long profilingSwapBuffersTime; @@ -87,11 +87,11 @@ public abstract class WindowsWGLDrawable extends GLDrawableImpl { } else { t0 = 0; } - + if (!WGLUtil.SwapBuffers(getHandle()) && (GDI.GetLastError() != GDI.ERROR_SUCCESS)) { throw new GLException("Error swapping buffers"); } - + if (PROFILING) { profilingSwapBuffersTime += System.currentTimeMillis() - t0; if (++profilingSwapBuffersTicks == PROFILING_TICKS) { diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java index 156e75196..203af110c 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java @@ -137,8 +137,8 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { protected final boolean isComplete() { return null != windowsWGLDynamicLookupHelper; } - - + + @Override protected final void destroy() { if(null != sharedResourceRunner) { @@ -216,7 +216,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { private AbstractGraphicsScreen screen; private GLDrawableImpl drawable; private GLContextImpl context; - + SharedResource(WindowsGraphicsDevice dev, AbstractGraphicsScreen scrn, GLDrawableImpl draw, GLContextImpl ctx, boolean arbPixelFormat, boolean arbMultisample, boolean arbPBuffer, boolean arbReadDrawable) { device = dev; @@ -243,7 +243,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { final public GLContextImpl getContext() { return context; } @Override public GLRendererQuirks getRendererQuirks() { - return null != context ? context.getRendererQuirks() : null; + return null != context ? context.getRendererQuirks() : null; } final boolean hasARBPixelFormat() { return hasARBPixelFormat; } @@ -276,7 +276,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { public boolean isDeviceSupported(String connection) { return true; } - + @Override public SharedResourceRunner.Resource createSharedResource(String connection) { final WindowsGraphicsDevice sharedDevice = new WindowsGraphicsDevice(connection, AbstractGraphicsDevice.DEFAULT_UNIT); @@ -290,7 +290,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { final GLCapabilitiesImmutable caps = new GLCapabilities(glp); final GLDrawableImpl sharedDrawable = createOnscreenDrawableImpl(createDummySurfaceImpl(sharedDevice, false, caps, caps, null, 64, 64)); sharedDrawable.setRealized(true); - + final GLContextImpl sharedContext = (GLContextImpl) sharedDrawable.createContext(null); if (null == sharedContext) { throw new GLException("Couldn't create shared context for drawable: "+sharedDrawable); @@ -473,8 +473,8 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { } @Override - protected final ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, - GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, + protected final ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final WindowsGraphicsDevice device; if(createNewDevice || !(deviceReq instanceof WindowsGraphicsDevice)) { @@ -485,13 +485,13 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { final AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); final WindowsWGLGraphicsConfiguration config = WindowsWGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen); if(null == config) { - throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); - } + throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); + } return new WrappedSurface(config, 0, upstreamHook, createNewDevice); } @Override - public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable chosenCaps, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { final WindowsGraphicsDevice device; if( createNewDevice || !(deviceReq instanceof WindowsGraphicsDevice) ) { @@ -502,12 +502,12 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { final AbstractGraphicsScreen screen = new DefaultGraphicsScreen(device, 0); chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(chosenCaps); final WindowsWGLGraphicsConfiguration config = WindowsWGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(chosenCaps, requestedCaps, chooser, screen); - if(null == config) { + if(null == config) { throw new GLException("Choosing GraphicsConfiguration failed w/ "+chosenCaps+" on "+screen); - } + } return new GDISurface(config, 0, new GDIDummyUpstreamSurfaceHook(width, height), createNewDevice); - } - + } + @Override protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { final WindowsGraphicsDevice device = new WindowsGraphicsDevice(deviceReq.getConnection(), deviceReq.getUnitID()); diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDynamicLibraryBundleInfo.java index 7ec6c50f8..6098cde7f 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDynamicLibraryBundleInfo.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl.windows.wgl; import jogamp.opengl.*; @@ -41,10 +41,10 @@ public final class WindowsWGLDynamicLibraryBundleInfo extends DesktopGLDynamicLi final List> libsList = new ArrayList>(); final List libsGL = new ArrayList(); libsGL.add("OpenGL32"); - libsList.add(libsGL); + libsList.add(libsGL); return libsList; } - + @Override public final List getToolGetProcAddressFuncNameList() { List res = new ArrayList(); diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java index 42b92305a..cb445f005 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -58,7 +58,7 @@ import jogamp.nativewindow.windows.MARGINS; import jogamp.nativewindow.windows.PIXELFORMATDESCRIPTOR; import jogamp.opengl.GLGraphicsConfigurationUtil; -public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable { +public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable { protected static final int MAX_PFORMATS = 256; protected static final int MAX_ATTRIBS = 256; @@ -66,7 +66,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio private boolean isDetermined = false; private boolean isExternal = false; - WindowsWGLGraphicsConfiguration(AbstractGraphicsScreen screen, + WindowsWGLGraphicsConfiguration(AbstractGraphicsScreen screen, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser) { super(screen, capsChosen, capsRequested); @@ -161,7 +161,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio if (0 == hdc) { throw new GLException("Error: HDC is null"); } - + if (!WGLUtil.SetPixelFormat(hdc, caps.getPFDID(), caps.getPFD())) { throw new GLException("Unable to set pixel format " + caps.getPFDID() + " of " + caps + " for device context " + toHexString(hdc) + @@ -192,7 +192,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } setCapsPFD(caps); } - + /** * Only sets this configuration's capabilities and marks it as determined, * the actual pixelformat is not set. @@ -209,20 +209,20 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio * External configuration's HDC pixelformat shall not be modified */ public final boolean isExternal() { return isExternal; } - + final void markExternal() { this.isExternal=true; } - + /** * Determined configuration states set target capabilties via {@link #setCapsPFD(WGLGLCapabilities)}, * but does not imply a set pixelformat. - * - * @see #setPixelFormat(long, WGLGLCapabilities) + * + * @see #setPixelFormat(long, WGLGLCapabilities) * @see #setCapsPFD(WGLGLCapabilities) */ public final boolean isDetermined() { return isDetermined; } - + public final PIXELFORMATDESCRIPTOR getPixelFormat() { return isDetermined ? ((WGLGLCapabilities)capabilitiesChosen).getPFD() : null; } public final int getPixelFormatID() { return isDetermined ? ((WGLGLCapabilities)capabilitiesChosen).getPFDID() : 0; } public final boolean isChoosenByARB() { return isDetermined ? ((WGLGLCapabilities)capabilitiesChosen).isSetByARB() : false; } @@ -255,7 +255,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } return niattribs; } - + static boolean wglARBPFIDValid(WindowsWGLContext sharedCtx, long hdc, int pfdID) { final IntBuffer out = Buffers.newDirectIntBuffer(1); final IntBuffer in = Buffers.newDirectIntBuffer(1); @@ -270,7 +270,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio static int wglARBPFDIDCount(WindowsWGLContext sharedCtx, long hdc) { final IntBuffer iresults = Buffers.newDirectIntBuffer(1); final IntBuffer iattributes = Buffers.newDirectIntBuffer(1); - iattributes.put(0, WGLExt.WGL_NUMBER_PIXEL_FORMATS_ARB); + iattributes.put(0, WGLExt.WGL_NUMBER_PIXEL_FORMATS_ARB); WGLExt wglExt = sharedCtx.getWGLExt(); // pfdID shall be ignored here (spec), however, pass a valid pdf index '1' below (possible driver bug) @@ -293,7 +293,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } return pfdIDCount; } - + static int[] wglAllARBPFDIDs(int pfdIDCount) { int[] pfdIDs = new int[pfdIDCount]; for (int i = 0; i < pfdIDCount; i++) { @@ -301,7 +301,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } return pfdIDs; } - + static WGLGLCapabilities wglARBPFID2GLCapabilities(WindowsWGLDrawableFactory.SharedResource sharedResource, AbstractGraphicsDevice device, GLProfile glp, long hdc, int pfdID, int winattrbits) { @@ -314,7 +314,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio final int niattribs = fillAttribsForGeneralWGLARBQuery(sharedResource, iattributes); if (!((WindowsWGLContext)sharedResource.getContext()).getWGLExt().wglGetPixelFormatAttribivARB(hdc, pfdID, 0, niattribs, iattributes, iresults)) { - throw new GLException("wglARBPFID2GLCapabilities: Error getting pixel format attributes for pixel format " + pfdID + + throw new GLException("wglARBPFID2GLCapabilities: Error getting pixel format attributes for pixel format " + pfdID + " of device context " + toHexString(hdc) + ", werr " + GDI.GetLastError()); } return AttribList2GLCapabilities(device, glp, hdc, pfdID, iattributes, niattribs, iresults, winattrbits); @@ -338,7 +338,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio final WGLExt wglExt = ((WindowsWGLContext)sharedResource.getContext()).getWGLExt(); final IntBuffer pformatsTmp = Buffers.newDirectIntBuffer(WindowsWGLGraphicsConfiguration.MAX_PFORMATS); final IntBuffer numFormatsTmp = Buffers.newDirectIntBuffer(1); - + if ( !wglExt.wglChoosePixelFormatARB(hdc, iattributes, fattributes, WindowsWGLGraphicsConfiguration.MAX_PFORMATS, pformatsTmp, numFormatsTmp) ) { @@ -388,7 +388,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio if(null != caps) { bucket.add(caps); if(DEBUG) { - final int j = bucket.size() - 1; + final int j = bucket.size() - 1; System.err.println("wglARBPFIDs2GLCapabilities: bucket["+i+" -> "+j+"]: "+caps); } } else if(DEBUG) { @@ -411,7 +411,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio IntBuffer iattributes, WindowsWGLDrawableFactory.SharedResource sharedResource, int accelerationValue, - int[] floatMode) throws GLException { + int[] floatMode) throws GLException { if (!sharedResource.hasARBPixelFormat()) { return false; } @@ -426,10 +426,10 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } final boolean usePBuffer = caps.isPBuffer() && sharedResource.hasARBPBuffer() ; - + final int surfaceType; if( caps.isOnscreen() ) { - surfaceType = WGLExt.WGL_DRAW_TO_WINDOW_ARB; + surfaceType = WGLExt.WGL_DRAW_TO_WINDOW_ARB; } else if( caps.isFBO() ) { surfaceType = WGLExt.WGL_DRAW_TO_WINDOW_ARB; // native replacement! } else if( usePBuffer ) { @@ -441,7 +441,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } iattributes.put(niattribs++, surfaceType); iattributes.put(niattribs++, GL.GL_TRUE); - + iattributes.put(niattribs++, WGLExt.WGL_DOUBLE_BUFFER_ARB); if (caps.getDoubleBuffered()) { iattributes.put(niattribs++, GL.GL_TRUE); @@ -455,7 +455,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } else { iattributes.put(niattribs++, GL.GL_FALSE); } - + iattributes.put(niattribs++, WGLExt.WGL_RED_BITS_ARB); iattributes.put(niattribs++, caps.getRedBits()); iattributes.put(niattribs++, WGLExt.WGL_GREEN_BITS_ARB); @@ -505,7 +505,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return true; } - static int AttribList2DrawableTypeBits(final IntBuffer iattribs, + static int AttribList2DrawableTypeBits(final IntBuffer iattribs, final int niattribs, final IntBuffer iresults) { int val = 0; @@ -533,7 +533,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return val; } - static WGLGLCapabilities AttribList2GLCapabilities(final AbstractGraphicsDevice device, + static WGLGLCapabilities AttribList2GLCapabilities(final AbstractGraphicsDevice device, final GLProfile glp, final long hdc, final int pfdID, final IntBuffer iattribs, final int niattribs, IntBuffer iresults, final int winattrmask) { final int allDrawableTypeBits = AttribList2DrawableTypeBits(iattribs, niattribs, iresults); @@ -554,7 +554,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } final WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); res.setValuesByARB(iattribs, niattribs, iresults); - return (WGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); + return (WGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); } // @@ -608,7 +608,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio } if( GLGraphicsConfigurationUtil.BITMAP_BIT == drawableTypeBits ) { // BITMAP exclusive PFD SafeGuard: Only accept BITMAP compatible color formats! - final int pfdColorBits = pfd.getCColorBits(); + final int pfdColorBits = pfd.getCColorBits(); if ( pfdColorBits != 24 || 0 < pfd.getCAlphaBits() ) { // Allowed: RGB888 && !alpha if(DEBUG) { System.err.println("Drop [color bits excl BITMAP]: " + WGLGLCapabilities.PFD2String(pfd, pfdID)); @@ -619,24 +619,24 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio final WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); res.setValuesByGDI(); - return (WGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); + return (WGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); } static WGLGLCapabilities PFD2GLCapabilitiesNoCheck(AbstractGraphicsDevice device, final GLProfile glp, final long hdc, final int pfdID) { PIXELFORMATDESCRIPTOR pfd = createPixelFormatDescriptor(hdc, pfdID); return PFD2GLCapabilitiesNoCheck(device, glp, pfd, pfdID); } - + static WGLGLCapabilities PFD2GLCapabilitiesNoCheck(AbstractGraphicsDevice device, GLProfile glp, PIXELFORMATDESCRIPTOR pfd, int pfdID) { if(null == pfd) { return null; } final WGLGLCapabilities res = new WGLGLCapabilities(pfd, pfdID, glp); res.setValuesByGDI(); - - return (WGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, PFD2DrawableTypeBits(pfd), res); + + return (WGLGLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, PFD2DrawableTypeBits(pfd), res); } - + static PIXELFORMATDESCRIPTOR GLCapabilities2PFD(GLCapabilitiesImmutable caps, PIXELFORMATDESCRIPTOR pfd) { int colorDepth = (caps.getRedBits() + caps.getGreenBits() + @@ -665,7 +665,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio pfdFlags |= GDI.PFD_DOUBLEBUFFER; } } - + if (caps.getStereo()) { pfdFlags |= GDI.PFD_STEREO; } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java index 3d093b972..9e917a0eb 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -93,7 +93,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat if (chooser != null && !(chooser instanceof GLCapabilitiesChooser)) { throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilitiesChooser objects"); } - + return chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested, (GLCapabilitiesChooser)chooser, absScreen); } @@ -123,7 +123,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat final GLProfile glp = GLProfile.getDefault(device); List availableCaps = null; - + final GLContext sharedContext; if ( factory.hasRendererQuirk(device, GLRendererQuirks.NeedCurrCtx4ARBPixFmtQueries) ) { sharedContext = sharedResource.getContext(); @@ -151,10 +151,10 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } } finally { if ( null != sharedContext ) { - sharedContext.release(); + sharedContext.release(); } else { sharedDrawable.unlockSurface(); - } + } } if( null != availableCaps && availableCaps.size() > 1 ) { @@ -166,7 +166,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat private static List getAvailableGLCapabilitiesARB(WindowsWGLDrawableFactory.SharedResource sharedResource, AbstractGraphicsDevice device, GLProfile glProfile, long hdc) { final int pfdIDCount = WindowsWGLGraphicsConfiguration.wglARBPFDIDCount((WindowsWGLContext)sharedResource.getContext(), hdc); final int[] pformats = WindowsWGLGraphicsConfiguration.wglAllARBPFDIDs(pfdIDCount); - return WindowsWGLGraphicsConfiguration.wglARBPFIDs2GLCapabilities(sharedResource, device, glProfile, hdc, pformats, + return WindowsWGLGraphicsConfiguration.wglARBPFIDs2GLCapabilities(sharedResource, device, glProfile, hdc, pformats, GLGraphicsConfigurationUtil.ALL_BITS & ~GLGraphicsConfigurationUtil.BITMAP_BIT); // w/o BITMAP } @@ -175,7 +175,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat int numFormats = pformats.length; List bucket = new ArrayList(numFormats); for (int i = 0; i < numFormats; i++) { - final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(device, glProfile, hdc, pformats[i], + final GLCapabilitiesImmutable caps = WindowsWGLGraphicsConfiguration.PFD2GLCapabilities(device, glProfile, hdc, pformats[i], bitmapOnly ? GLGraphicsConfigurationUtil.BITMAP_BIT : GLGraphicsConfigurationUtil.ALL_BITS ); if(null != caps) { bucket.add(caps); @@ -226,7 +226,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat " for device context " + toHexString(hdc) + ": error code " + GDI.GetLastError()); } - set = true; + set = true; } if (DEBUG) { System.err.println("setPixelFormat (post): hdc "+toHexString(hdc) +", "+pfdID+" -> "+config.getPixelFormatID()+", set: "+set); @@ -332,9 +332,9 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat final boolean isOpaque = capsChosen.isBackgroundOpaque() && GDI.DwmIsCompositionEnabled(); final int winattrbits = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsChosen) & ~GLGraphicsConfigurationUtil.BITMAP_BIT; // w/o BITMAP final GLProfile glProfile = capsChosen.getGLProfile(); - + final int pfdIDCount = WindowsWGLGraphicsConfiguration.wglARBPFDIDCount((WindowsWGLContext)sharedResource.getContext(), hdc); - + if(DEBUG) { System.err.println("updateGraphicsConfigurationARB: hdc "+toHexString(hdc)+", pfdIDCount(hdc) "+pfdIDCount+", capsChosen "+capsChosen+", "+GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrbits).toString()); System.err.println("isOpaque "+isOpaque+" (translucency requested: "+(!capsChosen.isBackgroundOpaque())+", compositioning enabled: "+GDI.DwmIsCompositionEnabled()+")"); @@ -346,7 +346,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } return false; } - + WGLGLCapabilities pixelFormatCaps = null; // chosen or preset PFD ID's caps boolean pixelFormatSet = false; // indicates a preset PFD ID [caps] final int presetPFDID = extHDC ? -1 : WGLUtil.GetPixelFormat(hdc) ; @@ -406,9 +406,9 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } } - List availableCaps = + List availableCaps = WindowsWGLGraphicsConfiguration.wglARBPFIDs2GLCapabilities(sharedResource, device, glProfile, hdc, pformats, winattrbits); - + if( null == availableCaps || 0 == availableCaps.size() ) { if (DEBUG) { System.err.println("updateGraphicsConfigurationARB: wglARBPFIDs2GLCapabilities failed with " + pformats.length + " pfd ids"); @@ -467,11 +467,11 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat // final boolean useFBO = capsChosen.isFBO(); final GLProfile glProfile = capsChosen.getGLProfile(); final int winattrmask = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsChosen); - + if(DEBUG) { System.err.println("updateGraphicsConfigurationGDI: capsChosen "+capsChosen+", "+GLGraphicsConfigurationUtil.winAttributeBits2String(null, winattrmask).toString()); } - + AbstractGraphicsDevice device = config.getScreen().getDevice(); int pfdID; // chosen or preset PFD ID WGLGLCapabilities pixelFormatCaps = null; // chosen or preset PFD ID's caps @@ -503,7 +503,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat if(null != caps) { availableCaps.add(caps); if(DEBUG) { - final int j = availableCaps.size() - 1; + final int j = availableCaps.size() - 1; System.err.println("updateGraphicsConfigurationGDI: availableCaps["+i+" -> "+j+"]: "+caps); } } else if(DEBUG) { @@ -543,7 +543,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat } pixelFormatCaps = (WGLGLCapabilities) availableCaps.get(chosenIndex); if (DEBUG) { - System.err.println("chosen pfdID (GDI): chosenIndex "+ chosenIndex + ", caps " + pixelFormatCaps + + System.err.println("chosen pfdID (GDI): chosenIndex "+ chosenIndex + ", caps " + pixelFormatCaps + " (" + WGLGLCapabilities.PFD2String(pixelFormatCaps.getPFD(), pixelFormatCaps.getPFDID()) +")"); } } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java index 3b2ff133a..ddfcbb55b 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -65,7 +65,7 @@ public class WindowsAWTWGLGraphicsConfigurationFactory extends GLGraphicsConfigu public static void registerFactory() { GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, GLCapabilitiesImmutable.class, new WindowsAWTWGLGraphicsConfigurationFactory()); } - private WindowsAWTWGLGraphicsConfigurationFactory() { + private WindowsAWTWGLGraphicsConfigurationFactory() { } protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( @@ -114,7 +114,7 @@ public class WindowsAWTWGLGraphicsConfigurationFactory extends GLGraphicsConfigu throw new GLException("Unable to choose a GraphicsConfiguration: "+capsChosen+",\n\t"+chooser+"\n\t"+winScreen); } - GLDrawableFactory drawableFactory = GLDrawableFactory.getFactory(((GLCapabilitiesImmutable)capsChosen).getGLProfile()); + GLDrawableFactory drawableFactory = GLDrawableFactory.getFactory(((GLCapabilitiesImmutable)capsChosen).getGLProfile()); GraphicsConfiguration chosenGC = null; if ( drawableFactory instanceof WindowsWGLDrawableFactory ) { @@ -138,7 +138,7 @@ public class WindowsAWTWGLGraphicsConfigurationFactory extends GLGraphicsConfigu } // go on .. } - + if( null == chosenGC ) { // 2nd Choice: Choose and match the GL Visual with AWT: // - collect all AWT PFDs @@ -147,7 +147,7 @@ public class WindowsAWTWGLGraphicsConfigurationFactory extends GLGraphicsConfigu // The resulting GraphicsConfiguration has to be 'forced' on the AWT native peer, // ie. returned by GLCanvas's getGraphicsConfiguration() befor call by super.addNotify(). // - + // collect all available PFD IDs GraphicsConfiguration[] configs = device.getConfigurations(); int[] pfdIDs = new int[configs.length]; @@ -171,11 +171,11 @@ public class WindowsAWTWGLGraphicsConfigurationFactory extends GLGraphicsConfigu System.err.println("WindowsAWTWGLGraphicsConfigurationFactory: Found matching AWT PFD ID "+winConfig.getPixelFormatID()+" -> "+winConfig); } } - } + } } else { chosenGC = device.getDefaultConfiguration(); } - + if ( null == chosenGC ) { throw new GLException("Unable to determine GraphicsConfiguration: "+winConfig); } diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/GLXUtil.java b/src/jogl/classes/jogamp/opengl/x11/glx/GLXUtil.java index 2c591cfbd..12e3db3bd 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/GLXUtil.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/GLXUtil.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -45,14 +45,14 @@ import com.jogamp.nativewindow.x11.X11GraphicsDevice; public class GLXUtil { public static final boolean DEBUG = Debug.debug("GLXUtil"); - + public static synchronized boolean isGLXAvailableOnServer(X11GraphicsDevice x11Device) { if(null == x11Device) { throw new IllegalArgumentException("null X11GraphicsDevice"); } if(0 == x11Device.getHandle()) { throw new IllegalArgumentException("null X11GraphicsDevice display handle"); - } + } boolean glXAvailable = false; x11Device.lock(); try { @@ -60,17 +60,17 @@ public class GLXUtil { } catch (Throwable t) { /* n/a */ } finally { x11Device.unlock(); - } - return glXAvailable; + } + return glXAvailable; } - + public static String getGLXClientString(X11GraphicsDevice x11Device, int name) { x11Device.lock(); try { return GLX.glXGetClientString(x11Device.getHandle(), name); } finally { x11Device.unlock(); - } + } } public static String queryGLXServerString(X11GraphicsDevice x11Device, int screen_idx, int name) { x11Device.lock(); @@ -78,27 +78,27 @@ public class GLXUtil { return GLX.glXQueryServerString(x11Device.getHandle(), screen_idx, name); } finally { x11Device.unlock(); - } - } + } + } public static String queryGLXExtensionsString(X11GraphicsDevice x11Device, int screen_idx) { x11Device.lock(); try { return GLX.glXQueryExtensionsString(x11Device.getHandle(), screen_idx); } finally { x11Device.unlock(); - } + } } - + public static VersionNumber getGLXServerVersionNumber(X11GraphicsDevice x11Device) { final IntBuffer major = Buffers.newDirectIntBuffer(1); final IntBuffer minor = Buffers.newDirectIntBuffer(1); - + x11Device.lock(); try { if (!GLX.glXQueryVersion(x11Device.getHandle(), major, minor)) { throw new GLException("glXQueryVersion failed"); } - + // Work around bugs in ATI's Linux drivers where they report they // only implement GLX version 1.2 on the server side if (major.get(0) == 1 && minor.get(0) == 2) { @@ -117,7 +117,7 @@ public class GLXUtil { } return new VersionNumber(major.get(0), minor.get(0), 0); } - + public static boolean isMultisampleAvailable(String extensions) { if (extensions != null) { return (extensions.indexOf("GLX_ARB_multisample") >= 0); @@ -142,8 +142,8 @@ public class GLXUtil { public static VersionNumber getClientVersionNumber() { return clientVersionNumber; } - - public static synchronized void initGLXClientDataSingleton(X11GraphicsDevice x11Device) { + + public static synchronized void initGLXClientDataSingleton(X11GraphicsDevice x11Device) { if(null != clientVendorName) { return; // already initialized } @@ -152,10 +152,10 @@ public class GLXUtil { } if(0 == x11Device.getHandle()) { throw new IllegalArgumentException("null X11GraphicsDevice display handle"); - } + } clientMultisampleAvailable = isMultisampleAvailable(GLX.glXGetClientString(x11Device.getHandle(), GLX.GLX_EXTENSIONS)); clientVendorName = GLX.glXGetClientString(x11Device.getHandle(), GLX.GLX_VENDOR); - + int[] major = new int[1]; int[] minor = new int[1]; final String str = GLX.glXGetClientString(x11Device.getHandle(), GLX.GLX_VERSION); diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java index 72e84b05e..ba88ff3c4 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java @@ -79,15 +79,15 @@ public class X11ExternalGLXContext extends X11GLXContext { long drawable = GLX.glXGetCurrentDrawable(); if (drawable == 0) { throw new GLException("Error: attempted to make an external GLDrawable without a drawable/context current"); - } + } IntBuffer val = Buffers.newDirectIntBuffer(1); - + int w, h; GLX.glXQueryDrawable(display, drawable, GLX.GLX_WIDTH, val); w=val.get(0); GLX.glXQueryDrawable(display, drawable, GLX.GLX_HEIGHT, val); h=val.get(0); - + GLX.glXQueryContext(display, ctx, GLX.GLX_SCREEN, val); X11GraphicsScreen x11Screen = (X11GraphicsScreen) X11GraphicsScreen.createScreenDevice(display, val.get(0), false); diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java index fca36c0cc..650fd31d3 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java @@ -73,7 +73,7 @@ public class X11ExternalGLXDrawable extends X11GLXDrawable { throw new GLException("Error: attempted to make an external GLDrawable without a drawable current"); } IntBuffer val = Buffers.newDirectIntBuffer(1); - + GLX.glXQueryContext(display, context, GLX.GLX_SCREEN, val); X11GraphicsScreen x11Screen = (X11GraphicsScreen) X11GraphicsScreen.createScreenDevice(display, val.get(0), false); diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java index 0ecf11a43..22a48e093 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java @@ -142,7 +142,7 @@ public class X11GLXContext extends GLContextImpl { if(null != glXServerVersion) { return isGLXVersionGreaterEqualOneThree; } - glXServerVersion = ((X11GLXDrawableFactory)drawable.getFactoryImpl()).getGLXVersionNumber(drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice()); + glXServerVersion = ((X11GLXDrawableFactory)drawable.getFactoryImpl()).getGLXVersionNumber(drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice()); isGLXVersionGreaterEqualOneThree = null != glXServerVersion ? glXServerVersion.compareTo(X11GLXDrawableFactory.versionOneThree) >= 0 : false; return isGLXVersionGreaterEqualOneThree; } @@ -262,7 +262,7 @@ public class X11GLXContext extends GLContextImpl { t.printStackTrace(); } } - + if(0!=ctx) { if (!glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), ctx)) { if(DEBUG) { @@ -419,7 +419,7 @@ public class X11GLXContext extends GLContextImpl { if (GLX.glXGetCurrentContext() != contextHandle) { if (!glXMakeContextCurrent(dpy, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) { - throw new GLException("Error making context " + toHexString(contextHandle) + + throw new GLException("Error making context " + toHexString(contextHandle) + " current on Thread " + getThreadName() + " with display " + toHexString(dpy) + ", drawableWrite " + toHexString(drawable.getHandle()) + @@ -525,7 +525,7 @@ public class X11GLXContext extends GLContextImpl { @Override protected boolean setSwapIntervalImpl(int interval) { - if( !drawable.getChosenGLCapabilities().isOnscreen() ) { return false; } + if( !drawable.getChosenGLCapabilities().isOnscreen() ) { return false; } final GLXExt glXExt = getGLXExt(); if(0==hasSwapInterval) { @@ -534,7 +534,7 @@ public class X11GLXContext extends GLContextImpl { if( glXExt.isExtensionAvailable(GLXExtensions.GLX_MESA_swap_control) ) { if(DEBUG) { System.err.println("X11GLXContext.setSwapInterval using: "+GLXExtensions.GLX_MESA_swap_control); } hasSwapInterval = 1; - } else */ + } else */ if ( glXExt.isExtensionAvailable(GLXExtensions.GLX_SGI_swap_control) ) { if(DEBUG) { System.err.println("X11GLXContext.setSwapInterval using: "+GLXExtensions.GLX_SGI_swap_control); } hasSwapInterval = 2; @@ -542,7 +542,7 @@ public class X11GLXContext extends GLContextImpl { hasSwapInterval = -1; } } catch (Throwable t) { hasSwapInterval=-1; } - } + } /* try { switch( hasSwapInterval ) { case 1: @@ -581,7 +581,7 @@ public class X11GLXContext extends GLContextImpl { try { final IntBuffer maxGroupsNIO = Buffers.newDirectIntBuffer(maxGroups.length - maxGroups_offset); final IntBuffer maxBarriersNIO = Buffers.newDirectIntBuffer(maxBarriers.length - maxBarriers_offset); - + if( glXExt.glXQueryMaxSwapGroupsNV(ns.getDisplayHandle(), ns.getScreenIndex(), maxGroupsNIO, maxBarriersNIO) ) { maxGroupsNIO.get(maxGroups, maxGroups_offset, maxGroupsNIO.remaining()); @@ -623,7 +623,7 @@ public class X11GLXContext extends GLContextImpl { } @Override - public final ByteBuffer glAllocateMemoryNV(int size, float readFrequency, float writeFrequency, float priority) { + public final ByteBuffer glAllocateMemoryNV(int size, float readFrequency, float writeFrequency, float priority) { return getGLXExt().glXAllocateMemoryNV(size, readFrequency, writeFrequency, priority); } @@ -631,7 +631,7 @@ public class X11GLXContext extends GLContextImpl { public final void glFreeMemoryNV(ByteBuffer pointer) { getGLXExt().glXFreeMemoryNV(pointer); } - + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index 5df458b7e..3f0841b6c 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -86,7 +86,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { public static final VersionNumber versionOneFour = new VersionNumber(1, 4, 0); static final String GLX_SGIX_pbuffer = "GLX_SGIX_pbuffer"; - + private static DesktopGLDynamicLookupHelper x11GLXDynamicLookupHelper = null; public X11GLXDrawableFactory() { @@ -134,7 +134,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { protected final boolean isComplete() { return null != x11GLXDynamicLookupHelper; } - + @Override protected final void destroy() { if(null != sharedResourceRunner) { @@ -205,7 +205,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { final public GLContextImpl getContext() { return context; } @Override public GLRendererQuirks getRendererQuirks() { - return null != context ? context.getRendererQuirks() : null; + return null != context ? context.getRendererQuirks() : null; } final String getGLXVendorName() { return glXServerVendorName; } @@ -251,18 +251,18 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { } return res; } - + @Override public SharedResourceRunner.Resource createSharedResource(String connection) { final X11GraphicsDevice sharedDevice = new X11GraphicsDevice(X11Util.openDisplay(connection), AbstractGraphicsDevice.DEFAULT_UNIT, true /* owner */); sharedDevice.lock(); try { final X11GraphicsScreen sharedScreen = new X11GraphicsScreen(sharedDevice, sharedDevice.getDefaultScreen()); - + GLXUtil.initGLXClientDataSingleton(sharedDevice); final String glXServerVendorName = GLX.glXQueryServerString(sharedDevice.getHandle(), 0, GLX.GLX_VENDOR); final boolean glXServerMultisampleAvailable = GLXUtil.isMultisampleAvailable(GLX.glXQueryServerString(sharedDevice.getHandle(), 0, GLX.GLX_EXTENSIONS)); - + final GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP, false); if (null == glp) { throw new GLException("Couldn't get default GLProfile for device: "+sharedDevice); @@ -283,7 +283,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { if (null == sharedContext) { throw new GLException("Couldn't create shared context for drawable: "+sharedDrawable); } - + boolean madeCurrent = false; sharedContext.makeCurrent(); try { @@ -493,12 +493,12 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { } @Override - protected final ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + protected final ProxySurface createMutableSurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstreamHook) { final X11GraphicsDevice device; - if( createNewDevice || !(deviceReq instanceof X11GraphicsDevice) ) { + if( createNewDevice || !(deviceReq instanceof X11GraphicsDevice) ) { device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), true /* owner */); } else { device = (X11GraphicsDevice) deviceReq; @@ -506,18 +506,18 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { final X11GraphicsScreen screen = new X11GraphicsScreen(device, device.getDefaultScreen()); final X11GLXGraphicsConfiguration config = X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsChosen, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED); if(null == config) { - throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); + throw new GLException("Choosing GraphicsConfiguration failed w/ "+capsChosen+" on "+screen); } return new WrappedSurface(config, 0, upstreamHook, createNewDevice); } - + @Override - public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, + public final ProxySurface createDummySurfaceImpl(AbstractGraphicsDevice deviceReq, boolean createNewDevice, GLCapabilitiesImmutable chosenCaps, GLCapabilitiesImmutable requestedCaps, GLCapabilitiesChooser chooser, int width, int height) { chosenCaps = GLGraphicsConfigurationUtil.fixOnscreenGLCapabilities(chosenCaps); - return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, new X11DummyUpstreamSurfaceHook(width, height)); - } - + return createMutableSurfaceImpl(deviceReq, createNewDevice, chosenCaps, requestedCaps, chooser, new X11DummyUpstreamSurfaceHook(width, height)); + } + @Override protected final ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { final X11GraphicsDevice device = new X11GraphicsDevice(X11Util.openDisplay(deviceReq.getConnection()), deviceReq.getUnitID(), true /* owner */); diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDynamicLibraryBundleInfo.java index f25f7ae2c..951174f71 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDynamicLibraryBundleInfo.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.opengl.x11.glx; import jogamp.opengl.*; @@ -40,8 +40,8 @@ public final class X11GLXDynamicLibraryBundleInfo extends DesktopGLDynamicLibrar public final List> getToolLibNames() { final List> libsList = new ArrayList>(); final List libsGL = new ArrayList(); - - // Be aware that on DRI systems, eg ATI fglrx, etc, + + // Be aware that on DRI systems, eg ATI fglrx, etc, // you have to set LIBGL_DRIVERS_PATH env variable. // Eg on Ubuntu 64bit systems this is: // export LIBGL_DRIVERS_PATH=/usr/lib/fglrx/dri:/usr/lib32/fglrx/dri @@ -55,11 +55,11 @@ public final class X11GLXDynamicLibraryBundleInfo extends DesktopGLDynamicLibrar // last but not least .. the generic one libsGL.add("GL"); - - libsList.add(libsGL); + + libsList.add(libsGL); return libsList; - } - + } + @Override public final List getToolGetProcAddressFuncNameList() { List res = new ArrayList(); diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java index c23bd5337..5aea33f21 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -61,9 +61,9 @@ import com.jogamp.nativewindow.x11.X11GraphicsScreen; public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implements Cloneable { public static final int MAX_ATTRIBS = 128; - private GLCapabilitiesChooser chooser; + private GLCapabilitiesChooser chooser; - X11GLXGraphicsConfiguration(X11GraphicsScreen screen, + X11GLXGraphicsConfiguration(X11GraphicsScreen screen, X11GLCapabilities capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser) { super(screen, capsChosen, capsRequested, capsChosen.getXVisualInfo()); this.chooser=chooser; @@ -86,8 +86,8 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem void updateGraphicsConfiguration() { final CapabilitiesImmutable aChosenCaps = getChosenCapabilities(); if( !(aChosenCaps instanceof X11GLCapabilities) || VisualIDHolder.VID_UNDEFINED == aChosenCaps.getVisualID(VIDType.X11_XVISUAL) ) { - // This case is actually quite impossible, since on X11 the visualID and hence GraphicsConfiguration - // must be determined _before_ window creation! + // This case is actually quite impossible, since on X11 the visualID and hence GraphicsConfiguration + // must be determined _before_ window creation! final X11GLXGraphicsConfiguration newConfig = (X11GLXGraphicsConfiguration) GraphicsConfigurationFactory.getFactory(getScreen().getDevice(), aChosenCaps).chooseGraphicsConfiguration( aChosenCaps, getRequestedCapabilities(), chooser, getScreen(), VisualIDHolder.VID_UNDEFINED); @@ -121,7 +121,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem glp = GLProfile.getDefault(x11Screen.getDevice()); } final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); - final X11GLCapabilities caps = GLXFBConfig2GLCapabilities(device, glp, fbcfg, GLGraphicsConfigurationUtil.ALL_BITS, factory.isGLXMultisampleAvailable(device)); + final X11GLCapabilities caps = GLXFBConfig2GLCapabilities(device, glp, fbcfg, GLGraphicsConfigurationUtil.ALL_BITS, factory.isGLXMultisampleAvailable(device)); if(null==caps) { throw new GLException("GLCapabilities null of "+toHexString(fbcfg)); } @@ -130,7 +130,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem static IntBuffer GLCapabilities2AttribList(GLCapabilitiesImmutable caps, boolean forFBAttr, boolean isMultisampleAvailable, - long display, int screen) + long display, int screen) { int colorDepth = (caps.getRedBits() + caps.getGreenBits() + @@ -143,7 +143,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem if (forFBAttr) { res.put(idx++, GLX.GLX_DRAWABLE_TYPE); - + final int surfaceType; if( caps.isOnscreen() ) { surfaceType = GLX.GLX_WINDOW_BIT; @@ -157,7 +157,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem throw new GLException("no surface type set in caps: "+caps); } res.put(idx++, surfaceType); - + res.put(idx++, GLX.GLX_RENDER_TYPE); res.put(idx++, GLX.GLX_RGBA_BIT); } else { @@ -233,8 +233,8 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem } // FBConfig - - static boolean GLXFBConfigIDValid(long display, int screen, int fbcfgid) { + + static boolean GLXFBConfigIDValid(long display, int screen, int fbcfgid) { long fbcfg = X11GLXGraphicsConfiguration.glXFBConfigID2FBConfig(display, screen, fbcfgid); return (0 != fbcfg) ? X11GLXGraphicsConfiguration.GLXFBConfigValid( display, fbcfg ) : false ; } @@ -278,8 +278,8 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem int winattrmask, boolean isMultisampleAvailable) { final int allDrawableTypeBits = FBCfgDrawableTypeBits(device, fbcfg); int drawableTypeBits = winattrmask & allDrawableTypeBits; - - final long display = device.getHandle(); + + final long display = device.getHandle(); int fbcfgid = X11GLXGraphicsConfiguration.glXFBConfig2FBConfigID(display, fbcfg); XVisualInfo visualInfo = GLX.glXGetVisualFromFBConfig(display, fbcfg); if(null == visualInfo) { @@ -307,8 +307,8 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem res.setSampleBuffers(glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLE_BUFFERS, tmp) != 0); res.setNumSamples (glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLES, tmp)); } - final XRenderDirectFormat xrmask = ( null != visualInfo ) ? - XVisual2XRenderMask( display, visualInfo.getVisual() ) : + final XRenderDirectFormat xrmask = ( null != visualInfo ) ? + XVisual2XRenderMask( display, visualInfo.getVisual() ) : null ; final int alphaMask = ( null != xrmask ) ? xrmask.getAlphaMask() : 0; res.setBackgroundOpaque( 0 >= alphaMask ); @@ -318,7 +318,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem res.setTransparentBlueValue(xrmask.getBlueMask()); res.setTransparentAlphaValue(alphaMask); } - // ALPHA shall be set at last - due to it's auto setting by the above (!opaque / samples) + // ALPHA shall be set at last - due to it's auto setting by the above (!opaque / samples) res.setDoubleBuffered(glXGetFBConfig(display, fbcfg, GLX.GLX_DOUBLEBUFFER, tmp) != 0); res.setStereo (glXGetFBConfig(display, fbcfg, GLX.GLX_STEREO, tmp) != 0); res.setHardwareAccelerated(glXGetFBConfig(display, fbcfg, GLX.GLX_CONFIG_CAVEAT, tmp) != GLX.GLX_SLOW_CONFIG); @@ -332,8 +332,8 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem res.setAccumAlphaBits(glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_ALPHA_SIZE, tmp)); res.setDepthBits (glXGetFBConfig(display, fbcfg, GLX.GLX_DEPTH_SIZE, tmp)); res.setStencilBits (glXGetFBConfig(display, fbcfg, GLX.GLX_STENCIL_SIZE, tmp)); - - return (X11GLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); + + return (X11GLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); } private static String glXGetFBConfigErrorCode(int err) { @@ -363,7 +363,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem static long glXFBConfigID2FBConfig(long display, int screen, int id) { final IntBuffer attribs = Buffers.newDirectIntBuffer(new int[] { GLX.GLX_FBCONFIG_ID, id, 0 }); final IntBuffer count = Buffers.newDirectIntBuffer(1); - count.put(0, -1); + count.put(0, -1); PointerBuffer fbcfgsL = GLX.glXChooseFBConfig(display, screen, attribs, count); if (fbcfgsL == null || fbcfgsL.limit()<1) { return 0; @@ -380,7 +380,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem XVisualInfo[] infos = X11Lib.XGetVisualInfo(display, X11Lib.VisualIDMask, template, count, 0); if (infos == null || infos.length == 0) { return null; - } + } XVisualInfo res = XVisualInfo.create(infos[0]); if (DEBUG) { System.err.println("Fetched XVisualInfo for visual ID " + toHexString(visualID)); @@ -391,10 +391,10 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem static X11GLCapabilities XVisualInfo2GLCapabilities(final X11GraphicsDevice device, GLProfile glp, XVisualInfo info, final int winattrmask, boolean isMultisampleEnabled) { - final int allDrawableTypeBits = GLGraphicsConfigurationUtil.WINDOW_BIT | + final int allDrawableTypeBits = GLGraphicsConfigurationUtil.WINDOW_BIT | GLGraphicsConfigurationUtil.BITMAP_BIT | GLGraphicsConfigurationUtil.FBO_BIT ; - + final int drawableTypeBits = winattrmask & allDrawableTypeBits; if( 0 == drawableTypeBits ) { @@ -425,13 +425,13 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem // Note: use of hardware acceleration is determined by // glXCreateContext, not by the XVisualInfo. Optimistically claim // that all GLCapabilities have the capability to be hardware - // accelerated. + // accelerated. if (isMultisampleEnabled) { res.setSampleBuffers(glXGetConfig(display, info, GLX.GLX_SAMPLE_BUFFERS, tmp) != 0); res.setNumSamples (glXGetConfig(display, info, GLX.GLX_SAMPLES, tmp)); } - final XRenderDirectFormat xrmask = ( null != info ) ? - XVisual2XRenderMask( display, info.getVisual() ) : + final XRenderDirectFormat xrmask = ( null != info ) ? + XVisual2XRenderMask( display, info.getVisual() ) : null ; final int alphaMask = ( null != xrmask ) ? xrmask.getAlphaMask() : 0; res.setBackgroundOpaque( 0 >= alphaMask ); @@ -454,7 +454,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem res.setAccumBlueBits (glXGetConfig(display, info, GLX.GLX_ACCUM_BLUE_SIZE, tmp)); res.setAccumAlphaBits(glXGetConfig(display, info, GLX.GLX_ACCUM_ALPHA_SIZE, tmp)); - return (X11GLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); + return (X11GLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); } private static String glXGetConfigErrorCode(int err) { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java index a7c7d3fe6..abe310a3f 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -109,7 +109,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF if (chooser != null && !(chooser instanceof GLCapabilitiesChooser)) { throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilitiesChooser objects"); } - + if(!GLXUtil.isGLXAvailableOnServer((X11GraphicsDevice)absScreen.getDevice())) { if(null != fallbackX11GraphicsConfigurationFactory) { if(DEBUG) { @@ -118,7 +118,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF return fallbackX11GraphicsConfigurationFactory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, absScreen, VisualIDHolder.VID_UNDEFINED); } throw new InternalError("No GLX and no fallback GraphicsConfigurationFactory available for: "+absScreen); - } + } return chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested, (GLCapabilitiesChooser)chooser, (X11GraphicsScreen)absScreen, nativeVisualID); } @@ -134,7 +134,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF final GLProfile glp = GLProfile.getDefault(device); List availableCaps = null; - + sharedDevice.lock(); try { if( sharedResource.isGLXVersionGreaterEqualOneThree() ) { @@ -219,9 +219,9 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF if (capsChosen == null) { capsChosen = new GLCapabilities(null); } - X11GraphicsDevice x11Device = (X11GraphicsDevice) x11Screen.getDevice(); + X11GraphicsDevice x11Device = (X11GraphicsDevice) x11Screen.getDevice(); X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); - + capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, factory, x11Device); final boolean usePBuffer = !capsChosen.isOnscreen() && capsChosen.isPBuffer(); @@ -262,7 +262,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF return null; } final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); - + final X11GLCapabilities caps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(x11Device, glp, fbcfg, GLGraphicsConfigurationUtil.ALL_BITS, factory.isGLXMultisampleAvailable(x11Device)); return new X11GLXGraphicsConfiguration(x11Screen, caps, caps, new DefaultGLCapabilitiesChooser()); } @@ -280,8 +280,8 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF X11GraphicsDevice x11Device = (X11GraphicsDevice) x11Screen.getDevice(); long display = x11Device.getHandle(); int screen = x11Screen.getIndex(); - - final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); + + final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); final boolean isMultisampleAvailable = factory.isGLXMultisampleAvailable(x11Device); final IntBuffer attribs = X11GLXGraphicsConfiguration.GLCapabilities2AttribList(capsChosen, true, isMultisampleAvailable, display, screen); final IntBuffer count = Buffers.newDirectIntBuffer(1); @@ -337,14 +337,14 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } } } - + if(DEBUG) { System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: got configs: "+availableCaps.size()); for(int i=0; i chosenIndex ) { if (DEBUG) { @@ -393,15 +393,15 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF X11GraphicsDevice absDevice = (X11GraphicsDevice) x11Screen.getDevice(); long display = absDevice.getHandle(); int screen = x11Screen.getIndex(); - - final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); - final boolean isMultisampleAvailable = factory.isGLXMultisampleAvailable(absDevice); + + final X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory(); + final boolean isMultisampleAvailable = factory.isGLXMultisampleAvailable(absDevice); final IntBuffer attribs = X11GLXGraphicsConfiguration.GLCapabilities2AttribList(capsChosen, false, isMultisampleAvailable, display, screen); XVisualInfo recommendedVis = null; // 1st choice: get GLCapabilities based on users GLCapabilities setting recommendedIndex as preferred choice // skipped if xvisualID is given - if( VisualIDHolder.VID_UNDEFINED == xvisualID ) { + if( VisualIDHolder.VID_UNDEFINED == xvisualID ) { recommendedVis = GLX.glXChooseVisual(display, screen, attribs); if (DEBUG) { System.err.print("glXChooseVisual recommended "); @@ -441,7 +441,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF System.err.println(i+": "+availableCaps.get(i)); } } - + if( VisualIDHolder.VID_UNDEFINED != xvisualID ) { for(int i=0; i chosenIndex ) { if (DEBUG) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookMutableSize.java b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookMutableSize.java index 22c95f3dd..c98bf5436 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookMutableSize.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookMutableSize.java @@ -29,11 +29,11 @@ public class DelegatedUpstreamSurfaceHookMutableSize extends UpstreamSurfaceHook upstream.destroy(s); } } - + @Override public String toString() { - return getClass().getSimpleName()+"[ "+ width + "x" + height + ", " + upstream + "]"; + return getClass().getSimpleName()+"[ "+ width + "x" + height + ", " + upstream + "]"; } - + } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookWithSurfaceSize.java b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookWithSurfaceSize.java index 85e24582c..1557f4e51 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookWithSurfaceSize.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/DelegatedUpstreamSurfaceHookWithSurfaceSize.java @@ -42,13 +42,13 @@ public class DelegatedUpstreamSurfaceHookWithSurfaceSize implements UpstreamSurf @Override public final int getHeight(ProxySurface s) { return surface.getHeight(); - } - + } + @Override public String toString() { - final String us_s = null != surface ? ( surface.getClass().getName() + ": 0x" + Long.toHexString(surface.getSurfaceHandle()) + " " +surface.getWidth() + "x" + surface.getHeight() ) : "nil"; + final String us_s = null != surface ? ( surface.getClass().getName() + ": 0x" + Long.toHexString(surface.getSurfaceHandle()) + " " +surface.getWidth() + "x" + surface.getHeight() ) : "nil"; return getClass().getSimpleName()+"["+upstream+", "+us_s+"]"; } - + } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/MutableGraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/MutableGraphicsConfiguration.java index eaad513aa..8b8ccb191 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/MutableGraphicsConfiguration.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/MutableGraphicsConfiguration.java @@ -41,10 +41,10 @@ public class MutableGraphicsConfiguration extends DefaultGraphicsConfiguration { public void setChosenCapabilities(CapabilitiesImmutable caps) { super.setChosenCapabilities(caps); } - + @Override public void setScreen(AbstractGraphicsScreen screen) { super.setScreen(screen); } - + } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java b/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java index 29f4964c0..a8dd9165c 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/NativeWindowVersion.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.nativewindow; import com.jogamp.common.GlueGenVersion; diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSize.java b/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSize.java index 29c540ac4..5838c7a56 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSize.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSize.java @@ -18,9 +18,9 @@ public class UpstreamSurfaceHookMutableSize implements UpstreamSurfaceHook.Mutab @Override public final void setSize(int width, int height) { this.width = width; - this.height = height; + this.height = height; } - + @Override public final int getWidth(ProxySurface s) { return width; @@ -35,11 +35,11 @@ public class UpstreamSurfaceHookMutableSize implements UpstreamSurfaceHook.Mutab @Override public void destroy(ProxySurface s) { /* nop */ } - + @Override public String toString() { - return getClass().getSimpleName()+"[ "+ width + "x" + height + "]"; + return getClass().getSimpleName()+"[ "+ width + "x" + height + "]"; } - + } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java index 7e3d30a47..15f3355d0 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 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 @@ -29,11 +29,11 @@ * 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. */ @@ -57,7 +57,7 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple private GraphicsConfiguration config; AbstractGraphicsConfiguration encapsulated; - public AWTGraphicsConfiguration(AWTGraphicsScreen screen, + public AWTGraphicsConfiguration(AWTGraphicsScreen screen, CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, GraphicsConfiguration config, AbstractGraphicsConfiguration encapsulated) { super(screen, capsChosen, capsRequested); @@ -71,9 +71,9 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple this.config = config; this.encapsulated=null; } - + /** - * @param capsChosen if null, capsRequested is copied and aligned + * @param capsChosen if null, capsRequested is copied and aligned * with the graphics {@link Capabilities} of the AWT Component to produce the chosen {@link Capabilities}. * Otherwise the capsChosen is used. * @param capsRequested if null, default {@link Capabilities} are used, otherwise the given values. @@ -81,7 +81,7 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple public static AWTGraphicsConfiguration create(Component awtComp, CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested) { final GraphicsConfiguration awtGfxConfig = awtComp.getGraphicsConfiguration(); if(null==awtGfxConfig) { - throw new NativeWindowException("AWTGraphicsConfiguration.create: Null AWT GraphicsConfiguration @ "+awtComp); + throw new NativeWindowException("AWTGraphicsConfiguration.create: Null AWT GraphicsConfiguration @ "+awtComp); } final GraphicsDevice awtGraphicsDevice = awtGfxConfig.getDevice(); if(null==awtGraphicsDevice) { @@ -112,7 +112,7 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple public void setChosenCapabilities(CapabilitiesImmutable capsChosen) { super.setChosenCapabilities(capsChosen); } - + @Override public Object clone() { return super.clone(); @@ -171,7 +171,7 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple public String toString() { return getClass().getSimpleName()+"[" + getScreen() + ",\n\tchosen " + capabilitiesChosen+ - ",\n\trequested " + capabilitiesRequested+ + ",\n\trequested " + capabilitiesRequested+ ",\n\t" + config + ",\n\tencapsulated "+encapsulated+"]"; } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsDevice.java index 635e6d263..a7fa53577 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsDevice.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 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 @@ -29,11 +29,11 @@ * 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. */ diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java index f4ee06e28..d3cf5bff6 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 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 @@ -29,11 +29,11 @@ * 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. */ diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java index e5290aee1..44163fc73 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTPrintLifecycle.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -69,15 +69,15 @@ import jogamp.nativewindow.awt.AWTMisc; } finally { ctx.releasePrint(); } - * + * *
                *

                */ public interface AWTPrintLifecycle { public static final int DEFAULT_PRINT_TILE_SIZE = 1024; - - + + /** * Shall be called before {@link PrinterJob#print()}. *

                @@ -85,12 +85,12 @@ public interface AWTPrintLifecycle { *

                * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels - * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples * @param tileWidth custom tile width for {@link com.jogamp.opengl.util.TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. * @param tileHeight custom tile height for {@link com.jogamp.opengl.util.TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. */ void setupPrint(double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight); - + /** * Shall be called after {@link PrinterJob#print()}. *

                @@ -111,11 +111,11 @@ public interface AWTPrintLifecycle { *

                * See Usage. *

                - * + * * @param c container to be traversed through to perform {@link AWTPrintLifecycle#setupPrint(double, double, int, int, int) setupPrint(..)} on all {@link AWTPrintLifecycle} elements. * @param scaleMatX {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatX * width pixels * @param scaleMatY {@link Graphics2D} {@link Graphics2D#scale(double, double) scaling factor}, i.e. rendering 1/scaleMatY * height pixels - * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples + * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using given num samples * @param tileWidth custom tile width for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. * @param tileHeight custom tile height for {@link TileRenderer#setTileSize(int, int, int) tile renderer}, pass -1 for default. * @return the context @@ -139,7 +139,7 @@ public interface AWTPrintLifecycle { * @return count of performed actions of last {@link #setupPrint(Container, double, double, int, int, int) setupPrint(..)} or {@link #releasePrint()}. */ public int getCount() { return count; } - + private final Container cont; private final double scaleMatX; private final double scaleMatY; @@ -147,7 +147,7 @@ public interface AWTPrintLifecycle { private final int tileWidth; private final int tileHeight; private int count; - + private final AWTMisc.ComponentAction setupAction = new AWTMisc.ComponentAction() { @Override public void run(Component c) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java index e499ff705..e350aaff4 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java @@ -78,7 +78,7 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { /** * Adds this closing listener to the components Window if exist and only one time. *

                - * If the closing listener is already added, and {@link IllegalStateException} is thrown. + * If the closing listener is already added, and {@link IllegalStateException} is thrown. *

                * * @return true if added, otherwise false. diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java index 7a7a771d6..e4d3884a7 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -45,29 +45,29 @@ import com.jogamp.common.nio.Buffers; * {@link DataBuffer} specialization using NIO direct buffer of type {@link DataBuffer#TYPE_INT} as storage. */ public final class DirectDataBufferInt extends DataBuffer { - + public static class DirectWritableRaster extends WritableRaster { protected DirectWritableRaster(SampleModel sampleModel, DirectDataBufferInt dataBuffer, Point origin) { super(sampleModel, dataBuffer, origin); } } - + public static class BufferedImageInt extends BufferedImage { final int customImageType; public BufferedImageInt (int customImageType, ColorModel cm, WritableRaster raster, Hashtable properties) { super(cm, raster, false /* isRasterPremultiplied */, properties); - this.customImageType = customImageType; + this.customImageType = customImageType; } - + /** - * @return one of the custom image-type values {@link BufferedImage#TYPE_INT_ARGB TYPE_INT_ARGB}, - * {@link BufferedImage#TYPE_INT_ARGB_PRE TYPE_INT_ARGB_PRE}, + * @return one of the custom image-type values {@link BufferedImage#TYPE_INT_ARGB TYPE_INT_ARGB}, + * {@link BufferedImage#TYPE_INT_ARGB_PRE TYPE_INT_ARGB_PRE}, * {@link BufferedImage#TYPE_INT_RGB TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_BGR TYPE_INT_BGR}. */ public int getCustomType() { return customImageType; } - + @Override public String toString() { return new String("BufferedImageInt@"+Integer.toHexString(hashCode()) @@ -75,26 +75,26 @@ public final class DirectDataBufferInt extends DataBuffer { +" "+getColorModel()+" "+getRaster()); } } - + /** - * Creates a {@link BufferedImageInt} using a {@link DirectColorModel direct color model} in {@link ColorSpace#CS_sRGB sRGB color space}.
                + * Creates a {@link BufferedImageInt} using a {@link DirectColorModel direct color model} in {@link ColorSpace#CS_sRGB sRGB color space}.
                * It uses a {@link DirectWritableRaster} utilizing {@link DirectDataBufferInt} storage. *

                - * Note that due to using the custom storage type {@link DirectDataBufferInt}, the resulting + * Note that due to using the custom storage type {@link DirectDataBufferInt}, the resulting * {@link BufferedImage}'s {@link BufferedImage#getType() image-type} is of {@link BufferedImage#TYPE_CUSTOM TYPE_CUSTOM}. * We are not able to change this detail, since the AWT image implementation associates the {@link BufferedImage#getType() image-type} * with a build-in storage-type. * Use {@link BufferedImageInt#getCustomType()} to retrieve the custom image-type, which will return the imageType - * value passed here. + * value passed here. *

                - * + * * @param width * @param height - * @param imageType one of {@link BufferedImage#TYPE_INT_ARGB TYPE_INT_ARGB}, {@link BufferedImage#TYPE_INT_ARGB_PRE TYPE_INT_ARGB_PRE}, + * @param imageType one of {@link BufferedImage#TYPE_INT_ARGB TYPE_INT_ARGB}, {@link BufferedImage#TYPE_INT_ARGB_PRE TYPE_INT_ARGB_PRE}, * {@link BufferedImage#TYPE_INT_RGB TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_BGR TYPE_INT_BGR}. * @param location origin, if null 0/0 is assumed. * @param properties Hashtable of - * String/Object pairs. Used for {@link BufferedImage#getProperty(String)} etc. + * String/Object pairs. Used for {@link BufferedImage#getProperty(String)} etc. * @return */ public static BufferedImageInt createBufferedImage(int width, int height, int imageType, Point location, Hashtable properties) { @@ -150,30 +150,30 @@ public final class DirectDataBufferInt extends DataBuffer { bandMasks[0] = rmask; bandMasks[1] = gmask; bandMasks[2] = bmask; - + final DirectDataBufferInt dataBuffer = new DirectDataBufferInt(width*height); if( null == location ) { location = new Point(0,0); } - final SinglePixelPackedSampleModel sppsm = new SinglePixelPackedSampleModel(dataBuffer.getDataType(), + final SinglePixelPackedSampleModel sppsm = new SinglePixelPackedSampleModel(dataBuffer.getDataType(), width, height, width /* scanLineStride */, bandMasks); // IntegerComponentRasters must haveinteger DataBuffers: // final WritableRaster raster = new IntegerInterleavedRaster(sppsm, dataBuffer, location); // Not public: // final WritableRaster raster = new SunWritableRaster(sppsm, dataBuffer, location); final WritableRaster raster = new DirectWritableRaster(sppsm, dataBuffer, location); - + return new BufferedImageInt(imageType, colorModel, raster, properties); } - + /** Default data bank. */ private IntBuffer data; /** All data banks */ private IntBuffer bankdata[]; - + /** - * Constructs an nio integer-based {@link DataBuffer} with a single bank + * Constructs an nio integer-based {@link DataBuffer} with a single bank * and the specified size. * * @param size The size of the {@link DataBuffer}. @@ -222,17 +222,17 @@ public final class DirectDataBufferInt extends DataBuffer { /** * Returns the default (first) int data array in {@link DataBuffer}. - * + * * @return The first integer data array. */ public IntBuffer getData() { return data; } - /** - * Returns the data array for the specified bank. - * - * @param bank The bank whose data array you want to get. + /** + * Returns the data array for the specified bank. + * + * @param bank The bank whose data array you want to get. * @return The data array for the specified bank. */ public IntBuffer getData(int bank) { @@ -241,7 +241,7 @@ public final class DirectDataBufferInt extends DataBuffer { /** * Returns the requested data array element from the first (default) bank. - * + * * @param i The data array element you want to get. * @return The requested data array element as an integer. * @see #setElem(int, int) @@ -253,7 +253,7 @@ public final class DirectDataBufferInt extends DataBuffer { /** * Returns the requested data array element from the specified bank. - * + * * @param bank The bank from which you want to get a data array element. * @param i The data array element you want to get. * @return The requested data array element as an integer. diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 38a46f214..49b2daeae 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -123,7 +123,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, private boolean localVisibility = component.isVisible(); private boolean globalVisibility = localVisibility; private boolean visibilityPropagation = false; - + private String s(ComponentEvent e) { return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"],"+Platform.getNewline()+ " ** COMP "+e.getComponent()+Platform.getNewline()+ @@ -164,7 +164,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } @Override - public void componentHidden(ComponentEvent e) { + public void componentHidden(ComponentEvent e) { if(DEBUG) { System.err.println("JAWTWindow.componentHidden: "+s(e)); } @@ -174,7 +174,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, @Override public void hierarchyChanged(HierarchyEvent e) { final long bits = e.getChangeFlags(); - final java.awt.Component changed = e.getChanged(); + final java.awt.Component changed = e.getChanged(); if( 0 != ( java.awt.event.HierarchyEvent.DISPLAYABILITY_CHANGED & bits ) ) { final boolean displayable = changed.isDisplayable(); final boolean resetLocalVisibility = changed == component && !displayable && localVisibility != component.isVisible(); @@ -220,7 +220,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if(DEBUG) { System.err.println("JAWTWindow.invalidate() - "+Thread.currentThread().getName()); if( isSurfaceLayerAttached() ) { - System.err.println("OffscreenSurfaceLayer still attached: 0x"+Long.toHexString(offscreenSurfaceLayer)); + System.err.println("OffscreenSurfaceLayer still attached: 0x"+Long.toHexString(offscreenSurfaceLayer)); } // Thread.dumpStack(); } @@ -237,14 +237,14 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected final boolean updateBounds(JAWT_Rectangle jawtBounds) { final Rectangle jb = new Rectangle(jawtBounds.getX(), jawtBounds.getY(), jawtBounds.getWidth(), jawtBounds.getHeight()); final boolean changed = !bounds.equals(jb); - + if(changed) { if(DEBUG) { System.err.println("JAWTWindow.updateBounds: "+bounds+" -> "+jb); // Thread.dumpStack(); } bounds.set(jawtBounds.getX(), jawtBounds.getY(), jawtBounds.getWidth(), jawtBounds.getHeight()); - + if(component instanceof Container) { final java.awt.Insets contInsets = ((Container)component).getInsets(); insets.set(contInsets.left, contInsets.right, contInsets.top, contInsets.bottom); @@ -279,7 +279,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, // // OffscreenLayerOption // - + @Override public void setShallUseOffscreenLayer(boolean v) { shallUseOffscreenLayer = v; @@ -316,9 +316,9 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, * Layout the offscreen layer according to the implementing class's constraints. *

                * This method allows triggering a re-layout of the offscreen surface - * in case the implementation requires it. + * in case the implementation requires it. *

                - *

                + *

                * Call this method if any parent or ancestor's layout has been changed, * which could affects the layout of this surface. *

                @@ -326,14 +326,14 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false */ protected void layoutSurfaceLayerImpl(long layerHandle, boolean visible) {} - + private final void layoutSurfaceLayerIfEnabled(boolean visible) throws NativeWindowException { if( isOffscreenLayerSurfaceEnabled() && 0 != offscreenSurfaceLayer ) { layoutSurfaceLayerImpl(offscreenSurfaceLayer, visible); } } - - + + @Override public final void detachSurfaceLayer() throws NativeWindowException { if( 0 == offscreenSurfaceLayer) { @@ -351,35 +351,35 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } }; - /** + /** * @param detachNotify Runnable to be called before native detachment */ protected void detachSurfaceLayerImpl(final long layerHandle, final Runnable detachNotify) { throw new UnsupportedOperationException("offscreen layer not supported"); } - + @Override public final long getAttachedSurfaceLayer() { return offscreenSurfaceLayer; } - + @Override public final boolean isSurfaceLayerAttached() { return 0 != offscreenSurfaceLayer; } - + @Override public final void setChosenCapabilities(CapabilitiesImmutable caps) { ((MutableGraphicsConfiguration)getGraphicsConfiguration()).setChosenCapabilities(caps); - getPrivateGraphicsConfiguration().setChosenCapabilities(caps); + getPrivateGraphicsConfiguration().setChosenCapabilities(caps); } - + @Override public final RecursiveLock getLock() { return surfaceLock; } - + // // SurfaceUpdateListener // @@ -527,7 +527,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, public final AbstractGraphicsConfiguration getGraphicsConfiguration() { return config.getNativeGraphicsConfiguration(); } - + @Override public final long getDisplayHandle() { return getGraphicsConfiguration().getScreen().getDevice().getHandle(); @@ -545,7 +545,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, @Override public final int getHeight() { - return component.getHeight(); + return component.getHeight(); } // @@ -647,10 +647,10 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, protected abstract Point getLocationOnScreenNativeImpl(int x, int y); protected static Component getLocationOnScreenNonBlocking(Point storage, Component comp) { - final java.awt.Insets insets = new java.awt.Insets(0, 0, 0, 0); // DEBUG + final java.awt.Insets insets = new java.awt.Insets(0, 0, 0, 0); // DEBUG Component last = null; while(null != comp) { - final int dx = comp.getX(); + final int dx = comp.getX(); final int dy = comp.getY(); if( DEBUG ) { final java.awt.Insets ins = AWTMisc.getInsets(comp, false); @@ -674,7 +674,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } return last; } - + @Override public boolean hasFocus() { return component.hasFocus(); @@ -693,7 +693,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } return sb; } - + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -715,7 +715,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return sb.toString(); } - + protected final String toHexString(long l) { return "0x"+Long.toHexString(l); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java index fb6d39b2f..c83814907 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 @@ -45,7 +45,7 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl *

                * FIXME: This shall be removed when relocated EGL to the nativewindow package, * since then it can be utilized directly. - *

                + *

                */ public interface EGLDisplayLifecycleCallback { /** @@ -55,14 +55,14 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl * @return the initialized EGL display ID, or 0 if not successful */ public long eglGetAndInitDisplay(long[] nativeDisplayID); - + /** * Implementation should issue an EGL.eglTerminate(eglDisplayHandle) call. * @param eglDisplayHandle */ void eglTerminate(long eglDisplayHandle); } - + /** * Note that this is not an open connection, ie no native display handle exist. * This constructor exist to setup a default device connection/unit.
                @@ -78,9 +78,9 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl this.nativeDisplayID[0] = nativeDisplayID; this.eglLifecycleCallback = eglLifecycleCallback; } - + public long getNativeDisplayID() { return nativeDisplayID[0]; } - + @Override public Object clone() { return super.clone(); @@ -100,7 +100,7 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl } return false; } - + @Override public boolean close() { if(null != eglLifecycleCallback && 0 != handle) { @@ -111,11 +111,11 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl } return super.close(); } - + @Override public boolean isHandleOwner() { return null != eglLifecycleCallback; - } + } @Override public void clearHandleOwner() { eglLifecycleCallback = null; @@ -126,9 +126,9 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl } @Override protected Object setHandleOwnership(Object newOwnership) { - final EGLDisplayLifecycleCallback oldOwnership = eglLifecycleCallback; + final EGLDisplayLifecycleCallback oldOwnership = eglLifecycleCallback; eglLifecycleCallback = (EGLDisplayLifecycleCallback) newOwnership; return oldOwnership; - } + } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java index 0dc788c17..89df7f853 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index 5c4fd82d2..6057f6700 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -54,28 +54,28 @@ import jogamp.nativewindow.x11.X11Lib; public class SWTAccessor { private static final boolean DEBUG = true; - + private static final Field swt_control_handle; private static final boolean swt_uses_long_handles; - - private static Object swt_osx_init = new Object(); + + private static Object swt_osx_init = new Object(); private static Field swt_osx_control_view = null; private static Field swt_osx_view_id = null; - + private static final String nwt; private static final boolean isOSX; private static final boolean isWindows; private static final boolean isX11; private static final boolean isX11GTK; - + // X11/GTK, Windows/GDI, .. private static final String str_handle = "handle"; - + // OSX/Cocoa private static final String str_osx_view = "view"; // OSX private static final String str_osx_id = "id"; // OSX // static final String str_NSView = "org.eclipse.swt.internal.cocoa.NSView"; - + private static final Method swt_control_internal_new_GC; private static final Method swt_control_internal_dispose_GC; private static final String str_internal_new_GC = "internal_new_GC"; @@ -85,18 +85,18 @@ public class SWTAccessor { public static final Class OS_gtk_class; private static final String str_OS_gtk_version = "GTK_VERSION"; public static final VersionNumber OS_gtk_version; - + private static final Method OS_gtk_widget_realize; private static final Method OS_gtk_widget_unrealize; // optional (removed in SWT 4.3) private static final Method OS_GTK_WIDGET_WINDOW; private static final Method OS_gtk_widget_get_window; private static final Method OS_gdk_x11_drawable_get_xdisplay; private static final Method OS_gdk_x11_display_get_xdisplay; - private static final Method OS_gdk_window_get_display; - private static final Method OS_gdk_x11_drawable_get_xid; + private static final Method OS_gdk_window_get_display; + private static final Method OS_gdk_x11_drawable_get_xid; private static final Method OS_gdk_x11_window_get_xid; private static final Method OS_gdk_window_set_back_pixmap; - + private static final String str_gtk_widget_realize = "gtk_widget_realize"; private static final String str_gtk_widget_unrealize = "gtk_widget_unrealize"; private static final String str_GTK_WIDGET_WINDOW = "GTK_WIDGET_WINDOW"; @@ -107,11 +107,11 @@ public class SWTAccessor { private static final String str_gdk_x11_drawable_get_xid = "gdk_x11_drawable_get_xid"; private static final String str_gdk_x11_window_get_xid = "gdk_x11_window_get_xid"; private static final String str_gdk_window_set_back_pixmap = "gdk_window_set_back_pixmap"; - + private static final VersionNumber GTK_VERSION_2_14_0 = new VersionNumber(2, 14, 0); private static final VersionNumber GTK_VERSION_2_24_0 = new VersionNumber(2, 24, 0); private static final VersionNumber GTK_VERSION_3_0_0 = new VersionNumber(3, 0, 0); - + private static VersionNumber GTK_VERSION(int version) { // return (major << 16) + (minor << 8) + micro; final int micro = ( version ) & 0x0f; @@ -119,20 +119,20 @@ public class SWTAccessor { final int major = ( version >> 16 ) & 0x0f; return new VersionNumber(major, minor, micro); } - + static { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { NativeWindowFactory.initSingleton(); // last resort .. return null; } } ); - + nwt = NativeWindowFactory.getNativeWindowType(false); isOSX = NativeWindowFactory.TYPE_MACOSX == nwt; isWindows = NativeWindowFactory.TYPE_WINDOWS == nwt; isX11 = NativeWindowFactory.TYPE_X11 == nwt; - - Field f = null; + + Field f = null; if( !isOSX ) { try { f = Control.class.getField(str_handle); @@ -141,7 +141,7 @@ public class SWTAccessor { } } swt_control_handle = f; // maybe null ! - + boolean ulh; if (null != swt_control_handle) { ulh = swt_control_handle.getGenericType().toString().equals(long.class.toString()); @@ -151,7 +151,7 @@ public class SWTAccessor { swt_uses_long_handles = ulh; // System.err.println("SWT long handles: " + swt_uses_long_handles); // System.err.println("Platform 64bit: "+Platform.is64Bit()); - + Method m=null; try { m = ReflectionUtil.getMethod(Control.class, str_internal_new_GC, new Class[] { GCData.class }); @@ -159,12 +159,12 @@ public class SWTAccessor { throw new NativeWindowException(ex); } swt_control_internal_new_GC = m; - + try { if(swt_uses_long_handles) { - m = Control.class.getDeclaredMethod(str_internal_dispose_GC, new Class[] { long.class, GCData.class }); + m = Control.class.getDeclaredMethod(str_internal_dispose_GC, new Class[] { long.class, GCData.class }); } else { - m = Control.class.getDeclaredMethod(str_internal_dispose_GC, new Class[] { int.class, GCData.class }); + m = Control.class.getDeclaredMethod(str_internal_dispose_GC, new Class[] { int.class, GCData.class }); } } catch (NoSuchMethodException ex) { throw new NativeWindowException(ex); @@ -181,7 +181,7 @@ public class SWTAccessor { c = ReflectionUtil.getClass(str_OS_gtk_class, false, SWTAccessor.class.getClassLoader()); Field field_OS_gtk_version = c.getField(str_OS_gtk_version); _gtk_version = GTK_VERSION(field_OS_gtk_version.getInt(null)); - m1 = c.getDeclaredMethod(str_gtk_widget_realize, handleType); + m1 = c.getDeclaredMethod(str_gtk_widget_realize, handleType); if (_gtk_version.compareTo(GTK_VERSION_2_14_0) >= 0) { m4 = c.getDeclaredMethod(str_gtk_widget_get_window, handleType); } else { @@ -189,9 +189,9 @@ public class SWTAccessor { } if (_gtk_version.compareTo(GTK_VERSION_2_24_0) >= 0) { m6 = c.getDeclaredMethod(str_gdk_x11_display_get_xdisplay, handleType); - m7 = c.getDeclaredMethod(str_gdk_window_get_display, handleType); + m7 = c.getDeclaredMethod(str_gdk_window_get_display, handleType); } else { - m5 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xdisplay, handleType); + m5 = c.getDeclaredMethod(str_gdk_x11_drawable_get_xdisplay, handleType); } if (_gtk_version.compareTo(GTK_VERSION_3_0_0) >= 0) { m9 = c.getDeclaredMethod(str_gdk_x11_window_get_xid, handleType); @@ -200,7 +200,7 @@ public class SWTAccessor { } ma = c.getDeclaredMethod(str_gdk_window_set_back_pixmap, handleType, handleType, boolean.class); } catch (Exception ex) { throw new NativeWindowException(ex); } - // optional + // optional try { m2 = c.getDeclaredMethod(str_gtk_widget_unrealize, handleType); } catch (Exception ex) { } @@ -213,33 +213,33 @@ public class SWTAccessor { OS_gtk_widget_get_window = m4; OS_gdk_x11_drawable_get_xdisplay = m5; OS_gdk_x11_display_get_xdisplay = m6; - OS_gdk_window_get_display = m7; + OS_gdk_window_get_display = m7; OS_gdk_x11_drawable_get_xid = m8; OS_gdk_x11_window_get_xid = m9; OS_gdk_window_set_back_pixmap = ma; - + isX11GTK = isX11 && null != OS_gtk_class; - + if(DEBUG) { System.err.println("SWTAccessor.: GTK Version: "+OS_gtk_version); } } - + private static Number getIntOrLong(long arg) { if(swt_uses_long_handles) { return new Long(arg); } return new Integer((int) arg); } - - private static void callStaticMethodL2V(Method m, long arg) { + + private static void callStaticMethodL2V(Method m, long arg) { ReflectionUtil.callMethod(null, m, new Object[] { getIntOrLong(arg) }); } - - private static void callStaticMethodLLZ2V(Method m, long arg0, long arg1, boolean arg3) { + + private static void callStaticMethodLLZ2V(Method m, long arg0, long arg1, boolean arg3) { ReflectionUtil.callMethod(null, m, new Object[] { getIntOrLong(arg0), getIntOrLong(arg1), Boolean.valueOf(arg3) }); } - + private static long callStaticMethodL2L(Method m, long arg) { Object o = ReflectionUtil.callMethod(null, m, new Object[] { getIntOrLong(arg) }); if(o instanceof Number) { @@ -252,18 +252,18 @@ public class SWTAccessor { // // Public properties // - + public static boolean isUsingLongHandles() { return swt_uses_long_handles; } public static boolean useX11GTK() { return isX11GTK; } public static VersionNumber GTK_VERSION() { return OS_gtk_version; } - + // // Common GTK // - + public static long gdk_widget_get_window(long handle) { final long window; if (OS_gtk_version.compareTo(GTK_VERSION_2_14_0) >= 0) { @@ -276,7 +276,7 @@ public class SWTAccessor { } return window; } - + public static long gdk_window_get_xdisplay(long window) { final long xdisplay; if (OS_gtk_version.compareTo(GTK_VERSION_2_24_0) >= 0) { @@ -293,7 +293,7 @@ public class SWTAccessor { } return xdisplay; } - + public static long gdk_window_get_xwindow(long window) { final long xWindow; if (OS_gtk_version.compareTo(GTK_VERSION_3_0_0) >= 0) { @@ -306,15 +306,15 @@ public class SWTAccessor { } return xWindow; } - + public static void gdk_window_set_back_pixmap(long window, long pixmap, boolean parent_relative) { callStaticMethodLLZ2V(OS_gdk_window_set_back_pixmap, window, pixmap, parent_relative); } - + // // Common any toolkit // - + /** * @param swtControl the SWT Control to retrieve the native widget-handle from * @return the native widget-handle @@ -335,9 +335,9 @@ public class SWTAccessor { } } catch (Exception ex) { throw new NativeWindowException(ex); - } + } } - } else { + } else { try { h = swt_control_handle.getLong(swtControl); } catch (Exception ex) { @@ -350,14 +350,14 @@ public class SWTAccessor { return h; } - public static void setRealized(final Control swtControl, final boolean realize) - throws NativeWindowException + public static void setRealized(final Control swtControl, final boolean realize) + throws NativeWindowException { if(!realize && swtControl.isDisposed()) { return; } final long handle = getHandle(swtControl); - + if(null != OS_gtk_class) { invoke(true, new Runnable() { public void run() { @@ -365,16 +365,16 @@ public class SWTAccessor { callStaticMethodL2V(OS_gtk_widget_realize, handle); } else if(null != OS_gtk_widget_unrealize) { callStaticMethodL2V(OS_gtk_widget_unrealize, handle); - } + } } }); } } - + /** * @param swtControl the SWT Control to retrieve the native device handle from * @return the AbstractGraphicsDevice w/ the native device handle - * @throws NativeWindowException if the widget handle is null + * @throws NativeWindowException if the widget handle is null * @throws UnsupportedOperationException if the windowing system is not supported */ public static AbstractGraphicsDevice getDevice(Control swtControl) throws NativeWindowException, UnsupportedOperationException { @@ -391,7 +391,7 @@ public class SWTAccessor { } throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } - + /** * @param device * @param screen -1 is default screen of the given device, e.g. maybe 0 or determined by native API. >= 0 is specific screen @@ -400,7 +400,7 @@ public class SWTAccessor { public static AbstractGraphicsScreen getScreen(AbstractGraphicsDevice device, int screen) { return NativeWindowFactory.createScreen(device, screen); } - + public static int getNativeVisualID(AbstractGraphicsDevice device, long windowHandle) { if( isX11 ) { return X11Lib.GetVisualIDFromWindow(device.getHandle(), windowHandle); @@ -408,29 +408,29 @@ public class SWTAccessor { if( isWindows || isOSX ) { return VisualIDHolder.VID_UNDEFINED; } - throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); + throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } - + /** * @param swtControl the SWT Control to retrieve the native window handle from * @return the native window handle - * @throws NativeWindowException if the widget handle is null + * @throws NativeWindowException if the widget handle is null * @throws UnsupportedOperationException if the windowing system is not supported */ public static long getWindowHandle(Control swtControl) throws NativeWindowException, UnsupportedOperationException { - final long handle = getHandle(swtControl); + final long handle = getHandle(swtControl); if(0 == handle) { throw new NativeWindowException("Null SWT handle of SWT control "+swtControl); } if( isX11GTK ) { - return gdk_window_get_xwindow( gdk_widget_get_window( handle ) ); + return gdk_window_get_xwindow( gdk_widget_get_window( handle ) ); } if( isWindows || isOSX ) { return handle; } throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); } - + public static long newGC(final Control swtControl, final GCData gcData) { final Object[] o = new Object[1]; invoke(true, new Runnable() { @@ -444,7 +444,7 @@ public class SWTAccessor { throw new InternalError("SWT internal_new_GC did not return int or long but "+o[0].getClass()); } } - + public static void disposeGC(final Control swtControl, final long gc, final GCData gcData) { invoke(true, new Runnable() { public void run() { @@ -456,7 +456,7 @@ public class SWTAccessor { } }); } - + /** * Runs the specified action in an SWT compatible thread, which is: *
                  @@ -468,7 +468,7 @@ public class SWTAccessor { *
                • Linux, Windows, .. *
                    *
                  • Current thread.
                  • - *
                • + *
                * * @see Platform#AWT_AVAILABLE * @see Platform#getOSType() @@ -479,9 +479,9 @@ public class SWTAccessor { OSXUtil.RunOnMainThread(wait, runnable); } else { runnable.run(); - } + } } - + /** * Runs the specified action on the SWT UI thread. *

                @@ -492,56 +492,56 @@ public class SWTAccessor { public static void invoke(org.eclipse.swt.widgets.Display display, boolean wait, Runnable runnable) { if( display.isDisposed() || Thread.currentThread() == display.getThread() ) { invoke(wait, runnable); - } else if( wait ) { + } else if( wait ) { display.syncExec(runnable); } else { display.asyncExec(runnable); } } - + // // Specific X11 GTK ChildWindow - Using plain X11 native parenting (works well) // - + public static long createCompatibleX11ChildWindow(AbstractGraphicsScreen screen, Control swtControl, int visualID, int width, int height) { final long handle = getHandle(swtControl); final long parentWindow = gdk_widget_get_window( handle ); gdk_window_set_back_pixmap (parentWindow, 0, false); - + final long x11ParentHandle = gdk_window_get_xwindow(parentWindow); final long x11WindowHandle = X11Lib.CreateWindow(x11ParentHandle, screen.getDevice().getHandle(), screen.getIndex(), visualID, width, height, true, true); - + return x11WindowHandle; } - + public static void resizeX11Window(AbstractGraphicsDevice device, Rectangle clientArea, long x11Window) { - X11Lib.SetWindowPosSize(device.getHandle(), x11Window, clientArea.x, clientArea.y, clientArea.width, clientArea.height); + X11Lib.SetWindowPosSize(device.getHandle(), x11Window, clientArea.x, clientArea.y, clientArea.width, clientArea.height); } public static void destroyX11Window(AbstractGraphicsDevice device, long x11Window) { X11Lib.DestroyWindow(device.getHandle(), x11Window); } - + // // Specific X11 SWT/GTK ChildWindow - Using SWT/GTK native parenting (buggy - sporadic resize flickering, sporadic drop of rendering) // // FIXME: Need to use reflection for 32bit access as well ! // - + // public static final int GDK_WA_TYPE_HINT = 1 << 9; // public static final int GDK_WA_VISUAL = 1 << 6; - + public static long createCompatibleGDKChildWindow(Control swtControl, int visualID, int width, int height) { return 0; /** final long handle = SWTAccessor.getHandle(swtControl); final long parentWindow = gdk_widget_get_window( handle ); - + final long screen = OS.gdk_screen_get_default (); final long gdkvisual = OS.gdk_x11_screen_lookup_visual (screen, visualID); - + final GdkWindowAttr attrs = new GdkWindowAttr(); attrs.width = width > 0 ? width : 1; - attrs.height = height > 0 ? height : 1; + attrs.height = height > 0 ? height : 1; attrs.event_mask = OS.GDK_KEY_PRESS_MASK | OS.GDK_KEY_RELEASE_MASK | OS.GDK_FOCUS_CHANGE_MASK | OS.GDK_POINTER_MOTION_MASK | OS.GDK_BUTTON_PRESS_MASK | OS.GDK_BUTTON_RELEASE_MASK | @@ -550,16 +550,16 @@ public class SWTAccessor { OS.GDK_POINTER_MOTION_HINT_MASK; attrs.window_type = OS.GDK_WINDOW_CHILD; attrs.visual = gdkvisual; - + final long childWindow = OS.gdk_window_new (parentWindow, attrs, OS.GDK_WA_VISUAL|GDK_WA_TYPE_HINT); OS.gdk_window_set_user_data (childWindow, handle); OS.gdk_window_set_back_pixmap (parentWindow, 0, false); - + OS.gdk_window_show (childWindow); OS.gdk_flush(); return childWindow; */ } - + public static void showGDKWindow(long gdkWindow) { /* OS.gdk_window_show (gdkWindow); OS.gdk_flush(); */ @@ -576,8 +576,8 @@ public class SWTAccessor { OS.gdk_window_resize (gdkWindow, clientArea.width, clientArea.height); OS.gdk_flush(); */ } - + public static void destroyGDKWindow(long gdkWindow) { // OS.gdk_window_destroy (gdkWindow); - } + } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java index 5cabdf150..7468d254b 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 @@ -34,7 +34,7 @@ package com.jogamp.nativewindow.windows; import javax.media.nativewindow.*; -/** +/** * Encapsulates a graphics device on Windows platforms.
                */ public class WindowsGraphicsDevice extends DefaultGraphicsDevice implements Cloneable { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsConfiguration.java index 0d2914c7d..120c86584 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsConfiguration.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsConfiguration.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -48,7 +48,7 @@ import jogamp.nativewindow.x11.XVisualInfo; public class X11GraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable { private XVisualInfo info; - public X11GraphicsConfiguration(X11GraphicsScreen screen, + public X11GraphicsConfiguration(X11GraphicsScreen screen, CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, XVisualInfo info) { super(screen, capsChosen, capsRequested); @@ -71,12 +71,12 @@ public class X11GraphicsConfiguration extends MutableGraphicsConfiguration imple final public int getXVisualID() { return (null!=info)?(int)info.getVisualid():0; } - + @Override public String toString() { return getClass().getSimpleName()+"["+getScreen()+", visualID 0x" + Long.toHexString(getXVisualID()) + ",\n\tchosen " + capabilitiesChosen+ - ",\n\trequested " + capabilitiesRequested+ + ",\n\trequested " + capabilitiesRequested+ "]"; } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index e630e012e..40d212df3 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -87,12 +87,12 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl handleOwner = owner; isXineramaEnabled = X11Util.XineramaIsEnabled(this); } - + private static int getDefaultScreenImpl(long dpy) { return X11Lib.DefaultScreen(dpy); } - + /** * Returns the default screen number as referenced by the display connection, i.e. 'somewhere:0.1' -> 1 *

                @@ -110,7 +110,7 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl } return ds; } - + public int getDefaultVisualID() { final long display = getHandle(); if(0==display) { @@ -118,11 +118,11 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl } return X11Lib.DefaultVisualID(display, getDefaultScreenImpl(display)); } - + public final boolean isXineramaEnabled() { return isXineramaEnabled; } - + @Override public Object clone() { return super.clone(); @@ -142,7 +142,7 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl } return false; } - + @Override public boolean close() { if(handleOwner && 0 != handle) { @@ -153,11 +153,11 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl } return super.close(); } - + @Override public boolean isHandleOwner() { return handleOwner; - } + } @Override public void clearHandleOwner() { handleOwner = false; @@ -168,8 +168,8 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl } @Override protected Object setHandleOwnership(Object newOwnership) { - final Boolean oldOwnership = Boolean.valueOf(handleOwner); + final Boolean oldOwnership = Boolean.valueOf(handleOwner); handleOwner = ((Boolean) newOwnership).booleanValue(); return oldOwnership; - } + } } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java index 2ec66290a..8aac7095a 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -62,7 +62,7 @@ public class X11GraphicsScreen extends DefaultGraphicsScreen implements Cloneabl // It still could be an AWT hold handle .. return X11Lib.DefaultVisualID(getDevice().getHandle(), getIndex()); } - + public Object clone() { return super.clone(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java index 4e45113d4..48f72e574 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 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 @@ -29,11 +29,11 @@ * 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. */ @@ -44,7 +44,7 @@ package javax.media.nativewindow; pixel format in a toolkit-independent manner. */ public interface AbstractGraphicsConfiguration extends VisualIDHolder, Cloneable { public Object clone(); - + /** * Return the screen this graphics configuration is valid for */ diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java index ed305d49e..31b64269f 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2005 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 @@ -29,11 +29,11 @@ * 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. */ @@ -47,7 +47,7 @@ import jogamp.nativewindow.Debug; */ public interface AbstractGraphicsDevice extends Cloneable { public static final boolean DEBUG = Debug.debug("GraphicsDevice"); - + /** Dummy connection value for a default connection where no native support for multiple devices is available */ public static String DEFAULT_CONNECTION = "decon"; @@ -58,7 +58,7 @@ public interface AbstractGraphicsDevice extends Cloneable { public static int DEFAULT_UNIT = 0; public Object clone(); - + /** * Returns the type of the underlying subsystem, ie * NativeWindowFactory.TYPE_KD, NativeWindowFactory.TYPE_X11, .. @@ -96,7 +96,7 @@ public interface AbstractGraphicsDevice extends Cloneable { * The unique ID may be used as a key for semantic device mapping. *

                *

                - * The returned string object reference is unique using {@link String#intern()} + * The returned string object reference is unique using {@link String#intern()} * and hence can be used as a key itself. *

                */ @@ -114,29 +114,29 @@ public interface AbstractGraphicsDevice extends Cloneable { */ public void lock(); - /** + /** * Optionally unlocking the device, utilizing eg {@link javax.media.nativewindow.ToolkitLock#unlock()}. * The lock implementation must be recursive. - * + * * @throws RuntimeException in case the lock is not acquired by this thread. */ public void unlock(); /** - * @throws RuntimeException if current thread does not hold the lock + * @throws RuntimeException if current thread does not hold the lock */ public void validateLocked() throws RuntimeException; - - /** + + /** * Optionally [re]opening the device if handle is null. *

                * The default implementation is a NOP. *

                *

                - * Example implementations like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice} - * or {@link com.jogamp.nativewindow.egl.EGLGraphicsDevice} + * Example implementations like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice} + * or {@link com.jogamp.nativewindow.egl.EGLGraphicsDevice} * issue the native open operation in case handle is null. - *

                + *

                * * @return true if the handle was null and opening was successful, otherwise false. */ @@ -148,19 +148,19 @@ public interface AbstractGraphicsDevice extends Cloneable { * The default implementation {@link ToolkitLock#dispose() dispose} it's {@link ToolkitLock} and sets the handle to null. *

                *

                - * Example implementations like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice} - * or {@link com.jogamp.nativewindow.egl.EGLGraphicsDevice} + * Example implementations like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice} + * or {@link com.jogamp.nativewindow.egl.EGLGraphicsDevice} * issue the native close operation or skip it depending on the {@link #isHandleOwner() handles's ownership}. - *

                + *

                * * @return true if the handle was not null and closing was successful, otherwise false. */ public boolean close(); - + /** * @return true if instance owns the handle to issue {@link #close()}, otherwise false. */ public boolean isHandleOwner(); - + public void clearHandleOwner(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java index acb98073b..da8f12f3e 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java +++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsScreen.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2005 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 @@ -28,11 +28,11 @@ * 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. */ @@ -45,7 +45,7 @@ package javax.media.nativewindow; public interface AbstractGraphicsScreen extends Cloneable { public Object clone(); - + /** * Return the device this graphics configuration is valid for */ diff --git a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java index f2a8e2394..9eed887b5 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java +++ b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java @@ -61,7 +61,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { // Switch for on- or offscreen private boolean onscreen = true; - + // offscreen bitmap mode private boolean isBitmap = false; @@ -74,7 +74,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { public Object cloneMutable() { return clone(); } - + @Override public Object clone() { try { @@ -85,7 +85,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { } /** - * Copies all {@link Capabilities} values + * Copies all {@link Capabilities} values * from source into this instance. * @return this instance */ @@ -103,7 +103,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { transparentValueAlpha = other.getTransparentAlphaValue(); return this; } - + @Override public int hashCode() { // 31 * x == (x << 5) - x @@ -150,15 +150,15 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { **/ @Override public int compareTo(final CapabilitiesImmutable caps) { - /** + /** if ( ! ( o instanceof CapabilitiesImmutable ) ) { Class c = (null != o) ? o.getClass() : null ; throw new ClassCastException("Not a CapabilitiesImmutable object, but " + c); } final CapabilitiesImmutable caps = (CapabilitiesImmutable) o; */ - + final int rgba = redBits * greenBits * blueBits * ( alphaBits + 1 ); - + final int xrgba = caps.getRedBits() * caps.getGreenBits() * caps.getBlueBits() * ( caps.getAlphaBits() + 1 ); if(rgba > xrgba) { @@ -222,17 +222,17 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { 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. *

                - * Note: If alpha bits are zero, they are set to one + * Note: If alpha bits are zero, they are set to one * by {@link #setBackgroundOpaque(boolean)} and it's OpenGL specialization GLCapabilities::setSampleBuffers(boolean).
                * Ensure to call this method after the above to ensure a zero value.
                * The above automated settings takes into account, that the user calls this method to request alpha bits, * not to reflect a current state. Nevertheless if this is the case - call it at last. - *

                + *

                */ public void setAlphaBits(int alphaBits) { this.alphaBits = alphaBits; @@ -271,7 +271,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { * Defaults to true. *

                *

                - * If requesting an offscreen surface without further selection of it's mode, + * If requesting an offscreen surface without further selection of it's mode, * e.g. FBO, Pbuffer or {@link #setBitmap(boolean) bitmap}, * the implementation will choose the best available offscreen mode. *

                @@ -304,12 +304,12 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { } isBitmap = enable; } - + @Override public boolean isBitmap() { - return isBitmap; + return isBitmap; } - + @Override public final int getTransparentRedValue() { return transparentValueRed; } @@ -354,7 +354,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { public StringBuilder toString(StringBuilder sink) { return toString(sink, true); } - + /** Returns a textual representation of this Capabilities object. */ @Override @@ -365,7 +365,7 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { msg.append("]"); return msg.toString(); } - + /** Return a textual representation of this object's on/off screen state. Use the given StringBuilder [optional]. */ protected StringBuilder onoffScreenToString(StringBuilder sink) { if(null == sink) { @@ -381,19 +381,19 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { } else if(onscreen) { sink.append("."); // no additional off-screen modes besides on-screen } else { - sink.append("auto-cfg"); // auto-config off-screen mode + sink.append("auto-cfg"); // auto-config off-screen mode } - sink.append("]"); - + sink.append("]"); + return sink; } - + /** Element separator */ protected static final String ESEP = "/"; /** Component separator */ protected static final String CSEP = ", "; - - protected StringBuilder toString(StringBuilder sink, boolean withOnOffScreen) { + + protected StringBuilder toString(StringBuilder sink, boolean withOnOffScreen) { if(null == sink) { sink = new StringBuilder(); } @@ -409,6 +409,6 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable { } return sink; } - + protected final String toHexString(int val) { return Integer.toHexString(val); } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java index e1fdf4938..1f4db7997 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java +++ b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesChooser.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ @@ -58,7 +58,7 @@ public interface CapabilitiesChooser { not necessarily required, that the chooser select that entry.

                Note: this method is called automatically by the - {@link GraphicsConfigurationFactory#chooseGraphicsConfiguration} method + {@link GraphicsConfigurationFactory#chooseGraphicsConfiguration} method when an instance of this class is passed in to it. It should generally not be invoked by users directly, unless it is desired to delegate the diff --git a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java index 85659f286..c496a1535 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java @@ -70,12 +70,12 @@ public interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable, C * Returns whether an opaque or translucent surface is requested, supported or chosen. *

                * Default is true, i.e. opaque. - *

                + *

                */ boolean isBackgroundOpaque(); /** - * Returns whether an on- or offscreen surface is requested, available or chosen. + * Returns whether an on- or offscreen surface is requested, available or chosen. *

                * Default is true, i.e. onscreen. *

                @@ -83,7 +83,7 @@ public interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable, C * Mind that an capabilities intance w/ available semantics * may show onscreen, but also the offscreen modes FBO, Pbuffer or {@link #setBitmap(boolean) bitmap}. * This is valid, since one native configuration maybe used for either functionality. - *

                + *

                */ boolean isOnscreen(); @@ -97,7 +97,7 @@ public interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable, C *

                */ boolean isBitmap(); - + /** * Gets the transparent red value for the frame buffer configuration. This * value is undefined if; equals true. diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java index 4f07bca9b..6095db052 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -66,16 +66,16 @@ import jogamp.nativewindow.Debug; */ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { - private static final boolean DEBUG; + private static final boolean DEBUG; static { Debug.initSingleton(); DEBUG = Debug.isPropertyDefined("nativewindow.debug.CapabilitiesChooser", true); } - + private final static int NO_SCORE = -9999999; private final static int COLOR_MISMATCH_PENALTY_SCALE = 36; - + public int chooseCapabilities(final CapabilitiesImmutable desired, final List available, final int windowSystemRecommendedChoice) { @@ -112,7 +112,7 @@ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { if (desired.isOnscreen() && !cur.isOnscreen()) { continue; // requested onscreen, but n/a } - + int score = 0; // Compute difference in color depth score += (COLOR_MISMATCH_PENALTY_SCALE * @@ -132,7 +132,7 @@ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { System.err.println(" ]"); } - // Ready to select. Choose score closest to 0. + // Ready to select. Choose score closest to 0. int scoreClosestToZero = NO_SCORE; int chosenIndex = -1; for (int i = 0; i < availnum; i++) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java index 6b23172e1..3e32f30df 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 @@ -36,12 +36,12 @@ import jogamp.nativewindow.Debug; public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphicsConfiguration { protected static final boolean DEBUG = Debug.debug("GraphicsConfiguration"); - + private AbstractGraphicsScreen screen; protected CapabilitiesImmutable capabilitiesChosen; protected CapabilitiesImmutable capabilitiesRequested; - public DefaultGraphicsConfiguration(AbstractGraphicsScreen screen, + public DefaultGraphicsConfiguration(AbstractGraphicsScreen screen, CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested) { if(null == screen) { throw new IllegalArgumentException("Null screen"); @@ -89,7 +89,7 @@ public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphics final public int getVisualID(VIDType type) throws NativeWindowException { return capabilitiesChosen.getVisualID(type); } - + /** * Set the capabilities to a new value. * @@ -119,7 +119,7 @@ public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphics public String toString() { return getClass().getSimpleName()+"[" + screen + ",\n\tchosen " + capabilitiesChosen+ - ",\n\trequested " + capabilitiesRequested+ + ",\n\trequested " + capabilitiesRequested+ "]"; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java index 0bf5c2937..d74954a0d 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -140,8 +140,8 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice public final void validateLocked() throws RuntimeException { toolkitLock.validateLocked(); } - - /** + + /** * {@inheritDoc} *

                * Locking is perfomed via delegation to {@link ToolkitLock#lock()}, {@link ToolkitLock#unlock()}. @@ -154,7 +154,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice public final void unlock() { toolkitLock.unlock(); } - + @Override public boolean open() { return false; @@ -174,11 +174,11 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice public boolean isHandleOwner() { return false; } - + @Override - public void clearHandleOwner() { + public void clearHandleOwner() { } - + @Override public String toString() { return getClass().getSimpleName()+"[type "+getType()+", connection "+getConnection()+", unitID "+getUnitID()+", handle 0x"+Long.toHexString(getHandle())+", owner "+isHandleOwner()+", "+toolkitLock+"]"; @@ -193,14 +193,14 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice handle = newHandle; return oldHandle; } - + protected Object getHandleOwnership() { return null; } protected Object setHandleOwnership(Object newOwnership) { return null; } - + public static final void swapDeviceHandleAndOwnership(final DefaultGraphicsDevice aDevice1, final DefaultGraphicsDevice aDevice2) { aDevice1.lock(); try { @@ -219,7 +219,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice aDevice1.unlock(); } } - + /** * Set the internal ToolkitLock, which is used within the * {@link #lock()} and {@link #unlock()} implementation. @@ -228,7 +228,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice * The current ToolkitLock is being locked/unlocked while swapping the reference, * ensuring no concurrent access can occur during the swap. *

                - * + * * @param locker the ToolkitLock, if null, {@link jogamp.nativewindow.NullToolkitLock} is being used * @return the previous ToolkitLock instance */ @@ -253,8 +253,8 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice return toolkitLock; } - /** - * Returns a unique String object using {@link String#intern()} for the given arguments, + /** + * Returns a unique String object using {@link String#intern()} for the given arguments, * which object reference itself can be used as a key. */ protected static String getUniqueID(String type, String connection, int unitID) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java index 9fa58c7a3..ffcad235c 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 @@ -57,7 +57,7 @@ public class DefaultGraphicsScreen implements Cloneable, AbstractGraphicsScreen public AbstractGraphicsDevice getDevice() { return device; } - + public int getIndex() { return idx; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java index 9694f2491..e1aa91959 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008-2009 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 @@ -48,7 +48,7 @@ import java.util.Set; /** * Provides the mechanism by which the graphics configuration for a - * window can be chosen before the window is created. The graphics + * window can be chosen before the window is created. The graphics * configuration decides parameters related to hardware accelerated rendering such * as the OpenGL pixel format.
                * On some window systems (EGL/OpenKODE and X11 in particular) it is necessary to @@ -69,21 +69,21 @@ public abstract class GraphicsConfigurationFactory { public final Class deviceType; public final Class capsType; private final int hash32; - + public DeviceCapsType(Class deviceType, Class capsType) { this.deviceType = deviceType; this.capsType = capsType; - + // 31 * x == (x << 5) - x int hash32 = 31 + deviceType.hashCode(); hash32 = ((hash32 << 5) - hash32) + capsType.hashCode(); this.hash32 = hash32; } - + public final int hashCode() { return hash32; } - + public final boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof DeviceCapsType) { @@ -92,18 +92,18 @@ public abstract class GraphicsConfigurationFactory { } return false; } - + @Override public final String toString() { return "DeviceCapsType["+deviceType.getName()+", "+capsType.getName()+"]"; } - + } - + private static final Map registeredFactories; - private static final DeviceCapsType defaultDeviceCapsType; + private static final DeviceCapsType defaultDeviceCapsType; static boolean initialized = false; - + static { DEBUG = Debug.debug("GraphicsConfiguration"); if(DEBUG) { @@ -113,7 +113,7 @@ public abstract class GraphicsConfigurationFactory { registeredFactories = Collections.synchronizedMap(new HashMap()); defaultDeviceCapsType = new DeviceCapsType(AbstractGraphicsDevice.class, CapabilitiesImmutable.class); } - + public static synchronized void initSingleton() { if(!initialized) { initialized = true; @@ -121,31 +121,31 @@ public abstract class GraphicsConfigurationFactory { if(DEBUG) { System.err.println(Thread.currentThread().getName()+" - GraphicsConfigurationFactory.initSingleton()"); } - + // Register the default no-op factory for arbitrary // AbstractGraphicsDevice implementations, including // AWTGraphicsDevice instances -- the OpenGL binding will take // care of handling AWTGraphicsDevices on X11 platforms (as // well as X11GraphicsDevices in non-AWT situations) registerFactory(defaultDeviceCapsType.deviceType, defaultDeviceCapsType.capsType, new DefaultGraphicsConfigurationFactoryImpl()); - + if (NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(true)) { try { - ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.X11GraphicsConfigurationFactory", - "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader()); + ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.X11GraphicsConfigurationFactory", + "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader()); } catch (Exception e) { throw new RuntimeException(e); } if(NativeWindowFactory.isAWTAvailable()) { try { - ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.awt.X11AWTGraphicsConfigurationFactory", - "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader()); + ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.awt.X11AWTGraphicsConfigurationFactory", + "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader()); } catch (Exception e) { /* n/a */ } } } } } - + public static synchronized void shutdown() { if(initialized) { initialized = false; @@ -155,7 +155,7 @@ public abstract class GraphicsConfigurationFactory { registeredFactories.clear(); } } - + protected static String getThreadName() { return Thread.currentThread().getName(); } @@ -176,10 +176,10 @@ public abstract class GraphicsConfigurationFactory { /** * Returns the graphics configuration factory for use with the * given device and capability. - * + * * @see #getFactory(Class, Class) */ - public static GraphicsConfigurationFactory getFactory(AbstractGraphicsDevice device, CapabilitiesImmutable caps) { + public static GraphicsConfigurationFactory getFactory(AbstractGraphicsDevice device, CapabilitiesImmutable caps) { if (device == null) { throw new IllegalArgumentException("null device"); } @@ -195,7 +195,7 @@ public abstract class GraphicsConfigurationFactory { *

                * Note: Registered device types maybe classes or interfaces, where capabilities types are interfaces only. *

                - * + * *

                * Pseudo code for finding a suitable factory is: *

                @@ -211,7 +211,7 @@ public abstract class GraphicsConfigurationFactory {
                      * @param deviceType the minimum capabilities class type accepted, must implement or extend {@link AbstractGraphicsDevice}
                      * @param capabilitiesType the minimum capabilities class type accepted, must implement or extend {@link CapabilitiesImmutable}
                      *
                -     * @throws IllegalArgumentException if the deviceType does not implement {@link AbstractGraphicsDevice} or 
                +     * @throws IllegalArgumentException if the deviceType does not implement {@link AbstractGraphicsDevice} or
                      *                                  capabilitiesType does not implement {@link CapabilitiesImmutable}
                      */
                     public static GraphicsConfigurationFactory getFactory(Class deviceType, Class capabilitiesType)
                @@ -228,12 +228,12 @@ public abstract class GraphicsConfigurationFactory {
                             System.err.println("GraphicsConfigurationFactory.getFactory: "+deviceType.getName()+", "+capabilitiesType.getName());
                             dumpFactories();
                         }
                -        
                -        final List> deviceTypes = getAllAssignableClassesFrom(defaultDeviceCapsType.deviceType, deviceType, false);        
                +
                +        final List> deviceTypes = getAllAssignableClassesFrom(defaultDeviceCapsType.deviceType, deviceType, false);
                         if(DEBUG) {
                             System.err.println("GraphicsConfigurationFactory.getFactory() deviceTypes: " + deviceTypes);
                         }
                -        final List> capabilitiesTypes = getAllAssignableClassesFrom(defaultDeviceCapsType.capsType, capabilitiesType, true);        
                +        final List> capabilitiesTypes = getAllAssignableClassesFrom(defaultDeviceCapsType.capsType, capabilitiesType, true);
                         if(DEBUG) {
                             System.err.println("GraphicsConfigurationFactory.getFactory() capabilitiesTypes: " + capabilitiesTypes);
                         }
                @@ -259,7 +259,7 @@ public abstract class GraphicsConfigurationFactory {
                         return factory;
                     }
                     private static ArrayList> getAllAssignableClassesFrom(Class superClassOrInterface, Class fromClass, boolean interfacesOnly) {
                -        // Using a todo list avoiding a recursive loop! 
                +        // Using a todo list avoiding a recursive loop!
                         final ArrayList> inspectClasses  = new ArrayList>();
                         final ArrayList> resolvedInterfaces = new ArrayList>();
                         inspectClasses.add(fromClass);
                @@ -277,7 +277,7 @@ public abstract class GraphicsConfigurationFactory {
                             }
                         }
                         types.addAll(Arrays.asList(fromClass.getInterfaces()));
                -                
                +
                         for(int i=0; i iface = types.get(i);
                             if( superClassOrInterface.isAssignableFrom(iface) && !resolvedInterfaces.contains(iface) ) {
                @@ -302,20 +302,20 @@ public abstract class GraphicsConfigurationFactory {
                         }
                     }
                 
                -    /** 
                +    /**
                      * Registers a GraphicsConfigurationFactory handling
                      * the given graphics device and capability class.
                      * 

                * This does not need to be called by end users, only implementors of new * GraphicsConfigurationFactory subclasses. *

                - * + * *

                * Note: Registered device types maybe classes or interfaces, where capabilities types are interfaces only. - *

                - * + *

                + * *

                See {@link #getFactory(Class, Class)} for a description of the find algorithm.

                - * + * * @param deviceType the minimum capabilities class type accepted, must implement or extend interface {@link AbstractGraphicsDevice} * @param capabilitiesType the minimum capabilities class type accepted, must extend interface {@link CapabilitiesImmutable} * @return the previous registered factory, or null if none @@ -329,7 +329,7 @@ public abstract class GraphicsConfigurationFactory { } if (!(defaultDeviceCapsType.capsType.isAssignableFrom(capabilitiesType))) { throw new IllegalArgumentException("Given capabilities class must implement CapabilitiesImmutable"); - } + } final DeviceCapsType dct = new DeviceCapsType(abstractGraphicsDeviceImplementor, capabilitiesType); final GraphicsConfigurationFactory prevFactory; if(null == factory) { @@ -352,7 +352,7 @@ public abstract class GraphicsConfigurationFactory { *

                Selects a graphics configuration on the specified graphics * device compatible with the supplied {@link Capabilities}. Some * platforms (e.g.: X11, EGL, KD) require the graphics configuration - * to be specified when the native window is created. + * to be specified when the native window is created. * These architectures have seperated their device, screen, window and drawable * context and hence are capable of quering the capabilities for each screen. * A fully established window is not required.

                @@ -360,7 +360,7 @@ public abstract class GraphicsConfigurationFactory { *

                Other platforms (e.g. Windows, MacOSX) don't offer the mentioned seperation * and hence need a fully established window and it's drawable. * Here the validation of the capabilities is performed later. - * In this case, the AbstractGraphicsConfiguration implementation + * In this case, the AbstractGraphicsConfiguration implementation * must allow an overwrite of the Capabilites, for example * {@link DefaultGraphicsConfiguration#setChosenCapabilities DefaultGraphicsConfiguration.setChosenCapabilities(..)}. *

                @@ -385,7 +385,7 @@ public abstract class GraphicsConfigurationFactory { * @param capsRequested the original requested capabilities * @param chooser the choosing implementation * @param screen the referring Screen - * @param nativeVisualID if not {@link VisualIDHolder#VID_UNDEFINED} it reflects a pre-chosen visualID of the native platform's windowing system. + * @param nativeVisualID if not {@link VisualIDHolder#VID_UNDEFINED} it reflects a pre-chosen visualID of the native platform's windowing system. * @return the complete GraphicsConfiguration * * @throws IllegalArgumentException if the data type of the passed diff --git a/src/nativewindow/classes/javax/media/nativewindow/MutableSurface.java b/src/nativewindow/classes/javax/media/nativewindow/MutableSurface.java index ff53c8109..a0db11ad9 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/MutableSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/MutableSurface.java @@ -31,12 +31,12 @@ package javax.media.nativewindow; /** * Provides a {@link NativeSurface} with a mutable surfaceHandle * via {@link #setSurfaceHandle(long)}. - * + * * @see NativeSurface */ public interface MutableSurface extends NativeSurface { - /** + /** * Sets the surface handle which is created outside of this implementation. */ public void setSurfaceHandle(long surfaceHandle); diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java index a89caec76..a755b1812 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package javax.media.nativewindow; /** Provides low-level information required for @@ -54,10 +54,10 @@ public interface NativeSurface extends SurfaceUpdatedListener { *

                * The surface handle shall be valid after a successfull call, * ie return a value other than {@link #LOCK_SURFACE_UNLOCKED} and {@link #LOCK_SURFACE_NOT_READY}, - * which is - *

                 
                -   *    boolean ok = LOCK_SURFACE_NOT_READY < lockSurface(); 
                -   * 
                + * which is + *
                +   *    boolean ok = LOCK_SURFACE_NOT_READY < lockSurface();
                +   * 
                *

                *

                * The caller may need to take care of the result {@link #LOCK_SURFACE_CHANGED}, @@ -71,7 +71,7 @@ public interface NativeSurface extends SurfaceUpdatedListener { * This call allows recursion from the same thread. *

                *

                - * The implementation may want to aquire the + * The implementation may want to aquire the * application level {@link com.jogamp.common.util.locks.RecursiveLock} * first before proceeding with a native surface lock. *

                @@ -115,7 +115,7 @@ public interface NativeSurface extends SurfaceUpdatedListener { *
                */ public boolean isSurfaceLockedByOtherThread(); - + /** * Return the locking owner's Thread, or null if not locked. */ @@ -123,15 +123,15 @@ public interface NativeSurface extends SurfaceUpdatedListener { /** * Provide a mechanism to utilize custom (pre-) swap surface - * code. This method is called before the render toolkit (e.g. JOGL) + * code. This method is called before the render toolkit (e.g. JOGL) * swaps the buffer/surface if double buffering is enabled. - *

                + *

                * The implementation may itself apply the swapping, * in which case true shall be returned. *

                * * @return true if this method completed swapping the surface, - * otherwise false, in which case eg the GLDrawable + * otherwise false, in which case eg the GLDrawable * implementation has to swap the code. */ public boolean surfaceSwap(); @@ -153,13 +153,13 @@ public interface NativeSurface extends SurfaceUpdatedListener { /** Remove the specified {@link SurfaceUpdatedListener} from the list. */ public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l); - + /** * Returns the handle to the surface for this NativeSurface.

                - * + * * The surface handle should be set/update by {@link #lockSurface()}, * where {@link #unlockSurface()} is not allowed to modify it. - * After {@link #unlockSurface()} it is no more guaranteed + * After {@link #unlockSurface()} it is no more guaranteed * that the surface handle is still valid. * * The surface handle shall reflect the platform one @@ -195,16 +195,16 @@ public interface NativeSurface extends SurfaceUpdatedListener { public AbstractGraphicsConfiguration getGraphicsConfiguration(); /** - * Convenience: Get display handle from + * Convenience: Get display handle from * AbstractGraphicsConfiguration . AbstractGraphicsScreen . AbstractGraphicsDevice */ public long getDisplayHandle(); /** - * Convenience: Get display handle from + * Convenience: Get display handle from * AbstractGraphicsConfiguration . AbstractGraphicsScreen */ public int getScreenIndex(); - + } diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowException.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowException.java index 593c1e7d6..0943c8c09 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowException.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowException.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 07d1008b4..bad72f355 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008-2009 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 @@ -90,13 +90,13 @@ public abstract class NativeWindowFactory { private static final String nativeWindowingTypePure; // canonical String via String.intern() private static final String nativeWindowingTypeCustom; // canonical String via String.intern() - + private static NativeWindowFactory defaultFactory; private static Map, NativeWindowFactory> registeredFactories; - + private static Class nativeWindowClass; private static boolean isAWTAvailable; - + private static final String JAWTUtilClassName = "jogamp.nativewindow.jawt.JAWTUtil" ; /** {@link jogamp.nativewindow.x11.X11Util} implements {@link ToolkitProperties}. */ private static final String X11UtilClassName = "jogamp.nativewindow.x11.X11Util"; @@ -104,16 +104,16 @@ public abstract class NativeWindowFactory { private static final String OSXUtilClassName = "jogamp.nativewindow.macosx.OSXUtil"; /** {@link jogamp.nativewindow.windows.GDIUtil} implements {@link ToolkitProperties}. */ private static final String GDIClassName = "jogamp.nativewindow.windows.GDIUtil"; - + private static ToolkitLock jawtUtilJAWTToolkitLock; - + private static boolean requiresToolkitLock; private static boolean desktopHasThreadingIssues; // Shutdown hook mechanism for the factory private static volatile boolean isJVMShuttingDown = false; private static final List customShutdownHooks = new ArrayList(); - + /** Creates a new NativeWindowFactory instance. End users do not need to call this method. */ protected NativeWindowFactory() { @@ -139,10 +139,10 @@ public abstract class NativeWindowFactory { case MACOS: return TYPE_MACOSX; case WINDOWS: - return TYPE_WINDOWS; + return TYPE_WINDOWS; case OPENKODE: return TYPE_EGL; - + case LINUX: case FREEBSD: case SUNOS: @@ -158,7 +158,7 @@ public abstract class NativeWindowFactory { static { final boolean[] _DEBUG = new boolean[] { false }; final String[] _tmp = new String[] { null }; - + AccessController.doPrivileged(new PrivilegedAction() { public Object run() { Platform.initSingleton(); // last resort .. @@ -168,16 +168,16 @@ public abstract class NativeWindowFactory { new Thread(new Runnable() { public void run() { NativeWindowFactory.shutdown(true); - } }, "NativeWindowFactory_ShutdownHook" ) ) ; + } }, "NativeWindowFactory_ShutdownHook" ) ) ; return null; } } ) ; - + DEBUG = _DEBUG[0]; if(DEBUG) { System.err.println(Thread.currentThread().getName()+" - Info: NativeWindowFactory."); // Thread.dumpStack(); } - + // Gather the windowing TK first nativeWindowingTypePure = _getNativeWindowingType(); if(null==_tmp[0] || _tmp[0].length()==0) { @@ -202,23 +202,23 @@ public abstract class NativeWindowFactory { } if( null != clazzName ) { ReflectionUtil.callStaticMethod(clazzName, "initSingleton", null, null, cl ); - + final Boolean res1 = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "requiresToolkitLock", null, null, cl); requiresToolkitLock = res1.booleanValue(); final Boolean res2 = (Boolean) ReflectionUtil.callStaticMethod(clazzName, "hasThreadingIssues", null, null, cl); desktopHasThreadingIssues = res2.booleanValue(); - } else { + } else { requiresToolkitLock = false; desktopHasThreadingIssues = false; } } - /** Returns true if the JVM is shutting down, otherwise false. */ + /** Returns true if the JVM is shutting down, otherwise false. */ public static final boolean isJVMShuttingDown() { return isJVMShuttingDown; } - - /** + + /** * Add a custom shutdown hook to be performed at JVM shutdown before shutting down NativeWindowFactory instance. - * + * * @param head if true add runnable at the start, otherwise at the end * @param runnable runnable to be added. */ @@ -234,7 +234,7 @@ public abstract class NativeWindowFactory { } } - /** + /** * Cleanup resources at JVM shutdown */ public static synchronized void shutdown(boolean _isJVMShuttingDown) { @@ -246,14 +246,14 @@ public abstract class NativeWindowFactory { final int cshCount = customShutdownHooks.size(); for(int i=0; i < cshCount; i++) { try { - if( DEBUG ) { + if( DEBUG ) { System.err.println("NativeWindowFactory.shutdown - customShutdownHook #"+(i+1)+"/"+cshCount); } customShutdownHooks.get(i).run(); } catch(Throwable t) { System.err.println("NativeWindowFactory.shutdown: Catched "+t.getClass().getName()+" during customShutdownHook #"+(i+1)+"/"+cshCount); - if( DEBUG ) { - t.printStackTrace(); + if( DEBUG ) { + t.printStackTrace(); } } } @@ -262,7 +262,7 @@ public abstract class NativeWindowFactory { if(DEBUG) { System.err.println("NativeWindowFactory.shutdown(): Post customShutdownHook"); } - + if(initialized) { initialized = false; if(null != registeredFactories) { @@ -271,14 +271,14 @@ public abstract class NativeWindowFactory { } GraphicsConfigurationFactory.shutdown(); } - + shutdownNativeImpl(NativeWindowFactory.class.getClassLoader()); // always re-shutdown // SharedResourceToolkitLock.shutdown(DEBUG); // not used yet if(DEBUG) { System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() END JVM Shutdown "+isJVMShuttingDown); } } - + private static void shutdownNativeImpl(final ClassLoader cl) { final String clazzName; if( TYPE_X11 == nativeWindowingTypePure ) { @@ -292,11 +292,11 @@ public abstract class NativeWindowFactory { } if( null != clazzName ) { ReflectionUtil.callStaticMethod(clazzName, "shutdown", null, null, cl ); - } + } } - + /** Returns true if {@link #initSingleton()} has been called w/o subsequent {@link #shutdown(boolean)}. */ - public static synchronized boolean isInitialized() { return initialized; } + public static synchronized boolean isInitialized() { return initialized; } /** * Static one time initialization of this factory.
                @@ -316,7 +316,7 @@ public abstract class NativeWindowFactory { if( Platform.AWT_AVAILABLE && ReflectionUtil.isClassAvailable("com.jogamp.nativewindow.awt.AWTGraphicsDevice", cl) ) { - + Method[] jawtUtilMethods = AccessController.doPrivileged(new PrivilegedAction() { public Method[] run() { try { @@ -327,7 +327,7 @@ public abstract class NativeWindowFactory { jawtUtilInitMethod.setAccessible(true); Method jawtUtilGetJAWTToolkitLockMethod = _jawtUtilClass.getDeclaredMethod("getJAWTToolkitLock", new Class[]{}); jawtUtilGetJAWTToolkitLockMethod.setAccessible(true); - return new Method[] { jawtUtilInitMethod, jawtUtilIsHeadlessMethod, jawtUtilGetJAWTToolkitLockMethod }; + return new Method[] { jawtUtilInitMethod, jawtUtilIsHeadlessMethod, jawtUtilGetJAWTToolkitLockMethod }; } catch (Exception e) { if(DEBUG) { e.printStackTrace(); @@ -340,7 +340,7 @@ public abstract class NativeWindowFactory { final Method jawtUtilInitMethod = jawtUtilMethods[0]; final Method jawtUtilIsHeadlessMethod = jawtUtilMethods[1]; final Method jawtUtilGetJAWTToolkitLockMethod = jawtUtilMethods[2]; - + ReflectionUtil.callMethod(null, jawtUtilInitMethod); Object resO = ReflectionUtil.callMethod(null, jawtUtilIsHeadlessMethod); @@ -351,21 +351,21 @@ public abstract class NativeWindowFactory { } else { throw new RuntimeException("JAWTUtil.isHeadlessMode() didn't return a Boolean"); } - resO = ReflectionUtil.callMethod(null, jawtUtilGetJAWTToolkitLockMethod); + resO = ReflectionUtil.callMethod(null, jawtUtilGetJAWTToolkitLockMethod); if(resO instanceof ToolkitLock) { jawtUtilJAWTToolkitLock = (ToolkitLock) resO; } else { throw new RuntimeException("JAWTUtil.getJAWTToolkitLock() didn't return a ToolkitLock"); - } + } } } - + // X11 initialization after possible AWT initialization // This is performed post AWT initialization, allowing AWT to complete the same, - // which may have been triggered before NativeWindow initialization. - // This way behavior is more uniforms across configurations (Applet/RCP, applications, ..). + // which may have been triggered before NativeWindow initialization. + // This way behavior is more uniforms across configurations (Applet/RCP, applications, ..). initSingletonNativeImpl(cl); - + registeredFactories = Collections.synchronizedMap(new HashMap, NativeWindowFactory>()); // register our default factory -> NativeWindow @@ -373,17 +373,17 @@ public abstract class NativeWindowFactory { nativeWindowClass = javax.media.nativewindow.NativeWindow.class; registerFactory(nativeWindowClass, factory); defaultFactory = factory; - + if ( isAWTAvailable ) { // register either our default factory or (if exist) the X11/AWT one -> AWT Component registerFactory(ReflectionUtil.getClass(ReflectionUtil.AWTNames.ComponentClass, false, cl), factory); } - + if(DEBUG) { System.err.println("NativeWindowFactory requiresToolkitLock "+requiresToolkitLock+", desktopHasThreadingIssues "+desktopHasThreadingIssues); System.err.println("NativeWindowFactory isAWTAvailable "+isAWTAvailable+", defaultFactory "+factory); } - + GraphicsConfigurationFactory.initSingleton(); } } @@ -392,20 +392,20 @@ public abstract class NativeWindowFactory { public static boolean requiresToolkitLock() { return requiresToolkitLock; } - + /** @return true if not headless, AWT Component and NativeWindow's AWT part available */ public static boolean isAWTAvailable() { return isAWTAvailable; } /** * @param useCustom if false return the native value, if true return a custom value if set, otherwise fallback to the native value. - * @return the native window type, e.g. {@link #TYPE_X11}, which is canonical via {@link String#intern()}. + * @return the native window type, e.g. {@link #TYPE_X11}, which is canonical via {@link String#intern()}. * Hence {@link String#equals(Object)} and == produce the same result. */ public static String getNativeWindowType(boolean useCustom) { return useCustom?nativeWindowingTypeCustom:nativeWindowingTypePure; } - /** Don't know if we shall add this factory here .. + /** Don't know if we shall add this factory here .. public static AbstractGraphicsDevice createGraphicsDevice(String type, String connection, int unitID, long handle, ToolkitLock locker) { if(TYPE_EGL == type) { return new @@ -427,13 +427,13 @@ public abstract class NativeWindowFactory { return defaultFactory; } - /** + /** * Returns the AWT {@link ToolkitLock} (JAWT based) if {@link #isAWTAvailable}, otherwise null. *

                * The JAWT based {@link ToolkitLock} also locks the global lock, * which matters if the latter is required. - *

                - */ + *

                + */ public static ToolkitLock getAWTToolkitLock() { return jawtUtilJAWTToolkitLock; } @@ -441,7 +441,7 @@ public abstract class NativeWindowFactory { public static ToolkitLock getNullToolkitLock() { return NativeWindowFactoryImpl.getNullToolkitLock(); } - + /** * Provides the system default {@link ToolkitLock} for the default system windowing type. * @see #getNativeWindowType(boolean) @@ -486,7 +486,7 @@ public abstract class NativeWindowFactory { } return NativeWindowFactoryImpl.getNullToolkitLock(); } - + /** * @param device * @param screen -1 is default screen of the given device, e.g. maybe 0 or determined by native API. >= 0 is specific screen @@ -510,7 +510,7 @@ public abstract class NativeWindowFactory { } return new DefaultGraphicsScreen(device, screen); } - + /** Returns the appropriate NativeWindowFactory to handle window objects of the given type. The windowClass might be {@link NativeWindow NativeWindow}, in which case the client has @@ -543,7 +543,7 @@ public abstract class NativeWindowFactory { } /** Converts the given window object and it's - {@link AbstractGraphicsConfiguration AbstractGraphicsConfiguration} into a + {@link AbstractGraphicsConfiguration AbstractGraphicsConfiguration} into a {@link NativeWindow NativeWindow} which can be operated upon by a custom toolkit, e.g. {@link javax.media.opengl.GLDrawableFactory javax.media.opengl.GLDrawableFactory}.
                The object may be a component for a particular window toolkit, such as an AWT @@ -554,7 +554,7 @@ public abstract class NativeWindowFactory { NativeWindowFactory is responsible for handling objects from a particular window toolkit. The built-in NativeWindowFactory handles NativeWindow instances as well as AWT Components.
                - + @throws IllegalArgumentException if the given window object could not be handled by any of the registered NativeWindowFactory instances @@ -573,22 +573,22 @@ public abstract class NativeWindowFactory { NativeWindow. Implementors of concrete NativeWindowFactory subclasses should override this method. */ protected abstract NativeWindow getNativeWindowImpl(Object winObj, AbstractGraphicsConfiguration config) throws IllegalArgumentException; - + /** * Returns the {@link OffscreenLayerSurface} instance of this {@link NativeSurface}. *

                - * In case this surface is a {@link NativeWindow}, we traverse from the given surface + * In case this surface is a {@link NativeWindow}, we traverse from the given surface * up to root until an implementation of {@link OffscreenLayerSurface} is found. * In case ifEnabled is true, the surface must also implement {@link OffscreenLayerOption} - * where {@link OffscreenLayerOption#isOffscreenLayerSurfaceEnabled()} is true. + * where {@link OffscreenLayerOption#isOffscreenLayerSurfaceEnabled()} is true. *

                - * + * * @param surface The surface to query. - * @param ifEnabled If true, only return the enabled {@link OffscreenLayerSurface}, see {@link OffscreenLayerOption#isOffscreenLayerSurfaceEnabled()}. + * @param ifEnabled If true, only return the enabled {@link OffscreenLayerSurface}, see {@link OffscreenLayerOption#isOffscreenLayerSurfaceEnabled()}. * @return */ public static OffscreenLayerSurface getOffscreenLayerSurface(NativeSurface surface, boolean ifEnabled) { - if(surface instanceof OffscreenLayerSurface && + if(surface instanceof OffscreenLayerSurface && ( !ifEnabled || surface instanceof OffscreenLayerOption ) ) { final OffscreenLayerSurface ols = (OffscreenLayerSurface) surface; return ( !ifEnabled || ((OffscreenLayerOption)ols).isOffscreenLayerSurfaceEnabled() ) ? ols : null; @@ -601,12 +601,12 @@ public abstract class NativeWindowFactory { final OffscreenLayerSurface ols = (OffscreenLayerSurface) nw; return ( !ifEnabled || ((OffscreenLayerOption)ols).isOffscreenLayerSurfaceEnabled() ) ? ols : null; } - nw = nw.getParent(); + nw = nw.getParent(); } } - return null; + return null; } - + /** * Returns true if the given visualID is valid for further processing, i.e. OpenGL usage, * otherwise return false. @@ -619,8 +619,8 @@ public abstract class NativeWindowFactory { *

                */ public static boolean isNativeVisualIDValidForProcessing(int visualID) { - return NativeWindowFactory.TYPE_X11 != NativeWindowFactory.getNativeWindowType(false) || + return NativeWindowFactory.TYPE_X11 != NativeWindowFactory.getNativeWindowType(false) || VisualIDHolder.VID_UNDEFINED != visualID ; } - + } diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerOption.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerOption.java index 12d30b3cd..11496899a 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerOption.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerOption.java @@ -32,30 +32,30 @@ package javax.media.nativewindow; * within the implementation. */ public interface OffscreenLayerOption { - /** + /** * Request an offscreen layer, if supported. *

                * Shall be called before the first {@link NativeWindow#lockSurface()}, * and hence before realization. *

                - * + * * @see #getShallUseOffscreenLayer() - * @see #isOffscreenLayerSurfaceEnabled() + * @see #isOffscreenLayerSurfaceEnabled() */ public void setShallUseOffscreenLayer(boolean v); /** Returns the property set by {@link #setShallUseOffscreenLayer(boolean)}. */ public boolean getShallUseOffscreenLayer(); - /** + /** * Returns true if this instance uses an offscreen layer, otherwise false. *

                * This instance is an offscreen layer, if {@link #setShallUseOffscreenLayer(boolean) setShallUseOffscreenLayer(true)} * has been called before it's realization and first lock and the underlying implementation supports it. *

                * The return value is undefined before issuing the first {@link NativeWindow#lockSurface()}. - * - * @see #setShallUseOffscreenLayer(boolean) + * + * @see #setShallUseOffscreenLayer(boolean) */ public boolean isOffscreenLayerSurfaceEnabled(); } \ No newline at end of file diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index 1826008ad..8681422ef 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -33,36 +33,36 @@ import com.jogamp.common.util.locks.RecursiveLock; * Interface specifying the offscreen layer surface protocol. */ public interface OffscreenLayerSurface { - /** + /** * Attach the offscreen layer to this offscreen layer surface. *

                * Implementation may realize all required resources at this point. *

                - * + * * @see #isOffscreenLayerSurfaceEnabled() * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false */ public void attachSurfaceLayer(final long layerHandle) throws NativeWindowException; - - /** + + /** * Detaches a previously attached offscreen layer from this offscreen layer surface. * @see #attachSurfaceLayer(long) * @see #isOffscreenLayerSurfaceEnabled() - * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false + * @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false * or no surface layer is attached. */ public void detachSurfaceLayer() throws NativeWindowException; - + /** Returns the attached surface layer or null if none is attached. */ public long getAttachedSurfaceLayer(); - + /** Returns true if a surface layer is attached, otherwise false. */ public boolean isSurfaceLayerAttached(); - + /** Sets the capabilities of this instance, allowing upstream API's to refine it, i.e. OpenGL related settings. */ public void setChosenCapabilities(CapabilitiesImmutable caps); - - /** Returns the recursive lock object of this surface, which synchronizes multithreaded access. */ + + /** Returns the recursive lock object of this surface, which synchronizes multithreaded access. */ public RecursiveLock getLock(); - + } diff --git a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java index 15a8738c5..eb0a6cf04 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java @@ -33,44 +33,44 @@ import jogamp.nativewindow.Debug; /** * Provides a mutable {@link NativeSurface}, i.e. {@link MutableSurface}, while allowing an * {@link UpstreamSurfaceHook} to influence the lifecycle and information. - * + * * @see UpstreamSurfaceHook * @see MutableSurface * @see NativeSurface */ -public interface ProxySurface extends MutableSurface { +public interface ProxySurface extends MutableSurface { public static final boolean DEBUG = Debug.debug("ProxySurface"); - - /** + + /** * Implementation specific bit-value stating this {@link ProxySurface} owns the upstream's surface handle * @see #addUpstreamOptionBits(int) * @see #clearUpstreamOptionBits(int) * @see #getUpstreamOptionBits() - */ + */ public static final int OPT_PROXY_OWNS_UPSTREAM_SURFACE = 1 << 6; - - /** + + /** * Implementation specific bit-value stating this {@link ProxySurface} owns the upstream's {@link AbstractGraphicsDevice}. * @see #addUpstreamOptionBits(int) * @see #clearUpstreamOptionBits(int) * @see #getUpstreamOptionBits() - */ + */ public static final int OPT_PROXY_OWNS_UPSTREAM_DEVICE = 1 << 7; - - /** + + /** * Implementation specific bitvalue stating the upstream's {@link NativeSurface} is an invisible window, i.e. maybe incomplete. * @see #addUpstreamOptionBits(int) * @see #clearUpstreamOptionBits(int) * @see #getUpstreamOptionBits() - */ + */ public static final int OPT_UPSTREAM_WINDOW_INVISIBLE = 1 << 8; /** Allow redefining the AbstractGraphicsConfiguration */ - public void setGraphicsConfiguration(AbstractGraphicsConfiguration cfg); + public void setGraphicsConfiguration(AbstractGraphicsConfiguration cfg); /** * Return the upstream {@link NativeSurface} if used, otherwise null. - *

                + *

                * An upstream {@link NativeSurface} may backup this {@link ProxySurface} instance's representation, * e.g. via a {@link #setUpstreamSurfaceHook(UpstreamSurfaceHook) set} {@link UpstreamSurfaceHook}. *

                @@ -80,47 +80,47 @@ public interface ProxySurface extends MutableSurface { *

                */ public NativeSurface getUpstreamSurface(); - + /** Returns the {@link UpstreamSurfaceHook} if {@link #setUpstreamSurfaceHook(UpstreamSurfaceHook) set}, otherwise null. */ public UpstreamSurfaceHook getUpstreamSurfaceHook(); - + /** * Sets the {@link UpstreamSurfaceHook} and returns the previous value. */ public void setUpstreamSurfaceHook(UpstreamSurfaceHook hook); - - /** - * Enables or disables the {@link UpstreamSurfaceHook} lifecycle functions + + /** + * Enables or disables the {@link UpstreamSurfaceHook} lifecycle functions * {@link UpstreamSurfaceHook#create(ProxySurface)} and {@link UpstreamSurfaceHook#destroy(ProxySurface)}. *

                * Use this for small code blocks where the native resources shall not change, * i.e. resizing a derived (OpenGL) drawable. - *

                + *

                */ public void enableUpstreamSurfaceHookLifecycle(boolean enable); - - /** + + /** * {@link UpstreamSurfaceHook#create(ProxySurface)} is being issued and the proxy surface/window handles shall be set. - */ + */ public void createNotify(); - - /** + + /** * {@link UpstreamSurfaceHook#destroy(ProxySurface)} is being issued and all proxy surface/window handles shall be cleared. - */ + */ public void destroyNotify(); - + public StringBuilder getUpstreamOptionBits(StringBuilder sink); public int getUpstreamOptionBits(); - + /** Returns true if the give bit-mask v is set in this instance upstream-option-bits, otherwise false.*/ public boolean containsUpstreamOptionBits(int v); - + /** Add the given bit-mask to this instance upstream-option-bits using bit-or w/ v.*/ public void addUpstreamOptionBits(int v); - + /** Clear the given bit-mask from this instance upstream-option-bits using bit-and w/ ~v*/ public void clearUpstreamOptionBits(int v); - + public StringBuilder toString(StringBuilder sink); public String toString(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/SurfaceUpdatedListener.java b/src/nativewindow/classes/javax/media/nativewindow/SurfaceUpdatedListener.java index 0912b5afe..de65a3031 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/SurfaceUpdatedListener.java +++ b/src/nativewindow/classes/javax/media/nativewindow/SurfaceUpdatedListener.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package javax.media.nativewindow; diff --git a/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java b/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java index eccfcfa4f..017b996d7 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java @@ -53,26 +53,26 @@ public interface ToolkitLock { * @throws RuntimeException in case of a timeout */ public void lock(); - + /** * Release the lock. * * @throws RuntimeException in case the lock is not acquired by this thread. */ public void unlock(); - + /** - * @throws RuntimeException if current thread does not hold the lock + * @throws RuntimeException if current thread does not hold the lock */ public void validateLocked() throws RuntimeException; - - /** + + /** * Dispose this instance. - *

                + *

                * Shall be called when instance is no more required. *

                * This allows implementations sharing a lock via resources - * to decrease the reference counter. + * to decrease the reference counter. */ public void dispose(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/UpstreamSurfaceHook.java b/src/nativewindow/classes/javax/media/nativewindow/UpstreamSurfaceHook.java index 6fe2e5364..f08a6c938 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/UpstreamSurfaceHook.java +++ b/src/nativewindow/classes/javax/media/nativewindow/UpstreamSurfaceHook.java @@ -28,24 +28,24 @@ package javax.media.nativewindow; -/** - * Interface allowing upstream caller to pass lifecycle actions and size info - * to a {@link ProxySurface} instance. - */ +/** + * Interface allowing upstream caller to pass lifecycle actions and size info + * to a {@link ProxySurface} instance. + */ public interface UpstreamSurfaceHook { /** called within {@link ProxySurface#createNotify()} within lock, before using surface. */ public void create(ProxySurface s); /** called within {@link ProxySurface#destroyNotify()} within lock, before clearing fields. */ public void destroy(ProxySurface s); - /** Returns the width of the upstream surface, used if {@link ProxySurface#UPSTREAM_PROVIDES_SIZE} is set. */ + /** Returns the width of the upstream surface, used if {@link ProxySurface#UPSTREAM_PROVIDES_SIZE} is set. */ public int getWidth(ProxySurface s); - /** Returns the height of the upstream surface, used if {@link ProxySurface#UPSTREAM_PROVIDES_SIZE} is set. */ + /** Returns the height of the upstream surface, used if {@link ProxySurface#UPSTREAM_PROVIDES_SIZE} is set. */ public int getHeight(ProxySurface s); - + /** - * {@link UpstreamSurfaceHook} w/ mutable size, allowing it's {@link ProxySurface} user to resize. - */ + * {@link UpstreamSurfaceHook} w/ mutable size, allowing it's {@link ProxySurface} user to resize. + */ public interface MutableSize extends UpstreamSurfaceHook { public void setSize(int width, int height); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java b/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java index 4f3d3ff00..4ee71ee79 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java +++ b/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java @@ -38,7 +38,7 @@ import java.util.Comparator; *

                */ public interface VisualIDHolder { - + public enum VIDType { // Generic Values INTRINSIC(0), NATIVE(1), @@ -47,19 +47,19 @@ public interface VisualIDHolder { // X11 Values X11_XVISUAL(20), X11_FBCONFIG(21), // Windows Values - WIN32_PFD(30); - + WIN32_PFD(30); + public final int id; VIDType(int id){ this.id = id; } - } - + } + /** * Returns the native visual ID of the given type * if supported, or {@link #VID_UNDEFINED} if not supported. - *

                + *

                * Depending on the native windowing system, type is handled as follows: *

                  *
                • X11 throws NativeWindowException on EGL_CONFIG, WIN32_PFD @@ -76,7 +76,7 @@ public interface VisualIDHolder { *
                • X11_XVISUAL: X11 XVisual ID
                • *
                • X11_FBCONFIG: X11 FBConfig ID or VID_UNDEFINED
                • *
                - *
              • Windows/GL throws NativeWindowException on EGL_CONFIG, X11_XVISUAL, X11_FBCONFIG + *
              • Windows/GL throws NativeWindowException on EGL_CONFIG, X11_XVISUAL, X11_FBCONFIG *
                  *
                • INTRINSIC: Win32 PIXELFORMATDESCRIPTOR ID
                • *
                • NATIVE: Win32 PIXELFORMATDESCRIPTOR ID
                • @@ -91,35 +91,35 @@ public interface VisualIDHolder { *
                *

                * Note: INTRINSIC and NATIVE are always handled, - * but may result in {@link #VID_UNDEFINED}. The latter is true if - * the native value are actually undefined or the corresponding object is not + * but may result in {@link #VID_UNDEFINED}. The latter is true if + * the native value are actually undefined or the corresponding object is not * mapped to a native visual object. - * + * * @throws NativeWindowException if type is neither * INTRINSIC nor NATIVE - * and does not match the native implementation. + * and does not match the native implementation. */ int getVisualID(VIDType type) throws NativeWindowException ; - - /** + + /** * {@link #getVisualID(VIDType)} result indicating an undefined value, * which could be cause by an unsupported query. *

                * We assume the const value 0 doesn't reflect a valid native visual ID * and is interpreted as no value on all platforms. * This is currently true for Android, X11 and Windows. - *

                + *

                */ static final int VID_UNDEFINED = 0; - + /** Comparing {@link VIDType#NATIVE} */ public static class VIDComparator implements Comparator { private VIDType type; - + public VIDComparator(VIDType type) { this.type = type; } - + public int compare(VisualIDHolder vid1, VisualIDHolder vid2) { final int id1 = vid1.getVisualID(type); final int id2 = vid2.getVisualID(type); @@ -131,5 +131,5 @@ public interface VisualIDHolder { } return 0; } - } + } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java b/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java index 02f68f442..8570b78da 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java +++ b/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java @@ -37,7 +37,7 @@ package javax.media.nativewindow; * this protocol default behavior {@link WindowClosingMode#DISPOSE_ON_CLOSE DISPOSE_ON_CLOSE} shall be used.

                */ public interface WindowClosingProtocol { - + /** * Window closing mode if triggered by toolkit close operation. */ @@ -47,7 +47,7 @@ public interface WindowClosingProtocol { * This is the default behavior within an AWT environment. */ DO_NOTHING_ON_CLOSE, - + /** * Dispose resources on native window close operation.
                * This is the default behavior in case no underlying toolkit defines otherwise. diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java index 17b4930c5..b8b48a46c 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java @@ -4,14 +4,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -21,12 +21,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package javax.media.nativewindow.util; public class Dimension implements Cloneable, DimensionImmutable { @@ -48,7 +48,7 @@ public class Dimension implements Cloneable, DimensionImmutable { public Object cloneMutable() { return clone(); } - + public Object clone() { try { return super.clone(); @@ -92,7 +92,7 @@ public class Dimension implements Cloneable, DimensionImmutable { public int compareTo(final DimensionImmutable d) { final int tsq = width*height; final int xsq = d.getWidth()*d.getHeight(); - + if(tsq > xsq) { return 1; } else if(tsq < xsq) { @@ -100,13 +100,13 @@ public class Dimension implements Cloneable, DimensionImmutable { } return 0; } - + @Override public boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof Dimension) { Dimension p = (Dimension)obj; - return height == p.height && + return height == p.height && width == p.width ; } return false; diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java index 22bd3f48b..9caa433a6 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java @@ -46,12 +46,12 @@ public interface DimensionImmutable extends WriteCloneable, Comparable * Compares square of size. - *

                + *

                * {@inheritDoc} */ @Override public int compareTo(final DimensionImmutable d); - + /** * Checks whether two dimensions objects are equal. Two instances * of DimensionReadOnly are equal if two components diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java index 942c12c2b..dbd997c60 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,18 +20,18 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package javax.media.nativewindow.util; public class Insets implements Cloneable, InsetsImmutable { static final InsetsImmutable zeroInsets = new Insets(); public static final InsetsImmutable getZero() { return zeroInsets; } - + int l, r, t, b; public Insets() { @@ -44,11 +44,11 @@ public class Insets implements Cloneable, InsetsImmutable { this.t=top; this.b=bottom; } - + public Object cloneMutable() { return clone(); } - + protected Object clone() { try { return super.clone(); @@ -77,7 +77,7 @@ public class Insets implements Cloneable, InsetsImmutable { public final void setRightWidth(int right) { r = right; } public final void setTopHeight(int top) { t = top; } public final void setBottomHeight(int bottom) { b = bottom; } - + @Override public boolean equals(Object obj) { if(this == obj) { return true; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java index 075641ede..0f99a7861 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java @@ -41,13 +41,13 @@ public interface InsetsImmutable extends WriteCloneable { /** @return total width, ie. left_width + right_width */ int getTotalWidth(); - + /** @return top inset height */ int getTopHeight(); /** @return bottom inset height */ int getBottomHeight(); - + /** @return total height, ie. top_height + bottom_height */ int getTotalHeight(); diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java index 4c233bb16..aba515d52 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java @@ -45,7 +45,7 @@ public class Point implements Cloneable, PointImmutable { public Object cloneMutable() { return clone(); } - + public Object clone() { try { return super.clone(); @@ -58,7 +58,7 @@ public class Point implements Cloneable, PointImmutable { public int compareTo(final PointImmutable d) { final int sq = x*y; final int xsq = d.getX()*d.getY(); - + if(sq > xsq) { return 1; } else if(sq < xsq) { @@ -66,7 +66,7 @@ public class Point implements Cloneable, PointImmutable { } return 0; } - + @Override public boolean equals(Object obj) { if(this == obj) { return true; } @@ -120,5 +120,5 @@ public class Point implements Cloneable, PointImmutable { y *= sy ; return this; } - + } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java index b00329bb5..f5377e059 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java @@ -41,12 +41,12 @@ public interface PointImmutable extends WriteCloneable, Comparable * Compares the square of the position. - *

                + *

                * {@inheritDoc} */ @Override public int compareTo(final PointImmutable d); - + /** * Checks whether two points objects are equal. Two instances * of PointReadOnly are equal if the two components @@ -57,5 +57,5 @@ public interface PointImmutable extends WriteCloneable, Comparable xsq) { return 1; } else if(sq < xsq) { @@ -160,7 +160,7 @@ public class Rectangle implements Cloneable, RectangleImmutable { { final int sq = x*y; final int xsq = d.getX()*d.getY(); - + if(sq > xsq) { return 1; } else if(sq < xsq) { @@ -169,7 +169,7 @@ public class Rectangle implements Cloneable, RectangleImmutable { } return 0; } - + @Override public boolean equals(Object obj) { if(this == obj) { return true; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java index 440d9e000..ce735f53f 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java @@ -49,7 +49,7 @@ public interface RectangleImmutable extends WriteCloneable, Comparable0.0 and 1.0. *

                * Coverage is computed by: @@ -57,19 +57,19 @@ public interface RectangleImmutable extends WriteCloneable, Comparable - *

                + *

                */ float coverage(RectangleImmutable r); - + /** *

                * Compares square of size 1st, if equal the square of position. - *

                + *

                * {@inheritDoc} */ @Override public int compareTo(final RectangleImmutable d); - + /** * Checks whether two rect objects are equal. Two instances * of Rectangle are equal if the four integer values diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java index 3084816a5..917f7e230 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java @@ -4,14 +4,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -21,15 +21,15 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package javax.media.nativewindow.util; -/** +/** * Immutable SurfaceSize Class, consisting of it's read only components:
                *
                  *
                • {@link javax.media.nativewindow.util.DimensionImmutable} size in pixels
                • @@ -63,7 +63,7 @@ public class SurfaceSize implements Comparable { /** *

                  * Compares {@link DimensionImmutable#compareTo(DimensionImmutable) resolution} 1st, if equal the bitsPerPixel. - *

                  + *

                  * {@inheritDoc} */ @Override @@ -72,7 +72,7 @@ public class SurfaceSize implements Comparable { if( 0 != rres ) { return rres; } - final int xbpp = ssz.getBitsPerPixel(); + final int xbpp = ssz.getBitsPerPixel(); if(bitsPerPixel > xbpp) { return 1; } else if(bitsPerPixel < xbpp) { @@ -80,7 +80,7 @@ public class SurfaceSize implements Comparable { } return 0; } - + /** * Checks whether two size objects are equal. Two instances * of SurfaceSize are equal if the two components diff --git a/src/nativewindow/classes/jogamp/nativewindow/Debug.java b/src/nativewindow/classes/jogamp/nativewindow/Debug.java index c5e316364..a7bf536ec 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/Debug.java +++ b/src/nativewindow/classes/jogamp/nativewindow/Debug.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -51,7 +51,7 @@ public class Debug extends PropertyAccess { // Some common properties private static final boolean verbose; private static final boolean debugAll; - + static { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { diff --git a/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java index 52e9c8308..b3b5d2131 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2009 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 diff --git a/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java index c9f830811..5fdbbf697 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java @@ -36,20 +36,20 @@ import com.jogamp.common.util.locks.RecursiveLock; /** * Implementing a global recursive {@link javax.media.nativewindow.ToolkitLock}. *

                  - * This is the last resort for unstable driver where multiple X11 display connections + * This is the last resort for unstable driver where multiple X11 display connections * to the same connection name are not treated thread safe within the GL/X11 driver. *

                  */ public class GlobalToolkitLock implements ToolkitLock { private static final RecursiveLock globalLock = LockFactory.createRecursiveLock(); private static GlobalToolkitLock singleton = new GlobalToolkitLock(); - + public static final GlobalToolkitLock getSingleton() { return singleton; } - + private GlobalToolkitLock() { } - + @Override public final void lock() { globalLock.lock(); @@ -61,17 +61,17 @@ public class GlobalToolkitLock implements ToolkitLock { if(TRACE_LOCK) { System.err.println("GlobalToolkitLock.unlock()"); } globalLock.unlock(); // implicit lock validation } - + @Override public final void validateLocked() throws RuntimeException { globalLock.validateLocked(); } - + @Override public final void dispose() { // nop } - + public String toString() { return "GlobalToolkitLock[obj 0x"+Integer.toHexString(hashCode())+", isOwner "+globalLock.isOwner(Thread.currentThread())+", "+globalLock.toString()+"]"; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java index 1a106b1b9..36a25acfb 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.nativewindow; @@ -36,7 +36,7 @@ import com.jogamp.common.jvm.JNILibLoaderBase; import com.jogamp.common.os.Platform; import com.jogamp.common.util.cache.TempJarCache; -public class NWJNILibLoader extends JNILibLoaderBase { +public class NWJNILibLoader extends JNILibLoaderBase { public static boolean loadNativeWindow(final String ossuffix) { return AccessController.doPrivileged(new PrivilegedAction() { public Boolean run() { diff --git a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java index a3a66b7f1..e3f6ab5ca 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 @@ -48,7 +48,7 @@ public class NativeWindowFactoryImpl extends NativeWindowFactory { public static ToolkitLock getNullToolkitLock() { return nullToolkitLock; } - + // This subclass of NativeWindowFactory handles the case of // NativeWindows being passed in protected NativeWindow getNativeWindowImpl(Object winObj, AbstractGraphicsConfiguration config) throws IllegalArgumentException { @@ -69,7 +69,7 @@ public class NativeWindowFactoryImpl extends NativeWindowFactory { winObj.getClass().getName() + " is unsupported; expected " + "javax.media.nativewindow.NativeWindow or "+AWTNames.ComponentClass); } - + private Constructor nativeWindowConstructor = null; private NativeWindow getAWTNativeWindow(Object winObj, AbstractGraphicsConfiguration config) { @@ -93,7 +93,7 @@ public class NativeWindowFactoryImpl extends NativeWindowFactory { } nativeWindowConstructor = ReflectionUtil.getConstructor( - windowClassName, new Class[] { Object.class, AbstractGraphicsConfiguration.class }, + windowClassName, new Class[] { Object.class, AbstractGraphicsConfiguration.class }, getClass().getClassLoader()); } catch (Exception e) { throw new IllegalArgumentException(e); diff --git a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java index 5fc5fe376..d8ce98acb 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java @@ -38,7 +38,7 @@ import javax.media.nativewindow.ToolkitLock; public class NullToolkitLock implements ToolkitLock { /** Singleton via {@link NativeWindowFactoryImpl#getNullToolkitLock()} */ protected NullToolkitLock() { } - + @Override public final void lock() { if(TRACE_LOCK) { @@ -51,21 +51,21 @@ public class NullToolkitLock implements ToolkitLock { public final void unlock() { if(TRACE_LOCK) { System.err.println("NullToolkitLock.unlock()"); } } - + @Override public final void validateLocked() throws RuntimeException { if( NativeWindowFactory.requiresToolkitLock() ) { throw new RuntimeException("NullToolkitLock does not lock, but locking is required."); } } - + @Override public final void dispose() { // nop } - + public String toString() { return "NullToolkitLock[]"; } - + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java index 56e342793..8a1048c6f 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java @@ -40,7 +40,7 @@ import javax.media.nativewindow.UpstreamSurfaceHook; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; -public abstract class ProxySurfaceImpl implements ProxySurface { +public abstract class ProxySurfaceImpl implements ProxySurface { private final SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); private AbstractGraphicsConfiguration config; // control access due to delegation private UpstreamSurfaceHook upstream; @@ -70,15 +70,15 @@ public abstract class ProxySurfaceImpl implements ProxySurface { this.upstreamSurfaceHookLifecycleEnabled = true; if(ownsDevice) { addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); - } + } } @Override public NativeSurface getUpstreamSurface() { return null; } - + @Override public final UpstreamSurfaceHook getUpstreamSurfaceHook() { return upstream; } - + @Override public void setUpstreamSurfaceHook(UpstreamSurfaceHook hook) { if(null == hook) { @@ -86,14 +86,14 @@ public abstract class ProxySurfaceImpl implements ProxySurface { } upstream = hook; } - + @Override public final void enableUpstreamSurfaceHookLifecycle(boolean enable) { upstreamSurfaceHookLifecycleEnabled = enable; } - + @Override - public void createNotify() { + public void createNotify() { if(upstreamSurfaceHookLifecycleEnabled) { upstream.create(this); } @@ -113,15 +113,15 @@ public abstract class ProxySurfaceImpl implements ProxySurface { } this.surfaceHandle_old = 0; } - - /** + + /** * Must be overridden by implementations allowing having a {@link UpstreamSurfaceHook} being passed. - * @see #destroyNotify() + * @see #destroyNotify() */ protected void invalidateImpl() { - throw new InternalError("UpstreamSurfaceHook given, but required method not implemented."); + throw new InternalError("UpstreamSurfaceHook given, but required method not implemented."); } - + protected final AbstractGraphicsConfiguration getPrivateGraphicsConfiguration() { return config; } @@ -140,7 +140,7 @@ public abstract class ProxySurfaceImpl implements ProxySurface { public final void setGraphicsConfiguration(AbstractGraphicsConfiguration cfg) { config = cfg; } - + @Override public final int getScreenIndex() { return getGraphicsConfiguration().getScreen().getIndex(); @@ -151,7 +151,7 @@ public abstract class ProxySurfaceImpl implements ProxySurface { @Override public abstract void setSurfaceHandle(long surfaceHandle); - + @Override public final int getWidth() { return upstream.getWidth(this); @@ -252,7 +252,7 @@ public abstract class ProxySurfaceImpl implements ProxySurface { public final Thread getSurfaceLockOwner() { return surfaceLock.getOwner(); } - + public final StringBuilder getUpstreamOptionBits(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); @@ -284,21 +284,21 @@ public abstract class ProxySurfaceImpl implements ProxySurface { sink.append(" ]"); return sink; } - + @Override public final int getUpstreamOptionBits() { return implBitfield; } - + @Override public final boolean containsUpstreamOptionBits(int v) { return v == ( implBitfield & v ) ; } - + @Override public final void addUpstreamOptionBits(int v) { implBitfield |= v; } - + @Override public final void clearUpstreamOptionBits(int v) { implBitfield &= ~v; } - + @Override public StringBuilder toString(StringBuilder sink) { if(null == sink) { @@ -315,7 +315,7 @@ public abstract class ProxySurfaceImpl implements ProxySurface { // append("\n, upstreamSurface "+getUpstreamSurface()); return sink; } - + @Override public String toString() { StringBuilder msg = new StringBuilder(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java index 5b79de0b8..51dd58543 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java @@ -50,7 +50,7 @@ public class ResourceToolkitLock implements ToolkitLock { private ResourceToolkitLock() { this.lock = LockFactory.createRecursiveLock(); } - + @Override public final void lock() { lock.lock(); @@ -62,17 +62,17 @@ public class ResourceToolkitLock implements ToolkitLock { if(TRACE_LOCK) { System.err.println("ResourceToolkitLock.unlock()"); } lock.unlock(); // implicit lock validation } - + @Override public final void validateLocked() throws RuntimeException { lock.validateLocked(); } - + @Override public final void dispose() { // nop } - + public String toString() { return "ResourceToolkitLock[obj 0x"+Integer.toHexString(hashCode())+", isOwner "+lock.isOwner(Thread.currentThread())+", "+lock.toString()+"]"; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java index 94d12e6fc..e20d3d138 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java @@ -54,8 +54,8 @@ public class SharedResourceToolkitLock implements ToolkitLock { handle2Lock = new LongObjectHashMap(); handle2Lock.setKeyNotFoundValue(null); } - - /** + + /** * @return number of unclosed EGL Displays.
                  */ public static int shutdown(boolean verbose) { @@ -70,7 +70,7 @@ public class SharedResourceToolkitLock implements ToolkitLock { } return handle2Lock.size(); } - + public static void dumpOpenDisplayConnections() { System.err.println("SharedResourceToolkitLock: Open ResourceToolkitLock's: "+handle2Lock.size()); int i=0; @@ -79,7 +79,7 @@ public class SharedResourceToolkitLock implements ToolkitLock { System.err.println("SharedResourceToolkitLock: Open["+i+"]: "+e.value); } } - + public static final SharedResourceToolkitLock get(long handle) { SharedResourceToolkitLock res; synchronized(handle2Lock) { @@ -106,8 +106,8 @@ public class SharedResourceToolkitLock implements ToolkitLock { this.handle = handle; this.refCount = 0; } - - + + @Override public final void lock() { lock.lock(); @@ -119,12 +119,12 @@ public class SharedResourceToolkitLock implements ToolkitLock { if(TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.unlock()"); } lock.unlock(); } - + @Override public final void validateLocked() throws RuntimeException { lock.validateLocked(); } - + @Override public final void dispose() { if(0 < refCount) { // volatile OK @@ -141,7 +141,7 @@ public class SharedResourceToolkitLock implements ToolkitLock { if(DEBUG || TRACE_LOCK) { System.err.println("SharedResourceToolkitLock.dispose() * NULL *: "+this); } } } - + public String toString() { return "SharedResourceToolkitLock[refCount "+refCount+", handle 0x"+Long.toHexString(handle)+", obj 0x"+Integer.toHexString(hashCode())+", isOwner "+lock.isOwner(Thread.currentThread())+", "+lock.toString()+"]"; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java b/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java index 4f68c6945..d11e240fa 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java +++ b/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -39,27 +39,27 @@ public class SurfaceUpdatedHelper implements SurfaceUpdatedListener { // // Management Utils - // + // public int size() { return surfaceUpdatedListeners.size(); } public SurfaceUpdatedListener get(int i) { return surfaceUpdatedListeners.get(i); } - + // // Implementation of NativeSurface SurfaceUpdatedListener methods - // - + // + public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { addSurfaceUpdatedListener(-1, l); } - public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) + public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { if(l == null) { return; } synchronized(surfaceUpdatedListenersLock) { - if(0>index) { - index = surfaceUpdatedListeners.size(); + if(0>index) { + index = surfaceUpdatedListeners.size(); } surfaceUpdatedListeners.add(index, l); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java b/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java index ed23def8f..47b3e63fa 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java +++ b/src/nativewindow/classes/jogamp/nativewindow/ToolkitProperties.java @@ -8,14 +8,14 @@ import javax.media.nativewindow.NativeWindowFactory; * Implementation requires to provide static methods: *
                       public static void initSingleton() {}
                  -    
                  +
                       public static void shutdown() {}
                  -    
                  +
                       public static boolean requiresToolkitLock() {}
                  -    
                  +
                       public static boolean hasThreadingIssues() {}
                    * 
                  - * Above static methods are invoked by {@link NativeWindowFactory#initSingleton()}, + * Above static methods are invoked by {@link NativeWindowFactory#initSingleton()}, * or {@link NativeWindowFactory#shutdown()} via reflection. *

                  */ @@ -25,23 +25,23 @@ public interface ToolkitProperties { * Called by {@link NativeWindowFactory#initSingleton()} */ // void initSingleton(); - - /** + + /** * Cleanup resources. *

                  * Called by {@link NativeWindowFactory#shutdown()} *

                  */ // void shutdown(); - + /** * Called by {@link NativeWindowFactory#initSingleton()} */ // boolean requiresToolkitLock(); - + /** * Called by {@link NativeWindowFactory#initSingleton()} */ - // boolean hasThreadingIssues(); - + // boolean hasThreadingIssues(); + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java b/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java index c94f249a1..f622db8cc 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java +++ b/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java @@ -37,7 +37,7 @@ import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; /** * Generic Surface implementation which wraps an existing window handle. - * + * * @see ProxySurface */ public class WrappedSurface extends ProxySurfaceImpl { @@ -46,7 +46,7 @@ public class WrappedSurface extends ProxySurfaceImpl { /** * Utilizes a {@link UpstreamSurfaceHook.MutableSize} to hold the size information, * which is being passed to the {@link ProxySurface} instance. - * + * * @param cfg the {@link AbstractGraphicsConfiguration} to be used * @param handle the wrapped pre-existing native surface handle, maybe 0 if not yet determined * @param initialWidth @@ -59,7 +59,7 @@ public class WrappedSurface extends ProxySurfaceImpl { super(cfg, new UpstreamSurfaceHookMutableSize(initialWidth, initialHeight), ownsDevice); surfaceHandle=handle; } - + /** * @param cfg the {@link AbstractGraphicsConfiguration} to be used * @param handle the wrapped pre-existing native surface handle, maybe 0 if not yet determined @@ -74,7 +74,7 @@ public class WrappedSurface extends ProxySurfaceImpl { } @Override - protected void invalidateImpl() { + protected void invalidateImpl() { surfaceHandle = 0; } @@ -87,7 +87,7 @@ public class WrappedSurface extends ProxySurfaceImpl { public final void setSurfaceHandle(long surfaceHandle) { this.surfaceHandle=surfaceHandle; } - + @Override protected final int lockSurfaceImpl() { return LOCK_SUCCESS; diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java index 23c48d20e..0fa5006cc 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java +++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java @@ -71,19 +71,19 @@ public class AWTMisc { } return (Container) c; } - + /** * Return insets of the component w/o traversing up to parent, * i.e. trying Window and JComponent. *

                  - * Exception is JRootPane. + * Exception is JRootPane. * Return it's parent's Window component's insets if available, * otherwise return JRootPane's insets.
                  - * This is due to experience that some JRootPane's + * This is due to experience that some JRootPane's * do not expose valid insets value. *

                  * @param topLevelOnly if true only returns insets of top-level components, i.e. Window and JRootPanel, - * otherwise for JComponent as well. + * otherwise for JComponent as well. */ public static Insets getInsets(Component c, boolean topLevelOnly) { if( c instanceof Window ) { @@ -108,7 +108,7 @@ public class AWTMisc { */ public void run(Component c); } - + public static int performAction(Container c, Class cType, ComponentAction action) { int count = 0; final int cc = c.getComponentCount(); @@ -128,18 +128,18 @@ public class AWTMisc { } return count; } - + /** * Traverse to the next forward or backward component using the * container's FocusTraversalPolicy. - * - * @param comp the assumed current focuse component + * + * @param comp the assumed current focuse component * @param forward if true, returns the next focus component, otherwise the previous one. * @return */ public static Component getNextFocus(Component comp, boolean forward) { Container focusContainer = comp.getFocusCycleRootAncestor(); - while ( focusContainer != null && + while ( focusContainer != null && ( !focusContainer.isShowing() || !focusContainer.isFocusable() || !focusContainer.isEnabled() ) ) { comp = focusContainer; @@ -155,7 +155,7 @@ public class AWTMisc { } return next; } - + /** * Issue this when your non AWT toolkit gains focus to clear AWT menu path */ diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java index f579da217..815facbee 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ @@ -47,7 +47,7 @@ import java.awt.Toolkit; import java.security.AccessController; import java.security.PrivilegedAction; -public class JAWTJNILibLoader extends NWJNILibLoader { +public class JAWTJNILibLoader extends NWJNILibLoader { static { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { @@ -55,7 +55,7 @@ public class JAWTJNILibLoader extends NWJNILibLoader { // a Dialog with "awt.dll not found" might pop up. // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4481947. Toolkit.getDefaultToolkit(); - + // Must pre-load JAWT on all non-Mac platforms to // ensure references from jogl_awt shared object // will succeed since JAWT shared object isn't in @@ -74,9 +74,9 @@ public class JAWTJNILibLoader extends NWJNILibLoader { } }); } - + public static void initSingleton() { - // just exist to ensure static init has been run + // just exist to ensure static init has been run } - + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index 844b17469..32946fe2d 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,7 +29,7 @@ * 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. @@ -63,13 +63,13 @@ public class JAWTUtil { /** OSX JAWT version option to use CALayer */ public static final int JAWT_MACOSX_USE_CALAYER = 0x80000000; - + /** OSX JAWT CALayer availability on Mac OS X >= 10.6 Update 4 (recommended) */ public static final VersionNumber JAWT_MacOSXCALayerMinVersion = new VersionNumber(10,6,4); - + /** OSX JAWT CALayer required with Java >= 1.7.0 (implies OS X >= 10.7 */ public static final VersionNumber JAWT_MacOSXCALayerRequiredForJavaVersion = Platform.Version17; - + // See whether we're running in headless mode private static final boolean headlessMode; private static final JAWT jawtLockObject; @@ -81,27 +81,27 @@ public class JAWTUtil { private static final Method sunToolkitAWTLockMethod; private static final Method sunToolkitAWTUnlockMethod; private static final boolean hasSunToolkitAWTLock; - + private static final RecursiveLock jawtLock; private static final ToolkitLock jawtToolkitLock; private static class PrivilegedDataBlob1 { PrivilegedDataBlob1() { ok = false; - } + } Method sunToolkitAWTLockMethod; Method sunToolkitAWTUnlockMethod; boolean ok; } - + /** * Returns true if this platform's JAWT implementation supports offscreen layer. */ public static boolean isOffscreenLayerSupported() { return Platform.OS_TYPE == Platform.OSType.MACOS && - Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0; + Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0; } - + /** * Returns true if this platform's JAWT implementation requires using offscreen layer. */ @@ -109,8 +109,8 @@ public class JAWTUtil { return Platform.OS_TYPE == Platform.OSType.MACOS && Platform.JAVA_VERSION_NUMBER.compareTo(JAWT_MacOSXCALayerRequiredForJavaVersion)>=0; } - - /** + + /** * CALayer size needs to be set using the AWT component size. *

                  * AWT's super-calayer, i.e. the AWT's own component CALayer, @@ -120,13 +120,13 @@ public class JAWTUtil { *

                  * As of today, this flag is enabled for all known AWT versions. *

                  - *

                  + *

                  * Sync w/ NativeWindowProtocols.h - *

                  + *

                  */ public static final int JAWT_OSX_CALAYER_QUIRK_SIZE = 1 << 0; - - /** + + /** * CALayer position needs to be set to zero. *

                  * AWT's super-calayer, i.e. the AWT's own component CALayer, @@ -137,19 +137,19 @@ public class JAWTUtil { *

                  *

                  * Further more a re-layout seems to be required in this case, - * i.e. a programmatic forced resize +1 and it's inverted resize -1. + * i.e. a programmatic forced resize +1 and it's inverted resize -1. *

                  *

                  - * This flag is enabled w/ AWT < 1.7.0_40. + * This flag is enabled w/ AWT < 1.7.0_40. *

                  - *

                  + *

                  * Sync w/ NativeWindowProtocols.h - *

                  + *

                  */ public static final int JAWT_OSX_CALAYER_QUIRK_POSITION = 1 << 1; - - /** - * CALayer position needs to be derived from AWT position + + /** + * CALayer position needs to be derived from AWT position * in relation to super CALayer. *

                  * AWT's super-calayer, i.e. the AWT top-container's CALayer, @@ -165,7 +165,7 @@ public class JAWTUtil { *

                  *

                  * The super-calayer lies within the AWT top-container client space (content). - *

                  + *

                  *

                  * Component's location in super-calayer: *

                  @@ -188,12 +188,12 @@ public class JAWTUtil {
                      * 

                  * As of today, this flag is enabled for w/ AWT >= 1.7.0_40. *

                  - *

                  + *

                  * Sync w/ NativeWindowProtocols.h - *

                  + *

                  */ public static final int JAWT_OSX_CALAYER_QUIRK_LAYOUT = 1 << 2; - + /** * Returns bitfield of required JAWT OSX CALayer quirks to mediate AWT impl. bugs. *

                  @@ -211,12 +211,12 @@ public class JAWTUtil { */ public static int getOSXCALayerQuirks() { int res = 0; - if( Platform.OS_TYPE == Platform.OSType.MACOS && + if( Platform.OS_TYPE == Platform.OSType.MACOS && Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0 ) { - + /** Knowing impl. all expose the SIZE bug */ res |= JAWT_OSX_CALAYER_QUIRK_SIZE; - + final int c = Platform.JAVA_VERSION_NUMBER.compareTo(Platform.Version17); if( c < 0 || c == 0 && Platform.JAVA_VERSION_UPDATE < 40 ) { res |= JAWT_OSX_CALAYER_QUIRK_POSITION; @@ -226,20 +226,20 @@ public class JAWTUtil { } return res; } - + /** * @param useOffscreenLayerIfAvailable * @return */ public static JAWT getJAWT(boolean useOffscreenLayerIfAvailable) { - final int jawt_version_flags = JAWTFactory.JAWT_VERSION_1_4; + final int jawt_version_flags = JAWTFactory.JAWT_VERSION_1_4; JAWT jawt = JAWT.create(); - + // default queries boolean tryOffscreenLayer; boolean tryOnscreen; int jawt_version_flags_offscreen = jawt_version_flags; - + if(isOffscreenLayerRequired()) { if(Platform.OS_TYPE == Platform.OSType.MACOS) { if(Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0) { @@ -263,11 +263,11 @@ public class JAWTUtil { } else { tryOffscreenLayer = false; tryOnscreen = true; - } + } if(DEBUG) { System.err.println("JAWTUtil.getJAWT(tryOffscreenLayer "+tryOffscreenLayer+", tryOnscreen "+tryOnscreen+")"); } - + StringBuilder errsb = new StringBuilder(); if(tryOffscreenLayer) { errsb.append("Offscreen 0x").append(Integer.toHexString(jawt_version_flags_offscreen)); @@ -282,15 +282,15 @@ public class JAWTUtil { errsb.append("Onscreen 0x").append(Integer.toHexString(jawt_version_flags)); if( JAWT.getJAWT(jawt, jawt_version_flags) ) { return jawt; - } + } } throw new RuntimeException("Unable to initialize JAWT, trials: "+errsb.toString()); } - + public static boolean isJAWTUsingOffscreenLayer(JAWT jawt) { return 0 != ( jawt.getCachedVersion() & JAWTUtil.JAWT_MACOSX_USE_CALAYER ); } - + static { if(DEBUG) { System.err.println("JAWTUtil initialization (JAWT/JNI/..."); @@ -319,10 +319,10 @@ public class JAWTUtil { isQueueFlusherThread = m; j2dExist = ok; - PrivilegedDataBlob1 pdb1 = (PrivilegedDataBlob1) AccessController.doPrivileged(new PrivilegedAction() { + PrivilegedDataBlob1 pdb1 = (PrivilegedDataBlob1) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { PrivilegedDataBlob1 d = new PrivilegedDataBlob1(); - try { + try { final Class sunToolkitClass = Class.forName("sun.awt.SunToolkit"); d.sunToolkitAWTLockMethod = sunToolkitClass.getDeclaredMethod("awtLock", new Class[]{}); d.sunToolkitAWTLockMethod.setAccessible(true); @@ -337,7 +337,7 @@ public class JAWTUtil { }); sunToolkitAWTLockMethod = pdb1.sunToolkitAWTLockMethod; sunToolkitAWTUnlockMethod = pdb1.sunToolkitAWTUnlockMethod; - + boolean _hasSunToolkitAWTLock = false; if ( pdb1.ok ) { try { @@ -351,10 +351,10 @@ public class JAWTUtil { // hasSunToolkitAWTLock = false; jawtLock = LockFactory.createRecursiveLock(); - jawtToolkitLock = new ToolkitLock() { + jawtToolkitLock = new ToolkitLock() { public final void lock() { JAWTUtil.lockToolkit(); - } + } public final void unlock() { JAWTUtil.unlockToolkit(); } @@ -411,11 +411,11 @@ public class JAWTUtil { public static void initSingleton() { // just exist to ensure static init has been run } - + /** * Called by {@link NativeWindowFactory#shutdown()} */ - public static void shutdown() { + public static void shutdown() { } public static boolean hasJava2D() { @@ -443,7 +443,7 @@ public class JAWTUtil { * which just uses AWT's global ReentrantLock. *

                  *

                  - * AWT locking is wrapped through a recursive lock object. + * AWT locking is wrapped through a recursive lock object. *

                  */ public static void lockToolkit() throws NativeWindowException { @@ -471,11 +471,11 @@ public class JAWTUtil { * which just uses AWT's global ReentrantLock. *

                  *

                  - * AWT unlocking is wrapped through a recursive lock object. + * AWT unlocking is wrapped through a recursive lock object. *

                  */ public static void unlockToolkit() { - jawtLock.validateLocked(); + jawtLock.validateLocked(); if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.unlock(): "+jawtLock); } if( 1 == jawtLock.getHoldCount() ) { if(!headlessMode && !isJava2DQueueFlusherThread()) { @@ -492,14 +492,14 @@ public class JAWTUtil { } jawtLock.unlock(); } - + public static final void validateLocked() throws RuntimeException { jawtLock.validateLocked(); - } + } public static ToolkitLock getJAWTToolkitLock() { return jawtToolkitLock; } - + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWT_PlatformInfo.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWT_PlatformInfo.java index 40d7b8032..4f12d1925 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWT_PlatformInfo.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWT_PlatformInfo.java @@ -1,21 +1,21 @@ /* * 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 @@ -28,11 +28,11 @@ * 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. */ diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index b712f6a1a..87e3d3dd8 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -102,7 +102,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } windowHandle=0; } - + @Override protected void attachSurfaceLayerImpl(final long layerHandle) { OSXUtil.RunOnMainThread(false, new Runnable() { @@ -119,7 +119,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { if( null != outterInsets ) { p1.translate(-outterInsets.left, -outterInsets.top); } - + if( DEBUG ) { final java.awt.Point pA0 = component.getLocationOnScreen(); final Point pA1 = new Point(pA0.x, pA0.y); @@ -133,7 +133,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, p1.getX(), p1.getY(), getWidth(), getHeight(), JAWTUtil.getOSXCALayerQuirks()); } } ); } - + @Override protected void layoutSurfaceLayerImpl(long layerHandle, boolean visible) { final int caLayerQuirks = JAWTUtil.getOSXCALayerQuirks(); @@ -149,7 +149,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { if( null != outterInsets ) { p1.translate(-outterInsets.left, -outterInsets.top); } - + if( DEBUG ) { final java.awt.Point pA0 = component.getLocationOnScreen(); final Point pA1 = new Point(pA0.x, pA0.y); @@ -163,7 +163,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, visible, p1.getX(), p1.getY(), getWidth(), getHeight(), caLayerQuirks); } - + @Override protected void detachSurfaceLayerImpl(final long layerHandle, final Runnable detachNotify) { OSXUtil.RunOnMainThread(false, new Runnable() { @@ -172,17 +172,17 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { OSXUtil.RemoveCASublayer(rootSurfaceLayer, layerHandle); } } ); } - + @Override public final long getWindowHandle() { return windowHandle; } - + @Override public final long getSurfaceHandle() { return offscreenSurfaceDrawableSet ? offscreenSurfaceDrawable : drawable /* super.getSurfaceHandle() */ ; } - + public void setSurfaceHandle(long surfaceHandle) { if( !isOffscreenLayerSurfaceEnabled() ) { throw new java.lang.UnsupportedOperationException("Not using CALAYER"); @@ -198,7 +198,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { // use offscreen if supported and [ applet or requested ] return JAWTUtil.getJAWT(getShallUseOffscreenLayer() || isApplet()); } - + protected int lockSurfaceImpl() throws NativeWindowException { int ret = NativeWindow.LOCK_SURFACE_NOT_READY; ds = getJAWT().GetDrawingSurface(component); @@ -247,7 +247,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { return NativeWindow.LOCK_SURFACE_NOT_READY; } drawable = macosxdsi.getCocoaViewRef(); - + if (drawable == 0) { unlockSurfaceImpl(); return NativeWindow.LOCK_SURFACE_NOT_READY; @@ -259,9 +259,9 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { /** * Only create a fake invisible NSWindow for the drawable handle * to please frameworks requiring such (eg. NEWT). - * - * The actual surface/ca-layer shall be created/attached - * by the upper framework (JOGL) since they require more information. + * + * The actual surface/ca-layer shall be created/attached + * by the upper framework (JOGL) since they require more information. */ String errMsg = null; if(0 == drawable) { @@ -286,10 +286,10 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { OSXUtil.RunOnMainThread(false, new Runnable() { public void run() { String errMsg = null; - if(0 == rootSurfaceLayer && 0 != jawtSurfaceLayersHandle) { + if(0 == rootSurfaceLayer && 0 != jawtSurfaceLayersHandle) { rootSurfaceLayer = OSXUtil.CreateCALayer(bounds.getWidth(), bounds.getHeight()); if(0 == rootSurfaceLayer) { - errMsg = "Could not create root CALayer"; + errMsg = "Could not create root CALayer"; } else { try { SetJAWTRootSurfaceLayer0(jawtSurfaceLayersHandle, rootSurfaceLayer); @@ -318,10 +318,10 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } ret = NativeWindow.LOCK_SUCCESS; } - + return ret; } - + protected void unlockSurfaceImpl() throws NativeWindowException { if(null!=ds) { if (null!=dsi) { @@ -340,7 +340,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { System.err.println("MaxOSXJAWTWindow: 0x"+Integer.toHexString(this.hashCode())+" - thread: "+Thread.currentThread().getName()); dumpJAWTInfo(); } - + /** * {@inheritDoc} *

                  @@ -350,9 +350,9 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { * .. * ds = getJAWT().GetDrawingSurface(component); * due to a SIGSEGV. - * + * * Hence we have some threading / sync issues with the native JAWT implementation. - *

                  + *

                  */ @Override public Point getLocationOnScreen(Point storage) { @@ -361,36 +361,36 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } getLocationOnScreenNonBlocking(storage, component); return storage; - } + } protected Point getLocationOnScreenNativeImpl(final int x0, final int y0) { return null; } - - + + private static native long GetJAWTSurfaceLayersHandle0(Buffer jawtDrawingSurfaceInfoBuffer); - - /** + + /** * Set the given root CALayer in the JAWT surface - */ + */ private static native void SetJAWTRootSurfaceLayer0(long jawtSurfaceLayersHandle, long caLayer); - - /** + + /** * Unset the given root CALayer in the JAWT surface, passing the NIO DrawingSurfaceInfo buffer - */ + */ private static native void UnsetJAWTRootSurfaceLayer0(long jawtSurfaceLayersHandle, long caLayer); - + // Variables for lockSurface/unlockSurface private JAWT_DrawingSurface ds; private boolean dsLocked; private JAWT_DrawingSurfaceInfo dsi; private long jawtSurfaceLayersHandle; - + private JAWT_MacOSXDrawingSurfaceInfo macosxdsi; - + private volatile long rootSurfaceLayer = 0; // attached to the JAWT_SurfaceLayer - + private long windowHandle = 0; private long offscreenSurfaceDrawable = 0; private boolean offscreenSurfaceDrawableSet = false; - + // Workaround for instance of 4796548 private boolean firstLock = true; diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java index 74dabb67f..876531151 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java index 905a313d5..64e177155 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ @@ -67,7 +67,7 @@ public class WindowsJAWTWindow extends JAWTWindow { protected JAWT fetchJAWTImpl() throws NativeWindowException { return JAWTUtil.getJAWT(false); // no offscreen } - + protected int lockSurfaceImpl() throws NativeWindowException { int ret = NativeWindow.LOCK_SUCCESS; ds = getJAWT().GetDrawingSurface(component); diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java index 2e5dc7fb5..b08a7d83a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,7 +29,7 @@ * 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. @@ -62,7 +62,7 @@ public class X11JAWTWindow extends JAWTWindow { protected JAWT fetchJAWTImpl() throws NativeWindowException { return JAWTUtil.getJAWT(false); // no offscreen } - + protected int lockSurfaceImpl() throws NativeWindowException { int ret = NativeWindow.LOCK_SUCCESS; ds = getJAWT().GetDrawingSurface(component); @@ -123,11 +123,11 @@ public class X11JAWTWindow extends JAWTWindow { // surface is locked and hence the device return X11Lib.GetRelativeLocation(getDisplayHandle(), getScreenIndex(), getWindowHandle(), 0 /*root win*/, x, y); } - + // Variables for lockSurface/unlockSurface private JAWT_DrawingSurface ds; private boolean dsLocked; private JAWT_DrawingSurfaceInfo dsi; private JAWT_X11DrawingSurfaceInfo x11dsi; - + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java index 27e0a5e50..f1104d02f 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java @@ -1,22 +1,22 @@ /* * 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 @@ -29,11 +29,11 @@ * 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. */ diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXDummyUpstreamSurfaceHook.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXDummyUpstreamSurfaceHook.java index de3206c0c..b71af1042 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXDummyUpstreamSurfaceHook.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXDummyUpstreamSurfaceHook.java @@ -9,12 +9,12 @@ import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; public class OSXDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize { long nsWindow; - + /** - * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, - * not the actual dummy surface width. + * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, + * not the actual dummy surface width. * The latter is platform specific and small - * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, + * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, * not the actual dummy surface height, * The latter is platform specific and small */ @@ -22,7 +22,7 @@ public class OSXDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize super(width, height); nsWindow = 0; } - + @Override public final void create(ProxySurface s) { if(0 == nsWindow && 0 == s.getSurfaceHandle()) { @@ -35,11 +35,11 @@ public class OSXDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize throw new NativeWindowException("Error NS view 0"); } s.setSurfaceHandle(nsView); - s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); } s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); } - + @Override public final void destroy(ProxySurface s) { if( s.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 0d498fa54..004a91a42 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -41,9 +41,9 @@ import jogamp.nativewindow.NWJNILibLoader; import jogamp.nativewindow.ToolkitProperties; public class OSXUtil implements ToolkitProperties { - private static boolean isInit = false; + private static boolean isInit = false; private static final boolean DEBUG = Debug.debug("OSXUtil"); - + /** * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties @@ -56,10 +56,10 @@ public class OSXUtil implements ToolkitProperties { if(!NWJNILibLoader.loadNativeWindow("macosx")) { throw new NativeWindowException("NativeWindow MacOSX native library load error."); } - + if( !initIDs0() ) { throw new NativeWindowException("MacOSX: Could not initialized native stub"); - } + } isInit = true; } } @@ -69,27 +69,27 @@ public class OSXUtil implements ToolkitProperties { * @see ToolkitProperties */ public static void shutdown() { } - + /** * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties */ public static boolean requiresToolkitLock() { return false; } - + /** * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties */ public static final boolean hasThreadingIssues() { return false; } - + public static boolean isNSView(long object) { return 0 != object ? isNSView0(object) : false; } - + public static boolean isNSWindow(long object) { return 0 != object ? isNSWindow0(object) : false; } - + /** * In case the windowOrView is top-level, * you shall set topLevel to true where @@ -108,7 +108,7 @@ public class OSXUtil implements ToolkitProperties { * @param src_y * @return the client position */ - public static Point GetLocationOnScreen(long windowOrView, boolean topLevel, int src_x, int src_y) { + public static Point GetLocationOnScreen(long windowOrView, boolean topLevel, int src_x, int src_y) { final Point los = (Point) GetLocationOnScreen0(windowOrView, src_x, src_y); if(topLevel) { // top-level position -> client window position @@ -117,11 +117,11 @@ public class OSXUtil implements ToolkitProperties { } return los; } - + public static Insets GetInsets(long windowOrView) { return (Insets) GetInsets0(windowOrView); } - + public static long CreateNSWindow(int x, int y, int width, int height) { return CreateNSWindow0(x, y, width, height); } @@ -134,11 +134,11 @@ public class OSXUtil implements ToolkitProperties { public static long GetNSWindow(long nsView) { return GetNSWindow0(nsView); } - - /** + + /** * Create a CALayer suitable to act as a root CALayer. * @see #DestroyCALayer(long) - * @see #AddCASublayer(long, long) + * @see #AddCASublayer(long, long) */ public static long CreateCALayer(final int width, final int height) { final long l = CreateCALayer0(width, height); @@ -147,8 +147,8 @@ public class OSXUtil implements ToolkitProperties { } return l; } - - /** + + /** * Attach a sub CALayer to the root CALayer *

                  * Method will trigger a display @@ -156,7 +156,7 @@ public class OSXUtil implements ToolkitProperties { *

                  *

                  * Hence it is important that related resources are not locked if - * they will be used for creation. + * they will be used for creation. *

                  * @param caLayerQuirks TODO * @see #CreateCALayer(int, int) @@ -171,18 +171,18 @@ public class OSXUtil implements ToolkitProperties { } AddCASublayer0(rootCALayer, subCALayer, x, y, width, height, caLayerQuirks); } - - /** + + /** * Fix root and sub CALayer position to 0/0 and size *

                  * If the sub CALayer implements the Objective-C NativeWindow protocol NWDedicatedSize (e.g. JOGL's MyNSOpenGLLayer), - * the dedicated size is passed to the layer, which propagates it appropriately. + * the dedicated size is passed to the layer, which propagates it appropriately. *

                  *

                  * On OSX/Java7 our root CALayer's frame position and size gets corrupted by its NSView, * hence we have created the NWDedicatedSize protocol. *

                  - * + * * @param rootCALayer the root surface layer, maybe null. * @param subCALayer the client surface layer, maybe null. * @param visible TODO @@ -196,8 +196,8 @@ public class OSXUtil implements ToolkitProperties { } FixCALayerLayout0(rootCALayer, subCALayer, visible, x, y, width, height, caLayerQuirks); } - - /** + + /** * Detach a sub CALayer from the root CALayer. */ public static void RemoveCASublayer(final long rootCALayer, final long subCALayer) { @@ -209,11 +209,11 @@ public class OSXUtil implements ToolkitProperties { } RemoveCASublayer0(rootCALayer, subCALayer); } - - /** + + /** * Destroy a CALayer. * @see #CreateCALayer(int, int) - */ + */ public static void DestroyCALayer(final long caLayer) { if(0==caLayer) { throw new IllegalArgumentException("caLayer 0x"+Long.toHexString(caLayer)); @@ -223,13 +223,13 @@ public class OSXUtil implements ToolkitProperties { } DestroyCALayer0(caLayer); } - + /** * Run on OSX UI main thread. - *

                  + *

                  * 'waitUntilDone' is implemented on Java site via lock/wait on {@link RunnableTask} to not freeze OSX main thread. *

                  - * + * * @param waitUntilDone * @param runnable */ @@ -238,10 +238,10 @@ public class OSXUtil implements ToolkitProperties { runnable.run(); // don't leave the JVM } else { // Utilize Java side lock/wait and simply pass the Runnable async to OSX main thread, - // otherwise we may freeze the OSX main thread. + // otherwise we may freeze the OSX main thread. Throwable throwable = null; final Object sync = new Object(); - final RunnableTask rt = new RunnableTask( runnable, waitUntilDone ? sync : null, true, waitUntilDone ? null : System.err ); + final RunnableTask rt = new RunnableTask( runnable, waitUntilDone ? sync : null, true, waitUntilDone ? null : System.err ); synchronized(sync) { RunOnMainThread0(rt); if( waitUntilDone ) { @@ -260,7 +260,7 @@ public class OSXUtil implements ToolkitProperties { } } } - + /** * Run later on .. * @param onMain if true, run on main-thread, otherwise on the current OSX thread. @@ -270,20 +270,20 @@ public class OSXUtil implements ToolkitProperties { public static void RunLater(boolean onMain, Runnable runnable, int delay) { RunLater0(onMain, new RunnableTask( runnable, null, true, System.err ), delay); } - + private static Runnable _nop = new Runnable() { public void run() {}; }; - - /** Issues a {@link #RunOnMainThread(boolean, Runnable)} w/ an NOP runnable, while waiting until done. */ + + /** Issues a {@link #RunOnMainThread(boolean, Runnable)} w/ an NOP runnable, while waiting until done. */ public static void WaitUntilFinish() { RunOnMainThread(true, _nop); } - + /** * Run on OSX UI main thread. - *

                  + *

                  * 'waitUntilDone' is implemented on Java site via lock/wait on {@link FunctionTask} to not freeze OSX main thread. *

                  - * + * * @param waitUntilDone * @param func */ @@ -292,10 +292,10 @@ public class OSXUtil implements ToolkitProperties { return func.eval(args); // don't leave the JVM } else { // Utilize Java side lock/wait and simply pass the Runnable async to OSX main thread, - // otherwise we may freeze the OSX main thread. + // otherwise we may freeze the OSX main thread. Throwable throwable = null; final Object sync = new Object(); - final FunctionTask rt = new FunctionTask( func, waitUntilDone ? sync : null, true, waitUntilDone ? null : System.err ); + final FunctionTask rt = new FunctionTask( func, waitUntilDone ? sync : null, true, waitUntilDone ? null : System.err ); synchronized(sync) { rt.setArgs(args); RunOnMainThread0(rt); @@ -316,20 +316,20 @@ public class OSXUtil implements ToolkitProperties { return rt.getResult(); } } - + public static boolean IsMainThread() { return IsMainThread0(); } - + /** Returns the screen refresh rate in Hz. If unavailable, returns 60Hz. */ public static int GetScreenRefreshRate(int scrn_idx) { return GetScreenRefreshRate0(scrn_idx); } - + /*** private static boolean isAWTEDTMainThreadInit = false; private static boolean isAWTEDTMainThread; - + public synchronized static boolean isAWTEDTMainThread() { if(!isAWTEDTMainThreadInit) { isAWTEDTMainThreadInit = true; @@ -343,10 +343,10 @@ public class OSXUtil implements ToolkitProperties { } else { isAWTEDTMainThread = false; } - } + } return isAWTEDTMainThread; } */ - + private static native boolean initIDs0(); private static native boolean isNSView0(long object); private static native boolean isNSWindow0(long object); diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIDummyUpstreamSurfaceHook.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIDummyUpstreamSurfaceHook.java index aa5f3dac5..e5de43c0a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIDummyUpstreamSurfaceHook.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIDummyUpstreamSurfaceHook.java @@ -9,31 +9,31 @@ import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; public class GDIDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize { /** - * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, - * not the actual dummy surface width. + * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, + * not the actual dummy surface width. * The latter is platform specific and small - * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, + * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, * not the actual dummy surface height, * The latter is platform specific and small */ public GDIDummyUpstreamSurfaceHook(int width, int height) { super(width, height); } - + @Override public final void create(ProxySurface s) { final GDISurface ms = (GDISurface)s; - if(0 == ms.getWindowHandle()) { + if(0 == ms.getWindowHandle()) { final long windowHandle = GDIUtil.CreateDummyWindow(0, 0, 64, 64); if(0 == windowHandle) { throw new NativeWindowException("Error windowHandle 0, werr: "+GDI.GetLastError()); - } + } ms.setWindowHandle(windowHandle); - ms.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + ms.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); } s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); } - + @Override public final void destroy(ProxySurface s) { final GDISurface ms = (GDISurface)s; @@ -46,5 +46,5 @@ public class GDIDummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize ms.setWindowHandle(0); ms.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); } - } + } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java index cc9c9853b..3e07b2a9e 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java @@ -43,7 +43,7 @@ import jogamp.nativewindow.windows.GDI; * allowing the use of HDC via lockSurface()/unlockSurface() protocol. * The latter will get and release the HDC. * The size via getWidth()/getHeight() is invalid. - * + * * @see ProxySurface */ public class GDISurface extends ProxySurfaceImpl { @@ -65,20 +65,20 @@ public class GDISurface extends ProxySurfaceImpl { } @Override - protected void invalidateImpl() { + protected void invalidateImpl() { if(0 != surfaceHandle) { throw new NativeWindowException("didn't release surface Handle: "+this); } windowHandle = 0; // surfaceHandle = 0; } - + /** * {@inheritDoc} *

                  - * Actually the window handle (HWND), since the surfaceHandle (HDC) is derived + * Actually the window handle (HWND), since the surfaceHandle (HDC) is derived * from it at {@link #lockSurface()}. - *

                  + *

                  */ @Override public final void setSurfaceHandle(long surfaceHandle) { @@ -86,7 +86,7 @@ public class GDISurface extends ProxySurfaceImpl { } /** - * Sets the window handle (HWND). + * Sets the window handle (HWND). */ public final void setWindowHandle(long windowHandle) { this.windowHandle = windowHandle; @@ -118,7 +118,7 @@ public class GDISurface extends ProxySurfaceImpl { final protected void unlockSurfaceImpl() { if (0 != surfaceHandle) { if(0 == GDI.ReleaseDC(windowHandle, surfaceHandle)) { - throw new NativeWindowException("DC not released: "+this+", isWindow "+GDI.IsWindow(windowHandle)+", werr "+GDI.GetLastError()+", thread: "+Thread.currentThread().getName()); + throw new NativeWindowException("DC not released: "+this+", isWindow "+GDI.IsWindow(windowHandle)+", werr "+GDI.GetLastError()+", thread: "+Thread.currentThread().getName()); } surfaceHandle=0; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index 00741a328..db61b1efd 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -37,11 +37,11 @@ import jogamp.nativewindow.ToolkitProperties; public class GDIUtil implements ToolkitProperties { private static final boolean DEBUG = Debug.debug("GDIUtil"); - + private static final String dummyWindowClassNameBase = "_dummyWindow_clazz" ; private static RegisteredClassFactory dummyWindowClassFactory; private static boolean isInit = false; - + /** * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties @@ -59,42 +59,42 @@ public class GDIUtil implements ToolkitProperties { if( !initIDs0() ) { throw new NativeWindowException("GDI: Could not initialized native stub"); } - dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0()); + dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0()); isInit = true; } } } } - + /** * Called by {@link NativeWindowFactory#shutdown()} * @see ToolkitProperties */ - public static void shutdown() { + public static void shutdown() { } - + /** * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties */ public static boolean requiresToolkitLock() { return false; } - + /** * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties */ public static final boolean hasThreadingIssues() { return false; } - + private static RegisteredClass dummyWindowClass = null; private static Object dummyWindowSync = new Object(); - + public static long CreateDummyWindow(int x, int y, int width, int height) { synchronized(dummyWindowSync) { dummyWindowClass = dummyWindowClassFactory.getSharedClass(); return CreateDummyWindow0(dummyWindowClass.getHInstance(), dummyWindowClass.getName(), dummyWindowClass.getName(), x, y, width, height); } } - + public static boolean DestroyDummyWindow(long hwnd) { boolean res; synchronized(dummyWindowSync) { @@ -106,27 +106,27 @@ public class GDIUtil implements ToolkitProperties { } return res; } - + public static Point GetRelativeLocation(long src_win, long dest_win, int src_x, int src_y) { return (Point) GetRelativeLocation0(src_win, dest_win, src_x, src_y); } - + public static boolean IsUndecorated(long win) { return IsUndecorated0(win); } - + public static boolean IsChild(long win) { return IsChild0(win); } - + public static native boolean CreateWindowClass(long hInstance, String clazzName, long wndProc); public static native boolean DestroyWindowClass(long hInstance, String className); - + private static native boolean initIDs0(); - private static native long getDummyWndProc0(); + private static native long getDummyWndProc0(); private static native Object GetRelativeLocation0(long src_win, long dest_win, int src_x, int src_y); private static native boolean IsChild0(long win); private static native boolean IsUndecorated0(long win); - - static native long CreateDummyWindow0(long hInstance, String className, String windowName, int x, int y, int width, int height); + + static native long CreateDummyWindow0(long hInstance, String className, String windowName, int x, int y, int width, int height); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java index 949f5d06d..976693e3a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java @@ -39,7 +39,7 @@ public class RegisteredClass { /** Application handle, same as {@link RegisteredClassFactory#getHInstance()}. */ public final long getHInstance() { return hInstance; } - + /** Unique Window Class Name */ public final String getName() { return className; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java index 0280b0df7..e033a9f66 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java @@ -34,9 +34,9 @@ import javax.media.nativewindow.NativeWindowException; public class RegisteredClassFactory { private static final boolean DEBUG = Debug.debug("RegisteredClass"); - private static final ArrayList registeredFactories; + private static final ArrayList registeredFactories; private static final long hInstance; - + static { hInstance = GDI.GetApplicationHandle(); if( 0 == hInstance ) { @@ -44,7 +44,7 @@ public class RegisteredClassFactory { } registeredFactories = new ArrayList(); } - + private String classBaseName; private long wndProc; @@ -52,9 +52,9 @@ public class RegisteredClassFactory { private int classIter = 0; private int sharedRefCount = 0; private final Object sync = new Object(); - + /** - * Release the {@link RegisteredClass} of all {@link RegisteredClassFactory}. + * Release the {@link RegisteredClass} of all {@link RegisteredClassFactory}. */ public static void shutdownSharedClasses() { synchronized(registeredFactories) { @@ -65,7 +65,7 @@ public class RegisteredClassFactory { GDIUtil.DestroyWindowClass(rcf.sharedClass.getHInstance(), rcf.sharedClass.getName()); rcf.sharedClass = null; rcf.sharedRefCount = 0; - rcf.classIter = 0; + rcf.classIter = 0; if(DEBUG) { System.err.println("RegisteredClassFactory #"+j+"/"+registeredFactories.size()+" shutdownSharedClasses : "+rcf.sharedClass); } @@ -74,7 +74,7 @@ public class RegisteredClassFactory { } } } - + /** Application handle. */ public static long getHInstance() { return hInstance; } @@ -94,7 +94,7 @@ public class RegisteredClassFactory { } String clazzName = null; boolean registered = false; - final int classIterMark = classIter - 1; + final int classIterMark = classIter - 1; while ( !registered && classIterMark != classIter ) { // Retry with next clazz name, this could happen if more than one JVM is running clazzName = classBaseName + classIter; diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java index 827862002..2c8ef642c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11DummyUpstreamSurfaceHook.java @@ -14,17 +14,17 @@ import com.jogamp.nativewindow.x11.X11GraphicsScreen; public class X11DummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize { /** - * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, - * not the actual dummy surface width. + * @param width the initial width as returned by {@link NativeSurface#getWidth()} via {@link UpstreamSurfaceHook#getWidth(ProxySurface)}, + * not the actual dummy surface width. * The latter is platform specific and small - * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, + * @param height the initial height as returned by {@link NativeSurface#getHeight()} via {@link UpstreamSurfaceHook#getHeight(ProxySurface)}, * not the actual dummy surface height, * The latter is platform specific and small */ public X11DummyUpstreamSurfaceHook(int width, int height) { super(width, height); } - + @Override public final void create(ProxySurface s) { final X11GraphicsConfiguration cfg = (X11GraphicsConfiguration) s.getGraphicsConfiguration(); @@ -42,14 +42,14 @@ public class X11DummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize throw new NativeWindowException("Creating dummy window failed w/ "+cfg); } s.setSurfaceHandle(windowHandle); - s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); + s.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); } s.addUpstreamOptionBits(ProxySurface.OPT_UPSTREAM_WINDOW_INVISIBLE); } finally { device.unlock(); } } - + @Override public final void destroy(ProxySurface s) { if( s.containsUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ) ) { @@ -59,7 +59,7 @@ public class X11DummyUpstreamSurfaceHook extends UpstreamSurfaceHookMutableSize } device.lock(); try { - X11Lib.DestroyWindow(device.getHandle(), s.getSurfaceHandle()); + X11Lib.DestroyWindow(device.getHandle(), s.getSurfaceHandle()); s.setSurfaceHandle(0); s.clearUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_SURFACE ); } finally { diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java index b11dd1df1..d6e7b5970 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -47,10 +47,10 @@ import com.jogamp.nativewindow.x11.X11GraphicsScreen; public class X11GraphicsConfigurationFactory extends GraphicsConfigurationFactory { public static void registerFactory() { GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, CapabilitiesImmutable.class, new X11GraphicsConfigurationFactory()); - } + } private X11GraphicsConfigurationFactory() { } - + protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen screen, int nativeVisualID) throws IllegalArgumentException, NativeWindowException { @@ -109,7 +109,7 @@ public class X11GraphicsConfigurationFactory extends GraphicsConfigurationFactor XVisualInfo best=null; int rdepth = capabilities.getRedBits() + capabilities.getGreenBits() + capabilities.getBlueBits() + capabilities.getAlphaBits(); for (int i = 0; vinfos!=null && i < num[0]; i++) { - if ( best == null || + if ( best == null || best.getDepth() < vinfos[i].getDepth() ) { best = vinfos[i]; diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 78e432b7f..6431fb3f5 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -54,16 +54,16 @@ import com.jogamp.nativewindow.x11.X11GraphicsDevice; */ public class X11Util implements ToolkitProperties { public static final boolean DEBUG = Debug.debug("X11Util"); - - /** + + /** * See Bug 515 - https://jogamp.org/bugzilla/show_bug.cgi?id=515 - *

                  + *

                  * It is observed that ATI X11 drivers, eg. - *

                    + *
                      *
                    • fglrx 8.78.6,
                    • *
                    • fglrx 11.08/8.881 and
                    • *
                    • fglrx 11.11/8.911
                    • - *
                    + *
                  * are quite sensitive to multiple Display connections. *

                  *

                  @@ -81,11 +81,11 @@ public class X11Util implements ToolkitProperties { *

                  *

                  * With ATI X11 drivers all connections must be closed at JVM shutdown, - * otherwise a SIGSEGV (after JVM safepoint) will be caused. + * otherwise a SIGSEGV (after JVM safepoint) will be caused. *

                  */ public static final boolean ATI_HAS_XCLOSEDISPLAY_BUG = !Debug.isPropertyDefined("nativewindow.debug.X11Util.ATI_HAS_NO_XCLOSEDISPLAY_BUG", true); - + /** See {@link #ATI_HAS_XCLOSEDISPLAY_BUG}. */ public static final boolean HAS_XCLOSEDISPLAY_BUG = Debug.isPropertyDefined("nativewindow.debug.X11Util.HAS_XCLOSEDISPLAY_BUG", true); @@ -105,7 +105,7 @@ public class X11Util implements ToolkitProperties { private static final Object setX11ErrorHandlerLock = new Object(); private static final String X11_EXTENSION_ATIFGLRXDRI = "ATIFGLRXDRI"; private static final String X11_EXTENSION_ATIFGLEXTENSION = "ATIFGLEXTENSION"; - + /** * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties @@ -121,15 +121,15 @@ public class X11Util implements ToolkitProperties { if(!NWJNILibLoader.loadNativeWindow("x11")) { throw new NativeWindowException("NativeWindow X11 native library load error."); } - + final boolean isInitOK = initialize0( XERROR_STACKDUMP ); - + final boolean hasX11_EXTENSION_ATIFGLRXDRI, hasX11_EXTENSION_ATIFGLEXTENSION; final long dpy = X11Lib.XOpenDisplay(PropertyAccess.getProperty("nativewindow.x11.display.default", true)); if(0 != dpy) { if(XSYNC_ENABLED) { X11Lib.XSynchronize(dpy, true); - } + } try { nullDisplayName = X11Lib.XDisplayString(dpy); hasX11_EXTENSION_ATIFGLRXDRI = X11Lib.QueryExtension(dpy, X11_EXTENSION_ATIFGLRXDRI); @@ -147,7 +147,7 @@ public class X11Util implements ToolkitProperties { if ( !markAllDisplaysUnclosable ) { markAllDisplaysUnclosable = ( ATI_HAS_XCLOSEDISPLAY_BUG && isATIFGLRX ) || HAS_XCLOSEDISPLAY_BUG; } - + if(DEBUG) { System.err.println("X11Util.initSingleton(): OK "+isInitOK+"]"+ ",\n\t X11 Display(NULL) <"+nullDisplayName+">"+ @@ -164,17 +164,17 @@ public class X11Util implements ToolkitProperties { } } } - + // not exactly thread safe, but good enough for our purpose, // which is to tag a NamedDisplay uncloseable after creation. - private static Object globalLock = new Object(); + private static Object globalLock = new Object(); private static LongObjectHashMap openDisplayMap = new LongObjectHashMap(); // handle -> name private static List openDisplayList = new ArrayList(); // open, no close attempt private static List reusableDisplayList = new ArrayList(); // close attempt, marked uncloseable, for reuse private static List pendingDisplayList = new ArrayList(); // all open (close attempt or reusable) in creation order private static final HashMap displayXineramaEnabledMap = new HashMap(); - - /** + + /** * Cleanup resources. *

                  * Called by {@link NativeWindowFactory#shutdown()} @@ -184,7 +184,7 @@ public class X11Util implements ToolkitProperties { public static void shutdown() { if(isInit) { synchronized(X11Util.class) { - if(isInit) { + if(isInit) { final boolean isJVMShuttingDown = NativeWindowFactory.isJVMShuttingDown() ; if( DEBUG || ( ( openDisplayMap.size() > 0 || reusableDisplayList.size() > 0 || pendingDisplayList.size() > 0 ) && @@ -207,9 +207,9 @@ public class X11Util implements ToolkitProperties { } } } - - // Only at JVM shutdown time, since AWT impl. seems to - // dislike closing of X11 Display's (w/ ATI driver). + + // Only at JVM shutdown time, since AWT impl. seems to + // dislike closing of X11 Display's (w/ ATI driver). if( isJVMShuttingDown ) { synchronized(globalLock) { isInit = false; @@ -226,7 +226,7 @@ public class X11Util implements ToolkitProperties { } } } - + /** * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties @@ -234,15 +234,15 @@ public class X11Util implements ToolkitProperties { public static final boolean requiresToolkitLock() { return true; // JAWT locking: yes, instead of native X11 locking w use a recursive lock per display connection. } - + /** * Called by {@link NativeWindowFactory#initSingleton()} * @see ToolkitProperties */ public static final boolean hasThreadingIssues() { - return hasThreadingIssues; // JOGL impl. may utilize special locking "somewhere" + return hasThreadingIssues; // JOGL impl. may utilize special locking "somewhere" } - + public static void setX11ErrorHandler(boolean onoff, boolean quiet) { synchronized(setX11ErrorHandlerLock) { setX11ErrorHandler0(onoff, quiet); @@ -271,7 +271,7 @@ public class X11Util implements ToolkitProperties { public static boolean getMarkAllDisplaysUnclosable() { return markAllDisplaysUnclosable; } - + private X11Util() {} public static class NamedDisplay { @@ -303,7 +303,7 @@ public class X11Util implements ToolkitProperties { public final int hashCode() { return hash32; } - + public final boolean equals(Object obj) { if(this == obj) { return true; } if(obj instanceof NamedDisplay) { @@ -311,10 +311,10 @@ public class X11Util implements ToolkitProperties { } return false; } - + public final void addRef() { refCount++; } public final void removeRef() { refCount--; } - + public final String getName() { return name; } public final long getHandle() { return handle; } public final int getRefCount() { return refCount; } @@ -365,7 +365,7 @@ public class X11Util implements ToolkitProperties { return openDisplayList.size(); } } - + public static void dumpOpenDisplayConnections() { synchronized(globalLock) { System.err.println("X11Util: Open X11 Display Connections: "+openDisplayList.size()); @@ -381,7 +381,7 @@ public class X11Util implements ToolkitProperties { } } } - + public static int getReusableDisplayConnectionNumber() { synchronized(globalLock) { return reusableDisplayList.size(); @@ -439,7 +439,7 @@ public class X11Util implements ToolkitProperties { NamedDisplay namedDpy = null; name = validateDisplayName(name); boolean reused = false; - + synchronized(globalLock) { for(int i=0; i - * If usrEDTUtil is null, + * If usrEDTUtil is null, * the device's default EDTUtil is created and used. *

                  *

                  - * If a previous one exists and it differs from usrEDTUtil, + * If a previous one exists and it differs from usrEDTUtil, * it's being stopped, wait-until-idle. *

                  *

                  @@ -167,7 +167,7 @@ public abstract class Display { *

                  */ public abstract EDTUtil setEDTUtil(EDTUtil usrEDTUtil); - + public abstract EDTUtil getEDTUtil(); /** @@ -176,7 +176,7 @@ public abstract class Display { public abstract boolean isEDTRunning(); public abstract void dispatchMessages(); - + // Global Displays protected static final ArrayList> displayList = new ArrayList>(); protected static int displaysActive = 0; @@ -193,12 +193,12 @@ public abstract class Display { } /** - * + * * @param type * @param name * @param fromIndex start index, then increasing until found or end of list - * @paran shared if true, only shared instances are found, otherwise also exclusive - * @return + * @paran shared if true, only shared instances are found, otherwise also exclusive + * @return */ public static Display getFirstDisplayOf(String type, String name, int fromIndex, boolean shared) { return getDisplayOfImpl(type, name, fromIndex, 1, shared); @@ -209,7 +209,7 @@ public abstract class Display { * @param type * @param name * @param fromIndex start index, then decreasing until found or end of list. -1 is interpreted as size - 1. - * @paran shared if true, only shared instances are found, otherwise also exclusive + * @paran shared if true, only shared instances are found, otherwise also exclusive * @return */ public static Display getLastDisplayOf(String type, String name, int fromIndex, boolean shared) { @@ -231,7 +231,7 @@ public abstract class Display { } else { if( display.getType().equals(type) && display.getName().equals(name) && - ( !shared || shared && !display.isExclusive() ) + ( !shared || shared && !display.isExclusive() ) ) { return display; } @@ -241,7 +241,7 @@ public abstract class Display { } return null; } - + protected static void addDisplay2List(Display display) { synchronized(displayList) { // GC before add @@ -256,7 +256,7 @@ public abstract class Display { displayList.add(new WeakReference(display)); } } - + /** Returns the global display collection */ public static Collection getAllDisplays() { ArrayList list; diff --git a/src/newt/classes/com/jogamp/newt/MonitorDevice.java b/src/newt/classes/com/jogamp/newt/MonitorDevice.java index 42ac34240..625a7b39f 100644 --- a/src/newt/classes/com/jogamp/newt/MonitorDevice.java +++ b/src/newt/classes/com/jogamp/newt/MonitorDevice.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.newt; import java.util.List; @@ -36,7 +36,7 @@ import javax.media.nativewindow.util.RectangleImmutable; import com.jogamp.common.util.ArrayHashSet; -/** +/** * Visual output device, i.e. a CRT, LED ..consisting of it's components:
                  * *
                • Immutable @@ -55,7 +55,7 @@ import com.jogamp.common.util.ArrayHashSet; */ public abstract class MonitorDevice { protected final Screen screen; // backref - protected final int nativeId; // unique monitor device ID + protected final int nativeId; // unique monitor device ID protected final DimensionImmutable sizeMM; // in [mm] protected final MonitorMode originalMode; protected final ArrayHashSet supportedModes; // FIXME: May need to support mutable mode, i.e. adding modes on the fly! @@ -73,14 +73,14 @@ public abstract class MonitorDevice { this.viewport = viewport; this.modeChanged = false; } - + /** Returns the {@link Screen} owning this monitor. */ public final Screen getScreen() { return screen; } - + /** - * Tests equality of two MonitorDevice objects + * Tests equality of two MonitorDevice objects * by evaluating equality of it's components:
                  *
                    *
                  • nativeID
                  • @@ -105,10 +105,10 @@ public abstract class MonitorDevice { public final int hashCode() { return nativeId; } - + /** @return the immutable unique native Id of this monitor device. */ public final int getId() { return nativeId; } - + /** * @return the immutable monitor size in millimeters. */ @@ -140,11 +140,11 @@ public abstract class MonitorDevice { return supportedModes.getData(); } - /** Returns the {@link RectangleImmutable rectangular} portion of the rotated virtual {@link Screen} size represented by this monitor. */ + /** Returns the {@link RectangleImmutable rectangular} portion of the rotated virtual {@link Screen} size represented by this monitor. */ public final RectangleImmutable getViewport() { return viewport; } - + /** Returns true if given coordinates are contained by this {@link #getViewport() viewport}, otherwise false. */ public final boolean contains(int x, int y) { return x >= viewport.getX() && @@ -152,8 +152,8 @@ public abstract class MonitorDevice { y >= viewport.getY() && y < viewport.getY() + viewport.getHeight() ; } - - /** + + /** * Returns the coverage of given rectangle w/ this this {@link #getViewport() viewport}, i.e. between 0.0 and 1.0. *

                    * Coverage is computed by: @@ -161,12 +161,12 @@ public abstract class MonitorDevice { * isect = viewport.intersection(r); * coverage = area( isect ) / area( viewport ) ; * - *

                    + *

                    */ public final float coverage(RectangleImmutable r) { return viewport.coverage(r); } - + /** * Returns the union of the given monitor's {@link #getViewport() viewport}. * @param result storage for result, will be returned @@ -186,14 +186,14 @@ public abstract class MonitorDevice { result.set(x1, y1, x2 - x1, y2 - y1); return result; } - + public final boolean isOriginalMode() { return currentMode.hashCode() == originalMode.hashCode(); } - + /** * Returns true if the {@link MonitorMode} - * has been changed programmatic via this API only, otherwise false. + * has been changed programmatic via this API only, otherwise false. *

                    * Note: We cannot guarantee that we won't interfere w/ another running * application's screen mode change or vice versa. @@ -202,7 +202,7 @@ public abstract class MonitorDevice { public final boolean isModeChangedByUs() { return modeChanged && !isOriginalMode(); } - + /** * Returns the cached current {@link MonitorMode} w/o native query. *

                    @@ -212,7 +212,7 @@ public abstract class MonitorDevice { public final MonitorMode getCurrentMode() { return currentMode; } - + /** * Returns the current {@link MonitorMode} resulting from a native query. *

                    diff --git a/src/newt/classes/com/jogamp/newt/MonitorMode.java b/src/newt/classes/com/jogamp/newt/MonitorMode.java index 218cd8bd5..175d6e5f2 100644 --- a/src/newt/classes/com/jogamp/newt/MonitorMode.java +++ b/src/newt/classes/com/jogamp/newt/MonitorMode.java @@ -37,7 +37,7 @@ import javax.media.nativewindow.util.SurfaceSize; import com.jogamp.newt.util.MonitorModeUtil; -/** +/** * Immutable MonitorMode Class, consisting of it's read only components:
                    *

                      *
                    • nativeId
                    • @@ -79,7 +79,7 @@ import com.jogamp.newt.util.MonitorModeUtil; // Pick the monitor: // Either the one used by a window .. MonitorDevice monitor = window.getMainMonitor(); - + // Or arbitrary from the list .. List allMonitor = getMonitorDevices(); MonitorDevice monitor = allMonitor.get(0); @@ -87,7 +87,7 @@ import com.jogamp.newt.util.MonitorModeUtil; // Current and original modes .. MonitorMode mmCurrent = monitor.queryCurrentMode(); MonitorMode mmOrig = monitor.getOriginalMode(); - + // Target resolution Dimension res = new Dimension(800, 600); @@ -102,7 +102,7 @@ import com.jogamp.newt.util.MonitorModeUtil; monitorModes = MonitorModeUtil.filterByFlags(monitorModes, 0); // no interlace, double-scan etc monitorModes = MonitorModeUtil.filterByRotation(monitorModes, rot); monitorModes = MonitorModeUtil.filterByResolution(monitorModes, res); - monitorModes = MonitorModeUtil.filterByRate(monitorModes, freq); + monitorModes = MonitorModeUtil.filterByRate(monitorModes, freq); monitorModes = MonitorModeUtil.getHighestAvailableBpp(monitorModes); // pick 1st one and set to current .. @@ -111,20 +111,20 @@ import com.jogamp.newt.util.MonitorModeUtil; * */ public class MonitorMode implements Comparable { - + /** Comparator for 2 {@link MonitorMode}s, following comparison order as described in {@link MonitorMode#compareTo(MonitorMode)}, returning the ascending order. */ public static final Comparator monitorModeComparator = new Comparator() { public int compare(MonitorMode mm1, MonitorMode mm2) { return mm1.compareTo(mm2); } }; - + /** Comparator for 2 {@link MonitorMode}s, following comparison order as described in {@link MonitorMode#compareTo(MonitorMode)}, returning the descending order. */ public static final Comparator monitorModeComparatorInv = new Comparator() { public int compare(MonitorMode mm1, MonitorMode mm2) { return mm2.compareTo(mm1); } }; - - /** + + /** * Immutable surfaceSize, flags and refreshRate Class, consisting of it's read only components:
                      *
                        *
                      • nativeId
                      • @@ -141,7 +141,7 @@ public class MonitorMode implements Comparable { /** Vertical refresh rate */ public final float refreshRate; public final int hashCode; - + public SizeAndRRate(SurfaceSize surfaceSize, float refreshRate, int flags) { if(null==surfaceSize) { throw new IllegalArgumentException("surfaceSize must be set ("+surfaceSize+")"); @@ -151,11 +151,11 @@ public class MonitorMode implements Comparable { this.refreshRate=refreshRate; this.hashCode = getHashCode(); } - + private final static String STR_INTERLACE = "Interlace"; private final static String STR_DOUBLESCAN = "DoubleScan"; private final static String STR_SEP = ", "; - + public static final StringBuilder flags2String(int flags) { final StringBuilder sb = new StringBuilder(); boolean sp = false; @@ -175,11 +175,11 @@ public class MonitorMode implements Comparable { public final String toString() { return new String(surfaceSize+" @ "+refreshRate+" Hz, flags ["+flags2String(flags).toString()+"]"); } - + /** *

                        * Compares {@link SurfaceSize#compareTo(SurfaceSize) surfaceSize} 1st, then {@link #flags}, then {@link #refreshRate}. - *

                        + *

                        *

                        * Flags are compared as follows: *

                        @@ -196,7 +196,7 @@ public class MonitorMode implements Comparable {
                                     final int rssz = surfaceSize.compareTo(sszr.surfaceSize);
                                     if( 0 != rssz ) {
                                         return rssz;
                        -            }            
                        +            }
                                     final int tflags = 0 == flags ? Integer.MAX_VALUE : flags; // normalize NONE
                                     final int xflags = 0 == sszr.flags ? Integer.MAX_VALUE : sszr.flags; // normalize NONE
                                     if( tflags == xflags ) {
                        @@ -218,9 +218,9 @@ public class MonitorMode implements Comparable {
                                         return 0;
                                     }
                                 }
                        -        
                        +
                                 /**
                        -         * Tests equality of two {@link SizeAndRRate} objects 
                        +         * Tests equality of two {@link SizeAndRRate} objects
                                  * by evaluating equality of it's components:
                        *
                          *
                        • surfaceSize
                        • @@ -238,7 +238,7 @@ public class MonitorMode implements Comparable { } return false; } - + /** * Returns a combined hash code of it's elements:
                          *
                            @@ -249,16 +249,16 @@ public class MonitorMode implements Comparable { */ public final int hashCode() { return hashCode; - } + } private final int getHashCode() { // 31 * x == (x << 5) - x int hash = 31 + surfaceSize.hashCode(); hash = ((hash << 5) - hash) + flags; hash = ((hash << 5) - hash) + (int)(refreshRate*100.0f); return hash; - } + } } - + /** zero rotation, compared to normal settings */ public static final int ROTATE_0 = 0; @@ -270,15 +270,15 @@ public class MonitorMode implements Comparable { /** 270 degrees CCW rotation */ public static final int ROTATE_270 = 270; - + /** Frame is split into two fields. See {@link #getFlags()}. */ public static final int FLAG_INTERLACE = 1 << 0; - + /** Lines are doubled. See {@link #getFlags()}. */ public static final int FLAG_DOUBLESCAN = 1 << 1; /** The immutable native Id of this instance, which may not be unique. */ - private final int nativeId; + private final int nativeId; private final SizeAndRRate sizeAndRRate; private final int rotation; private final int hashCode; @@ -301,7 +301,7 @@ public class MonitorMode implements Comparable { this.rotation = rotation; this.hashCode = getHashCode(); } - + /** * Creates a user instance w/o {@link #getId() identity} to filter our matching modes w/ identity. *

                            @@ -314,16 +314,16 @@ public class MonitorMode implements Comparable { */ public MonitorMode(SurfaceSize surfaceSize, float refreshRate, int flags, int rotation) { this(0, new SizeAndRRate(surfaceSize, refreshRate, flags), rotation); - } + } /** @return the immutable native Id of this mode, may not be unique, may be 0. */ public final int getId() { return nativeId; } - + /** Returns the surfaceSize and refreshRate instance. */ - public final SizeAndRRate getSizeAndRRate() { + public final SizeAndRRate getSizeAndRRate() { return sizeAndRRate; } - + /** Returns the unrotated {@link SurfaceSize} */ public final SurfaceSize getSurfaceSize() { return sizeAndRRate.surfaceSize; @@ -338,23 +338,23 @@ public class MonitorMode implements Comparable { public final int getFlags() { return sizeAndRRate.flags; } - + /** Returns the CCW rotation of this mode */ public final int getRotation() { return rotation; } - - /** Returns the rotated screen width, + + /** Returns the rotated screen width, * derived from getMonitorMode().getSurfaceSize().getResolution() - * and getRotation() + * and getRotation() */ public final int getRotatedWidth() { return getRotatedWH(true); } - - /** Returns the rotated screen height, + + /** Returns the rotated screen height, * derived from getMonitorMode().getSurfaceSize().getResolution() - * and getRotation() + * and getRotation() */ public final int getRotatedHeight() { return getRotatedWH(false); @@ -367,9 +367,9 @@ public class MonitorMode implements Comparable { /** *

                            * Compares {@link SizeAndRRate#compareTo(SizeAndRRate) sizeAndRRate} 1st, then {@link #rotation}. - *

                            + *

                            *

                            - * Rotation is compared inverted, i.e. 360 - rotation, + * Rotation is compared inverted, i.e. 360 - rotation, * so the lowest rotation reflects a higher value. *

                            *

                            @@ -380,7 +380,7 @@ public class MonitorMode implements Comparable { *

                          • flags
                          • *
                          • refresh rate
                          • *
                          • rotation
                          • - *
                          + *
                        *

                        * {@inheritDoc} */ @@ -399,9 +399,9 @@ public class MonitorMode implements Comparable { } return 0; } - + /** - * Tests equality of two {@link MonitorMode} objects + * Tests equality of two {@link MonitorMode} objects * by evaluating equality of it's components:
                        *
                          *
                        • nativeId
                        • @@ -438,7 +438,7 @@ public class MonitorMode implements Comparable { hash = ((hash << 5) - hash) + getRotation(); return hash; } - + private final int getRotatedWH(boolean width) { final DimensionImmutable d = sizeAndRRate.surfaceSize.getResolution(); final boolean swap = MonitorMode.ROTATE_90 == rotation || MonitorMode.ROTATE_270 == rotation ; @@ -446,5 +446,5 @@ public class MonitorMode implements Comparable { return d.getHeight(); } return d.getWidth(); - } + } } diff --git a/src/newt/classes/com/jogamp/newt/NewtFactory.java b/src/newt/classes/com/jogamp/newt/NewtFactory.java index e66b2f624..7116877a3 100644 --- a/src/newt/classes/com/jogamp/newt/NewtFactory.java +++ b/src/newt/classes/com/jogamp/newt/NewtFactory.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package com.jogamp.newt; @@ -53,16 +53,16 @@ public class NewtFactory { public static final boolean DEBUG_IMPLEMENTATION = Debug.debug("Window"); public static final String DRIVER_DEFAULT_ROOT_PACKAGE = "jogamp.newt.driver"; - + static { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { NativeWindowFactory.initSingleton(); // last resort .. - + // Work-around for initialization order problems on Mac OS X // between native Newt and (apparently) Fmod WindowImpl.init(NativeWindowFactory.getNativeWindowType(true)); - + return null; } } ); } @@ -75,7 +75,7 @@ public class NewtFactory { clazzName = DRIVER_DEFAULT_ROOT_PACKAGE + packageName + "." + classBaseName ; } else { clazzName = packageName + "." + classBaseName ; - } + } try { clazz = Class.forName(clazzName); } catch (Throwable t) { @@ -90,7 +90,7 @@ public class NewtFactory { private static boolean useEDT = true; - /** + /** * Toggles the usage of an EventDispatchThread while creating a Display.
                          * The default is enabled.
                          * The EventDispatchThread is thread local to the Display instance.
                          @@ -108,7 +108,7 @@ public class NewtFactory { * Native creation is lazily done at usage, ie. {@link Display#addReference()}. *

                          *

                          - * An already existing display connection of the same name will be reused. + * An already existing display connection of the same name will be reused. *

                          * @param name the display connection name which is a technical platform specific detail, * see {@link AbstractGraphicsDevice#getConnection()}. Use null for default. diff --git a/src/newt/classes/com/jogamp/newt/NewtVersion.java b/src/newt/classes/com/jogamp/newt/NewtVersion.java index 9adb7aac5..e70d63f88 100644 --- a/src/newt/classes/com/jogamp/newt/NewtVersion.java +++ b/src/newt/classes/com/jogamp/newt/NewtVersion.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.newt; import com.jogamp.common.GlueGenVersion; diff --git a/src/newt/classes/com/jogamp/newt/Screen.java b/src/newt/classes/com/jogamp/newt/Screen.java index f56ee344b..1274b3459 100644 --- a/src/newt/classes/com/jogamp/newt/Screen.java +++ b/src/newt/classes/com/jogamp/newt/Screen.java @@ -39,7 +39,7 @@ import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.util.Rectangle; import javax.media.nativewindow.util.RectangleImmutable; -/** +/** * A screen may span multiple {@link MonitorDevice}s representing their combined virtual size. */ public abstract class Screen { @@ -102,7 +102,7 @@ public abstract class Screen { /** * See {@link Display#addReference()} - * + * * @return number of references post operation * @throws NativeWindowException if the native creation failed. * @see #removeReference() @@ -113,7 +113,7 @@ public abstract class Screen { /** * See {@link Display#removeReference()} - * + * * @return number of references post operation * @see #addReference() * @see #setDestroyWhenUnused(boolean) @@ -132,12 +132,12 @@ public abstract class Screen { * @return the x position of the virtual viewport's top-left origin. */ public abstract int getX(); - + /** * @return the y position of the virtual viewport's top-left origin. */ public abstract int getY(); - + /** * @return the rotated virtual viewport's width. */ @@ -152,19 +152,19 @@ public abstract class Screen { * @return the rotated virtual viewport, i.e. origin and size. */ public abstract RectangleImmutable getViewport(); - + /** * @return the associated Display */ public abstract Display getDisplay(); - /** + /** * @return The screen fully qualified Screen name, * which is a key of {@link com.jogamp.newt.Display#getFQName()} + {@link #getIndex()}. */ public abstract String getFQName(); - /** + /** * Return a list of all {@link MonitorMode}s for all {@link MonitorDevice}s. *

                          * The list is ordered in descending order, @@ -173,23 +173,23 @@ public abstract class Screen { */ public abstract List getMonitorModes(); - /** + /** * Return a list of available {@link MonitorDevice}s. */ public abstract List getMonitorDevices(); /** - * Returns the {@link MonitorDevice} which {@link MonitorDevice#getViewport() viewport} + * Returns the {@link MonitorDevice} which {@link MonitorDevice#getViewport() viewport} * {@link MonitorDevice#coverage(RectangleImmutable) covers} the given rectangle the most. *

                          - * If no coverage is detected the first {@link MonitorDevice} is returned. + * If no coverage is detected the first {@link MonitorDevice} is returned. *

                          */ public final MonitorDevice getMainMonitor(RectangleImmutable r) { MonitorDevice res = null; float maxCoverage = Float.MIN_VALUE; final List monitors = getMonitorDevices(); - for(int i=monitors.size()-1; i>=0; i--) { + for(int i=monitors.size()-1; i>=0; i--) { final MonitorDevice monitor = monitors.get(i); final float coverage = monitor.coverage(r); if( coverage > maxCoverage ) { @@ -207,14 +207,14 @@ public abstract class Screen { * Returns the union of all monitor's {@link MonitorDevice#getViewport() viewport}. *

                          * Should be equal to {@link #getX()}, {@link #getY()}, {@link #getWidth()} and {@link #getHeight()}, - * however, some native toolkits may choose a different virtual screen area. + * however, some native toolkits may choose a different virtual screen area. *

                          * @param result storage for result, will be returned */ public final Rectangle unionOfMonitorViewportSize(final Rectangle result) { return MonitorDevice.unionOfViewports(result, getMonitorDevices()); } - + /** * @param sml {@link MonitorModeListener} to be added for {@link MonitorEvent} */ @@ -274,7 +274,7 @@ public abstract class Screen { } return null; } - + protected static void addScreen2List(Screen screen) { synchronized(screenList) { // GC before add @@ -289,7 +289,7 @@ public abstract class Screen { screenList.add(new WeakReference(screen)); } } - + /** Returns the global screen collection */ public static Collection getAllScreens() { ArrayList list; @@ -308,7 +308,7 @@ public abstract class Screen { } return list; } - + public static int getActiveScreenNumber() { synchronized(screenList) { return screensActive; diff --git a/src/newt/classes/com/jogamp/newt/Window.java b/src/newt/classes/com/jogamp/newt/Window.java index 02727353f..04eb07a25 100644 --- a/src/newt/classes/com/jogamp/newt/Window.java +++ b/src/newt/classes/com/jogamp/newt/Window.java @@ -58,8 +58,8 @@ import javax.media.nativewindow.util.RectangleImmutable; *
                        • ... and more
                        • * *

                          - * One use case is {@link com.jogamp.newt.opengl.GLWindow}, which delegates - * window operation to an instance of this interface while providing OpenGL + * One use case is {@link com.jogamp.newt.opengl.GLWindow}, which delegates + * window operation to an instance of this interface while providing OpenGL * functionality. *

                          */ @@ -90,14 +90,14 @@ public interface Window extends NativeWindow, WindowClosingProtocol { Screen getScreen(); /** - * Returns the {@link MonitorDevice} which {@link MonitorDevice#getViewport() viewport} + * Returns the {@link MonitorDevice} which {@link MonitorDevice#getViewport() viewport} * {@link MonitorDevice#coverage(RectangleImmutable) covers} this window the most. *

                          - * If no coverage is detected the first {@link MonitorDevice} is returned. + * If no coverage is detected the first {@link MonitorDevice} is returned. *

                          */ MonitorDevice getMainMonitor(); - + /** * Set the CapabilitiesChooser to help determine the native visual type. * @@ -129,7 +129,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { * Visibility is set to false. *

                          *

                          - * Method sends out {@link WindowEvent#EVENT_WINDOW_DESTROY_NOTIFY pre-} and + * Method sends out {@link WindowEvent#EVENT_WINDOW_DESTROY_NOTIFY pre-} and * {@link WindowEvent#EVENT_WINDOW_DESTROYED post-} destruction events * to all of it's {@link WindowListener}. *

                          @@ -151,7 +151,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { * Set a custom action handling destruction issued by a {@link WindowImpl#windowDestroyNotify(boolean) toolkit triggered window destroy} * replacing the default {@link #destroy()} action. *

                          - * The custom action shall call {@link #destroy()} + * The custom action shall call {@link #destroy()} * but may perform further tasks before and after. *

                          */ @@ -369,7 +369,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { * @param x new top-level position, use -1 for default position. * @param y new top-level position, use -1 for default position. * @param forceDestroyCreate if true, uses re-creation strategy for reparenting, default is false. - * + * * @return The issued reparent action type (strategy) as defined in Window.ReparentAction * @see #reparentWindow(NativeWindow) */ @@ -378,7 +378,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { /** * Enable or disable fullscreen mode for this window. *

                          - * Fullscreen mode is established on the {@link #getMainMonitor() main monitor}. + * Fullscreen mode is established on the {@link #getMainMonitor() main monitor}. *

                          * @param fullscreen enable or disable fullscreen mode * @return success @@ -393,14 +393,14 @@ public interface Window extends NativeWindow, WindowClosingProtocol { *

                          * Disable fullscreen via {@link #setFullscreen(boolean)}. *

                          - * @param monitors if null fullscreen will be spanned across all {@link MonitorDevice}s, + * @param monitors if null fullscreen will be spanned across all {@link MonitorDevice}s, * otherwise across the given list of {@link MonitorDevice}. * @return success * @see #setFullscreen(boolean) * @see #isFullscreen() */ boolean setFullscreen(List monitors); - + boolean isFullscreen(); static interface FocusRunnable { @@ -429,7 +429,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { * and to perform focus traversal with a 3rd party toolkit. *

                          *

                          - * The {@link KeyListener} methods are not invoked for {@link KeyEvent#isAutoRepeat() auto-repeat} events. + * The {@link KeyListener} methods are not invoked for {@link KeyEvent#isAutoRepeat() auto-repeat} events. *

                          * @param l */ @@ -469,7 +469,7 @@ public interface Window extends NativeWindow, WindowClosingProtocol { /** * Send a {@link WindowEvent} to all {@link WindowListener}. - * @param eventType a {@link WindowEvent} type, e.g. {@link WindowEvent#EVENT_WINDOW_REPAINT}. + * @param eventType a {@link WindowEvent} type, e.g. {@link WindowEvent#EVENT_WINDOW_REPAINT}. */ public void sendWindowEvent(int eventType); @@ -585,8 +585,8 @@ public interface Window extends NativeWindow, WindowClosingProtocol { * Returns all {@link MouseListener} */ MouseListener[] getMouseListeners(); - - /** Enable or disable default {@link GestureHandler}. Default is enabled. */ + + /** Enable or disable default {@link GestureHandler}. Default is enabled. */ void setDefaultGesturesEnabled(boolean enable); /** Return true if default {@link GestureHandler} are enabled. */ boolean areDefaultGesturesEnabled(); @@ -627,5 +627,5 @@ public interface Window extends NativeWindow, WindowClosingProtocol { /** * Removes the given {@link GestureHandler.GestureListener} from the list. */ - void removeGestureListener(GestureHandler.GestureListener gl); + void removeGestureListener(GestureHandler.GestureListener gl); } diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 13affdf49..de1b7224f 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.newt.awt; @@ -84,11 +84,11 @@ import com.jogamp.opengl.util.TileRenderer; /** * AWT {@link java.awt.Canvas Canvas} containing a NEWT {@link Window} using native parenting. - * + * *
                          Offscreen Layer Remarks
                          - * + * * {@link OffscreenLayerOption#setShallUseOffscreenLayer(boolean) setShallUseOffscreenLayer(true)} - * maybe called to use an offscreen drawable (FBO or PBuffer) allowing + * maybe called to use an offscreen drawable (FBO or PBuffer) allowing * the underlying JAWT mechanism to composite the image, if supported. */ @SuppressWarnings("serial") @@ -104,7 +104,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto private AWTParentWindowAdapter awtAdapter = null; private AWTAdapter awtMouseAdapter = null; private AWTAdapter awtKeyAdapter = null; - + private AWTWindowClosingProtocol awtWindowClosingProtocol = new AWTWindowClosingProtocol(this, new Runnable() { public void run() { @@ -115,7 +115,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto if( newtChild != null ) { newtChild.sendWindowEvent(WindowEvent.EVENT_WINDOW_DESTROY_NOTIFY); } - } + } } ); /** @@ -147,36 +147,36 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto super(gc); setNEWTChild(child); } - + public void setShallUseOffscreenLayer(boolean v) { shallUseOffscreenLayer = v; } - + public final boolean getShallUseOffscreenLayer() { - return shallUseOffscreenLayer; + return shallUseOffscreenLayer; } - - public final boolean isOffscreenLayerSurfaceEnabled() { + + public final boolean isOffscreenLayerSurfaceEnabled() { return jawtWindow.isOffscreenLayerSurfaceEnabled(); } - - /** - * Returns true if the AWT component is parented to an {@link java.applet.Applet}, - * otherwise false. This information is valid only after {@link #addNotify()} is issued, - * ie. before adding the component to the AWT tree and make it visible. + + /** + * Returns true if the AWT component is parented to an {@link java.applet.Applet}, + * otherwise false. This information is valid only after {@link #addNotify()} is issued, + * ie. before adding the component to the AWT tree and make it visible. */ public boolean isApplet() { return jawtWindow.isApplet(); } boolean isParent() { - return null!=newtChild && jawtWindow == newtChild.getParent(); + return null!=newtChild && jawtWindow == newtChild.getParent(); } - + boolean isFullscreen() { return null != newtChild && newtChild.isFullscreen(); } - + class FocusAction implements Window.FocusRunnable { public boolean run() { final boolean isParent = isParent(); @@ -199,7 +199,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } } private FocusAction focusAction = new FocusAction(); - + WindowListener clearAWTMenusOnNewtFocus = new WindowAdapter() { @Override public void windowResized(WindowEvent e) { @@ -224,15 +224,15 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto handleKey(e, true); } } - - void handleKey(KeyEvent evt, boolean onRelease) { + + void handleKey(KeyEvent evt, boolean onRelease) { if(null == keyboardFocusManager) { throw new InternalError("XXX"); } final AWTKeyStroke ks = AWTKeyStroke.getAWTKeyStroke(evt.getKeyCode(), evt.getModifiers(), onRelease); boolean suppress = false; if(null != ks) { - final Set fwdKeys = keyboardFocusManager.getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS); + final Set fwdKeys = keyboardFocusManager.getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS); final Set bwdKeys = keyboardFocusManager.getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS); if(fwdKeys.contains(ks)) { final Component nextFocus = AWTMisc.getNextFocus(NewtCanvasAWT.this, true /* forward */); @@ -253,38 +253,38 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } } if(suppress) { - evt.setConsumed(true); + evt.setConsumed(true); } if(DEBUG) { System.err.println("NewtCanvasAWT.focusKey: XXX: "+ks); } } } - private final FocusTraversalKeyListener newtFocusTraversalKeyListener = new FocusTraversalKeyListener(); + private final FocusTraversalKeyListener newtFocusTraversalKeyListener = new FocusTraversalKeyListener(); class FocusPropertyChangeListener implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent evt) { final Object oldF = evt.getOldValue(); final Object newF = evt.getNewValue(); final boolean isParent = isParent(); - final boolean isFullscreen = isFullscreen(); + final boolean isFullscreen = isFullscreen(); if(DEBUG) { System.err.println("NewtCanvasAWT.FocusProperty: "+evt.getPropertyName()+", src "+evt.getSource()+", "+oldF+" -> "+newF+", isParent "+isParent+", isFS "+isFullscreen); } if(isParent && !isFullscreen) { if(newF == NewtCanvasAWT.this) { - if(DEBUG) { + if(DEBUG) { System.err.println("NewtCanvasAWT.FocusProperty: AWT focus -> NEWT focus traversal"); } requestFocusNEWTChild(); } else if(oldF == NewtCanvasAWT.this && newF == null) { // focus traversal to NEWT - NOP - if(DEBUG) { + if(DEBUG) { System.err.println("NewtCanvasAWT.FocusProperty: NEWT focus"); } } else if(null != newF && newF != NewtCanvasAWT.this) { // focus traversal to another AWT component - if(DEBUG) { + if(DEBUG) { System.err.println("NewtCanvasAWT.FocusProperty: lost focus - clear focus"); } if(newtChild.getDelegatedWindow() instanceof DriverClearFocus) { @@ -292,7 +292,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } } } - } + } } private final FocusPropertyChangeListener focusPropertyChangeListener = new FocusPropertyChangeListener(); private volatile KeyboardFocusManager keyboardFocusManager = null; @@ -300,7 +300,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto private final void requestFocusNEWTChild() { if(null!=newtChild) { newtChild.setFocusAction(null); - if(isOnscreen) { + if(isOnscreen) { KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner(); } newtChild.requestFocus(); @@ -308,17 +308,17 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } } - /** + /** * Sets a new NEWT child, provoking reparenting. *

                          * A previously detached newChild will be released to top-level status - * and made invisible. + * and made invisible. *

                          *

                          - * Note: When switching NEWT child's, detaching the previous first via setNEWTChild(null) - * produced much cleaner visual results. + * Note: When switching NEWT child's, detaching the previous first via setNEWTChild(null) + * produced much cleaner visual results. *

                          - * @return the previous attached newt child. + * @return the previous attached newt child. */ public Window setNEWTChild(Window newChild) { final Window prevChild = newtChild; @@ -336,17 +336,17 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto updateLayoutSize(); // will be done later at paint/display/..: attachNewtChild(cont); - + return prevChild; } - + private final void updateLayoutSize() { if( null != newtChild ) { // use NEWT child's size for min/pref size! java.awt.Dimension minSize = new java.awt.Dimension(newtChild.getWidth(), newtChild.getHeight()); setMinimumSize(minSize); setPreferredSize(minSize); - } + } } /** @return the current NEWT child */ @@ -357,7 +357,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto /** @return this AWT Canvas NativeWindow representation, may be null in case {@link #removeNotify()} has been called, * or {@link #addNotify()} hasn't been called yet.*/ public NativeWindow getNativeWindow() { return jawtWindow; } - + public WindowClosingMode getDefaultCloseOperation() { return awtWindowClosingProtocol.getDefaultCloseOperation(); } @@ -373,16 +373,16 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } else { // before native peer is valid: X11 disableBackgroundErase(); - + // creates the native peer super.addNotify(); - + // after native peer is valid: Windows disableBackgroundErase(); - - jawtWindow = NewtFactoryAWT.getNativeWindow(this, null != newtChild ? newtChild.getRequestedCapabilities() : null); + + jawtWindow = NewtFactoryAWT.getNativeWindow(this, null != newtChild ? newtChild.getRequestedCapabilities() : null); jawtWindow.setShallUseOffscreenLayer(shallUseOffscreenLayer); - + if(DEBUG) { // if ( isShowing() == false ) -> Container was not visible yet. // if ( isShowing() == true ) -> Container is already visible. @@ -397,7 +397,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto @Override public void removeNotify() { awtWindowClosingProtocol.removeClosingListener(); - + if( Beans.isDesignTime() ) { super.removeNotify(); } else { @@ -419,7 +419,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto public final void destroy() { destroyImpl(false /* removeNotify */, false /* windowClosing */); } - + private final void destroyImpl(boolean removeNotify, boolean windowClosing) { if( null !=newtChild ) { java.awt.Container cont = AWTMisc.getContainer(this); @@ -427,7 +427,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto System.err.println("NewtCanvasAWT.destroy(removeNotify "+removeNotify+", windowClosing "+windowClosing+"): nw "+newtWinHandleToHexString(newtChild)+", from "+cont); } detachNewtChild(cont); - + if( !removeNotify ) { final Window cWin = newtChild; final Window dWin = cWin.getDelegatedWindow(); @@ -437,14 +437,14 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } else { cWin.destroy(); } - } + } } if( ( removeNotify || windowClosing ) && null!=jawtWindow ) { NewtFactoryAWT.destroyNativeWindow(jawtWindow); jawtWindow=null; - } + } } - + @Override public void paint(Graphics g) { if( validateComponent(true) && !printActive ) { @@ -469,9 +469,9 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } } } - + private volatile boolean printActive = false; - private GLAnimatorControl printAnimator = null; + private GLAnimatorControl printAnimator = null; private GLAutoDrawable printGLAD = null; private AWTTilePainter printAWTTiles = null; @@ -481,15 +481,15 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } return null; } - + @Override public void setupPrint(double scaleMatX, double scaleMatY, int numSamples, int tileWidth, int tileHeight) { - printActive = true; + printActive = true; final int componentCount = isOpaque() ? 3 : 4; final TileRenderer printRenderer = new TileRenderer(); printAWTTiles = new AWTTilePainter(printRenderer, componentCount, scaleMatX, scaleMatY, numSamples, tileWidth, tileHeight, DEBUG); AWTEDTExecutor.singleton.invoke(getTreeLock(), true /* allowOnNonEDT */, true /* wait */, setupPrintOnEDT); - } + } private final Runnable setupPrintOnEDT = new Runnable() { @Override public void run() { @@ -497,14 +497,14 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto if(DEBUG) { System.err.println(getThreadName()+": Info: NewtCanvasAWT setupPrint - skipped GL render, drawable not valid yet"); } - printActive = false; + printActive = false; return; // not yet available .. } if( !isVisible() ) { if(DEBUG) { System.err.println(getThreadName()+": Info: NewtCanvasAWT setupPrint - skipped GL render, drawable visible"); } - printActive = false; + printActive = false; return; // not yet available .. } final GLAutoDrawable glad = getGLAD(); @@ -512,14 +512,14 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto if( DEBUG ) { System.err.println("AWT print.setup exit, newtChild not a GLAutoDrawable: "+newtChild); } - printActive = false; + printActive = false; return; } printAnimator = glad.getAnimator(); if( null != printAnimator ) { printAnimator.remove(glad); } - printGLAD = glad; // _not_ default, shall be replaced by offscreen GLAD + printGLAD = glad; // _not_ default, shall be replaced by offscreen GLAD final GLCapabilities caps = (GLCapabilities)glad.getChosenGLCapabilities().cloneMutable(); final int printNumSamples = printAWTTiles.getNumSamples(caps); GLDrawable printDrawable = printGLAD.getDelegatedDrawable(); @@ -527,7 +527,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto final boolean reqNewGLADSize = printAWTTiles.customTileWidth != -1 && printAWTTiles.customTileWidth != printDrawable.getWidth() || printAWTTiles.customTileHeight != -1 && printAWTTiles.customTileHeight != printDrawable.getHeight(); final boolean reqNewGLADOnscrn = caps.isOnscreen(); - + // It is desired to use a new offscreen GLAD, however Bug 830 forbids this for AA onscreen context. // Bug 830: swapGLContextAndAllGLEventListener and onscreen MSAA w/ NV/GLX final boolean reqNewGLAD = !caps.getSampleBuffers() && ( reqNewGLADOnscrn || reqNewGLADSamples || reqNewGLADSize ); @@ -546,8 +546,8 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto caps.setNumSamples(printNumSamples); } final GLDrawableFactory factory = GLDrawableFactory.getFactory(caps.getGLProfile()); - printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, - printAWTTiles.customTileWidth != -1 ? printAWTTiles.customTileWidth : DEFAULT_PRINT_TILE_SIZE, + printGLAD = factory.createOffscreenAutoDrawable(null, caps, null, + printAWTTiles.customTileWidth != -1 ? printAWTTiles.customTileWidth : DEFAULT_PRINT_TILE_SIZE, printAWTTiles.customTileHeight != -1 ? printAWTTiles.customTileHeight : DEFAULT_PRINT_TILE_SIZE, null); GLDrawableUtil.swapGLContextAndAllGLEventListener(glad, printGLAD); @@ -634,7 +634,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto System.err.println("AWT print.X: "+printAWTTiles); } } - + private final boolean validateComponent(boolean attachNewtChild) { if( Beans.isDesignTime() || !isDisplayable() ) { return false; @@ -645,14 +645,14 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto if( 0 >= getWidth() || 0 >= getHeight() ) { return false; } - + if( attachNewtChild && !newtChildAttached && null != newtChild ) { attachNewtChild(); } return true; } - + private final void configureNewtChild(boolean attach) { if(null!=awtAdapter) { awtAdapter.removeFrom(this); @@ -670,13 +670,13 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto keyboardFocusManager.removePropertyChangeListener("focusOwner", focusPropertyChangeListener); keyboardFocusManager = null; } - + if( null != newtChild ) { newtChild.setKeyboardFocusHandler(null); if(attach) { if(null == jawtWindow.getGraphicsConfiguration()) { throw new InternalError("XXX"); - } + } isOnscreen = jawtWindow.getGraphicsConfiguration().getChosenCapabilities().isOnscreen(); awtAdapter = (AWTParentWindowAdapter) new AWTParentWindowAdapter(jawtWindow, newtChild).addTo(this); awtAdapter.removeWindowClosingFrom(this); // we utilize AWTWindowClosingProtocol triggered destruction! @@ -733,13 +733,13 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto newtChild.reparentWindow(jawtWindow); newtChild.addSurfaceUpdatedListener(jawtWindow); if( jawtWindow.isOffscreenLayerSurfaceEnabled() && - 0 != ( JAWTUtil.JAWT_OSX_CALAYER_QUIRK_POSITION & JAWTUtil.getOSXCALayerQuirks() ) ) { + 0 != ( JAWTUtil.JAWT_OSX_CALAYER_QUIRK_POSITION & JAWTUtil.getOSXCALayerQuirks() ) ) { AWTEDTExecutor.singleton.invoke(false, forceRelayout); } newtChild.setVisible(true); configureNewtChild(true); newtChild.sendWindowEvent(WindowEvent.EVENT_WINDOW_RESIZED); // trigger a resize/relayout to listener - + if(DEBUG) { System.err.println("NewtCanvasAWT.attachNewtChild.X: win "+newtWinHandleToHexString(newtChild)+", EDTUtil: cur "+newtChild.getScreen().getDisplay().getEDTUtil()+", comp "+this); } @@ -759,7 +759,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto System.err.println("NewtCanvasAWT.forceRelayout.X"); } } }; - + private final void detachNewtChild(java.awt.Container cont) { if( null == newtChild || null == jawtWindow || !newtChildAttached ) { return; // nop @@ -773,14 +773,14 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto ", cont "+cont); } - newtChild.removeSurfaceUpdatedListener(jawtWindow); + newtChild.removeSurfaceUpdatedListener(jawtWindow); newtChildAttached = false; newtChild.setFocusAction(null); // no AWT focus traversal .. configureNewtChild(false); newtChild.setVisible(false); - + newtChild.reparentWindow(null); // will destroy context (offscreen -> onscreen) and implicit detachSurfaceLayer - + if(DEBUG) { System.err.println("NewtCanvasAWT.detachNewtChild.X: win "+newtWinHandleToHexString(newtChild)+", EDTUtil: cur "+newtChild.getScreen().getDisplay().getEDTUtil()+", comp "+this); } @@ -837,7 +837,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } protected static String getThreadName() { return Thread.currentThread().getName(); } - + static String newtWinHandleToHexString(Window w) { return null != w ? toHexString(w.getWindowHandle()) : "nil"; } diff --git a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java index c7153840f..9b1b82297 100644 --- a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java +++ b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java @@ -47,12 +47,12 @@ import jogamp.nativewindow.jawt.JAWTUtil; import com.jogamp.newt.awt.NewtCanvasAWT; import com.jogamp.newt.opengl.GLWindow; -/** +/** * Simple GLEventListener deployment as an applet using JOGL. This demo must be * referenced from a web page via an <applet> tag. - * + * *

                          - * Example of an applet tag using GearsES2 within the applet area (normal case): + * Example of an applet tag using GearsES2 within the applet area (normal case): *

                                   <applet width=100 height=100>
                                      <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
                          @@ -65,9 +65,9 @@ import com.jogamp.newt.opengl.GLWindow;
                                   </applet>Hello Gears !
                            *  
                          *

                          - * + * *

                          - * Example of an applet tag using GearsES2 in an undecorated, translucent, closeable and always-on-top window: + * Example of an applet tag using GearsES2 in an undecorated, translucent, closeable and always-on-top window: *

                                   <applet width=1 height=1>
                                      <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
                          @@ -95,12 +95,12 @@ import com.jogamp.newt.opengl.GLWindow;
                           @SuppressWarnings("serial")
                           public class JOGLNewtApplet1Run extends Applet {
                               public static final boolean DEBUG = JOGLNewtAppletBase.DEBUG;
                          -    
                          +
                               GLWindow glWindow = null;
                               NewtCanvasAWT newtCanvasAWT = null;
                               JOGLNewtAppletBase base = null;
                               /** if valid glStandalone:=true (own window) ! */
                          -    int glXd=Integer.MAX_VALUE, glYd=Integer.MAX_VALUE, glWidth=Integer.MAX_VALUE, glHeight=Integer.MAX_VALUE; 
                          +    int glXd=Integer.MAX_VALUE, glYd=Integer.MAX_VALUE, glWidth=Integer.MAX_VALUE, glHeight=Integer.MAX_VALUE;
                           
                               public void init() {
                                   if(DEBUG) {
                          @@ -135,7 +135,7 @@ public class JOGLNewtApplet1Run extends Applet {
                                       glCloseable = JOGLNewtAppletBase.str2Bool(getParameter("gl_closeable"), glCloseable);
                                       glOpaque = JOGLNewtAppletBase.str2Bool(getParameter("gl_opaque"), glOpaque);
                                       glAlphaBits = JOGLNewtAppletBase.str2Int(getParameter("gl_alpha"), glAlphaBits);
                          -            glNumMultisampleBuffer = JOGLNewtAppletBase.str2Int(getParameter("gl_multisamplebuffer"), glNumMultisampleBuffer); 
                          +            glNumMultisampleBuffer = JOGLNewtAppletBase.str2Int(getParameter("gl_multisamplebuffer"), glNumMultisampleBuffer);
                                       glXd = JOGLNewtAppletBase.str2Int(getParameter("gl_dx"), glXd);
                                       glYd = JOGLNewtAppletBase.str2Int(getParameter("gl_dy"), glYd);
                                       glWidth = JOGLNewtAppletBase.str2Int(getParameter("gl_width"), glWidth);
                          @@ -168,8 +168,8 @@ public class JOGLNewtApplet1Run extends Applet {
                                       System.err.println("glNumMultisampleBuffer: "+glNumMultisampleBuffer);
                                       System.err.println("glNoDefaultKeyListener: "+glNoDefaultKeyListener);
                                   }
                          -        
                          -        base = new JOGLNewtAppletBase(glEventListenerClazzName, 
                          +
                          +        base = new JOGLNewtAppletBase(glEventListenerClazzName,
                                                                 glSwapInterval,
                                                                 glNoDefaultKeyListener,
                                                                 glCloseable,
                          @@ -252,9 +252,9 @@ public class JOGLNewtApplet1Run extends Applet {
                                       System.err.println("GLWindow: "+glWindow);
                                   }
                                   base.start();
                          -        if( null != newtCanvasAWT && 
                          +        if( null != newtCanvasAWT &&
                                       newtCanvasAWT.isOffscreenLayerSurfaceEnabled() &&
                          -            0 != ( JAWTUtil.JAWT_OSX_CALAYER_QUIRK_POSITION & JAWTUtil.getOSXCALayerQuirks() ) ) {          
                          +            0 != ( JAWTUtil.JAWT_OSX_CALAYER_QUIRK_POSITION & JAWTUtil.getOSXCALayerQuirks() ) ) {
                                       // force relayout
                                       final int cW = newtCanvasAWT.getWidth();
                                       final int cH = newtCanvasAWT.getHeight();
                          diff --git a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java
                          index 1004adb8e..a6a30a8bf 100644
                          --- a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java
                          +++ b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java
                          @@ -57,7 +57,7 @@ import com.jogamp.opengl.util.Animator;
                           
                           public class JOGLNewtAppletBase implements KeyListener, GLEventListener {
                               public static final boolean DEBUG = Debug.debug("Applet");
                          -    
                          +
                               String glEventListenerClazzName;
                               int glSwapInterval;
                               boolean noDefaultKeyListener;
                          @@ -71,13 +71,13 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener {
                               boolean isValid = false;
                               NativeWindow awtParent;
                           
                          -    public JOGLNewtAppletBase(String glEventListenerClazzName, 
                          +    public JOGLNewtAppletBase(String glEventListenerClazzName,
                                                         int glSwapInterval,
                                                         boolean noDefaultKeyListener,
                                                         boolean glClosable,
                                                         boolean glDebug,
                                                         boolean glTrace) {
                          -    
                          +
                                   this.glEventListenerClazzName=glEventListenerClazzName;
                                   this.glSwapInterval=glSwapInterval;
                                   this.noDefaultKeyListener = noDefaultKeyListener;
                          @@ -174,8 +174,8 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener {
                                                               glWindow.reparentWindow(awtParent);
                                                           }
                                                          }
                          -                            }).start();                         
                          -                        }                        
                          +                            }).start();
                          +                        }
                                               }
                                           } } );
                           
                          @@ -203,7 +203,7 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener {
                                       if(glEventListener instanceof KeyListener) {
                                           glWindow.addKeyListener((KeyListener)glEventListener);
                                       }
                          -            
                          +
                                       if(!noDefaultKeyListener) {
                                           glWindow.addKeyListener(this);
                                       }
                          @@ -216,7 +216,7 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener {
                                       glAnimator.setThreadGroup(tg);
                                       glAnimator.add(glWindow);
                                       glAnimator.setUpdateFPSFrames(FPSCounter.DEFAULT_FRAMES_PER_INTERVAL, null);
                          -            
                          +
                                   } catch (Throwable t) {
                                       throw new RuntimeException(t);
                                   }
                          @@ -262,14 +262,14 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener {
                                   if(glDebug) {
                                       try {
                                           _gl = _gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Debug", null, _gl, null) );
                          -            } catch (Exception e) {e.printStackTrace();} 
                          +            } catch (Exception e) {e.printStackTrace();}
                                   }
                           
                                   if(glTrace) {
                                       try {
                                           // Trace ..
                                           _gl = _gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Trace", null, _gl, new Object[] { System.err } ) );
                          -            } catch (Exception e) {e.printStackTrace();} 
                          +            } catch (Exception e) {e.printStackTrace();}
                                   }
                           
                                   if(glSwapInterval>=0) {
                          @@ -317,9 +317,9 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener {
                                       }
                                  }
                               }
                          -    
                          +
                               @Override
                          -    public void keyReleased(KeyEvent e) { 
                          +    public void keyReleased(KeyEvent e) {
                               }
                           }
                           
                          diff --git a/src/newt/classes/com/jogamp/newt/event/DoubleTapScrollGesture.java b/src/newt/classes/com/jogamp/newt/event/DoubleTapScrollGesture.java
                          index bc67cbee6..7dda47534 100644
                          --- a/src/newt/classes/com/jogamp/newt/event/DoubleTapScrollGesture.java
                          +++ b/src/newt/classes/com/jogamp/newt/event/DoubleTapScrollGesture.java
                          @@ -41,15 +41,15 @@ import jogamp.newt.Debug;
                            *
                            *    - touchSlop (scaled in pixels):
                            *       - Min. movement w/ 2 pointer within ScaledDoubleTapSlop starting 'scroll' mode
                          - *       
                          + *
                            *    - Avoid computation if not within gesture, especially for MOVE/DRAG
                          - *    
                          + *
                            *    - Only allow gesture to start with PRESS
                          - *    
                          - *    - Leave gesture completely with RELEASE of both/all fingers, or dist-diff exceeds doubleTapSlop 
                          - *    
                          + *
                          + *    - Leave gesture completely with RELEASE of both/all fingers, or dist-diff exceeds doubleTapSlop
                          + *
                            *    - Tolerate temporary lift 1 of 2 pointer
                          - *    
                          + *
                            *     - Always validate pointer-id
                            * 
                          *

                          @@ -74,27 +74,27 @@ public class DoubleTapScrollGesture implements GestureHandler { public static final int SCROLL_SLOP_PIXEL; /** Two pointer 'double tap' slop in pixels (fallback), defaults to 104 pixels. Can be overriden by integer property newt.event.double_tap_slop_pixel.*/ public static final int DOUBLE_TAP_SLOP_PIXEL; - + /** Scroll threshold in millimeter, defaults to 3 mm. Can be overriden by integer property newt.event.scroll_slop_mm.*/ public static final float SCROLL_SLOP_MM; /** Two pointer 'double tap' slop in millimeter, defaults to 20 mm. Can be overriden by integer property newt.event.double_tap_slop_mm.*/ public static final float DOUBLE_TAP_SLOP_MM; - + static { Debug.initSingleton(); - + SCROLL_SLOP_PIXEL = Debug.getIntProperty("newt.event.scroll_slop_pixel", true, 16); DOUBLE_TAP_SLOP_PIXEL = Debug.getIntProperty("newt.event.double_tap_slop_pixel", true, 104); SCROLL_SLOP_MM = Debug.getIntProperty("newt.event.scroll_slop_mm", true, 3); DOUBLE_TAP_SLOP_MM = Debug.getIntProperty("newt.event.double_tap_slop_mm", true, 20); } - + private static final int ST_NONE = 0; private static final int ST_1PRESS = 1; private static final int ST_2PRESS_T = 2; private static final int ST_2PRESS_C = 3; private static final int ST_SCROLL = 4; - + private final int scrollSlop, scrollSlopSquare, doubleTapSlop, doubleTapSlopSquare; private final float[] scrollDistance = new float[] { 0f, 0f }; private int[] pIds = new int[] { -1, -1 }; @@ -104,18 +104,18 @@ public class DoubleTapScrollGesture implements GestureHandler { private int lastX, lastY; private int pointerDownCount; private MouseEvent hitGestureEvent; - + private static final int getSquareDistance(float x1, float y1, float x2, float y2) { final int deltaX = (int) x1 - (int) x2; final int deltaY = (int) y1 - (int) y2; return deltaX * deltaX + deltaY * deltaY; } - + private int gesturePointers(final MouseEvent e, final int excludeIndex) { - int j = 0; + int j = 0; for(int i=e.getPointerCount()-1; i>=0; i--) { if( excludeIndex != i ) { - final int id = e.getPointerId(i); + final int id = e.getPointerId(i); if( pIds[0] == id || pIds[1] == id ) { j++; } @@ -123,10 +123,10 @@ public class DoubleTapScrollGesture implements GestureHandler { } return j; } - + /** * scaledScrollSlop < scaledDoubleTapSlop - * @param scaledScrollSlop Distance a pointer can wander before we think the user is scrolling in pixels. + * @param scaledScrollSlop Distance a pointer can wander before we think the user is scrolling in pixels. * @param scaledDoubleTapSlop Distance in pixels between the first touch and second touch to still be considered a double tap. */ public DoubleTapScrollGesture(int scaledScrollSlop, int scaledDoubleTapSlop) { @@ -137,9 +137,9 @@ public class DoubleTapScrollGesture implements GestureHandler { pointerDownCount = 0; clear(true); if(DEBUG) { - System.err.println("DoubleTapScroll scrollSlop (scaled) "+scrollSlop); - System.err.println("DoubleTapScroll doubleTapSlop (scaled) "+doubleTapSlop); - } + System.err.println("DoubleTapScroll scrollSlop (scaled) "+scrollSlop); + System.err.println("DoubleTapScroll doubleTapSlop (scaled) "+doubleTapSlop); + } } public String toString() { @@ -160,17 +160,17 @@ public class DoubleTapScrollGesture implements GestureHandler { lastY = 0; } } - + @Override public boolean isWithinGesture() { return ST_2PRESS_C <= gestureState; } - + @Override public boolean hasGesture() { return null != hitGestureEvent; } - + @Override public InputEvent getGestureEvent() { if( null != hitGestureEvent ) { @@ -184,17 +184,17 @@ public class DoubleTapScrollGesture implements GestureHandler { modifiers |= com.jogamp.newt.event.InputEvent.SHIFT_MASK; } return new MouseEvent(MouseEvent.EVENT_MOUSE_WHEEL_MOVED, ge.getSource(), ge.getWhen(), modifiers, - ge.getAllPointerTypes(), ge.getAllPointerIDs(), - ge.getAllX(), ge.getAllY(), ge.getAllPressures(), ge.getMaxPressure(), + ge.getAllPointerTypes(), ge.getAllPointerIDs(), + ge.getAllX(), ge.getAllY(), ge.getAllPressures(), ge.getMaxPressure(), ge.getButton(), ge.getClickCount(), rotationXYZ, scrollSlop); } return null; } - + public final float[] getScrollDistanceXY() { return scrollDistance; } - + @Override public boolean process(final InputEvent in) { if( null != hitGestureEvent || !(in instanceof MouseEvent) ) { @@ -220,7 +220,7 @@ public class DoubleTapScrollGesture implements GestureHandler { final int y1 = pe.getY(1); final int xm = (x0+x1)/2; final int ym = (y0+y1)/2; - + if( ST_1PRESS == gestureState ) { final int sqDist = getSquareDistance(x0, y0, x1, y1); final boolean isDistWithinDoubleTapSlop = sqDist < doubleTapSlopSquare; @@ -254,7 +254,7 @@ public class DoubleTapScrollGesture implements GestureHandler { System.err.println(this+".pressed: gPtr "+gPtr+", this "+lastX+"/"+lastY+", "+pe); } } break; - + case MouseEvent.EVENT_MOUSE_RELEASED: { pointerDownCount--; // lifted final int gPtr = gesturePointers(pe, 0); // w/o lifted pointer @@ -269,7 +269,7 @@ public class DoubleTapScrollGesture implements GestureHandler { System.err.println(this+".released: gPtr "+gPtr+", "+pe); } } break; - + case MouseEvent.EVENT_MOUSE_DRAGGED: { if( 2 == pointerDownCount && ST_1PRESS < gestureState ) { final int gPtr = gesturePointers(pe, -1); @@ -289,11 +289,11 @@ public class DoubleTapScrollGesture implements GestureHandler { gestureState = ST_SCROLL; } } break; - + case ST_2PRESS_C: gestureState = ST_SCROLL; break; - + case ST_SCROLL: scrollDistance[0] = lastX - xm; scrollDistance[1] = lastY - ym; @@ -338,7 +338,7 @@ public class DoubleTapScrollGesture implements GestureHandler { } } } break; - + default: } return null != hitGestureEvent; diff --git a/src/newt/classes/com/jogamp/newt/event/GestureHandler.java b/src/newt/classes/com/jogamp/newt/event/GestureHandler.java index 2c8f29bb7..2e98a8a01 100644 --- a/src/newt/classes/com/jogamp/newt/event/GestureHandler.java +++ b/src/newt/classes/com/jogamp/newt/event/GestureHandler.java @@ -30,7 +30,7 @@ package com.jogamp.newt.event; import jogamp.newt.Debug; /** - * Generic gesture handler interface designed to allow pass-through + * Generic gesture handler interface designed to allow pass-through * filtering of {@link InputEvent}s. *

                          * To avoid negative impact on event processing, @@ -44,18 +44,18 @@ import jogamp.newt.Debug; */ public interface GestureHandler { public static final boolean DEBUG = Debug.debug("Window.MouseEvent"); - + /** A custom gesture event */ @SuppressWarnings("serial") public static class GestureEvent extends InputEvent { /** A gesture has been detected. */ public static final short EVENT_GESTURE_DETECTED = 400; - + private final GestureHandler handler; - + /** * Creates a gesture event with default type {@link #EVENT_GESTURE_DETECTED}. - * + * * @param source * @param when * @param modifiers @@ -65,7 +65,7 @@ public interface GestureHandler { super(EVENT_GESTURE_DETECTED, source, when, modifiers); this.handler = handler; } - + /** * Creates a gesture event with custom event_type ! * @param event_type must lie within [400..599] @@ -78,14 +78,14 @@ public interface GestureHandler { super(event_type, source, when, modifiers); this.handler = handler; } - + /** Return the {@link GestureHandler}, which produced the event. */ public final GestureHandler getHandler() { return handler; } } - + /** * Listener for {@link GestureEvent}s. - * + * * @see GestureEvent */ public static interface GestureListener extends NEWTEventListener @@ -93,50 +93,50 @@ public interface GestureHandler { /** {@link GestureHandler} {@link GestureHandler#hasGesture() has detected} the gesture. */ public void gestureDetected(GestureEvent gh); } - - /** - * Clears state of handler, i.e. resets all states incl. previous detected gesture. + + /** + * Clears state of handler, i.e. resets all states incl. previous detected gesture. * @param clearStarted if true, also clears {@link #isWithinGesture() started} state, * otherwise stay within gesture - if appropriate. - * Staying within a gesture allows fluent continuous gesture sequence, - * e.g. for scrolling. + * Staying within a gesture allows fluent continuous gesture sequence, + * e.g. for scrolling. */ public void clear(boolean clearStarted); - - /** + + /** * Returns true if a previous {@link #process(InputEvent)} command produced a gesture, - * which has not been {@link #clear(boolean) cleared}. + * which has not been {@link #clear(boolean) cleared}. * Otherwise returns false. - */ + */ public boolean hasGesture(); - - /** + + /** * Returns the corresponding {@link InputEvent} for the gesture as detected by * a previous {@link #process(InputEvent)}, which has not been {@link #clear(boolean) cleared}. * Otherwise returns null. *

                          * Only implemented for gestures mapping to {@link InputEvent}s. - *

                          - */ + *

                          + */ public InputEvent getGestureEvent(); - - /** + + /** * Returns true if within a gesture as detected by a previous {@link #process(InputEvent)} command, - * which has not been {@link #clear(boolean) cleared}. + * which has not been {@link #clear(boolean) cleared}. * Otherwise returns false. - */ + */ public boolean isWithinGesture(); /** * Process the given {@link InputEvent} and returns true if it produced the gesture. * Otherwise returns false. *

                          - * If a gesture was already detected previously and has not been cleared, - * method does not process the event and returns true. + * If a gesture was already detected previously and has not been cleared, + * method does not process the event and returns true. *

                          *

                          - * Besides validation of the event's details, - * the handler may also validate the {@link InputEvent.InputClass} and/or {@link InputEvent.InputType}. + * Besides validation of the event's details, + * the handler may also validate the {@link InputEvent.InputClass} and/or {@link InputEvent.InputType}. *

                          */ public boolean process(InputEvent e); diff --git a/src/newt/classes/com/jogamp/newt/event/InputEvent.java b/src/newt/classes/com/jogamp/newt/event/InputEvent.java index 1bd67efa5..6520dafcf 100644 --- a/src/newt/classes/com/jogamp/newt/event/InputEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/InputEvent.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package com.jogamp.newt.event; @@ -43,17 +43,17 @@ public abstract class InputEvent extends NEWTEvent /** Interface marking class of input types */ public static interface InputClass { } - + /** Interface marking type of input devices */ public static interface InputType { } - + public static final int SHIFT_MASK = 1 << 0; public static final int CTRL_MASK = 1 << 1; public static final int META_MASK = 1 << 2; public static final int ALT_MASK = 1 << 3; public static final int ALT_GRAPH_MASK = 1 << 4; - + public static final int BUTTON1_MASK = 1 << 5; public static final int BUTTON2_MASK = 1 << 6; public static final int BUTTON3_MASK = 1 << 7; @@ -63,23 +63,23 @@ public abstract class InputEvent extends NEWTEvent public static final int BUTTON7_MASK = 1 << 11; public static final int BUTTON8_MASK = 1 << 12; public static final int BUTTON9_MASK = 1 << 13; - + public static final int BUTTONLAST_MASK = 1 << 20; // 16 buttons public static final int BUTTONALL_MASK = 0xffff << 5 ; // 16 buttons - + /** Event is caused by auto-repeat. */ public static final int AUTOREPEAT_MASK = 1 << 29; - + /** Pointer is confined, see {@link Window#confinePointer(boolean)}. */ public static final int CONFINED_MASK = 1 << 30; - + /** Pointer is invisible, see {@link Window#setPointerVisible(boolean)}. */ public static final int INVISIBLE_MASK = 1 << 31; - /** + /** * Returns the corresponding button mask for the given button. *

                          - * In case the given button lies outside + * In case the given button lies outside * of the valid range [{@link MouseEvent#BUTTON1} .. {@link MouseEvent#BUTTON_COUNT}], * null is returned. *

                          @@ -90,7 +90,7 @@ public abstract class InputEvent extends NEWTEvent } return 0; } - + protected InputEvent(short eventType, Object source, long when, int modifiers) { super(eventType, source, when); this.modifiers=modifiers; @@ -128,11 +128,11 @@ public abstract class InputEvent extends NEWTEvent public boolean isConfined() { return (modifiers&CONFINED_MASK)!=0; } - /** {@link #getModifiers()} contains {@link #INVISIBLE_MASK}. Pointer is invisible, see {@link Window#setPointerVisible(boolean)}. */ + /** {@link #getModifiers()} contains {@link #INVISIBLE_MASK}. Pointer is invisible, see {@link Window#setPointerVisible(boolean)}. */ public boolean isInvisible() { return (modifiers&INVISIBLE_MASK)!=0; } - + public StringBuilder getModifiersString(StringBuilder sb) { if(null == sb) { sb = new StringBuilder(); @@ -141,7 +141,7 @@ public abstract class InputEvent extends NEWTEvent boolean isFirst = true; if(isShiftDown()) { if(!isFirst) { sb.append(", "); } isFirst = false; sb.append("shift"); } if(isControlDown()) { if(!isFirst) { sb.append(", "); } isFirst = false; sb.append("ctrl"); } - if(isMetaDown()) { if(!isFirst) { sb.append(", "); } isFirst = false; sb.append("meta"); } + if(isMetaDown()) { if(!isFirst) { sb.append(", "); } isFirst = false; sb.append("meta"); } if(isAltDown()) { if(!isFirst) { sb.append(", "); } isFirst = false; sb.append("alt"); } if(isAltGraphDown()) { if(!isFirst) { sb.append(", "); } isFirst = false; sb.append("altgr"); } if(isAutoRepeat()) { if(!isFirst) { sb.append(", "); } isFirst = false; sb.append("repeat"); } @@ -151,18 +151,18 @@ public abstract class InputEvent extends NEWTEvent if(isConfined()) { if(!isFirst) { sb.append(", "); } isFirst = false; sb.append("confined"); } if(isInvisible()) { if(!isFirst) { sb.append(", "); } isFirst = false; sb.append("invisible"); } sb.append("]"); - + return sb; } /** * See also {@link MouseEvent}'s section about Multiple-Pointer Events. - * @return Array of pressed mouse buttons [{@link MouseEvent#BUTTON1} .. {@link MouseEvent#BUTTON6}]. + * @return Array of pressed mouse buttons [{@link MouseEvent#BUTTON1} .. {@link MouseEvent#BUTTON6}]. * If none is down, the resulting array is of length 0. */ public final short[] getButtonsDown() { final int len = getButtonDownCount(); - + final short[] res = new short[len]; int j = 0; for(int i=1; i<=MouseEvent.BUTTON_COUNT; i++) { @@ -174,13 +174,13 @@ public abstract class InputEvent extends NEWTEvent /** * See also {@link MouseEvent}'s section about Multiple-Pointer Events. * @param button the button to test - * @return true if the given button is down + * @return true if the given button is down */ public final boolean isButtonDown(int button) { return ( modifiers & getButtonMask(button) ) != 0; } - /** + /** * Returns the number of pressed buttons by counting the set bits: *
                             *     getBitCount(modifiers & BUTTONALL_MASK);
                          @@ -194,8 +194,8 @@ public abstract class InputEvent extends NEWTEvent
                            public final int getButtonDownCount() {
                                return IntBitfield.getBitCount(modifiers & BUTTONALL_MASK);
                            }
                          - 
                          - /** 
                          +
                          + /**
                             * Returns true if at least one button is pressed, otherwise false:
                             * 
                             *     0 != ( modifiers & BUTTONALL_MASK )
                          @@ -209,11 +209,11 @@ public abstract class InputEvent extends NEWTEvent
                            public final boolean isAnyButtonDown() {
                                return 0 != ( modifiers & BUTTONALL_MASK );
                            }
                          - 
                          +
                            public String toString() {
                                return toString(null).toString();
                            }
                          - 
                          +
                            public StringBuilder toString(StringBuilder sb) {
                                if(null == sb) {
                                    sb = new StringBuilder();
                          diff --git a/src/newt/classes/com/jogamp/newt/event/KeyAdapter.java b/src/newt/classes/com/jogamp/newt/event/KeyAdapter.java
                          index 42ebea722..a89148574 100644
                          --- a/src/newt/classes/com/jogamp/newt/event/KeyAdapter.java
                          +++ b/src/newt/classes/com/jogamp/newt/event/KeyAdapter.java
                          @@ -4,14 +4,14 @@
                            *
                            * Redistribution and use in source and binary forms, with or without modification, are
                            * permitted provided that the following conditions are met:
                          - * 
                          + *
                            *    1. Redistributions of source code must retain the above copyright notice, this list of
                            *       conditions and the following disclaimer.
                          - * 
                          + *
                            *    2. 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.
                          - * 
                          + *
                            * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR
                          @@ -21,12 +21,12 @@
                            * 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.
                          - * 
                          + *
                            * The views and conclusions contained in the software and documentation are those of the
                            * authors and should not be interpreted as representing official policies, either expressed
                            * or implied, of JogAmp Community.
                            */
                          - 
                          +
                           package com.jogamp.newt.event;
                           
                           public abstract class KeyAdapter implements KeyListener
                          diff --git a/src/newt/classes/com/jogamp/newt/event/KeyEvent.java b/src/newt/classes/com/jogamp/newt/event/KeyEvent.java
                          index 085f598dc..81680bf32 100644
                          --- a/src/newt/classes/com/jogamp/newt/event/KeyEvent.java
                          +++ b/src/newt/classes/com/jogamp/newt/event/KeyEvent.java
                          @@ -1,22 +1,22 @@
                           /*
                            * Copyright (c) 2008 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
                          @@ -29,7 +29,7 @@
                            * 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.
                          - * 
                          + *
                            */
                           
                           package com.jogamp.newt.event;
                          @@ -37,8 +37,8 @@ package com.jogamp.newt.event;
                           import com.jogamp.common.util.IntBitfield;
                           
                           /**
                          - * 
                          KeyEvent Delivery
                          - * + *
                          KeyEvent Delivery
                          + * * Key events are delivered in the following order: *

                          * @@ -48,10 +48,10 @@ import com.jogamp.common.util.IntBitfield; *
                          *

                          * In case the native platform does not - * deliver keyboard events in the above order or skip events, - * the NEWT driver will reorder and inject synthetic events if required. + * deliver keyboard events in the above order or skip events, + * the NEWT driver will reorder and inject synthetic events if required. *

                          - * Besides regular modifiers like {@link InputEvent#SHIFT_MASK} etc., + * Besides regular modifiers like {@link InputEvent#SHIFT_MASK} etc., * the {@link InputEvent#AUTOREPEAT_MASK} bit is added if repetition is detected, following above constraints. *

                          *

                          @@ -60,38 +60,38 @@ import com.jogamp.common.util.IntBitfield; P = pressed, R = released 0 = normal, 1 = auto-repeat - P(0), [ R(1), P(1), R(1), ..], R(0) + P(0), [ R(1), P(1), R(1), ..], R(0) *

                          * The idea is if you mask out auto-repeat in your event listener * you just get one long pressed P/R tuple for {@link #isPrintableKey() printable} and {@link #isActionKey() Action} keys. *

                          *

                          - * {@link #isActionKey() Action} keys will produce {@link #EVENT_KEY_PRESSED pressed} + * {@link #isActionKey() Action} keys will produce {@link #EVENT_KEY_PRESSED pressed} * and {@link #EVENT_KEY_RELEASED released} events including {@link #isAutoRepeat() auto-repeat}. *

                          *

                          * {@link #isPrintableKey() Printable} keys will produce {@link #EVENT_KEY_PRESSED pressed} and {@link #EVENT_KEY_RELEASED released} events. *

                          *

                          - * {@link #isModifierKey() Modifier} keys will produce {@link #EVENT_KEY_PRESSED pressed} and {@link #EVENT_KEY_RELEASED released} events + * {@link #isModifierKey() Modifier} keys will produce {@link #EVENT_KEY_PRESSED pressed} and {@link #EVENT_KEY_RELEASED released} events * excluding {@link #isAutoRepeat() auto-repeat}. * They will also influence subsequent event's {@link #getModifiers() modifier} bits while pressed. *

                          - * + * *
                          Unicode Mapping
                          *

                          - * {@link #getKeyChar() Key-chars}, as well as + * {@link #getKeyChar() Key-chars}, as well as * {@link #isPrintableKey() printable} {@link #getKeyCode() key-codes} and {@link #getKeySymbol() key-symbols} - * use the UTF-16 unicode space w/o collision. - * + * use the UTF-16 unicode space w/o collision. + * *

                          *

                          - * Non-{@link #isPrintableKey() printable} {@link #getKeyCode() key-codes} and {@link #getKeySymbol() key-symbols}, + * Non-{@link #isPrintableKey() printable} {@link #getKeyCode() key-codes} and {@link #getKeySymbol() key-symbols}, * i.e. {@link #isModifierKey() modifier-} and {@link #isActionKey() action-}keys, * are mapped to unicode's control and private range and do not collide w/ {@link #isPrintableKey() printable} unicode values * with the following exception. *

                          - * + * *
                          Unicode Collision
                          *

                          * The following {@link #getKeyCode() Key-code}s and {@link #getKeySymbol() key-symbol}s collide w/ unicode space:
                          @@ -103,9 +103,9 @@ import com.jogamp.common.util.IntBitfield; *

                          * Collision was chosen for {@link #getKeyCode() Key-code} and {@link #getKeySymbol() key-symbol} mapping * to allow a minimal code range, i.e. [0..255]. - * The reduced code range in turn allows the implementation to utilize fast and small lookup tables, - * e.g. to implement a key-press state tracker. - *

                          + * The reduced code range in turn allows the implementation to utilize fast and small lookup tables, + * e.g. to implement a key-press state tracker. + *

                          *
                            * http://www.utf8-chartable.de/unicode-utf8-table.pl
                            * http://www.unicode.org/Public/5.1.0/ucd/PropList.txt
                          @@ -136,7 +136,7 @@ public class KeyEvent extends InputEvent
                                           }
                                       }
                                       flags = _flags;
                          -            
                          +
                                       //
                                       // Validate flags
                                       //
                          @@ -147,12 +147,12 @@ public class KeyEvent extends InputEvent
                                       }
                                   }
                               }
                          -    
                          +
                               public static KeyEvent create(short eventType, Object source, long when, int modifiers, short keyCode, short keySym, char keyChar) {
                                   return new KeyEvent(eventType, source, when, modifiers, keyCode, keySym, getModifierMask(keySym), keyChar);
                               }
                           
                          -    /** 
                          +    /**
                                * Returns the UTF-16 character reflecting the {@link #getKeySymbol() key symbol}
                                * incl. active {@link #isModifierKey() modifiers}.
                                * @see #getKeySymbol()
                          @@ -162,12 +162,12 @@ public class KeyEvent extends InputEvent
                                   return keyChar;
                               }
                           
                          -    /** 
                          +    /**
                                * Returns the virtual key symbol reflecting the current keyboard layout.
                                * 

                          * For {@link #isPrintableKey() printable keys}, the key symbol is the {@link #isModifierKey() unmodified} - * representation of the UTF-16 {@link #getKeyChar() key char}.
                          - * E.g. symbol [{@link #VK_A}, 'A'] for char 'a'. + * representation of the UTF-16 {@link #getKeyChar() key char}.
                          + * E.g. symbol [{@link #VK_A}, 'A'] for char 'a'. *

                          * @see #isPrintableKey() * @see #getKeyChar() @@ -176,18 +176,18 @@ public class KeyEvent extends InputEvent public final short getKeySymbol() { return keySym; } - - /** + + /** * Returns the virtual key code using a fixed mapping to the US keyboard layout. *

                          - * In contrast to {@link #getKeySymbol() key symbol}, key code - * uses a fixed US keyboard layout and therefore is keyboard layout independent. + * In contrast to {@link #getKeySymbol() key symbol}, key code + * uses a fixed US keyboard layout and therefore is keyboard layout independent. *

                          *

                          - * E.g. virtual key code {@link #VK_Y} denotes the same physical key - * regardless whether keyboard layout QWERTY or + * E.g. virtual key code {@link #VK_Y} denotes the same physical key + * regardless whether keyboard layout QWERTY or * QWERTZ is active. The {@link #getKeySymbol() key symbol} of the former is - * {@link #VK_Y}, where the latter produces {@link #VK_Y}. + * {@link #VK_Y}, where the latter produces {@link #VK_Y}. *

                          * @see #getKeyChar() * @see #getKeySymbol() @@ -228,9 +228,9 @@ public class KeyEvent extends InputEvent } return (short) keyChar; } - - /** - * Returns true if the given virtualKey represents a modifier key, otherwise false. + + /** + * Returns true if the given virtualKey represents a modifier key, otherwise false. *

                          * A modifier key is one of {@link #VK_SHIFT}, {@link #VK_CONTROL}, {@link #VK_ALT}, {@link #VK_ALT_GRAPH}, {@link #VK_META}. *

                          @@ -247,10 +247,10 @@ public class KeyEvent extends InputEvent return false; } } - + /** * If vKey is a {@link #isModifierKey() modifier key}, method returns the corresponding modifier mask, - * otherwise 0. + * otherwise 0. */ public static int getModifierMask(short vKey) { switch (vKey) { @@ -266,10 +266,10 @@ public class KeyEvent extends InputEvent } return 0; } - - /** + + /** * Returns true if {@link #getKeySymbol() key symbol} represents a modifier key, - * otherwise false. + * otherwise false. *

                          * See {@link #isModifierKey(short)} for details. *

                          @@ -280,8 +280,8 @@ public class KeyEvent extends InputEvent public final boolean isModifierKey() { return 0 != ( F_MODIFIER_MASK & flags ) ; } - - /** + + /** * Returns true if {@link #getKeySymbol() key symbol} represents a non-printable and * non-{@link #isModifierKey(short) modifier} action key, otherwise false. *

                          @@ -289,12 +289,12 @@ public class KeyEvent extends InputEvent * A = U - ( P + M ) *

                          * @see #isPrintableKey() - * @see #isModifierKey() + * @see #isModifierKey() */ public final boolean isActionKey() { return 0 != ( F_ACTION_MASK & flags ) ; } - + /** * Returns true if given uniChar represents a printable character, * i.e. a value other than {@link #VK_UNDEFINED} and not a control or non-printable private code. @@ -307,7 +307,7 @@ public class KeyEvent extends InputEvent *

                          * Distinction of key character and virtual key code is made due to unicode collision. *

                          - * + * * @param uniChar the UTF-16 unicode value, which maybe a virtual key code or key character. * @param isKeyChar true if uniChar is a key character, otherwise a virtual key code */ @@ -333,9 +333,9 @@ public class KeyEvent extends InputEvent return VK_UNDEFINED != uniChar; } - /** - * Returns true if {@link #getKeySymbol() key symbol} and {@link #getKeyChar() key char} - * represents a printable character, i.e. a value other than {@link #VK_UNDEFINED} + /** + * Returns true if {@link #getKeySymbol() key symbol} and {@link #getKeyChar() key char} + * represents a printable character, i.e. a value other than {@link #VK_UNDEFINED} * and not a control or non-printable private code. *

                          * A printable character is neither a {@link #isModifierKey(short) modifier key}, nor an {@link #isActionKey(short) action key}. @@ -347,7 +347,7 @@ public class KeyEvent extends InputEvent public final boolean isPrintableKey() { return 0 != ( F_PRINTABLE_MASK & flags ) ; } - + private final short keyCode; private final short keySym; private final char keyChar; @@ -370,7 +370,7 @@ public class KeyEvent extends InputEvent public static class NonPrintableRange { /** min. unicode value, inclusive */ - public short min; + public short min; /** max. unicode value, inclusive */ public short max; /** true if valid for keyChar values as well, otherwise only valid for keyCode and keySym due to collision. */ @@ -381,7 +381,7 @@ public class KeyEvent extends InputEvent this.inclKeyChar = inclKeyChar; } }; - /** + /** * Non printable key ranges, currently fixed to an array of size 4. *

                          * Not included, queried upfront: @@ -390,98 +390,98 @@ public class KeyEvent extends InputEvent *

                        • {@link #VK_TAB}
                        • *
                        • {@link #VK_ENTER}
                        • * - *

                          + *

                          */ - public final static NonPrintableRange[] nonPrintableKeys = { + public final static NonPrintableRange[] nonPrintableKeys = { new NonPrintableRange( (short)0x0000, (short)0x001F, true ), // Unicode: Non printable controls: [0x00 - 0x1F], see exclusion above new NonPrintableRange( (short)0x0061, (short)0x0078, false), // Small 'a' thru 'z' (0x61 - 0x7a) - Not used for keyCode / keySym - Re-used for Fn (collision) - new NonPrintableRange( (short)0x008F, (short)0x009F, true ), // Unicode: Non printable controls: [0x7F - 0x9F], Numpad keys [0x7F - 0x8E] are printable! + new NonPrintableRange( (short)0x008F, (short)0x009F, true ), // Unicode: Non printable controls: [0x7F - 0x9F], Numpad keys [0x7F - 0x8E] are printable! new NonPrintableRange( (short)0xE000, (short)0xF8FF, true ) // Unicode: Private 0xE000 - 0xF8FF (Marked Non-Printable) }; - + // // Unicode: Non printable controls: [0x00 - 0x1F] // - + /** * This value, {@value}, is used to indicate that the keyCode is unknown. */ public static final short VK_UNDEFINED = (short) 0x0; - + static final short VK_FREE01 = (short) 0x01; - + /** Constant for the HOME function key. ASCII: Start Of Text. */ public static final short VK_HOME = (short) 0x02; - + /** Constant for the END function key. ASCII: End Of Text. */ public static final short VK_END = (short) 0x03; - + /** Constant for the END function key. ASCII: End Of Transmission. */ public static final short VK_FINAL = (short) 0x04; /** Constant for the PRINT function key. ASCII: Enquiry. */ public static final short VK_PRINTSCREEN = (short) 0x05; - + static final short VK_FREE06 = (short) 0x06; static final short VK_FREE07 = (short) 0x07; - + /** Constant for the BACK SPACE key "\b", matching ASCII. Printable! */ public static final short VK_BACK_SPACE = (short) 0x08; - + /** Constant for the HORIZ TAB key "\t", matching ASCII. Printable! */ public static final short VK_TAB = (short) 0x09; - + /** LINE_FEED "\n", matching ASCII, n/a on keyboard. */ static final short VK_FREE0A = (short) 0x0A; - + /** Constant for the PAGE DOWN function key. ASCII: Vertical Tabulation. */ public static final short VK_PAGE_DOWN = (short) 0x0B; - + /** Constant for the CLEAR key, i.e. FORM FEED, matching ASCII. */ public static final short VK_CLEAR = (short) 0x0C; - + /** Constant for the ENTER key, i.e. CARRIAGE RETURN, matching ASCII. Printable! */ public static final short VK_ENTER = (short) 0x0D; - + static final short VK_FREE0E = (short) 0x0E; - + /** Constant for the CTRL function key. ASCII: shift-in. */ public static final short VK_SHIFT = (short) 0x0F; /** Constant for the PAGE UP function key. ASCII: Data Link Escape. */ public static final short VK_PAGE_UP = (short) 0x10; - + /** Constant for the CTRL function key. ASCII: device-ctrl-one. */ public static final short VK_CONTROL = (short) 0x11; - + /** Constant for the left ALT function key. ASCII: device-ctrl-two. */ public static final short VK_ALT = (short) 0x12; - + /** Constant for the ALT_GRAPH function key, i.e. right ALT key. ASCII: device-ctrl-three. */ public static final short VK_ALT_GRAPH = (short) 0x13; - + /** Constant for the CAPS LOCK function key. ASCII: device-ctrl-four. */ public static final short VK_CAPS_LOCK = (short) 0x14; - + static final short VK_FREE15 = (short) 0x15; - + /** Constant for the PAUSE function key. ASCII: sync-idle. */ public static final short VK_PAUSE = (short) 0x16; - + /** scroll lock key. ASCII: End Of Transmission Block. */ public static final short VK_SCROLL_LOCK = (short) 0x17; - + /** Constant for the CANCEL function key. ASCII: Cancel. */ public static final short VK_CANCEL = (short) 0x18; - + static final short VK_FREE19 = (short) 0x19; - + /** Constant for the INSERT function key. ASCII: Substitute. */ public static final short VK_INSERT = (short) 0x1A; - + /** Constant for the ESCAPE function key. ASCII: Escape. */ public static final short VK_ESCAPE = (short) 0x1B; - + /** Constant for the Convert function key, Japanese "henkan". ASCII: File Separator. */ public static final short VK_CONVERT = (short) 0x1C; @@ -496,48 +496,48 @@ public class KeyEvent extends InputEvent // // Unicode: Printable [0x20 - 0x7E] - // NOTE: Collision of 'a' - 'x' [0x61 .. 0x78], used for keyCode/keySym Fn function keys + // NOTE: Collision of 'a' - 'x' [0x61 .. 0x78], used for keyCode/keySym Fn function keys // - + /** Constant for the SPACE function key. ASCII: SPACE. */ public static final short VK_SPACE = (short) 0x20; - + /** Constant for the "!" key. */ public static final short VK_EXCLAMATION_MARK = (short) 0x21; /** Constant for the """ key. */ public static final short VK_QUOTEDBL = (short) 0x22; - + /** Constant for the "#" key. */ public static final short VK_NUMBER_SIGN = (short) 0x23; /** Constant for the "$" key. */ public static final short VK_DOLLAR = (short) 0x24; - + /** Constant for the "%" key. */ public static final short VK_PERCENT = (short) 0x25; - + /** Constant for the "&" key. */ public static final short VK_AMPERSAND = (short) 0x26; - + /** Constant for the "'" key. */ public static final short VK_QUOTE = (short) 0x27; - + /** Constant for the "(" key. */ public static final short VK_LEFT_PARENTHESIS = (short) 0x28; - + /** Constant for the ")" key. */ public static final short VK_RIGHT_PARENTHESIS = (short) 0x29; - + /** Constant for the "*" key */ public static final short VK_ASTERISK = (short) 0x2A; - + /** Constant for the "+" key. */ public static final short VK_PLUS = (short) 0x2B; - + /** Constant for the comma key, "," */ public static final short VK_COMMA = (short) 0x2C; - + /** Constant for the minus key, "-" */ public static final short VK_MINUS = (short) 0x2D; @@ -582,13 +582,13 @@ public class KeyEvent extends InputEvent /** Constant for the equals key, ">" */ public static final short VK_GREATER = (short) 0x3E; - + /** Constant for the equals key, "?" */ public static final short VK_QUESTIONMARK = (short) 0x3F; - + /** Constant for the equals key, "@" */ public static final short VK_AT = (short) 0x40; - + /** VK_A thru VK_Z are the same as Capital UTF16/ASCII 'A' thru 'Z' (0x41 - 0x5A) */ public static final short VK_A = (short) 0x41; /** See {@link #VK_A}. */ @@ -656,17 +656,17 @@ public class KeyEvent extends InputEvent /** Constant for the "_" key */ public static final short VK_UNDERSCORE = (short) 0x5F; - + /** Constant for the "`" key */ public static final short VK_BACK_QUOTE = (short) 0x60; - + /** Small UTF/ASCII 'a' thru 'z' (0x61 - 0x7a) - Not used for keyCode / keySym. */ - - /** - * Constant for the Fn function keys. + + /** + * Constant for the Fn function keys. *

                          * F1..F24, i.e. Fn, are mapped from on 0x60+n -> [0x61 .. 0x78]. - *

                          + *

                          *

                          * Warning: The Fn function keys do collide with unicode characters small 'a' thru 'x'!
                          * See Unicode Collision for details. @@ -743,26 +743,26 @@ public class KeyEvent extends InputEvent /** Constant for the F24 function key. See {@link #VK_F1}. */ public static final short VK_F24 = (short) ( 0x60+24 ); - + /** Constant for the "{" key */ public static final short VK_LEFT_BRACE = (short) 0x7B; /** Constant for the "|" key */ public static final short VK_PIPE = (short) 0x7C; /** Constant for the "}" key */ public static final short VK_RIGHT_BRACE = (short) 0x7D; - + /** Constant for the "~" key, matching ASCII */ public static final short VK_TILDE = (short) 0x7E; - + // // Unicode: Non printable controls: [0x7F - 0x9F] // // Numpad keys [0x7F - 0x8E] are printable // - + /** Numeric keypad decimal separator key. Non printable UTF control. */ public static final short VK_SEPARATOR = (short) 0x7F; - + /** Numeric keypad VK_NUMPAD0 thru VK_NUMPAD9 are mapped to UTF control (0x80 - 0x89). Non printable UTF control. */ public static final short VK_NUMPAD0 = (short) 0x80; /** See {@link #VK_NUMPAD0}. */ @@ -783,28 +783,28 @@ public class KeyEvent extends InputEvent public static final short VK_NUMPAD8 = (short) 0x88; /** See {@link #VK_NUMPAD0}. */ public static final short VK_NUMPAD9 = (short) 0x89; - + /** Numeric keypad decimal separator key. Non printable UTF control. */ public static final short VK_DECIMAL = (short) 0x8A; - + /** Numeric keypad add key. Non printable UTF control. */ public static final short VK_ADD = (short) 0x8B; /** Numeric keypad subtract key. Non printable UTF control. */ public static final short VK_SUBTRACT = (short) 0x8C; - + /** Numeric keypad multiply key. Non printable UTF control. */ public static final short VK_MULTIPLY = (short) 0x8D; - + /** Numeric keypad divide key. Non printable UTF control. */ public static final short VK_DIVIDE = (short) 0x8E; - + /** Constant for the DEL key, matching ASCII. Non printable UTF control. */ public static final short VK_DELETE = (short) 0x93; - + /** Numeric keypad num lock key. Non printable UTF control. */ public static final short VK_NUM_LOCK = (short) 0x94; - + /** Constant for the cursor- or numerical-pad left arrow key. Non printable UTF control. */ public static final short VK_LEFT = (short) 0x95; @@ -816,22 +816,22 @@ public class KeyEvent extends InputEvent /** Constant for the cursor- or numerical pad down arrow key. Non printable UTF control. */ public static final short VK_DOWN = (short) 0x98; - + /** Constant for the Context Menu key. Non printable UTF control. */ public static final short VK_CONTEXT_MENU = (short) 0x99; /** * Constant for the MS "Windows" function key. - * It is used for both the left and right version of the key. + * It is used for both the left and right version of the key. */ public static final short VK_WINDOWS = (short) 0x9A; /** Constant for the Meta function key. */ public static final short VK_META = (short) 0x9B; - + /** Constant for the Help function key. */ public static final short VK_HELP = (short) 0x9C; - + /** Constant for the Compose function key. */ public static final short VK_COMPOSE = (short) 0x9D; @@ -840,21 +840,21 @@ public class KeyEvent extends InputEvent /** Constant for the Stop function key. */ public static final short VK_STOP = (short) 0x9F; - + // // Unicode: Printable [0x00A0 - 0xDFFF] // - + /** Constant for the inverted exclamation mark key. */ public static final short VK_INVERTED_EXCLAMATION_MARK = (short) 0xA1; - + /** Constant for the Euro currency sign key. */ public static final short VK_EURO_SIGN = (short) 0x20AC; // // Unicode: Private 0xE000 - 0xF8FF (Marked Non-Printable) // - + /* for Sun keyboards */ public static final short VK_CUT = (short) 0xF879; public static final short VK_COPY = (short) 0xF87A; @@ -871,7 +871,7 @@ public class KeyEvent extends InputEvent */ /* Japanese PC 106 keyboard: kanji. Japanese Solaris keyboard: nihongo */ public static final short VK_INPUT_METHOD_ON_OFF = (short) 0xF890; - + /** * Constant for the Code Input function key. */ diff --git a/src/newt/classes/com/jogamp/newt/event/KeyListener.java b/src/newt/classes/com/jogamp/newt/event/KeyListener.java index b3927d81a..4b16ab61e 100644 --- a/src/newt/classes/com/jogamp/newt/event/KeyListener.java +++ b/src/newt/classes/com/jogamp/newt/event/KeyListener.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,22 +29,22 @@ * 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. - * + * */ package com.jogamp.newt.event; /** * Listener for {@link KeyEvent}s. - * + * * @see KeyEvent */ public interface KeyListener extends NEWTEventListener { /** A key has been {@link KeyEvent#EVENT_KEY_PRESSED pressed}, excluding {@link #isAutoRepeat() auto-repeat} {@link #isModifierKey() modifier} keys. See {@link KeyEvent}. */ public void keyPressed(KeyEvent e); - - /** + + /** * A key has been {@link KeyEvent#EVENT_KEY_RELEASED released}, excluding {@link #isAutoRepeat() auto-repeat} {@link #isModifierKey() modifier} keys. See {@link KeyEvent}. *

                          * To simulated the removed keyTyped(KeyEvent e) semantics, @@ -52,9 +52,9 @@ public interface KeyListener extends NEWTEventListener *

                                   if( !e.isPrintableKey() || e.isAutoRepeat() ) {
                                       return;
                          -        }            
                          +        }
                                * 
                          - *

                          + *

                          */ public void keyReleased(KeyEvent e); } diff --git a/src/newt/classes/com/jogamp/newt/event/MonitorEvent.java b/src/newt/classes/com/jogamp/newt/event/MonitorEvent.java index c47936a7a..77c66a2da 100644 --- a/src/newt/classes/com/jogamp/newt/event/MonitorEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/MonitorEvent.java @@ -35,19 +35,19 @@ import com.jogamp.newt.MonitorMode; public class MonitorEvent extends OutputEvent { public static final short EVENT_MONITOR_MODE_CHANGE_NOTIFY = 600; public static final short EVENT_MONITOR_MODE_CHANGED = 601; - + private final MonitorMode mode; - + public MonitorEvent (short eventType, MonitorDevice source, long when, MonitorMode mode) { super(eventType, source, when); this.mode = mode; } - + /** Returns the {@link #getSource() source}, which is a {@link MonitorDevice}. */ public final MonitorDevice getMonitor() { return (MonitorDevice)source; } - + public final MonitorMode getMode() { return mode; } - + public static String getEventTypeString(short type) { switch(type) { case EVENT_MONITOR_MODE_CHANGE_NOTIFY: return "EVENT_MONITOR_MODE_CHANGE_NOTIFY"; @@ -55,7 +55,7 @@ public class MonitorEvent extends OutputEvent { default: return "unknown (" + type + ")"; } } - + public final String toString() { return toString(null).toString(); } diff --git a/src/newt/classes/com/jogamp/newt/event/MouseAdapter.java b/src/newt/classes/com/jogamp/newt/event/MouseAdapter.java index 3607ae634..652f87d5b 100644 --- a/src/newt/classes/com/jogamp/newt/event/MouseAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/MouseAdapter.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.newt.event; public abstract class MouseAdapter implements MouseListener diff --git a/src/newt/classes/com/jogamp/newt/event/MouseEvent.java b/src/newt/classes/com/jogamp/newt/event/MouseEvent.java index 57dd7e68c..4d7cc3b36 100644 --- a/src/newt/classes/com/jogamp/newt/event/MouseEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/MouseEvent.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package com.jogamp.newt.event; @@ -37,12 +37,12 @@ package com.jogamp.newt.event; /** * Pointer event of type {@link PointerType}. *

                          - * The historical misleading class name may change in the future to PointerEvent. + * The historical misleading class name may change in the future to PointerEvent. *

                          *

                          * http://www.w3.org/Submission/pointer-events/#pointerevent-interface *

                          - *
                          Multiple-Pointer Events
                          + *
                          Multiple-Pointer Events
                          *

                          * In case an instance represents a multiple-pointer event, i.e. {@link #getPointerCount()} is > 1, * the first data element of the multiple-pointer fields represents the pointer triggering this event.
                          @@ -62,10 +62,10 @@ package com.jogamp.newt.event; *

                          *

                          * If representing a multiple-pointer event, the {@link #getButton() button number} is mapped to the first {@link #getPointerId(int) pointer ID} - * triggering the event and the {@link InputEvent#BUTTON1_MASK button mask bits} in the {@link #getModifiers() modifiers} + * triggering the event and the {@link InputEvent#BUTTON1_MASK button mask bits} in the {@link #getModifiers() modifiers} * field represent the pressed pointer IDs.
                          * Hence users can query the pressed button count as well as the pressed pointer count via {@link InputEvent#getButtonDownCount()} - * or use the simple query {@link InputEvent#isAnyButtonDown()}. + * or use the simple query {@link InputEvent#isAnyButtonDown()}. *

                          */ @SuppressWarnings("serial") @@ -75,7 +75,7 @@ public class MouseEvent extends InputEvent public static enum PointerClass implements InputEvent.InputClass { Offscreen, Onscreen, Undefined; } - + /** Type of pointer devices */ public static enum PointerType implements InputEvent.InputType { /** {@link PointerClass#Offscreen} mouse. Ordinal 0. */ @@ -88,10 +88,10 @@ public class MouseEvent extends InputEvent Pen(PointerClass.Onscreen), /** {@link PointerClass#Undefined} ?. Ordinal 4. */ Undefined(PointerClass.Undefined); - + public PointerClass getPointerClass() { return pc; } - - /** + + /** * Returns the matching PointerType value corresponding to the given PointerType's integer ordinal. *
                                    *   given:
                          @@ -108,8 +108,8 @@ public class MouseEvent extends InputEvent
                                       }
                                       throw new IllegalArgumentException("Ordinal "+ordinal+" out of range of PointerType.values()[0.."+(all.length-1)+"]");
                                   }
                          -        
                          -        /** 
                          +
                          +        /**
                                    * Returns the PointerType array of matching PointerType values corresponding to the given PointerType's integer ordinal values.
                                    * 

                          * See {@link #valueOf(int)}. @@ -124,13 +124,13 @@ public class MouseEvent extends InputEvent } return types; } - + private PointerType(PointerClass pc) { this.pc = pc; } PointerClass pc; } - + /** ID for button 1, value 1 */ public static final short BUTTON1 = 1; /** ID for button 2, value 2 */ @@ -149,17 +149,17 @@ public class MouseEvent extends InputEvent public static final short BUTTON8 = 8; /** ID for button 6, value 9 */ public static final short BUTTON9 = 9; - + /** Maximum number of buttons, value 16 */ public static final short BUTTON_COUNT = 16; - /** + /** * Maximum number of buttons, value 16. * @deprecated Use {@link #BUTTON_COUNT} .. semantics. */ public static final short BUTTON_NUMBER = 16; - - /** Returns the 3-axis XYZ rotation array by given rotation on Y axis or X axis (if SHIFT_MASK is given in mods). */ + + /** Returns the 3-axis XYZ rotation array by given rotation on Y axis or X axis (if SHIFT_MASK is given in mods). */ public static final float[] getRotationXYZ(final float rotationXorY, final int mods) { final float[] rotationXYZ = new float[] { 0f, 0f, 0f }; if( 0 != ( mods & InputEvent.SHIFT_MASK ) ) { @@ -169,14 +169,14 @@ public class MouseEvent extends InputEvent } return rotationXYZ; } - - public static final short getClickTimeout() { - return 300; + + public static final short getClickTimeout() { + return 300; } - - /** + + /** * Constructor for traditional one-pointer event. - * + * * @param eventType * @param source * @param when @@ -193,7 +193,7 @@ public class MouseEvent extends InputEvent int modifiers, int x, int y, short clickCount, short button, float[] rotationXYZ, float rotationScale) { - super(eventType, source, when, modifiers); + super(eventType, source, when, modifiers); this.x = new int[]{x}; this.y = new int[]{y}; switch(eventType) { @@ -214,15 +214,15 @@ public class MouseEvent extends InputEvent this.pointerType = constMousePointerTypes; } - /** + /** * Constructor for a multiple-pointer event. *

                          * First element of multiple-pointer arrays represents the pointer which triggered the event! *

                          - *

                          + *

                          * See details for multiple-pointer events. *

                          - * + * * @param eventType * @param source * @param when @@ -239,12 +239,12 @@ public class MouseEvent extends InputEvent * @param rotationXYZ Rotation of all axis * @param rotationScale Rotation scale */ - public MouseEvent(short eventType, Object source, long when, int modifiers, - PointerType pointerType[], short[] pointerID, - int[] x, int[] y, float[] pressure, float maxPressure, + public MouseEvent(short eventType, Object source, long when, int modifiers, + PointerType pointerType[], short[] pointerID, + int[] x, int[] y, float[] pressure, float maxPressure, short button, short clickCount, float[] rotationXYZ, float rotationScale) { - super(eventType, source, when, modifiers); + super(eventType, source, when, modifiers); this.x = x; this.y = y; final int pointerCount = pointerType.length; @@ -266,12 +266,12 @@ public class MouseEvent extends InputEvent this.rotationScale = rotationScale; this.pointerType = pointerType; } - + public MouseEvent createVariant(short newEventType) { return new MouseEvent(newEventType, source, getWhen(), getModifiers(), pointerType, pointerID, x, y, pressure, maxPressure, button, clickCount, rotationXYZ, rotationScale); } - + /** * See details for multiple-pointer events. * @return the count of pointers involved in this event @@ -279,7 +279,7 @@ public class MouseEvent extends InputEvent public final int getPointerCount() { return pointerType.length; } - + /** * See details for multiple-pointer events. * @return the {@link PointerType} for the data at index or null if index not available. @@ -290,7 +290,7 @@ public class MouseEvent extends InputEvent } return pointerType[index]; } - + /** * See details for multiple-pointer events. * @return array of all {@link PointerType}s for all pointers @@ -298,10 +298,10 @@ public class MouseEvent extends InputEvent public final PointerType[] getAllPointerTypes() { return pointerType; } - + /** * Return the pointer id for the given index or -1 if index not available. - *

                          + *

                          * IDs start w/ 0 and are consecutive numbers. *

                          *

                          @@ -317,7 +317,7 @@ public class MouseEvent extends InputEvent } return pointerID[index]; } - + /** * See details for multiple-pointer events. * @return the pointer index for the given pointer id or -1 if id not available. @@ -332,7 +332,7 @@ public class MouseEvent extends InputEvent } return -1; } - + /** * See details for multiple-pointer events. * @return array of all pointer IDs for all pointers. IDs start w/ 0 and are consecutive numbers. @@ -340,15 +340,15 @@ public class MouseEvent extends InputEvent public final short[] getAllPointerIDs() { return pointerID; } - - /** + + /** * Returns the button number, e.g. [{@link #BUTTON1}..{@link #BUTTON_COUNT}-1]. *

                          * A button value of 0 denotes no button activity, i.e. {@link PointerType#Mouse} move. *

                          *

                          * See details for multiple-pointer events. - *

                          + *

                          */ public final short getButton() { return button; @@ -357,16 +357,16 @@ public class MouseEvent extends InputEvent public final short getClickCount() { return clickCount; } - + public final int getX() { return x[0]; } - + public final int getY() { return y[0]; } - /** + /** * See details for multiple-pointer events. * @param index pointer-index within [0 .. {@link #getPointerCount()}-1] * @return X-Coord associated with the pointer-index. @@ -376,7 +376,7 @@ public class MouseEvent extends InputEvent return x[index]; } - /** + /** * See details for multiple-pointer events. * @param index pointer-index within [0 .. {@link #getPointerCount()}-1] * @return Y-Coord associated with the pointer-index. @@ -385,7 +385,7 @@ public class MouseEvent extends InputEvent public final int getY(int index) { return y[index]; } - + /** * See details for multiple-pointer events. * @return array of all X-Coords for all pointers @@ -393,7 +393,7 @@ public class MouseEvent extends InputEvent public final int[] getAllX() { return x; } - + /** * See details for multiple-pointer events. * @return array of all Y-Coords for all pointers @@ -401,9 +401,9 @@ public class MouseEvent extends InputEvent public final int[] getAllY() { return y; } - + /** - * @param normalized if true, method returns the normalized pressure, i.e. pressure / maxPressure + * @param normalized if true, method returns the normalized pressure, i.e. pressure / maxPressure * @return The pressure associated with the pointer-index 0. * The value of zero is return if not available. * @see #getMaxPressure() @@ -411,11 +411,11 @@ public class MouseEvent extends InputEvent public final float getPressure(boolean normalized){ return normalized ? pressure[0] / maxPressure : pressure[0]; } - + /** * See details for multiple-pointer events. * @param index pointer-index within [0 .. {@link #getPointerCount()}-1] - * @param normalized if true, method returns the normalized pressure, i.e. pressure / maxPressure + * @param normalized if true, method returns the normalized pressure, i.e. pressure / maxPressure * @return The pressure associated with the pointer-index. * The value of zero is return if not available. * @see #getMaxPressure() @@ -423,7 +423,7 @@ public class MouseEvent extends InputEvent public final float getPressure(int index, boolean normalized){ return normalized ? pressure[index] / maxPressure : pressure[index]; } - + /** * See details for multiple-pointer events. * @return array of all raw, un-normalized pressures for all pointers @@ -431,12 +431,12 @@ public class MouseEvent extends InputEvent public final float[] getAllPressures() { return pressure; } - - /** + + /** * Returns the maximum pressure known for the input device generating this event. *

                          * This value may be self calibrating on devices/OS, where no known maximum pressure is known. - * Hence subsequent events may return a higher value. + * Hence subsequent events may return a higher value. *

                          *

                          * Self calibrating maximum pressure is performed on: @@ -448,25 +448,25 @@ public class MouseEvent extends InputEvent public final float getMaxPressure() { return maxPressure; } - + /** * Returns a 3-component float array filled with the values of the rotational axis * in the following order: horizontal-, vertical- and z-axis. - *

                          + *

                          * A vertical rotation of > 0.0f is up and < 0.0f is down. *

                          *

                          - * A horizontal rotation of > 0.0f is left and < 0.0f is right. + * A horizontal rotation of > 0.0f is left and < 0.0f is right. *

                          *

                          - * A z-axis rotation of > 0.0f is back and < 0.0f is front. + * A z-axis rotation of > 0.0f is back and < 0.0f is front. *

                          *

                          * However, on some OS this might be flipped due to the OS default behavior. * The latter is true for OS X 10.7 (Lion) for example. *

                          *

                          - * On PointerClass {@link PointerClass#Onscreen onscreen} devices, i.e. {@link PointerType#TouchScreen touch screens}, + * On PointerClass {@link PointerClass#Onscreen onscreen} devices, i.e. {@link PointerType#TouchScreen touch screens}, * rotation events are usually produced by a 2-finger movement, where horizontal and vertical rotation values are filled. *

                          *

                          @@ -475,13 +475,13 @@ public class MouseEvent extends InputEvent *

                          *

                          * The {@link InputEvent#SHIFT_MASK} modifier is set in case |horizontal| > |vertical| value.
                          - * This can be utilized to implement only one 2d rotation direction, you may use {@link #isShiftDown()} to query it. + * This can be utilized to implement only one 2d rotation direction, you may use {@link #isShiftDown()} to query it. *

                          *

                          * In case the pointer type is {@link PointerType#Mouse mouse}, * events are usually send in steps of one, ie. -1.0f and 1.0f. * Higher values may result due to fast scrolling. - * Fractional values may result due to slow scrolling with high resolution devices.
                          + * Fractional values may result due to slow scrolling with high resolution devices.
                          * Here the button number refers to the wheel number. *

                          *

                          @@ -492,24 +492,24 @@ public class MouseEvent extends InputEvent public final float[] getRotation() { return rotationXYZ; } - - /** + + /** * Returns the scale used to determine the {@link #getRotation() rotation value}, * which semantics depends on the {@link #getPointerType() pointer type's} {@link PointerClass}. *

                          * For {@link PointerClass#Offscreen}, the scale is usually 1.0f and denominates * an abstract value without association to a physical value. - *

                          + *

                          *

                          * For {@link PointerClass#Onscreen}, the scale varies and denominates - * the divisor of the distance the finger[s] have moved on the screen. - * Hence scale * rotation reproduces the screen distance in pixels the finger[s] have moved. - *

                          + * the divisor of the distance the finger[s] have moved on the screen. + * Hence scale * rotation reproduces the screen distance in pixels the finger[s] have moved. + *

                          */ public final float getRotationScale() { return rotationScale; } - + public final String toString() { return toString(null).toString(); } @@ -533,7 +533,7 @@ public class MouseEvent extends InputEvent .append("p[").append(pressure[i]).append("/").append(maxPressure).append("=").append(pressure[i]/maxPressure).append("]"); } sb.append("]"); - } + } sb.append(", "); return super.toString(sb).append("]"); } @@ -551,14 +551,14 @@ public class MouseEvent extends InputEvent default: return "unknown (" + type + ")"; } } - + /** PointerType for each pointer (multiple pointer) */ private final PointerType pointerType[]; - /** + /** * Pointer-ID for each pointer (multiple pointer). IDs start w/ 0 and are consecutive numbers. - *

                          + *

                          * A pointer-ID of -1 may also denote no pointer/button activity, i.e. {@link PointerType#Mouse} move. - *

                          + *

                          */ private final short pointerID[]; /** X-axis for each pointer (multiple pointer) */ @@ -581,11 +581,11 @@ public class MouseEvent extends InputEvent /** Rotation scale */ private final float rotationScale; private final float maxPressure; - + private static final float[] constMousePressure0 = new float[]{0f}; private static final float[] constMousePressure1 = new float[]{1f}; private static final PointerType[] constMousePointerTypes = new PointerType[] { PointerType.Mouse }; - + public static final short EVENT_MOUSE_CLICKED = 200; public static final short EVENT_MOUSE_ENTERED = 201; public static final short EVENT_MOUSE_EXITED = 202; diff --git a/src/newt/classes/com/jogamp/newt/event/MouseListener.java b/src/newt/classes/com/jogamp/newt/event/MouseListener.java index ce6796081..5378080b9 100644 --- a/src/newt/classes/com/jogamp/newt/event/MouseListener.java +++ b/src/newt/classes/com/jogamp/newt/event/MouseListener.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package com.jogamp.newt.event; @@ -38,7 +38,7 @@ import com.jogamp.newt.event.MouseEvent.PointerType; /** * Listener for {@link MouseEvent}s. - * + * * @see MouseEvent */ public interface MouseListener extends NEWTEventListener @@ -50,13 +50,13 @@ public interface MouseListener extends NEWTEventListener public void mouseReleased(MouseEvent e); public void mouseMoved(MouseEvent e); public void mouseDragged(MouseEvent e); - + /** * Traditional event name originally produced by a {@link PointerType#Mouse mouse} pointer type. *

                          * Triggered for any rotational pointer events, see - * {@link MouseEvent#getRotation()} and {@link MouseEvent#getRotationScale()}. - *

                          + * {@link MouseEvent#getRotation()} and {@link MouseEvent#getRotationScale()}. + *

                          */ public void mouseWheelMoved(MouseEvent e); } diff --git a/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java b/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java index 02bb4f929..022e2d0e1 100644 --- a/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package com.jogamp.newt.event; @@ -50,7 +50,7 @@ package com.jogamp.newt.event; */ @SuppressWarnings("serial") public class NEWTEvent extends java.util.EventObject { - /** + /** * See {@link #setConsumed(boolean)} for description. */ public static final Object consumedTag = new Object(); @@ -78,11 +78,11 @@ public class NEWTEvent extends java.util.EventObject { return when; } - /** + /** * Attach the passed object to this event.
                          * If an object was previously attached, it will be replaced.
                          * Attachments to NEWT events allow users to pass on information - * from one custom listener to another, ie custom listener to listener + * from one custom listener to another, ie custom listener to listener * communication. * @param attachment User application specific object */ @@ -90,14 +90,14 @@ public class NEWTEvent extends java.util.EventObject { this.attachment = attachment; } - /** + /** * @return The user application specific attachment, or null */ public final Object getAttachment() { return attachment; } - - /** + + /** * Returns true if this events has been {@link #setConsumed(boolean) consumed}, * otherwise false. * @see #setConsumed(boolean) @@ -105,8 +105,8 @@ public class NEWTEvent extends java.util.EventObject { public final boolean isConsumed() { return consumedTag == attachment; } - - /** + + /** * If consumed is true, this event is marked as consumed, * ie. the event will not be propagated any further to potential other event listener. * Otherwise the event will be propagated to other event listener, the default. @@ -130,7 +130,7 @@ public class NEWTEvent extends java.util.EventObject { setAttachment( null ); } } - + public String toString() { return toString(null).toString(); } diff --git a/src/newt/classes/com/jogamp/newt/event/NEWTEventConsumer.java b/src/newt/classes/com/jogamp/newt/event/NEWTEventConsumer.java index 6aa19e5f8..14fba6742 100644 --- a/src/newt/classes/com/jogamp/newt/event/NEWTEventConsumer.java +++ b/src/newt/classes/com/jogamp/newt/event/NEWTEventConsumer.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,18 +20,18 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.newt.event; public interface NEWTEventConsumer { - /** - * Consume the event + /** + * Consume the event * * @return true if the event has been consumed, * otherwise it returns false for later propagation. diff --git a/src/newt/classes/com/jogamp/newt/event/NEWTEventFiFo.java b/src/newt/classes/com/jogamp/newt/event/NEWTEventFiFo.java index fe224bba6..7dd56ad1e 100644 --- a/src/newt/classes/com/jogamp/newt/event/NEWTEventFiFo.java +++ b/src/newt/classes/com/jogamp/newt/event/NEWTEventFiFo.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.newt.event; import java.util.LinkedList; diff --git a/src/newt/classes/com/jogamp/newt/event/NEWTEventListener.java b/src/newt/classes/com/jogamp/newt/event/NEWTEventListener.java index 677136573..f7ee3d739 100644 --- a/src/newt/classes/com/jogamp/newt/event/NEWTEventListener.java +++ b/src/newt/classes/com/jogamp/newt/event/NEWTEventListener.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package com.jogamp.newt.event; diff --git a/src/newt/classes/com/jogamp/newt/event/OutputEvent.java b/src/newt/classes/com/jogamp/newt/event/OutputEvent.java index 86fa95877..80c7780f8 100644 --- a/src/newt/classes/com/jogamp/newt/event/OutputEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/OutputEvent.java @@ -39,7 +39,7 @@ public abstract class OutputEvent extends NEWTEvent public String toString() { return toString(null).toString(); } - + public StringBuilder toString(StringBuilder sb) { if(null == sb) { sb = new StringBuilder(); diff --git a/src/newt/classes/com/jogamp/newt/event/PinchToZoomGesture.java b/src/newt/classes/com/jogamp/newt/event/PinchToZoomGesture.java index eceea053d..d275eab46 100644 --- a/src/newt/classes/com/jogamp/newt/event/PinchToZoomGesture.java +++ b/src/newt/classes/com/jogamp/newt/event/PinchToZoomGesture.java @@ -35,7 +35,7 @@ import jogamp.newt.Debug; * 2 pointer zoom, a.k.a. pinch to zoom, gesture handler processing {@link MouseEvent}s * while producing {@link ZoomEvent}s if gesture is completed. *

                          - * Zoom value lies within [0..2], with 1 as 1:1. + * Zoom value lies within [0..2], with 1 as 1:1. *

                          *
                            *   - choosing the smallest surface edge (width/height -> x/y)
                          @@ -44,7 +44,7 @@ import jogamp.newt.Debug;
                            */
                           public class PinchToZoomGesture implements GestureHandler {
                               public static final boolean DEBUG = Debug.debug("Window.MouseEvent");
                          -    
                          +
                               /** A {@link GestureHandler.GestureEvent} denominating zoom. */
                               @SuppressWarnings("serial")
                               public static class ZoomEvent extends GestureEvent {
                          @@ -57,10 +57,10 @@ public class PinchToZoomGesture implements GestureHandler {
                                   }
                                   /** Triggering {@link MouseEvent} */
                                   public final MouseEvent getTrigger() { return pe; }
                          -        /** Zoom value lies within [0..2], with 1 as 1:1. */ 
                          +        /** Zoom value lies within [0..2], with 1 as 1:1. */
                                   public final float getZoom() { return zoom; }
                               }
                          -    
                          +
                               private final NativeSurface surface;
                               private float zoom;
                               private int zoomLastEdgeDist;
                          @@ -68,7 +68,7 @@ public class PinchToZoomGesture implements GestureHandler {
                               private boolean zoomMode;
                               private ZoomEvent zoomEvent;
                               private short[] pIds = new short[] { -1, -1 };
                          -    
                          +
                               public PinchToZoomGesture(NativeSurface surface) {
                                   clear(true);
                                   this.surface = surface;
                          @@ -80,10 +80,10 @@ public class PinchToZoomGesture implements GestureHandler {
                               }
                           
                               private int gesturePointers(final MouseEvent e, final int excludeIndex) {
                          -        int j = 0;       
                          +        int j = 0;
                                   for(int i=e.getPointerCount()-1; i>=0; i--) {
                                       if( excludeIndex != i ) {
                          -                final int id = e.getPointerId(i); 
                          +                final int id = e.getPointerId(i);
                                           if( pIds[0] == id || pIds[1] == id ) {
                                               j++;
                                           }
                          @@ -91,7 +91,7 @@ public class PinchToZoomGesture implements GestureHandler {
                                   }
                                   return j;
                               }
                          -    
                          +
                               @Override
                               public void clear(boolean clearStarted) {
                                   zoomEvent = null;
                          @@ -103,31 +103,31 @@ public class PinchToZoomGesture implements GestureHandler {
                                       pIds[1] = -1;
                                   }
                               }
                          -    
                          +
                               @Override
                               public boolean isWithinGesture() {
                                   return zoomMode;
                               }
                          -    
                          +
                               @Override
                               public boolean hasGesture() {
                                   return null != zoomEvent;
                               }
                          -    
                          +
                               @Override
                               public InputEvent getGestureEvent() {
                                   return zoomEvent;
                               }
                          -    
                          -    /** Zoom value lies within [0..2], with 1 as 1:1. */ 
                          +
                          +    /** Zoom value lies within [0..2], with 1 as 1:1. */
                               public final float getZoom() {
                                   return zoom;
                               }
                          -    /** Set zoom value within [0..2], with 1 as 1:1. */ 
                          +    /** Set zoom value within [0..2], with 1 as 1:1. */
                               public final void setZoom(float zoom) {
                                   this.zoom=zoom;
                               }
                          -    
                          +
                               @Override
                               public boolean process(final InputEvent in) {
                                   if( null != zoomEvent || !(in instanceof MouseEvent) ) {
                          @@ -137,15 +137,15 @@ public class PinchToZoomGesture implements GestureHandler {
                                   if( pe.getPointerType(0).getPointerClass() != MouseEvent.PointerClass.Onscreen ) {
                                       return false;
                                   }
                          -        
                          +
                                   final int pointerDownCount = pe.getPointerCount();
                                   final int eventType = pe.getEventType();
                                   final boolean useY = surface.getWidth() >= surface.getHeight(); // use smallest dimension
                                   switch ( eventType ) {
                                       case MouseEvent.EVENT_MOUSE_PRESSED: {
                                           if( 1 == pointerDownCount ) {
                          -                    pIds[0] = pe.getPointerId(0);                    
                          -                    pIds[1] = -1;                    
                          +                    pIds[0] = pe.getPointerId(0);
                          +                    pIds[1] = -1;
                                           } else if ( 2 <= pointerDownCount ) { // && 1 == gesturePointers(pe, 0) /* w/o pressed pointer */) {
                                               pIds[0] = pe.getPointerId(0);
                                               pIds[1] = pe.getPointerId(1);
                          @@ -155,13 +155,13 @@ public class PinchToZoomGesture implements GestureHandler {
                                               System.err.println(this+".pressed: down "+pointerDownCount+", gPtr "+gesturePointers(pe, -1)+", event "+pe);
                                           }
                                       } break;
                          -            
                          +
                                       case MouseEvent.EVENT_MOUSE_RELEASED: {
                                           final int gPtr = gesturePointers(pe, 0); // w/o lifted pointer
                                           if ( 1 == gPtr ) {
                                               zoomFirstTouch = true;
                                               zoomMode = false;
                          -                } else if( 0 == gPtr ) { 
                          +                } else if( 0 == gPtr ) {
                                               // all lifted
                                               clear(true);
                                           }
                          @@ -169,7 +169,7 @@ public class PinchToZoomGesture implements GestureHandler {
                                               System.err.println(this+".released: down "+pointerDownCount+", gPtr "+gPtr+", event "+pe);
                                           }
                                       } break;
                          -            
                          +
                                       case MouseEvent.EVENT_MOUSE_DRAGGED: {
                                           if( 2 <= pointerDownCount ) {
                                               final int gPtr = gesturePointers(pe, -1);
                          @@ -187,13 +187,13 @@ public class PinchToZoomGesture implements GestureHandler {
                                                           zoomMode = true;
                                                       } else if( zoomMode ) {
                                                           final int d = Math.abs(edge0-edge1);
                          -                                final int dd = d - zoomLastEdgeDist;                        
                          +                                final int dd = d - zoomLastEdgeDist;
                                                           final float screenEdge = useY ? surface.getHeight() : surface.getWidth();
                                                           final float incr = (float)dd / screenEdge; // [-1..1]
                                                           if(DEBUG) {
                                                               System.err.println("XXX2: id0 "+pIds[0]+" -> idx0 "+p0Idx+", id1 "+pIds[1]+" -> idx1 "+p1Idx);
                                                               System.err.println("XXX3: d "+d+", ld "+zoomLastEdgeDist+", dd "+dd+", screen "+screenEdge+" -> incr "+incr+", zoom "+zoom+" -> "+(zoom+incr));
                          -                                }        
                          +                                }
                                                           zoom += incr;
                                                           // clip value
                                                           if( 2f < zoom ) {
                          @@ -211,7 +211,7 @@ public class PinchToZoomGesture implements GestureHandler {
                                               }
                                           }
                                       } break;
                          -            
                          +
                                       default:
                                   }
                                   return null != zoomEvent;
                          diff --git a/src/newt/classes/com/jogamp/newt/event/TraceKeyAdapter.java b/src/newt/classes/com/jogamp/newt/event/TraceKeyAdapter.java
                          index 629dc50d7..e826f4a6a 100644
                          --- a/src/newt/classes/com/jogamp/newt/event/TraceKeyAdapter.java
                          +++ b/src/newt/classes/com/jogamp/newt/event/TraceKeyAdapter.java
                          @@ -3,14 +3,14 @@
                            *
                            * Redistribution and use in source and binary forms, with or without modification, are
                            * permitted provided that the following conditions are met:
                          - * 
                          + *
                            *    1. Redistributions of source code must retain the above copyright notice, this list of
                            *       conditions and the following disclaimer.
                          - * 
                          + *
                            *    2. 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.
                          - * 
                          + *
                            * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR
                          @@ -20,12 +20,12 @@
                            * 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.
                          - * 
                          + *
                            * The views and conclusions contained in the software and documentation are those of the
                            * authors and should not be interpreted as representing official policies, either expressed
                            * or implied, of JogAmp Community.
                            */
                          - 
                          +
                           package com.jogamp.newt.event;
                           
                           public class TraceKeyAdapter implements KeyListener {
                          diff --git a/src/newt/classes/com/jogamp/newt/event/TraceMouseAdapter.java b/src/newt/classes/com/jogamp/newt/event/TraceMouseAdapter.java
                          index 14ee633a0..d035091c4 100644
                          --- a/src/newt/classes/com/jogamp/newt/event/TraceMouseAdapter.java
                          +++ b/src/newt/classes/com/jogamp/newt/event/TraceMouseAdapter.java
                          @@ -3,14 +3,14 @@
                            *
                            * Redistribution and use in source and binary forms, with or without modification, are
                            * permitted provided that the following conditions are met:
                          - * 
                          + *
                            *    1. Redistributions of source code must retain the above copyright notice, this list of
                            *       conditions and the following disclaimer.
                          - * 
                          + *
                            *    2. 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.
                          - * 
                          + *
                            * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR
                          @@ -20,12 +20,12 @@
                            * 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.
                          - * 
                          + *
                            * The views and conclusions contained in the software and documentation are those of the
                            * authors and should not be interpreted as representing official policies, either expressed
                            * or implied, of JogAmp Community.
                            */
                          - 
                          +
                           package com.jogamp.newt.event;
                           
                           public class TraceMouseAdapter implements MouseListener {
                          diff --git a/src/newt/classes/com/jogamp/newt/event/TraceWindowAdapter.java b/src/newt/classes/com/jogamp/newt/event/TraceWindowAdapter.java
                          index 8542820c4..630e85303 100644
                          --- a/src/newt/classes/com/jogamp/newt/event/TraceWindowAdapter.java
                          +++ b/src/newt/classes/com/jogamp/newt/event/TraceWindowAdapter.java
                          @@ -3,14 +3,14 @@
                            *
                            * Redistribution and use in source and binary forms, with or without modification, are
                            * permitted provided that the following conditions are met:
                          - * 
                          + *
                            *    1. Redistributions of source code must retain the above copyright notice, this list of
                            *       conditions and the following disclaimer.
                          - * 
                          + *
                            *    2. 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.
                          - * 
                          + *
                            * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR
                          @@ -20,12 +20,12 @@
                            * 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.
                          - * 
                          + *
                            * The views and conclusions contained in the software and documentation are those of the
                            * authors and should not be interpreted as representing official policies, either expressed
                            * or implied, of JogAmp Community.
                            */
                          - 
                          +
                           package com.jogamp.newt.event;
                           
                           public class TraceWindowAdapter implements WindowListener {
                          diff --git a/src/newt/classes/com/jogamp/newt/event/WindowAdapter.java b/src/newt/classes/com/jogamp/newt/event/WindowAdapter.java
                          index b9e487e9b..e237c0d80 100644
                          --- a/src/newt/classes/com/jogamp/newt/event/WindowAdapter.java
                          +++ b/src/newt/classes/com/jogamp/newt/event/WindowAdapter.java
                          @@ -3,14 +3,14 @@
                            *
                            * Redistribution and use in source and binary forms, with or without modification, are
                            * permitted provided that the following conditions are met:
                          - * 
                          + *
                            *    1. Redistributions of source code must retain the above copyright notice, this list of
                            *       conditions and the following disclaimer.
                          - * 
                          + *
                            *    2. 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.
                          - * 
                          + *
                            * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR
                          @@ -20,12 +20,12 @@
                            * 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.
                          - * 
                          + *
                            * The views and conclusions contained in the software and documentation are those of the
                            * authors and should not be interpreted as representing official policies, either expressed
                            * or implied, of JogAmp Community.
                            */
                          - 
                          +
                           package com.jogamp.newt.event;
                           
                           public abstract class WindowAdapter implements WindowListener
                          diff --git a/src/newt/classes/com/jogamp/newt/event/WindowEvent.java b/src/newt/classes/com/jogamp/newt/event/WindowEvent.java
                          index 24b3b380a..8c7abfe99 100644
                          --- a/src/newt/classes/com/jogamp/newt/event/WindowEvent.java
                          +++ b/src/newt/classes/com/jogamp/newt/event/WindowEvent.java
                          @@ -1,22 +1,22 @@
                           /*
                            * Copyright (c) 2008 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
                          @@ -29,7 +29,7 @@
                            * 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.
                          - * 
                          + *
                            */
                           
                           package com.jogamp.newt.event;
                          @@ -42,7 +42,7 @@ package com.jogamp.newt.event;
                           @SuppressWarnings("serial")
                           public class WindowEvent extends NEWTEvent {
                               public static final short EVENT_WINDOW_RESIZED = 100;
                          -    public static final short EVENT_WINDOW_MOVED   = 101; 
                          +    public static final short EVENT_WINDOW_MOVED   = 101;
                               public static final short EVENT_WINDOW_DESTROY_NOTIFY = 102;
                               public static final short EVENT_WINDOW_GAINED_FOCUS = 103;
                               public static final short EVENT_WINDOW_LOST_FOCUS = 104;
                          @@ -65,7 +65,7 @@ public class WindowEvent extends NEWTEvent {
                                       default: return "unknown (" + type + ")";
                                   }
                               }
                          -    
                          +
                               public String toString() {
                                   return toString(null).toString();
                               }
                          diff --git a/src/newt/classes/com/jogamp/newt/event/WindowListener.java b/src/newt/classes/com/jogamp/newt/event/WindowListener.java
                          index dde182510..e097edf23 100644
                          --- a/src/newt/classes/com/jogamp/newt/event/WindowListener.java
                          +++ b/src/newt/classes/com/jogamp/newt/event/WindowListener.java
                          @@ -1,22 +1,22 @@
                           /*
                            * Copyright (c) 2008 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
                          @@ -29,7 +29,7 @@
                            * 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.
                          - * 
                          + *
                            */
                           
                           package com.jogamp.newt.event;
                          @@ -44,17 +44,17 @@ public interface WindowListener extends NEWTEventListener {
                               /** Window has been moved. */
                               public void windowMoved(WindowEvent e);
                           
                          -    /** 
                          +    /**
                                * Window destruction has been requested.
                                * 

                          * Depending on the {@link WindowClosingProtocol#getDefaultCloseOperation() default close operation}, * the window maybe destroyed or not. *

                          - * In case the window will be destroyed (see above), release of resources is recommended. + * In case the window will be destroyed (see above), release of resources is recommended. **/ public void windowDestroyNotify(WindowEvent e); - /** + /** * Window has been destroyed. */ public void windowDestroyed(WindowEvent e); diff --git a/src/newt/classes/com/jogamp/newt/event/WindowUpdateEvent.java b/src/newt/classes/com/jogamp/newt/event/WindowUpdateEvent.java index a0f6e2cb4..8a204d234 100644 --- a/src/newt/classes/com/jogamp/newt/event/WindowUpdateEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/WindowUpdateEvent.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.newt.event; import javax.media.nativewindow.util.Rectangle; diff --git a/src/newt/classes/com/jogamp/newt/event/awt/AWTAdapter.java b/src/newt/classes/com/jogamp/newt/event/awt/AWTAdapter.java index 6de2eee45..e3bf18448 100644 --- a/src/newt/classes/com/jogamp/newt/event/awt/AWTAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/awt/AWTAdapter.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.newt.event.awt; import jogamp.newt.Debug; @@ -48,10 +48,10 @@ import jogamp.newt.Debug; * Common:
                          *
                               // your demo/render code
                          -    javax.media.opengl.GLEvenListener demo1 = new javax.media.opengl.GLEvenListener() { ... } ; 
                          +    javax.media.opengl.GLEvenListener demo1 = new javax.media.opengl.GLEvenListener() { ... } ;
                           
                               // your AWT agnostic NEWT mouse listener code
                          -    com.jogamp.newt.event.MouseListener mouseListener = new com.jogamp.newt.event.MouseAdapter() { ... } ; 
                          +    com.jogamp.newt.event.MouseListener mouseListener = new com.jogamp.newt.event.MouseAdapter() { ... } ;
                            * 

                          *

                          * Default NEWT use case, without using the AWTAdapter:
                          @@ -96,7 +96,7 @@ import jogamp.newt.Debug;
                          new AWTMouseAdapter(mouseListener, glWindow).addTo(comp);
                          *

                          - * + * * Last but not least, the AWTAdapter maybe used as a general AWT event forwarder to NEWT.
                          * *

                          @@ -108,7 +108,7 @@ import jogamp.newt.Debug;
                          new AWTMouseAdapter(glWindow).addTo(comp); // forward all AWT events to glWindow, as NEWT events
                          *

                          - * + * * @see #attachTo */ public abstract class AWTAdapter implements java.util.EventListener @@ -118,7 +118,7 @@ public abstract class AWTAdapter implements java.util.EventListener com.jogamp.newt.event.NEWTEventListener newtListener; com.jogamp.newt.Window newtWindow; - /** + /** * Simply wrap aroung a NEWT EventListener, exposed as an AWT EventListener.
                          * The NEWT EventListener will be called when an event happens.
                          */ @@ -130,7 +130,7 @@ public abstract class AWTAdapter implements java.util.EventListener this.newtWindow = null; } - /** + /** * Wrap aroung a NEWT EventListener, exposed as an AWT EventListener,
                          * where the given NEWT Window impersonates as the event's source. * The NEWT EventListener will be called when an event happens.
                          @@ -146,7 +146,7 @@ public abstract class AWTAdapter implements java.util.EventListener this.newtWindow = newtProxy; } - /** + /** * Create a pipeline adapter, AWT EventListener.
                          * Once attached to an AWT component, it sends the converted AWT events to the NEWT downstream window.
                          * This is only supported with EDT enabled! @@ -162,15 +162,15 @@ public abstract class AWTAdapter implements java.util.EventListener } } - public final com.jogamp.newt.Window getNewtWindow() { - return newtWindow; + public final com.jogamp.newt.Window getNewtWindow() { + return newtWindow; } - + public final com.jogamp.newt.event.NEWTEventListener getNewtEventListener() { - return newtListener; + return newtListener; } - - /** + + /** * Due to the fact that some NEWT {@link com.jogamp.newt.event.NEWTEventListener} * are mapped to more than one {@link java.util.EventListener}, * this method is for your convenience to use this Adapter as a listener for all types.
                          diff --git a/src/newt/classes/com/jogamp/newt/event/awt/AWTKeyAdapter.java b/src/newt/classes/com/jogamp/newt/event/awt/AWTKeyAdapter.java index bef2e5d0f..1b53671ba 100644 --- a/src/newt/classes/com/jogamp/newt/event/awt/AWTKeyAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/awt/AWTKeyAdapter.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,18 +20,18 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.newt.event.awt; import jogamp.newt.awt.event.AWTNewtEventFactory; /** - * AWT: + * AWT: * printable: PRESSED (t0), TYPED (t0), RELEASED (t1) * non-printable: PRESSED (t0), RELEASED (t1) */ diff --git a/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java b/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java index 115743a0d..ab4bf7a3f 100644 --- a/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,17 +20,17 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.newt.event.awt; import jogamp.newt.awt.event.AWTNewtEventFactory; -public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseListener, +public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.awt.event.MouseWheelListener { diff --git a/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java b/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java index e91bb2f82..8c9781b77 100644 --- a/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,20 +20,20 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.newt.event.awt; import java.awt.Dimension; import jogamp.newt.awt.event.AWTNewtEventFactory; -public class AWTWindowAdapter - extends AWTAdapter +public class AWTWindowAdapter + extends AWTAdapter implements java.awt.event.ComponentListener, java.awt.event.WindowListener, java.awt.event.FocusListener { WindowClosingListener windowClosingListener; @@ -63,17 +63,17 @@ public class AWTWindowAdapter if(awtComponent instanceof java.awt.Window) { ((java.awt.Window)awtComponent).addWindowListener(this); } - return this; + return this; } - + public AWTAdapter removeWindowClosingFrom(java.awt.Component awtComponent) { java.awt.Window win = getWindow(awtComponent); if( null != win && null != windowClosingListener ) { win.removeWindowListener(windowClosingListener); } - return this; + return this; } - + public AWTAdapter removeFrom(java.awt.Component awtComponent) { awtComponent.removeFocusListener(this); awtComponent.removeComponentListener(this); @@ -225,7 +225,7 @@ public class AWTWindowAdapter enqueueEvent(true, event); } } - public void windowClosed(java.awt.event.WindowEvent e) { + public void windowClosed(java.awt.event.WindowEvent e) { com.jogamp.newt.event.WindowEvent event = AWTNewtEventFactory.createWindowEvent(e, newtWindow); if(null!=newtListener) { ((com.jogamp.newt.event.WindowListener)newtListener).windowDestroyed(event); diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index cae1a06a2..ac81e8469 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -127,7 +127,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind } @Override - public void windowResized(WindowEvent e) { + public void windowResized(WindowEvent e) { defaultWindowResizedOp(getWidth(), getHeight()); } @@ -139,7 +139,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind public final Object getUpstreamWidget() { return window; } - + /** * Creates a new GLWindow attaching a new Window referencing a * new default Screen and default Display with the given GLCapabilities. @@ -218,7 +218,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind @Override public final CapabilitiesImmutable getChosenCapabilities() { final GLDrawable _drawable = drawable; - return null != _drawable ? _drawable.getChosenGLCapabilities() : window.getChosenCapabilities(); + return null != _drawable ? _drawable.getChosenGLCapabilities() : window.getChosenCapabilities(); } @Override @@ -339,7 +339,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind public final int getY() { return window.getY(); } - + @Override public final int getWidth() { return window.getWidth(); @@ -349,7 +349,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind public final int getHeight() { return window.getHeight(); } - + @Override public final void setPosition(int x, int y) { window.setPosition(x, y); @@ -363,7 +363,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind public final boolean setFullscreen(boolean fullscreen) { return window.setFullscreen(fullscreen); } - + @Override public boolean setFullscreen(List monitors) { return window.setFullscreen(monitors); @@ -418,7 +418,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind public void setWindowDestroyNotifyAction(Runnable r) { window.setWindowDestroyNotifyAction(r); } - + @Override public final void setVisible(boolean visible) { window.setVisible(visible); @@ -450,7 +450,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind public void preserveGLStateAtDestroy(boolean value) { GLWindow.this.preserveGLStateAtDestroy(value); } - + @Override public synchronized void destroyActionPreLock() { // nop @@ -464,7 +464,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind //Exception e1 = new Exception(msg); //e1.printStackTrace(); } - + destroyImplInLock(); if(Window.DEBUG_IMPLEMENTATION) { @@ -493,7 +493,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind } else { t0 = 0; } - + if (null == drawable && visible && 0 != window.getWindowHandle() && 0 * At native creation, {@link #setVisible(boolean) setVisible(true)}, @@ -619,7 +619,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind setVisible(true); } } - + /** * {@inheritDoc} *

                          @@ -643,7 +643,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind public final void swapBuffers() throws GLException { defaultSwapBuffers(); } - + //---------------------------------------------------------------------- // NEWTEventConsumer // @@ -807,7 +807,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind public final void removeGestureListener(GestureHandler.GestureListener gl) { window.removeGestureListener(gl); } - + //---------------------------------------------------------------------- // NativeWindow completion // @@ -893,7 +893,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind _forceGL3 = true; } else if(args[i].equals("-gl4es3")) { _forceGL4ES3 = true; - } + } } } forceES2 = _forceES2; @@ -905,7 +905,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind System.err.println("forceES3 "+forceES3); System.err.println("forceGL3 "+forceGL3); System.err.println("forceGL4ES3 "+forceGL4ES3); - + System.err.println(VersionUtil.getPlatformInfo()); System.err.println(GlueGenVersion.getInstance()); System.err.println(JoglVersion.getInstance()); diff --git a/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java index a2135273b..a25b43777 100644 --- a/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java +++ b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -71,9 +71,9 @@ import com.jogamp.newt.util.EDTUtil; public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { private static final boolean DEBUG = Debug.debug("Window"); private static final boolean isOSX = NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false); - - private final AbstractGraphicsScreen screen; - + + private final AbstractGraphicsScreen screen; + private WindowClosingMode newtChildCloseOp = WindowClosingMode.DISPOSE_ON_CLOSE; private volatile Rectangle clientArea; @@ -82,22 +82,22 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { private volatile boolean newtChildReady = false; // ready if SWTEDTUtil is set and newtChild parented private volatile boolean postSetSize = false; // pending resize - /** - * Creates an instance using {@link #NewtCanvasSWT(Composite, int, Window)} + /** + * Creates an instance using {@link #NewtCanvasSWT(Composite, int, Window)} * on the SWT thread. - * + * *

                          * Note: The NEWT child {@link Display}'s {@link EDTUtil} is being set to an SWT conform implementation - * via {@link Display#setEDTUtil(EDTUtil)}. + * via {@link Display#setEDTUtil(EDTUtil)}. *

                          - * + * * @param parent the SWT composite - * @param style additional styles to SWT#NO_BACKGROUND - * @param child optional preassigned {@link #Window}, maybe null + * @param style additional styles to SWT#NO_BACKGROUND + * @param child optional preassigned {@link #Window}, maybe null * @return a new instance */ public static NewtCanvasSWT create(final Composite parent, final int style, final Window child) { - final NewtCanvasSWT[] res = new NewtCanvasSWT[] { null }; + final NewtCanvasSWT[] res = new NewtCanvasSWT[] { null }; parent.getDisplay().syncExec( new Runnable() { public void run() { res[0] = new NewtCanvasSWT( parent, style, child); @@ -105,22 +105,22 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { }); return res[0]; } - + /** * Instantiates a NewtCanvas with a NEWT child. - * + * *

                          * Note: The NEWT child {@link Display}'s {@link EDTUtil} is being set to an SWT conform implementation - * via {@link Display#setEDTUtil(EDTUtil)}. + * via {@link Display#setEDTUtil(EDTUtil)}. *

                          - * + * * @param parent the SWT composite - * @param style additional styles to SWT#NO_BACKGROUND - * @param child optional preassigned {@link #Window}, maybe null + * @param style additional styles to SWT#NO_BACKGROUND + * @param child optional preassigned {@link #Window}, maybe null */ public NewtCanvasSWT(final Composite parent, final int style, Window child) { super(parent, style | SWT.NO_BACKGROUND); - + SWTAccessor.setRealized(this, true); clientArea = getClientArea(); @@ -128,7 +128,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { final AbstractGraphicsDevice device = SWTAccessor.getDevice(this); screen = SWTAccessor.getScreen(device, -1 /* default */); nativeWindow = null; - + if(null != child) { setNEWTChild(child); } @@ -161,12 +161,12 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { addListener (SWT.Paint, listener); addListener (SWT.Dispose, listener); } - + /** assumes nativeWindow == null ! */ protected final boolean validateNative() { updateSizeCheck(); final Rectangle nClientArea = clientArea; - if(0 >= nClientArea.width || 0 >= nClientArea.height) { + if(0 >= nClientArea.width || 0 >= nClientArea.height) { return false; } screen.getDevice().open(); @@ -177,9 +177,9 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { final boolean visualIDValid = NativeWindowFactory.isNativeVisualIDValidForProcessing(visualID); if(DEBUG) { System.err.println("NewtCanvasSWT.validateNative() windowHandle 0x"+Long.toHexString(nativeWindowHandle)+", visualID 0x"+Integer.toHexString(visualID)+", valid "+visualIDValid); - } + } if( visualIDValid ) { - /* Get the nativewindow-Graphics Device associated with this control (which is determined by the parent Composite). + /* Get the nativewindow-Graphics Device associated with this control (which is determined by the parent Composite). * Note: SWT is owner of the native handle, hence no closing operation will be a NOP. */ final CapabilitiesImmutable caps = new Capabilities(); final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(screen.getDevice(), caps); @@ -187,7 +187,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { if(DEBUG) { System.err.println("NewtCanvasSWT.validateNative() factory: "+factory+", windowHandle 0x"+Long.toHexString(nativeWindowHandle)+", visualID 0x"+Integer.toHexString(visualID)+", chosen config: "+config); // Thread.dumpStack(); - } + } if (null == config) { throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); } @@ -198,11 +198,11 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { return null != nativeWindow; } - + protected final void updateSizeCheck() { final Rectangle oClientArea = clientArea; final Rectangle nClientArea = getClientArea(); - if ( nClientArea != null && + if ( nClientArea != null && ( nClientArea.width != oClientArea.width || nClientArea.height != oClientArea.height ) ) { clientArea = nClientArea; // write back new value @@ -217,12 +217,12 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { } } } - + @Override public void update() { // don't paint background etc .. nop avoids flickering } - + /** * Destroys this resource: *
                            @@ -248,12 +248,12 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { } screen.getDevice().close(); nativeWindow = null; - super.dispose(); + super.dispose(); } - + /** @return this SWT Canvas NativeWindow representation, may be null in case it has not been realized. */ public NativeWindow getNativeWindow() { return nativeWindow; } - + public WindowClosingMode getDefaultCloseOperation() { return newtChildCloseOp; // TODO: implement ?! } @@ -264,28 +264,28 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { boolean isParent() { - return null!=newtChild ; + return null!=newtChild ; } boolean isFullscreen() { return null != newtChild && newtChild.isFullscreen(); } - /** + /** * Sets a new NEWT child, provoking reparenting. *

                            * A previously detached newChild will be released to top-level status - * and made invisible. + * and made invisible. *

                            *

                            - * Note: When switching NEWT child's, detaching the previous first via setNEWTChild(null) - * produced much cleaner visual results. + * Note: When switching NEWT child's, detaching the previous first via setNEWTChild(null) + * produced much cleaner visual results. *

                            *

                            * Note: The NEWT child {@link Display}'s {@link EDTUtil} is being set to an SWT conform implementation - * via {@link Display#setEDTUtil(EDTUtil)}. + * via {@link Display#setEDTUtil(EDTUtil)}. *

                            - * @return the previous attached newt child. + * @return the previous attached newt child. */ public Window setNEWTChild(final Window newChild) { final Window prevChild = newtChild; @@ -302,14 +302,14 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { if(null != nativeWindow && null != newChild) { reparentWindow( true ); } - return prevChild; + return prevChild; } - + /** @return the current NEWT child */ public Window getNEWTChild() { return newtChild; } - + @Override public boolean setParent(Composite parent) { return super.setParent(parent); @@ -319,11 +319,11 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { newtChildReady = attach; if( null != newtChild ) { newtChild.setKeyboardFocusHandler(null); - if(attach) { - newtChildCloseOp = newtChild.setDefaultCloseOperation(WindowClosingMode.DO_NOTHING_ON_CLOSE); + if(attach) { + newtChildCloseOp = newtChild.setDefaultCloseOperation(WindowClosingMode.DO_NOTHING_ON_CLOSE); } else { newtChild.setFocusAction(null); - newtChild.setDefaultCloseOperation(newtChildCloseOp); + newtChild.setDefaultCloseOperation(newtChildCloseOp); } } } @@ -335,13 +335,13 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { if(DEBUG) { System.err.println("NewtCanvasSWT.reparentWindow.0: add="+add+", win "+newtWinHandleToHexString(newtChild)+", EDTUtil: cur "+newtChild.getScreen().getDisplay().getEDTUtil()); } - + newtChild.setFocusAction(null); // no AWT focus traversal .. if(add) { updateSizeCheck(); final int w = clientArea.width; final int h = clientArea.height; - + // set SWT EDT and start it { final Display newtDisplay = newtChild.getScreen().getDisplay(); @@ -349,14 +349,14 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { edtUtil.start(); newtDisplay.setEDTUtil( edtUtil ); } - - newtChild.setSize(w, h); + + newtChild.setSize(w, h); newtChild.reparentWindow(nativeWindow); newtChild.setVisible(true); - configureNewtChild(true); + configureNewtChild(true); newtChild.sendWindowEvent(WindowEvent.EVENT_WINDOW_RESIZED); // trigger a resize/relayout to listener - - // force this SWT Canvas to be focus-able, + + // force this SWT Canvas to be focus-able, // since it is completely covered by the newtChild (z-order). setEnabled(true); } else { @@ -375,19 +375,19 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { newtChild.requestFocus(); } } - + @Override public boolean forceFocus() { final boolean res = NewtCanvasSWT.super.forceFocus(); requestFocusNEWTChild(); - return res; + return res; } - + private class SWTNativeWindow implements NativeWindow { private final AbstractGraphicsConfiguration config; private final long nativeWindowHandle; private final InsetsImmutable insets; // only required to allow proper client position calculation on OSX - + public SWTNativeWindow(AbstractGraphicsConfiguration config, long nativeWindowHandle) { this.config = config; this.nativeWindowHandle = nativeWindowHandle; @@ -397,7 +397,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { this.insets = new Insets(0, 0, 0, 0); } } - + @Override public int lockSurface() throws NativeWindowException, RuntimeException { return NativeSurface.LOCK_SUCCESS; @@ -432,7 +432,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { } @Override - public long getSurfaceHandle() { + public long getSurfaceHandle() { return 0; } @@ -462,7 +462,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { } @Override - public void surfaceUpdated(Object updater, NativeSurface ns, long when) { } + public void surfaceUpdated(Object updater, NativeSurface ns, long when) { } @Override public void destroy() { } @@ -497,7 +497,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { if( isOSX ) { final Point los = OSXUtil.GetLocationOnScreen(nativeWindowHandle, false, 0, 0); // top-level position -> client window position - los.set(los.getX() + insets.getLeftWidth(), los.getY() + insets.getTopHeight()); + los.set(los.getX() + insets.getLeftWidth(), los.getY() + insets.getTopHeight()); if(null!=point) { return point.translate(los); } else { @@ -506,7 +506,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { } else { // client position on 'normal' windowing systems is 0/0 if(null == point) { - point = new Point(0, 0); + point = new Point(0, 0); } return point; } @@ -515,7 +515,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { @Override public boolean hasFocus() { return isFocusControl(); - } + } }; static String newtWinHandleToHexString(Window w) { diff --git a/src/newt/classes/com/jogamp/newt/util/EDTUtil.java b/src/newt/classes/com/jogamp/newt/util/EDTUtil.java index 52ca95682..582dc3e1f 100644 --- a/src/newt/classes/com/jogamp/newt/util/EDTUtil.java +++ b/src/newt/classes/com/jogamp/newt/util/EDTUtil.java @@ -63,17 +63,17 @@ public interface EDTUtil { * @param ms poll period in milliseconds */ public void setPollPeriod(long ms); - + /** * Starts the EDT after it's creation or after {@link #invokeStop(boolean, Runnable) stopping}. *

                            * If the EDT is running, it must be {@link #invokeStop(boolean, Runnable) stopped} first * and the caller should wait {@link #waitUntilStopped() until it's stopped}. *

                            - * + * * @return true if EDT has been successfully restarted, otherwise false * @throws IllegalStateException if EDT is running and not subject to be stopped, i.e. {@link #isRunning()} returns true - * + * * @see #invokeStop(boolean, java.lang.Runnable) * @see #waitUntilStopped() */ @@ -82,11 +82,11 @@ public interface EDTUtil { /** * Returns true if the current thread is the event dispatch thread (EDT). *

                            - * The EDT is the platform specific thread dispatching toolkit-events + * The EDT is the platform specific thread dispatching toolkit-events * and executing toolkit-tasks enqueued via {@link #invoke(boolean, Runnable)}. *

                            *

                            - * Usually it is the same thread as used to dequeue informal {@link NEWTEvent}s (NEDT), see {@link #isCurrentThreadNEDT()}, + * Usually it is the same thread as used to dequeue informal {@link NEWTEvent}s (NEDT), see {@link #isCurrentThreadNEDT()}, * however, this may differ, e.g. SWT and AWT implementation. *

                            */ @@ -95,28 +95,28 @@ public interface EDTUtil { /** * Returns true if the current thread is the internal NEWT event dequeue thread (NEDT). *

                            - * The NEDT is the NEWT thread used to dequeue informal {@link NEWTEvent}s enqueued internally + * The NEDT is the NEWT thread used to dequeue informal {@link NEWTEvent}s enqueued internally * via {@link DisplayImpl#enqueueEvent(boolean, NEWTEvent)}. *

                            *

                            - * Usually it is the same thread as the EDT, see {@link #isCurrentThreadEDT()}, + * Usually it is the same thread as the EDT, see {@link #isCurrentThreadEDT()}, * however, this may differ, e.g. SWT and AWT implementation. *

                            */ public boolean isCurrentThreadNEDT(); - + /** * Returns true if either {@link #isCurrentThreadEDT()} or {@link #isCurrentThreadNEDT()} is true, * otherwise false. */ public boolean isCurrentThreadEDTorNEDT(); - + /** * @return True if EDT is running and not subject to be stopped. */ public boolean isRunning(); - /** + /** * Append the final task to the EDT task queue, * signals EDT to stop. *

                            @@ -133,22 +133,22 @@ public interface EDTUtil { *

                          • {@link #start()} may follow immediately, ie creating a new EDT
                          • *
                          *

                          - * @return true if task has been executed or queued for later execution, otherwise false + * @return true if task has been executed or queued for later execution, otherwise false */ public boolean invokeStop(boolean wait, Runnable finalTask); - /** + /** * Appends task to the EDT task queue if current thread is not EDT, - * otherwise execute task immediately. + * otherwise execute task immediately. *

                          * Wait until execution is finished if wait == true. *

                          * Can be issued from within EDT, ie from within an enqueued task.
                          - * @return true if task has been executed or queued for later execution, otherwise false + * @return true if task has been executed or queued for later execution, otherwise false */ public boolean invoke(boolean wait, Runnable task); - /** + /** * Wait until the EDT task queue is empty.
                          * The last task may still be in execution when this method returns. * @return true if waited for idle, otherwise false, i.e. in case of current thread is EDT or NEDT diff --git a/src/newt/classes/com/jogamp/newt/util/MainThread.java b/src/newt/classes/com/jogamp/newt/util/MainThread.java index 5e79e9b49..049320b21 100644 --- a/src/newt/classes/com/jogamp/newt/util/MainThread.java +++ b/src/newt/classes/com/jogamp/newt/util/MainThread.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2009 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 @@ -29,7 +29,7 @@ * 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. @@ -54,13 +54,13 @@ import jogamp.newt.NEWTJNILibLoader; * NEWT Utility class MainThread

                          * *

                          - * FIXME: Update this documentation! + * FIXME: Update this documentation! * This class just provides a main-thread utility, forking of a main java class * on another thread while being able to continue doing platform specific things * on the main-thread. The latter is essential for eg. MacOSX, where we continue * to run NSApp.run(). *

                          - * + * * This class provides a startup singleton main thread, * from which a new thread with the users main class is launched.
                          * @@ -72,17 +72,17 @@ import jogamp.newt.NEWTJNILibLoader; * use a NEWT multithreaded application with window handling within the different threads, * even on these restricted platforms.
                          * - * To support your NEWT Window platform, + * To support your NEWT Window platform, * you have to pass your main thread actions to {@link #invoke invoke(..)}, * have a look at the {@link jogamp.newt.driver.macosx.WindowDriver NEWT Mac OSX Window} driver implementation.
                          - * TODO: Some hardcoded dependencies exist in this implementation, + * TODO: Some hardcoded dependencies exist in this implementation, * where you have to patch this code or factor it out.

                          - * + * * If your platform is not Mac OS X, but you want to test your code without modifying * this class, you have to set the system property newt.MainThread.force to true.

                          * * The code is compatible with all other platform, which support multithreaded windowing handling. - * Since those platforms won't trigger the main thread serialization, the main method + * Since those platforms won't trigger the main thread serialization, the main method * will be simply executed, in case you haven't set newt.MainThread.force to true.

                          * * Test case on Mac OS X (or any other platform): @@ -96,35 +96,35 @@ public class MainThread { private static final Platform.OSType osType; private static final boolean isMacOSX; private static final ThreadGroup rootThreadGroup; - + /** if true, use the main thread EDT, otherwise AWT's EDT */ public static final boolean HINT_USE_MAIN_THREAD; - + static { NativeWindowFactory.initSingleton(); NEWTJNILibLoader.loadNEWT(); - HINT_USE_MAIN_THREAD = !NativeWindowFactory.isAWTAvailable() || + HINT_USE_MAIN_THREAD = !NativeWindowFactory.isAWTAvailable() || Debug.getBooleanProperty("newt.MainThread.force", true); osType = Platform.getOSType(); isMacOSX = osType == Platform.OSType.MACOS; rootThreadGroup = getRootThreadGroup(); } - + public static boolean useMainThread = false; - + protected static final boolean DEBUG = Debug.debug("MainThread"); private static final MainThread singletonMainThread = new MainThread(); // one singleton MainThread - + private static final ThreadGroup getRootThreadGroup() { ThreadGroup rootGroup = Thread.currentThread( ).getThreadGroup( ); ThreadGroup parentGroup; while ( ( parentGroup = rootGroup.getParent() ) != null ) { rootGroup = parentGroup; } - return rootGroup; + return rootGroup; } - + private static final Thread[] getAllThreads(int[] count) { int tn; Thread[] threads = new Thread[ rootThreadGroup.activeCount() ]; @@ -149,17 +149,17 @@ public class MainThread { t.printStackTrace(); } } - return res; + return res; } private static final int getNonDaemonThreadCount(List ignoreThreads) { int res = 0; int[] tn = { 0 }; Thread[] threads = getAllThreads(tn); - + for(int i = tn[0] - 1; i >= 0; i--) { final Thread thread = threads[i]; try { - if(thread.isAlive() && !thread.isDaemon() && !ignoreThreads.contains(thread)) { + if(thread.isAlive() && !thread.isDaemon() && !ignoreThreads.contains(thread)) { res++; if(DEBUG) System.err.println("MainAction.run(): non daemon thread: "+thread); } @@ -167,9 +167,9 @@ public class MainThread { t.printStackTrace(); } } - return res; + return res; } - + static class UserApp extends Thread { private final String mainClassNameShort; private final String mainClassName; @@ -181,7 +181,7 @@ public class MainThread { super(); this.mainClassName=mainClassName; this.mainClassArgs=mainClassArgs; - + final Class mainClass = ReflectionUtil.getClass(mainClassName, true, getClass().getClassLoader()); if(null==mainClass) { throw new ClassNotFoundException("MainAction couldn't find main class "+mainClassName); @@ -192,7 +192,7 @@ public class MainThread { setName(getName()+"-UserApp-"+mainClassNameShort); setDaemon(false); - + if(DEBUG) System.err.println("MainAction(): instantiated: "+getName()+", is daemon "+isDaemon()+", main-class: "+mainClass.getName()); } @@ -230,32 +230,32 @@ public class MainThread { if(isMacOSX) { try { if(DEBUG) { - System.err.println("MainAction.main(): "+Thread.currentThread()+" MainAction fin - stopNSApp.0"); + System.err.println("MainAction.main(): "+Thread.currentThread()+" MainAction fin - stopNSApp.0"); } - ReflectionUtil.callStaticMethod(MACOSXDisplayClassName, "stopNSApplication", + ReflectionUtil.callStaticMethod(MACOSXDisplayClassName, "stopNSApplication", null, null, MainThread.class.getClassLoader()); if(DEBUG) { - System.err.println("MainAction.main(): "+Thread.currentThread()+" MainAction fin - stopNSApp.X"); + System.err.println("MainAction.main(): "+Thread.currentThread()+" MainAction fin - stopNSApp.X"); } } catch (Exception e) { e.printStackTrace(); } } else { if(DEBUG) System.err.println("MainAction.run(): "+Thread.currentThread().getName()+" MainAction fin - System.exit(0)"); - System.exit(0); - } + System.exit(0); + } } } } private static UserApp mainAction; - /** Your new java application main entry, which pipelines your application - * @throws ClassNotFoundException - * @throws NoSuchMethodException + /** Your new java application main entry, which pipelines your application + * @throws ClassNotFoundException + * @throws NoSuchMethodException * @throws SecurityException */ public static void main(String[] args) throws SecurityException, NoSuchMethodException, ClassNotFoundException { final Thread cur = Thread.currentThread(); - + useMainThread = HINT_USE_MAIN_THREAD; if(DEBUG) { @@ -268,7 +268,7 @@ public class MainThread { if(!useMainThread && !NativeWindowFactory.isAWTAvailable()) { throw new RuntimeException("!USE_MAIN_THREAD and no AWT available"); } - + if(args.length==0) { return; } @@ -282,7 +282,7 @@ public class MainThread { mainAction = new UserApp(mainClassName, mainClassArgs); if(isMacOSX) { - ReflectionUtil.callStaticMethod(MACOSXDisplayClassName, "initSingleton", + ReflectionUtil.callStaticMethod(MACOSXDisplayClassName, "initSingleton", null, null, MainThread.class.getClassLoader()); } @@ -290,24 +290,24 @@ public class MainThread { try { cur.setName(cur.getName()+"-MainThread"); } catch (Exception e) {} - + // dispatch user's main thread .. mainAction.start(); - + if(isMacOSX) { try { if(DEBUG) { - System.err.println("MainThread.main(): "+cur.getName()+"- runNSApp"); + System.err.println("MainThread.main(): "+cur.getName()+"- runNSApp"); } - ReflectionUtil.callStaticMethod(MACOSXDisplayClassName, "runNSApplication", + ReflectionUtil.callStaticMethod(MACOSXDisplayClassName, "runNSApplication", null, null, MainThread.class.getClassLoader()); } catch (Exception e) { e.printStackTrace(); } - } - if(DEBUG) { System.err.println("MainThread - wait until last non daemon thread ends ..."); } + } + if(DEBUG) { System.err.println("MainThread - wait until last non daemon thread ends ..."); } } else { - // run user's main in this thread + // run user's main in this thread mainAction.run(); } } diff --git a/src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java b/src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java index c30b427d6..fdd7985fe 100644 --- a/src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java +++ b/src/newt/classes/com/jogamp/newt/util/MonitorModeUtil.java @@ -42,7 +42,7 @@ import javax.media.nativewindow.util.SurfaceSize; * filters etc. */ public class MonitorModeUtil { - + public static int getIndex(List monitorModes, MonitorMode search) { return monitorModes.indexOf(search); } @@ -69,7 +69,7 @@ public class MonitorModeUtil { } return null; } - + /** Sort the given {@link MonitorMode} collection w/ {@link MonitorMode#compareTo(MonitorMode)} function. */ public static void sort(List monitorModes, boolean ascendingOrder) { if( ascendingOrder ) { @@ -78,9 +78,9 @@ public class MonitorModeUtil { Collections.sort(monitorModes, MonitorMode.monitorModeComparatorInv); } } - + /** - * + * * @param monitorModes * @param surfaceSize * @return modes with exact {@link SurfaceSize}. May return zero sized list for non. @@ -99,7 +99,7 @@ public class MonitorModeUtil { } /** - * + * * @param monitorModes * @param rotation * @return modes with exact rotation. May return zero sized list for non. @@ -118,7 +118,7 @@ public class MonitorModeUtil { } /** - * + * * @param monitorModes * @param bitsPerPixel * @return modes with exact bpp. May return zero sized list for non. @@ -137,7 +137,7 @@ public class MonitorModeUtil { } /** - * + * * @param monitorModes * @param flags * @return modes with exact flags. May return zero sized list for non. @@ -165,7 +165,7 @@ public class MonitorModeUtil { if( null!=monitorModes && monitorModes.size()>0 ) { final int resolution_sq = resolution.getHeight()*resolution.getWidth(); int mode_dsq=Integer.MAX_VALUE, mode_dsq_idx=0; - + for (int i=0; null!=monitorModes && i() { public Object run() { PropertyAccess.addTrustedPrefix("newt."); return null; } } ); - + verbose = isPropertyDefined("newt.verbose", true); debugAll = isPropertyDefined("newt.debug", true); if (verbose) { diff --git a/src/newt/classes/jogamp/newt/DefaultEDTUtil.java b/src/newt/classes/jogamp/newt/DefaultEDTUtil.java index 3d1037ad5..f33b4744e 100644 --- a/src/newt/classes/jogamp/newt/DefaultEDTUtil.java +++ b/src/newt/classes/jogamp/newt/DefaultEDTUtil.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2009 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 @@ -29,7 +29,7 @@ * 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. @@ -51,7 +51,7 @@ public class DefaultEDTUtil implements EDTUtil { public static final boolean DEBUG = Debug.debug("EDT"); private final Object edtLock = new Object(); // locking the EDT start/stop state - private /* final */ ThreadGroup threadGroup; + private /* final */ ThreadGroup threadGroup; private final String name; private final Runnable dispatchMessages; private NEDT edt = null; @@ -75,7 +75,7 @@ public class DefaultEDTUtil implements EDTUtil { final public void setPollPeriod(long ms) { pollPeriod = ms; } - + @Override public final boolean start() throws IllegalStateException { synchronized(edtLock) { @@ -117,7 +117,7 @@ public class DefaultEDTUtil implements EDTUtil { public final boolean isCurrentThreadEDT() { return edt == Thread.currentThread(); // EDT == NEDT } - + @Override public final boolean isCurrentThreadNEDT() { return edt == Thread.currentThread(); // EDT == NEDT @@ -126,8 +126,8 @@ public class DefaultEDTUtil implements EDTUtil { @Override public final boolean isCurrentThreadEDTorNEDT() { return edt == Thread.currentThread(); // EDT == NEDT - } - + } + @Override public final boolean isRunning() { return edt.isRunning() ; @@ -149,9 +149,9 @@ public class DefaultEDTUtil implements EDTUtil { private static Runnable nullTask = new Runnable() { @Override - public void run() { } + public void run() { } }; - + private final boolean invokeImpl(boolean wait, Runnable task, boolean stop) { Throwable throwable = null; RunnableTask rTask = null; @@ -201,7 +201,7 @@ public class DefaultEDTUtil implements EDTUtil { synchronized(edt.tasks) { rTask = new RunnableTask(task, wait ? rTaskLock : null, - true /* always catch and report Exceptions, don't disturb EDT */, + true /* always catch and report Exceptions, don't disturb EDT */, wait ? null : System.err); if(stop) { rTask.setAttachment(new Boolean(true)); // mark final task, will imply shouldStop:=true @@ -305,8 +305,8 @@ public class DefaultEDTUtil implements EDTUtil { throw new InternalError("XXX"); } } - - /** + + /** * Utilizing locking only on tasks and its execution, * not for event dispatching. */ @@ -315,7 +315,7 @@ public class DefaultEDTUtil implements EDTUtil { if(DEBUG) { System.err.println(getName()+": Default-EDT run() START "+ getName()); } - if(Lock.DEBUG) { + if(Lock.DEBUG) { validateNoRecursiveLocksHold(); } RuntimeException error = null; @@ -368,7 +368,7 @@ public class DefaultEDTUtil implements EDTUtil { } finally { if(DEBUG) { RunnableTask rt = ( tasks.size() > 0 ) ? tasks.get(0) : null ; - System.err.println(getName()+": Default-EDT run() END "+ getName()+", tasks: "+tasks.size()+", "+rt+", "+error); + System.err.println(getName()+": Default-EDT run() END "+ getName()+", tasks: "+tasks.size()+", "+rt+", "+error); } synchronized(edtLock) { isRunning = false; diff --git a/src/newt/classes/jogamp/newt/DisplayImpl.java b/src/newt/classes/jogamp/newt/DisplayImpl.java index 0f47c87a0..c6cb706a4 100644 --- a/src/newt/classes/jogamp/newt/DisplayImpl.java +++ b/src/newt/classes/jogamp/newt/DisplayImpl.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt; @@ -60,16 +60,16 @@ public abstract class DisplayImpl extends Display { } }); } - + /** Ensure static init has been run. */ /* pp */static void initSingleton() { } - - private static Class getDisplayClass(String type) - throws ClassNotFoundException + + private static Class getDisplayClass(String type) + throws ClassNotFoundException { final Class displayClass = NewtFactory.getCustomClass(type, "DisplayDriver"); if(null==displayClass) { - throw new ClassNotFoundException("Failed to find NEWT Display Class <"+type+".DisplayDriver>"); + throw new ClassNotFoundException("Failed to find NEWT Display Class <"+type+".DisplayDriver>"); } return displayClass; } @@ -100,7 +100,7 @@ public abstract class DisplayImpl extends Display { display.setEDTUtil( display.edtUtil ); // device's default if EDT is used, or null Display.addDisplay2List(display); } - + if(DEBUG) { System.err.println("Display.create() NEW: "+display+" "+getThreadName()); } @@ -109,7 +109,7 @@ public abstract class DisplayImpl extends Display { throw new RuntimeException(e); } } - + @Override public boolean equals(Object obj) { if (obj == null) { @@ -168,7 +168,7 @@ public abstract class DisplayImpl extends Display { protected EDTUtil createEDTUtil() { final EDTUtil def; if(NewtFactory.useEDT()) { - def = new DefaultEDTUtil(Thread.currentThread().getThreadGroup(), "Display-"+getFQName(), dispatchMessagesRunnable); + def = new DefaultEDTUtil(Thread.currentThread().getThreadGroup(), "Display-"+getFQName(), dispatchMessagesRunnable); if(DEBUG) { System.err.println("Display.createEDTUtil("+getFQName()+"): "+def.getClass().getName()); } @@ -271,7 +271,7 @@ public abstract class DisplayImpl extends Display { if(DEBUG) { System.err.println("Display.destroy(): "+this+", active "+displaysActive+" "+getThreadName()); } - } + } final DisplayImpl f_dpy = this; final AbstractGraphicsDevice f_aDevice = aDevice; aDevice = null; @@ -287,10 +287,10 @@ public abstract class DisplayImpl extends Display { dumpDisplayList("Display.destroy("+getFQName()+") END"); } } - + /** May be utilized at a shutdown hook, impl. does not block. */ /* pp */ static final void shutdownAll() { - final int dCount = displayList.size(); + final int dCount = displayList.size(); if(DEBUG) { dumpDisplayList("Display.shutdownAll "+dCount+" instances, on thread "+getThreadName()); } @@ -306,7 +306,7 @@ public abstract class DisplayImpl extends Display { final EDTUtil edtUtil = d.getEDTUtil(); final AbstractGraphicsDevice f_aDevice = d.aDevice; d.aDevice = null; - d.refCount=0; + d.refCount=0; final Runnable closeNativeTask = new Runnable() { public void run() { if ( null != d.getGraphicsDevice() ) { @@ -381,7 +381,7 @@ public abstract class DisplayImpl extends Display { public final String getFQName() { return fqname; } - + @Override public final boolean isExclusive() { return exclusive; @@ -438,7 +438,7 @@ public abstract class DisplayImpl extends Display { @Override public String toString() { final EDTUtil _edtUtil = edtUtil; - final boolean _edtUtilRunning = ( null != _edtUtil ) ? _edtUtil.isRunning() : false; + final boolean _edtUtilRunning = ( null != _edtUtil ) ? _edtUtil.isRunning() : false; return "NEWT-Display["+getFQName()+", excl "+exclusive+", refCount "+refCount+", hasEDT "+(null!=_edtUtil)+", edtRunning "+_edtUtilRunning+", "+aDevice+"]"; } @@ -455,8 +455,8 @@ public abstract class DisplayImpl extends Display { } }; final void dispatchMessage(final NEWTEvent event) { - try { - final Object source = event.getSource(); + try { + final Object source = event.getSource(); if(source instanceof NEWTEventConsumer) { final NEWTEventConsumer consumer = (NEWTEventConsumer) source ; if(!consumer.consumeEvent(event)) { @@ -476,10 +476,10 @@ public abstract class DisplayImpl extends Display { throw re; } } - + final void dispatchMessage(final NEWTEventTask eventTask) { final NEWTEvent event = eventTask.get(); - try { + try { if(null == event) { // Ooops ? System.err.println("Warning: event of eventTask is NULL"); @@ -495,15 +495,15 @@ public abstract class DisplayImpl extends Display { throw re; } } - eventTask.notifyCaller(); + eventTask.notifyCaller(); } - + @Override public void dispatchMessages() { // System.err.println("Display.dispatchMessages() 0 "+this+" "+getThreadName()); - if(0==refCount || // no screens + if(0==refCount || // no screens null==getGraphicsDevice() // no native device - ) + ) { return; } @@ -541,13 +541,13 @@ public abstract class DisplayImpl extends Display { } return; } - + // can't wait if we are on EDT or NEDT -> consume right away if(wait && _edtUtil.isCurrentThreadEDTorNEDT() ) { dispatchMessage(e); return; } - + final Object lock = new Object(); final NEWTEventTask eTask = new NEWTEventTask(e, wait?lock:null); synchronized(lock) { @@ -565,13 +565,13 @@ public abstract class DisplayImpl extends Display { if( null != eTask.getException() ) { throw eTask.getException(); } - } + } } } public interface DisplayRunnable { T run(long dpy); - } + } public static final T runWithLockedDevice(AbstractGraphicsDevice device, DisplayRunnable action) { T res; device.lock(); @@ -589,7 +589,7 @@ public abstract class DisplayImpl extends Display { } return runWithLockedDevice(device, action); } - + protected volatile EDTUtil edtUtil = null; protected int id; protected String name; diff --git a/src/newt/classes/jogamp/newt/MonitorDeviceImpl.java b/src/newt/classes/jogamp/newt/MonitorDeviceImpl.java index 43d558515..9e10879c4 100644 --- a/src/newt/classes/jogamp/newt/MonitorDeviceImpl.java +++ b/src/newt/classes/jogamp/newt/MonitorDeviceImpl.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.newt; import javax.media.nativewindow.util.DimensionImmutable; @@ -41,7 +41,7 @@ public class MonitorDeviceImpl extends MonitorDevice { public MonitorDeviceImpl(ScreenImpl screen, int nativeId, DimensionImmutable sizeMM, Rectangle viewport, MonitorMode currentMode, ArrayHashSet supportedModes) { super(screen, nativeId, sizeMM, viewport, currentMode, supportedModes); } - + @Override public final MonitorMode queryCurrentMode() { final ScreenImpl screenImpl = (ScreenImpl)screen; @@ -54,7 +54,7 @@ public class MonitorDeviceImpl extends MonitorDevice { } MonitorMode mmU = supportedModes.get(mm0); // unified instance if( null == mmU ) { - // add new mode avoiding exception! + // add new mode avoiding exception! mmU = sms.getMonitorModes().getOrAdd(mm0); mmU = supportedModes.getOrAdd(mmU); if( Screen.DEBUG ) { @@ -89,21 +89,21 @@ public class MonitorDeviceImpl extends MonitorDevice { if( mmU.equals( mmC ) ) { if(Screen.DEBUG) { System.err.println("Screen.setCurrentMode: 0.0 is-current (skip) "+mmU+" == "+mmC); - } + } return true; } final long tStart; if(Screen.DEBUG) { - tStart = System.currentTimeMillis(); + tStart = System.currentTimeMillis(); } else { tStart = 0; } - + sms.fireMonitorModeChangeNotify(this, mmU); if(Screen.DEBUG) { System.err.println("Screen.setCurrentMode ("+(System.currentTimeMillis()-tStart)+"ms): fireModeChangeNotify() "+mmU); } - + boolean success = screenImpl.setCurrentMonitorModeImpl(this, mmU); if(success) { if(Screen.DEBUG) { @@ -135,13 +135,13 @@ public class MonitorDeviceImpl extends MonitorDevice { private final void setCurrentModeValue(MonitorMode currentMode) { this.currentMode = currentMode; } - + /* pp */ final void setViewportValue(Rectangle viewport) { this.viewport = viewport; } - + /* pp */ ArrayHashSet getSupportedModesImpl() { return supportedModes; } - + } diff --git a/src/newt/classes/jogamp/newt/MonitorModeProps.java b/src/newt/classes/jogamp/newt/MonitorModeProps.java index 820807e15..9d8f4919c 100644 --- a/src/newt/classes/jogamp/newt/MonitorModeProps.java +++ b/src/newt/classes/jogamp/newt/MonitorModeProps.java @@ -54,12 +54,12 @@ public class MonitorModeProps { * 1: bpp */ public static final int NUM_SURFACE_SIZE_PROPERTIES = 1; - + /** WARNING: must be synchronized with ScreenMode.h, native implementation * 2: refresh-rate (Hz*100), flags */ public static final int NUM_SIZEANDRATE_PROPERTIES = 2; - + /** WARNING: must be synchronized with ScreenMode.h, native implementation * 2: id, rotation */ @@ -69,7 +69,7 @@ public class MonitorModeProps { * count + all the above */ public static final int NUM_MONITOR_MODE_PROPERTIES_ALL = 8; - + public static final int IDX_MONITOR_MODE_BPP = 1 // count + MonitorModeProps.NUM_RESOLUTION_PROPERTIES ; @@ -79,7 +79,7 @@ public class MonitorModeProps { + MonitorModeProps.NUM_SIZEANDRATE_PROPERTIES + 1 // id of MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES ; - + /** WARNING: must be synchronized with ScreenMode.h, native implementation * 10: count + id, ScreenSizeMM[width, height], rotated Viewport[x, y, width, height], currentMonitorModeId, rotation, supportedModeId+ */ @@ -89,15 +89,15 @@ public class MonitorModeProps { + 1 // native mode + MonitorModeProps.NUM_RESOLUTION_PROPERTIES // sizeMM ; - + public static class Cache { public final ArrayHashSet resolutions = new ArrayHashSet(); public final ArrayHashSet surfaceSizes = new ArrayHashSet(); - public final ArrayHashSet sizeAndRates = new ArrayHashSet(); + public final ArrayHashSet sizeAndRates = new ArrayHashSet(); public final ArrayHashSet monitorModes = new ArrayHashSet(); public final ArrayHashSet monitorDevices = new ArrayHashSet(); } - + /** WARNING: must be synchronized with ScreenMode.h, native implementation */ private static DimensionImmutable streamInResolution(int[] resolutionProperties, int offset) { Dimension resolution = new Dimension(resolutionProperties[offset++], resolutionProperties[offset++]); @@ -116,7 +116,7 @@ public class MonitorModeProps { final int flags = sizeAndRRateProperties[offset++]; return new MonitorMode.SizeAndRRate(surfaceSize, refreshRate, flags); } - + /** WARNING: must be synchronized with ScreenMode.h, native implementation */ private static MonitorMode streamInMonitorMode0(MonitorMode.SizeAndRRate sizeAndRate, int[] modeProperties, int offset) { final int id = modeProperties[offset++]; @@ -161,7 +161,7 @@ public class MonitorModeProps { if(null!=cache) { sizeAndRate = cache.sizeAndRates.getOrAdd(sizeAndRate); } - + MonitorMode monitorMode = MonitorModeProps.streamInMonitorMode0(sizeAndRate, modeProperties, offset); if(null!=cache) { monitorMode = cache.monitorModes.getOrAdd(monitorMode); @@ -193,12 +193,12 @@ public class MonitorModeProps { } return data; } - - /** + + /** * WARNING: must be synchronized with ScreenMode.h, native implementation *

                          * Note: This variant only works for impl. w/ a unique mode key pair modeId, rotation. - *

                          + *

                          * @param mode_idx if not null, returns the index of resulting {@link MonitorDevice} within {@link Cache#monitorDevices}. * @param cache hash arrays of unique {@link MonitorMode} components and {@link MonitorDevice}s, allowing to avoid duplicates * @param modeProperties the input data @@ -218,7 +218,7 @@ public class MonitorModeProps { if(count > monitorProperties.length-offset) { throw new RuntimeException("properties array too short (count), should be >= "+count+", is "+(monitorProperties.length-offset)); } - final int limit = offset + count; + final int limit = offset + count; offset++; final List allMonitorModes = cache.monitorModes.getData(); final int id = monitorProperties[offset++]; @@ -252,7 +252,7 @@ public class MonitorModeProps { monitor_idx[0] = _monitorIdx; } return monitorDevice; - } + } private static MonitorMode getByNativeIdAndRotation(List monitorModes, int modeId, int rotation) { if( null!=monitorModes && monitorModes.size()>0 ) { for (int i=0; i * This variant expects count to be {@link MIN_MONITOR_DEVICE_PROPERTIES} - 1 - {@link NUM_MONITOR_MODE_PROPERTIES}, - * due to lack of supported mode and current mode. + * due to lack of supported mode and current mode. *

                          * * @param mode_idx if not null, returns the index of resulting {@link MonitorDevice} within {@link Cache#monitorDevices}. @@ -310,7 +310,7 @@ public class MonitorModeProps { } return monitorDevice; } - + /** WARNING: must be synchronized with ScreenMode.h, native implementation */ public static int[] streamOutMonitorDevice (MonitorDevice monitorDevice) { // min 11: count, id, ScreenSizeMM[width, height], Viewport[x, y, width, height], currentMonitorModeId, rotation, supportedModeId+ @@ -339,7 +339,7 @@ public class MonitorModeProps { } return data; } - + public final void swapRotatePair(int rotation, int[] pairs, int offset, int numPairs) { if( MonitorMode.ROTATE_0 == rotation || MonitorMode.ROTATE_180 == rotation ) { // nop @@ -347,9 +347,9 @@ public class MonitorModeProps { } for(int i=0; i() { public Boolean run() { diff --git a/src/newt/classes/jogamp/newt/OffscreenWindow.java b/src/newt/classes/jogamp/newt/OffscreenWindow.java index 0a302d76b..eba844230 100644 --- a/src/newt/classes/jogamp/newt/OffscreenWindow.java +++ b/src/newt/classes/jogamp/newt/OffscreenWindow.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt; @@ -50,7 +50,7 @@ import com.jogamp.newt.MonitorDevice; public class OffscreenWindow extends WindowImpl implements MutableSurface { long surfaceHandle; - + public OffscreenWindow() { surfaceHandle = 0; } @@ -72,7 +72,7 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { synchronized(OffscreenWindow.class) { setWindowHandle(nextWindowHandle++); } - visibleChanged(false, true); + visibleChanged(false, true); } protected void closeNativeImpl() { @@ -92,7 +92,7 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { @Override public long getSurfaceHandle() { return surfaceHandle; - } + } protected void requestFocusImpl(boolean reparented) { } @@ -101,7 +101,7 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { public void setPosition(int x, int y) { // nop } - + @Override public boolean setFullscreen(boolean fullscreen) { return false; // nop @@ -112,7 +112,7 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { return false; // nop } - + protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { sizeChanged(false, width, height, false); if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { @@ -137,13 +137,13 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { } return new Point(0,0); } - + protected Point getLocationOnScreenImpl(int x, int y) { return new Point(x,y); } - + protected void updateInsetsImpl(Insets insets) { - // nop .. + // nop .. } } diff --git a/src/newt/classes/jogamp/newt/ScreenImpl.java b/src/newt/classes/jogamp/newt/ScreenImpl.java index 7068d7464..d7e6c641c 100644 --- a/src/newt/classes/jogamp/newt/ScreenImpl.java +++ b/src/newt/classes/jogamp/newt/ScreenImpl.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt; @@ -56,7 +56,7 @@ import com.jogamp.newt.util.MonitorModeUtil; public abstract class ScreenImpl extends Screen implements MonitorModeListener { protected static final boolean DEBUG_TEST_SCREENMODE_DISABLED; - + static { Debug.initSingleton(); DEBUG_TEST_SCREENMODE_DISABLED = Debug.isPropertyDefined("newt.test.Screen.disableScreenMode", true); @@ -67,14 +67,14 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { public static final int default_sm_heightmm = 324; public static final int default_sm_rate = 60; public static final int default_sm_rotation = 0; - + static { DisplayImpl.initSingleton(); } - + /** Ensure static init has been run. */ /* pp */static void initSingleton() { } - + protected DisplayImpl display; protected int screen_idx; protected String fqname; @@ -85,14 +85,14 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { protected static Dimension usrSize = null; // property values: newt.ws.swidth and newt.ws.sheight protected static volatile boolean usrSizeQueried = false; private ArrayList refMonitorModeListener = new ArrayList(); - + private long tCreated; // creationTime - private static Class getScreenClass(String type) throws ClassNotFoundException + private static Class getScreenClass(String type) throws ClassNotFoundException { final Class screenClass = NewtFactory.getCustomClass(type, "ScreenDriver"); if(null==screenClass) { - throw new ClassNotFoundException("Failed to find NEWT Screen Class <"+type+".ScreenDriver>"); + throw new ClassNotFoundException("Failed to find NEWT Screen Class <"+type+".ScreenDriver>"); } return screenClass; } @@ -104,7 +104,7 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { if(!usrSizeQueried) { usrSizeQueried = true; final int w = Debug.getIntProperty("newt.ws.swidth", true, 0); - final int h = Debug.getIntProperty("newt.ws.sheight", true, 0); + final int h = Debug.getIntProperty("newt.ws.sheight", true, 0); if(w>0 && h>0) { usrSize = new Dimension(w, h); System.err.println("User screen size "+usrSize); @@ -135,7 +135,7 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { System.err.println("Screen.create() NEW: "+screen+" "+Display.getThreadName()); } return screen; - } + } } catch (Exception e) { throw new RuntimeException(e); } @@ -167,16 +167,16 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { @Override public synchronized final void createNative() throws NativeWindowException - { + { if(null == aScreen) { if(DEBUG) { tCreated = System.nanoTime(); System.err.println("Screen.createNative() START ("+DisplayImpl.getThreadName()+", "+this+")"); } else { tCreated = 0; - } + } display.addReference(); - + createNativeImpl(); if(null == aScreen) { throw new NativeWindowException("Screen.createNative() failed to instanciate an AbstractGraphicsScreen"); @@ -249,7 +249,7 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { protected abstract void createNativeImpl(); protected abstract void closeNativeImpl(); - + /** * Returns the validated screen index, which is either the passed idx * value or 0. @@ -258,23 +258,23 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { *

                          */ protected abstract int validateScreenIndex(int idx); - + /** * Stores the virtual origin and virtual rotated screen size. *

                          - * This method is called after the MonitorMode has been set or changed, + * This method is called after the MonitorMode has been set or changed, * hence you may utilize it. *

                          *

                          * Default implementation uses the union of all monitor's viewport, - * calculated via {@link #unionOfMonitorViewportSize()}. + * calculated via {@link #unionOfMonitorViewportSize()}. *

                          * @param vOriginSize storage for result */ - protected void calcVirtualScreenOriginAndSize(final Rectangle vOriginSize) { + protected void calcVirtualScreenOriginAndSize(final Rectangle vOriginSize) { unionOfMonitorViewportSize(vOriginSize); } - + @Override public final String getFQName() { return fqname; @@ -335,15 +335,15 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { } // - // MonitorDevice and MonitorMode + // MonitorDevice and MonitorMode // - + /** * To be implemented by the native specification.
                          * Is called within a thread safe environment.
                          * Is called only to collect the {@link MonitorMode}s and {@link MonitorDevice}s, usually at startup setting up modes.
                          *
                          - * WARNING: must be synchronized with + * WARNING: must be synchronized with *
                            *
                          • {@link MonitorModeProps#NUM_SCREEN_MODE_PROPERTIES} and
                          • *
                          • {@link MonitorModeProps#MIN_MONITOR_DEVICE_PROPERTIES}
                          • @@ -356,19 +356,19 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { * @param cache memory pool caching the result */ protected abstract void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache); - + protected Rectangle getNativeMonitorDeviceViewportImpl(MonitorDevice monitor) { return null; } - + /** * To be implemented by the native specification.
                            * Is called within a thread safe environment.
                            *

                            - * Implementation shall not unify the result w/ monitor's supported modes or a locally + * Implementation shall not unify the result w/ monitor's supported modes or a locally * saved {@link MonitorModeProps.Cache}, since caller will perform such tasks. *

                            */ protected abstract MonitorMode queryCurrentMonitorModeImpl(MonitorDevice monitor); - + /** * To be implemented by the native specification.
                            * Is called within a thread safe environment.
                            @@ -378,13 +378,13 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { @Override public final List getMonitorModes() { final ScreenMonitorState sms = getScreenMonitorStatus(false); - return null != sms ? sms.getMonitorModes().getData() : null; + return null != sms ? sms.getMonitorModes().getData() : null; } - + @Override public final List getMonitorDevices() { final ScreenMonitorState sms = getScreenMonitorStatus(false); - return null != sms ? sms.getMonitorDevices().getData() : null; + return null != sms ? sms.getMonitorDevices().getData() : null; } final ScreenMonitorState getScreenMonitorStatus(boolean throwException) { @@ -395,7 +395,7 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { } return res; } - + @Override public void monitorModeChangeNotify(MonitorEvent me) { if(DEBUG) { @@ -417,9 +417,9 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { if( null != newViewport ) { monitor.setViewportValue(newViewport); } - } + } } - + @Override public void monitorModeChanged(MonitorEvent me, boolean success) { if(success) { @@ -443,9 +443,9 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { public synchronized final void removeMonitorModeListener(MonitorModeListener sml) { refMonitorModeListener.remove(sml); } - + /** - * + * * @param cache optional .. * @param modeId * @return @@ -468,7 +468,7 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { } /** - * + * * @param cache mandatory ! * @param monitorId * @param currentMode @@ -493,7 +493,7 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { } return MonitorModeProps.streamInMonitorDevice(null, cache, this, props, 0); } - + /** * Utilizes {@link #getCurrentMonitorModeImpl()}, if the latter returns null it uses * the current screen size and dummy values. @@ -530,7 +530,7 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { sms = ScreenMonitorState.getScreenMonitorState(this.getFQName()); if(null==sms) { final MonitorModeProps.Cache cache = new MonitorModeProps.Cache(); - if( 0 >= collectNativeMonitorModes(cache) ) { + if( 0 >= collectNativeMonitorModes(cache) ) { updateVirtualScreenOriginAndSize(); vScrnSizeUpdated = true; final MonitorMode mode = getVirtualMonitorMode(cache, 0); @@ -557,7 +557,7 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { System.err.println("["+i+"]["+j+"]: "+iMode.next()); } } - } + } sms = new ScreenMonitorState(cache.monitorDevices, cache.monitorModes); ScreenMonitorState.mapScreenMonitorState(this.getFQName(), sms); } @@ -580,7 +580,7 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { * Collects {@link MonitorDevice}s and {@link MonitorMode}s within the given cache. *

                            */ - private final int collectNativeMonitorModes(MonitorModeProps.Cache cache) { + private final int collectNativeMonitorModes(MonitorModeProps.Cache cache) { if(!DEBUG_TEST_SCREENMODE_DISABLED) { collectNativeMonitorModesAndDevicesImpl(cache); } @@ -639,12 +639,12 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { } finally { sms.unlock(); } - } + } } finally { ScreenMonitorState.unlockScreenMonitorState(); } } - + private final void shutdown() { ScreenMonitorState sms = ScreenMonitorState.getScreenMonitorStateUnlocked(getFQName()); if(null != sms) { @@ -661,11 +661,11 @@ public abstract class ScreenImpl extends Screen implements MonitorModeListener { } } ScreenMonitorState.unmapScreenMonitorStateUnlocked(getFQName()); - } + } } - + /** pp */ static final void shutdownAll() { - final int sCount = screenList.size(); + final int sCount = screenList.size(); if(DEBUG) { System.err.println("Screen.shutdownAll "+sCount+" instances, on thread "+Display.getThreadName()); } diff --git a/src/newt/classes/jogamp/newt/ScreenMonitorState.java b/src/newt/classes/jogamp/newt/ScreenMonitorState.java index 66e75be16..01e6cfee9 100644 --- a/src/newt/classes/jogamp/newt/ScreenMonitorState.java +++ b/src/newt/classes/jogamp/newt/ScreenMonitorState.java @@ -42,7 +42,7 @@ import java.util.HashMap; public class ScreenMonitorState { private static boolean DEBUG = Screen.DEBUG; - + private final RecursiveLock lock = LockFactory.createRecursiveLock(); private final ArrayHashSet allMonitors; private final ArrayHashSet allMonitorModes; @@ -105,21 +105,21 @@ public class ScreenMonitorState { protected static void unlockScreenMonitorState() { screen2ScreenMonitorState.unlock(); } - + public ScreenMonitorState(ArrayHashSet allMonitors, ArrayHashSet allMonitorModes) { - this.allMonitors = allMonitors; + this.allMonitors = allMonitors; this.allMonitorModes = allMonitorModes; } - protected ArrayHashSet getMonitorDevices() { + protected ArrayHashSet getMonitorDevices() { return allMonitors; } - - protected ArrayHashSet getMonitorModes() { + + protected ArrayHashSet getMonitorModes() { return allMonitorModes; } - + protected final int addListener(MonitorModeListener l) { lock(); try { @@ -151,14 +151,14 @@ public class ScreenMonitorState { protected final MonitorDevice getMonitor(MonitorDevice monitor) { return allMonitors.get(monitor); } - + protected final void validateMonitor(MonitorDevice monitor) { final MonitorDevice md = allMonitors.get(monitor); if( null == md ) { throw new InternalError("Monitor unknown: "+monitor); } } - + protected final void fireMonitorModeChangeNotify(MonitorDevice monitor, MonitorMode desiredMode) { lock(); try { diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index a35d89408..a0ef8816b 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt; @@ -87,19 +87,19 @@ import jogamp.nativewindow.SurfaceUpdatedHelper; public abstract class WindowImpl implements Window, NEWTEventConsumer { public static final boolean DEBUG_TEST_REPARENT_INCOMPATIBLE; - + static { Debug.initSingleton(); DEBUG_TEST_REPARENT_INCOMPATIBLE = Debug.isPropertyDefined("newt.test.Window.reparent.incompatible", true); - + ScreenImpl.initSingleton(); } - - protected static final ArrayList> windowList = new ArrayList>(); - + + protected static final ArrayList> windowList = new ArrayList>(); + /** Maybe utilized at a shutdown hook, impl. does not block. */ public static final void shutdownAll() { - final int wCount = windowList.size(); + final int wCount = windowList.size(); if(DEBUG_IMPLEMENTATION) { System.err.println("Window.shutdownAll "+wCount+" instances, on thread "+getThreadName()); } @@ -132,25 +132,25 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } } - + /** Timeout of queued events (repaint and resize) */ - static final long QUEUED_EVENT_TO = 1200; // ms + static final long QUEUED_EVENT_TO = 1200; // ms private static final PointerType[] constMousePointerTypes = new PointerType[] { PointerType.Mouse }; - + // // Volatile: Multithread Mutable Access - // + // private volatile long windowHandle = 0; // lifecycle critical private volatile boolean visible = false; // lifecycle critical - private volatile boolean hasFocus = false; + private volatile boolean hasFocus = false; private volatile int width = 128, height = 128; // client-area size w/o insets, default: may be overwritten by user private volatile int x = 64, y = 64; // client-area pos w/o insets private volatile Insets insets = new Insets(); // insets of decoration (if top-level && decorated) - + private RecursiveLock windowLock = LockFactory.createRecursiveLock(); // Window instance wide lock private int surfaceLockCount = 0; // surface lock recursion count - + private ScreenImpl screen; // never null after create - may change reference though (reparent) private boolean screenReferenceAdded = false; private NativeWindow parentWindow = null; @@ -162,7 +162,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer private List fullscreenMonitors = null; private boolean fullscreenUseMainMonitor = true; private boolean autoPosition = true; // default: true (allow WM to choose top-level position, if not set by user) - + private int nfs_width, nfs_height, nfs_x, nfs_y; // non fullscreen client-area size/pos w/o insets private NativeWindow nfs_parent = null; // non fullscreen parent, in case explicit reparenting is performed (offscreen) private String title = "Newt Window"; @@ -178,26 +178,26 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer private KeyListener keyboardFocusHandler = null; private SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper(); - + private Object childWindowsLock = new Object(); private ArrayList childWindows = new ArrayList(); private ArrayList mouseListeners = new ArrayList(); - + /** from event passing: {@link WindowImpl#consumePointerEvent(MouseEvent)}. */ private static class PointerState0 { /** mouse entered window - is inside the window (may be synthetic) */ boolean insideWindow = false; - + /** last time when a mouse button was pressed */ long lastButtonPressTime = 0; - + void clearButton() { lastButtonPressTime = 0; } } private PointerState0 pState0 = new PointerState0(); - + /** from direct input: {@link WindowImpl#doPointerEvent(boolean, boolean, int[], short, int, int, boolean, short[], int[], int[], float[], float, float[], float)}. */ private static class PointerState1 extends PointerState0 { /** current pressed mouse button number */ @@ -206,15 +206,15 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer int buttonPressedMask = 0; /** last mouse button click count */ short lastButtonClickCount = (short)0; - + final void clearButton() { super.clearButton(); lastButtonPressTime = 0; - lastButtonClickCount = (short)0; + lastButtonClickCount = (short)0; buttonPressed = 0; - buttonPressedMask = 0; + buttonPressedMask = 0; } - + /** last pointer-move position for 8 touch-down pointers */ final Point[] movePositions = new Point[] { new Point(), new Point(), new Point(), new Point(), @@ -227,16 +227,16 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } private PointerState1 pState1 = new PointerState1(); - + /** pointer names -> pointer ID (consecutive index, starting w/ 0) */ private final ArrayHashSet pName2pID = new ArrayHashSet(); - + private boolean defaultGestureHandlerEnabled = true; private DoubleTapScrollGesture gesture2PtrTouchScroll = null; private ArrayList pointerGestureHandler = new ArrayList(); - + private ArrayList gestureListeners = new ArrayList(); - + private ArrayList keyListeners = new ArrayList(); private ArrayList windowListeners = new ArrayList(); @@ -267,7 +267,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer { final Class windowClass = NewtFactory.getCustomClass(type, "WindowDriver"); if(null==windowClass) { - throw new ClassNotFoundException("Failed to find NEWT Window Class <"+type+".WindowDriver>"); + throw new ClassNotFoundException("Failed to find NEWT Window Class <"+type+".WindowDriver>"); } return windowClass; } @@ -293,7 +293,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer throw new NativeWindowException(t); } } - + public static WindowImpl create(Object[] cstrArguments, Screen screen, CapabilitiesImmutable caps) { try { Class windowClass = getWindowClass(screen.getDisplay().getType()); @@ -329,11 +329,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer hasFocus = false; parentWindowHandle = 0; } - + protected final void setGraphicsConfiguration(AbstractGraphicsConfiguration cfg) { config = cfg; } - + public static interface LifecycleHook { /** * Reset of internal state counter, ie totalFrames, etc. @@ -341,8 +341,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer */ public abstract void resetCounter(); - /** - * Invoked after Window setVisible, + /** + * Invoked after Window setVisible, * allows allocating resources depending on the native Window. * Called from EDT while window is locked. */ @@ -354,9 +354,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer * @param value true to set the one-shot preservation if supported, otherwise clears it. */ void preserveGLStateAtDestroy(boolean value); - - /** - * Invoked before Window destroy action, + + /** + * Invoked before Window destroy action, * allows releasing of resources depending on the native Window.
                            * Surface not locked yet.
                            * Called not necessarily from EDT. @@ -388,12 +388,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer * @see #pauseRenderingAction() */ void resumeRenderingAction(); - + /** * Shutdown rendering action (thread) abnormally. *

                            * Should be called only at shutdown, if necessary. - *

                            + *

                            */ void shutdownRenderingAction(); } @@ -406,14 +406,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } else { tStart = 0; } - - if( null != parentWindow && + + if( null != parentWindow && NativeSurface.LOCK_SURFACE_NOT_READY >= parentWindow.lockSurface() ) { throw new NativeWindowException("Parent surface lock: not ready: "+parentWindow); } - + // child window: position defaults to 0/0, no auto position, no negative position - if( null != parentWindow && ( autoPosition || 0>getX() || 0>getY() ) ) { + if( null != parentWindow && ( autoPosition || 0>getX() || 0>getY() ) ) { definePosition(0, 0); } boolean postParentlockFocus = false; @@ -556,28 +556,28 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer /** * Notifies the driver impl. that the instantiation is finished, - * ie. instance created and all fields set. + * ie. instance created and all fields set. */ protected void instantiationFinished() { // nop } - + protected boolean canCreateNativeImpl() { return true; // default: always able to be created } - - /** + + /** * The native implementation must set the native windowHandle.
                            * *

                            * The implementation shall respect the states {@link #isAlwaysOnTop()}/{@link #FLAG_IS_ALWAYSONTOP} and * {@link #isUndecorated()}/{@link #FLAG_IS_UNDECORATED}, ie. the created window shall reflect those settings. *

                            - * + * *

                            * The implementation should invoke the referenced java state callbacks * to notify this Java object of state changes.

                            - * + * * @see #windowDestroyNotify(boolean) * @see #focusChanged(boolean, boolean) * @see #visibleChanged(boolean, boolean) @@ -589,16 +589,16 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer protected abstract void closeNativeImpl(); - /** + /** * Async request which shall be performed within {@link #TIMEOUT_NATIVEWINDOW}. *

                            - * If if force == false the native implementation + * If if force == false the native implementation * may only request focus if not yet owner.

                            *

                            * {@link #focusChanged(boolean, boolean)} should be called - * to notify about the focus traversal. - *

                            - * + * to notify about the focus traversal. + *

                            + * * @param force if true, bypass {@link #focusChanged(boolean, boolean)} and force focus request */ protected abstract void requestFocusImpl(boolean force); @@ -608,7 +608,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public static final int FLAG_CHANGE_FULLSCREEN = 1 << 2; public static final int FLAG_CHANGE_ALWAYSONTOP = 1 << 3; public static final int FLAG_CHANGE_VISIBILITY = 1 << 4; - + public static final int FLAG_HAS_PARENT = 1 << 8; public static final int FLAG_IS_UNDECORATED = 1 << 9; public static final int FLAG_IS_FULLSCREEN = 1 << 10; @@ -619,12 +619,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer /** * The native implementation should invoke the referenced java state callbacks * to notify this Java object of state changes. - * + * *

                            * Implementations shall set x/y to 0, in case it's negative. This could happen due * to insets and positioning a decorated window to 0/0, which would place the frame * outside of the screen.

                            - * + * * @param x client-area position, or <0 if unchanged * @param y client-area position, or <0 if unchanged * @param width client-area size, or <=0 if unchanged @@ -635,12 +635,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer * @see #positionChanged(boolean,int, int) */ protected abstract boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags); - - /** + + /** * Tests whether a single reconfigure flag is supported by implementation. *

                            * Default is all but {@link #FLAG_IS_FULLSCREEN_SPAN} - *

                            + *

                            */ protected boolean isReconfigureFlagSupported(int changeFlags) { return 0 == ( changeFlags & FLAG_IS_FULLSCREEN_SPAN ); @@ -656,14 +656,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer protected static String getReconfigureFlagsAsString(StringBuilder sb, int flags) { if(null == sb) { sb = new StringBuilder(); } sb.append("["); - + if( 0 != ( FLAG_CHANGE_PARENTING & flags) ) { sb.append("*"); } sb.append("PARENT_"); sb.append(0 != ( FLAG_HAS_PARENT & flags)); sb.append(", "); - + if( 0 != ( FLAG_CHANGE_FULLSCREEN & flags) ) { sb.append("*"); } @@ -679,24 +679,24 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer sb.append("UNDECOR_"); sb.append(0 != ( FLAG_IS_UNDECORATED & flags)); sb.append(", "); - + if( 0 != ( FLAG_CHANGE_ALWAYSONTOP & flags) ) { sb.append("*"); } sb.append("ALWAYSONTOP_"); sb.append(0 != ( FLAG_IS_ALWAYSONTOP & flags)); sb.append(", "); - + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { sb.append("*"); } sb.append("VISIBLE_"); sb.append(0 != ( FLAG_IS_VISIBLE & flags)); - + sb.append("]"); return sb.toString(); } - + protected void setTitleImpl(String title) {} /** @@ -713,11 +713,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer * @return if not null, the screen location of the given coordinates */ protected abstract Point getLocationOnScreenImpl(int x, int y); - + /** Triggered by user via {@link #getInsets()}.
                            - * Implementations may implement this hook to update the insets.
                            + * Implementations may implement this hook to update the insets.
                            * However, they may prefer the event driven path via {@link #insetsChanged(boolean, int, int, int, int)}. - * + * * @see #getInsets() * @see #insetsChanged(boolean, int, int, int, int) */ @@ -726,7 +726,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer protected boolean setPointerVisibleImpl(boolean pointerVisible) { return false; } protected boolean confinePointerImpl(boolean confine) { return false; } protected void warpPointerImpl(int x, int y) { } - + //---------------------------------------------------------------------- // NativeSurface // @@ -791,7 +791,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public final RecursiveLock getLock() { return windowLock; } - + @Override public long getSurfaceHandle() { return windowHandle; // default: return window handle @@ -810,7 +810,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer @Override public final long getDisplayHandle() { return config.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle(); - } + } @Override public final int getScreenIndex() { @@ -879,19 +879,19 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public final Screen getScreen() { return screen; } - + @Override public final MonitorDevice getMainMonitor() { return screen.getMainMonitor(new Rectangle(getX(), getY(), getWidth(), getHeight())); } - + protected final void setVisibleImpl(boolean visible, int x, int y, int width, int height) { - reconfigureWindowImpl(x, y, width, height, getReconfigureFlags(FLAG_CHANGE_VISIBILITY, visible)); - } + reconfigureWindowImpl(x, y, width, height, getReconfigureFlags(FLAG_CHANGE_VISIBILITY, visible)); + } final void setVisibleActionImpl(boolean visible) { boolean nativeWindowCreated = false; boolean madeVisible = false; - + final RecursiveLock _lock = windowLock; _lock.lock(); try { @@ -911,7 +911,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer madeVisible = nativeWindowCreated; } // always flag visible, allowing a retry .. - WindowImpl.this.visible = true; + WindowImpl.this.visible = true; } else if(WindowImpl.this.visible != visible) { if(isNativeValid()) { setVisibleImpl(visible, getX(), getY(), getWidth(), getHeight()); @@ -965,14 +965,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if(DEBUG_IMPLEMENTATION) { System.err.println("Window setVisible: START ("+getThreadName()+") "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle)+", visible: "+this.visible+" -> "+visible+", parentWindowHandle "+toHexString(parentWindowHandle)+", parentWindow "+(null!=parentWindow)); } - runOnEDTIfAvail(wait, new VisibleAction(visible)); + runOnEDTIfAvail(wait, new VisibleAction(visible)); } @Override public void setVisible(boolean visible) { setVisible(true, visible); } - + private class SetSizeAction implements Runnable { int width, height; boolean disregardFS; @@ -1024,11 +1024,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer private void setFullscreenSize(int width, int height) { runOnEDTIfAvail(true, new SetSizeAction(width, height, true)); - } + } @Override public void setSize(int width, int height) { runOnEDTIfAvail(true, new SetSizeAction(width, height, false)); - } + } @Override public void setTopLevelSize(int width, int height) { setSize(width - getInsets().getTotalWidth(), height - getInsets().getTotalHeight()); @@ -1049,10 +1049,10 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if(DEBUG_IMPLEMENTATION) { System.err.println("Window DestroyAction() hasScreen "+(null != screen)+", isNativeValid "+isNativeValid()+" - "+getThreadName()); } - + // send synced destroy-notify notification sendWindowEvent(WindowEvent.EVENT_WINDOW_DESTROY_NOTIFY); - + // Childs first .. synchronized(childWindowsLock) { if(childWindows.size()>0) { @@ -1111,30 +1111,30 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if(animatorPaused) { lifecycleHook.resumeRenderingAction(); } - + // these refs shall be kept alive - resurrection via setVisible(true) /** if(null!=parentWindow && parentWindow instanceof Window) { ((Window)parentWindow).removeChild(WindowImpl.this); - } + } childWindows = null; surfaceUpdatedListeners = null; mouseListeners = null; keyListeners = null; capsRequested = null; lifecycleHook = null; - - screen = null; + + screen = null; windowListeners = null; parentWindow = null; - */ + */ } } private final DestroyAction destroyAction = new DestroyAction(); @Override public void destroy() { - visible = false; // Immediately mark synchronized visibility flag, avoiding possible recreation + visible = false; // Immediately mark synchronized visibility flag, avoiding possible recreation runOnEDTIfAvail(true, destroyAction); } @@ -1144,15 +1144,15 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } destroy(); } - + /** * @param cWin child window, must not be null * @param pWin parent window, may be null - * @return true if at least one of both window's configurations is offscreen + * @return true if at least one of both window's configurations is offscreen */ protected static boolean isOffscreenInstance(NativeWindow cWin, NativeWindow pWin) { boolean ofs = false; - final AbstractGraphicsConfiguration cWinCfg = cWin.getGraphicsConfiguration(); + final AbstractGraphicsConfiguration cWinCfg = cWin.getGraphicsConfiguration(); if( null != cWinCfg ) { ofs = !cWinCfg.getChosenCapabilities().isOnscreen(); } @@ -1164,7 +1164,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } return ofs; } - + private class ReparentAction implements Runnable { final NativeWindow newParentWindow; final int topLevelX, topLevelY; @@ -1187,7 +1187,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer removeScreenReference(); screen = newScreen; } - + public final void run() { boolean animatorPaused = false; if(null!=lifecycleHook) { @@ -1198,7 +1198,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer lifecycleHook.resumeRenderingAction(); } } - + private void reparent() { // mirror pos/size so native change notification can get overwritten final int oldX = getX(); @@ -1209,7 +1209,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer int width = oldWidth; int height = oldHeight; boolean wasVisible; - + final RecursiveLock _lock = windowLock; _lock.lock(); try { @@ -1217,7 +1217,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // force recreation if offscreen, since it may become onscreen forceDestroyCreate |= isOffscreenInstance(WindowImpl.this, newParentWindow); } - + wasVisible = isVisible(); Window newParentWindowNEWT = null; @@ -1233,7 +1233,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if(null!=newParentWindow) { // REPARENT TO CHILD WINDOW - + // reset position to 0/0 within parent space x = 0; y = 0; @@ -1278,7 +1278,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer operation = ReparentOperation.ACTION_NATIVE_CREATION_PENDING; } } else if ( forceDestroyCreate || !NewtFactory.isScreenCompatible(newParentWindow, screen) ) { - // Destroy this window, may create a new compatible Screen/Display, while trying to preserve resources if becoming visible again. + // Destroy this window, may create a new compatible Screen/Display, while trying to preserve resources if becoming visible again. destroy( wasVisible ); if(null!=newParentWindowNEWT) { setScreen( (ScreenImpl) newParentWindowNEWT.getScreen() ); @@ -1333,11 +1333,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if ( ReparentOperation.ACTION_INVALID == operation ) { throw new NativeWindowException("Internal Error: reparentAction not set"); } - + if(DEBUG_IMPLEMENTATION) { System.err.println("Window.reparent: ACTION ("+getThreadName()+") windowHandle "+toHexString(windowHandle)+" new parentWindowHandle "+toHexString(newParentWindowHandle)+", reparentAction "+operation+", pos/size "+x+"/"+y+" "+width+"x"+height+", visible "+wasVisible); } - + if( ReparentOperation.ACTION_NOP == operation ) { return; } @@ -1401,18 +1401,18 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } if(ok) { requestFocusInt( 0 == parentWindowHandle /* skipFocusAction if top-level */); - display.dispatchMessagesNative(); // status up2date + display.dispatchMessagesNative(); // status up2date } } } if(!ok || !wasVisible) { - // make size and position persistent manual, + // make size and position persistent manual, // since we don't have a WM feedback (invisible or recreation) definePosition(x, y); defineSize(width, height); } - + if(!ok) { // native reparent failed -> try creation, while trying to preserve resources if becoming visible again. if(DEBUG_IMPLEMENTATION) { @@ -1430,7 +1430,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer definePosition(x, y); defineSize(width, height); } - + if(DEBUG_IMPLEMENTATION) { System.err.println("Window.reparent: END-1 ("+getThreadName()+") windowHandle "+toHexString(windowHandle)+", visible: "+visible+", parentWindowHandle "+toHexString(parentWindowHandle)+", parentWindow "+ Display.hashCodeNullSafe(parentWindow)+" "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()); } @@ -1451,7 +1451,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // This may run on the new Display/Screen connection, hence a new EDT task runOnEDTIfAvail(true, reparentActionRecreate); break; - + default: } } @@ -1566,7 +1566,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if(WindowImpl.this.alwaysOnTop != alwaysOnTop) { // set current state WindowImpl.this.alwaysOnTop = alwaysOnTop; - + if( isNativeValid() ) { // Mirror pos/size so native change notification can get overwritten final int x = getX(); @@ -1591,12 +1591,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public final void setAlwaysOnTop(boolean value) { runOnEDTIfAvail(true, new AlwaysOnTopAction(value)); } - + @Override public final boolean isAlwaysOnTop() { return alwaysOnTop; } - + @Override public String getTitle() { return title; @@ -1624,7 +1624,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer setVal = setPointerVisibleImpl(pointerVisible); } if(setVal) { - this.pointerVisible = pointerVisible; + this.pointerVisible = pointerVisible; } } } @@ -1632,7 +1632,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public boolean isPointerConfined() { return pointerConfined; } - + @Override public void confinePointer(boolean confine) { if(this.pointerConfined != confine) { @@ -1652,18 +1652,18 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } if(setVal) { - this.pointerConfined = confine; + this.pointerConfined = confine; } - } + } } - + @Override public void warpPointer(int x, int y) { if(0 != getWindowHandle()) { warpPointerImpl(x, y); } } - + @Override public final InsetsImmutable getInsets() { if(isUndecorated()) { @@ -1672,7 +1672,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer updateInsetsImpl(insets); return insets; } - + @Override public final int getWidth() { return width; @@ -1694,8 +1694,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } protected final boolean autoPosition() { return autoPosition; } - - /** Sets the position fields {@link #x} and {@link #y} to the given values and {@link #autoPosition} to false. */ + + /** Sets the position fields {@link #x} and {@link #y} to the given values and {@link #autoPosition} to false. */ protected final void definePosition(int x, int y) { if(DEBUG_IMPLEMENTATION) { System.err.println("definePosition: "+this.x+"/"+this.y+" -> "+x+"/"+y); @@ -1705,7 +1705,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer this.x = x; this.y = y; } - /** Sets the size fields {@link #width} and {@link #height} to the given values. */ + /** Sets the size fields {@link #width} and {@link #height} to the given values. */ protected final void defineSize(int width, int height) { if(DEBUG_IMPLEMENTATION) { System.err.println("defineSize: "+this.width+"x"+this.height+" -> "+width+"x"+height); @@ -1713,7 +1713,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } this.width = width; this.height = height; } - + @Override public final boolean isVisible() { return visible; @@ -1732,7 +1732,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public final Window getDelegatedWindow() { return this; } - + //---------------------------------------------------------------------- // WindowImpl // @@ -1755,8 +1755,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer return old; } - /** - * If this Window actually wraps a {@link NativeSurface} from another instance or toolkit, + /** + * If this Window actually wraps a {@link NativeSurface} from another instance or toolkit, * it will return such reference. Otherwise returns null. */ public NativeSurface getWrappedSurface() { @@ -1768,13 +1768,13 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer windowDestroyNotifyAction = r; } - /** - * Returns the non delegated {@link AbstractGraphicsConfiguration}, + /** + * Returns the non delegated {@link AbstractGraphicsConfiguration}, * see {@link #getGraphicsConfiguration()}. */ public final AbstractGraphicsConfiguration getPrivateGraphicsConfiguration() { return config; } - + protected final long getParentWindowHandle() { return isFullscreen() ? 0 : parentWindowHandle; } @@ -1864,7 +1864,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public void requestFocus(boolean wait) { requestFocus(wait /* wait */, false /* skipFocusAction */, brokenFocusChange /* force */); } - + private void requestFocus(boolean wait, boolean skipFocusAction, boolean force) { if( isNativeValid() && ( force || !hasFocus() ) && @@ -1872,7 +1872,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer runOnEDTIfAvail(wait, force ? requestFocusActionForced : requestFocusAction); } } - + /** Internally forcing request focus on current thread */ private void requestFocusInt(boolean skipFocusAction) { if( skipFocusAction || !focusAction() ) { @@ -1880,14 +1880,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer System.err.println("Window.RequestFocusInt: forcing - ("+getThreadName()+"): skipFocusAction "+skipFocusAction+", focus "+hasFocus+" -> true - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle)); } requestFocusImpl(true); - } + } } - + @Override public void setFocusAction(FocusRunnable focusAction) { this.focusAction = focusAction; } - + private boolean focusAction() { if(DEBUG_IMPLEMENTATION) { System.err.println("Window.focusAction() START - "+getThreadName()+", focusAction: "+focusAction+" - windowHandle "+toHexString(getWindowHandle())); @@ -1903,16 +1903,16 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } return res; } - + protected void setBrokenFocusChange(boolean v) { brokenFocusChange = v; } - + @Override public void setKeyboardFocusHandler(KeyListener l) { keyboardFocusHandler = l; } - + private class SetPositionAction implements Runnable { int x, y; @@ -1932,7 +1932,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if(isNativeValid()) { // this.x/this.y will be set by sizeChanged, triggered by windowing event system reconfigureWindowImpl(x, y, getWidth(), getHeight(), getReconfigureFlags(0, isVisible())); - + // Wait until custom position is reached within tolerances waitForPosition(true, x, y, Window.TIMEOUT_NATIVEWINDOW); } else { @@ -1950,16 +1950,16 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer autoPosition = false; runOnEDTIfAvail(true, new SetPositionAction(x, y)); } - + @Override public void setTopLevelPosition(int x, int y) { setPosition(x + getInsets().getLeftWidth(), y + getInsets().getTopHeight()); } - + private class FullScreenAction implements Runnable { boolean fullscreen; - private boolean init(boolean fullscreen) { + private boolean init(boolean fullscreen) { if(isNativeValid()) { this.fullscreen = fullscreen; return isFullscreen() != fullscreen; @@ -1967,7 +1967,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer WindowImpl.this.fullscreen = fullscreen; // set current state for createNative(..) return false; } - } + } public boolean fsOn() { return fullscreen; } public final void run() { @@ -1981,9 +1981,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer final int oldY = getY(); final int oldWidth = getWidth(); final int oldHeight = getHeight(); - + int x,y,w,h; - + final RectangleImmutable sviewport = screen.getViewport(); final RectangleImmutable viewport; final int fs_span_flag; @@ -2007,7 +2007,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer nfs_y = oldY; nfs_width = oldWidth; nfs_height = oldHeight; - x = viewport.getX(); + x = viewport.getX(); y = viewport.getY(); w = viewport.getWidth(); h = viewport.getHeight(); @@ -2020,12 +2020,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer y = nfs_y; w = nfs_width; h = nfs_height; - + if(null!=parentWindow) { // reset position to 0/0 within parent space x = 0; y = 0; - + // refit if size is bigger than parent if( w > parentWindow.getWidth() ) { w = parentWindow.getWidth(); @@ -2044,7 +2044,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer final DisplayImpl display = (DisplayImpl) screen.getDisplay(); display.dispatchMessagesNative(); // status up2date final boolean wasVisible = isVisible(); - + // Lock parentWindow only during reparenting (attempt) final NativeWindow parentWindowLocked; if( null != parentWindow ) { @@ -2065,8 +2065,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer parentWindowLocked = null; } try { - reconfigureWindowImpl(x, y, w, h, - getReconfigureFlags( ( ( null != parentWindowLocked ) ? FLAG_CHANGE_PARENTING : 0 ) | + reconfigureWindowImpl(x, y, w, h, + getReconfigureFlags( ( ( null != parentWindowLocked ) ? FLAG_CHANGE_PARENTING : 0 ) | fs_span_flag | FLAG_CHANGE_FULLSCREEN | FLAG_CHANGE_DECORATION, isVisible()) ); } finally { if(null!=parentWindowLocked) { @@ -2074,7 +2074,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } display.dispatchMessagesNative(); // status up2date - + if(wasVisible) { setVisibleImpl(true, x, y, w, h); boolean ok = 0 <= WindowImpl.this.waitForVisible(true, false); @@ -2086,7 +2086,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } if(ok) { requestFocusInt(fullscreen /* skipFocusAction if fullscreen */); - display.dispatchMessagesNative(); // status up2date + display.dispatchMessagesNative(); // status up2date } if(DEBUG_IMPLEMENTATION) { System.err.println("Window fs done: ok " + ok + ", " + WindowImpl.this); @@ -2098,24 +2098,24 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer sendWindowEvent(WindowEvent.EVENT_WINDOW_RESIZED); // trigger a resize/relayout and repaint to listener } } - private final FullScreenAction fullScreenAction = new FullScreenAction(); + private final FullScreenAction fullScreenAction = new FullScreenAction(); @Override public boolean setFullscreen(boolean fullscreen) { return setFullscreenImpl(fullscreen, true, null); } - + @Override public boolean setFullscreen(List monitors) { return setFullscreenImpl(true, false, monitors); } - + private boolean setFullscreenImpl(boolean fullscreen, boolean useMainMonitor, List monitors) { synchronized(fullScreenAction) { fullscreenMonitors = monitors; fullscreenUseMainMonitor = useMainMonitor; if( fullScreenAction.init(fullscreen) ) { - if(fullScreenAction.fsOn() && isOffscreenInstance(WindowImpl.this, parentWindow)) { + if(fullScreenAction.fsOn() && isOffscreenInstance(WindowImpl.this, parentWindow)) { // enable fullscreen on offscreen instance if(null != parentWindow) { nfs_parent = parentWindow; @@ -2124,19 +2124,19 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer throw new InternalError("Offscreen instance w/o parent unhandled"); } } - + runOnEDTIfAvail(true, fullScreenAction); - + if(!fullScreenAction.fsOn() && null != nfs_parent) { // disable fullscreen on offscreen instance reparentWindow(nfs_parent, -1, -1, true /* forceDestroyCreate */); nfs_parent = null; } } - return this.fullscreen; + return this.fullscreen; } } - + private class MonitorModeListenerImpl implements MonitorModeListener { boolean animatorPaused = false; boolean hadFocus = false; @@ -2226,7 +2226,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer //---------------------------------------------------------------------- // Child Window Management - // + // @Override public final boolean removeChild(NativeWindow win) { @@ -2282,7 +2282,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if(DEBUG_IMPLEMENTATION) { System.err.println("Window.consumeEvent: REPAINT "+Thread.currentThread().getName()+" - queued "+e+", discard-to "+discardTO); // Thread.dumpStack(); - } + } return discardTO; // discardTO:=true -> consumed } return true; @@ -2343,11 +2343,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // // MouseListener/Event Support // - + // // Native MouseEvents pre-processed to be enqueued or consumed directly // - + public final void sendMouseEvent(short eventType, int modifiers, int x, int y, short button, float rotation) { doMouseEvent(false, false, eventType, modifiers, x, y, button, MouseEvent.getRotationXYZ(rotation, modifiers), 1f); @@ -2369,11 +2369,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer int x, int y, short button, float[] rotationXYZ, float rotationScale) { doMouseEvent(true, wait, eventType, modifiers, x, y, button, rotationXYZ, rotationScale); } */ - + /** * Send mouse event (one-pointer) either to be directly consumed or to be enqueued - * - * @param enqueue if true, event will be {@link #enqueueEvent(boolean, NEWTEvent) enqueued}, + * + * @param enqueue if true, event will be {@link #enqueueEvent(boolean, NEWTEvent) enqueued}, * otherwise {@link #consumeEvent(NEWTEvent) consumed} directly. * @param wait if true wait until {@link #consumeEvent(NEWTEvent) consumed}. */ @@ -2383,7 +2383,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer throw new NativeWindowException("Invalid mouse button number" + button); } doPointerEvent(enqueue, wait, constMousePointerTypes, eventType, modifiers, - 0 /*actionIdx*/, new short[] { (short)(button-1) }, + 0 /*actionIdx*/, new short[] { (short)(button-1) }, new int[]{x}, new int[]{y}, new float[]{0f} /*pressure*/, 1f /*maxPressure*/, rotationXYZ, rotationScale); } @@ -2396,11 +2396,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer *

                            *

                            * The given pointer names, pNames, are mapped to consecutive pointer IDs starting w/ 0 - * using a hash-map if normalPNames is false. - * Otherwise a simple int to short type cast is performed. + * using a hash-map if normalPNames is false. + * Otherwise a simple int to short type cast is performed. *

                            - * - * @param enqueue if true, event will be {@link #enqueueEvent(boolean, NEWTEvent) enqueued}, + * + * @param enqueue if true, event will be {@link #enqueueEvent(boolean, NEWTEvent) enqueued}, * otherwise {@link #consumeEvent(NEWTEvent) consumed} directly. * @param wait if true wait until {@link #consumeEvent(NEWTEvent) consumed}. * @param pTypes {@link MouseEvent.PointerType} for each pointer (multiple pointer) @@ -2410,14 +2410,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer * @param normalPNames see pName below. * @param pNames Pointer name for each pointer (multiple pointer). * We assume consecutive pointer names starting w/ 0 if normalPIDs is true. - * Otherwise we hash-map the values during state pressed to retrieve the normal ID. + * Otherwise we hash-map the values during state pressed to retrieve the normal ID. * @param pX X-axis for each pointer (multiple pointer) * @param pY Y-axis for each pointer (multiple pointer) * @param pPressure Pressure for each pointer (multiple pointer) * @param maxPressure Maximum pointer pressure for all pointer */ public final void doPointerEvent(boolean enqueue, boolean wait, - final PointerType[] pTypes, short eventType, int modifiers, + final PointerType[] pTypes, short eventType, int modifiers, int actionIdx, boolean normalPNames, final int[] pNames, final int[] pX, final int[] pY, float[] pPressure, float maxPressure, final float[] rotationXYZ, final float rotationScale) { @@ -2447,25 +2447,25 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer pIDs[i] = (short)pNames[i]; } } - doPointerEvent(enqueue, wait, pTypes, eventType, modifiers, actionIdx, pIDs, + doPointerEvent(enqueue, wait, pTypes, eventType, modifiers, actionIdx, pIDs, pX, pY, pPressure, maxPressure, rotationXYZ, rotationScale); } - + /** * Send multiple-pointer event either to be directly consumed or to be enqueued *

                            * The index for the element of multiple-pointer arrays represents the pointer which triggered the event * is passed via actionIdx. - *

                            - * - * @param enqueue if true, event will be {@link #enqueueEvent(boolean, NEWTEvent) enqueued}, + *

                            + * + * @param enqueue if true, event will be {@link #enqueueEvent(boolean, NEWTEvent) enqueued}, * otherwise {@link #consumeEvent(NEWTEvent) consumed} directly. * @param wait if true wait until {@link #consumeEvent(NEWTEvent) consumed}. * @param pTypes {@link MouseEvent.PointerType} for each pointer (multiple pointer) * @param eventType * @param modifiers * @param pActionIdx index of multiple-pointer arrays representing the pointer which triggered the event - * @param pID Pointer ID for each pointer (multiple pointer). We assume consecutive pointerIDs starting w/ 0. + * @param pID Pointer ID for each pointer (multiple pointer). We assume consecutive pointerIDs starting w/ 0. * A pointer-ID of -1 may also denote no pointer/button activity, i.e. {@link PointerType#Mouse} move. * @param pX X-axis for each pointer (multiple pointer) * @param pY Y-axis for each pointer (multiple pointer) @@ -2473,14 +2473,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer * @param maxPressure Maximum pointer pressure for all pointer */ public final void doPointerEvent(boolean enqueue, boolean wait, - final PointerType[] pTypes, short eventType, int modifiers, + final PointerType[] pTypes, short eventType, int modifiers, int pActionIdx, final short[] pID, final int[] pX, final int[] pY, final float[] pPressure, float maxPressure, final float[] rotationXYZ, float rotationScale) { final long when = System.currentTimeMillis(); final int pCount = pTypes.length; - + if( 0 > pActionIdx || pActionIdx >= pCount) { - throw new IllegalArgumentException("actionIdx out of bounds [0.."+(pCount-1)+"]"); + throw new IllegalArgumentException("actionIdx out of bounds [0.."+(pCount-1)+"]"); } if( 0 < pActionIdx ) { // swap values to make idx 0 the triggering pointer @@ -2518,11 +2518,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer button = com.jogamp.newt.event.MouseEvent.BUTTON1; } } - + // // - Determine ENTERED/EXITED state // - Remove redundant move/drag events - // - Reset states if applicable + // - Reset states if applicable // int x = pX[0]; int y = pY[0]; @@ -2537,7 +2537,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer movePositionP0.set(0, 0); } // Fall through intended! - + case MouseEvent.EVENT_MOUSE_ENTERED: // clip coordinates to window dimension x = Math.min(Math.max(x, 0), getWidth()-1); @@ -2545,11 +2545,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer pState1.insideWindow = eventType == MouseEvent.EVENT_MOUSE_ENTERED; pState1.clearButton(); break; - + case MouseEvent.EVENT_MOUSE_MOVED: case MouseEvent.EVENT_MOUSE_DRAGGED: if( null != movePositionP0 ) { - if( pState1.insideWindow && movePositionP0.getX() == x && movePositionP0.getY() == y ) { + if( pState1.insideWindow && movePositionP0.getX() == x && movePositionP0.getY() == y ) { if(DEBUG_MOUSE_EVENT) { System.err.println("doPointerEvent: skip "+MouseEvent.getEventTypeString(eventType)+" w/ same position: "+movePositionP0); } @@ -2557,16 +2557,16 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } movePositionP0.set(x, y); } - + // Fall through intended ! - + default: if(!pState1.insideWindow) { - pState1.insideWindow = true; + pState1.insideWindow = true; pState1.clearButton(); } } - + if( x < 0 || y < 0 || x >= getWidth() || y >= getHeight() ) { if(DEBUG_MOUSE_EVENT) { System.err.println("doPointerEvent: drop: "+MouseEvent.getEventTypeString(eventType)+ @@ -2582,29 +2582,29 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer final int buttonMask = InputEvent.getButtonMask(button); modifiers |= buttonMask; // Always add current button to modifier mask (Bug 571) modifiers |= pState1.buttonPressedMask; // Always add currently pressed mouse buttons to modifier mask - + if( isPointerConfined() ) { modifiers |= InputEvent.CONFINED_MASK; } if( !isPointerVisible() ) { modifiers |= InputEvent.INVISIBLE_MASK; } - + pX[0] = x; pY[0] = y; - + // // - Determine CLICK COUNT // - Ignore sent CLICKED // - Track buttonPressed incl. buttonPressedMask // - Fix MOVED/DRAGGED event // - final MouseEvent e; + final MouseEvent e; switch( eventType ) { case MouseEvent.EVENT_MOUSE_CLICKED: e = null; break; - + case MouseEvent.EVENT_MOUSE_PRESSED: if( 0 >= pPressure[0] ) { pPressure[0] = maxPressure; @@ -2618,16 +2618,16 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } pState1.lastButtonPressTime = when; pState1.buttonPressed = button; - e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, + e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, pX, pY, pPressure, maxPressure, button, pState1.lastButtonClickCount, rotationXYZ, rotationScale); } else { - e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, + e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, pX, pY, pPressure, maxPressure, button, (short)1, rotationXYZ, rotationScale); } break; case MouseEvent.EVENT_MOUSE_RELEASED: if( 1 == pCount ) { - e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, + e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, pX, pY, pPressure, maxPressure, button, pState1.lastButtonClickCount, rotationXYZ, rotationScale); if( when - pState1.lastButtonPressTime >= MouseEvent.getClickTimeout() ) { pState1.lastButtonClickCount = (short)0; @@ -2635,7 +2635,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } pState1.buttonPressed = 0; } else { - e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, + e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, pX, pY, pPressure, maxPressure, button, (short)1, rotationXYZ, rotationScale); } pState1.buttonPressedMask &= ~buttonMask; @@ -2645,10 +2645,10 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer break; case MouseEvent.EVENT_MOUSE_MOVED: if ( 0 != pState1.buttonPressedMask ) { // any button or pointer move -> drag - e = new MouseEvent(MouseEvent.EVENT_MOUSE_DRAGGED, this, when, modifiers, pTypes, pID, + e = new MouseEvent(MouseEvent.EVENT_MOUSE_DRAGGED, this, when, modifiers, pTypes, pID, pX, pY, pPressure, maxPressure, pState1.buttonPressed, (short)1, rotationXYZ, rotationScale); } else { - e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, + e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, pX, pY, pPressure, maxPressure, button, (short)0, rotationXYZ, rotationScale); } break; @@ -2658,12 +2658,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } // Fall through intended! default: - e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, + e = new MouseEvent(eventType, this, when, modifiers, pTypes, pID, pX, pY, pPressure, maxPressure, button, (short)0, rotationXYZ, rotationScale); } doEvent(enqueue, wait, e); // actual mouse event } - + @Override public final void addMouseListener(MouseListener l) { addMouseListener(-1, l); @@ -2676,8 +2676,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } @SuppressWarnings("unchecked") ArrayList clonedListeners = (ArrayList) mouseListeners.clone(); - if(0>index) { - index = clonedListeners.size(); + if(0>index) { + index = clonedListeners.size(); } clonedListeners.add(index, l); mouseListeners = clonedListeners; @@ -2698,8 +2698,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public final MouseListener getMouseListener(int index) { @SuppressWarnings("unchecked") ArrayList clonedListeners = (ArrayList) mouseListeners.clone(); - if(0>index) { - index = clonedListeners.size()-1; + if(0>index) { + index = clonedListeners.size()-1; } return clonedListeners.get(index); } @@ -2717,7 +2717,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public final boolean areDefaultGesturesEnabled() { return defaultGestureHandlerEnabled; } - + @Override public final void addGestureHandler(GestureHandler gh) { addGestureHandler(-1, gh); @@ -2729,7 +2729,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } @SuppressWarnings("unchecked") ArrayList cloned = (ArrayList) pointerGestureHandler.clone(); - if(0>index) { + if(0>index) { index = cloned.size(); } cloned.add(index, gh); @@ -2756,7 +2756,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } @SuppressWarnings("unchecked") ArrayList cloned = (ArrayList) gestureListeners.clone(); - if(0>index) { + if(0>index) { index = cloned.size(); } cloned.add(index, gl); @@ -2772,11 +2772,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer cloned.remove(gl); gestureListeners= cloned; } - + private static int step(int lower, int edge, int value) { return value < edge ? lower : value; } - + /** * Consume the {@link MouseEvent}, i.e. *
                            @@ -2786,18 +2786,18 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                                  *   - dispatch event to listener
                                  * 
                            */ - protected void consumePointerEvent(MouseEvent pe) { + protected void consumePointerEvent(MouseEvent pe) { int x = pe.getX(); int y = pe.getY(); - + if(DEBUG_MOUSE_EVENT) { System.err.println("consumePointerEvent.in: "+pe); } - + // // - Determine ENTERED/EXITED state // - Synthesize ENTERED event - // - Reset states if applicable + // - Reset states if applicable // final long when = pe.getWhen(); int eventType = pe.getEventType(); @@ -2812,7 +2812,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer pState0.clearButton(); eEntered = null; break; - + default: if(!pState0.insideWindow) { pState0.insideWindow = true; @@ -2833,12 +2833,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } return; // .. invalid .. } - + // // Handle Default Gestures // if( defaultGestureHandlerEnabled && - pe.getPointerType(0).getPointerClass() == MouseEvent.PointerClass.Onscreen ) + pe.getPointerType(0).getPointerClass() == MouseEvent.PointerClass.Onscreen ) { if( null == gesture2PtrTouchScroll ) { final int scaledScrollSlop; @@ -2849,16 +2849,16 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer final float pixWPerMM = (float)monitor.getCurrentMode().getRotatedWidth() / (float)mm.getWidth(); final float pixHPerMM = (float)monitor.getCurrentMode().getRotatedHeight() / (float)mm.getHeight(); final float pixPerMM = Math.min(pixHPerMM, pixWPerMM); - scaledScrollSlop = Math.round(DoubleTapScrollGesture.SCROLL_SLOP_MM * pixPerMM); - scaledDoubleTapSlop = Math.round(DoubleTapScrollGesture.DOUBLE_TAP_SLOP_MM * pixPerMM); + scaledScrollSlop = Math.round(DoubleTapScrollGesture.SCROLL_SLOP_MM * pixPerMM); + scaledDoubleTapSlop = Math.round(DoubleTapScrollGesture.DOUBLE_TAP_SLOP_MM * pixPerMM); if(DEBUG_MOUSE_EVENT) { System.err.println("consumePointerEvent.gscroll: scrollSlop "+scaledScrollSlop+", doubleTapSlop "+scaledDoubleTapSlop+", pixPerMM "+pixPerMM+", "+monitor); } } else { scaledScrollSlop = DoubleTapScrollGesture.SCROLL_SLOP_PIXEL; - scaledDoubleTapSlop = DoubleTapScrollGesture.DOUBLE_TAP_SLOP_PIXEL; + scaledDoubleTapSlop = DoubleTapScrollGesture.DOUBLE_TAP_SLOP_PIXEL; } - gesture2PtrTouchScroll = new DoubleTapScrollGesture(step(DoubleTapScrollGesture.SCROLL_SLOP_PIXEL, DoubleTapScrollGesture.SCROLL_SLOP_PIXEL/2, scaledScrollSlop), + gesture2PtrTouchScroll = new DoubleTapScrollGesture(step(DoubleTapScrollGesture.SCROLL_SLOP_PIXEL, DoubleTapScrollGesture.SCROLL_SLOP_PIXEL/2, scaledScrollSlop), step(DoubleTapScrollGesture.DOUBLE_TAP_SLOP_PIXEL, DoubleTapScrollGesture.DOUBLE_TAP_SLOP_PIXEL/2, scaledDoubleTapSlop)); } if( gesture2PtrTouchScroll.process(pe) ) { @@ -2903,11 +2903,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } } - + // // - Synthesize mouse CLICKED // - Ignore sent CLICKED - // + // final MouseEvent eClicked; switch( eventType ) { case MouseEvent.EVENT_MOUSE_PRESSED: @@ -2921,7 +2921,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer eClicked = pe.createVariant(MouseEvent.EVENT_MOUSE_CLICKED); } else { eClicked = null; - pState0.lastButtonPressTime = 0; + pState0.lastButtonPressTime = 0; } break; case MouseEvent.EVENT_MOUSE_CLICKED: @@ -2935,7 +2935,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer default: eClicked = null; } - + if( null != pe ) { if(DEBUG_MOUSE_EVENT) { System.err.println("consumePointerEvent.send.1: "+pe); @@ -2949,7 +2949,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer dispatchMouseEvent(eClicked); } } - + private final void dispatchMouseEvent(MouseEvent e) { for(int i = 0; !e.isConsumed() && i < mouseListeners.size(); i++ ) { MouseListener l = mouseListeners.get(i); @@ -2989,15 +2989,15 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // private static final int keyTrackingRange = 255; private final IntBitfield keyPressedState = new IntBitfield( keyTrackingRange + 1 ); - + protected final boolean isKeyCodeTracked(final short keyCode) { return ( 0xFFFF & (int)keyCode ) <= keyTrackingRange; } - + /** * @param keyCode the keyCode to set pressed state * @param pressed true if pressed, otherwise false - * @return the previus pressed value + * @return the previus pressed value */ protected final boolean setKeyPressed(short keyCode, boolean pressed) { final int v = 0xFFFF & (int)keyCode; @@ -3008,7 +3008,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } /** * @param keyCode the keyCode to test pressed state - * @return true if pressed, otherwise false + * @return true if pressed, otherwise false */ protected final boolean isKeyPressed(short keyCode) { final int v = 0xFFFF & (int)keyCode; @@ -3017,7 +3017,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } return false; } - + public void sendKeyEvent(short eventType, int modifiers, short keyCode, short keySym, char keyChar) { // Always add currently pressed mouse buttons to modifier mask consumeKeyEvent( KeyEvent.create(eventType, this, System.currentTimeMillis(), modifiers | pState1.buttonPressedMask, keyCode, keySym, keyChar) ); @@ -3027,12 +3027,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // Always add currently pressed mouse buttons to modifier mask enqueueEvent(wait, KeyEvent.create(eventType, this, System.currentTimeMillis(), modifiers | pState1.buttonPressedMask, keyCode, keySym, keyChar) ); } - + @Override public final void setKeyboardVisible(boolean visible) { if(isNativeValid()) { // We don't skip the impl. if it seems that there is no state change, - // since we cannot assume the impl. reliably gives us it's current state. + // since we cannot assume the impl. reliably gives us it's current state. final boolean ok = setKeyboardVisibleImpl(visible); if(DEBUG_IMPLEMENTATION || DEBUG_KEY_EVENT) { System.err.println("setKeyboardVisible(native): visible "+keyboardVisible+" -- op[visible:"+visible +", ok "+ok+"] -> "+(visible && ok)); @@ -3046,13 +3046,13 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public final boolean isKeyboardVisible() { return keyboardVisible; } - /** + /** * Returns true if operation was successful, otherwise false. *

                            * We assume that a failed invisible operation is due to an already invisible keyboard, - * hence even if an invisible operation failed, the keyboard is considered invisible! - *

                            - */ + * hence even if an invisible operation failed, the keyboard is considered invisible! + *

                            + */ protected boolean setKeyboardVisibleImpl(boolean visible) { return false; // nop } @@ -3066,7 +3066,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } protected boolean keyboardVisible = false; - + @Override public void addKeyListener(KeyListener l) { addKeyListener(-1, l); @@ -3079,7 +3079,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } @SuppressWarnings("unchecked") ArrayList clonedListeners = (ArrayList) keyListeners.clone(); - if(0>index) { + if(0>index) { index = clonedListeners.size(); } clonedListeners.add(index, l); @@ -3101,7 +3101,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public KeyListener getKeyListener(int index) { @SuppressWarnings("unchecked") ArrayList clonedListeners = (ArrayList) keyListeners.clone(); - if(0>index) { + if(0>index) { index = clonedListeners.size()-1; } return clonedListeners.get(index); @@ -3125,7 +3125,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } return e.isConsumed(); } - + protected void consumeKeyEvent(KeyEvent e) { boolean consumedE = false; if( null != keyboardFocusHandler && !e.isAutoRepeat() ) { @@ -3164,7 +3164,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } @Override - public void addWindowListener(int index, WindowListener l) + public void addWindowListener(int index, WindowListener l) throws IndexOutOfBoundsException { if(l == null) { @@ -3172,8 +3172,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } @SuppressWarnings("unchecked") ArrayList clonedListeners = (ArrayList) windowListeners.clone(); - if(0>index) { - index = clonedListeners.size(); + if(0>index) { + index = clonedListeners.size(); } clonedListeners.add(index, l); windowListeners = clonedListeners; @@ -3194,8 +3194,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer public WindowListener getWindowListener(int index) { @SuppressWarnings("unchecked") ArrayList clonedListeners = (ArrayList) windowListeners.clone(); - if(0>index) { - index = clonedListeners.size()-1; + if(0>index) { + index = clonedListeners.size()-1; } return clonedListeners.get(index); } @@ -3234,7 +3234,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer l.windowRepaint((WindowUpdateEvent)e); break; default: - throw + throw new NativeWindowException("Unexpected window event type " + e.getEventType()); } @@ -3248,7 +3248,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer System.err.println("Window.focusChanged: ("+getThreadName()+"): (defer: "+defer+") "+this.hasFocus+" -> "+focusGained+" - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle)); } hasFocus = focusGained; - final int evt = focusGained ? WindowEvent.EVENT_WINDOW_GAINED_FOCUS : WindowEvent.EVENT_WINDOW_LOST_FOCUS ; + final int evt = focusGained ? WindowEvent.EVENT_WINDOW_GAINED_FOCUS : WindowEvent.EVENT_WINDOW_LOST_FOCUS ; if(!defer) { sendWindowEvent(evt); } else { @@ -3256,7 +3256,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } } - + /** Triggered by implementation's WM events to update the visibility state. */ protected void visibleChanged(boolean defer, boolean visible) { if(this.visible != visible) { @@ -3282,7 +3282,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer display.dispatchMessagesNative(); // status up2date } if(this.visible != visible) { - final String msg = "Visibility not reached as requested within "+timeOut+"ms : requested "+visible+", is "+this.visible; + final String msg = "Visibility not reached as requested within "+timeOut+"ms : requested "+visible+", is "+this.visible; if(failFast) { throw new NativeWindowException(msg); } else if (DEBUG_IMPLEMENTATION) { @@ -3297,7 +3297,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } - /** Triggered by implementation's WM events to update the client-area size w/o insets/decorations. */ + /** Triggered by implementation's WM events to update the client-area size w/o insets/decorations. */ protected void sizeChanged(boolean defer, int newWidth, int newHeight, boolean force) { if(force || getWidth() != newWidth || getHeight() != newHeight) { if(DEBUG_IMPLEMENTATION) { @@ -3316,7 +3316,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } } - + private boolean waitForSize(int w, int h, boolean failFast, long timeOut) { final DisplayImpl display = (DisplayImpl) screen.getDisplay(); display.dispatchMessagesNative(); // status up2date @@ -3338,8 +3338,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer return true; } } - - /** Triggered by implementation's WM events to update the position. */ + + /** Triggered by implementation's WM events to update the position. */ protected void positionChanged(boolean defer, int newX, int newY) { if ( getX() != newX || getY() != newY ) { if(DEBUG_IMPLEMENTATION) { @@ -3352,7 +3352,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer enqueueWindowEvent(false, WindowEvent.EVENT_WINDOW_MOVED); } } else { - autoPosition = false; // ensure it's off even w/ same position + autoPosition = false; // ensure it's off even w/ same position } } @@ -3396,10 +3396,10 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } return ok; } - + /** - * Triggered by implementation's WM events to update the insets. - * + * Triggered by implementation's WM events to update the insets. + * * @see #getInsets() * @see #updateInsetsImpl(Insets) */ @@ -3409,7 +3409,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if(DEBUG_IMPLEMENTATION) { System.err.println("Window.insetsChanged: skip insets change for undecoration mode"); } - } else if ( (left != insets.getLeftWidth() || right != insets.getRightWidth() || + } else if ( (left != insets.getLeftWidth() || right != insets.getRightWidth() || top != insets.getTopHeight() || bottom != insets.getBottomHeight() ) ) { insets.set(left, right, top, bottom); @@ -3419,10 +3419,10 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } } - + /** * Triggered by implementation's WM events or programmatic while respecting {@link #getDefaultCloseOperation()}. - * + * * @param force if true, overrides {@link #setDefaultCloseOperation(WindowClosingMode)} with {@link WindowClosingProtocol#DISPOSE_ON_CLOSE} * and hence force destruction. Otherwise is follows the user settings. * @return true if this window is no more valid and hence has been destroyed, otherwise false. @@ -3434,9 +3434,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer System.err.println("Window.windowDestroyNotify(isNativeValid: "+isNativeValid()+", force: "+force+", mode "+defMode+" -> "+mode+") "+getThreadName()+": "+this); // Thread.dumpStack(); } - + final boolean destroyed; - + if( isNativeValid() ) { if( WindowClosingMode.DISPOSE_ON_CLOSE == mode ) { if(force) { @@ -3457,7 +3457,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer // send synced destroy notifications sendWindowEvent(WindowEvent.EVENT_WINDOW_DESTROY_NOTIFY); } - + destroyed = !isNativeValid(); } else { destroyed = true; @@ -3465,19 +3465,19 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer if(DEBUG_IMPLEMENTATION) { System.err.println("Window.windowDestroyNotify(isNativeValid: "+isNativeValid()+", force: "+force+", mode "+mode+") END "+getThreadName()+": destroyed "+destroyed+", "+this); - } - + } + return destroyed; } @Override public void windowRepaint(int x, int y, int width, int height) { - windowRepaint(false, x, y, width, height); + windowRepaint(false, x, y, width, height); } - + /** * Triggered by implementation's WM events to update the content - */ + */ protected void windowRepaint(boolean defer, int x, int y, int width, int height) { width = ( 0 >= width ) ? getWidth() : width; height = ( 0 >= height ) ? getHeight() : height; @@ -3542,7 +3542,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer protected final void shouldNotCallThis() { throw new NativeWindowException("Should not call this"); } - + public static String getThreadName() { return Display.getThreadName(); } diff --git a/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java b/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java index 861a6d6be..2ba5b3460 100644 --- a/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java +++ b/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.newt.awt; import javax.media.nativewindow.AbstractGraphicsConfiguration; @@ -76,12 +76,12 @@ public class NewtFactoryAWT extends NewtFactory { } return (JAWTWindow)nw; } - + public static void destroyNativeWindow(JAWTWindow jawtWindow) { final AbstractGraphicsConfiguration config = jawtWindow.getGraphicsConfiguration(); jawtWindow.destroy(); - config.getScreen().getDevice().close(); + config.getScreen().getDevice().close(); } - + } diff --git a/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java b/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java index d71ad175b..0ee3cc0cd 100644 --- a/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java +++ b/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,26 +20,26 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.newt.awt.event; import com.jogamp.newt.event.MouseEvent; /** * - *
                            AWT Event Modifier Mapping
                            + *
                            AWT Event Modifier Mapping
                            *
                                 Modifier       AWT Constant                     AWT Bit  AWT Ex  NEWT Constant              NEWT Bit
                                 -------------  -------------------------------  -------  ------  -------------------------  --------
                            -    Shift          Event.SHIFT_MASK                 0                
                            -    Ctrl           Event.CTRL_MASK                  1                
                            -    Meta           Event.META_MASK                  2                
                            -    Alt            Event.ALT_MASK                   3               
                            +    Shift          Event.SHIFT_MASK                 0
                            +    Ctrl           Event.CTRL_MASK                  1
                            +    Meta           Event.META_MASK                  2
                            +    Alt            Event.ALT_MASK                   3
                                 Button1        InputEvent.BUTTON1_MASK          4
                                 Button2        InputEvent.BUTTON2_MASK          3
                                 Button3        InputEvent.BUTTON3_MASK          2
                            @@ -88,10 +88,10 @@ public class AWTNewtEventFactory {
                                         Method _getMaskForButtonMethod = null;
                                         try {
                                             _getMaskForButtonMethod = ReflectionUtil.getMethod(java.awt.event.InputEvent.class, "getMaskForButton", int.class);
                            -            } catch(Throwable t) {}        
                            +            } catch(Throwable t) {}
                                         getMaskForButtonMethod = _getMaskForButtonMethod;
                                     } */
                            -        
                            +
                                     awtButtonDownMasks = new int[com.jogamp.newt.event.MouseEvent.BUTTON_COUNT] ; // java.awt.MouseInfo.getNumberOfButtons() ;
                                     for (int n = 0 ; n < awtButtonDownMasks.length ; ++n) {
                                         awtButtonDownMasks[n] = getAWTButtonDownMaskImpl(n+1);
                            @@ -112,12 +112,12 @@ public class AWTNewtEventFactory {
                                         case java.awt.event.WindowEvent.WINDOW_LOST_FOCUS: return com.jogamp.newt.event.WindowEvent.EVENT_WINDOW_LOST_FOCUS;
                                         case java.awt.event.FocusEvent.FOCUS_LOST: return com.jogamp.newt.event.WindowEvent.EVENT_WINDOW_LOST_FOCUS;
                                         // n/a case java.awt.event.WindowEvent.WINDOW_STATE_CHANGED: return com.jogamp.newt.event.WindowEvent.EVENT_WINDOW_STATE_CHANGED;
                            -    
                            +
                                         case java.awt.event.ComponentEvent.COMPONENT_MOVED: return com.jogamp.newt.event.WindowEvent.EVENT_WINDOW_MOVED;
                                         case java.awt.event.ComponentEvent.COMPONENT_RESIZED: return com.jogamp.newt.event.WindowEvent.EVENT_WINDOW_RESIZED;
                                         // n/a case java.awt.event.ComponentEvent.COMPONENT_SHOWN: return com.jogamp.newt.event.WindowEvent.EVENT_WINDOW_SHOWN;
                                         // n/a case java.awt.event.ComponentEvent.COMPONENT_HIDDEN: return com.jogamp.newt.event.WindowEvent.EVENT_WINDOW_HIDDEN;
                            -    
                            +
                                         case java.awt.event.MouseEvent.MOUSE_CLICKED: return com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_CLICKED;
                                         case java.awt.event.MouseEvent.MOUSE_PRESSED: return com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_PRESSED;
                                         case java.awt.event.MouseEvent.MOUSE_RELEASED: return com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED;
                            @@ -126,17 +126,17 @@ public class AWTNewtEventFactory {
                                         case java.awt.event.MouseEvent.MOUSE_EXITED: return com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_EXITED;
                                         case java.awt.event.MouseEvent.MOUSE_DRAGGED: return com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_DRAGGED;
                                         case java.awt.event.MouseEvent.MOUSE_WHEEL: return com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_WHEEL_MOVED;
                            -    
                            +
                                         case java.awt.event.KeyEvent.KEY_PRESSED: return com.jogamp.newt.event.KeyEvent.EVENT_KEY_PRESSED;
                                         case java.awt.event.KeyEvent.KEY_RELEASED: return com.jogamp.newt.event.KeyEvent.EVENT_KEY_RELEASED;
                                     }
                                     return (short)0;
                                 }
                            -    
                            +
                                 private static int getAWTButtonDownMaskImpl(int button) {
                                     /**
                                      * java.awt.event.InputEvent.getMaskForButton(button);
                            -         * 
                            +         *
                                     if(null != getMaskForButtonMethod) {
                                         Object r=null;
                                         try {
                            @@ -157,16 +157,16 @@ public class AWTNewtEventFactory {
                                                 m = 1 << ( 10 + button ) ; // b4 = 1<<14, b5 = 1<<15, etc
                                             } else {
                                                 m = 0;
                            -                }                
                            +                }
                                     }
                                     return m;
                                 }
                            -    
                            +
                                 /**
                                  * 

                            * See AWT event modifier mapping details. *

                            - * + * * @param button * @return */ @@ -175,9 +175,9 @@ public class AWTNewtEventFactory { return awtButtonDownMasks[button-1]; } else { return 0; - } + } } - + public static final short awtButton2Newt(int awtButton) { if( 0 < awtButton && awtButton <= com.jogamp.newt.event.MouseEvent.BUTTON_COUNT ) { return (short)awtButton; @@ -185,32 +185,32 @@ public class AWTNewtEventFactory { return (short)0; } } - + /** * Converts the specified set of AWT event modifiers and extended event * modifiers to the equivalent NEWT event modifiers. - * + * *

                            * See AWT event modifier mapping details. *

                            - * + * * @param awtMods * The AWT event modifiers. - * + * * @param awtModsEx * The AWT extended event modifiers. * AWT passes mouse button specific bits here and are the preferred way check the mouse button state. */ public static final int awtModifiers2Newt(final int awtMods, final int awtModsEx) { int newtMods = 0; - + /** Redundant old modifiers .. if ((awtMods & java.awt.event.InputEvent.SHIFT_MASK) != 0) newtMods |= com.jogamp.newt.event.InputEvent.SHIFT_MASK; if ((awtMods & java.awt.event.InputEvent.CTRL_MASK) != 0) newtMods |= com.jogamp.newt.event.InputEvent.CTRL_MASK; if ((awtMods & java.awt.event.InputEvent.META_MASK) != 0) newtMods |= com.jogamp.newt.event.InputEvent.META_MASK; if ((awtMods & java.awt.event.InputEvent.ALT_MASK) != 0) newtMods |= com.jogamp.newt.event.InputEvent.ALT_MASK; if ((awtMods & java.awt.event.InputEvent.ALT_GRAPH_MASK) != 0) newtMods |= com.jogamp.newt.event.InputEvent.ALT_GRAPH_MASK; */ - + if ((awtModsEx & java.awt.event.InputEvent.SHIFT_DOWN_MASK) != 0) newtMods |= com.jogamp.newt.event.InputEvent.SHIFT_MASK; if ((awtModsEx & java.awt.event.InputEvent.CTRL_DOWN_MASK) != 0) newtMods |= com.jogamp.newt.event.InputEvent.CTRL_MASK; if ((awtModsEx & java.awt.event.InputEvent.META_DOWN_MASK) != 0) newtMods |= com.jogamp.newt.event.InputEvent.META_MASK; @@ -221,7 +221,7 @@ public class AWTNewtEventFactory { // being ignored intentionally. The AWT docs say that the // BUTTON1_DOWN_MASK etc bits in the extended modifiers are // the preferred place to check current button state. - + if( 0 != awtModsEx ) { for (int n = 0 ; n < awtButtonDownMasks.length ; ++n) { if ( (awtModsEx & awtButtonDownMasks[n]) != 0 ) { @@ -232,7 +232,7 @@ public class AWTNewtEventFactory { return newtMods; } - + public static short awtKeyCode2NewtKeyCode(final int awtKeyCode) { final short defNEWTKeyCode = (short)awtKeyCode; switch (awtKeyCode) { @@ -371,7 +371,7 @@ public class AWTNewtEventFactory { case java.awt.event.KeyEvent.VK_MULTIPLY : return com.jogamp.newt.event.KeyEvent.VK_MULTIPLY; case java.awt.event.KeyEvent.VK_DIVIDE : return com.jogamp.newt.event.KeyEvent.VK_DIVIDE; case java.awt.event.KeyEvent.VK_NUM_LOCK : return com.jogamp.newt.event.KeyEvent.VK_NUM_LOCK; - case java.awt.event.KeyEvent.VK_KP_LEFT : /** Fall through intended .. */ + case java.awt.event.KeyEvent.VK_KP_LEFT : /** Fall through intended .. */ case java.awt.event.KeyEvent.VK_LEFT : return com.jogamp.newt.event.KeyEvent.VK_LEFT; case java.awt.event.KeyEvent.VK_KP_UP : /** Fall through intended .. */ case java.awt.event.KeyEvent.VK_UP : return com.jogamp.newt.event.KeyEvent.VK_UP; @@ -381,7 +381,7 @@ public class AWTNewtEventFactory { case java.awt.event.KeyEvent.VK_DOWN : return com.jogamp.newt.event.KeyEvent.VK_DOWN; case java.awt.event.KeyEvent.VK_CONTEXT_MENU : return com.jogamp.newt.event.KeyEvent.VK_CONTEXT_MENU; case java.awt.event.KeyEvent.VK_WINDOWS : return com.jogamp.newt.event.KeyEvent.VK_WINDOWS; - case java.awt.event.KeyEvent.VK_META : return com.jogamp.newt.event.KeyEvent.VK_META; + case java.awt.event.KeyEvent.VK_META : return com.jogamp.newt.event.KeyEvent.VK_META; case java.awt.event.KeyEvent.VK_HELP : return com.jogamp.newt.event.KeyEvent.VK_HELP; case java.awt.event.KeyEvent.VK_COMPOSE : return com.jogamp.newt.event.KeyEvent.VK_COMPOSE; case java.awt.event.KeyEvent.VK_BEGIN : return com.jogamp.newt.event.KeyEvent.VK_BEGIN; @@ -558,7 +558,7 @@ public class AWTNewtEventFactory { case com.jogamp.newt.event.KeyEvent.VK_DOWN : return java.awt.event.KeyEvent.VK_DOWN; case com.jogamp.newt.event.KeyEvent.VK_CONTEXT_MENU : return java.awt.event.KeyEvent.VK_CONTEXT_MENU; case com.jogamp.newt.event.KeyEvent.VK_WINDOWS : return java.awt.event.KeyEvent.VK_WINDOWS; - case com.jogamp.newt.event.KeyEvent.VK_META : return java.awt.event.KeyEvent.VK_META; + case com.jogamp.newt.event.KeyEvent.VK_META : return java.awt.event.KeyEvent.VK_META; case com.jogamp.newt.event.KeyEvent.VK_HELP : return java.awt.event.KeyEvent.VK_HELP; case com.jogamp.newt.event.KeyEvent.VK_COMPOSE : return java.awt.event.KeyEvent.VK_COMPOSE; case com.jogamp.newt.event.KeyEvent.VK_BEGIN : return java.awt.event.KeyEvent.VK_BEGIN; @@ -636,7 +636,7 @@ public class AWTNewtEventFactory { } return new com.jogamp.newt.event.MouseEvent( newtType, (null==newtSource)?(Object)event.getComponent():(Object)newtSource, event.getWhen(), - mods, event.getX(), event.getY(), (short)event.getClickCount(), + mods, event.getX(), event.getY(), (short)event.getClickCount(), newtButton, MouseEvent.getRotationXYZ(rotation, mods), 1f); } return null; // no mapping .. @@ -650,11 +650,11 @@ public class AWTNewtEventFactory { if( (short)0 != newtType ) { final short newtKeyCode = awtKeyCode2NewtKeyCode( event.getKeyCode() ); return com.jogamp.newt.event.KeyEvent.create( - newtType, (null==newtSource)?(Object)event.getComponent():(Object)newtSource, event.getWhen(), - awtModifiers2Newt(event.getModifiers(), event.getModifiersEx()), + newtType, (null==newtSource)?(Object)event.getComponent():(Object)newtSource, event.getWhen(), + awtModifiers2Newt(event.getModifiers(), event.getModifiersEx()), newtKeyCode, newtKeyCode, event.getKeyChar()); } return null; // no mapping .. } - + } diff --git a/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java b/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java index fa494adca..325f17278 100644 --- a/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java +++ b/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.newt.awt.event; import java.awt.KeyboardFocusManager; @@ -45,7 +45,7 @@ import com.jogamp.newt.event.awt.AWTWindowAdapter; public class AWTParentWindowAdapter extends AWTWindowAdapter implements java.awt.event.HierarchyListener { NativeWindow downstreamParent; - + public AWTParentWindowAdapter(NativeWindow downstreamParent, com.jogamp.newt.Window downstream) { super(downstream); this.downstreamParent = downstreamParent; @@ -111,12 +111,12 @@ public class AWTParentWindowAdapter extends AWTWindowAdapter implements java.awt public void componentMoved(java.awt.event.ComponentEvent e) { if(DEBUG_IMPLEMENTATION) { - System.err.println("AWT: componentMoved: "+e); + System.err.println("AWT: componentMoved: "+e); } final Window newtWindow = getNewtWindow(); if(newtWindow.getDelegatedWindow() instanceof DriverUpdatePosition) { ((DriverUpdatePosition)newtWindow.getDelegatedWindow()).updatePosition(0, 0); - } + } } public void windowActivated(java.awt.event.WindowEvent e) { @@ -130,7 +130,7 @@ public class AWTParentWindowAdapter extends AWTWindowAdapter implements java.awt public void hierarchyChanged(java.awt.event.HierarchyEvent e) { if( null == getNewtEventListener() ) { long bits = e.getChangeFlags(); - final java.awt.Component changed = e.getChanged(); + final java.awt.Component changed = e.getChanged(); if( 0 != ( java.awt.event.HierarchyEvent.SHOWING_CHANGED & bits ) ) { final boolean showing = changed.isShowing(); if(DEBUG_IMPLEMENTATION) { @@ -142,7 +142,7 @@ public class AWTParentWindowAdapter extends AWTWindowAdapter implements java.awt getNewtWindow().setVisible(showing); } }}); - } + } if(DEBUG_IMPLEMENTATION) { if( 0 != ( java.awt.event.HierarchyEvent.DISPLAYABILITY_CHANGED & bits ) ) { final boolean displayability = changed.isDisplayable(); diff --git a/src/newt/classes/jogamp/newt/driver/DriverClearFocus.java b/src/newt/classes/jogamp/newt/driver/DriverClearFocus.java index 0a824e83b..0ff86fe93 100644 --- a/src/newt/classes/jogamp/newt/driver/DriverClearFocus.java +++ b/src/newt/classes/jogamp/newt/driver/DriverClearFocus.java @@ -1,10 +1,10 @@ package jogamp.newt.driver; -/** +/** * Interface tagging driver requirement of clearing the focus. *

                            - * Some drivers require a programmatic {@link #clearFocus()} when traversing the focus. - *

                            + * Some drivers require a programmatic {@link #clearFocus()} when traversing the focus. + *

                            */ public interface DriverClearFocus { /** Programmatic clear the focus */ diff --git a/src/newt/classes/jogamp/newt/driver/DriverUpdatePosition.java b/src/newt/classes/jogamp/newt/driver/DriverUpdatePosition.java index 2ec327187..e5f9b6a68 100644 --- a/src/newt/classes/jogamp/newt/driver/DriverUpdatePosition.java +++ b/src/newt/classes/jogamp/newt/driver/DriverUpdatePosition.java @@ -1,14 +1,14 @@ package jogamp.newt.driver; -/** +/** * Interface tagging driver requirement of absolute positioning, ie. depend on parent position. */ public interface DriverUpdatePosition { - /** + /** * Programmatic update the top-left corner * of the client area relative to it's parent. - * - * @param x x-component + * + * @param x x-component * @param y y-component **/ void updatePosition(int x, int y); diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java b/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java index 9a1632130..14cc9c69d 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java +++ b/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.awt; @@ -100,7 +100,7 @@ public class AWTCanvas extends Canvas { @Override public void paint(Graphics g) { } - + public boolean hasDeviceChanged() { boolean res = displayConfigChanged; displayConfigChanged=false; @@ -154,12 +154,12 @@ public class AWTCanvas extends Canvas { public NativeWindow getNativeWindow() { final JAWTWindow _jawtWindow = jawtWindow; return (null != _jawtWindow) ? _jawtWindow : null; - } - + } + public boolean isOffscreenLayerSurfaceEnabled() { - return null != jawtWindow ? jawtWindow.isOffscreenLayerSurfaceEnabled() : false; + return null != jawtWindow ? jawtWindow.isOffscreenLayerSurfaceEnabled() : false; } - + public void removeNotify() { try { dispose(); @@ -188,7 +188,7 @@ public class AWTCanvas extends Canvas { } } } - + private String getThreadName() { return Thread.currentThread().getName(); } /** @@ -200,7 +200,7 @@ public class AWTCanvas extends Canvas { * Workaround for problems with Xinerama and java.awt.Component.checkGD * when adding to a container on a different graphics device than the * one that this Canvas is associated with. - * + * * GC will be null unless: * - A native peer has assigned it. This means we have a native * peer, and are already comitted to a graphics configuration. @@ -214,7 +214,7 @@ public class AWTCanvas extends Canvas { * chosen is only non-null on platforms where the GLDrawableFactory * returns a non-null GraphicsConfiguration (in the GLCanvas * constructor). - * + * * if gc is from this Canvas' native peer then it should equal chosen, * otherwise it is from an ancestor component that this Canvas is being * added to, and we go into this block. @@ -224,21 +224,21 @@ public class AWTCanvas extends Canvas { * Check for compatibility with gc. If they differ by only the * device then return a new GCconfig with the super-class' GDevice * (and presumably the same visual ID in Xinerama). - * + * */ if (!chosen.getDevice().getIDstring().equals(gc.getDevice().getIDstring())) { /* * Here we select a GraphicsConfiguration on the alternate * device that is presumably identical to the chosen * configuration, but on the other device. - * + * * Should really check to ensure that we select a configuration * with the same X visual ID for Xinerama screens, otherwise the * GLDrawable may have the wrong visual ID (I don't think this * ever gets updated). May need to add a method to * X11GLDrawableFactory to do this in a platform specific * manner. - * + * * However, on platforms where we can actually get into this * block, both devices should have the same visual list, and the * same configuration should be selected here. @@ -265,7 +265,7 @@ public class AWTCanvas extends Canvas { chosen = compatible; if( !config.getChosenCapabilities().equals(awtConfig.getChosenCapabilities())) { displayConfigChanged=true; - } + } awtConfig = config; } } @@ -275,7 +275,7 @@ public class AWTCanvas extends Canvas { * return the GC that was selected in the constructor (and might * cause an exception in Component.checkGD when adding to a * container, but in this case that would be the desired behavior). - * + * */ return chosen; } else if (gc == null) { @@ -299,7 +299,7 @@ public class AWTCanvas extends Canvas { CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, GraphicsDevice device) { - final AbstractGraphicsScreen aScreen = null != device ? + final AbstractGraphicsScreen aScreen = null != device ? AWTGraphicsScreen.createScreenDevice(device, AbstractGraphicsDevice.DEFAULT_UNIT): AWTGraphicsScreen.createDefault(); AWTGraphicsConfiguration config = (AWTGraphicsConfiguration) diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java b/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java index 02f4be0cd..bddb43b30 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java +++ b/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java @@ -40,9 +40,9 @@ import jogamp.newt.Debug; public class AWTEDTUtil implements EDTUtil { public static final boolean DEBUG = Debug.debug("EDT"); - + private final Object edtLock = new Object(); // locking the EDT start/stop state - private final ThreadGroup threadGroup; + private final ThreadGroup threadGroup; private final String name; private final Runnable dispatchMessages; private NEDT nedt = null; @@ -66,7 +66,7 @@ public class AWTEDTUtil implements EDTUtil { final public void setPollPeriod(long ms) { pollPeriod = ms; } - + @Override public final boolean start() throws IllegalStateException { synchronized(edtLock) { @@ -107,12 +107,12 @@ public class AWTEDTUtil implements EDTUtil { public final boolean isCurrentThreadNEDT() { return nedt == Thread.currentThread(); } - + @Override public final boolean isCurrentThreadEDTorNEDT() { - return EventQueue.isDispatchThread() || nedt == Thread.currentThread(); + return EventQueue.isDispatchThread() || nedt == Thread.currentThread(); } - + @Override final public boolean isRunning() { return nedt.isRunning() ; @@ -127,12 +127,12 @@ public class AWTEDTUtil implements EDTUtil { public final boolean invoke(boolean wait, Runnable task) { return invokeImpl(wait, task, false); } - + private static Runnable nullTask = new Runnable() { @Override - public void run() { } + public void run() { } }; - + private final boolean invokeImpl(boolean wait, Runnable task, boolean stop) { Throwable throwable = null; RunnableTask rTask = null; @@ -145,7 +145,7 @@ public class AWTEDTUtil implements EDTUtil { if(DEBUG) { Thread.dumpStack(); } - return false; + return false; } if( isCurrentThreadEDT() ) { if(null != task) { @@ -181,7 +181,7 @@ public class AWTEDTUtil implements EDTUtil { if(null != task) { rTask = new RunnableTask(task, wait ? rTaskLock : null, - true /* always catch and report Exceptions, don't disturb EDT */, + true /* always catch and report Exceptions, don't disturb EDT */, wait ? null : System.err); AWTEDTExecutor.singleton.invoke(false, rTask); } @@ -205,7 +205,7 @@ public class AWTEDTUtil implements EDTUtil { } return true; } - } + } @Override final public boolean waitUntilIdle() { @@ -241,7 +241,7 @@ public class AWTEDTUtil implements EDTUtil { } } } - + class NEDT extends Thread { volatile boolean shouldStop = false; volatile boolean isRunning = false; @@ -261,7 +261,7 @@ public class AWTEDTUtil implements EDTUtil { super.start(); } - /** + /** * Utilizing locking only on tasks and its execution, * not for event dispatching. */ @@ -302,7 +302,7 @@ public class AWTEDTUtil implements EDTUtil { } } finally { if(DEBUG) { - System.err.println(getName()+": AWT-EDT run() END "+ getName()+", "+error); + System.err.println(getName()+": AWT-EDT run() END "+ getName()+", "+error); } synchronized(edtLock) { isRunning = false; @@ -317,7 +317,7 @@ public class AWTEDTUtil implements EDTUtil { } // finally } // run() } // EventDispatchThread - + } diff --git a/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java index 30449f9bc..9e716d544 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.awt; @@ -57,7 +57,7 @@ public class DisplayDriver extends DisplayImpl { protected EDTUtil createEDTUtil() { final EDTUtil def; if(NewtFactory.useEDT()) { - def = new AWTEDTUtil(Thread.currentThread().getThreadGroup(), "AWTDisplay-"+getFQName(), dispatchMessagesRunnable); + def = new AWTEDTUtil(Thread.currentThread().getThreadGroup(), "AWTDisplay-"+getFQName(), dispatchMessagesRunnable); if(DEBUG) { System.err.println("Display.createNative("+getFQName()+") Create EDTUtil: "+def.getClass().getName()); } @@ -67,7 +67,7 @@ public class DisplayDriver extends DisplayImpl { return def; } - protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { + protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { aDevice.close(); } diff --git a/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java index 126143e1e..a2430e2bb 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java @@ -1,21 +1,21 @@ /* * Copyright (c) 2008 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 @@ -28,7 +28,7 @@ * 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. - * + * */ package jogamp.newt.driver.awt; @@ -66,10 +66,10 @@ public class ScreenDriver extends ScreenImpl { } protected void closeNativeImpl() { } - + protected int validateScreenIndex(int idx) { - return idx; // pass through ... - } + return idx; // pass through ... + } private static MonitorMode getModeProps(Cache cache, DisplayMode mode) { int rate = mode.getRefreshRate(); @@ -90,16 +90,16 @@ public class ScreenDriver extends ScreenImpl { props[i++] = 0; // flags props[i++] = 0; // mode_idx props[i++] = 0; // rotation - return MonitorModeProps.streamInMonitorMode(null, cache, props, 0); + return MonitorModeProps.streamInMonitorMode(null, cache, props, 0); } - + @Override protected void collectNativeMonitorModesAndDevicesImpl(Cache cache) { final GraphicsDevice awtGD = ((AWTGraphicsDevice)getDisplay().getGraphicsDevice()).getGraphicsDevice(); final DisplayMode[] awtModes = awtGD.getDisplayModes(); for(int i=0; i=0 || y>=0) { System.err.println("BCEGL Window.setPositionImpl n/a in BroadcomEGL"); } - + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); } @@ -122,7 +122,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl { } protected void updateInsetsImpl(Insets insets) { - // nop .. + // nop .. } @Override diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java index 4872a9071..52c92a5da 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -72,7 +72,7 @@ public class DisplayDriver extends DisplayImpl { DispatchMessages(); } - protected static native boolean initIDs(); + protected static native boolean initIDs(); private native void DispatchMessages(); } diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java index be99052d7..5a1917419 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -53,9 +53,9 @@ public class ScreenDriver extends ScreenImpl { protected void closeNativeImpl() { } protected int validateScreenIndex(int idx) { - return 0; // only one screen available - } - + return 0; // only one screen available + } + @Override protected final void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache) { int[] props = new int[ MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL ]; @@ -92,20 +92,20 @@ public class ScreenDriver extends ScreenImpl { protected boolean setCurrentMonitorModeImpl(final MonitorDevice monitor, final MonitorMode mode) { return false; } - + @Override protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { vOriginSize.set(0, 0, cachedWidth, cachedHeight); } - + /** Called from {@link #initNative()}. */ protected void setScreenSize(int width, int height) { cachedWidth = width; cachedHeight = height; } - + private static int cachedWidth = 0; - private static int cachedHeight = 0; + private static int cachedHeight = 0; protected static native boolean initIDs(); protected native void initNative(); diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java index e820439d0..560e49e96 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -65,7 +65,7 @@ public class WindowDriver extends WindowImpl { final EGLGraphicsDevice aDevice = (EGLGraphicsDevice) aScreen.getDevice(); final EGLGraphicsDevice eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(aDevice.getNativeDisplayID(), aDevice.getConnection(), aDevice.getUnitID()); final DefaultGraphicsScreen eglScreen = new DefaultGraphicsScreen(eglDevice, aScreen.getIndex()); - + final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( capsRequested, capsRequested, capabilitiesChooser, eglScreen, VisualIDHolder.VID_UNDEFINED); if (null == cfg) { @@ -89,24 +89,24 @@ public class WindowDriver extends WindowImpl { windowHandleClose = nativeWindowHandle; addWindowListener(LinuxMouseTracker.getSingleton()); addWindowListener(LinuxEventDeviceTracker.getSingleton()); - focusChanged(false, true); + focusChanged(false, true); } protected void closeNativeImpl() { final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) getGraphicsConfiguration().getScreen().getDevice(); - + removeWindowListener(LinuxMouseTracker.getSingleton()); removeWindowListener(LinuxEventDeviceTracker.getSingleton()); - + if(0!=windowHandleClose) { CloseWindow(windowHandleClose, windowUserData); windowUserData=0; } - + eglDevice.close(); } - protected void requestFocusImpl(boolean reparented) { + protected void requestFocusImpl(boolean reparented) { focusChanged(false, true); } @@ -115,7 +115,7 @@ public class WindowDriver extends WindowImpl { setVisible0(nativeWindowHandle, 0 != ( FLAG_IS_VISIBLE & flags)); visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); } - + if(0!=nativeWindowHandle) { if(0 != ( FLAG_CHANGE_FULLSCREEN & flags)) { final boolean fs = 0 != ( FLAG_IS_FULLSCREEN & flags) ; @@ -135,11 +135,11 @@ public class WindowDriver extends WindowImpl { System.err.println("setPosition n/a in KD"); } } - + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); } - + return true; } @@ -148,9 +148,9 @@ public class WindowDriver extends WindowImpl { } protected void updateInsetsImpl(Insets insets) { - // nop .. + // nop .. } - + //---------------------------------------------------------------------- // Internals only // diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java index ee93eb932..4cb566bc2 100644 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2012 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.intel.gdl; diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java index 27b776562..b5202aaf9 100644 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2012 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.intel.gdl; @@ -62,9 +62,9 @@ public class ScreenDriver extends jogamp.newt.ScreenImpl { protected void closeNativeImpl() { } protected int validateScreenIndex(int idx) { - return 0; // only one screen available + return 0; // only one screen available } - + @Override protected final void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache) { int[] props = new int[ MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL ]; @@ -101,11 +101,11 @@ public class ScreenDriver extends jogamp.newt.ScreenImpl { protected boolean setCurrentMonitorModeImpl(final MonitorDevice monitor, final MonitorMode mode) { return false; } - + protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { vOriginSize.set(0, 0, cachedWidth, cachedHeight); } - + //---------------------------------------------------------------------- // Internals only // @@ -118,7 +118,7 @@ public class ScreenDriver extends jogamp.newt.ScreenImpl { cachedWidth = width; cachedHeight = height; } - + private static int cachedWidth = 0; private static int cachedHeight = 0; } diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java index 98335f192..80821d4da 100644 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2012 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.intel.gdl; @@ -108,7 +108,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl { } visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); } - + return true; } @@ -126,9 +126,9 @@ public class WindowDriver extends jogamp.newt.WindowImpl { } protected void updateInsetsImpl(Insets insets) { - // nop .. + // nop .. } - + //---------------------------------------------------------------------- // Internals only // diff --git a/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java index 3cd72e971..1b92ca586 100644 --- a/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2012 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.kd; diff --git a/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java index f893275ca..17cc5dd2f 100644 --- a/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2012 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.kd; @@ -58,9 +58,9 @@ public class ScreenDriver extends ScreenImpl { protected void closeNativeImpl() { } protected int validateScreenIndex(int idx) { - return 0; // only one screen available - } - + return 0; // only one screen available + } + @Override protected final void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache) { int[] props = new int[ MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL ]; @@ -97,16 +97,16 @@ public class ScreenDriver extends ScreenImpl { protected boolean setCurrentMonitorModeImpl(final MonitorDevice monitor, final MonitorMode mode) { return false; } - + protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { vOriginSize.set(0, 0, cachedWidth, cachedHeight); } - + protected void sizeChanged(int w, int h) { cachedWidth = w; cachedHeight = h; } - + private static int cachedWidth = 0; - private static int cachedHeight = 0; + private static int cachedHeight = 0; } diff --git a/src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java index c733a3e94..d30d4f025 100644 --- a/src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2012 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.kd; @@ -97,7 +97,7 @@ public class WindowDriver extends WindowImpl { setVisible0(eglWindowHandle, 0 != ( FLAG_IS_VISIBLE & flags)); visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); } - + if(0!=eglWindowHandle) { if(0 != ( FLAG_CHANGE_FULLSCREEN & flags)) { final boolean fs = 0 != ( FLAG_IS_FULLSCREEN & flags) ; @@ -117,11 +117,11 @@ public class WindowDriver extends WindowImpl { System.err.println("setPosition n/a in KD"); } } - + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); } - + return true; } @@ -130,9 +130,9 @@ public class WindowDriver extends WindowImpl { } protected void updateInsetsImpl(Insets insets) { - // nop .. + // nop .. } - + //---------------------------------------------------------------------- // Internals only // diff --git a/src/newt/classes/jogamp/newt/driver/linux/LinuxEventDeviceTracker.java b/src/newt/classes/jogamp/newt/driver/linux/LinuxEventDeviceTracker.java index e68b91d82..b7c86a26d 100644 --- a/src/newt/classes/jogamp/newt/driver/linux/LinuxEventDeviceTracker.java +++ b/src/newt/classes/jogamp/newt/driver/linux/LinuxEventDeviceTracker.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -126,7 +126,7 @@ public class LinuxEventDeviceTracker implements WindowListener { try { while(true) { Thread.sleep(1000); - } + } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -186,7 +186,7 @@ public class LinuxEventDeviceTracker implements WindowListener { /** * The Linux input event interface. * http://www.kernel.org/doc/Documentation/input/input.txt - * + * * struct input_event { * struct timeval time; * unsigned short type; @@ -262,7 +262,7 @@ public class LinuxEventDeviceTracker implements WindowListener { break; case 1: // EV_KEY keyCode = LinuxEVKey2NewtVKey(code); // The device independent code. - keyChar = NewtVKey2Unicode(keyCode, modifiers); // The printable character w/ key modifiers. + keyChar = NewtVKey2Unicode(keyCode, modifiers); // The printable character w/ key modifiers. if(Window.DEBUG_KEY_EVENT) { System.out.println("[EV_KEY: [time "+timeSeconds+":"+timeSecondFraction+"] type "+type+" / code "+code+" = value "+value); } @@ -946,7 +946,7 @@ public class LinuxEventDeviceTracker implements WindowListener { case 248: // mic mute break; // FIXME - default: + default: } if(Window.DEBUG_KEY_EVENT) { diff --git a/src/newt/classes/jogamp/newt/driver/linux/LinuxMouseTracker.java b/src/newt/classes/jogamp/newt/driver/linux/LinuxMouseTracker.java index 0d6278bfb..1e314b7f4 100644 --- a/src/newt/classes/jogamp/newt/driver/linux/LinuxMouseTracker.java +++ b/src/newt/classes/jogamp/newt/driver/linux/LinuxMouseTracker.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -48,16 +48,16 @@ import com.jogamp.newt.event.WindowUpdateEvent; * within it's own polling thread. */ public class LinuxMouseTracker implements WindowListener { - + private static final LinuxMouseTracker lmt; - + static { lmt = new LinuxMouseTracker(); final Thread t = new Thread(lmt.mouseDevicePoller, "NEWT-LinuxMouseTracker"); t.setDaemon(true); t.start(); } - + public static LinuxMouseTracker getSingleton() { return lmt; } @@ -71,7 +71,7 @@ public class LinuxMouseTracker implements WindowListener { private short old_buttonDown = 0; private WindowImpl focusedWindow = null; private MouseDevicePoller mouseDevicePoller = new MouseDevicePoller(); - + @Override public void windowResized(WindowEvent e) { } @@ -107,7 +107,7 @@ public class LinuxMouseTracker implements WindowListener { @Override public void windowRepaint(WindowUpdateEvent e) { } - + class MouseDevicePoller implements Runnable { @Override public void run() { @@ -150,17 +150,17 @@ public class LinuxMouseTracker implements WindowListener { yo=(b[0]&128)>0; xd=b[1]; yd=b[2]; - + x+=xd; y-=yd; - + if(x<0) { x=0; } if(y<0) { y=0; } - + buttonDown = 0; if(lb) { buttonDown = MouseEvent.BUTTON1; @@ -171,7 +171,7 @@ public class LinuxMouseTracker implements WindowListener { if(rb) { buttonDown = MouseEvent.BUTTON3; } - + if(null != focusedWindow) { if( x >= focusedWindow.getScreen().getWidth() ) { x = focusedWindow.getScreen().getWidth() - 1; @@ -179,31 +179,31 @@ public class LinuxMouseTracker implements WindowListener { if( y >= focusedWindow.getScreen().getHeight() ) { y = focusedWindow.getScreen().getHeight() - 1; } - int wx = x - focusedWindow.getX(), wy = y - focusedWindow.getY(); - + int wx = x - focusedWindow.getX(), wy = y - focusedWindow.getY(); + if(old_x != x || old_y != y) { // mouse moved - focusedWindow.sendMouseEvent(MouseEvent.EVENT_MOUSE_MOVED, 0, wx, wy, (short)0, 0 ); + focusedWindow.sendMouseEvent(MouseEvent.EVENT_MOUSE_MOVED, 0, wx, wy, (short)0, 0 ); } - + if(old_buttonDown != buttonDown) { // press/release if( 0 != buttonDown ) { - focusedWindow.sendMouseEvent(MouseEvent.EVENT_MOUSE_PRESSED, 0, wx, wy, buttonDown, 0 ); + focusedWindow.sendMouseEvent(MouseEvent.EVENT_MOUSE_PRESSED, 0, wx, wy, buttonDown, 0 ); } else { - focusedWindow.sendMouseEvent(MouseEvent.EVENT_MOUSE_RELEASED, 0, wx, wy, old_buttonDown, 0 ); + focusedWindow.sendMouseEvent(MouseEvent.EVENT_MOUSE_RELEASED, 0, wx, wy, old_buttonDown, 0 ); } - } + } } else { if(Window.DEBUG_MOUSE_EVENT) { System.out.println(x+"/"+y+", hs="+hs+",vs="+vs+",lb="+lb+",rb="+rb+",mb="+mb+",xo="+xo+",yo="+yo+"xd="+xd+",yd="+yd); } } - + old_x = x; old_y = y; old_buttonDown = buttonDown; - + } if(null != fis) { try { @@ -214,5 +214,5 @@ public class LinuxMouseTracker implements WindowListener { } } } - } + } } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java index a99bc4f23..2dbdfdce7 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2012 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.macosx; @@ -60,19 +60,19 @@ public class DisplayDriver extends DisplayImpl { public static void initSingleton() { // just exist to ensure static init has been run } - + public DisplayDriver() { } protected void dispatchMessagesNative() { // nop } - + protected void createNativeImpl() { aDevice = new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); } - protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { + protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { aDevice.close(); } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacKeyUtil.java b/src/newt/classes/jogamp/newt/driver/macosx/MacKeyUtil.java index baa94facd..a89150d7c 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/MacKeyUtil.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/MacKeyUtil.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -30,7 +30,7 @@ package jogamp.newt.driver.macosx; import com.jogamp.newt.event.KeyEvent; public class MacKeyUtil { - + // // KeyCodes (Layout Dependent) // @@ -64,17 +64,17 @@ public class MacKeyUtil { private static final short kVK_ANSI_8 = 0x1C; private static final short kVK_ANSI_0 = 0x1D; private static final short kVK_ANSI_RightBracket = 0x1E; - private static final short kVK_ANSI_O = 0x1F; + private static final short kVK_ANSI_O = 0x1F; private static final short kVK_ANSI_U = 0x20; private static final short kVK_ANSI_LeftBracket = 0x21; private static final short kVK_ANSI_I = 0x22; private static final short kVK_ANSI_P = 0x23; private static final short kVK_ANSI_L = 0x25; private static final short kVK_ANSI_J = 0x26; - private static final short kVK_ANSI_Quote = 0x27; + private static final short kVK_ANSI_Quote = 0x27; private static final short kVK_ANSI_K = 0x28; private static final short kVK_ANSI_Semicolon = 0x29; - private static final short kVK_ANSI_Backslash = 0x2A; + private static final short kVK_ANSI_Backslash = 0x2A; private static final short kVK_ANSI_Comma = 0x2B; private static final short kVK_ANSI_Slash = 0x2C; private static final short kVK_ANSI_N = 0x2D; @@ -99,7 +99,7 @@ public class MacKeyUtil { private static final short kVK_ANSI_Keypad7 = 0x59; private static final short kVK_ANSI_Keypad8 = 0x5B; private static final short kVK_ANSI_Keypad9 = 0x5C; - + // // KeyCodes (Layout Independent) // @@ -150,7 +150,7 @@ public class MacKeyUtil { private static final short kVK_RightArrow = 0x7C; private static final short kVK_DownArrow = 0x7D; private static final short kVK_UpArrow = 0x7E; - + // // Key constants handled differently on Mac OS X than other platforms // @@ -230,8 +230,8 @@ public class MacKeyUtil { private static final char NSHelpFunctionKey = 0xF746; private static final char NSModeSwitchFunctionKey = 0xF747; */ - - static short validateKeyCode(short keyCode, char keyChar) { + + static short validateKeyCode(short keyCode, char keyChar) { // OS X Virtual Keycodes switch(keyCode) { // @@ -267,17 +267,17 @@ public class MacKeyUtil { case kVK_ANSI_8: return KeyEvent.VK_8; case kVK_ANSI_0: return KeyEvent.VK_0; case kVK_ANSI_RightBracket: return KeyEvent.VK_CLOSE_BRACKET; - case kVK_ANSI_O: return KeyEvent.VK_O; + case kVK_ANSI_O: return KeyEvent.VK_O; case kVK_ANSI_U: return KeyEvent.VK_U; case kVK_ANSI_LeftBracket: return KeyEvent.VK_OPEN_BRACKET; case kVK_ANSI_I: return KeyEvent.VK_I; case kVK_ANSI_P: return KeyEvent.VK_P; case kVK_ANSI_L: return KeyEvent.VK_L; case kVK_ANSI_J: return KeyEvent.VK_J; - case kVK_ANSI_Quote: return KeyEvent.VK_QUOTE; + case kVK_ANSI_Quote: return KeyEvent.VK_QUOTE; case kVK_ANSI_K: return KeyEvent.VK_K; case kVK_ANSI_Semicolon: return KeyEvent.VK_SEMICOLON; - case kVK_ANSI_Backslash: return KeyEvent.VK_BACK_SLASH; + case kVK_ANSI_Backslash: return KeyEvent.VK_BACK_SLASH; case kVK_ANSI_Comma: return KeyEvent.VK_COMMA; case kVK_ANSI_Slash: return KeyEvent.VK_SLASH; case kVK_ANSI_N: return KeyEvent.VK_N; @@ -302,7 +302,7 @@ public class MacKeyUtil { case kVK_ANSI_Keypad7: return KeyEvent.VK_7; case kVK_ANSI_Keypad8: return KeyEvent.VK_8; case kVK_ANSI_Keypad9: return KeyEvent.VK_9; - + // // KeyCodes (Layout Independent) // @@ -321,7 +321,7 @@ public class MacKeyUtil { case kVK_RightControl: return KeyEvent.VK_CONTROL; // case kVK_Function: return KeyEvent.VK_F; case kVK_F17: return KeyEvent.VK_F17; - // case kVK_VolumeUp: + // case kVK_VolumeUp: // case kVK_VolumeDown: // case kVK_Mute: case kVK_F18: return KeyEvent.VK_F18; @@ -354,7 +354,7 @@ public class MacKeyUtil { case kVK_DownArrow: return KeyEvent.VK_DOWN; case kVK_UpArrow: return KeyEvent.VK_UP; } - + switch (keyChar) { case NSUpArrowFunctionKey: return KeyEvent.VK_UP; case NSDownArrowFunctionKey: return KeyEvent.VK_DOWN; @@ -422,5 +422,5 @@ public class MacKeyUtil { } return (short) keyChar; // let's hope for the best (compatibility of keyChar/keyCode's) - } + } } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java index a3bb26731..5d3b7287b 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2011 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.macosx; @@ -44,7 +44,7 @@ import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.MonitorMode; public class ScreenDriver extends ScreenImpl { - + static { DisplayDriver.initSingleton(); } @@ -68,7 +68,7 @@ public class ScreenDriver extends ScreenImpl { } return res; } - + @Override protected final void collectNativeMonitorModesAndDevicesImpl(MonitorModeProps.Cache cache) { int crtIdx = 0; @@ -85,16 +85,16 @@ public class ScreenDriver extends ScreenImpl { final MonitorMode currentMode = getMonitorModeImpl(cache, crtIdx, -1); if ( null == currentMode ) { throw new InternalError("Could not gather current mode of device "+crtIdx+", but gathered "+modeIdx+" modes"); - } + } final int[] monitorProps = getMonitorProps0(crtIdx); if ( null == monitorProps ) { throw new InternalError("Could not gather device "+crtIdx+", but gathered "+modeIdx+" modes"); - } + } // merge monitor-props + supported modes MonitorModeProps.streamInMonitorDevice(null, cache, this, supportedModes, currentMode, monitorProps, 0); - + // next monitor, 1st mode - supportedModes= new ArrayHashSet(); + supportedModes= new ArrayHashSet(); crtIdx++; modeIdx=0; } else { @@ -108,16 +108,16 @@ public class ScreenDriver extends ScreenImpl { protected MonitorMode queryCurrentMonitorModeImpl(MonitorDevice monitor) { return getMonitorModeImpl(null, monitor.getId(), -1); } - + @Override protected boolean setCurrentMonitorModeImpl(MonitorDevice monitor, MonitorMode mode) { return setMonitorMode0(monitor.getId(), mode.getId(), mode.getRotation()); } - + protected int validateScreenIndex(int idx) { - return 0; // big-desktop w/ multiple monitor attached, only one screen available + return 0; // big-desktop w/ multiple monitor attached, only one screen available } - + private native int[] getMonitorProps0(int crt_idx); private native int[] getMonitorMode0(int crt_index, int mode_idx); private native boolean setMonitorMode0(int crt_index, int nativeId, int rot); diff --git a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java index 08638d868..f36d32772 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.macosx; @@ -53,14 +53,14 @@ import com.jogamp.newt.event.InputEvent; import com.jogamp.newt.event.KeyEvent; public class WindowDriver extends WindowImpl implements MutableSurface, DriverClearFocus, DriverUpdatePosition { - + static { DisplayDriver.initSingleton(); } public WindowDriver() { } - + @Override protected void createNativeImpl() { final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( @@ -69,7 +69,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); } setGraphicsConfiguration(cfg); - reconfigureWindowImpl(getX(), getY(), getWidth(), getHeight(), getReconfigureFlags(FLAG_CHANGE_VISIBILITY, true)); + reconfigureWindowImpl(getX(), getY(), getWidth(), getHeight(), getReconfigureFlags(FLAG_CHANGE_VISIBILITY, true)); if (0 == getWindowHandle()) { throw new NativeWindowException("Error creating window"); } @@ -79,7 +79,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl protected void closeNativeImpl() { try { if(DEBUG_IMPLEMENTATION) { System.err.println("MacWindow.CloseAction "+Thread.currentThread().getName()); } - final long handle = getWindowHandle(); + final long handle = getWindowHandle(); visibleChanged(true, false); setWindowHandle(0); surfaceHandle = 0; @@ -92,16 +92,16 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl } } ); } } catch (Throwable t) { - if(DEBUG_IMPLEMENTATION) { + if(DEBUG_IMPLEMENTATION) { Exception e = new Exception("Warning: closeNative failed - "+Thread.currentThread().getName(), t); e.printStackTrace(); } } } - + @Override protected int lockSurfaceImpl() { - /** + /** * if( isOffscreenInstance ) { * return LOCK_SUCCESS; * } @@ -116,7 +116,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl @Override protected void unlockSurfaceImpl() { - /** + /** * if( isOffscreenInstance ) { * return; * } @@ -129,7 +129,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl } } } - + @Override public final long getSurfaceHandle() { return 0 != sscSurfaceHandle ? sscSurfaceHandle : surfaceHandle; @@ -147,14 +147,14 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl public void run() { orderOut0( 0 != getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle() ); } } ); - } /** this is done by recreation! + } /** this is done by recreation! else if (isVisible()){ OSXUtil.RunOnMainThread(false, new Runnable() { public void run() { orderFront0( 0!=getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle() ); } } ); } */ - } + } } @Override @@ -179,7 +179,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl focusChanged(false, true); } } - + @Override public final void clearFocus() { if(DEBUG_IMPLEMENTATION) { @@ -194,9 +194,9 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl focusChanged(false, false); } } - + private boolean useParent(NativeWindow parent) { return null != parent && 0 != parent.getWindowHandle(); } - + @Override public void updatePosition(int x, int y) { final long handle = getWindowHandle(); @@ -215,8 +215,8 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl // no native event (fullscreen, some reparenting) positionChanged(true, x, y); } - } - + } + @Override protected void sizeChanged(boolean defer, int newWidth, int newHeight, boolean force) { final long handle = getWindowHandle(); @@ -237,7 +237,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl } super.sizeChanged(defer, newWidth, newHeight, force); } - + @Override protected boolean reconfigureWindowImpl(final int x, final int y, final int width, final int height, int flags) { final boolean _isOffscreenInstance = isOffscreenInstance(this, this.getParent()); @@ -250,11 +250,11 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl final boolean useParent = useParent(parent); if( useParent ) { pClientLevelOnSreen = getLocationOnScreenImpl(x, y, parent, useParent); - } else { + } else { pClientLevelOnSreen = new Point(x, y); } } - + if(DEBUG_IMPLEMENTATION) { final AbstractGraphicsConfiguration cWinCfg = this.getGraphicsConfiguration(); final NativeWindow pWin = getParent(); @@ -269,9 +269,9 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl "\n\t, "+getReconfigureFlagsAsString(null, flags)); // Thread.dumpStack(); } - + final boolean setVisible = 0 != ( FLAG_IS_VISIBLE & flags); - + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && !setVisible ) { if ( !isOffscreenInstance ) { OSXUtil.RunOnMainThread(false, new Runnable() { @@ -290,11 +290,11 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl if(isOffscreenInstance) { createWindow(true, 0 != getWindowHandle(), pClientLevelOnSreen, 64, 64, false, setVisible, false); } else { - createWindow(false, 0 != getWindowHandle(), pClientLevelOnSreen, width, height, + createWindow(false, 0 != getWindowHandle(), pClientLevelOnSreen, width, height, 0 != ( FLAG_IS_FULLSCREEN & flags), setVisible, 0 != ( FLAG_IS_ALWAYSONTOP & flags)); } } else { - if( width>0 && height>0 ) { + if( width>0 && height>0 ) { if( !isOffscreenInstance ) { OSXUtil.RunOnMainThread(false, new Runnable() { public void run() { @@ -306,7 +306,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl sizeChanged(true, width, height, false); } if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && setVisible ) { - if( !isOffscreenInstance ) { + if( !isOffscreenInstance ) { OSXUtil.RunOnMainThread(false, new Runnable() { public void run() { orderFront0(getWindowHandle()); @@ -321,7 +321,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl } } if(DEBUG_IMPLEMENTATION) { - System.err.println("MacWindow reconfig.X: clientPos "+pClientLevelOnSreen+", "+width+"x"+height+" -> clientPos "+getLocationOnScreenImpl(0, 0)+", insets: "+getInsets()); + System.err.println("MacWindow reconfig.X: clientPos "+pClientLevelOnSreen+", "+width+"x"+height+" -> clientPos "+getLocationOnScreenImpl(0, 0)+", insets: "+getInsets()); } return true; } @@ -332,28 +332,28 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl final boolean useParent = useParent(parent); return getLocationOnScreenImpl(x, y, parent, useParent); } - + private Point getLocationOnScreenImpl(final int x, final int y, final NativeWindow parent, final boolean useParent) { if( !useParent && !isOffscreenInstance && 0 != surfaceHandle) { return OSXUtil.GetLocationOnScreen(surfaceHandle, true, x, y); } - + final Point p = new Point(x, y); if( useParent ) { p.translate( parent.getLocationOnScreen(null) ); } return p; } - + @Override protected void updateInsetsImpl(Insets insets) { // nop - using event driven insetsChange(..) } - + /** Callback for native screen position change event of the client area. */ - protected void screenPositionChanged(boolean defer, int newX, int newY) { + protected void screenPositionChanged(boolean defer, int newX, int newY) { // passed coordinates are in screen position of the client area - if(getWindowHandle()!=0) { + if(getWindowHandle()!=0) { final NativeWindow parent = getParent(); if( null == parent || isOffscreenInstance ) { if(DEBUG_IMPLEMENTATION) { @@ -362,7 +362,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl positionChanged(defer, newX, newY); } else { // screen position -> rel child window position - Point absPos = new Point(newX, newY); + Point absPos = new Point(newX, newY); Point parentOnScreen = parent.getLocationOnScreen(null); absPos.translate( parentOnScreen.scale(-1, -1) ); if(DEBUG_IMPLEMENTATION) { @@ -374,10 +374,10 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl System.err.println("MacWindow.positionChanged.2 (Screen Pos - IGN): ("+getThreadName()+"): (defer: "+defer+") "+getX()+"/"+getY()+" -> "+newX+"/"+newY); } } - + @Override protected boolean setPointerVisibleImpl(final boolean pointerVisible) { - if( !isOffscreenInstance ) { + if( !isOffscreenInstance ) { return setPointerVisible0(getWindowHandle(), hasFocus(), pointerVisible); } // else may need offscreen solution ? FIXME return false; @@ -385,29 +385,29 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl @Override protected boolean confinePointerImpl(final boolean confine) { - if( !isOffscreenInstance ) { + if( !isOffscreenInstance ) { return confinePointer0(getWindowHandle(), confine); } // else may need offscreen solution ? FIXME return false; } - + @Override protected void warpPointerImpl(final int x, final int y) { - if( !isOffscreenInstance ) { + if( !isOffscreenInstance ) { warpPointer0(getWindowHandle(), x, y); } // else may need offscreen solution ? FIXME } - + @Override public final void sendKeyEvent(short eventType, int modifiers, short keyCode, short keySym, char keyChar) { throw new InternalError("XXX: Adapt Java Code to Native Code Changes"); } - + @Override public final void enqueueKeyEvent(boolean wait, short eventType, int modifiers, short _keyCode, short _keySym, char keyChar) { - throw new InternalError("XXX: Adapt Java Code to Native Code Changes"); + throw new InternalError("XXX: Adapt Java Code to Native Code Changes"); } - + protected final void enqueueKeyEvent(boolean wait, short eventType, int modifiers, short _keyCode, char keyChar, char keySymChar) { // Note that we send the key char for the key code on this // platform -- we do not get any useful key codes out of the system @@ -427,7 +427,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl ", was: pressed "+isKeyPressed(keyCode)+", isModifierKeyCode "+isModifierKeyCode+ ", nativeValid "+isNativeValid()+", isOffscreen "+isOffscreenInstance); } */ - + // OSX delivery order is PRESSED (t0), RELEASED (t1) and TYPED (t2) -> NEWT order: PRESSED (t0) and RELEASED (t1) // Auto-Repeat: OSX delivers only PRESSED, inject auto-repeat RELEASE key _before_ PRESSED switch(eventType) { @@ -451,15 +451,15 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl //---------------------------------------------------------------------- // Internals only - // - - private void createWindow(final boolean offscreenInstance, final boolean recreate, - final PointImmutable pS, final int width, final int height, + // + + private void createWindow(final boolean offscreenInstance, final boolean recreate, + final PointImmutable pS, final int width, final int height, final boolean fullscreen, final boolean visible, final boolean alwaysOnTop) { final long parentWinHandle = getParentWindowHandle(); final long preWinHandle = getWindowHandle(); - + if(DEBUG_IMPLEMENTATION) { System.err.println("MacWindow.createWindow on thread "+Thread.currentThread().getName()+ ": offscreen "+offscreenInstance+", recreate "+recreate+ @@ -474,7 +474,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl setWindowHandle(0); if( 0 == surfaceHandle ) { throw new NativeWindowException("Internal Error - create w/ window, but no Newt NSView"); - } + } OSXUtil.RunOnMainThread(false, new Runnable() { public void run() { changeContentView0(parentWinHandle, preWinHandle, 0); @@ -483,14 +483,14 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl } else { if( 0 != surfaceHandle ) { throw new NativeWindowException("Internal Error - create w/o window, but has Newt NSView"); - } + } surfaceHandle = createView0(pS.getX(), pS.getY(), width, height, fullscreen); if( 0 == surfaceHandle ) { throw new NativeWindowException("Could not create native view "+Thread.currentThread().getName()+" "+this); } } - - final long newWin = createWindow0( pS.getX(), pS.getY(), width, height, fullscreen, + + final long newWin = createWindow0( pS.getX(), pS.getY(), width, height, fullscreen, ( isUndecorated() || offscreenInstance ) ? NSBorderlessWindowMask : NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask, NSBackingStoreBuffered, surfaceHandle); @@ -498,9 +498,9 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl throw new NativeWindowException("Could not create native window "+Thread.currentThread().getName()+" "+this); } setWindowHandle( newWin ); - + final boolean isOpaque = getGraphicsConfiguration().getChosenCapabilities().isBackgroundOpaque() && !offscreenInstance; - // Blocking initialization on main-thread! + // Blocking initialization on main-thread! OSXUtil.RunOnMainThread(true, new Runnable() { public void run() { initWindow0( parentWinHandle, newWin, pS.getX(), pS.getY(), width, height, @@ -517,7 +517,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl ie.printStackTrace(); } } - + protected static native boolean initIDs0(); private native long createView0(int x, int y, int w, int h, boolean fullscreen); private native long createWindow0(int x, int y, int w, int h, boolean fullscreen, int windowStyle, int backingStoreType, long view); @@ -543,7 +543,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl private native void changeContentView0(long parentWindowOrView, long window, long view); /** Must be called on Main-Thread */ private native void setWindowClientTopLeftPointAndSize0(long window, int x, int y, int w, int h, boolean display); - /** Must be called on Main-Thread */ + /** Must be called on Main-Thread */ private native void setWindowClientTopLeftPoint0(long window, int x, int y, boolean display); /** Must be called on Main-Thread */ private native void setAlwaysOnTop0(long window, boolean atop); @@ -551,7 +551,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl private static native boolean setPointerVisible0(long windowHandle, boolean hasFocus, boolean visible); private static native boolean confinePointer0(long windowHandle, boolean confine); private static native void warpPointer0(long windowHandle, int x, int y); - + // Window styles private static final int NSBorderlessWindowMask = 0; private static final int NSTitledWindowMask = 1 << 0; @@ -567,5 +567,5 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl private volatile long surfaceHandle = 0; private long sscSurfaceHandle = 0; private boolean isOffscreenInstance = false; - + } diff --git a/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java index 595d5e952..d3c7416cc 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.windows; @@ -52,10 +52,10 @@ public class DisplayDriver extends DisplayImpl { NEWTJNILibLoader.loadNEWT(); sharedClassFactory = new RegisteredClassFactory(newtClassBaseName, WindowDriver.getNewtWndProc0()); - + if (!WindowDriver.initIDs0(RegisteredClassFactory.getHInstance())) { throw new NativeWindowException("Failed to initialize WindowsWindow jmethodIDs"); - } + } } public static void initSingleton() { @@ -76,7 +76,7 @@ public class DisplayDriver extends DisplayImpl { aDevice = new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); } - protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { + protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { sharedClassFactory.releaseSharedClass(); aDevice.close(); } diff --git a/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java index 621091320..e789b995f 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/windows/ScreenDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.windows; @@ -60,7 +60,7 @@ public class ScreenDriver extends ScreenImpl { protected void createNativeImpl() { aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); } - + @Override protected void closeNativeImpl() { } @@ -71,7 +71,7 @@ public class ScreenDriver extends ScreenImpl { private final String getActiveMonitorName(String adapterName, int monitor_idx) { return getActiveMonitorName0(adapterName, monitor_idx); } - + private final MonitorMode getMonitorModeImpl(MonitorModeProps.Cache cache, String adapterName, int crtModeIdx) { if( null == adapterName ) { return null; @@ -107,7 +107,7 @@ public class ScreenDriver extends ScreenImpl { final int[] monitorProps = getMonitorDevice0(adapterName, crtIdx); // merge monitor-props + supported modes MonitorModeProps.streamInMonitorDevice(null, cache, this, supportedModes, currentMode, monitorProps, 0); - + // next monitor, 1st mode supportedModes= new ArrayHashSet(); } @@ -116,7 +116,7 @@ public class ScreenDriver extends ScreenImpl { adapterName = getAdapterName(crtIdx); } } - + @Override protected Rectangle getNativeMonitorDeviceViewportImpl(MonitorDevice monitor) { final String adapterName = getAdapterName(monitor.getId()); @@ -135,7 +135,7 @@ public class ScreenDriver extends ScreenImpl { protected MonitorMode queryCurrentMonitorModeImpl(MonitorDevice monitor) { return getMonitorModeImpl(null, getAdapterName(monitor.getId()), -1); } - + @Override protected boolean setCurrentMonitorModeImpl(MonitorDevice monitor, MonitorMode mode) { return setMonitorMode0(monitor.getId(), @@ -150,14 +150,14 @@ public class ScreenDriver extends ScreenImpl { @Override protected int validateScreenIndex(int idx) { - return 0; // big-desktop w/ multiple monitor attached, only one screen available + return 0; // big-desktop w/ multiple monitor attached, only one screen available } - + @Override protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { vOriginSize.set(getVirtualOriginX0(), getVirtualOriginY0(), getVirtualWidthImpl0(), getVirtualHeightImpl0()); } - + // Native calls private native int getVirtualOriginX0(); private native int getVirtualOriginY0(); diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java index b2e175415..30405aa05 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.windows; @@ -74,26 +74,26 @@ public class WindowDriver extends WindowImpl { } final long hWnd = getWindowHandle(); hdc = GDI.GetDC(hWnd); - + // return ( 0 == hdc ) ? LOCK_SURFACE_NOT_READY : ( hdc_old != hdc ) ? LOCK_SURFACE_CHANGED : LOCK_SUCCESS ; - if( 0 == hdc ) { + if( 0 == hdc ) { return LOCK_SURFACE_NOT_READY; - } + } hmon = MonitorFromWindow0(hWnd); - + // Let's not trigger on HDC change, GLDrawableImpl.'s destroy/create is a nop here anyways. // FIXME: Validate against EGL surface creation: ANGLE uses HWND -> fine! - return LOCK_SUCCESS; - + return LOCK_SUCCESS; + /** if( hdc_old == hdc ) { return LOCK_SUCCESS; } - if(DEBUG_IMPLEMENTATION) { + if(DEBUG_IMPLEMENTATION) { System.err.println("WindowsWindow: surface change "+toHexString(hdc_old)+" -> "+toHexString(hdc)); // Thread.dumpStack(); } - return LOCK_SURFACE_CHANGED; */ + return LOCK_SURFACE_CHANGED; */ } @Override @@ -137,24 +137,24 @@ public class WindowDriver extends WindowImpl { } setGraphicsConfiguration(cfg); final VersionNumber winVer = Platform.getOSVersionNumber(); - final int flags = getReconfigureFlags(0, true) & + final int flags = getReconfigureFlags(0, true) & ( FLAG_IS_ALWAYSONTOP | FLAG_IS_UNDECORATED ) ; final long _windowHandle = CreateWindow0(DisplayDriver.getHInstance(), display.getWindowClassName(), display.getWindowClassName(), winVer.getMajor(), winVer.getMinor(), - getParentWindowHandle(), getX(), getY(), getWidth(), getHeight(), autoPosition(), flags); + getParentWindowHandle(), getX(), getY(), getWidth(), getHeight(), autoPosition(), flags); if ( 0 == _windowHandle ) { throw new NativeWindowException("Error creating window"); } setWindowHandle(_windowHandle); windowHandleClose = _windowHandle; - + if(DEBUG_IMPLEMENTATION) { Exception e = new Exception("Info: Window new window handle "+Thread.currentThread().getName()+ " (Parent HWND "+toHexString(getParentWindowHandle())+ ") : HWND "+toHexString(_windowHandle)+", "+Thread.currentThread()); e.printStackTrace(); } - } + } protected void closeNativeImpl() { if(windowHandleClose != 0) { @@ -162,7 +162,7 @@ public class WindowDriver extends WindowImpl { try { GDI.ReleaseDC(windowHandleClose, hdc); } catch (Throwable t) { - if(DEBUG_IMPLEMENTATION) { + if(DEBUG_IMPLEMENTATION) { Exception e = new Exception("Warning: closeNativeImpl failed - "+Thread.currentThread().getName(), t); e.printStackTrace(); } @@ -188,14 +188,14 @@ public class WindowDriver extends WindowImpl { System.err.println("WindowsWindow reconfig: "+x+"/"+y+" "+width+"x"+height+", "+ getReconfigureFlagsAsString(null, flags)); } - + if(0 == ( FLAG_IS_UNDECORATED & flags)) { final InsetsImmutable i = getInsets(); - + // client position -> top-level window position x -= i.getLeftWidth() ; y -= i.getTopHeight() ; - + if(0 top-level window size width += i.getTotalWidth(); @@ -203,9 +203,9 @@ public class WindowDriver extends WindowImpl { } } reconfigureWindow0( getParentWindowHandle(), getWindowHandle(), x, y, width, height, flags); - + if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); + visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); } return true; } @@ -222,7 +222,7 @@ public class WindowDriver extends WindowImpl { @Override protected boolean setPointerVisibleImpl(final boolean pointerVisible) { final boolean[] res = new boolean[] { false }; - + this.runOnEDTIfAvail(true, new Runnable() { public void run() { res[0] = setPointerVisible0(getWindowHandle(), pointerVisible); @@ -234,19 +234,19 @@ public class WindowDriver extends WindowImpl { @Override protected boolean confinePointerImpl(final boolean confine) { final Boolean[] res = new Boolean[] { Boolean.FALSE }; - + this.runOnEDTIfAvail(true, new Runnable() { public void run() { final Point p0 = getLocationOnScreenImpl(0, 0); - res[0] = Boolean.valueOf(confinePointer0(getWindowHandle(), confine, + res[0] = Boolean.valueOf(confinePointer0(getWindowHandle(), confine, p0.getX(), p0.getY(), p0.getX()+getWidth(), p0.getY()+getHeight())); } }); return res[0].booleanValue(); } - + @Override - protected void warpPointerImpl(final int x, final int y) { + protected void warpPointerImpl(final int x, final int y) { this.runOnEDTIfAvail(true, new Runnable() { public void run() { final Point sPos = getLocationOnScreenImpl(x, y); @@ -255,44 +255,44 @@ public class WindowDriver extends WindowImpl { }); return; } - + protected Point getLocationOnScreenImpl(int x, int y) { return GDIUtil.GetRelativeLocation( getWindowHandle(), 0 /*root win*/, x, y); } protected void updateInsetsImpl(Insets insets) { - // nop - using event driven insetsChange(..) + // nop - using event driven insetsChange(..) } - + // // PointerEvent Handling // /** * Send multiple-pointer {@link MouseEvent.PointerType#TouchScreen} event to be directly consumed *

                            - * Assumes non normal pointer names and rotation/scroll will be determined by a gesture handler. + * Assumes non normal pointer names and rotation/scroll will be determined by a gesture handler. *

                            *

                            * See {@link #doPointerEvent(boolean, boolean, PointerType[], short, int, int, boolean, int[], int[], int[], float[], float, float[], float)} * for details. *

                            */ - public final void sendTouchScreenEvent(short eventType, int modifiers, + public final void sendTouchScreenEvent(short eventType, int modifiers, int pActionIdx, int[] pNames, int[] pX, int[] pY, float[] pPressure, float maxPressure) { final int pCount = pNames.length; final MouseEvent.PointerType[] pTypes = new MouseEvent.PointerType[pCount]; for(int i=pCount-1; i>=0; i--) { pTypes[i] = PointerType.TouchScreen; } - doPointerEvent(false /*enqueue*/, false /*wait*/, - pTypes, eventType, modifiers, pActionIdx, false /*normalPNames*/, pNames, + doPointerEvent(false /*enqueue*/, false /*wait*/, + pTypes, eventType, modifiers, pActionIdx, false /*normalPNames*/, pNames, pX, pY, pPressure, maxPressure, new float[] { 0f, 0f, 0f} /*rotationXYZ*/, 1f/*rotationScale*/); } - + // // KeyEvent Handling // private short repeatedKey = KeyEvent.VK_UNDEFINED; - + private final boolean handlePressTypedAutoRepeat(boolean isModifierKey, int modifiers, short keyCode, short keySym, char keyChar) { if( setKeyPressed(keyCode, true) ) { // AR: Key was already pressed: Either [enter | within] AR mode @@ -308,18 +308,18 @@ public class WindowDriver extends WindowImpl { super.sendKeyEvent(KeyEvent.EVENT_KEY_RELEASED, modifiers, keyCode, keySym, keyChar); } return true; - } + } return false; } - + @Override public final void sendKeyEvent(short eventType, int modifiers, short keyCode, short keySym, char keyChar) { final boolean isModifierKey = KeyEvent.isModifierKey(keySym); // System.err.println("*** sendKeyEvent: event "+KeyEvent.getEventTypeString(eventType)+", keyCode "+toHexString(keyCode)+", keyChar <"+keyChar+">, mods "+toHexString(modifiers)+ // ", isKeyCodeTracked "+isKeyCodeTracked(keyCode)+", was: pressed "+isKeyPressed(keyCode)+", printableKey "+KeyEvent.isPrintableKey(keyCode, false)+" [modifierKey "+isModifierKey+"] - "+System.currentTimeMillis()); - + // Reorder: WINDOWS delivery order is PRESSED (t0), TYPED (t0) and RELEASED (t1) -> NEWT order: PRESSED (t0) and RELEASED (t1) - // Auto-Repeat: WINDOWS delivers only PRESSED (t0) and TYPED (t0). + // Auto-Repeat: WINDOWS delivers only PRESSED (t0) and TYPED (t0). switch(eventType) { case KeyEvent.EVENT_KEY_RELEASED: if( isKeyCodeTracked(keyCode) ) { @@ -339,12 +339,12 @@ public class WindowDriver extends WindowImpl { break; } } - + @Override public final void enqueueKeyEvent(boolean wait, short eventType, int modifiers, short keyCode, short keySym, char keyChar) { throw new InternalError("XXX: Adapt Java Code to Native Code Changes"); } - + //---------------------------------------------------------------------- // Internals only // @@ -361,5 +361,5 @@ public class WindowDriver extends WindowImpl { private static native boolean setPointerVisible0(long windowHandle, boolean visible); private static native boolean confinePointer0(long windowHandle, boolean grab, int l, int t, int r, int b); - private static native void warpPointer0(long windowHandle, int x, int y); + private static native void warpPointer0(long windowHandle, int x, int y); } diff --git a/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java index d911483b0..aa8067520 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.x11; @@ -83,7 +83,7 @@ public class DisplayDriver extends DisplayImpl { CompleteDisplay0(aDevice.getHandle()); } catch(RuntimeException e) { closeNativeImpl(aDevice); - throw e; + throw e; } } @@ -114,14 +114,14 @@ public class DisplayDriver extends DisplayImpl { protected long getJavaObjectAtom() { return javaObjectAtom; } protected long getWindowDeleteAtom() { return windowDeleteAtom; } // protected long getKbdHandle() { return kbdHandle; } // XKB disabled for now - - /** Returns null if !{@link #isNativeValid()}, otherwise the Boolean value of {@link X11GraphicsDevice#isXineramaEnabled()}. */ + + /** Returns null if !{@link #isNativeValid()}, otherwise the Boolean value of {@link X11GraphicsDevice#isXineramaEnabled()}. */ protected Boolean isXineramaEnabled() { return isNativeValid() ? Boolean.valueOf(((X11GraphicsDevice)aDevice).isXineramaEnabled()) : null; } - + //---------------------------------------------------------------------- // Internals only // - + private static native boolean initIDs0(boolean debug); private native void CompleteDisplay0(long handle); @@ -137,10 +137,10 @@ public class DisplayDriver extends DisplayImpl { /** X11 Window delete atom marker used on EDT */ private long windowDeleteAtom; - + /** X11 Window java object property used on EDT */ - private long javaObjectAtom; - + private long javaObjectAtom; + /** X11 Keyboard handle used on EDT */ // private long kbdHandle; // XKB disabled for now } diff --git a/src/newt/classes/jogamp/newt/driver/x11/RandR.java b/src/newt/classes/jogamp/newt/driver/x11/RandR.java index e39a6c63a..8b065d1f0 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/RandR.java +++ b/src/newt/classes/jogamp/newt/driver/x11/RandR.java @@ -38,18 +38,18 @@ import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.MonitorMode; public interface RandR { - public static final VersionNumber version110 = new VersionNumber(1, 1, 0); + public static final VersionNumber version110 = new VersionNumber(1, 1, 0); public static final VersionNumber version130 = new VersionNumber(1, 3, 0); public static final VersionNumber version140 = new VersionNumber(1, 4, 0); VersionNumber getVersion(); - + void dumpInfo(final long dpy, final int screen_idx); - + /** - * Encapsulate initial device query allowing caching of internal data structures. + * Encapsulate initial device query allowing caching of internal data structures. * Methods covered: - *
                              + *
                                *
                              • {@link #getMonitorDeviceCount(long, ScreenDriver)}
                              • *
                              • {@link #getAvailableRotations(long, ScreenDriver, int)}
                              • *
                              • {@link #getMonitorModeProps(long, ScreenDriver, int)}
                              • @@ -57,7 +57,7 @@ public interface RandR { *
                              • {@link #getMonitorDeviceProps(long, ScreenDriver, List, int, MonitorMode)}
                              • *
                              *

                              - * Above methods may be called w/o begin/end, in which case no + * Above methods may be called w/o begin/end, in which case no * internal data structures can be cached: *

                              * @param dpy TODO @@ -66,11 +66,11 @@ public interface RandR { */ boolean beginInitialQuery(long dpy, ScreenDriver screen); void endInitialQuery(long dpy, ScreenDriver screen); - + int getMonitorDeviceCount(final long dpy, final ScreenDriver screen); int[] getAvailableRotations(final long dpy, final ScreenDriver screen, final int crt_idx); /** - * + * * @param dpy * @param screen * @param mode_idx w/o indexing rotation @@ -80,7 +80,7 @@ public interface RandR { int[] getMonitorDeviceProps(final long dpy, final ScreenDriver screen, MonitorModeProps.Cache cache, final int crt_idx); int[] getMonitorDeviceViewport(final long dpy, final ScreenDriver screen, final int crt_idx); int[] getCurrentMonitorModeProps(final long dpy, final ScreenDriver screen, final int crt_idx); - boolean setCurrentMonitorMode(final long dpy, final ScreenDriver screen, MonitorDevice monitor, final MonitorMode mode); - - public void updateScreenViewport(final long dpy, final ScreenDriver screen, RectangleImmutable viewport); + boolean setCurrentMonitorMode(final long dpy, final ScreenDriver screen, MonitorDevice monitor, final MonitorMode mode); + + public void updateScreenViewport(final long dpy, final ScreenDriver screen, RectangleImmutable viewport); } diff --git a/src/newt/classes/jogamp/newt/driver/x11/RandR11.java b/src/newt/classes/jogamp/newt/driver/x11/RandR11.java index 877607f72..6c22a3fc6 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/RandR11.java +++ b/src/newt/classes/jogamp/newt/driver/x11/RandR11.java @@ -38,8 +38,8 @@ import com.jogamp.newt.MonitorMode; class RandR11 implements RandR { private static final boolean DEBUG = ScreenDriver.DEBUG; - - RandR11() { + + RandR11() { } @Override @@ -51,13 +51,13 @@ class RandR11 implements RandR { public void dumpInfo(final long dpy, final int screen_idx) { // NOP } - + private int widthMM=0, heightMM=0; private int modeCount = 0; private int resolutionCount = 0; private int[][] nrates = null; // [nres_number][nrate_number] private int[] idx_rate = null, idx_res = null; - + @Override public boolean beginInitialQuery(long dpy, ScreenDriver screen) { // initialize iterators and static data @@ -76,11 +76,11 @@ class RandR11 implements RandR { return false; } } - + for(int nresIdx=0; nresIdx < resolutionCount; nresIdx++) { modeCount += nrates[nresIdx].length; } - + idx_rate = new int[modeCount]; idx_res = new int[modeCount]; @@ -94,23 +94,23 @@ class RandR11 implements RandR { } return true; } - + @Override public void endInitialQuery(long dpy, ScreenDriver screen) { idx_rate=null; - idx_res=null; - nrates=null; + idx_res=null; + nrates=null; } - + @Override public int getMonitorDeviceCount(final long dpy, final ScreenDriver screen) { return 1; } - + @Override public int[] getAvailableRotations(final long dpy, final ScreenDriver screen, final int crt_idx) { if( 0 < crt_idx ) { - // RandR11 only supports 1 CRT + // RandR11 only supports 1 CRT return null; } final int screen_idx = screen.getIndex(); @@ -120,17 +120,17 @@ class RandR11 implements RandR { } return availRotations; } - + @Override public int[] getMonitorModeProps(final long dpy, final ScreenDriver screen, final int mode_idx) { if( mode_idx >= modeCount ) { return null; - } + } final int screen_idx = screen.getIndex(); - + final int nres_index = idx_res[mode_idx]; final int nrate_index = idx_rate[mode_idx]; - + final int[] res = getScreenResolution0(dpy, screen_idx, nres_index); if(null==res || 0==res.length) { return null; @@ -144,7 +144,7 @@ class RandR11 implements RandR { if( res[3] > heightMM ) { heightMM = res[3]; } - + int rate = nrates[nres_index][nrate_index]; if(0>=rate) { rate = ScreenImpl.default_sm_rate; @@ -166,13 +166,13 @@ class RandR11 implements RandR { if( MonitorModeProps.NUM_MONITOR_MODE_PROPERTIES_ALL != i ) { throw new InternalError("XX"); } - return props; + return props; } - + @Override public int[] getMonitorDeviceProps(final long dpy, final ScreenDriver screen, final MonitorModeProps.Cache cache, final int crt_idx) { if( 0 < crt_idx ) { - // RandR11 only supports 1 CRT + // RandR11 only supports 1 CRT return null; } final int[] currentModeProps = getCurrentMonitorModeProps(dpy, screen, crt_idx); @@ -194,15 +194,15 @@ class RandR11 implements RandR { props[i++] = currentMode.getId(); // current mode id props[i++] = currentMode.getRotation(); for(int j=0; jresId || resId>=resolutionCount) { throw new RuntimeException("Invalid resolution index: ! 0 < "+resId+" < "+resolutionCount+", "+monitor+", "+mode); - } + } final int f = (int)mode.getRefreshRate(); // simply cut-off, orig is int final int r = mode.getRotation(); @@ -335,11 +335,11 @@ class RandR11 implements RandR { } return done; } - + @Override public final void updateScreenViewport(final long dpy, final ScreenDriver screen, RectangleImmutable viewport) { // nop - } + } /** @return int[] { rot1, .. } */ private static native int[] getAvailableScreenRotations0(long display, int screen_index); @@ -353,7 +353,7 @@ class RandR11 implements RandR { private static native long getScreenConfiguration0(long display, int screen_index); private static native void freeScreenConfiguration0(long screenConfiguration); - + private static native int getCurrentScreenResolutionIndex0(long screenConfiguration); private static native int getCurrentScreenRate0(long screenConfiguration); private static native int getCurrentScreenRotation0(long screenConfiguration); @@ -361,5 +361,5 @@ class RandR11 implements RandR { /** needs own Display connection for XRANDR event handling */ private static native boolean setCurrentScreenModeStart0(long display, int screen_index, long screenConfiguration, int mode_index, int freq, int rot); private static native boolean setCurrentScreenModePollEnd0(long display, int screen_index, int mode_index, int freq, int rot); - + } diff --git a/src/newt/classes/jogamp/newt/driver/x11/RandR13.java b/src/newt/classes/jogamp/newt/driver/x11/RandR13.java index ac83fc5f2..a08741d9e 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/RandR13.java +++ b/src/newt/classes/jogamp/newt/driver/x11/RandR13.java @@ -43,19 +43,19 @@ import com.jogamp.newt.MonitorMode; *
                                * MonitorMode.id   == XRR mode-id (not index)
                                * MonitorDevice.id == XRR monitor-idx (not id)
                              - * 
                              + *
                            */ class RandR13 implements RandR { private static final boolean DEBUG = ScreenDriver.DEBUG; - - RandR13() { + + RandR13() { } - + @Override public final VersionNumber getVersion() { return version130; } - + @Override public void dumpInfo(final long dpy, final int screen_idx) { long screenResources = getScreenResources0(dpy, screen_idx); @@ -66,12 +66,12 @@ class RandR13 implements RandR { dumpInfo0(dpy, screen_idx, screenResources); } finally { freeScreenResources0(screenResources); - } + } } - + long sessionScreenResources = 0; IntLongHashMap crtInfoHandleMap = null; - + @Override public boolean beginInitialQuery(long dpy, ScreenDriver screen) { final int screen_idx = screen.getIndex(); @@ -84,7 +84,7 @@ class RandR13 implements RandR { return false; } } - + @Override public void endInitialQuery(long dpy, ScreenDriver screen) { if( null != crtInfoHandleMap ) { @@ -100,7 +100,7 @@ class RandR13 implements RandR { sessionScreenResources = 0; } } - + private final long getScreenResourceHandle(final long dpy, final int screen_idx) { if( 0 != sessionScreenResources ) { return sessionScreenResources; @@ -112,7 +112,7 @@ class RandR13 implements RandR { freeScreenResources0( screenResourceHandle ); } } - + private final long getMonitorInfoHandle(final long dpy, final int screen_idx, long screenResources, final int monitor_idx) { if( null != crtInfoHandleMap ) { long h = crtInfoHandleMap.get(monitor_idx); @@ -129,8 +129,8 @@ class RandR13 implements RandR { if( null == crtInfoHandleMap ) { freeMonitorInfoHandle0(monitorInfoHandle); } - } - + } + @Override public int getMonitorDeviceCount(final long dpy, final ScreenDriver screen) { final int screen_idx = screen.getIndex(); @@ -141,7 +141,7 @@ class RandR13 implements RandR { releaseScreenResourceHandle(screenResources); } } - + @Override public int[] getAvailableRotations(final long dpy, final ScreenDriver screen, final int crt_idx) { final int screen_idx = screen.getIndex(); @@ -152,7 +152,7 @@ class RandR13 implements RandR { final int[] availRotations = getAvailableRotations0(monitorInfo); if(null==availRotations || 0==availRotations.length) { return null; - } + } return availRotations; } finally { releaseMonitorInfoHandle(monitorInfo); @@ -161,7 +161,7 @@ class RandR13 implements RandR { releaseScreenResourceHandle(screenResources); } } - + @Override public int[] getMonitorModeProps(final long dpy, final ScreenDriver screen, final int mode_idx) { final int screen_idx = screen.getIndex(); @@ -172,7 +172,7 @@ class RandR13 implements RandR { releaseScreenResourceHandle(screenResources); } } - + @Override public int[] getMonitorDeviceProps(final long dpy, final ScreenDriver screen, MonitorModeProps.Cache cache, final int crt_idx) { final int screen_idx = screen.getIndex(); @@ -188,9 +188,9 @@ class RandR13 implements RandR { releaseScreenResourceHandle(screenResources); } } - + @Override - public int[] getMonitorDeviceViewport(final long dpy, final ScreenDriver screen, final int crt_idx) { + public int[] getMonitorDeviceViewport(final long dpy, final ScreenDriver screen, final int crt_idx) { final int screen_idx = screen.getIndex(); final long screenResources = getScreenResourceHandle(dpy, screen_idx); try { @@ -204,7 +204,7 @@ class RandR13 implements RandR { releaseScreenResourceHandle(screenResources); } } - + @Override public int[] getCurrentMonitorModeProps(final long dpy, final ScreenDriver screen, final int crt_idx) { final int screen_idx = screen.getIndex(); @@ -220,7 +220,7 @@ class RandR13 implements RandR { releaseScreenResourceHandle(screenResources); } } - + @Override public boolean setCurrentMonitorMode(final long dpy, final ScreenDriver screen, MonitorDevice monitor, final MonitorMode mode) { final int screen_idx = screen.getIndex(); @@ -229,7 +229,7 @@ class RandR13 implements RandR { try { final long monitorInfo = getMonitorInfoHandle(dpy, screen_idx, screenResources, monitor.getId()); try { - res = setMonitorMode0(dpy, screenResources, monitorInfo, monitor.getId(), mode.getId(), mode.getRotation(), + res = setMonitorMode0(dpy, screenResources, monitorInfo, monitor.getId(), mode.getId(), mode.getRotation(), -1, -1); // no fixed position! } finally { releaseMonitorInfoHandle(monitorInfo); @@ -239,36 +239,36 @@ class RandR13 implements RandR { } return res; } - + @Override public final void updateScreenViewport(final long dpy, final ScreenDriver screen, final RectangleImmutable viewport) { final int screen_idx = screen.getIndex(); final long screenResources = getScreenResourceHandle(dpy, screen_idx); try { - setScreenViewport0(dpy, screen_idx, screenResources, viewport.getX(), viewport.getY(), viewport.getWidth(), viewport.getHeight()); + setScreenViewport0(dpy, screen_idx, screenResources, viewport.getX(), viewport.getY(), viewport.getWidth(), viewport.getHeight()); } finally { dumpInfo0(dpy, screen_idx, screenResources); releaseScreenResourceHandle(screenResources); } } - + private static native long getScreenResources0(long display, int screen_index); private static native void freeScreenResources0(long screenResources); private static native void dumpInfo0(long display, int screen_index, long screenResources); - + private static native int getMonitorDeviceCount0(long screenResources); - + private static native long getMonitorInfoHandle0(long display, int screen_index, long screenResources, int monitor_index); private static native void freeMonitorInfoHandle0(long monitorInfoHandle); - + private static native int[] getAvailableRotations0(long monitorInfo); private static native int[] getMonitorViewport0(long monitorInfo); private static native int[] getMonitorCurrentMode0(long monitorInfo); - + private static native int[] getMonitorMode0(long screenResources, int mode_index); private static native int[] getMonitorCurrentMode0(long screenResources, long monitorInfo); private static native int[] getMonitorDevice0(long display, long screenResources, long monitorInfo, int monitor_idx); - + private static native boolean setMonitorMode0(long display, long screenResources, long monitorInfo, int monitor_idx, int mode_id, int rotation, int x, int y); private static native boolean setScreenViewport0(long display, int screen_index, long screenResources, int x, int y, int width, int height); } diff --git a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java index c01d899f8..7f75e03f0 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.x11; @@ -54,19 +54,19 @@ import com.jogamp.nativewindow.x11.X11GraphicsScreen; import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.MonitorMode; -public class ScreenDriver extends ScreenImpl { +public class ScreenDriver extends ScreenImpl { protected static final boolean DEBUG_TEST_RANDR13_DISABLED; - + static { Debug.initSingleton(); DEBUG_TEST_RANDR13_DISABLED = Debug.isPropertyDefined("newt.test.Screen.disableRandR13", true); - + DisplayDriver.initSingleton(); } /** Ensure static init has been run. */ /* pp */static void initSingleton() { } - + public ScreenDriver() { } @@ -74,14 +74,14 @@ public class ScreenDriver extends ScreenImpl { protected void createNativeImpl() { // validate screen index Long handle = runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { - public Long run(long dpy) { + public Long run(long dpy) { return new Long(GetScreen0(dpy, screen_idx)); } } ); if (handle.longValue() == 0) { throw new RuntimeException("Error creating screen: " + screen_idx); } - final X11GraphicsDevice x11dev = (X11GraphicsDevice) getDisplay().getGraphicsDevice(); - final long dpy = x11dev.getHandle(); + final X11GraphicsDevice x11dev = (X11GraphicsDevice) getDisplay().getGraphicsDevice(); + final long dpy = x11dev.getHandle(); aScreen = new X11GraphicsScreen(x11dev, screen_idx); { int v[] = getRandRVersion0(dpy); @@ -118,7 +118,7 @@ public class ScreenDriver extends ScreenImpl { if( rAndR.beginInitialQuery(device.getHandle(), this) ) { try { final int crtCount = rAndR.getMonitorDeviceCount(device.getHandle(), this); - + // Gather all available rotations final ArrayHashSet availableRotations = new ArrayHashSet(); for(int i = 0; i < crtCount; i++) { @@ -129,7 +129,7 @@ public class ScreenDriver extends ScreenImpl { availableRotations.addAll(rotationList); } } - + // collect all modes, while injecting all available rotations { int modeIdx = 0; @@ -147,8 +147,8 @@ public class ScreenDriver extends ScreenImpl { if( cache.monitorModes.size() > 0 ) { for(int i = 0; i < crtCount; i++) { final int[] monitorProps = rAndR.getMonitorDeviceProps(device.getHandle(), this, cache, i); - if( null != monitorProps && - MonitorModeProps.MIN_MONITOR_DEVICE_PROPERTIES <= monitorProps[0] && // Enabled ? I.e. contains active modes ? + if( null != monitorProps && + MonitorModeProps.MIN_MONITOR_DEVICE_PROPERTIES <= monitorProps[0] && // Enabled ? I.e. contains active modes ? MonitorModeProps.MIN_MONITOR_DEVICE_PROPERTIES <= monitorProps.length ) { MonitorModeProps.streamInMonitorDevice(null, cache, this, monitorProps, 0); } @@ -174,11 +174,11 @@ public class ScreenDriver extends ScreenImpl { device.unlock(); } } - + @Override protected MonitorMode queryCurrentMonitorModeImpl(final MonitorDevice monitor) { if( null == rAndR ) { return null; } - + return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public MonitorMode run(long dpy) { final int[] currentModeProps = rAndR.getCurrentMonitorModeProps(dpy, ScreenDriver.this, monitor.getId()); @@ -189,14 +189,14 @@ public class ScreenDriver extends ScreenImpl { @Override protected boolean setCurrentMonitorModeImpl(final MonitorDevice monitor, final MonitorMode mode) { if( null == rAndR ) { return false; } - + final long t0 = System.currentTimeMillis(); boolean done = runWithOptTempDisplayHandle( new DisplayImpl.DisplayRunnable() { public Boolean run(long dpy) { return Boolean.valueOf( rAndR.setCurrentMonitorMode(dpy, ScreenDriver.this, monitor, mode) ); - } + } }).booleanValue(); - + if(DEBUG || !done) { System.err.println("X11Screen.setCurrentMonitorModeImpl: TO ("+SCREEN_MODE_CHANGE_TIMEOUT+") reached: "+ (System.currentTimeMillis()-t0)+"ms; "+monitor.getCurrentMode()+" -> "+mode); @@ -205,10 +205,10 @@ public class ScreenDriver extends ScreenImpl { } private DisplayImpl.DisplayRunnable xineramaEnabledQueryWithTemp = new DisplayImpl.DisplayRunnable() { - public Boolean run(long dpy) { - return new Boolean(X11Util.XineramaIsEnabled(dpy)); + public Boolean run(long dpy) { + return new Boolean(X11Util.XineramaIsEnabled(dpy)); } }; - + @Override protected int validateScreenIndex(final int idx) { final DisplayDriver x11Display = (DisplayDriver) getDisplay(); @@ -219,7 +219,7 @@ public class ScreenDriver extends ScreenImpl { return runWithTempDisplayHandle( xineramaEnabledQueryWithTemp ).booleanValue() ? 0 : idx; } } - + @Override protected void calcVirtualScreenOriginAndSize(final Rectangle vOriginSize) { final RectangleImmutable ov = (RectangleImmutable) getViewport().cloneMutable(); @@ -244,17 +244,17 @@ public class ScreenDriver extends ScreenImpl { System.err.println("X11Screen.calcVirtualScreenOriginAndSize: Querying X11: "+ov+" -> "+vOriginSize); } } - } - + } + //---------------------------------------------------------------------- // Internals only - // + // private final T runWithLockedDisplayDevice(DisplayRunnable action) { return display.runWithLockedDisplayDevice(action); } - + private final T runWithTempDisplayHandle(DisplayRunnable action) { - final long displayHandle = X11Util.openDisplay(display.getName()); + final long displayHandle = X11Util.openDisplay(display.getName()); if(0 == displayHandle) { throw new RuntimeException("null device"); } @@ -266,7 +266,7 @@ public class ScreenDriver extends ScreenImpl { } return res; } - + private final T runWithOptTempDisplayHandle(DisplayRunnable action) { if( null != rAndR && rAndR.getVersion().compareTo(RandR.version130) >= 0 ) { return display.runWithLockedDisplayDevice(action); @@ -274,12 +274,12 @@ public class ScreenDriver extends ScreenImpl { return runWithTempDisplayHandle(action); } } - + private static native long GetScreen0(long dpy, int scrn_idx); private static native int getWidth0(long display, int scrn_idx); private static native int getHeight0(long display, int scrn_idx); - + private static native int[] getRandRVersion0(long display); } diff --git a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java index 806dd270c..02f80c0c3 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java @@ -1,22 +1,22 @@ /* * Copyright (c) 2008 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 @@ -29,7 +29,7 @@ * 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. - * + * */ package jogamp.newt.driver.x11; @@ -57,7 +57,7 @@ public class WindowDriver extends WindowImpl { private static final int X11_WHEEL_ONE_DOWN_BUTTON = 5; private static final int X11_WHEEL_TWO_UP_BUTTON = 6; private static final int X11_WHEEL_TWO_DOWN_BUTTON = 7; - + static { ScreenDriver.initSingleton(); } @@ -70,21 +70,21 @@ public class WindowDriver extends WindowImpl { final ScreenDriver screen = (ScreenDriver) getScreen(); final DisplayDriver display = (DisplayDriver) screen.getDisplay(); final AbstractGraphicsDevice edtDevice = display.getGraphicsDevice(); - - // Decoupled X11 Device/Screen allowing X11 display lock-free off-thread rendering + + // Decoupled X11 Device/Screen allowing X11 display lock-free off-thread rendering final long renderDeviceHandle = X11Util.openDisplay(edtDevice.getConnection()); if( 0 == renderDeviceHandle ) { throw new RuntimeException("Error creating display(GfxCfg/Render): "+edtDevice.getConnection()); } renderDevice = new X11GraphicsDevice(renderDeviceHandle, AbstractGraphicsDevice.DEFAULT_UNIT, true /* owner */); final AbstractGraphicsScreen renderScreen = new X11GraphicsScreen(renderDevice, screen.getIndex()); - + final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice(), capsRequested); final AbstractGraphicsConfiguration cfg = factory.chooseGraphicsConfiguration( capsRequested, capsRequested, capabilitiesChooser, renderScreen, VisualIDHolder.VID_UNDEFINED); if(DEBUG_IMPLEMENTATION) { System.err.println("X11Window.createNativeImpl() factory: "+factory+", chosen config: "+cfg); - } + } if (null == cfg) { throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this); } @@ -93,13 +93,13 @@ public class WindowDriver extends WindowImpl { throw new NativeWindowException("Chosen Configuration w/o native visual ID: "+cfg); } setGraphicsConfiguration(cfg); - final int flags = getReconfigureFlags(0, true) & + final int flags = getReconfigureFlags(0, true) & ( FLAG_IS_ALWAYSONTOP | FLAG_IS_UNDECORATED ) ; edtDevice.lock(); - try { + try { setWindowHandle(CreateWindow0(getParentWindowHandle(), - edtDevice.getHandle(), screen.getIndex(), visualID, - display.getJavaObjectAtom(), display.getWindowDeleteAtom(), + edtDevice.getHandle(), screen.getIndex(), visualID, + display.getJavaObjectAtom(), display.getWindowDeleteAtom(), getX(), getY(), getWidth(), getHeight(), autoPosition(), flags)); } finally { edtDevice.unlock(); @@ -117,10 +117,10 @@ public class WindowDriver extends WindowImpl { final AbstractGraphicsDevice edtDevice = display.getGraphicsDevice(); edtDevice.lock(); try { - CloseWindow0(edtDevice.getHandle(), windowHandleClose, + CloseWindow0(edtDevice.getHandle(), windowHandleClose, display.getJavaObjectAtom(), display.getWindowDeleteAtom() /* , display.getKbdHandle() */); // XKB disabled for now } catch (Throwable t) { - if(DEBUG_IMPLEMENTATION) { + if(DEBUG_IMPLEMENTATION) { Exception e = new Exception("Warning: closeNativeImpl failed - "+Thread.currentThread().getName(), t); e.printStackTrace(); } @@ -135,7 +135,7 @@ public class WindowDriver extends WindowImpl { } } - /** + /** *

                            * X11 Window supports {@link #FLAG_IS_FULLSCREEN_SPAN} *

                            @@ -145,7 +145,7 @@ public class WindowDriver extends WindowImpl { protected boolean isReconfigureFlagSupported(int changeFlags) { return true; // all flags! } - + @Override protected boolean reconfigureWindowImpl(final int x, final int y, final int width, final int height, int flags) { if(DEBUG_IMPLEMENTATION) { @@ -153,8 +153,8 @@ public class WindowDriver extends WindowImpl { } final int _x, _y; if(0 == ( FLAG_IS_UNDECORATED & flags)) { - final InsetsImmutable i = getInsets(); - + final InsetsImmutable i = getInsets(); + // client position -> top-level window position _x = x - i.getLeftWidth() ; _y = y - i.getTopHeight() ; @@ -177,7 +177,7 @@ public class WindowDriver extends WindowImpl { final DisplayDriver display = (DisplayDriver) getScreen().getDisplay(); runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public Object run(long dpy) { - reconfigureWindow0( dpy, getScreenIndex(), + reconfigureWindow0( dpy, getScreenIndex(), getParentWindowHandle(), getWindowHandle(), display.getWindowDeleteAtom(), _x, _y, width, height, fflags); return null; @@ -205,23 +205,23 @@ public class WindowDriver extends WindowImpl { public Object run(long dpy) { reconfigureWindow0( dpy, getScreenIndex(), getParentWindowHandle(), getWindowHandle(), display.getWindowDeleteAtom(), - getX(), getY(), getWidth(), getHeight(), flags); + getX(), getY(), getWidth(), getHeight(), flags); return null; } }); } super.focusChanged(defer, focusGained); } - + protected void reparentNotify(long newParentWindowHandle) { if(DEBUG_IMPLEMENTATION) { final long p0 = getParentWindowHandle(); System.err.println("Window.reparentNotify ("+getThreadName()+"): "+toHexString(p0)+" -> "+toHexString(newParentWindowHandle)); } } - + @Override - protected void requestFocusImpl(final boolean force) { + protected void requestFocusImpl(final boolean force) { runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { public Object run(long dpy) { requestFocus0(dpy, getWindowHandle(), force); @@ -239,7 +239,7 @@ public class WindowDriver extends WindowImpl { } }); } - + @Override protected boolean setPointerVisibleImpl(final boolean pointerVisible) { return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { @@ -257,7 +257,7 @@ public class WindowDriver extends WindowImpl { } }).booleanValue(); } - + @Override protected void warpPointerImpl(final int x, final int y) { runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { @@ -267,7 +267,7 @@ public class WindowDriver extends WindowImpl { } }); } - + @Override protected Point getLocationOnScreenImpl(final int x, final int y) { return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { @@ -279,9 +279,9 @@ public class WindowDriver extends WindowImpl { @Override protected void updateInsetsImpl(Insets insets) { - // nop - using event driven insetsChange(..) + // nop - using event driven insetsChange(..) } - + @Override protected final void doMouseEvent(boolean enqueue, boolean wait, short eventType, int modifiers, int x, int y, short button, float[] rotationXYZ, float rotationScale) { @@ -321,34 +321,34 @@ public class WindowDriver extends WindowImpl { rotationXYZ[0] = -1; modifiers |= InputEvent.SHIFT_MASK; break; - } + } break; } super.doMouseEvent(enqueue, wait, eventType, modifiers, x, y, button, rotationXYZ, rotationScale); } - + /** Called by native TK */ protected final void sendKeyEvent(short eventType, int modifiers, short keyCode, short keySym, char keyChar0, String keyString) { // handleKeyEvent(true, false, eventType, modifiers, keyCode, keyChar); final boolean isModifierKey = KeyEvent.isModifierKey(keyCode); final boolean isAutoRepeat = 0 != ( KeyEvent.AUTOREPEAT_MASK & modifiers ); - final char keyChar = ( null != keyString ) ? keyString.charAt(0) : keyChar0; + final char keyChar = ( null != keyString ) ? keyString.charAt(0) : keyChar0; // System.err.println("*** sendKeyEvent: event "+KeyEvent.getEventTypeString(eventType)+", keyCode "+toHexString(keyCode)+", keyChar <"+keyChar0+">/<"+keyChar+">, keyString "+keyString+", mods "+toHexString(modifiers)+ // ", isKeyCodeTracked "+isKeyCodeTracked(keyCode)+", was: pressed "+isKeyPressed(keyCode)+", repeat "+isAutoRepeat+", [modifierKey "+isModifierKey+"] - "+System.currentTimeMillis()); - + if( !isAutoRepeat || !isModifierKey ) { // ! ( isModifierKey && isAutoRepeat ) switch(eventType) { case KeyEvent.EVENT_KEY_PRESSED: super.sendKeyEvent(KeyEvent.EVENT_KEY_PRESSED, modifiers, keyCode, keySym, keyChar); break; - + case KeyEvent.EVENT_KEY_RELEASED: super.sendKeyEvent(KeyEvent.EVENT_KEY_RELEASED, modifiers, keyCode, keySym, keyChar); break; } } } - + @Override public final void sendKeyEvent(short eventType, int modifiers, short keyCode, short keySym, char keyChar) { throw new InternalError("XXX: Adapt Java Code to Native Code Changes"); @@ -357,33 +357,33 @@ public class WindowDriver extends WindowImpl { public final void enqueueKeyEvent(boolean wait, short eventType, int modifiers, short keyCode, short keySym, char keyChar) { throw new InternalError("XXX: Adapt Java Code to Native Code Changes"); } - + //---------------------------------------------------------------------- // Internals only // private static final String getCurrentThreadName() { return Thread.currentThread().getName(); } // Callback for JNI private static final void dumpStack() { Thread.dumpStack(); } // Callback for JNI - + private final T runWithLockedDisplayDevice(DisplayRunnable action) { return ((DisplayDriver) getScreen().getDisplay()).runWithLockedDisplayDevice(action); } protected static native boolean initIDs0(); - - private native long CreateWindow0(long parentWindowHandle, long display, int screen_index, - int visualID, long javaObjectAtom, long windowDeleteAtom, - int x, int y, int width, int height, boolean autoPosition, int flags); + + private native long CreateWindow0(long parentWindowHandle, long display, int screen_index, + int visualID, long javaObjectAtom, long windowDeleteAtom, + int x, int y, int width, int height, boolean autoPosition, int flags); private native void CloseWindow0(long display, long windowHandle, long javaObjectAtom, long windowDeleteAtom /*, long kbdHandle*/ ); // XKB disabled for now private native void reconfigureWindow0(long display, int screen_index, long parentWindowHandle, long windowHandle, - long windowDeleteAtom, int x, int y, int width, int height, int flags); + long windowDeleteAtom, int x, int y, int width, int height, int flags); private native void requestFocus0(long display, long windowHandle, boolean force); - + private static native void setTitle0(long display, long windowHandle, String title); private static native long getParentWindow0(long display, long windowHandle); private static native boolean setPointerVisible0(long display, long windowHandle, boolean visible); private static native boolean confinePointer0(long display, long windowHandle, boolean grab); private static native void warpPointer0(long display, long windowHandle, int x, int y); - + private long windowHandleClose; private X11GraphicsDevice renderDevice; } diff --git a/src/newt/classes/jogamp/newt/event/NEWTEventTask.java b/src/newt/classes/jogamp/newt/event/NEWTEventTask.java index 93d5e2fb9..38a434279 100644 --- a/src/newt/classes/jogamp/newt/event/NEWTEventTask.java +++ b/src/newt/classes/jogamp/newt/event/NEWTEventTask.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.newt.event; import com.jogamp.newt.event.NEWTEvent; diff --git a/src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java b/src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java index 6024195e3..08eacdee5 100644 --- a/src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java +++ b/src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java @@ -40,16 +40,16 @@ import com.jogamp.newt.util.EDTUtil; */ public class SWTEDTUtil implements EDTUtil { public static final boolean DEBUG = Debug.debug("EDT"); - + private final Object edtLock = new Object(); // locking the EDT start/stop state - private final ThreadGroup threadGroup; + private final ThreadGroup threadGroup; private final String name; private final Runnable dispatchMessages; private final org.eclipse.swt.widgets.Display swtDisplay; private NEDT nedt = null; private int start_iter=0; private static long pollPeriod = EDTUtil.defaultEDTPollPeriod; - + public SWTEDTUtil(final com.jogamp.newt.Display newtDisplay, org.eclipse.swt.widgets.Display swtDisplay) { this.threadGroup = Thread.currentThread().getThreadGroup(); this.name=Thread.currentThread().getName()+"-SWTDisplay-"+newtDisplay.getFQName()+"-EDT-"; @@ -61,11 +61,11 @@ public class SWTEDTUtil implements EDTUtil { this.nedt = new NEDT(threadGroup, name); this.nedt.setDaemon(true); // don't stop JVM from shutdown .. } - + public final org.eclipse.swt.widgets.Display getDisplay() { return swtDisplay; } - + @Override public long getPollPeriod() { return pollPeriod; @@ -116,7 +116,7 @@ public class SWTEDTUtil implements EDTUtil { } nedt.start(); } - + @Override public boolean isCurrentThreadEDT() { return !swtDisplay.isDisposed() && swtDisplay.getThread() == Thread.currentThread(); @@ -126,18 +126,18 @@ public class SWTEDTUtil implements EDTUtil { public final boolean isCurrentThreadNEDT() { return nedt == Thread.currentThread(); } - + @Override public final boolean isCurrentThreadEDTorNEDT() { final Thread ct = Thread.currentThread(); return ( !swtDisplay.isDisposed() && ct == swtDisplay.getThread() ) || ct == nedt ; } - + @Override public boolean isRunning() { return nedt.isRunning(); } - + @Override public final boolean invokeStop(boolean wait, Runnable task) { return invokeImpl(wait, task, true); @@ -147,12 +147,12 @@ public class SWTEDTUtil implements EDTUtil { public final boolean invoke(boolean wait, Runnable task) { return invokeImpl(wait, task, false); } - + private static Runnable nullTask = new Runnable() { @Override - public void run() { } + public void run() { } }; - + private final boolean invokeImpl(boolean wait, Runnable task, boolean stop) { Throwable throwable = null; RunnableTask rTask = null; @@ -165,12 +165,12 @@ public class SWTEDTUtil implements EDTUtil { System.err.println(Thread.currentThread()+": Warning: SWT-EDT about (1) to stop, won't enqueue new task: "+nedt+", isRunning "+nedt.isRunning+", shouldStop "+nedt.shouldStop); Thread.dumpStack(); } - return false; + return false; } if( swtDisplay.isDisposed() ) { stop = true; } - + if( isCurrentThreadEDT() ) { if(null != task) { task.run(); @@ -179,7 +179,7 @@ public class SWTEDTUtil implements EDTUtil { if( stop ) { nedt.shouldStop = true; } - } else { + } else { if( !nedt.isRunning && !swtDisplay.isDisposed() ) { if( null != task ) { if( stop ) { @@ -210,11 +210,11 @@ public class SWTEDTUtil implements EDTUtil { return false; } } - + if( null != task ) { rTask = new RunnableTask(task, wait ? rTaskLock : null, - true /* always catch and report Exceptions, don't disturb EDT */, + true /* always catch and report Exceptions, don't disturb EDT */, wait ? null : System.err); swtDisplay.asyncExec(rTask); } @@ -238,7 +238,7 @@ public class SWTEDTUtil implements EDTUtil { } return true; } - } + } @Override final public boolean waitUntilIdle() { @@ -278,7 +278,7 @@ public class SWTEDTUtil implements EDTUtil { } } } - + class NEDT extends Thread { volatile boolean shouldStop = false; volatile boolean isRunning = false; @@ -298,7 +298,7 @@ public class SWTEDTUtil implements EDTUtil { super.start(); } - /** + /** * Utilizing locking only on tasks and its execution, * not for event dispatching. */ @@ -315,7 +315,7 @@ public class SWTEDTUtil implements EDTUtil { // EDT invoke thread is SWT-EDT, // hence dispatching is required to run on SWT-EDT as well. // Otherwise a deadlock may happen due to dispatched event's - // triggering a locking action. + // triggering a locking action. if ( !swtDisplay.isDisposed() ) { swtDisplay.syncExec(dispatchMessages); } else { @@ -343,7 +343,7 @@ public class SWTEDTUtil implements EDTUtil { } } finally { if(DEBUG) { - System.err.println(getName()+": SWT-EDT run() END "+ getName()+", "+error); + System.err.println(getName()+": SWT-EDT run() END "+ getName()+", "+error); } synchronized(edtLock) { isRunning = false; @@ -358,5 +358,5 @@ public class SWTEDTUtil implements EDTUtil { } // finally } // run() } // EventDispatchThread - + } diff --git a/src/newt/classes/jogamp/newt/swt/event/SWTNewtEventFactory.java b/src/newt/classes/jogamp/newt/swt/event/SWTNewtEventFactory.java index 3782a1186..b5c45c1aa 100644 --- a/src/newt/classes/jogamp/newt/swt/event/SWTNewtEventFactory.java +++ b/src/newt/classes/jogamp/newt/swt/event/SWTNewtEventFactory.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package jogamp.newt.swt.event; import org.eclipse.swt.SWT; @@ -206,7 +206,7 @@ public class SWTNewtEventFactory { } return res; } - + public static final com.jogamp.newt.event.MouseEvent createMouseEvent(org.eclipse.swt.widgets.Event event, Object source) { switch(event.type) { case SWT.MouseDown: @@ -229,7 +229,7 @@ public class SWTNewtEventFactory { } int mods = swtModifiers2Newt(event.stateMask, true); - + if( source instanceof com.jogamp.newt.Window) { final com.jogamp.newt.Window newtSource = (com.jogamp.newt.Window)source; if(newtSource.isPointerConfined()) { @@ -239,7 +239,7 @@ public class SWTNewtEventFactory { mods |= InputEvent.INVISIBLE_MASK; } } - + return new com.jogamp.newt.event.MouseEvent( type, (null==source)?(Object)event.data:source, (0xFFFFFFFFL & (long)event.time), mods, event.x, event.y, (short)event.count, (short)event.button, MouseEvent.getRotationXYZ(rotation, mods), 1f); @@ -260,32 +260,32 @@ public class SWTNewtEventFactory { final short newtKeyCode = swtKeyCode2NewtKeyCode( event.keyCode ); return com.jogamp.newt.event.KeyEvent.create( type, (null==source)?(Object)event.data:source, (0xFFFFFFFFL & (long)event.time), - swtModifiers2Newt(event.stateMask, false), + swtModifiers2Newt(event.stateMask, false), newtKeyCode, newtKeyCode, event.character); } return null; // no mapping .. } - + // // // - + short dragButtonDown = 0; - + public SWTNewtEventFactory() { resetButtonsDown(); } - + final void resetButtonsDown() { dragButtonDown = 0; } - + public final boolean dispatchMouseEvent(org.eclipse.swt.widgets.Event event, Object source, com.jogamp.newt.event.MouseListener l) { com.jogamp.newt.event.MouseEvent res = createMouseEvent(event, source); if(null != res) { if(null != l) { switch(event.type) { - case SWT.MouseDown: + case SWT.MouseDown: dragButtonDown = (short) event.button; l.mousePressed(res); break; case SWT.MouseUp: @@ -293,7 +293,7 @@ public class SWTNewtEventFactory { l.mouseReleased(res); { final com.jogamp.newt.event.MouseEvent res2 = new com.jogamp.newt.event.MouseEvent( - com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_CLICKED, + com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_CLICKED, res.getSource(), res.getWhen(), res.getModifiers(), res.getX(), res.getY(), res.getClickCount(), @@ -304,7 +304,7 @@ public class SWTNewtEventFactory { case SWT.MouseMove: if( 0 < dragButtonDown ) { final com.jogamp.newt.event.MouseEvent res2 = new com.jogamp.newt.event.MouseEvent( - com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_DRAGGED, + com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_DRAGGED, res.getSource(), res.getWhen(), res.getModifiers(), res.getX(), res.getY(), res.getClickCount(), @@ -315,14 +315,14 @@ public class SWTNewtEventFactory { } break; case SWT.MouseEnter: - l.mouseEntered(res); + l.mouseEntered(res); break; case SWT.MouseExit: resetButtonsDown(); - l.mouseExited(res); + l.mouseExited(res); break; case SWT.MouseVerticalWheel: - l.mouseWheelMoved(res); + l.mouseWheelMoved(res); break; } } @@ -337,7 +337,7 @@ public class SWTNewtEventFactory { if(null != l) { switch(event.type) { case SWT.KeyDown: - l.keyPressed(res); + l.keyPressed(res); break; case SWT.KeyUp: l.keyReleased(res); @@ -347,9 +347,9 @@ public class SWTNewtEventFactory { return true; } return false; - } - - public final void attachDispatchListener(final org.eclipse.swt.widgets.Control ctrl, final Object source, + } + + public final void attachDispatchListener(final org.eclipse.swt.widgets.Control ctrl, final Object source, final com.jogamp.newt.event.MouseListener ml, final com.jogamp.newt.event.KeyListener kl) { final Listener listener = new Listener () { -- cgit v1.2.3 From f1ae8ddb87c88a57dce4593f006881ef6a7f0932 Mon Sep 17 00:00:00 2001 From: Harvey Harrison Date: Thu, 17 Oct 2013 22:51:47 -0700 Subject: jogl: add missing @Override annotations Signed-off-by: Harvey Harrison --- .../com/jogamp/audio/windows/waveout/Mixer.java | 2 ++ .../com/jogamp/audio/windows/waveout/Vec3f.java | 1 + .../gluegen/opengl/BuildComposablePipeline.java | 31 +++++++++++++++++ .../com/jogamp/gluegen/opengl/GLEmitter.java | 3 ++ .../jogamp/gluegen/opengl/ant/StaticGLGenTask.java | 1 + .../NativeSignatureJavaMethodBindingEmitter.java | 6 ++++ .../runtime/opengl/GLProcAddressResolver.java | 1 + .../com/jogamp/graph/curve/OutlineShape.java | 3 ++ .../com/jogamp/graph/curve/opengl/RenderState.java | 1 + src/jogl/classes/com/jogamp/graph/font/Font.java | 1 + .../classes/com/jogamp/graph/geom/Outline.java | 3 ++ .../classes/com/jogamp/graph/geom/Triangle.java | 1 + src/jogl/classes/com/jogamp/graph/geom/Vertex.java | 1 + .../com/jogamp/graph/geom/opengl/SVertex.java | 21 ++++++++++++ src/jogl/classes/com/jogamp/opengl/FBObject.java | 4 +++ .../com/jogamp/opengl/GLRendererQuirks.java | 1 + .../opengl/cg/CgDynamicLibraryBundleInfo.java | 1 + .../com/jogamp/opengl/math/geom/AABBox.java | 3 ++ .../classes/com/jogamp/opengl/swt/GLCanvas.java | 1 + .../com/jogamp/opengl/util/AWTAnimatorImpl.java | 3 ++ .../classes/com/jogamp/opengl/util/Animator.java | 13 ++++++++ .../com/jogamp/opengl/util/AnimatorBase.java | 4 +++ .../jogamp/opengl/util/DefaultAnimatorImpl.java | 2 ++ .../com/jogamp/opengl/util/FPSAnimator.java | 14 ++++++++ .../com/jogamp/opengl/util/GLArrayDataClient.java | 1 + .../jogamp/opengl/util/GLArrayDataEditable.java | 1 + .../com/jogamp/opengl/util/GLArrayDataServer.java | 5 +++ .../com/jogamp/opengl/util/GLPixelBuffer.java | 2 ++ .../com/jogamp/opengl/util/ImmModeSink.java | 2 ++ .../classes/com/jogamp/opengl/util/PMVMatrix.java | 1 + .../com/jogamp/opengl/util/TileRendererBase.java | 1 + .../classes/com/jogamp/opengl/util/TimeFrameI.java | 1 + .../com/jogamp/opengl/util/av/AudioSink.java | 3 ++ .../com/jogamp/opengl/util/av/GLMediaPlayer.java | 1 + .../jogamp/opengl/util/awt/AWTGLPixelBuffer.java | 4 +++ .../com/jogamp/opengl/util/awt/TextRenderer.java | 32 ++++++++++++++++++ .../com/jogamp/opengl/util/glsl/ShaderCode.java | 3 ++ .../com/jogamp/opengl/util/glsl/ShaderProgram.java | 3 ++ .../jogamp/opengl/util/glsl/sdk/CompileShader.java | 1 + .../opengl/util/glsl/sdk/CompileShaderNVidia.java | 4 +++ .../com/jogamp/opengl/util/packrect/Level.java | 2 ++ .../com/jogamp/opengl/util/packrect/Rect.java | 1 + .../opengl/util/packrect/RectanglePacker.java | 2 ++ .../com/jogamp/opengl/util/texture/Texture.java | 1 + .../jogamp/opengl/util/texture/TextureCoords.java | 1 + .../jogamp/opengl/util/texture/TextureData.java | 1 + .../com/jogamp/opengl/util/texture/TextureIO.java | 14 ++++++++ .../opengl/util/texture/TextureSequence.java | 1 + .../jogamp/opengl/util/texture/TextureState.java | 1 + .../jogamp/opengl/util/texture/spi/JPEGImage.java | 2 ++ .../opengl/util/texture/spi/LEDataInputStream.java | 18 ++++++++++ .../util/texture/spi/LEDataOutputStream.java | 15 +++++++++ .../util/texture/spi/NetPbmTextureWriter.java | 1 + .../jogamp/opengl/util/texture/spi/PNGImage.java | 1 + .../jogamp/opengl/util/texture/spi/SGIImage.java | 2 ++ .../jogamp/opengl/util/texture/spi/TGAImage.java | 1 + .../util/texture/spi/awt/IIOTextureProvider.java | 3 ++ .../util/texture/spi/awt/IIOTextureWriter.java | 1 + .../classes/javax/media/opengl/GLArrayData.java | 1 + .../classes/javax/media/opengl/GLDebugMessage.java | 1 + .../javax/media/opengl/GLDrawableFactory.java | 1 + src/jogl/classes/javax/media/opengl/GLProfile.java | 5 +++ .../classes/javax/media/opengl/GLUniformData.java | 1 + .../classes/javax/media/opengl/awt/GLCanvas.java | 10 ++++-- .../opengl/glu/GLUtessellatorCallbackAdapter.java | 12 +++++++ .../graph/curve/opengl/RegionRendererImpl01.java | 1 + .../jogamp/graph/curve/opengl/RenderStateImpl.java | 3 ++ .../jogamp/graph/curve/opengl/VBORegion2PES2.java | 3 ++ .../jogamp/graph/curve/opengl/VBORegionSPES2.java | 3 ++ .../jogamp/graph/curve/tess/CDTriangulator2D.java | 3 ++ .../classes/jogamp/graph/font/JavaFontLoader.java | 3 ++ .../jogamp/graph/font/UbuntuFontLoader.java | 2 ++ .../jogamp/graph/font/typecast/TypecastFont.java | 14 ++++++++ .../font/typecast/TypecastFontConstructor.java | 4 +++ .../jogamp/graph/font/typecast/TypecastGlyph.java | 8 +++++ .../graph/font/typecast/TypecastHMetrics.java | 6 ++++ .../jogamp/graph/font/typecast/ot/OTFont.java | 1 + .../graph/font/typecast/ot/table/BaseTable.java | 13 ++++++++ .../graph/font/typecast/ot/table/CffTable.java | 14 ++++++++ .../font/typecast/ot/table/CharstringType2.java | 3 ++ .../font/typecast/ot/table/ClassDefFormat1.java | 1 + .../font/typecast/ot/table/ClassDefFormat2.java | 1 + .../graph/font/typecast/ot/table/CmapFormat.java | 1 + .../graph/font/typecast/ot/table/CmapFormat0.java | 3 ++ .../graph/font/typecast/ot/table/CmapFormat2.java | 3 ++ .../graph/font/typecast/ot/table/CmapFormat4.java | 4 +++ .../graph/font/typecast/ot/table/CmapFormat6.java | 3 ++ .../font/typecast/ot/table/CmapFormatUnknown.java | 3 ++ .../font/typecast/ot/table/CmapIndexEntry.java | 2 ++ .../graph/font/typecast/ot/table/CmapTable.java | 3 ++ .../font/typecast/ot/table/CoverageFormat1.java | 2 ++ .../font/typecast/ot/table/CoverageFormat2.java | 2 ++ .../graph/font/typecast/ot/table/CvtTable.java | 3 ++ .../font/typecast/ot/table/DirectoryEntry.java | 2 ++ .../graph/font/typecast/ot/table/DsigTable.java | 3 ++ .../graph/font/typecast/ot/table/FpgmTable.java | 3 ++ .../graph/font/typecast/ot/table/GaspRange.java | 1 + .../graph/font/typecast/ot/table/GaspTable.java | 3 ++ .../typecast/ot/table/GlyfCompositeDescript.java | 7 ++++ .../graph/font/typecast/ot/table/GlyfDescript.java | 6 ++++ .../font/typecast/ot/table/GlyfSimpleDescript.java | 8 +++++ .../graph/font/typecast/ot/table/GlyfTable.java | 2 ++ .../graph/font/typecast/ot/table/GposTable.java | 3 ++ .../graph/font/typecast/ot/table/GsubTable.java | 4 +++ .../graph/font/typecast/ot/table/HdmxTable.java | 3 ++ .../graph/font/typecast/ot/table/HeadTable.java | 3 ++ .../graph/font/typecast/ot/table/HheaTable.java | 3 ++ .../graph/font/typecast/ot/table/HmtxTable.java | 3 ++ .../typecast/ot/table/KernSubtableFormat0.java | 2 ++ .../typecast/ot/table/KernSubtableFormat2.java | 2 ++ .../graph/font/typecast/ot/table/KernTable.java | 2 ++ .../typecast/ot/table/LigatureSubstFormat1.java | 1 + .../graph/font/typecast/ot/table/LocaTable.java | 3 ++ .../graph/font/typecast/ot/table/LtshTable.java | 3 ++ .../graph/font/typecast/ot/table/MaxpTable.java | 3 ++ .../graph/font/typecast/ot/table/NameRecord.java | 1 + .../graph/font/typecast/ot/table/NameTable.java | 2 ++ .../graph/font/typecast/ot/table/Os2Table.java | 3 ++ .../graph/font/typecast/ot/table/Panose.java | 1 + .../graph/font/typecast/ot/table/PcltTable.java | 3 ++ .../graph/font/typecast/ot/table/PostTable.java | 3 ++ .../graph/font/typecast/ot/table/PrepTable.java | 3 ++ .../font/typecast/ot/table/SignatureBlock.java | 1 + .../font/typecast/ot/table/SingleSubstFormat1.java | 3 ++ .../font/typecast/ot/table/SingleSubstFormat2.java | 3 ++ .../font/typecast/ot/table/TableDirectory.java | 1 + .../graph/font/typecast/ot/table/VdmxTable.java | 3 ++ .../graph/font/typecast/ot/table/VheaTable.java | 3 ++ .../graph/font/typecast/ot/table/VmtxTable.java | 3 ++ .../graph/font/typecast/tt/engine/Parser.java | 1 + .../classes/jogamp/graph/geom/plane/Path2D.java | 5 +++ src/jogl/classes/jogamp/opengl/Debug.java | 1 + .../opengl/DesktopGLDynamicLookupHelper.java | 1 + src/jogl/classes/jogamp/opengl/FPSCounterImpl.java | 11 ++++++ src/jogl/classes/jogamp/opengl/GLContextImpl.java | 1 + .../jogamp/opengl/GLDebugMessageHandler.java | 2 ++ .../classes/jogamp/opengl/GLDrawableHelper.java | 4 ++- .../jogamp/opengl/GLDynamicLibraryBundleInfo.java | 1 + .../jogamp/opengl/GLOffscreenAutoDrawableImpl.java | 1 + src/jogl/classes/jogamp/opengl/GLRunnableTask.java | 1 + src/jogl/classes/jogamp/opengl/GLWorkerThread.java | 1 + src/jogl/classes/jogamp/opengl/MemoryObject.java | 2 ++ .../jogamp/opengl/SharedResourceRunner.java | 1 + src/jogl/classes/jogamp/opengl/ThreadingImpl.java | 1 + .../jogamp/opengl/awt/AWTThreadingPlugin.java | 3 ++ .../classes/jogamp/opengl/awt/AWTTilePainter.java | 1 + src/jogl/classes/jogamp/opengl/awt/Java2D.java | 3 ++ .../classes/jogamp/opengl/awt/VersionApplet.java | 9 +++++ .../egl/DesktopES2DynamicLibraryBundleInfo.java | 5 +++ .../classes/jogamp/opengl/egl/EGLDisplayUtil.java | 3 ++ .../classes/jogamp/opengl/egl/EGLDrawable.java | 1 + .../opengl/egl/EGLES1DynamicLibraryBundleInfo.java | 1 + .../opengl/egl/EGLES2DynamicLibraryBundleInfo.java | 1 + .../egl/EGLGraphicsConfigurationFactory.java | 1 + .../jogamp/opengl/egl/EGLUpstreamSurfaceHook.java | 1 + .../classes/jogamp/opengl/glu/GLUquadricImpl.java | 6 ++++ .../opengl/glu/gl2/nurbs/GL2CurveEvaluator.java | 6 ++++ .../opengl/glu/gl2/nurbs/GL2SurfaceEvaluator.java | 8 +++++ .../jogamp/opengl/glu/mipmap/Extract1010102.java | 2 ++ .../jogamp/opengl/glu/mipmap/Extract1555rev.java | 2 ++ .../opengl/glu/mipmap/Extract2101010rev.java | 2 ++ .../jogamp/opengl/glu/mipmap/Extract233rev.java | 2 ++ .../jogamp/opengl/glu/mipmap/Extract332.java | 2 ++ .../jogamp/opengl/glu/mipmap/Extract4444.java | 2 ++ .../jogamp/opengl/glu/mipmap/Extract4444rev.java | 2 ++ .../jogamp/opengl/glu/mipmap/Extract5551.java | 2 ++ .../jogamp/opengl/glu/mipmap/Extract565.java | 2 ++ .../jogamp/opengl/glu/mipmap/Extract565rev.java | 2 ++ .../jogamp/opengl/glu/mipmap/Extract8888.java | 2 ++ .../jogamp/opengl/glu/mipmap/Extract8888rev.java | 2 ++ .../jogamp/opengl/glu/mipmap/ExtractFloat.java | 2 ++ .../jogamp/opengl/glu/mipmap/ExtractSByte.java | 2 ++ .../jogamp/opengl/glu/mipmap/ExtractSInt.java | 2 ++ .../jogamp/opengl/glu/mipmap/ExtractSShort.java | 2 ++ .../jogamp/opengl/glu/mipmap/ExtractUByte.java | 2 ++ .../jogamp/opengl/glu/mipmap/ExtractUInt.java | 2 ++ .../jogamp/opengl/glu/mipmap/ExtractUShort.java | 2 ++ .../opengl/glu/tessellator/PriorityQHeap.java | 7 ++++ .../opengl/glu/tessellator/PriorityQSort.java | 7 ++++ .../jogamp/opengl/glu/tessellator/Render.java | 3 ++ .../jogamp/opengl/glu/tessellator/Sweep.java | 2 ++ .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java | 1 + .../macosx/cgl/MacOSXCGLDrawableFactory.java | 1 + .../macosx/cgl/MacOSXCGLGraphicsConfiguration.java | 1 + .../cgl/MacOSXCGLGraphicsConfigurationFactory.java | 1 + .../MacOSXAWTCGLGraphicsConfigurationFactory.java | 1 + .../opengl/util/GLArrayHandlerInterleaved.java | 3 ++ .../jogamp/opengl/util/GLDataArrayHandler.java | 3 ++ .../jogamp/opengl/util/GLFixedArrayHandler.java | 3 ++ .../opengl/util/GLFixedArrayHandlerFlat.java | 3 ++ .../jogamp/opengl/util/GLVBOArrayHandler.java | 1 + .../jogamp/opengl/util/av/EGLMediaPlayerImpl.java | 1 + .../jogamp/opengl/util/av/GLMediaPlayerImpl.java | 5 +++ .../av/impl/FFMPEGDynamicLibraryBundleInfo.java | 2 ++ .../opengl/util/av/impl/FFMPEGMediaPlayer.java | 1 + .../jogamp/opengl/util/glsl/GLSLArrayHandler.java | 3 ++ .../opengl/util/glsl/GLSLArrayHandlerFlat.java | 3 ++ .../util/glsl/GLSLArrayHandlerInterleaved.java | 3 ++ .../opengl/util/glsl/fixedfunc/FixedFuncHook.java | 39 ++++++++++++++++++++++ .../util/glsl/fixedfunc/FixedFuncPipeline.java | 1 + .../jogamp/opengl/util/jpeg/JPEGDecoder.java | 12 +++++++ .../classes/jogamp/opengl/util/pngj/ImageLine.java | 1 + .../jogamp/opengl/util/pngj/ImageLineHelper.java | 1 + .../jogamp/opengl/util/pngj/PngHelperInternal.java | 1 + .../classes/jogamp/opengl/util/pngj/PngReader.java | 1 + .../opengl/util/pngj/chunks/ChunkHelper.java | 2 ++ .../jogamp/opengl/util/pngj/chunks/ChunkRaw.java | 1 + .../jogamp/opengl/util/pngj/chunks/ChunksList.java | 4 +++ .../util/pngj/chunks/ChunksListForWrite.java | 2 ++ .../opengl/util/pngj/chunks/PngChunkSingle.java | 1 + .../opengl/util/pngj/chunks/PngMetadata.java | 1 + .../windows/wgl/WindowsWGLDrawableFactory.java | 1 + .../wgl/WindowsWGLGraphicsConfiguration.java | 2 ++ .../WindowsWGLGraphicsConfigurationFactory.java | 1 + .../WindowsAWTWGLGraphicsConfigurationFactory.java | 1 + .../opengl/x11/glx/X11GLXDrawableFactory.java | 1 + .../x11/glx/X11GLXGraphicsConfiguration.java | 2 ++ .../glx/X11GLXGraphicsConfigurationFactory.java | 1 + .../nativewindow/awt/AWTGraphicsConfiguration.java | 1 + .../jogamp/nativewindow/awt/AWTGraphicsScreen.java | 1 + .../nativewindow/awt/AWTWindowClosingProtocol.java | 2 ++ .../nativewindow/awt/DirectDataBufferInt.java | 4 +++ .../nativewindow/macosx/MacOSXGraphicsDevice.java | 1 + .../com/jogamp/nativewindow/swt/SWTAccessor.java | 4 +++ .../windows/WindowsGraphicsDevice.java | 1 + .../jogamp/nativewindow/x11/X11GraphicsScreen.java | 1 + .../nativewindow/DefaultCapabilitiesChooser.java | 1 + .../nativewindow/DefaultGraphicsConfiguration.java | 4 +++ .../media/nativewindow/DefaultGraphicsScreen.java | 2 ++ .../nativewindow/GraphicsConfigurationFactory.java | 2 ++ .../media/nativewindow/NativeWindowFactory.java | 4 +++ .../javax/media/nativewindow/ProxySurface.java | 1 + .../javax/media/nativewindow/VisualIDHolder.java | 1 + .../javax/media/nativewindow/util/Dimension.java | 2 ++ .../nativewindow/util/DimensionImmutable.java | 2 ++ .../javax/media/nativewindow/util/Insets.java | 3 ++ .../media/nativewindow/util/InsetsImmutable.java | 2 ++ .../javax/media/nativewindow/util/Point.java | 3 ++ .../media/nativewindow/util/PointImmutable.java | 2 ++ .../javax/media/nativewindow/util/Rectangle.java | 3 ++ .../nativewindow/util/RectangleImmutable.java | 2 ++ .../javax/media/nativewindow/util/SurfaceSize.java | 3 ++ .../classes/jogamp/nativewindow/Debug.java | 1 + .../DefaultGraphicsConfigurationFactoryImpl.java | 1 + .../jogamp/nativewindow/GlobalToolkitLock.java | 1 + .../jogamp/nativewindow/NWJNILibLoader.java | 1 + .../nativewindow/NativeWindowFactoryImpl.java | 1 + .../jogamp/nativewindow/NullToolkitLock.java | 1 + .../jogamp/nativewindow/ProxySurfaceImpl.java | 1 + .../jogamp/nativewindow/ResourceToolkitLock.java | 1 + .../nativewindow/SharedResourceToolkitLock.java | 1 + .../jogamp/nativewindow/SurfaceUpdatedHelper.java | 1 + .../jogamp/nativewindow/jawt/JAWTJNILibLoader.java | 1 + .../classes/jogamp/nativewindow/jawt/JAWTUtil.java | 4 +++ .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 10 ++++++ .../jawt/windows/Win32SunJDKReflection.java | 1 + .../jawt/windows/WindowsJAWTWindow.java | 5 +++ .../nativewindow/jawt/x11/X11JAWTWindow.java | 5 +++ .../nativewindow/jawt/x11/X11SunJDKReflection.java | 1 + .../jogamp/nativewindow/macosx/OSXUtil.java | 2 +- .../x11/X11GraphicsConfigurationFactory.java | 1 + .../classes/jogamp/nativewindow/x11/X11Util.java | 2 ++ .../awt/X11AWTGraphicsConfigurationFactory.java | 1 + src/newt/classes/com/jogamp/newt/Display.java | 2 ++ .../classes/com/jogamp/newt/MonitorDevice.java | 3 ++ src/newt/classes/com/jogamp/newt/MonitorMode.java | 8 +++++ src/newt/classes/com/jogamp/newt/NewtFactory.java | 1 + src/newt/classes/com/jogamp/newt/Screen.java | 2 ++ .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 13 ++++++++ .../jogamp/newt/awt/applet/JOGLNewtApplet1Run.java | 4 +++ .../jogamp/newt/awt/applet/JOGLNewtAppletBase.java | 6 ++++ .../jogamp/newt/event/DoubleTapScrollGesture.java | 1 + .../classes/com/jogamp/newt/event/InputEvent.java | 2 ++ .../classes/com/jogamp/newt/event/KeyAdapter.java | 2 ++ .../classes/com/jogamp/newt/event/KeyEvent.java | 2 ++ .../com/jogamp/newt/event/MonitorEvent.java | 2 ++ .../com/jogamp/newt/event/MouseAdapter.java | 8 +++++ .../classes/com/jogamp/newt/event/MouseEvent.java | 2 ++ .../classes/com/jogamp/newt/event/NEWTEvent.java | 1 + .../com/jogamp/newt/event/PinchToZoomGesture.java | 1 + .../com/jogamp/newt/event/TraceKeyAdapter.java | 2 ++ .../com/jogamp/newt/event/TraceMouseAdapter.java | 8 +++++ .../com/jogamp/newt/event/TraceWindowAdapter.java | 7 ++++ .../com/jogamp/newt/event/WindowAdapter.java | 7 ++++ .../classes/com/jogamp/newt/event/WindowEvent.java | 2 ++ .../com/jogamp/newt/event/WindowUpdateEvent.java | 2 ++ .../com/jogamp/newt/event/awt/AWTKeyAdapter.java | 2 ++ .../com/jogamp/newt/event/awt/AWTMouseAdapter.java | 10 ++++++ .../jogamp/newt/event/awt/AWTWindowAdapter.java | 22 ++++++++++++ .../classes/com/jogamp/newt/opengl/GLWindow.java | 2 ++ .../classes/com/jogamp/newt/swt/NewtCanvasSWT.java | 3 ++ src/newt/classes/jogamp/newt/Debug.java | 1 + src/newt/classes/jogamp/newt/DisplayImpl.java | 9 +++++ src/newt/classes/jogamp/newt/NEWTJNILibLoader.java | 1 + src/newt/classes/jogamp/newt/OffscreenWindow.java | 7 ++++ src/newt/classes/jogamp/newt/WindowImpl.java | 16 +++++++++ .../newt/awt/event/AWTParentWindowAdapter.java | 11 ++++++ .../classes/jogamp/newt/driver/awt/AWTCanvas.java | 4 +++ .../classes/jogamp/newt/driver/awt/AWTEDTUtil.java | 1 + .../jogamp/newt/driver/awt/DisplayDriver.java | 4 +++ .../jogamp/newt/driver/awt/ScreenDriver.java | 3 ++ .../jogamp/newt/driver/awt/WindowDriver.java | 6 ++++ .../jogamp/newt/driver/bcm/egl/DisplayDriver.java | 3 ++ .../jogamp/newt/driver/bcm/egl/ScreenDriver.java | 4 +++ .../jogamp/newt/driver/bcm/egl/WindowDriver.java | 6 ++++ .../newt/driver/bcm/vc/iv/DisplayDriver.java | 3 ++ .../jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java | 3 ++ .../jogamp/newt/driver/bcm/vc/iv/WindowDriver.java | 6 ++++ .../newt/driver/intel/gdl/DisplayDriver.java | 3 ++ .../jogamp/newt/driver/intel/gdl/ScreenDriver.java | 4 +++ .../jogamp/newt/driver/intel/gdl/WindowDriver.java | 6 ++++ .../jogamp/newt/driver/kd/DisplayDriver.java | 3 ++ .../jogamp/newt/driver/kd/ScreenDriver.java | 4 +++ .../jogamp/newt/driver/kd/WindowDriver.java | 6 ++++ .../jogamp/newt/driver/macosx/DisplayDriver.java | 3 ++ .../jogamp/newt/driver/macosx/ScreenDriver.java | 3 ++ .../jogamp/newt/driver/macosx/WindowDriver.java | 12 +++++++ .../jogamp/newt/driver/windows/DisplayDriver.java | 3 ++ .../jogamp/newt/driver/windows/WindowDriver.java | 9 +++++ .../jogamp/newt/driver/x11/DisplayDriver.java | 2 ++ .../jogamp/newt/driver/x11/ScreenDriver.java | 5 +++ .../jogamp/newt/driver/x11/WindowDriver.java | 8 +++++ src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java | 2 ++ 323 files changed, 1132 insertions(+), 4 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/audio/windows/waveout/Mixer.java b/src/jogl/classes/com/jogamp/audio/windows/waveout/Mixer.java index 0a502c123..3b76d2ebf 100644 --- a/src/jogl/classes/com/jogamp/audio/windows/waveout/Mixer.java +++ b/src/jogl/classes/com/jogamp/audio/windows/waveout/Mixer.java @@ -129,6 +129,7 @@ public class Mixer { super("Mixer Thread"); } + @Override public void run() { while (!shutdown) { List/**/ curTracks = tracks; @@ -166,6 +167,7 @@ public class Mixer { } } + @Override public void run() { while (!shutdown) { // Get the next buffer diff --git a/src/jogl/classes/com/jogamp/audio/windows/waveout/Vec3f.java b/src/jogl/classes/com/jogamp/audio/windows/waveout/Vec3f.java index 0726e5762..79fb80169 100644 --- a/src/jogl/classes/com/jogamp/audio/windows/waveout/Vec3f.java +++ b/src/jogl/classes/com/jogamp/audio/windows/waveout/Vec3f.java @@ -206,6 +206,7 @@ class Vec3f { z *= arg.z; } + @Override public String toString() { return "(" + x + ", " + y + ", " + z + ")"; } diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java index 8429fbcfd..5f358a6d3 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java @@ -402,6 +402,7 @@ public class BuildComposablePipeline { ifNames, null, new CodeGenUtils.EmissionCallback() { + @Override public void emit(PrintWriter w) { emitClassDocComment(w); } @@ -752,18 +753,22 @@ public class BuildComposablePipeline { this.mode = mode; } + @Override protected String getOutputName() { return className; } + @Override protected int getMode() { return mode; } + @Override protected boolean emptyMethodAllowed() { return true; } + @Override protected boolean emptyDownstreamAllowed() { return true; } @@ -773,6 +778,7 @@ public class BuildComposablePipeline { super.preMethodEmissionHook(output); } + @Override protected void constructorHook(PrintWriter output) { output.print(" public " + getOutputName() + "("); output.print(downstreamName + " " + getDownstreamObjectName()); @@ -803,6 +809,7 @@ public class BuildComposablePipeline { } } + @Override protected void emitClassDocComment(PrintWriter output) { output.println("/**"); output.println(" * Composable pipeline {@link " + outputPackage + "." + outputName + "}, implementing the interface"); @@ -837,10 +844,12 @@ public class BuildComposablePipeline { output.println("*/"); } + @Override protected boolean hasPreDownstreamCallHook(Method m) { return null != getMethod(prologClassOpt, m); } + @Override protected void preDownstreamCallHook(PrintWriter output, Method m) { if (null != prologNameOpt) { output.print(getPrologObjectNameOpt()); @@ -852,10 +861,12 @@ public class BuildComposablePipeline { } } + @Override protected boolean hasPostDownstreamCallHook(Method m) { return false; } + @Override protected void postDownstreamCallHook(PrintWriter output, Method m) { } } // end class CustomPipeline @@ -869,18 +880,22 @@ public class BuildComposablePipeline { className = "Debug" + getBaseInterfaceName(); } + @Override protected String getOutputName() { return className; } + @Override protected int getMode() { return 0; } + @Override protected boolean emptyMethodAllowed() { return false; } + @Override protected boolean emptyDownstreamAllowed() { return false; } @@ -890,6 +905,7 @@ public class BuildComposablePipeline { super.preMethodEmissionHook(output); } + @Override protected void constructorHook(PrintWriter output) { output.print(" public " + getOutputName() + "("); output.println(downstreamName + " " + getDownstreamObjectName() + ")"); @@ -971,6 +987,7 @@ public class BuildComposablePipeline { output.println(" private GLContext _context;"); } + @Override protected void emitClassDocComment(PrintWriter output) { output.println("/**"); output.println(" *

                            "); @@ -988,18 +1005,22 @@ public class BuildComposablePipeline { output.println(" */"); } + @Override protected boolean hasPreDownstreamCallHook(Method m) { return true; } + @Override protected void preDownstreamCallHook(PrintWriter output, Method m) { output.println(" checkContext();"); } + @Override protected boolean hasPostDownstreamCallHook(Method m) { return true; } + @Override protected void postDownstreamCallHook(PrintWriter output, Method m) { if (m.getName().equals("glBegin")) { output.println(" insideBeginEndPair = true;"); @@ -1041,18 +1062,22 @@ public class BuildComposablePipeline { className = "Trace" + getBaseInterfaceName(); } + @Override protected String getOutputName() { return className; } + @Override protected int getMode() { return 0; } + @Override protected boolean emptyMethodAllowed() { return false; } + @Override protected boolean emptyDownstreamAllowed() { return false; } @@ -1062,6 +1087,7 @@ public class BuildComposablePipeline { super.preMethodEmissionHook(output); } + @Override protected void constructorHook(PrintWriter output) { output.print(" public " + getOutputName() + "("); output.println(downstreamName + " " + getDownstreamObjectName() + ", PrintStream " + getOutputStreamName() + ")"); @@ -1112,6 +1138,7 @@ public class BuildComposablePipeline { output.println("}"); } + @Override protected void emitClassDocComment(PrintWriter output) { output.println("/**"); output.println(" *

                            "); @@ -1129,10 +1156,12 @@ public class BuildComposablePipeline { output.println(" */"); } + @Override protected boolean hasPreDownstreamCallHook(Method m) { return true; } + @Override protected void preDownstreamCallHook(PrintWriter output, Method m) { if (m.getName().equals("glEnd") || m.getName().equals("glEndList")) { output.println("indent-=2;"); @@ -1146,10 +1175,12 @@ public class BuildComposablePipeline { output.println(");"); } + @Override protected boolean hasPostDownstreamCallHook(Method m) { return true; } + @Override protected void postDownstreamCallHook(PrintWriter output, Method m) { Class ret = m.getReturnType(); if (ret != Void.TYPE) { diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java b/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java index 1af632682..547382ed1 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java @@ -134,6 +134,7 @@ public class GLEmitter extends ProcAddressEmitter { private List constants; private List functions; + @Override public void filterSymbols(List constants, List functions) { this.constants = constants; @@ -141,10 +142,12 @@ public class GLEmitter extends ProcAddressEmitter { doWork(); } + @Override public List getConstants() { return constants; } + @Override public List getFunctions() { return functions; } diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/ant/StaticGLGenTask.java b/src/jogl/classes/com/jogamp/gluegen/opengl/ant/StaticGLGenTask.java index b98f17117..21946ea89 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/ant/StaticGLGenTask.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/ant/StaticGLGenTask.java @@ -186,6 +186,7 @@ public class StaticGLGenTask extends Task * * @see org.apache.tools.ant.Task#execute() */ + @Override public void execute() throws BuildException { diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java b/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java index a17657382..6d9d6f2bb 100644 --- a/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java +++ b/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java @@ -131,6 +131,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding } } + @Override protected String getReturnTypeString(boolean skipArray) { if (isForImplementingMethodCall()) { JavaType returnType = getBinding().getJavaReturnType(); @@ -142,6 +143,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding return super.getReturnTypeString(skipArray); } + @Override protected void emitPreCallSetup(MethodBinding binding, PrintWriter writer) { super.emitPreCallSetup(binding, writer); for (int i = 0; i < binding.getNumArguments(); i++) { @@ -162,6 +164,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding return "__buffer_array_" + argNumber; } + @Override protected int emitArguments(PrintWriter writer) { boolean needComma = false; @@ -242,6 +245,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding return numEmitted; } + @Override protected void emitReturnVariableSetupAndCall(MethodBinding binding, PrintWriter writer) { writer.print(" "); JavaType returnType = binding.getJavaReturnType(); @@ -455,6 +459,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding return numArgsEmitted; } + @Override protected void emitCallResultReturn(MethodBinding binding, PrintWriter writer) { for (int i = 0; i < binding.getNumArguments(); i++) { JavaType type = binding.getJavaArgumentType(i); @@ -468,6 +473,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding super.emitCallResultReturn(binding, writer); } + @Override public String getName() { String res = super.getName(); if (forImplementingMethodCall && bufferObjectVariant) { diff --git a/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLProcAddressResolver.java b/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLProcAddressResolver.java index f8406075c..3fb315c99 100644 --- a/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLProcAddressResolver.java +++ b/src/jogl/classes/com/jogamp/gluegen/runtime/opengl/GLProcAddressResolver.java @@ -42,6 +42,7 @@ public class GLProcAddressResolver implements FunctionAddressResolver { public static final boolean DEBUG = false; + @Override public long resolve(String name, DynamicLookupHelper lookup) { long newProcAddress = 0; diff --git a/src/jogl/classes/com/jogamp/graph/curve/OutlineShape.java b/src/jogl/classes/com/jogamp/graph/curve/OutlineShape.java index cb2885e0f..60d5199eb 100644 --- a/src/jogl/classes/com/jogamp/graph/curve/OutlineShape.java +++ b/src/jogl/classes/com/jogamp/graph/curve/OutlineShape.java @@ -554,6 +554,7 @@ public class OutlineShape implements Comparable { * as criteria. * @see java.lang.Comparable#compareTo(java.lang.Object) */ + @Override public final int compareTo(OutlineShape outline) { float size = getBounds().getSize(); float newSize = outline.getBounds().getSize(); @@ -586,6 +587,7 @@ public class OutlineShape implements Comparable { * @return true if {@code obj} is an OutlineShape, not null, * same outlineState, equal bounds and equal outlines in the same order */ + @Override public boolean equals(Object obj) { if( obj == this) { return true; @@ -614,6 +616,7 @@ public class OutlineShape implements Comparable { /** * @return deep clone of this OutlineShape w/o Region */ + @Override public OutlineShape clone() { OutlineShape o; try { diff --git a/src/jogl/classes/com/jogamp/graph/curve/opengl/RenderState.java b/src/jogl/classes/com/jogamp/graph/curve/opengl/RenderState.java index 9c833fd24..6a8fb6a67 100644 --- a/src/jogl/classes/com/jogamp/graph/curve/opengl/RenderState.java +++ b/src/jogl/classes/com/jogamp/graph/curve/opengl/RenderState.java @@ -105,6 +105,7 @@ public abstract class RenderState { return sb; } + @Override public String toString() { return toString(null, false).toString(); } diff --git a/src/jogl/classes/com/jogamp/graph/font/Font.java b/src/jogl/classes/com/jogamp/graph/font/Font.java index 82211da92..a4a8fd53d 100644 --- a/src/jogl/classes/com/jogamp/graph/font/Font.java +++ b/src/jogl/classes/com/jogamp/graph/font/Font.java @@ -109,5 +109,6 @@ public interface Font { public boolean isPrintableChar( char c ); /** Shall return {@link #getFullFamilyName()} */ + @Override public String toString(); } \ No newline at end of file diff --git a/src/jogl/classes/com/jogamp/graph/geom/Outline.java b/src/jogl/classes/com/jogamp/graph/geom/Outline.java index dfa6a8635..77a318078 100644 --- a/src/jogl/classes/com/jogamp/graph/geom/Outline.java +++ b/src/jogl/classes/com/jogamp/graph/geom/Outline.java @@ -173,6 +173,7 @@ public class Outline implements Cloneable, Comparable { * as criteria. * @see java.lang.Comparable#compareTo(java.lang.Object) */ + @Override public final int compareTo(Outline outline) { float size = getBounds().getSize(); float newSize = outline.getBounds().getSize(); @@ -204,6 +205,7 @@ public class Outline implements Cloneable, Comparable { * @param obj the Object to compare this Outline with * @return true if {@code obj} is an Outline, not null, equals bounds and equal vertices in the same order */ + @Override public boolean equals(Object obj) { if( obj == this) { return true; @@ -229,6 +231,7 @@ public class Outline implements Cloneable, Comparable { /** * @return deep clone of this Outline */ + @Override public Outline clone() { Outline o; try { diff --git a/src/jogl/classes/com/jogamp/graph/geom/Triangle.java b/src/jogl/classes/com/jogamp/graph/geom/Triangle.java index bd0900495..a01cd834f 100644 --- a/src/jogl/classes/com/jogamp/graph/geom/Triangle.java +++ b/src/jogl/classes/com/jogamp/graph/geom/Triangle.java @@ -73,6 +73,7 @@ public class Triangle { this.boundaryVertices = boundaryVertices; } + @Override public String toString() { return "Tri ID: " + id + "\n" + vertices[0] + "\n" + vertices[1] + "\n" + vertices[2]; } diff --git a/src/jogl/classes/com/jogamp/graph/geom/Vertex.java b/src/jogl/classes/com/jogamp/graph/geom/Vertex.java index 40048235e..994253f71 100644 --- a/src/jogl/classes/com/jogamp/graph/geom/Vertex.java +++ b/src/jogl/classes/com/jogamp/graph/geom/Vertex.java @@ -76,6 +76,7 @@ public interface Vertex extends Vert3fImmutable, Cloneable { * @param obj the Object to compare this Vertex with * @return true if {@code obj} is a Vertex and not null, on-curve flag is equal and has same vertex- and tex-coords. */ + @Override boolean equals(Object obj); /** diff --git a/src/jogl/classes/com/jogamp/graph/geom/opengl/SVertex.java b/src/jogl/classes/com/jogamp/graph/geom/opengl/SVertex.java index 6b07688a7..b27604a44 100644 --- a/src/jogl/classes/com/jogamp/graph/geom/opengl/SVertex.java +++ b/src/jogl/classes/com/jogamp/graph/geom/opengl/SVertex.java @@ -45,14 +45,17 @@ public class SVertex implements Vertex { public static Factory factory() { return factory; } public static class Factory implements Vertex.Factory { + @Override public SVertex create() { return new SVertex(); } + @Override public SVertex create(float x, float y, float z, boolean onCurve) { return new SVertex(x, y, z, onCurve); } + @Override public SVertex create(float[] coordsBuffer, int offset, int length, boolean onCurve) { return new SVertex(coordsBuffer, offset, length, onCurve); } @@ -78,12 +81,14 @@ public class SVertex implements Vertex { setOnCurve(onCurve); } + @Override public final void setCoord(float x, float y, float z) { this.coord[0] = x; this.coord[1] = y; this.coord[2] = z; } + @Override public final void setCoord(float[] coordsBuffer, int offset, int length) { System.arraycopy(coordsBuffer, offset, coord, 0, length); } @@ -98,46 +103,57 @@ public class SVertex implements Vertex { return coord; } + @Override public final void setX(float x) { this.coord[0] = x; } + @Override public final void setY(float y) { this.coord[1] = y; } + @Override public final void setZ(float z) { this.coord[2] = z; } + @Override public final float getX() { return this.coord[0]; } + @Override public final float getY() { return this.coord[1]; } + @Override public final float getZ() { return this.coord[2]; } + @Override public final boolean isOnCurve() { return onCurve; } + @Override public final void setOnCurve(boolean onCurve) { this.onCurve = onCurve; } + @Override public final int getId(){ return id; } + @Override public final void setId(int id){ this.id = id; } + @Override public boolean equals(Object obj) { if( obj == this) { return true; @@ -152,15 +168,18 @@ public class SVertex implements Vertex { VectorUtil.checkEquality(getCoord(), v.getCoord()) ; } + @Override public final float[] getTexCoord() { return texCoord; } + @Override public final void setTexCoord(float s, float t) { this.texCoord[0] = s; this.texCoord[1] = t; } + @Override public final void setTexCoord(float[] texCoordsBuffer, int offset, int length) { System.arraycopy(texCoordsBuffer, offset, texCoord, 0, length); } @@ -168,10 +187,12 @@ public class SVertex implements Vertex { /** * @return deep clone of this Vertex, but keeping the id blank */ + @Override public SVertex clone(){ return new SVertex(this.coord, 0, 3, this.texCoord, 0, 2, this.onCurve); } + @Override public String toString() { return "[ID: " + id + ", onCurve: " + onCurve + ": p " + coord[0] + ", " + coord[1] + ", " + coord[2] + diff --git a/src/jogl/classes/com/jogamp/opengl/FBObject.java b/src/jogl/classes/com/jogamp/opengl/FBObject.java index c78b2b83d..72041a389 100644 --- a/src/jogl/classes/com/jogamp/opengl/FBObject.java +++ b/src/jogl/classes/com/jogamp/opengl/FBObject.java @@ -292,6 +292,7 @@ public class FBObject { int objectHashCode() { return super.hashCode(); } + @Override public String toString() { return getClass().getSimpleName()+"[type "+type+", format "+toHexString(format)+", "+width+"x"+height+ "; name "+toHexString(name)+", obj "+toHexString(objectHashCode())+"]"; @@ -414,6 +415,7 @@ public class FBObject { } } + @Override public String toString() { return getClass().getSimpleName()+"[type "+type+", format "+toHexString(format)+", samples "+samples+", "+getWidth()+"x"+getHeight()+ ", name "+toHexString(getName())+", obj "+toHexString(objectHashCode())+"]"; @@ -527,6 +529,7 @@ public class FBObject { setName(0); } } + @Override public String toString() { return getClass().getSimpleName()+"[type "+type+", target GL_TEXTURE_2D, level 0, format "+toHexString(format)+ ", "+getWidth()+"x"+getHeight()+", border 0, dataFormat "+toHexString(dataFormat)+ @@ -2306,6 +2309,7 @@ public class FBObject { int objectHashCode() { return super.hashCode(); } + @Override public final String toString() { final String caps = null != colorAttachmentPoints ? Arrays.asList(colorAttachmentPoints).toString() : null ; return "FBO[name r/w "+fbName+"/"+getReadFramebuffer()+", init "+initialized+", bound "+bound+", size "+width+"x"+height+ diff --git a/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java b/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java index ee77f8d2d..9c9129ae6 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java +++ b/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java @@ -262,6 +262,7 @@ public class GLRendererQuirks { return sb; } + @Override public final String toString() { return toString(null).toString(); } diff --git a/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java b/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java index 8d2d07d58..4270607f2 100644 --- a/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java @@ -43,6 +43,7 @@ public final class CgDynamicLibraryBundleInfo implements DynamicLibraryBundleInf private static final List glueLibNames; static { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { Platform.initSingleton(); diff --git a/src/jogl/classes/com/jogamp/opengl/math/geom/AABBox.java b/src/jogl/classes/com/jogamp/opengl/math/geom/AABBox.java index f1880a61b..d48677da5 100644 --- a/src/jogl/classes/com/jogamp/opengl/math/geom/AABBox.java +++ b/src/jogl/classes/com/jogamp/opengl/math/geom/AABBox.java @@ -333,10 +333,12 @@ public class AABBox implements Cloneable { return high[2] - low[2]; } + @Override public final AABBox clone() { return new AABBox(this.low, this.high); } + @Override public final boolean equals(Object obj) { if( obj == this ) { return true; @@ -349,6 +351,7 @@ public class AABBox implements Cloneable { VectorUtil.checkEquality(high, other.high) ; } + @Override public final String toString() { return "[ "+low[0]+"/"+low[1]+"/"+low[1]+" .. "+high[0]+"/"+high[0]+"/"+high[0]+", ctr "+ center[0]+"/"+center[1]+"/"+center[1]+" ]"; diff --git a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java index 33941a407..1a3e1e0c0 100644 --- a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java +++ b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java @@ -286,6 +286,7 @@ public class GLCanvas extends Canvas implements GLAutoDrawable { final GLCapabilitiesChooser chooser, final GLContext shareWith) { final GLCanvas[] res = new GLCanvas[] { null }; parent.getDisplay().syncExec(new Runnable() { + @Override public void run() { res[0] = new GLCanvas( parent, style, caps, chooser, shareWith ); } diff --git a/src/jogl/classes/com/jogamp/opengl/util/AWTAnimatorImpl.java b/src/jogl/classes/com/jogamp/opengl/util/AWTAnimatorImpl.java index 80289acf3..d0de3b3a0 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/AWTAnimatorImpl.java +++ b/src/jogl/classes/com/jogamp/opengl/util/AWTAnimatorImpl.java @@ -58,6 +58,7 @@ class AWTAnimatorImpl implements AnimatorBase.AnimatorImpl { private Map repaintManagers = new IdentityHashMap(); private Map dirtyRegions = new IdentityHashMap(); + @Override public void display(ArrayList drawables, boolean ignoreExceptions, boolean printExceptions) { @@ -97,6 +98,7 @@ class AWTAnimatorImpl implements AnimatorBase.AnimatorImpl { // Uses RepaintManager APIs to implement more efficient redrawing of // the Swing widgets we're animating private Runnable drawWithRepaintManagerRunnable = new Runnable() { + @Override public void run() { for (Iterator iter = lightweights.iterator(); iter.hasNext(); ) { JComponent comp = iter.next(); @@ -164,6 +166,7 @@ class AWTAnimatorImpl implements AnimatorBase.AnimatorImpl { } }; + @Override public boolean blockUntilDone(Thread thread) { return Thread.currentThread() != thread && !EventQueue.isDispatchThread(); } diff --git a/src/jogl/classes/com/jogamp/opengl/util/Animator.java b/src/jogl/classes/com/jogamp/opengl/util/Animator.java index cdfb73b21..27b9427eb 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/Animator.java +++ b/src/jogl/classes/com/jogamp/opengl/util/Animator.java @@ -109,6 +109,7 @@ public class Animator extends AnimatorBase { } } + @Override protected String getBaseName(String prefix) { return prefix + "Animator" ; } @@ -138,10 +139,12 @@ public class Animator extends AnimatorBase { } class MainLoop implements Runnable { + @Override public String toString() { return "[started "+isStartedImpl()+", animating "+isAnimatingImpl()+", paused "+isPausedImpl()+", drawable "+drawables.size()+", drawablesEmpty "+drawablesEmpty+"]"; } + @Override public void run() { try { if(DEBUG) { @@ -228,6 +231,7 @@ public class Animator extends AnimatorBase { private final boolean isAnimatingImpl() { return animThread != null && isAnimating ; } + @Override public final boolean isAnimating() { stateSync.lock(); try { @@ -240,6 +244,7 @@ public class Animator extends AnimatorBase { private final boolean isPausedImpl() { return animThread != null && pauseIssued ; } + @Override public final boolean isPaused() { stateSync.lock(); try { @@ -262,6 +267,7 @@ public class Animator extends AnimatorBase { threadGroup = tg; } + @Override public synchronized boolean start() { if ( isStartedImpl() ) { return false; @@ -286,10 +292,12 @@ public class Animator extends AnimatorBase { return finishLifecycleAction(waitForStartedCondition, 0); } private final Condition waitForStartedCondition = new Condition() { + @Override public boolean eval() { return !isStartedImpl() || (!drawablesEmpty && !isAnimating) ; } }; + @Override public synchronized boolean stop() { if ( !isStartedImpl() ) { return false; @@ -298,10 +306,12 @@ public class Animator extends AnimatorBase { return finishLifecycleAction(waitForStoppedCondition, 0); } private final Condition waitForStoppedCondition = new Condition() { + @Override public boolean eval() { return isStartedImpl(); } }; + @Override public synchronized boolean pause() { if ( !isStartedImpl() || pauseIssued ) { return false; @@ -310,11 +320,13 @@ public class Animator extends AnimatorBase { return finishLifecycleAction(waitForPausedCondition, 0); } private final Condition waitForPausedCondition = new Condition() { + @Override public boolean eval() { // end waiting if stopped as well return isStartedImpl() && isAnimating; } }; + @Override public synchronized boolean resume() { if ( !isStartedImpl() || !pauseIssued ) { return false; @@ -323,6 +335,7 @@ public class Animator extends AnimatorBase { return finishLifecycleAction(waitForResumeCondition, 0); } private final Condition waitForResumeCondition = new Condition() { + @Override public boolean eval() { // end waiting if stopped as well return isStartedImpl() && ( !drawablesEmpty && !isAnimating || drawablesEmpty && !pauseIssued ) ; diff --git a/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java b/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java index b447a339b..f6ee3376f 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java +++ b/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java @@ -194,6 +194,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { resume(); } final Condition waitForAnimatingAndECTCondition = new Condition() { + @Override public boolean eval() { final Thread dect = drawable.getExclusiveContextThread(); return isStarted() && !isPaused() && !isAnimating() && ( exclusiveContext && null == dect || !exclusiveContext && null != dect ); @@ -217,6 +218,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { if( exclusiveContext && isAnimating() ) { drawable.setExclusiveContextThread( null ); final Condition waitForNullECTCondition = new Condition() { + @Override public boolean eval() { return null != drawable.getExclusiveContextThread(); } }; @@ -240,6 +242,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { notifyAll(); } private final Condition waitForNotAnimatingIfEmptyCondition = new Condition() { + @Override public boolean eval() { return isStarted() && drawablesEmpty && isAnimating(); } }; @@ -577,6 +580,7 @@ public abstract class AnimatorBase implements GLAnimatorControl { protected static String getThreadName() { return Thread.currentThread().getName(); } + @Override public String toString() { return getClass().getName()+"[started "+isStarted()+", animating "+isAnimating()+", paused "+isPaused()+", drawable "+drawables.size()+ ", totals[dt "+getTotalFPSDuration()+", frames "+getTotalFPSFrames()+", fps "+getTotalFPS()+ diff --git a/src/jogl/classes/com/jogamp/opengl/util/DefaultAnimatorImpl.java b/src/jogl/classes/com/jogamp/opengl/util/DefaultAnimatorImpl.java index 0477e1903..a9c6e6456 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/DefaultAnimatorImpl.java +++ b/src/jogl/classes/com/jogamp/opengl/util/DefaultAnimatorImpl.java @@ -41,6 +41,7 @@ import javax.media.opengl.GLAutoDrawable; up this behavior if desired. */ class DefaultAnimatorImpl implements AnimatorBase.AnimatorImpl { + @Override public void display(ArrayList drawables, boolean ignoreExceptions, boolean printExceptions) { @@ -60,6 +61,7 @@ class DefaultAnimatorImpl implements AnimatorBase.AnimatorImpl { } } + @Override public boolean blockUntilDone(Thread thread) { return Thread.currentThread() != thread; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java b/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java index b48169c27..351c47e7e 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java +++ b/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java @@ -64,6 +64,7 @@ public class FPSAnimator extends AnimatorBase { private volatile boolean shouldRun; // MainTask trigger private volatile boolean shouldStop; // MainTask trigger + @Override protected String getBaseName(String prefix) { return "FPS" + prefix + "Animator" ; } @@ -140,10 +141,12 @@ public class FPSAnimator extends AnimatorBase { public boolean isActive() { return !alreadyStopped && !alreadyPaused; } + @Override public String toString() { return "Task[thread "+animThread+", stopped "+alreadyStopped+", paused "+alreadyPaused+" shouldRun "+shouldRun+", shouldStop "+shouldStop+" -- started "+isStartedImpl()+", animating "+isAnimatingImpl()+", paused "+isPausedImpl()+", drawable "+drawables.size()+", drawablesEmpty "+drawablesEmpty+"]"; } + @Override public void run() { if( justStarted ) { justStarted = false; @@ -208,6 +211,7 @@ public class FPSAnimator extends AnimatorBase { private final boolean isAnimatingImpl() { return animThread != null && isAnimating ; } + @Override public final boolean isAnimating() { stateSync.lock(); try { @@ -220,6 +224,7 @@ public class FPSAnimator extends AnimatorBase { private final boolean isPausedImpl() { return animThread != null && ( !shouldRun && !shouldStop ) ; } + @Override public final boolean isPaused() { stateSync.lock(); try { @@ -231,6 +236,7 @@ public class FPSAnimator extends AnimatorBase { static int timerNo = 0; + @Override public synchronized boolean start() { if ( null != timer || null != task || isStartedImpl() ) { return false; @@ -254,10 +260,12 @@ public class FPSAnimator extends AnimatorBase { return res; } private final Condition waitForStartedAddedCondition = new Condition() { + @Override public boolean eval() { return !isStartedImpl() || !isAnimating ; } }; private final Condition waitForStartedEmptyCondition = new Condition() { + @Override public boolean eval() { return !isStartedImpl() || isAnimating ; } }; @@ -265,6 +273,7 @@ public class FPSAnimator extends AnimatorBase { /** Stops this FPSAnimator. Due to the implementation of the FPSAnimator it is not guaranteed that the FPSAnimator will be completely stopped by the time this method returns. */ + @Override public synchronized boolean stop() { if ( null == timer || !isStartedImpl() ) { return false; @@ -297,10 +306,12 @@ public class FPSAnimator extends AnimatorBase { return res; } private final Condition waitForStoppedCondition = new Condition() { + @Override public boolean eval() { return isStartedImpl(); } }; + @Override public synchronized boolean pause() { if ( !isStartedImpl() || ( null != task && isPausedImpl() ) ) { return false; @@ -327,11 +338,13 @@ public class FPSAnimator extends AnimatorBase { return res; } private final Condition waitForPausedCondition = new Condition() { + @Override public boolean eval() { // end waiting if stopped as well return isAnimating && isStartedImpl(); } }; + @Override public synchronized boolean resume() { if ( null != task || !isStartedImpl() || !isPausedImpl() ) { return false; @@ -353,6 +366,7 @@ public class FPSAnimator extends AnimatorBase { return res; } private final Condition waitForResumeCondition = new Condition() { + @Override public boolean eval() { // end waiting if stopped as well return !drawablesEmpty && !isAnimating && isStartedImpl(); diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java index 2d685a1a8..f480c4bde 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java @@ -321,6 +321,7 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData Buffers.putf(buffer, v); } + @Override public String toString() { return "GLArrayDataClient["+name+ ", index "+index+ diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataEditable.java b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataEditable.java index 701f88e59..9a0f1cb37 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataEditable.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataEditable.java @@ -31,6 +31,7 @@ public interface GLArrayDataEditable extends GLArrayData { // Data and GL state modification .. // + @Override public void destroy(GL gl); public void reset(GL gl); diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java index 80639c5c7..e30fea2f4 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java @@ -327,6 +327,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE // Data and GL state modification .. // + @Override public void destroy(GL gl) { // super.destroy(gl): // - GLArrayDataClient.destroy(gl): disables & clears client-side buffer @@ -349,11 +350,13 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE * switch to client side data one * Only possible if buffer is defined. */ + @Override public void setVBOEnabled(boolean vboUsage) { checkSeal(false); super.setVBOEnabled(vboUsage); } + @Override public String toString() { return "GLArrayDataServer["+name+ ", index "+index+ @@ -384,6 +387,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE // non public matters .. // + @Override protected void init(String name, int index, int comps, int dataType, boolean normalized, int stride, Buffer data, int initialElementCount, boolean isVertexAttribute, GLArrayHandler glArrayHandler, @@ -396,6 +400,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE vboEnabled=true; } + @Override protected void init_vbo(GL gl) { super.init_vbo(gl); if(vboEnabled && vboName==0) { diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java b/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java index f0c6be44f..50124c349 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java @@ -216,6 +216,7 @@ public class GLPixelBuffer { } } } + @Override public String toString() { return "PixelAttributes[comp "+componentCount+", fmt 0x"+Integer.toHexString(format)+", type 0x"+Integer.toHexString(type)+", bytesPerPixel "+bytesPerPixel+"]"; } @@ -258,6 +259,7 @@ public class GLPixelBuffer { .append(", buffer[bytes ").append(byteSize).append(", elemSize ").append(bufferElemSize).append(", ").append(buffer).append("]"); return sb; } + @Override public String toString() { return "GLPixelBuffer["+toString(null).toString()+"]"; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java b/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java index 697b7cca0..986f6d8d3 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java +++ b/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java @@ -173,6 +173,7 @@ public class ImmModeSink { vboSet.reset(gl); } + @Override public String toString() { StringBuilder sb = new StringBuilder("ImmModeSink["); sb.append(",\n\tVBO list: "+vboSetList.size()+" ["); @@ -1236,6 +1237,7 @@ public class ImmModeSink { } } + @Override public String toString() { final String glslS = useGLSL ? ", useShaderState "+(null!=shaderState)+ diff --git a/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java b/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java index b4a0156e9..218897ffe 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java +++ b/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java @@ -897,6 +897,7 @@ public class PMVMatrix implements GLMatrixFunc { return sb; } + @Override public String toString() { return toString(null, "%10.5f").toString(); } diff --git a/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java b/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java index ff7cc5516..2ac4b1f82 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java +++ b/src/jogl/classes/com/jogamp/opengl/util/TileRendererBase.java @@ -244,6 +244,7 @@ public abstract class TileRendererBase { sb.append(", isSetup "+isSetup()); return sb; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); return getClass().getSimpleName()+ diff --git a/src/jogl/classes/com/jogamp/opengl/util/TimeFrameI.java b/src/jogl/classes/com/jogamp/opengl/util/TimeFrameI.java index 45f5d2694..b29846d91 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/TimeFrameI.java +++ b/src/jogl/classes/com/jogamp/opengl/util/TimeFrameI.java @@ -74,6 +74,7 @@ public class TimeFrameI { /** Set this frame's duration in milliseconds. */ public final void setDuration(int duration) { this.duration = duration; } + @Override public String toString() { return "TimeFrame[pts " + pts + " ms, l " + duration + " ms]"; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/av/AudioSink.java b/src/jogl/classes/com/jogamp/opengl/util/av/AudioSink.java index dffdfae8e..b964245ad 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/av/AudioSink.java +++ b/src/jogl/classes/com/jogamp/opengl/util/av/AudioSink.java @@ -193,6 +193,7 @@ public interface AudioSink { return ( byteCount << 3 ) / sampleSize; } + @Override public String toString() { return "AudioDataFormat[sampleRate "+sampleRate+", sampleSize "+sampleSize+", channelCount "+channelCount+ ", signed "+signed+", fixedP "+fixedP+", "+(planar?"planar":"packed")+", "+(littleEndian?"little":"big")+"-endian]"; } @@ -217,6 +218,7 @@ public interface AudioSink { /** Set this frame's size in bytes. */ public final void setByteSize(int size) { this.byteSize=size; } + @Override public String toString() { return "AudioFrame[pts " + pts + " ms, l " + duration + " ms, "+byteSize + " bytes]"; } @@ -235,6 +237,7 @@ public interface AudioSink { /** Get this frame's data. */ public final ByteBuffer getData() { return data; } + @Override public String toString() { return "AudioDataFrame[pts " + pts + " ms, l " + duration + " ms, "+byteSize + " bytes, " + data + "]"; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayer.java b/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayer.java index db6f5fdee..3f6b78d7e 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayer.java @@ -609,6 +609,7 @@ public interface GLMediaPlayer extends TextureSequence { public int getHeight(); /** Returns a string represantation of this player, incl. state and audio/video details. */ + @Override public String toString(); /** Returns a string represantation of this player's performance values. */ diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java b/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java index fb2bdbbcb..77b14b424 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/AWTGLPixelBuffer.java @@ -117,11 +117,13 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { return new BufferedImage (cm, raster1, cm.isAlphaPremultiplied(), null); } + @Override public StringBuilder toString(StringBuilder sb) { sb = super.toString(sb); sb.append(", allowRowStride ").append(allowRowStride).append(", image [").append(image.getWidth()).append("x").append(image.getHeight()).append(", ").append(image.toString()).append("]"); return sb; } + @Override public String toString() { return "AWTGLPixelBuffer["+toString(null).toString()+"]"; } @@ -213,6 +215,7 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { } /** Return the last {@link #allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocated} {@link AWTGLPixelBuffer} w/ {@link GLPixelAttributes#componentCount}. */ + @Override public AWTGLPixelBuffer getSingleBuffer(GLPixelAttributes pixelAttributes) { return 4 == pixelAttributes.componentCount ? singleRGBA4 : singleRGB3; } @@ -221,6 +224,7 @@ public class AWTGLPixelBuffer extends GLPixelBuffer { * Initializes the single {@link AWTGLPixelBuffer} w/ a given size, if not yet {@link #allocate(GL, GLPixelAttributes, int, int, int, boolean, int) allocated}. * @return the newly initialized single {@link AWTGLPixelBuffer}, or null if already allocated. */ + @Override public AWTGLPixelBuffer initSingleton(int componentCount, int width, int height, int depth, boolean pack) { if( 4 == componentCount ) { if( null != singleRGBA4 ) { diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java index 6e504c089..73d06cae0 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java @@ -755,6 +755,7 @@ public class TextRenderer { // Iterate through the contents of the backing store, removing // text strings that haven't been used recently packer.visit(new RectVisitor() { + @Override public void visit(Rect rect) { TextData data = (TextData) rect.getUserData(); @@ -914,11 +915,13 @@ public class TextRenderer { final FPSAnimator anim = new FPSAnimator(dbgCanvas, 10); dbgFrame.addWindowListener(new WindowAdapter() { + @Override public void windowClosing(WindowEvent e) { // Run this on another thread than the AWT event queue to // make sure the call to Animator.stop() completes before // exiting new Thread(new Runnable() { + @Override public void run() { anim.stop(); } @@ -1009,12 +1012,14 @@ public class TextRenderer { mCurrentIndex = 0; } + @Override public char last() { mCurrentIndex = Math.max(0, mLength - 1); return current(); } + @Override public char current() { if ((mLength == 0) || (mCurrentIndex >= mLength)) { return CharacterIterator.DONE; @@ -1023,36 +1028,43 @@ public class TextRenderer { return mSequence.charAt(mCurrentIndex); } + @Override public char next() { mCurrentIndex++; return current(); } + @Override public char previous() { mCurrentIndex = Math.max(mCurrentIndex - 1, 0); return current(); } + @Override public char setIndex(int position) { mCurrentIndex = position; return current(); } + @Override public int getBeginIndex() { return 0; } + @Override public int getEndIndex() { return mLength; } + @Override public int getIndex() { return mCurrentIndex; } + @Override public Object clone() { CharSequenceIterator iter = new CharSequenceIterator(mSequence); iter.mCurrentIndex = mCurrentIndex; @@ -1060,6 +1072,7 @@ public class TextRenderer { return iter; } + @Override public char first() { if (mLength == 0) { return CharacterIterator.DONE; @@ -1143,6 +1156,7 @@ public class TextRenderer { class Manager implements BackingStoreManager { private Graphics2D g; + @Override public Object allocateBackingStore(int w, int h) { // FIXME: should consider checking Font's attributes to see // whether we're likely to need to support a full RGBA backing @@ -1165,10 +1179,12 @@ public class TextRenderer { return renderer; } + @Override public void deleteBackingStore(Object backingStore) { ((TextureRenderer) backingStore).dispose(); } + @Override public boolean preExpand(Rect cause, int attemptNumber) { // Only try this one time; clear out potentially obsolete entries // NOTE: this heuristic and the fact that it clears the used bit @@ -1204,6 +1220,7 @@ public class TextRenderer { return false; } + @Override public boolean additionFailed(Rect cause, int attemptNumber) { // Heavy hammer -- might consider doing something different packer.clear(); @@ -1222,10 +1239,12 @@ public class TextRenderer { return false; } + @Override public boolean canCompact() { return true; } + @Override public void beginMovement(Object oldBackingStore, Object newBackingStore) { // Exit the begin / end pair if necessary if (inBeginEndPair) { @@ -1259,6 +1278,7 @@ public class TextRenderer { g = newRenderer.createGraphics(); } + @Override public void move(Object oldBackingStore, Rect oldLocation, Object newBackingStore, Rect newLocation) { TextureRenderer oldRenderer = (TextureRenderer) oldBackingStore; @@ -1280,6 +1300,7 @@ public class TextRenderer { } } + @Override public void endMovement(Object oldBackingStore, Object newBackingStore) { g.dispose(); @@ -1316,10 +1337,12 @@ public class TextRenderer { } public static class DefaultRenderDelegate implements RenderDelegate { + @Override public boolean intensityOnly() { return true; } + @Override public Rectangle2D getBounds(CharSequence str, Font font, FontRenderContext frc) { return getBounds(font.createGlyphVector(frc, @@ -1327,20 +1350,24 @@ public class TextRenderer { frc); } + @Override public Rectangle2D getBounds(String str, Font font, FontRenderContext frc) { return getBounds(font.createGlyphVector(frc, str), frc); } + @Override public Rectangle2D getBounds(GlyphVector gv, FontRenderContext frc) { return gv.getVisualBounds(); } + @Override public void drawGlyphVector(Graphics2D graphics, GlyphVector str, int x, int y) { graphics.drawGlyphVector(str, x, y); } + @Override public void draw(Graphics2D graphics, String str, int x, int y) { graphics.drawString(str, x, y); } @@ -1896,6 +1923,7 @@ public class TextRenderer { this.frame = frame; } + @Override public void display(GLAutoDrawable drawable) { GL2 gl = GLContext.getCurrentGL().getGL2(); gl.glClear(GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_COLOR_BUFFER_BIT); @@ -1913,6 +1941,7 @@ public class TextRenderer { if ((frame.getWidth() != w) || (frame.getHeight() != h)) { EventQueue.invokeLater(new Runnable() { + @Override public void run() { frame.setSize(w, h); } @@ -1920,6 +1949,7 @@ public class TextRenderer { } } + @Override public void dispose(GLAutoDrawable drawable) { glu.destroy(); glu=null; @@ -1927,9 +1957,11 @@ public class TextRenderer { } // Unused methods + @Override public void init(GLAutoDrawable drawable) { } + @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java index 68c1d0fec..6f16cc4fe 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java @@ -514,6 +514,7 @@ public class ShaderCode { id=-1; } + @Override public boolean equals(Object obj) { if(this==obj) { return true; } if(obj instanceof ShaderCode) { @@ -521,9 +522,11 @@ public class ShaderCode { } return false; } + @Override public int hashCode() { return id; } + @Override public String toString() { StringBuilder buf = new StringBuilder("ShaderCode[id="+id+", type="+shaderTypeStr()+", valid="+valid+", shader: "); for(int i=0; i= other.h()); } + @Override public String toString() { return "[Rect x: " + x() + " y: " + y() + " w: " + w() + " h: " + h() + "]"; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/packrect/RectanglePacker.java b/src/jogl/classes/com/jogamp/opengl/util/packrect/RectanglePacker.java index a9d609745..2ee6a79b3 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/packrect/RectanglePacker.java +++ b/src/jogl/classes/com/jogamp/opengl/util/packrect/RectanglePacker.java @@ -61,12 +61,14 @@ public class RectanglePacker { private int maxHeight = -1; static class RectHComparator implements Comparator { + @Override public int compare(Object o1, Object o2) { Rect r1 = (Rect) o1; Rect r2 = (Rect) o2; return r2.h() - r1.h(); } + @Override public boolean equals(Object obj) { return this == obj; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java b/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java index fd026d76e..584cacf8c 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java @@ -188,6 +188,7 @@ public class Texture { /** The texture coordinates corresponding to the entire image. */ private TextureCoords coords; + @Override public String toString() { return "Texture[target 0x"+Integer.toHexString(target)+", name "+texID+", "+ imgWidth+"/"+texWidth+" x "+imgHeight+"/"+texHeight+", y-flip "+mustFlipVertically+ diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java index 63f100630..ba59f89c5 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java @@ -94,5 +94,6 @@ public class TextureCoords { rectangle. */ public float top() { return top; } + @Override public String toString() { return "TexCoord[h: "+left+" - "+right+", v: "+bottom+" - "+top+"]"; } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java index 28029efc5..5d88a76c0 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java @@ -499,6 +499,7 @@ public class TextureData { public void flush(); } + @Override public String toString() { return "TextureData["+width+"x"+height+", y-flip "+mustFlipVertically+", internFormat 0x"+Integer.toHexString(internalFormat)+", "+ pixelAttributes+", border "+border+", estSize "+estimatedMemorySize+", alignment "+alignment+", rowlen "+rowLength; diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java index b6d89d6d2..67ab5176d 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java @@ -914,6 +914,7 @@ public class TextureIO { //---------------------------------------------------------------------- // DDS provider -- supports files only for now static class DDSTextureProvider implements TextureProvider { + @Override public TextureData newTextureData(GLProfile glp, File file, int internalFormat, int pixelFormat, @@ -928,6 +929,7 @@ public class TextureIO { return null; } + @Override public TextureData newTextureData(GLProfile glp, InputStream stream, int internalFormat, int pixelFormat, @@ -944,6 +946,7 @@ public class TextureIO { return null; } + @Override public TextureData newTextureData(GLProfile glp, URL url, int internalFormat, int pixelFormat, @@ -999,6 +1002,7 @@ public class TextureIO { } } TextureData.Flusher flusher = new TextureData.Flusher() { + @Override public void flush() { image.close(); } @@ -1042,6 +1046,7 @@ public class TextureIO { //---------------------------------------------------------------------- // Base class for SGI RGB and TGA image providers static abstract class StreamBasedTextureProvider implements TextureProvider { + @Override public TextureData newTextureData(GLProfile glp, File file, int internalFormat, int pixelFormat, @@ -1062,6 +1067,7 @@ public class TextureIO { } } + @Override public TextureData newTextureData(GLProfile glp, URL url, int internalFormat, int pixelFormat, @@ -1079,6 +1085,7 @@ public class TextureIO { //---------------------------------------------------------------------- // SGI RGB image provider static class SGITextureProvider extends StreamBasedTextureProvider { + @Override public TextureData newTextureData(GLProfile glp, InputStream stream, int internalFormat, int pixelFormat, @@ -1114,6 +1121,7 @@ public class TextureIO { //---------------------------------------------------------------------- // TGA (Targa) image provider static class TGATextureProvider extends StreamBasedTextureProvider { + @Override public TextureData newTextureData(GLProfile glp, InputStream stream, int internalFormat, int pixelFormat, @@ -1151,6 +1159,7 @@ public class TextureIO { //---------------------------------------------------------------------- // PNG image provider static class PNGTextureProvider extends StreamBasedTextureProvider { + @Override public TextureData newTextureData(GLProfile glp, InputStream stream, int internalFormat, int pixelFormat, @@ -1188,6 +1197,7 @@ public class TextureIO { //---------------------------------------------------------------------- // JPEG image provider static class JPGTextureProvider extends StreamBasedTextureProvider { + @Override public TextureData newTextureData(GLProfile glp, InputStream stream, int internalFormat, int pixelFormat, @@ -1226,6 +1236,7 @@ public class TextureIO { // DDS texture writer // static class DDSTextureWriter implements TextureWriter { + @Override public boolean write(File file, TextureData data) throws IOException { if (DDS.equals(IOUtil.getFileSuffix(file))) { @@ -1276,6 +1287,7 @@ public class TextureIO { // SGI (rgb) texture writer // static class SGITextureWriter implements TextureWriter { + @Override public boolean write(File file, TextureData data) throws IOException { String fileSuffix = IOUtil.getFileSuffix(file); @@ -1321,6 +1333,7 @@ public class TextureIO { // TGA (Targa) texture writer static class TGATextureWriter implements TextureWriter { + @Override public boolean write(File file, TextureData data) throws IOException { if (TGA.equals(IOUtil.getFileSuffix(file))) { @@ -1371,6 +1384,7 @@ public class TextureIO { // PNG texture writer static class PNGTextureWriter implements TextureWriter { + @Override public boolean write(File file, TextureData data) throws IOException { if (PNG.equals(IOUtil.getFileSuffix(file))) { // See whether the PNG writer can handle this TextureData diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java index e4f72abf0..c34e019c2 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java @@ -124,6 +124,7 @@ public interface TextureSequence { public final Texture getTexture() { return texture; } + @Override public String toString() { return "TextureFrame[pts " + pts + " ms, l " + duration + " ms, texID "+ (null != texture ? texture.getTextureObject() : 0) + "]"; } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureState.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureState.java index c8437d07c..d8320c690 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureState.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureState.java @@ -158,6 +158,7 @@ public class TextureState { public final int getWrapT() { return state[5]; } + @Override public final String toString() { return "TextureState[unit "+(state[0] - GL.GL_TEXTURE0)+", target "+toHexString(target)+ ": obj "+toHexString(state[1])+ diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/JPEGImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/JPEGImage.java index 471938754..2081788ba 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/JPEGImage.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/JPEGImage.java @@ -112,6 +112,7 @@ public class JPEGImage { data.put(i++, Cr); } + @Override public String toString() { return "JPEGPixels["+width+"x"+height+", sourceComp "+sourceComponents+", sourceCS "+sourceCS+", storageCS "+storageCS+", storageComp "+storageComponents+"]"; } @@ -171,5 +172,6 @@ public class JPEGImage { (bottom-to-top) order for calls to glTexImage2D. */ public ByteBuffer getData() { return data; } + @Override public String toString() { return "JPEGImage["+pixelWidth+"x"+pixelHeight+", bytesPerPixel "+bytesPerPixel+", reversedChannels "+reversedChannels+", "+pixelStorage+", "+data+"]"; } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataInputStream.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataInputStream.java index 4020ab3c0..3c90d96e4 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataInputStream.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataInputStream.java @@ -82,38 +82,45 @@ public class LEDataInputStream extends FilterInputStream implements DataInput dataIn = new DataInputStream(in); } + @Override public void close() throws IOException { dataIn.close(); // better close as we create it. // this will close underlying as well. } + @Override public synchronized final int read(byte b[]) throws IOException { return dataIn.read(b, 0, b.length); } + @Override public synchronized final int read(byte b[], int off, int len) throws IOException { int rl = dataIn.read(b, off, len); return rl; } + @Override public final void readFully(byte b[]) throws IOException { dataIn.readFully(b, 0, b.length); } + @Override public final void readFully(byte b[], int off, int len) throws IOException { dataIn.readFully(b, off, len); } + @Override public final int skipBytes(int n) throws IOException { return dataIn.skipBytes(n); } + @Override public final boolean readBoolean() throws IOException { int ch = dataIn.read(); @@ -122,6 +129,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput return (ch != 0); } + @Override public final byte readByte() throws IOException { int ch = dataIn.read(); @@ -130,6 +138,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput return (byte)(ch); } + @Override public final int readUnsignedByte() throws IOException { int ch = dataIn.read(); @@ -138,6 +147,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput return ch; } + @Override public final short readShort() throws IOException { int ch1 = dataIn.read(); @@ -147,6 +157,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput return (short)((ch1 << 0) + (ch2 << 8)); } + @Override public final int readUnsignedShort() throws IOException { int ch1 = dataIn.read(); @@ -156,6 +167,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput return (ch1 << 0) + (ch2 << 8); } + @Override public final char readChar() throws IOException { int ch1 = dataIn.read(); @@ -165,6 +177,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput return (char)((ch1 << 0) + (ch2 << 8)); } + @Override public final int readInt() throws IOException { int ch1 = dataIn.read(); @@ -176,6 +189,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput return ((ch1 << 0) + (ch2 << 8) + (ch3 << 16) + (ch4 << 24)); } + @Override public final long readLong() throws IOException { int i1 = readInt(); @@ -183,11 +197,13 @@ public class LEDataInputStream extends FilterInputStream implements DataInput return ((long)i1 & 0xFFFFFFFFL) + ((long)i2 << 32); } + @Override public final float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } + @Override public final double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); @@ -197,6 +213,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput * dont call this it is not implemented. * @return empty new string **/ + @Override public final String readLine() throws IOException { return new String(); @@ -206,6 +223,7 @@ public class LEDataInputStream extends FilterInputStream implements DataInput * dont call this it is not implemented * @return empty new string **/ + @Override public final String readUTF() throws IOException { return new String(); diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataOutputStream.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataOutputStream.java index a7101a576..93b097500 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataOutputStream.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/LEDataOutputStream.java @@ -78,43 +78,51 @@ public class LEDataOutputStream extends FilterOutputStream implements DataOutput dataOut = new DataOutputStream(out); } + @Override public void close() throws IOException { dataOut.close(); // better close as we create it. // this will close underlying as well. } + @Override public synchronized final void write(byte b[]) throws IOException { dataOut.write(b, 0, b.length); } + @Override public synchronized final void write(byte b[], int off, int len) throws IOException { dataOut.write(b, off, len); } + @Override public final void write(int b) throws IOException { dataOut.write(b); } + @Override public final void writeBoolean(boolean v) throws IOException { dataOut.writeBoolean(v); } + @Override public final void writeByte(int v) throws IOException { dataOut.writeByte(v); } /** Don't call this -- not implemented */ + @Override public final void writeBytes(String s) throws IOException { throw new UnsupportedOperationException(); } + @Override public final void writeChar(int v) throws IOException { dataOut.writeChar(((v >> 8) & 0xff) | @@ -122,21 +130,25 @@ public class LEDataOutputStream extends FilterOutputStream implements DataOutput } /** Don't call this -- not implemented */ + @Override public final void writeChars(String s) throws IOException { throw new UnsupportedOperationException(); } + @Override public final void writeDouble(double v) throws IOException { writeLong(Double.doubleToRawLongBits(v)); } + @Override public final void writeFloat(float v) throws IOException { writeInt(Float.floatToRawIntBits(v)); } + @Override public final void writeInt(int v) throws IOException { dataOut.writeInt((v >>> 24) | @@ -145,12 +157,14 @@ public class LEDataOutputStream extends FilterOutputStream implements DataOutput (v << 24)); } + @Override public final void writeLong(long v) throws IOException { writeInt((int) v); writeInt((int) (v >>> 32)); } + @Override public final void writeShort(int v) throws IOException { dataOut.writeShort(((v >> 8) & 0xff) | @@ -158,6 +172,7 @@ public class LEDataOutputStream extends FilterOutputStream implements DataOutput } /** Don't call this -- not implemented */ + @Override public final void writeUTF(String s) throws IOException { throw new UnsupportedOperationException(); diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java index 43b8eebe6..cabf4ebc5 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java @@ -84,6 +84,7 @@ public class NetPbmTextureWriter implements TextureWriter { public String getSuffix() { return (magic==6)?PPM:PAM; } + @Override public boolean write(File file, TextureData data) throws IOException { boolean res; final int magic_old = magic; diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java index bfde1bfac..71cbbf97e 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java @@ -314,5 +314,6 @@ public class PNGImage { } } + @Override public String toString() { return "PNGImage["+pixelWidth+"x"+pixelHeight+", dpi "+dpi[0]+" x "+dpi[1]+", bytesPerPixel "+bytesPerPixel+", reversedChannels "+reversedChannels+", "+data+"]"; } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java index fd96fba80..cbc8e652f 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java @@ -126,6 +126,7 @@ public class SGIImage { in.read(tmp); } + @Override public String toString() { return ("magic: " + magic + " storage: " + (int) storage + @@ -226,6 +227,7 @@ public class SGIImage { (bottom-to-top) order for calls to glTexImage2D. */ public byte[] getData() { return data; } + @Override public String toString() { return header.toString(); } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java index df9430a26..15cd63eb3 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java @@ -199,6 +199,7 @@ public class TGAImage { public byte[] imageIDbuf() { return imageIDbuf; } public String imageID() { return imageID; } + @Override public String toString() { return "TGA Header " + " id length: " + idLength + diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureProvider.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureProvider.java index f23cb74bf..18ad429d2 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureProvider.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureProvider.java @@ -54,6 +54,7 @@ import com.jogamp.opengl.util.texture.spi.*; public class IIOTextureProvider implements TextureProvider { private static final boolean DEBUG = Debug.debug("TextureIO"); + @Override public TextureData newTextureData(GLProfile glp, File file, int internalFormat, int pixelFormat, @@ -70,6 +71,7 @@ public class IIOTextureProvider implements TextureProvider { return new AWTTextureData(glp, internalFormat, pixelFormat, mipmap, img); } + @Override public TextureData newTextureData(GLProfile glp, InputStream stream, int internalFormat, int pixelFormat, @@ -86,6 +88,7 @@ public class IIOTextureProvider implements TextureProvider { return new AWTTextureData(glp, internalFormat, pixelFormat, mipmap, img); } + @Override public TextureData newTextureData(GLProfile glp, URL url, int internalFormat, int pixelFormat, diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureWriter.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureWriter.java index 438ab6cc2..be82e4fb8 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureWriter.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/awt/IIOTextureWriter.java @@ -53,6 +53,7 @@ import com.jogamp.opengl.util.texture.*; import com.jogamp.opengl.util.texture.spi.*; public class IIOTextureWriter implements TextureWriter { + @Override public boolean write(File file, TextureData data) throws IOException { int pixelFormat = data.getPixelFormat(); diff --git a/src/jogl/classes/javax/media/opengl/GLArrayData.java b/src/jogl/classes/javax/media/opengl/GLArrayData.java index 4025170cf..97f58a92a 100644 --- a/src/jogl/classes/javax/media/opengl/GLArrayData.java +++ b/src/jogl/classes/javax/media/opengl/GLArrayData.java @@ -201,6 +201,7 @@ public interface GLArrayData { */ public int getStride(); + @Override public String toString(); public void destroy(GL gl); diff --git a/src/jogl/classes/javax/media/opengl/GLDebugMessage.java b/src/jogl/classes/javax/media/opengl/GLDebugMessage.java index 1032cf929..acb33b058 100644 --- a/src/jogl/classes/javax/media/opengl/GLDebugMessage.java +++ b/src/jogl/classes/javax/media/opengl/GLDebugMessage.java @@ -202,6 +202,7 @@ public class GLDebugMessage { return sb; } + @Override public String toString() { return toString(null).toString(); } diff --git a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java index e486e2bfd..26bafd961 100644 --- a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java +++ b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java @@ -134,6 +134,7 @@ public abstract class GLDrawableFactory { private static final void initSingletonImpl() { NativeWindowFactory.initSingleton(); NativeWindowFactory.addCustomShutdownHook(false /* head */, new Runnable() { + @Override public void run() { shutdown0(); } diff --git a/src/jogl/classes/javax/media/opengl/GLProfile.java b/src/jogl/classes/javax/media/opengl/GLProfile.java index 15300e397..35dcce0f7 100644 --- a/src/jogl/classes/javax/media/opengl/GLProfile.java +++ b/src/jogl/classes/javax/media/opengl/GLProfile.java @@ -121,11 +121,13 @@ public class GLProfile { // run the whole static initialization privileged to speed up, // since this skips checking further access AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { Platform.initSingleton(); // Performance hack to trigger classloading of the GL classes impl, which makes up to 12%, 800ms down to 700ms new Thread(new Runnable() { + @Override public void run() { final ClassLoader cl = GLProfile.class.getClassLoader(); try { @@ -1020,6 +1022,7 @@ public class GLProfile { * @return true if given Object is a GLProfile and * if both, profile and profileImpl is equal with this. */ + @Override public final boolean equals(Object o) { if(this==o) { return true; } if(o instanceof GLProfile) { @@ -1029,6 +1032,7 @@ public class GLProfile { return false; } + @Override public int hashCode() { int hash = 5; hash = 97 * hash + getImplName().hashCode(); @@ -1469,6 +1473,7 @@ public class GLProfile { return true; } + @Override public String toString() { return "GLProfile[" + getName() + "/" + getImplName() + "."+(this.isHardwareRasterizer?"hw":"sw")+"]"; } diff --git a/src/jogl/classes/javax/media/opengl/GLUniformData.java b/src/jogl/classes/javax/media/opengl/GLUniformData.java index 700bba2eb..412bfb0a9 100644 --- a/src/jogl/classes/javax/media/opengl/GLUniformData.java +++ b/src/jogl/classes/javax/media/opengl/GLUniformData.java @@ -97,6 +97,7 @@ public class GLUniformData { return sb; } + @Override public String toString() { return toString(null).toString(); } diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index f08fbafe8..8757c7a26 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -449,8 +449,14 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing _lock.unlock(); } } - private final Runnable realizeOnEDTAction = new Runnable() { public void run() { setRealizedImpl(true); } }; - private final Runnable unrealizeOnEDTAction = new Runnable() { public void run() { setRealizedImpl(false); } }; + private final Runnable realizeOnEDTAction = new Runnable() { + @Override + public void run() { setRealizedImpl(true); } + }; + private final Runnable unrealizeOnEDTAction = new Runnable() { + @Override + public void run() { setRealizedImpl(false); } + }; @Override public final void setRealized(boolean realized) { diff --git a/src/jogl/classes/javax/media/opengl/glu/GLUtessellatorCallbackAdapter.java b/src/jogl/classes/javax/media/opengl/glu/GLUtessellatorCallbackAdapter.java index bd12dfb9d..15a7bb2a1 100644 --- a/src/jogl/classes/javax/media/opengl/glu/GLUtessellatorCallbackAdapter.java +++ b/src/jogl/classes/javax/media/opengl/glu/GLUtessellatorCallbackAdapter.java @@ -64,20 +64,32 @@ package javax.media.opengl.glu; */ public class GLUtessellatorCallbackAdapter implements GLUtessellatorCallback { + @Override public void begin(int type) {} + @Override public void edgeFlag(boolean boundaryEdge) {} + @Override public void vertex(Object vertexData) {} + @Override public void end() {} // public void mesh(jogamp.opengl.tessellator.GLUmesh mesh) {} + @Override public void error(int errnum) {} + @Override public void combine(double[] coords, Object[] data, float[] weight, Object[] outData) {} + @Override public void beginData(int type, Object polygonData) {} + @Override public void edgeFlagData(boolean boundaryEdge, Object polygonData) {} + @Override public void vertexData(Object vertexData, Object polygonData) {} + @Override public void endData(Object polygonData) {} + @Override public void errorData(int errnum, Object polygonData) {} + @Override public void combineData(double[] coords, Object[] data, float[] weight, Object[] outData, Object polygonData) {} diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java b/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java index 22600cb89..012b1d1dd 100644 --- a/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java +++ b/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java @@ -46,6 +46,7 @@ public class RegionRendererImpl01 extends RegionRenderer { } + @Override protected boolean initShaderProgram(GL2ES2 gl) { final ShaderState st = rs.getShaderState(); diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/RenderStateImpl.java b/src/jogl/classes/jogamp/graph/curve/opengl/RenderStateImpl.java index 8ca29b9f0..fe2dd7363 100644 --- a/src/jogl/classes/jogamp/graph/curve/opengl/RenderStateImpl.java +++ b/src/jogl/classes/jogamp/graph/curve/opengl/RenderStateImpl.java @@ -65,8 +65,11 @@ public class RenderStateImpl extends RenderState { this(st, pointFactory, new PMVMatrix()); } + @Override public final GLUniformData getWeight() { return gcu_Weight; } + @Override public final GLUniformData getAlpha() { return gcu_Alpha; } + @Override public final GLUniformData getColorStatic() { return gcu_ColorStatic; } //public final GLUniformData getStrength() { return gcu_Strength; } diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java index 86c0db8c6..77c862ed4 100644 --- a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java +++ b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java @@ -77,6 +77,7 @@ public class VBORegion2PES2 extends GLRegion { mgl_ActiveTexture = new GLUniformData(UniformNames.gcu_TextureUnit, textureEngine); } + @Override public void update(GL2ES2 gl, RenderState rs) { if(!isDirty()) { return; @@ -194,6 +195,7 @@ public class VBORegion2PES2 extends GLRegion { int[] maxTexSize = new int[] { -1 } ; + @Override protected void drawImpl(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int[/*1*/] texWidth) { if(vp_width <=0 || vp_height <= 0 || null==texWidth || texWidth[0] <= 0){ renderRegion(gl); @@ -296,6 +298,7 @@ public class VBORegion2PES2 extends GLRegion { verticeTxtAttr.enableBuffer(gl, false); } + @Override public void destroy(GL2ES2 gl, RenderState rs) { if(DEBUG_INSTANCE) { System.err.println("VBORegion2PES2 Destroy: " + this); diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java index 0a867b45c..9feb18a12 100644 --- a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java +++ b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java @@ -48,6 +48,7 @@ public class VBORegionSPES2 extends GLRegion { super(renderModes); } + @Override protected void update(GL2ES2 gl, RenderState rs) { if(!isDirty()) { return; @@ -125,6 +126,7 @@ public class VBORegionSPES2 extends GLRegion { setDirty(false); } + @Override protected void drawImpl(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int[/*1*/] texWidth) { verticeAttr.enableBuffer(gl, true); texCoordAttr.enableBuffer(gl, true); @@ -137,6 +139,7 @@ public class VBORegionSPES2 extends GLRegion { verticeAttr.enableBuffer(gl, false); } + @Override public final void destroy(GL2ES2 gl, RenderState rs) { if(DEBUG_INSTANCE) { System.err.println("VBORegionSPES2 Destroy: " + this); diff --git a/src/jogl/classes/jogamp/graph/curve/tess/CDTriangulator2D.java b/src/jogl/classes/jogamp/graph/curve/tess/CDTriangulator2D.java index 4f48b2d20..a60f91b87 100644 --- a/src/jogl/classes/jogamp/graph/curve/tess/CDTriangulator2D.java +++ b/src/jogl/classes/jogamp/graph/curve/tess/CDTriangulator2D.java @@ -65,6 +65,7 @@ public class CDTriangulator2D implements Triangulator{ /** Reset the triangulation to initial state * Clearing cached data */ + @Override public void reset() { maxTriID = 0; vertices = new ArrayList(); @@ -72,6 +73,7 @@ public class CDTriangulator2D implements Triangulator{ loops = new ArrayList(); } + @Override public void addCurve(Outline polyline) { Loop loop = null; @@ -93,6 +95,7 @@ public class CDTriangulator2D implements Triangulator{ } } + @Override public ArrayList generate() { for(int i=0;i() { + @Override public String run() { return System.getProperty("java.home"); } @@ -81,10 +82,12 @@ public class JavaFontLoader implements FontSet { return 0 != ( bits & bit ) ; } + @Override public Font getDefault() throws IOException { return get(FAMILY_REGULAR, 0) ; // Sans Serif Regular } + @Override public Font get(int family, int style) throws IOException { Font font = (Font)fontMap.get( ( family << 8 ) | style ); if (font != null) { diff --git a/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java b/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java index 254583739..9096f7d16 100644 --- a/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java +++ b/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java @@ -71,10 +71,12 @@ public class UbuntuFontLoader implements FontSet { return 0 != ( bits & bit ) ; } + @Override public Font getDefault() throws IOException { return get(FAMILY_REGULAR, 0) ; // Sans Serif Regular } + @Override public Font get(int family, int style) throws IOException { Font font = (Font)fontMap.get( ( family << 8 ) | style ); if (font != null) { diff --git a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFont.java b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFont.java index ba6c72650..67ae6c387 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFont.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFont.java @@ -148,25 +148,31 @@ class TypecastFont implements FontInt { char2Glyph = new IntObjectHashMap(cmapentries + cmapentries/4); } + @Override public StringBuilder getName(StringBuilder sb, int nameIndex) { return font.getName(nameIndex, sb); } + @Override public String getName(int nameIndex) { return getName(null, nameIndex).toString(); } + @Override public StringBuilder getAllNames(StringBuilder sb, String separator) { return font.getAllNames(sb, separator); } + @Override public StringBuilder getFullFamilyName(StringBuilder sb) { sb = getName(sb, Font.NAME_FAMILY).append("-"); getName(sb, Font.NAME_SUBFAMILY); return sb; } + @Override public float getAdvanceWidth(int i, float pixelSize) { return font.getHmtxTable().getAdvanceWidth(i) * metrics.getScale(pixelSize); } + @Override public Metrics getMetrics() { if (metrics == null) { metrics = new TypecastHMetrics(this); @@ -174,6 +180,7 @@ class TypecastFont implements FontInt { return metrics; } + @Override public Glyph getGlyph(char symbol) { TypecastGlyph result = (TypecastGlyph) char2Glyph.get(symbol); if (null == result) { @@ -219,11 +226,13 @@ class TypecastFont implements FontInt { return result; } + @Override public ArrayList getOutlineShapes(CharSequence string, float pixelSize, Factory vertexFactory) { AffineTransform transform = new AffineTransform(vertexFactory); return TypecastRenderer.getOutlineShapes(this, string, pixelSize, transform, vertexFactory); } + @Override public float getStringWidth(CharSequence string, float pixelSize) { float width = 0; final int len = string.length(); @@ -241,6 +250,7 @@ class TypecastFont implements FontInt { return (int)(width + 0.5f); } + @Override public float getStringHeight(CharSequence string, float pixelSize) { int height = 0; @@ -257,6 +267,7 @@ class TypecastFont implements FontInt { return height; } + @Override public AABBox getStringBounds(CharSequence string, float pixelSize) { if (string == null) { return new AABBox(); @@ -287,14 +298,17 @@ class TypecastFont implements FontInt { return new AABBox(0, 0, 0, totalWidth, totalHeight,0); } + @Override final public int getNumGlyphs() { return font.getNumGlyphs(); } + @Override public boolean isPrintableChar( char c ) { return FontFactory.isPrintableChar(c); } + @Override public String toString() { return getFullFamilyName(null).toString(); } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java index 77b5a9aa9..d7db981b0 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java @@ -43,8 +43,10 @@ import com.jogamp.graph.font.Font; public class TypecastFontConstructor implements FontConstructor { + @Override public Font create(final File ffile) throws IOException { Object o = AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { OTFontCollection fontset; try { @@ -64,8 +66,10 @@ public class TypecastFontConstructor implements FontConstructor { throw new InternalError("Unexpected Object: "+o); } + @Override public Font create(final URLConnection fconn) throws IOException { return AccessController.doPrivileged(new PrivilegedAction() { + @Override public Font run() { File tf = null; int len=0; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/TypecastGlyph.java b/src/jogl/classes/jogamp/graph/font/typecast/TypecastGlyph.java index 476b3fd4e..574aeb86d 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/TypecastGlyph.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/TypecastGlyph.java @@ -79,6 +79,7 @@ public class TypecastGlyph implements FontInt.GlyphInt { return fo.floatValue(); } + @Override public String toString() { return "\nAdvance:"+ @@ -122,6 +123,7 @@ public class TypecastGlyph implements FontInt.GlyphInt { return this.advance.get(size, useFrationalMetrics); } + @Override public String toString() { return "\nMetrics:"+ @@ -173,10 +175,12 @@ public class TypecastGlyph implements FontInt.GlyphInt { this.metrics.reset(); } + @Override public Font getFont() { return this.font; } + @Override public char getSymbol() { return this.symbol; } @@ -201,6 +205,7 @@ public class TypecastGlyph implements FontInt.GlyphInt { return this.metrics.getScale(pixelSize); } + @Override public AABBox getBBox(float pixelSize) { final float size = getScale(pixelSize); AABBox newBox = getBBox().clone(); @@ -212,14 +217,17 @@ public class TypecastGlyph implements FontInt.GlyphInt { this.metrics.addAdvance(advance, size); } + @Override public float getAdvance(float pixelSize, boolean useFrationalMetrics) { return this.metrics.getAdvance(pixelSize, useFrationalMetrics); } + @Override public Path2D getPath() { return this.path; } + @Override public Path2D getPath(float pixelSize) { final float size = getScale(pixelSize); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/TypecastHMetrics.java b/src/jogl/classes/jogamp/graph/font/typecast/TypecastHMetrics.java index a6ce58ae2..ecc41e438 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/TypecastHMetrics.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/TypecastHMetrics.java @@ -61,21 +61,27 @@ class TypecastHMetrics implements Metrics { bbox = new AABBox(lowx, lowy, 0, highx, highy, 0); // invert } + @Override public final float getAscent(float pixelSize) { return getScale(pixelSize) * -hheaTable.getAscender(); // invert } + @Override public final float getDescent(float pixelSize) { return getScale(pixelSize) * -hheaTable.getDescender(); // invert } + @Override public final float getLineGap(float pixelSize) { return getScale(pixelSize) * -hheaTable.getLineGap(); // invert } + @Override public final float getMaxExtend(float pixelSize) { return getScale(pixelSize) * hheaTable.getXMaxExtent(); } + @Override public final float getScale(float pixelSize) { return pixelSize * unitsPerEM_Inv; } + @Override public final AABBox getBBox(float pixelSize) { AABBox res = new AABBox(bbox.getLow(), bbox.getHigh()); res.scale(getScale(pixelSize)); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFont.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFont.java index 8fc4be92d..7c3b32e2c 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFont.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFont.java @@ -283,6 +283,7 @@ public class OTFont { _glyf = (GlyfTable) getTable(Table.glyf); } + @Override public String toString() { if (_tableDirectory != null) { return _tableDirectory.toString(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java index b6626a9cc..60975dd52 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java @@ -47,10 +47,12 @@ public class BaseTable implements Table { _coordinate = di.readShort(); } + @Override public int getBaseCoordFormat() { return 1; } + @Override public short getCoordinate() { return _coordinate; } @@ -69,10 +71,12 @@ public class BaseTable implements Table { _baseCoordPoint = di.readUnsignedShort(); } + @Override public int getBaseCoordFormat() { return 2; } + @Override public short getCoordinate() { return _coordinate; } @@ -89,10 +93,12 @@ public class BaseTable implements Table { _deviceTableOffset = di.readUnsignedShort(); } + @Override public int getBaseCoordFormat() { return 2; } + @Override public short getCoordinate() { return _coordinate; } @@ -211,6 +217,7 @@ public class BaseTable implements Table { } } + @Override public String toString() { StringBuilder sb = new StringBuilder() .append("\nBaseScript BaseScriptT").append(Integer.toHexString(_thisOffset)) @@ -273,6 +280,7 @@ public class BaseTable implements Table { } } + @Override public String toString() { StringBuilder sb = new StringBuilder() .append("\nBaseScriptList BaseScriptListT").append(Integer.toHexString(_thisOffset)) @@ -305,6 +313,7 @@ public class BaseTable implements Table { } } + @Override public String toString() { StringBuilder sb = new StringBuilder() .append("\nBaseTagList BaseTagListT").append(Integer.toHexString(_thisOffset)) @@ -338,6 +347,7 @@ public class BaseTable implements Table { } } + @Override public String toString() { return new StringBuilder() .append("\nAxis AxisT").append(Integer.toHexString(_thisOffset)) @@ -403,10 +413,12 @@ public class BaseTable implements Table { return String.valueOf(c); } + @Override public int getType() { return BASE; } + @Override public String toString() { StringBuilder sb = new StringBuilder() .append("; 'BASE' Table - Baseline\n;-------------------------------------\n\n") @@ -429,6 +441,7 @@ public class BaseTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java index 62486fb7f..a36a49923 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java @@ -164,6 +164,7 @@ public class CffTable implements Table { return ""; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); Enumeration keys = _entries.keys(); @@ -220,6 +221,7 @@ public class CffTable implements Table { return _data; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DICT\n"); @@ -254,6 +256,7 @@ public class CffTable implements Table { return new Dict(getData(), offset, len); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < getCount(); ++i) { @@ -287,6 +290,7 @@ public class CffTable implements Table { return name; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < getCount(); ++i) { @@ -321,6 +325,7 @@ public class CffTable implements Table { } } + @Override public String toString() { int nonStandardBase = CffStandardStrings.standardStrings.length; StringBuilder sb = new StringBuilder(); @@ -388,10 +393,12 @@ public class CffTable implements Table { } } + @Override public int getFormat() { return 0; } + @Override public int getSID(int gid) { if (gid == 0) { return 0; @@ -413,10 +420,12 @@ public class CffTable implements Table { } } + @Override public int getFormat() { return 1; } + @Override public int getSID(int gid) { if (gid == 0) { return 0; @@ -448,10 +457,12 @@ public class CffTable implements Table { } } + @Override public int getFormat() { return 2; } + @Override public int getSID(int gid) { if (gid == 0) { return 0; @@ -586,10 +597,12 @@ public class CffTable implements Table { return _charstringsArray[fontIndex].length; } + @Override public int getType() { return CFF; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'CFF' Table - Compact Font Format\n---------------------------------\n"); @@ -614,6 +627,7 @@ public class CffTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java index 93ff60988..7a7b51890 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java @@ -133,10 +133,12 @@ public class CharstringType2 extends Charstring { _globalSubrIndex = globalSubrIndex; } + @Override public int getIndex() { return _index; } + @Override public String getName() { return _name; } @@ -223,6 +225,7 @@ public class CharstringType2 extends Charstring { return _ip < _offset + _length; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); resetIP(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat1.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat1.java index 1079aeed4..94910e4f6 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat1.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat1.java @@ -32,6 +32,7 @@ public class ClassDefFormat1 extends ClassDef { } } + @Override public int getFormat() { return 1; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat2.java index 59bc7b329..9906ecfb1 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat2.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ClassDefFormat2.java @@ -30,6 +30,7 @@ public class ClassDefFormat2 extends ClassDef { } } + @Override public int getFormat() { return 2; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java index 62ce5ae4c..f7054852a 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java @@ -122,6 +122,7 @@ public abstract class CmapFormat { public abstract int mapCharCode(int charCode); + @Override public String toString() { return new StringBuilder() .append("format: ") diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat0.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat0.java index 2093158bd..dd1ede232 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat0.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat0.java @@ -71,10 +71,12 @@ public class CmapFormat0 extends CmapFormat { } } + @Override public int getRangeCount() { return 1; } + @Override public Range getRange(int index) throws ArrayIndexOutOfBoundsException { if (index != 0) { throw new ArrayIndexOutOfBoundsException(); @@ -82,6 +84,7 @@ public class CmapFormat0 extends CmapFormat { return new Range(0, 255); } + @Override public int mapCharCode(int charCode) { if (0 <= charCode && charCode < 256) { return _glyphIdArray[charCode]; diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat2.java index 222c93852..d071e9421 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat2.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat2.java @@ -118,10 +118,12 @@ public class CmapFormat2 extends CmapFormat { } } + @Override public int getRangeCount() { return _subHeaders.length; } + @Override public Range getRange(int index) throws ArrayIndexOutOfBoundsException { if (index < 0 || index >= _subHeaders.length) { throw new ArrayIndexOutOfBoundsException(); @@ -144,6 +146,7 @@ public class CmapFormat2 extends CmapFormat { _subHeaders[index]._entryCount - 1)); } + @Override public int mapCharCode(int charCode) { // Get the appropriate subheader diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java index ef65867af..2ae23d031 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java @@ -110,10 +110,12 @@ public class CmapFormat4 extends CmapFormat { // } } + @Override public int getRangeCount() { return _segCount; } + @Override public Range getRange(int index) throws ArrayIndexOutOfBoundsException { if (index < 0 || index >= _segCount) { throw new ArrayIndexOutOfBoundsException(); @@ -121,6 +123,7 @@ public class CmapFormat4 extends CmapFormat { return new Range(_startCode[index], _endCode[index]); } + @Override public int mapCharCode(int charCode) { try { for (int i = 0; i < _segCount; i++) { @@ -142,6 +145,7 @@ public class CmapFormat4 extends CmapFormat { return 0; } + @Override public String toString() { return new StringBuilder() .append(super.toString()) diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat6.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat6.java index a22e33244..2a33d8d40 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat6.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat6.java @@ -73,14 +73,17 @@ public class CmapFormat6 extends CmapFormat { //di.skipBytes(_length - 4); } + @Override public int getRangeCount() { return 0; } + @Override public Range getRange(int index) throws ArrayIndexOutOfBoundsException { throw new ArrayIndexOutOfBoundsException(); } + @Override public int mapCharCode(int charCode) { return 0; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormatUnknown.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormatUnknown.java index 3544b6f62..392683bcd 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormatUnknown.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormatUnknown.java @@ -40,14 +40,17 @@ public class CmapFormatUnknown extends CmapFormat { di.skipBytes(_length - 4); } + @Override public int getRangeCount() { return 0; } + @Override public Range getRange(int index) throws ArrayIndexOutOfBoundsException { throw new ArrayIndexOutOfBoundsException(); } + @Override public int mapCharCode(int charCode) { return 0; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java index 47f6c470d..4833318d5 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java @@ -90,6 +90,7 @@ public class CmapIndexEntry implements Comparable { _format = format; } + @Override public String toString() { return new StringBuilder() .append("platform id: ") @@ -104,6 +105,7 @@ public class CmapIndexEntry implements Comparable { .append(_offset).toString(); } + @Override public int compareTo(java.lang.Object obj) { CmapIndexEntry entry = (CmapIndexEntry) obj; if (getOffset() < entry.getOffset()) { diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java index 016efa093..2cdddb3ef 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java @@ -130,10 +130,12 @@ public class CmapTable implements Table { return null; } + @Override public int getType() { return cmap; } + @Override public String toString() { StringBuilder sb = new StringBuilder().append("cmap\n"); @@ -155,6 +157,7 @@ public class CmapTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CoverageFormat1.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CoverageFormat1.java index 712da54df..715bf11ec 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CoverageFormat1.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CoverageFormat1.java @@ -72,10 +72,12 @@ public class CoverageFormat1 extends Coverage { } } + @Override public int getFormat() { return 1; } + @Override public int findGlyph(int glyphId) { for (int i = 0; i < _glyphCount; i++) { if (_glyphIds[i] == glyphId) { diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CoverageFormat2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CoverageFormat2.java index 7196ed595..bd2a28f79 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CoverageFormat2.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CoverageFormat2.java @@ -72,10 +72,12 @@ public class CoverageFormat2 extends Coverage { } } + @Override public int getFormat() { return 2; } + @Override public int findGlyph(int glyphId) { for (int i = 0; i < _rangeCount; i++) { int n = _rangeRecords[i].getCoverageIndex(glyphId); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java index 867ef1823..9e1c47de9 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java @@ -29,6 +29,7 @@ public class CvtTable implements Table { } } + @Override public int getType() { return cvt; } @@ -37,6 +38,7 @@ public class CvtTable implements Table { return values; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'cvt ' Table - Control Value Table\n----------------------------------\n"); @@ -54,6 +56,7 @@ public class CvtTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java index 7abcec0ce..e34fa32e8 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java @@ -71,6 +71,7 @@ public class DirectoryEntry implements Cloneable { _length = di.readInt(); } + @Override public Object clone() { try { return super.clone(); @@ -104,6 +105,7 @@ public class DirectoryEntry implements Cloneable { .toString(); } + @Override public String toString() { return new StringBuilder() .append("'").append(getTagAsString()) diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java index f25c595d0..2b85f52d8 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java @@ -45,6 +45,7 @@ public class DsigTable implements Table { * Get the table type, as a table directory value. * @return The table type */ + @Override public int getType() { return DSIG; } @@ -55,10 +56,12 @@ public class DsigTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return de; } + @Override public String toString() { StringBuilder sb = new StringBuilder().append("DSIG\n"); for (int i = 0; i < numSigs; i++) { diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FpgmTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FpgmTable.java index b662265d9..467a4f360 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FpgmTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FpgmTable.java @@ -26,10 +26,12 @@ public class FpgmTable extends Program implements Table { readInstructions(di, de.getLength()); } + @Override public int getType() { return fpgm; } + @Override public String toString() { return Disassembler.disassemble(getInstructions(), 0); } @@ -40,6 +42,7 @@ public class FpgmTable extends Program implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java index cf4afa88e..cc87b19a4 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java @@ -30,6 +30,7 @@ public class GaspRange { rangeGaspBehavior = di.readUnsignedShort(); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" rangeMaxPPEM: ").append(rangeMaxPPEM) diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java index 45498eda1..8f91e6d00 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java @@ -34,10 +34,12 @@ public class GaspTable implements Table { } } + @Override public int getType() { return gasp; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'gasp' Table - Grid-fitting And Scan-conversion Procedure\n---------------------------------------------------------"); @@ -56,6 +58,7 @@ public class GaspTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfCompositeDescript.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfCompositeDescript.java index 50f62ed62..50e0fa339 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfCompositeDescript.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfCompositeDescript.java @@ -99,6 +99,7 @@ public class GlyfCompositeDescript extends GlyfDescript { } } + @Override public int getEndPtOfContours(int i) { GlyfCompositeComp c = getCompositeCompEndPt(i); if (c != null) { @@ -108,6 +109,7 @@ public class GlyfCompositeDescript extends GlyfDescript { return 0; } + @Override public byte getFlags(int i) { GlyfCompositeComp c = getCompositeComp(i); if (c != null) { @@ -117,6 +119,7 @@ public class GlyfCompositeDescript extends GlyfDescript { return 0; } + @Override public short getXCoordinate(int i) { GlyfCompositeComp c = getCompositeComp(i); if (c != null) { @@ -131,6 +134,7 @@ public class GlyfCompositeDescript extends GlyfDescript { return 0; } + @Override public short getYCoordinate(int i) { GlyfCompositeComp c = getCompositeComp(i); if (c != null) { @@ -145,10 +149,12 @@ public class GlyfCompositeDescript extends GlyfDescript { return 0; } + @Override public boolean isComposite() { return true; } + @Override public int getPointCount() { GlyfCompositeComp c = _components.get(_components.size()-1); GlyphDescription gd = _parentTable.getDescription(c.getGlyphIndex()); @@ -159,6 +165,7 @@ public class GlyfCompositeDescript extends GlyfDescript { } } + @Override public int getContourCount() { GlyfCompositeComp c = _components.get(_components.size()-1); return c.getFirstContour() + _parentTable.getDescription(c.getGlyphIndex()).getContourCount(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java index a7e2e7b69..6b06eb3de 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java @@ -92,26 +92,32 @@ public abstract class GlyfDescript extends Program implements GlyphDescription { return _numberOfContours; } + @Override public int getGlyphIndex() { return _glyphIndex; } + @Override public short getXMaximum() { return _xMax; } + @Override public short getXMinimum() { return _xMin; } + @Override public short getYMaximum() { return _yMax; } + @Override public short getYMinimum() { return _yMin; } + @Override public String toString() { return new StringBuilder() .append(" numberOfContours: ").append(_numberOfContours) diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java index f67162cff..c06ceaa13 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java @@ -92,30 +92,37 @@ public class GlyfSimpleDescript extends GlyfDescript { readCoords(_count, di); } + @Override public int getEndPtOfContours(int i) { return _endPtsOfContours[i]; } + @Override public byte getFlags(int i) { return _flags[i]; } + @Override public short getXCoordinate(int i) { return _xCoordinates[i]; } + @Override public short getYCoordinate(int i) { return _yCoordinates[i]; } + @Override public boolean isComposite() { return false; } + @Override public int getPointCount() { return _count; } + @Override public int getContourCount() { return getNumberOfContours(); } @@ -185,6 +192,7 @@ public class GlyfSimpleDescript extends GlyfDescript { } } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfTable.java index 34a8218d9..4b196c9e2 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfTable.java @@ -116,6 +116,7 @@ public class GlyfTable implements Table { } } + @Override public int getType() { return glyf; } @@ -126,6 +127,7 @@ public class GlyfTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GposTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GposTable.java index 9a367412d..30ecdd051 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GposTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GposTable.java @@ -45,10 +45,12 @@ public class GposTable implements Table { /** Get the table type, as a table directory value. * @return The table type */ + @Override public int getType() { return GPOS; } + @Override public String toString() { return "GPOS"; } @@ -59,6 +61,7 @@ public class GposTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GsubTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GsubTable.java index 0351c903d..c23d420a8 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GsubTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GsubTable.java @@ -99,6 +99,7 @@ public class GsubTable implements Table, LookupSubtableFactory { * 5 - Context - Replace one or more glyphs in context * 6 - Chaining - Context Replace one or more glyphs in chained context */ + @Override public LookupSubtable read( int type, DataInputStream dis, @@ -130,6 +131,7 @@ public class GsubTable implements Table, LookupSubtableFactory { /** Get the table type, as a table directory value. * @return The table type */ + @Override public int getType() { return GSUB; } @@ -146,6 +148,7 @@ public class GsubTable implements Table, LookupSubtableFactory { return _lookupList; } + @Override public String toString() { return "GSUB"; } @@ -174,6 +177,7 @@ public class GsubTable implements Table, LookupSubtableFactory { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java index 42f9bf0d0..64f5e6415 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java @@ -93,10 +93,12 @@ public class HdmxTable implements Table { return _records[i]; } + @Override public int getType() { return hdmx; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'hdmx' Table - Horizontal Device Metrics\n----------------------------------------\n"); @@ -124,6 +126,7 @@ public class HdmxTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java index cf7c58449..47e60f900 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java @@ -142,6 +142,7 @@ public class HeadTable implements Table { return _modified; } + @Override public int getType() { return head; } @@ -170,6 +171,7 @@ public class HeadTable implements Table { return _yMin; } + @Override public String toString() { return new StringBuilder() .append("'head' Table - Font Header\n--------------------------") @@ -199,6 +201,7 @@ public class HeadTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java index 0278929f1..242c9b139 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java @@ -92,6 +92,7 @@ public class HheaTable implements Table { return numberOfHMetrics; } + @Override public int getType() { return hhea; } @@ -100,6 +101,7 @@ public class HheaTable implements Table { return xMaxExtent; } + @Override public String toString() { return new StringBuilder() .append("'hhea' Table - Horizontal Header\n--------------------------------") @@ -129,6 +131,7 @@ public class HheaTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HmtxTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HmtxTable.java index dacd9e265..122a0a826 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HmtxTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HmtxTable.java @@ -106,10 +106,12 @@ public class HmtxTable implements Table { } } + @Override public int getType() { return hmtx; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'hmtx' Table - Horizontal Metrics\n---------------------------------\n"); @@ -135,6 +137,7 @@ public class HmtxTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat0.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat0.java index 89e6f9f11..1e7ff8c2d 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat0.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat0.java @@ -36,10 +36,12 @@ public class KernSubtableFormat0 extends KernSubtable { } } + @Override public int getKerningPairCount() { return nPairs; } + @Override public KerningPair getKerningPair(int i) { return kerningPairs[i]; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat2.java index 6f5e1f5e8..9c7fc81f9 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat2.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernSubtableFormat2.java @@ -31,10 +31,12 @@ public class KernSubtableFormat2 extends KernSubtable { array = di.readUnsignedShort(); } + @Override public int getKerningPairCount() { return 0; } + @Override public KerningPair getKerningPair(int i) { return null; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernTable.java index 1d526865a..006a86895 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/KernTable.java @@ -45,6 +45,7 @@ public class KernTable implements Table { /** Get the table type, as a table directory value. * @return The table type */ + @Override public int getType() { return kern; } @@ -55,6 +56,7 @@ public class KernTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LigatureSubstFormat1.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LigatureSubstFormat1.java index cad5e106a..1979ea586 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LigatureSubstFormat1.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LigatureSubstFormat1.java @@ -89,6 +89,7 @@ public class LigatureSubstFormat1 extends LigatureSubst { return 1; } + @Override public String getTypeAsString() { return "LigatureSubstFormat1"; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java index ce0862eea..2c7079fec 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java @@ -49,10 +49,12 @@ public class LocaTable implements Table { return _offsets[i] * _factor; } + @Override public int getType() { return loca; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'loca' Table - Index To Location Table\n--------------------------------------\n") @@ -71,6 +73,7 @@ public class LocaTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java index 9b0c8e6b4..47874cc56 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java @@ -38,10 +38,12 @@ public class LtshTable implements Table { * Get the table type, as a table directory value. * @return The table type */ + @Override public int getType() { return LTSH; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'LTSH' Table - Linear Threshold Table\n-------------------------------------") @@ -61,6 +63,7 @@ public class LtshTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java index 5ab6b51ca..abb6047fc 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java @@ -121,10 +121,12 @@ public class MaxpTable implements Table { return numGlyphs; } + @Override public int getType() { return maxp; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'maxp' Table - Maximum Profile\n------------------------------") @@ -156,6 +158,7 @@ public class MaxpTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java index 9f9822986..a1787e3e7 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java @@ -130,6 +130,7 @@ public class NameRecord { _record = sb.toString(); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameTable.java index 5b7a17d3b..ad8198b7f 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameTable.java @@ -130,6 +130,7 @@ public class NameTable implements Table { return sb; } + @Override public int getType() { return name; } @@ -140,6 +141,7 @@ public class NameTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java index 9dfbceb99..5340b297c 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java @@ -293,10 +293,12 @@ public class Os2Table implements Table { return _usMaxContext; } + @Override public int getType() { return OS_2; } + @Override public String toString() { return new StringBuilder() .append("'OS/2' Table - OS/2 and Windows Metrics\n---------------------------------------") @@ -351,6 +353,7 @@ public class Os2Table implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java index 1f6c5a1dd..771318108 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java @@ -79,6 +79,7 @@ public class Panose { return bXHeight; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.valueOf(bFamilyType)).append(" ") diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java index 6ed9b2b9c..a1f603d8f 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java @@ -65,10 +65,12 @@ public class PcltTable implements Table { * Get the table type, as a table directory value. * @return The table type */ + @Override public int getType() { return PCLT; } + @Override public String toString() { return new StringBuilder() .append("'PCLT' Table - Printer Command Language Table\n---------------------------------------------") @@ -98,6 +100,7 @@ public class PcltTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java index 46f1ac088..188b441ac 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java @@ -370,10 +370,12 @@ public class PostTable implements Table { /** Get the table type, as a table directory value. * @return The table type */ + @Override public int getType() { return post; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'post' Table - PostScript Metrics\n---------------------------------\n") @@ -416,6 +418,7 @@ public class PostTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PrepTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PrepTable.java index 2046d7fe4..4c64673b7 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PrepTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PrepTable.java @@ -26,10 +26,12 @@ public class PrepTable extends Program implements Table { readInstructions(di, de.getLength()); } + @Override public int getType() { return prep; } + @Override public String toString() { return Disassembler.disassemble(getInstructions(), 0); } @@ -40,6 +42,7 @@ public class PrepTable extends Program implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java index 15f0cd04f..31a2d17c9 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java @@ -32,6 +32,7 @@ public class SignatureBlock { di.readFully(signature); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < signatureLen; i += 16) { diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat1.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat1.java index a8df78504..e97e62a58 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat1.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat1.java @@ -73,10 +73,12 @@ public class SingleSubstFormat1 extends SingleSubst { _coverage = Coverage.read(dis); } + @Override public int getFormat() { return 1; } + @Override public int substitute(int glyphId) { int i = _coverage.findGlyph(glyphId); if (i > -1) { @@ -85,6 +87,7 @@ public class SingleSubstFormat1 extends SingleSubst { return glyphId; } + @Override public String getTypeAsString() { return "SingleSubstFormat1"; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat2.java index 2e47b2924..4d46b07b4 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat2.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SingleSubstFormat2.java @@ -78,10 +78,12 @@ public class SingleSubstFormat2 extends SingleSubst { _coverage = Coverage.read(dis); } + @Override public int getFormat() { return 2; } + @Override public int substitute(int glyphId) { int i = _coverage.findGlyph(glyphId); if (i > -1) { @@ -90,6 +92,7 @@ public class SingleSubstFormat2 extends SingleSubst { return glyphId; } + @Override public String getTypeAsString() { return "SingleSubstFormat2"; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java index 8c5678088..23ecba804 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java @@ -113,6 +113,7 @@ public class TableDirectory { return _version; } + @Override public String toString() { StringBuilder sb = new StringBuilder() .append("Offset Table\n------ -----") diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java index 28f9aa6e3..bebd7f946 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java @@ -148,10 +148,12 @@ public class VdmxTable implements Table { } } + @Override public int getType() { return VDMX; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'VDMX' Table - Precomputed Vertical Device Metrics\n") @@ -191,6 +193,7 @@ public class VdmxTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java index f42da119b..521b87cc8 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java @@ -105,6 +105,7 @@ public class VheaTable implements Table { return _numberOfLongVerMetrics; } + @Override public int getType() { return vhea; } @@ -113,6 +114,7 @@ public class VheaTable implements Table { return _yMaxExtent; } + @Override public String toString() { return new StringBuilder() .append("'vhea' Table - Vertical Header\n------------------------------") @@ -142,6 +144,7 @@ public class VheaTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VmtxTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VmtxTable.java index 348405380..1b77a6fdc 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VmtxTable.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VmtxTable.java @@ -77,10 +77,12 @@ public class VmtxTable implements Table { } } + @Override public int getType() { return vmtx; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("'vmtx' Table - Vertical Metrics\n-------------------------------\n"); @@ -106,6 +108,7 @@ public class VmtxTable implements Table { * particular table. * @return A directory entry */ + @Override public DirectoryEntry getDirectoryEntry() { return _de; } diff --git a/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Parser.java b/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Parser.java index c5a2b6e87..1159b2c17 100644 --- a/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Parser.java +++ b/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Parser.java @@ -148,6 +148,7 @@ public class Parser { instructions[2] = program; } + @Override public String toString() { StringBuilder sb = new StringBuilder(); int ip = 0; diff --git a/src/jogl/classes/jogamp/graph/geom/plane/Path2D.java b/src/jogl/classes/jogamp/graph/geom/plane/Path2D.java index c1ee17a4b..33b80d6b8 100644 --- a/src/jogl/classes/jogamp/graph/geom/plane/Path2D.java +++ b/src/jogl/classes/jogamp/graph/geom/plane/Path2D.java @@ -122,18 +122,22 @@ public final class Path2D implements Cloneable { this.t = at; } + @Override public int getWindingRule() { return p.getWindingRule(); } + @Override public boolean isDone() { return typeIndex >= p.typeSize; } + @Override public void next() { typeIndex++; } + @Override public int currentSegment(float[] coords) { if (isDone()) { throw new NoSuchElementException(iteratorOutOfBounds); @@ -256,6 +260,7 @@ public final class Path2D implements Cloneable { } } + @Override public String toString() { return "[size "+size()+", closed "+isClosed()+"]"; } diff --git a/src/jogl/classes/jogamp/opengl/Debug.java b/src/jogl/classes/jogamp/opengl/Debug.java index 74892d894..9332b670a 100644 --- a/src/jogl/classes/jogamp/opengl/Debug.java +++ b/src/jogl/classes/jogamp/opengl/Debug.java @@ -54,6 +54,7 @@ public class Debug extends PropertyAccess { static { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { PropertyAccess.addTrustedPrefix("jogl."); return null; diff --git a/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLookupHelper.java b/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLookupHelper.java index a1023acd2..c1e1d1821 100644 --- a/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLookupHelper.java +++ b/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLookupHelper.java @@ -39,6 +39,7 @@ public class DesktopGLDynamicLookupHelper extends GLDynamicLookupHelper { public final DesktopGLDynamicLibraryBundleInfo getDesktopGLBundleInfo() { return (DesktopGLDynamicLibraryBundleInfo) getBundleInfo(); } + @Override public final synchronized boolean loadGLULibrary() { /** hacky code .. where all platform GLU libs are tried ..*/ if(null==gluLib) { diff --git a/src/jogl/classes/jogamp/opengl/FPSCounterImpl.java b/src/jogl/classes/jogamp/opengl/FPSCounterImpl.java index c96f7db32..08a1fe882 100644 --- a/src/jogl/classes/jogamp/opengl/FPSCounterImpl.java +++ b/src/jogl/classes/jogamp/opengl/FPSCounterImpl.java @@ -87,16 +87,19 @@ public class FPSCounterImpl implements FPSCounter { return sb; } + @Override public String toString() { return toString(null).toString(); } + @Override public final synchronized void setUpdateFPSFrames(int frames, PrintStream out) { fpsUpdateFramesInterval = frames; fpsOutputStream = out; resetFPSCounter(); } + @Override public final synchronized void resetFPSCounter() { fpsStartTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // overwrite startTime to real init one fpsLastUpdateTime = fpsStartTime; @@ -106,34 +109,42 @@ public class FPSCounterImpl implements FPSCounter { fpsLastPeriod = 0; fpsTotalDuration=0; } + @Override public final synchronized int getUpdateFPSFrames() { return fpsUpdateFramesInterval; } + @Override public final synchronized long getFPSStartTime() { return fpsStartTime; } + @Override public final synchronized long getLastFPSUpdateTime() { return fpsLastUpdateTime; } + @Override public final synchronized long getLastFPSPeriod() { return fpsLastPeriod; } + @Override public final synchronized float getLastFPS() { return fpsLast; } + @Override public final synchronized int getTotalFPSFrames() { return fpsTotalFrames; } + @Override public final synchronized long getTotalFPSDuration() { return fpsTotalDuration; } + @Override public final synchronized float getTotalFPS() { return fpsTotal; } diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index 7c3a5922b..5f487fa6d 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -1189,6 +1189,7 @@ public abstract class GLContextImpl extends GLContext { GLEmitter by looking up anew all of its function pointers. */ protected final void resetProcAddressTable(final ProcAddressTable table) { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { table.reset(getDrawableImpl().getGLDynamicLookupHelper() ); return null; diff --git a/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java b/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java index b770f3b05..2c947693c 100644 --- a/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java +++ b/src/jogl/classes/jogamp/opengl/GLDebugMessageHandler.java @@ -109,6 +109,7 @@ public class GLDebugMessageHandler { private final long getAddressFor(final ProcAddressTable table, final String functionName) { return AccessController.doPrivileged(new PrivilegedAction() { + @Override public Long run() { try { return Long.valueOf( table.getAddressFor(functionName) ); @@ -300,6 +301,7 @@ public class GLDebugMessageHandler { public StdErrGLDebugListener(boolean threadDump) { this.threadDump = threadDump; } + @Override public void messageSent(GLDebugMessage event) { System.err.println(event); if(threadDump) { diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java index 2cf384fd7..4ce6a7121 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java @@ -80,7 +80,7 @@ public class GLDrawableHelper { /** -1 release, 0 nop, 1 claim */ private volatile int exclusiveContextSwitch; private GLAnimatorControl animatorCtrl; - private static Runnable nop = new Runnable() { public void run() {} }; + private static Runnable nop = new Runnable() { @Override public void run() {} }; public GLDrawableHelper() { reset(); @@ -493,6 +493,7 @@ public class GLDrawableHelper { final boolean isPaused = isAnimatorAnimatingOnOtherThread() && animatorCtrl.pause(); final GLEventListener[] res = new GLEventListener[] { null }; final Runnable action = new Runnable() { + @Override public void run() { res[0] = disposeGLEventListener(autoDrawable, listener, remove); } @@ -525,6 +526,7 @@ public class GLDrawableHelper { final boolean isPaused = isAnimatorAnimatingOnOtherThread() && animatorCtrl.pause(); final Runnable action = new Runnable() { + @Override public void run() { disposeAllGLEventListener(autoDrawable, remove); } diff --git a/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java index 640e181ae..39de3200d 100644 --- a/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java @@ -46,6 +46,7 @@ public abstract class GLDynamicLibraryBundleInfo implements DynamicLibraryBundle * *

                            */ + @Override public final boolean shallLinkGlobal() { return true; } /** diff --git a/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java index a22454d60..f175acf28 100644 --- a/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLOffscreenAutoDrawableImpl.java @@ -127,6 +127,7 @@ public class GLOffscreenAutoDrawableImpl extends GLAutoDrawableDelegate implemen return ((GLFBODrawableImpl)drawable).getFBObject(bufferName); } + @Override public final FBObject.TextureAttachment getTextureBuffer(int bufferName) { return ((GLFBODrawableImpl)drawable).getTextureBuffer(bufferName); } diff --git a/src/jogl/classes/jogamp/opengl/GLRunnableTask.java b/src/jogl/classes/jogamp/opengl/GLRunnableTask.java index 2238d49bc..6de92f533 100644 --- a/src/jogl/classes/jogamp/opengl/GLRunnableTask.java +++ b/src/jogl/classes/jogamp/opengl/GLRunnableTask.java @@ -52,6 +52,7 @@ public class GLRunnableTask implements GLRunnable { isFlushed = false; } + @Override public boolean run(GLAutoDrawable drawable) { boolean res = true; if(null == notifyObject) { diff --git a/src/jogl/classes/jogamp/opengl/GLWorkerThread.java b/src/jogl/classes/jogamp/opengl/GLWorkerThread.java index 979c6dc0a..100b46a5e 100644 --- a/src/jogl/classes/jogamp/opengl/GLWorkerThread.java +++ b/src/jogl/classes/jogamp/opengl/GLWorkerThread.java @@ -222,6 +222,7 @@ public class GLWorkerThread { protected static String getThreadName() { return Thread.currentThread().getName(); } static class WorkerRunnable implements Runnable { + @Override public void run() { // Notify starting thread that we're ready synchronized (lock) { diff --git a/src/jogl/classes/jogamp/opengl/MemoryObject.java b/src/jogl/classes/jogamp/opengl/MemoryObject.java index df793dadd..d10747690 100644 --- a/src/jogl/classes/jogamp/opengl/MemoryObject.java +++ b/src/jogl/classes/jogamp/opengl/MemoryObject.java @@ -59,10 +59,12 @@ public class MemoryObject { /** * @return the 32bit hash value generated via {@link HashUtil#getAddrSizeHash32_EqualDist(long, long)}. */ + @Override public int hashCode() { return hash; } + @Override public String toString() { return "MemoryObject[addr 0x"+Long.toHexString(addr)+", size 0x"+Long.toHexString(size)+", hash32: 0x"+Integer.toHexString(hash)+"]"; } diff --git a/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java b/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java index eddb36975..283ecdb9d 100644 --- a/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java +++ b/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java @@ -252,6 +252,7 @@ public class SharedResourceRunner implements Runnable { // done } + @Override public final void run() { final String threadName = getThreadName(); diff --git a/src/jogl/classes/jogamp/opengl/ThreadingImpl.java b/src/jogl/classes/jogamp/opengl/ThreadingImpl.java index 6ffe46b36..bf700d970 100644 --- a/src/jogl/classes/jogamp/opengl/ThreadingImpl.java +++ b/src/jogl/classes/jogamp/opengl/ThreadingImpl.java @@ -72,6 +72,7 @@ public class ThreadingImpl { static { threadingPlugin = AccessController.doPrivileged(new PrivilegedAction() { + @Override public ToolkitThreadingPlugin run() { final String singleThreadProp; { diff --git a/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java b/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java index cd1bb45c9..72c9ac54b 100644 --- a/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java +++ b/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java @@ -54,10 +54,12 @@ public class AWTThreadingPlugin implements ToolkitThreadingPlugin { public AWTThreadingPlugin() {} + @Override public final boolean isToolkitThread() throws GLException { return EventQueue.isDispatchThread(); } + @Override public final boolean isOpenGLThread() throws GLException { switch (ThreadingImpl.getMode()) { case ST_AWT: @@ -83,6 +85,7 @@ public class AWTThreadingPlugin implements ToolkitThreadingPlugin { } } + @Override public final void invokeOnOpenGLThread(boolean wait, Runnable r) throws GLException { switch (ThreadingImpl.getMode()) { case ST_AWT: diff --git a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java index 5faee1307..ff07b04d0 100644 --- a/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java +++ b/src/jogl/classes/jogamp/opengl/awt/AWTTilePainter.java @@ -147,6 +147,7 @@ public class AWTTilePainter { this.flipVertical = true; } + @Override public String toString() { return renderer.toString(); } public void setIsGLOriented(boolean v) { diff --git a/src/jogl/classes/jogamp/opengl/awt/Java2D.java b/src/jogl/classes/jogamp/opengl/awt/Java2D.java index 7a8ddf0b4..886cd9368 100644 --- a/src/jogl/classes/jogamp/opengl/awt/Java2D.java +++ b/src/jogl/classes/jogamp/opengl/awt/Java2D.java @@ -116,6 +116,7 @@ public class Java2D { static { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { if (DEBUG) { System.err.println("Checking for Java2D/OpenGL support"); @@ -565,6 +566,7 @@ public class Java2D { private static int getOGLUtilitiesIntField(final String name) { Integer i = AccessController.doPrivileged(new PrivilegedAction() { + @Override public Integer run() { try { Class utils = Class.forName("sun.java2d.opengl.OGLUtilities"); @@ -608,6 +610,7 @@ public class Java2D { System.err.println("Starting initialization of J2D FBO share context"); } invokeWithOGLSharedContextCurrent(device.getDefaultConfiguration(), new Runnable() { + @Override public void run() { j2dFBOShareContext = GLDrawableFactory.getFactory(GLProfile.getDefault(GLProfile.getDefaultDevice())).createExternalGLContext(); } diff --git a/src/jogl/classes/jogamp/opengl/awt/VersionApplet.java b/src/jogl/classes/jogamp/opengl/awt/VersionApplet.java index a29d1e6aa..9173a38cb 100644 --- a/src/jogl/classes/jogamp/opengl/awt/VersionApplet.java +++ b/src/jogl/classes/jogamp/opengl/awt/VersionApplet.java @@ -54,6 +54,7 @@ public class VersionApplet extends Applet { this.f = f; this.va = va; } + @Override public void windowClosing(WindowEvent ev) { f.setVisible(false); va.stop(); @@ -129,24 +130,28 @@ public class VersionApplet extends Applet { } } + @Override public void init() { System.err.println("VersionApplet: init() - begin"); my_init(); System.err.println("VersionApplet: init() - end"); } + @Override public void start() { System.err.println("VersionApplet: start() - begin"); canvas.setVisible(true); System.err.println("VersionApplet: start() - end"); } + @Override public void stop() { System.err.println("VersionApplet: stop() - begin"); canvas.setVisible(false); System.err.println("VersionApplet: stop() - end"); } + @Override public void destroy() { System.err.println("VersionApplet: destroy() - start"); my_release(); @@ -154,6 +159,7 @@ public class VersionApplet extends Applet { } class GLInfo implements GLEventListener { + @Override public void init(GLAutoDrawable drawable) { GL gl = drawable.getGL(); String s = JoglVersion.getGLInfo(gl, null).toString(); @@ -161,12 +167,15 @@ public class VersionApplet extends Applet { tareaVersion.append(s); } + @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } + @Override public void display(GLAutoDrawable drawable) { } + @Override public void dispose(GLAutoDrawable drawable) { } } diff --git a/src/jogl/classes/jogamp/opengl/egl/DesktopES2DynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/DesktopES2DynamicLibraryBundleInfo.java index 1179e2b7f..7b85c3e75 100644 --- a/src/jogl/classes/jogamp/opengl/egl/DesktopES2DynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/egl/DesktopES2DynamicLibraryBundleInfo.java @@ -47,20 +47,24 @@ public final class DesktopES2DynamicLibraryBundleInfo extends GLDynamicLibraryBu super(); } + @Override public final List getToolGetProcAddressFuncNameList() { List res = new ArrayList(); res.add("eglGetProcAddress"); return res; } + @Override public final long toolGetProcAddress(long toolGetProcAddressHandle, String funcName) { return EGL.eglGetProcAddress(toolGetProcAddressHandle, funcName); } + @Override public final boolean useToolGetProcAdressFirst(String funcName) { return true; } + @Override public final List> getToolLibNames() { final List> libsList = new ArrayList>(); final List libsGL = new ArrayList(); @@ -90,6 +94,7 @@ public final class DesktopES2DynamicLibraryBundleInfo extends GLDynamicLibraryBu return libsList; } + @Override public final List getGlueLibNames() { return glueLibNames; } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java index 89f34432d..3d864ad76 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java @@ -65,6 +65,7 @@ public class EGLDisplayUtil { this.createdStack = DEBUG ? new Throwable() : null; } + @Override public String toString() { return "EGLDisplay[0x"+Long.toHexString(eglDisplay)+": refCnt "+refCount+"]"; } @@ -248,9 +249,11 @@ public class EGLDisplayUtil { } public static final EGLGraphicsDevice.EGLDisplayLifecycleCallback eglLifecycleCallback = new EGLGraphicsDevice.EGLDisplayLifecycleCallback() { + @Override public long eglGetAndInitDisplay(long[] nativeDisplayID) { return eglGetDisplayAndInitialize(nativeDisplayID); } + @Override public void eglTerminate(long eglDisplayHandle) { EGLDisplayUtil.eglTerminate(eglDisplayHandle); } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java index bf269c548..ab28fb3fb 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java @@ -115,6 +115,7 @@ public abstract class EGLDrawable extends GLDrawableImpl { } } + @Override protected void destroyHandle() { final EGLWrappedSurface eglws = (EGLWrappedSurface) surface; if(DEBUG) { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java index 9ffcea864..361ec26ff 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java @@ -35,6 +35,7 @@ public final class EGLES1DynamicLibraryBundleInfo extends EGLDynamicLibraryBundl super(); } + @Override public final List> getToolLibNames() { final List> libsList = new ArrayList>(); { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java index de1f0a42e..74738463f 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java @@ -40,6 +40,7 @@ public final class EGLES2DynamicLibraryBundleInfo extends EGLDynamicLibraryBundl super(); } + @Override public final List> getToolLibNames() { final List> libsList = new ArrayList>(); { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java index 5764a6178..31fa14fbb 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java @@ -115,6 +115,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact private EGLGraphicsConfigurationFactory() { } + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl ( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java b/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java index 5083c854f..dac058dc7 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java @@ -44,6 +44,7 @@ public class EGLUpstreamSurfaceHook implements UpstreamSurfaceHook.MutableSize { static String getThreadName() { return Thread.currentThread().getName(); } + @Override public final void setSize(int width, int height) { if(null != upstreamSurfaceHookMutableSize) { upstreamSurfaceHookMutableSize.setSize(width, height); diff --git a/src/jogl/classes/jogamp/opengl/glu/GLUquadricImpl.java b/src/jogl/classes/jogamp/opengl/glu/GLUquadricImpl.java index b4383c2e6..717b1255c 100644 --- a/src/jogl/classes/jogamp/opengl/glu/GLUquadricImpl.java +++ b/src/jogl/classes/jogamp/opengl/glu/GLUquadricImpl.java @@ -164,6 +164,7 @@ public class GLUquadricImpl implements GLUquadric { replaceImmModeSink(); } + @Override public void enableImmModeSink(boolean val) { if(gl.isGL2()) { immModeSinkEnabled=val; @@ -175,10 +176,12 @@ public class GLUquadricImpl implements GLUquadric { } } + @Override public boolean isImmModeSinkEnabled() { return immModeSinkEnabled; } + @Override public void setImmMode(boolean val) { if(immModeSinkEnabled) { immModeSinkImmediate=val; @@ -187,10 +190,12 @@ public class GLUquadricImpl implements GLUquadric { } } + @Override public boolean getImmMode() { return immModeSinkImmediate; } + @Override public ImmModeSink replaceImmModeSink() { if(!immModeSinkEnabled) return null; @@ -222,6 +227,7 @@ public class GLUquadricImpl implements GLUquadric { return res; } + @Override public void resetImmModeSink(GL gl) { if(immModeSinkEnabled) { immModeSink.reset(gl); diff --git a/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2CurveEvaluator.java b/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2CurveEvaluator.java index f57c2310f..4213dfd46 100644 --- a/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2CurveEvaluator.java +++ b/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2CurveEvaluator.java @@ -92,6 +92,7 @@ class GL2CurveEvaluator implements CurveEvaluator { /** * Pushes eval bit */ + @Override public void bgnmap1f() { // DONE if (output_triangles) { @@ -108,6 +109,7 @@ class GL2CurveEvaluator implements CurveEvaluator { /** * Pops all OpenGL attributes */ + @Override public void endmap1f() { // DONE if (output_triangles) { @@ -127,6 +129,7 @@ class GL2CurveEvaluator implements CurveEvaluator { * @param order curve order * @param ps control points */ + @Override public void map1f(int type, float ulo, float uhi, int stride, int order, CArrayOfFloats ps) { if (output_triangles) { @@ -153,6 +156,7 @@ class GL2CurveEvaluator implements CurveEvaluator { * Calls opengl enable * @param type what to enable */ + @Override public void enable(int type) { // DONE gl.glEnable(type); @@ -164,6 +168,7 @@ class GL2CurveEvaluator implements CurveEvaluator { * @param u1 low u * @param u2 high u */ + @Override public void mapgrid1f(int nu, float u1, float u2) { if (output_triangles) { // System.out.println("TODO curveevaluator.mapgrid1f"); @@ -179,6 +184,7 @@ class GL2CurveEvaluator implements CurveEvaluator { * @param from lowest param * @param to highest param */ + @Override public void mapmesh1f(int style, int from, int to) { /* //DEBUG drawing control points this.poradi++; diff --git a/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2SurfaceEvaluator.java b/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2SurfaceEvaluator.java index 155c4f9a9..e9c9fca3f 100644 --- a/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2SurfaceEvaluator.java +++ b/src/jogl/classes/jogamp/opengl/glu/gl2/nurbs/GL2SurfaceEvaluator.java @@ -72,6 +72,7 @@ class GL2SurfaceEvaluator implements SurfaceEvaluator { /** * Pushes eval bit */ + @Override public void bgnmap2f() { if (output_triangles) { @@ -88,6 +89,7 @@ class GL2SurfaceEvaluator implements SurfaceEvaluator { * Sets glPolygonMode * @param style polygon mode (N_MESHFILL/N_MESHLINE/N_MESHPOINT) */ + @Override public void polymode(int style) { if (!output_triangles) { switch (style) { @@ -109,6 +111,7 @@ class GL2SurfaceEvaluator implements SurfaceEvaluator { /** * Pops all attributes */ + @Override public void endmap2f() { // TODO Auto-generated method stub if (output_triangles) { @@ -126,6 +129,7 @@ class GL2SurfaceEvaluator implements SurfaceEvaluator { * @param vlo * @param vhi */ + @Override public void domain2f(float ulo, float uhi, float vlo, float vhi) { // DONE } @@ -139,6 +143,7 @@ class GL2SurfaceEvaluator implements SurfaceEvaluator { * @param v0 lowest v * @param v1 highest v */ + @Override public void mapgrid2f(int nu, float u0, float u1, int nv, float v0, float v1) { if (output_triangles) { @@ -157,6 +162,7 @@ class GL2SurfaceEvaluator implements SurfaceEvaluator { * @param vmin minimum V * @param vmax maximum V */ + @Override public void mapmesh2f(int style, int umin, int umax, int vmin, int vmax) { if (output_triangles) { // System.out.println("TODO openglsurfaceavaluator.mapmesh2f output_triangles"); @@ -195,6 +201,7 @@ class GL2SurfaceEvaluator implements SurfaceEvaluator { * @param vorder surface order in v direction * @param pts control points */ + @Override public void map2f(int type, float ulo, float uhi, int ustride, int uorder, float vlo, float vhi, int vstride, int vorder, CArrayOfFloats pts) { // TODO Auto-generated method stub @@ -210,6 +217,7 @@ class GL2SurfaceEvaluator implements SurfaceEvaluator { * Calls opengl enable * @param type what to enable */ + @Override public void enable(int type) { //DONE gl.glEnable(type); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1010102.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1010102.java index 5269024b4..0c155ff96 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1010102.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1010102.java @@ -56,6 +56,7 @@ public class Extract1010102 implements Extract { public Extract1010102() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { long uint = 0; @@ -76,6 +77,7 @@ public class Extract1010102 implements Extract { extractComponents[3] = (float)( ( uint & 0x00000003 ) ) / 3.0f; } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1555rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1555rev.java index 6982931d3..5208ea537 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1555rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract1555rev.java @@ -56,6 +56,7 @@ public class Extract1555rev implements Extract { public Extract1555rev() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; @@ -76,6 +77,7 @@ public class Extract1555rev implements Extract { extractComponents[3] = (float)( ( ushort & 0x8000 ) >> 15); } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 00000000,00011111 == 0x001F // 00000011,11100000 == 0x03E0 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract2101010rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract2101010rev.java index 1c7db6218..1bf8abcc3 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract2101010rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract2101010rev.java @@ -56,6 +56,7 @@ public class Extract2101010rev implements Extract { public Extract2101010rev() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { long uint = 0; @@ -76,6 +77,7 @@ public class Extract2101010rev implements Extract { extractComponents[3] = (float)( ( uint & 0xC0000000 ) >> 30 ) / 3.0f; } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract233rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract233rev.java index 672c86c32..c86b39e63 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract233rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract233rev.java @@ -56,6 +56,7 @@ public class Extract233rev implements Extract { public Extract233rev() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { // 11100000 == 0xe0 // 00011100 == 0x1c @@ -66,6 +67,7 @@ public class Extract233rev implements Extract { extractComponents[2] = (float)((ubyte & 0xC0) >> 6) / 3.0f; } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11100000 == 0xE0 // 00011100 == 0x1C diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract332.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract332.java index 6cdbc5cb0..706f0c3f2 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract332.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract332.java @@ -56,6 +56,7 @@ public class Extract332 implements Extract { public Extract332() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { // 11100000 == 0xe0 // 00011100 == 0x1c @@ -66,6 +67,7 @@ public class Extract332 implements Extract { extractComponents[2] = (float)((ubyte & 0x03)) / 3.0f; } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11100000 == 0xE0 // 00011100 == 0x1C diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444.java index b36b9fb82..182d66ce2 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444.java @@ -56,6 +56,7 @@ public class Extract4444 implements Extract { public Extract4444() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; @@ -76,6 +77,7 @@ public class Extract4444 implements Extract { extractComponents[3] = (float)( ( ushort & 0x000F ) ) / 15.0f; } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444rev.java index b7a3ed55f..52ecdc17c 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract4444rev.java @@ -56,6 +56,7 @@ public class Extract4444rev implements Extract { public Extract4444rev() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; @@ -76,6 +77,7 @@ public class Extract4444rev implements Extract { extractComponents[3] = (float)( ( ushort & 0xF000 ) >> 12 ) / 15.0f; } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract5551.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract5551.java index 4dc566b25..21f53aa1d 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract5551.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract5551.java @@ -56,6 +56,7 @@ public class Extract5551 implements Extract { public Extract5551() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; @@ -76,6 +77,7 @@ public class Extract5551 implements Extract { extractComponents[3] = (float)( ( ushort & 0xF000 ) ); } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565.java index e198e46d4..7408c45b2 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565.java @@ -56,6 +56,7 @@ public class Extract565 implements Extract { public Extract565() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; @@ -74,6 +75,7 @@ public class Extract565 implements Extract { extractComponents[2] = (float)( ( ushort & 0x001F ) ) / 31.0f; } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11111000,00000000 == 0xF800 // 00000111,11100000 == 0x07E0 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565rev.java index fe19540ee..adaafa7ea 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract565rev.java @@ -56,6 +56,7 @@ public class Extract565rev implements Extract { public Extract565rev() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { int ushort = 0; @@ -74,6 +75,7 @@ public class Extract565rev implements Extract { extractComponents[2] = (float)( ( ushort & 0xF800 ) >> 11 ) / 31.0f; } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 00000000,00111111 == 0x001F // 00000111,11100000 == 0x07E0 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888.java index 4602f2af9..be155d578 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888.java @@ -56,6 +56,7 @@ public class Extract8888 implements Extract { public Extract8888() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { long uint = 0; @@ -76,6 +77,7 @@ public class Extract8888 implements Extract { extractComponents[3] = (float)( ( uint & 0x000000FF ) ) / 255.0f; } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888rev.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888rev.java index 373cb102a..294e60e12 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888rev.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Extract8888rev.java @@ -56,6 +56,7 @@ public class Extract8888rev implements Extract { public Extract8888rev() { } + @Override public void extract( boolean isSwap, ByteBuffer packedPixel, float[] extractComponents ) { long uint = 0; @@ -76,6 +77,7 @@ public class Extract8888rev implements Extract { extractComponents[3] = (float)( ( uint & 0xFF000000 ) >> 24 ) / 255.0f; } + @Override public void shove( float[] shoveComponents, int index, ByteBuffer packedPixel ) { // 11110000,00000000 == 0xF000 // 00001111,00000000 == 0x0F00 diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractFloat.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractFloat.java index ac0f2f290..1dd8bff8a 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractFloat.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractFloat.java @@ -56,6 +56,7 @@ public class ExtractFloat implements ExtractPrimitive { public ExtractFloat() { } + @Override public double extract( boolean isSwap, ByteBuffer data ) { float f = 0; if( isSwap ) { @@ -67,6 +68,7 @@ public class ExtractFloat implements ExtractPrimitive { return( f ); } + @Override public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < 1.0); data.asFloatBuffer().put( index, (float)value ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSByte.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSByte.java index 399386e30..dcbe52a40 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSByte.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSByte.java @@ -56,12 +56,14 @@ public class ExtractSByte implements ExtractPrimitive { public ExtractSByte() { } + @Override public double extract( boolean isSwap, ByteBuffer sbyte ) { byte b = sbyte.get(); assert( b <= 127 ); return( b ); } + @Override public void shove( double value, int index, ByteBuffer data ) { data.position( index ); data.put( (byte)value ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSInt.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSInt.java index be3fb3092..547bd944a 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSInt.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSInt.java @@ -56,6 +56,7 @@ public class ExtractSInt implements ExtractPrimitive { public ExtractSInt() { } + @Override public double extract( boolean isSwap, ByteBuffer uint ) { int i = 0; if( isSwap ) { @@ -67,6 +68,7 @@ public class ExtractSInt implements ExtractPrimitive { return( i ); } + @Override public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < Integer.MAX_VALUE); IntBuffer ib = data.asIntBuffer(); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSShort.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSShort.java index 1e123c9b4..7dc172976 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSShort.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractSShort.java @@ -56,6 +56,7 @@ public class ExtractSShort implements ExtractPrimitive { public ExtractSShort() { } + @Override public double extract( boolean isSwap, ByteBuffer ushort ) { short s = 0; if( isSwap ) { @@ -67,6 +68,7 @@ public class ExtractSShort implements ExtractPrimitive { return( s ); } + @Override public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < 32768.0); ShortBuffer sb = data.asShortBuffer(); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUByte.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUByte.java index 26ca5cd40..3e933811c 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUByte.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUByte.java @@ -56,12 +56,14 @@ public class ExtractUByte implements ExtractPrimitive { public ExtractUByte() { } + @Override public double extract( boolean isSwap, ByteBuffer ubyte ) { int i = 0x000000FF & ubyte.get(); assert( i <= 255 ); return( i ); } + @Override public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < 256.0); data.position( index ); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUInt.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUInt.java index 8c94c89fc..1c34828b3 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUInt.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUInt.java @@ -56,6 +56,7 @@ public class ExtractUInt implements ExtractPrimitive { public ExtractUInt() { } + @Override public double extract( boolean isSwap, ByteBuffer uint ) { long i = 0; if( isSwap ) { @@ -67,6 +68,7 @@ public class ExtractUInt implements ExtractPrimitive { return( i ); } + @Override public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < 0xFFFFFFFF); IntBuffer ib = data.asIntBuffer(); diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUShort.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUShort.java index 55115c6f7..8e0d25c42 100644 --- a/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUShort.java +++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/ExtractUShort.java @@ -56,6 +56,7 @@ public class ExtractUShort implements ExtractPrimitive { public ExtractUShort() { } + @Override public double extract( boolean isSwap, ByteBuffer ushort ) { int i = 0; if( isSwap ) { @@ -67,6 +68,7 @@ public class ExtractUShort implements ExtractPrimitive { return( i ); } + @Override public void shove( double value, int index, ByteBuffer data ) { assert(0.0 <= value && value < 65536.0); ShortBuffer sb = data.asShortBuffer(); diff --git a/src/jogl/classes/jogamp/opengl/glu/tessellator/PriorityQHeap.java b/src/jogl/classes/jogamp/opengl/glu/tessellator/PriorityQHeap.java index 474056cc3..1ac0fd438 100644 --- a/src/jogl/classes/jogamp/opengl/glu/tessellator/PriorityQHeap.java +++ b/src/jogl/classes/jogamp/opengl/glu/tessellator/PriorityQHeap.java @@ -81,6 +81,7 @@ class PriorityQHeap extends jogamp.opengl.glu.tessellator.PriorityQ { } /* really __gl_pqHeapDeletePriorityQ */ + @Override void pqDeletePriorityQ() { handles = null; nodes = null; @@ -137,6 +138,7 @@ class PriorityQHeap extends jogamp.opengl.glu.tessellator.PriorityQ { } /* really __gl_pqHeapInit */ + @Override boolean pqInit() { int i; @@ -152,6 +154,7 @@ class PriorityQHeap extends jogamp.opengl.glu.tessellator.PriorityQ { /* really __gl_pqHeapInsert */ /* returns LONG_MAX iff out of memory */ + @Override int pqInsert(Object keyNew) { int curr; int free; @@ -207,6 +210,7 @@ class PriorityQHeap extends jogamp.opengl.glu.tessellator.PriorityQ { } /* really __gl_pqHeapExtractMin */ + @Override Object pqExtractMin() { jogamp.opengl.glu.tessellator.PriorityQ.PQnode[] n = nodes; jogamp.opengl.glu.tessellator.PriorityQ.PQhandleElem[] h = handles; @@ -229,6 +233,7 @@ class PriorityQHeap extends jogamp.opengl.glu.tessellator.PriorityQ { } /* really __gl_pqHeapDelete */ + @Override void pqDelete(int hCurr) { jogamp.opengl.glu.tessellator.PriorityQ.PQnode[] n = nodes; jogamp.opengl.glu.tessellator.PriorityQ.PQhandleElem[] h = handles; @@ -252,10 +257,12 @@ class PriorityQHeap extends jogamp.opengl.glu.tessellator.PriorityQ { freeList = hCurr; } + @Override Object pqMinimum() { return handles[nodes[1].handle].key; } + @Override boolean pqIsEmpty() { return size == 0; } diff --git a/src/jogl/classes/jogamp/opengl/glu/tessellator/PriorityQSort.java b/src/jogl/classes/jogamp/opengl/glu/tessellator/PriorityQSort.java index f9e0225e3..cf54b15c3 100644 --- a/src/jogl/classes/jogamp/opengl/glu/tessellator/PriorityQSort.java +++ b/src/jogl/classes/jogamp/opengl/glu/tessellator/PriorityQSort.java @@ -71,6 +71,7 @@ class PriorityQSort extends jogamp.opengl.glu.tessellator.PriorityQ { } /* really __gl_pqSortDeletePriorityQ */ + @Override void pqDeletePriorityQ() { if (heap != null) heap.pqDeletePriorityQ(); order = null; @@ -100,6 +101,7 @@ class PriorityQSort extends jogamp.opengl.glu.tessellator.PriorityQ { } /* really __gl_pqSortInit */ + @Override boolean pqInit() { int p, r, i, j; int piv; @@ -191,6 +193,7 @@ class PriorityQSort extends jogamp.opengl.glu.tessellator.PriorityQ { /* really __gl_pqSortInsert */ /* returns LONG_MAX iff out of memory */ + @Override int pqInsert(Object keyNew) { int curr; @@ -220,6 +223,7 @@ class PriorityQSort extends jogamp.opengl.glu.tessellator.PriorityQ { } /* really __gl_pqSortExtractMin */ + @Override Object pqExtractMin() { Object sortMin, heapMin; @@ -240,6 +244,7 @@ class PriorityQSort extends jogamp.opengl.glu.tessellator.PriorityQ { } /* really __gl_pqSortMinimum */ + @Override Object pqMinimum() { Object sortMin, heapMin; @@ -257,11 +262,13 @@ class PriorityQSort extends jogamp.opengl.glu.tessellator.PriorityQ { } /* really __gl_pqSortIsEmpty */ + @Override boolean pqIsEmpty() { return (size == 0) && heap.pqIsEmpty(); } /* really __gl_pqSortDelete */ + @Override void pqDelete(int curr) { if (curr >= 0) { heap.pqDelete(curr); diff --git a/src/jogl/classes/jogamp/opengl/glu/tessellator/Render.java b/src/jogl/classes/jogamp/opengl/glu/tessellator/Render.java index 1801e1c59..a2e973508 100644 --- a/src/jogl/classes/jogamp/opengl/glu/tessellator/Render.java +++ b/src/jogl/classes/jogamp/opengl/glu/tessellator/Render.java @@ -279,6 +279,7 @@ class Render { } private static class RenderTriangle implements renderCallBack { + @Override public void render(GLUtessellatorImpl tess, jogamp.opengl.glu.tessellator.GLUhalfEdge e, long size) { /* Just add the triangle to a triangle list, so we can render all * the separate triangles at once. @@ -323,6 +324,7 @@ class Render { } private static class RenderFan implements renderCallBack { + @Override public void render(GLUtessellatorImpl tess, jogamp.opengl.glu.tessellator.GLUhalfEdge e, long size) { /* Render as many CCW triangles as possible in a fan starting from * edge "e". The fan *should* contain exactly "size" triangles @@ -345,6 +347,7 @@ class Render { } private static class RenderStrip implements renderCallBack { + @Override public void render(GLUtessellatorImpl tess, jogamp.opengl.glu.tessellator.GLUhalfEdge e, long size) { /* Render as many CCW triangles as possible in a strip starting from * edge "e". The strip *should* contain exactly "size" triangles diff --git a/src/jogl/classes/jogamp/opengl/glu/tessellator/Sweep.java b/src/jogl/classes/jogamp/opengl/glu/tessellator/Sweep.java index b4a400c1c..364a7f198 100644 --- a/src/jogl/classes/jogamp/opengl/glu/tessellator/Sweep.java +++ b/src/jogl/classes/jogamp/opengl/glu/tessellator/Sweep.java @@ -1150,6 +1150,7 @@ class Sweep { */ { /* __gl_dictListNewDict */ tess.dict = Dict.dictNewDict(tess, new Dict.DictLeq() { + @Override public boolean leq(Object frame, Object key1, Object key2) { return EdgeLeq(tess, (ActiveRegion) key1, (ActiveRegion) key2); } @@ -1231,6 +1232,7 @@ class Sweep { /* __gl_pqSortNewPriorityQ */ pq = tess.pq = PriorityQ.pqNewPriorityQ(new PriorityQ.Leq() { + @Override public boolean leq(Object key1, Object key2) { return Geom.VertLeq(((GLUvertex) key1), (GLUvertex) key2); } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java index 5cc4003fe..03aae3f78 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java @@ -822,6 +822,7 @@ public class MacOSXCGLContext extends GLContextImpl texID = fbod.getTextureBuffer(GL.GL_FRONT).getName(); pbufferHandle = 0; fbod.setSwapBufferContext(new GLFBODrawableImpl.SwapBufferContext() { + @Override public void swapBuffers(boolean doubleBuffered) { MacOSXCGLContext.NSOpenGLImpl.this.swapBuffers(); } } ) ; diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java index 6f86e840b..994eee8d7 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java @@ -229,6 +229,7 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl { } } + @Override protected final SharedResource getOrCreateSharedResourceImpl(AbstractGraphicsDevice adevice) { final String connection = adevice.getConnection(); SharedResource sr; diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java index 535c4d2d3..13e249a58 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java @@ -59,6 +59,7 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration super(screen, capsChosen, capsRequested); } + @Override public Object clone() { return super.clone(); } diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java index e761be7b7..db2a1df68 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java @@ -59,6 +59,7 @@ public class MacOSXCGLGraphicsConfigurationFactory extends GLGraphicsConfigurati private MacOSXCGLGraphicsConfigurationFactory() { } + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java index c08259665..21923531f 100644 --- a/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java @@ -63,6 +63,7 @@ public class MacOSXAWTCGLGraphicsConfigurationFactory extends GLGraphicsConfigur private MacOSXAWTCGLGraphicsConfigurationFactory() { } + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { diff --git a/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerInterleaved.java b/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerInterleaved.java index 5f9b25530..0d4452864 100644 --- a/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerInterleaved.java +++ b/src/jogl/classes/jogamp/opengl/util/GLArrayHandlerInterleaved.java @@ -46,12 +46,14 @@ public class GLArrayHandlerInterleaved extends GLVBOArrayHandler implements GLAr super(ad); } + @Override public final void setSubArrayVBOName(int vboName) { for(int i=0; i() { + @Override public DynamicLibraryBundle run() { return new DynamicLibraryBundle(new FFMPEGDynamicLibraryBundleInfo()); } } ); @@ -272,6 +273,7 @@ class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo { // lookup AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { for(int i = 0; i() { + @Override public Object run() { final ProcAddressTable pt = ctx.getGLProcAddressTable(); final long procAddrGLTexSubImage2D = pt.getAddressFor("glTexSubImage2D"); diff --git a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandler.java b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandler.java index 2d74fa532..3b443fdd0 100644 --- a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandler.java +++ b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandler.java @@ -50,14 +50,17 @@ public class GLSLArrayHandler extends GLVBOArrayHandler implements GLArrayHandle super(ad); } + @Override public final void setSubArrayVBOName(int vboName) { throw new UnsupportedOperationException(); } + @Override public final void addSubHandler(GLArrayHandlerFlat handler) { throw new UnsupportedOperationException(); } + @Override public final void enableState(GL gl, boolean enable, Object ext) { final GL2ES2 glsl = gl.getGL2ES2(); if( null != ext ) { diff --git a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerFlat.java b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerFlat.java index a5f78b5d6..34a381d7d 100644 --- a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerFlat.java +++ b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerFlat.java @@ -47,10 +47,12 @@ public class GLSLArrayHandlerFlat implements GLArrayHandlerFlat { this.ad = ad; } + @Override public GLArrayDataWrapper getData() { return ad; } + @Override public final void syncData(GL gl, Object ext) { final GL2ES2 glsl = gl.getGL2ES2(); if( null != ext ) { @@ -77,6 +79,7 @@ public class GLSLArrayHandlerFlat implements GLArrayHandlerFlat { }*/ } + @Override public final void enableState(GL gl, boolean enable, Object ext) { final GL2ES2 glsl = gl.getGL2ES2(); if( null != ext ) { diff --git a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerInterleaved.java b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerInterleaved.java index bcc146d78..b175bb5dc 100644 --- a/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerInterleaved.java +++ b/src/jogl/classes/jogamp/opengl/util/glsl/GLSLArrayHandlerInterleaved.java @@ -50,12 +50,14 @@ public class GLSLArrayHandlerInterleaved extends GLVBOArrayHandler implements GL super(ad); } + @Override public final void setSubArrayVBOName(int vboName) { for(int i=0; i 0) { eobrun--; @@ -1288,6 +1299,7 @@ public class JPEGDecoder { } } class ACSuccessiveDecoder implements DecoderFunction { + @Override public void decode(ComponentIn component, int[] zz) throws IOException { int k = spectralStart, e = spectralEnd, r = 0; while (k <= e) { diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/ImageLine.java b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLine.java index 906ce6373..e6afd8694 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/ImageLine.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLine.java @@ -315,6 +315,7 @@ public class ImageLine { /** * Basic info */ + @Override public String toString() { return "row=" + rown + " cols=" + imgInfo.cols + " bpc=" + imgInfo.bitDepth + " size=" + scanline.length; } diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/ImageLineHelper.java b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLineHelper.java index 438a69984..4636c3955 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/ImageLineHelper.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLineHelper.java @@ -92,6 +92,7 @@ public class ImageLineHelper { public double[] maxdif = { BIG_VALUE_NEG, BIG_VALUE_NEG, BIG_VALUE_NEG, BIG_VALUE }; // maxima public final int channels; // diferencia + @Override public String toString() { return channels == 3 ? String.format( "prom=%.1f (%.1f %.1f %.1f) max=%.1f (%.1f %.1f %.1f) min=%.1f (%.1f %.1f %.1f)", promlum, prom[0], diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngHelperInternal.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngHelperInternal.java index 1f598a5de..9e64c3eb1 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/PngHelperInternal.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngHelperInternal.java @@ -186,6 +186,7 @@ public class PngHelperInternal { } private static final ThreadLocal crcProvider = new ThreadLocal() { + @Override protected CRC32 initialValue() { return new CRC32(); } diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngReader.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngReader.java index 73442e0bb..0412beb8c 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/PngReader.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngReader.java @@ -994,6 +994,7 @@ public class PngReader { /** * Basic info, for debugging. */ + @Override public String toString() { // basic info return "filename=" + filename + " " + imgInfo.toString(); } diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkHelper.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkHelper.java index 82abb902d..4e8bf5635 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkHelper.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkHelper.java @@ -47,12 +47,14 @@ public class ChunkHelper { public static final String zTXt = "zTXt"; private static final ThreadLocal inflaterProvider = new ThreadLocal() { + @Override protected Inflater initialValue() { return new Inflater(); } }; private static final ThreadLocal deflaterProvider = new ThreadLocal() { + @Override protected Deflater initialValue() { return new Deflater(); } diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkRaw.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkRaw.java index 3aba26cca..dcb1958df 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkRaw.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkRaw.java @@ -108,6 +108,7 @@ public class ChunkRaw { return new ByteArrayInputStream(data); } + @Override public String toString() { return "chunkid=" + ChunkHelper.toString(idbytes) + " len=" + len; } diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksList.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksList.java index 3e0d03051..75107d761 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksList.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksList.java @@ -59,12 +59,14 @@ public class ChunksList { protected static List getXById(final List list, final String id, final String innerid) { if (innerid == null) return ChunkHelper.filterList(list, new ChunkPredicate() { + @Override public boolean match(PngChunk c) { return c.id.equals(id); } }); else return ChunkHelper.filterList(list, new ChunkPredicate() { + @Override public boolean match(PngChunk c) { if (!c.id.equals(id)) return false; @@ -152,12 +154,14 @@ public class ChunksList { */ public List getEquivalent(final PngChunk c2) { return ChunkHelper.filterList(chunks, new ChunkPredicate() { + @Override public boolean match(PngChunk c) { return ChunkHelper.equivalent(c, c2); } }); } + @Override public String toString() { return "ChunkList: read: " + chunks.size(); } diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksListForWrite.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksListForWrite.java index 3b84ab800..c502e9071 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksListForWrite.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunksListForWrite.java @@ -149,6 +149,7 @@ public class ChunksListForWrite extends ChunksList { return queuedChunks; } + @Override public String toString() { return "ChunkList: written: " + chunks.size() + " queue: " + queuedChunks.size(); } @@ -156,6 +157,7 @@ public class ChunksListForWrite extends ChunksList { /** * for debugging */ + @Override public String toStringFull() { StringBuilder sb = new StringBuilder(toString()); sb.append("\n Written:\n"); diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSingle.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSingle.java index 5247169e0..7df5ba021 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSingle.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSingle.java @@ -12,6 +12,7 @@ public abstract class PngChunkSingle extends PngChunk { super(id, imgInfo); } + @Override public final boolean allowsMultiple() { return false; } diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngMetadata.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngMetadata.java index fa3649613..139603448 100644 --- a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngMetadata.java +++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngMetadata.java @@ -41,6 +41,7 @@ public class PngMetadata { throw new PngjException("cannot set chunk : readonly metadata"); if (lazyOverwrite) { ChunkHelper.trimList(cl.getQueuedChunks(), new ChunkPredicate() { + @Override public boolean match(PngChunk c2) { return ChunkHelper.equivalent(c, c2); } diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java index 203af110c..95485b033 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java @@ -92,6 +92,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl { synchronized(WindowsWGLDrawableFactory.class) { if( null == windowsWGLDynamicLookupHelper ) { windowsWGLDynamicLookupHelper = AccessController.doPrivileged(new PrivilegedAction() { + @Override public DesktopGLDynamicLookupHelper run() { DesktopGLDynamicLookupHelper tmp; try { diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java index cb445f005..5f2b0c227 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java @@ -119,6 +119,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return cfg; } + @Override public Object clone() { return super.clone(); } @@ -715,6 +716,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio return createPixelFormatDescriptor(0, 0); } + @Override public String toString() { return "WindowsWGLGraphicsConfiguration["+getScreen()+", pfdID " + getPixelFormatID() + ", ARB-Choosen " + isChoosenByARB() + ",\n\trequested " + getRequestedCapabilities() + diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java index 9e917a0eb..961295208 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java @@ -79,6 +79,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat private WindowsWGLGraphicsConfigurationFactory() { } + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java index ddfcbb55b..96bd0bdd0 100644 --- a/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java @@ -68,6 +68,7 @@ public class WindowsAWTWGLGraphicsConfigurationFactory extends GLGraphicsConfigu private WindowsAWTWGLGraphicsConfigurationFactory() { } + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java index 3f0841b6c..78e549508 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java @@ -95,6 +95,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl { synchronized(X11GLXDrawableFactory.class) { if( null == x11GLXDynamicLookupHelper ) { x11GLXDynamicLookupHelper = AccessController.doPrivileged(new PrivilegedAction() { + @Override public DesktopGLDynamicLookupHelper run() { DesktopGLDynamicLookupHelper tmp; try { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java index 5aea33f21..4d1ed3985 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java @@ -69,6 +69,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem this.chooser=chooser; } + @Override public Object clone() { return super.clone(); } @@ -478,6 +479,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem return tmp.get(tmp.position()); } + @Override public String toString() { return "X11GLXGraphicsConfiguration["+getScreen()+", visualID " + toHexString(getXVisualID()) + ", fbConfigID " + toHexString(getFBConfigID()) + ",\n\trequested " + getRequestedCapabilities()+ diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java index abe310a3f..6050dabbb 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java @@ -92,6 +92,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF private X11GLXGraphicsConfigurationFactory() { } + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { if (!(absScreen instanceof X11GraphicsScreen)) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java index 15f3355d0..aa9b876dd 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java @@ -109,6 +109,7 @@ public class AWTGraphicsConfiguration extends DefaultGraphicsConfiguration imple } // open access to superclass method + @Override public void setChosenCapabilities(CapabilitiesImmutable capsChosen) { super.setChosenCapabilities(capsChosen); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java index d3cf5bff6..83d6efa75 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java @@ -87,6 +87,7 @@ public class AWTGraphicsScreen extends DefaultGraphicsScreen implements Cloneabl return new AWTGraphicsScreen(AWTGraphicsDevice.createDefault()); } + @Override public Object clone() { return super.clone(); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java index e350aaff4..27275c6e0 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java @@ -119,6 +119,7 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { * otherwise return the AWT/Swing close operation value translated to * a {@link WindowClosingProtocol} value . */ + @Override public final WindowClosingMode getDefaultCloseOperation() { synchronized(closingListenerLock) { if(defaultCloseOperationSetByUser) { @@ -129,6 +130,7 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { return AWTMisc.getNWClosingOperation(comp); } + @Override public final WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) { synchronized(closingListenerLock) { final WindowClosingMode _op = defaultCloseOperation; diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java index e4d3884a7..c02fc0a04 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java @@ -247,6 +247,7 @@ public final class DirectDataBufferInt extends DataBuffer { * @see #setElem(int, int) * @see #setElem(int, int, int) */ + @Override public int getElem(int i) { return data.get(i+offset); } @@ -260,6 +261,7 @@ public final class DirectDataBufferInt extends DataBuffer { * @see #setElem(int, int) * @see #setElem(int, int, int) */ + @Override public int getElem(int bank, int i) { return bankdata[bank].get(i+offsets[bank]); } @@ -273,6 +275,7 @@ public final class DirectDataBufferInt extends DataBuffer { * @see #getElem(int) * @see #getElem(int, int) */ + @Override public void setElem(int i, int val) { data.put(i+offset, val); } @@ -286,6 +289,7 @@ public final class DirectDataBufferInt extends DataBuffer { * @see #getElem(int) * @see #getElem(int, int) */ + @Override public void setElem(int bank, int i, int val) { bankdata[bank].put(i+offsets[bank], val); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java index 89df7f853..99ca006fa 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java @@ -43,6 +43,7 @@ public class MacOSXGraphicsDevice extends DefaultGraphicsDevice implements Clone super(NativeWindowFactory.TYPE_MACOSX, AbstractGraphicsDevice.DEFAULT_CONNECTION, unitID); } + @Override public Object clone() { return super.clone(); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index 6057f6700..361d61c65 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -122,6 +122,7 @@ public class SWTAccessor { static { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { NativeWindowFactory.initSingleton(); // last resort .. return null; @@ -360,6 +361,7 @@ public class SWTAccessor { if(null != OS_gtk_class) { invoke(true, new Runnable() { + @Override public void run() { if(realize) { callStaticMethodL2V(OS_gtk_widget_realize, handle); @@ -434,6 +436,7 @@ public class SWTAccessor { public static long newGC(final Control swtControl, final GCData gcData) { final Object[] o = new Object[1]; invoke(true, new Runnable() { + @Override public void run() { o[0] = ReflectionUtil.callMethod(swtControl, swt_control_internal_new_GC, new Object[] { gcData }); } @@ -447,6 +450,7 @@ public class SWTAccessor { public static void disposeGC(final Control swtControl, final long gc, final GCData gcData) { invoke(true, new Runnable() { + @Override public void run() { if(swt_uses_long_handles) { ReflectionUtil.callMethod(swtControl, swt_control_internal_dispose_GC, new Object[] { new Long(gc), gcData }); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java index 7468d254b..643982715 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java @@ -47,6 +47,7 @@ public class WindowsGraphicsDevice extends DefaultGraphicsDevice implements Clon super(NativeWindowFactory.TYPE_WINDOWS, connection, unitID); } + @Override public Object clone() { return super.clone(); } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java index 8aac7095a..700937829 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java @@ -63,6 +63,7 @@ public class X11GraphicsScreen extends DefaultGraphicsScreen implements Cloneabl return X11Lib.DefaultVisualID(getDevice().getHandle(), getIndex()); } + @Override public Object clone() { return super.clone(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java index 6095db052..77cbe2995 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java @@ -76,6 +76,7 @@ public class DefaultCapabilitiesChooser implements CapabilitiesChooser { private final static int NO_SCORE = -9999999; private final static int COLOR_MISMATCH_PENALTY_SCALE = 36; + @Override public int chooseCapabilities(final CapabilitiesImmutable desired, final List available, final int windowSystemRecommendedChoice) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java index 3e32f30df..42d7f3a23 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java @@ -69,18 +69,22 @@ public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphics } } + @Override final public AbstractGraphicsScreen getScreen() { return screen; } + @Override final public CapabilitiesImmutable getChosenCapabilities() { return capabilitiesChosen; } + @Override final public CapabilitiesImmutable getRequestedCapabilities() { return capabilitiesRequested; } + @Override public AbstractGraphicsConfiguration getNativeGraphicsConfiguration() { return this; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java index ffcad235c..4bd548916 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsScreen.java @@ -54,10 +54,12 @@ public class DefaultGraphicsScreen implements Cloneable, AbstractGraphicsScreen } } + @Override public AbstractGraphicsDevice getDevice() { return device; } + @Override public int getIndex() { return idx; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java index e1aa91959..c09e6eaa4 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java @@ -80,10 +80,12 @@ public abstract class GraphicsConfigurationFactory { this.hash32 = hash32; } + @Override public final int hashCode() { return hash32; } + @Override public final boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof DeviceCapsType) { diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index bad72f355..6962ce505 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -123,6 +123,7 @@ public abstract class NativeWindowFactory { return AccessController.doPrivileged(new PrivilegedAction() { private final File vcliblocation = new File( "/opt/vc/lib/libbcm_host.so"); + @Override public Boolean run() { if ( vcliblocation.isFile() ) { return Boolean.TRUE; @@ -160,12 +161,14 @@ public abstract class NativeWindowFactory { final String[] _tmp = new String[] { null }; AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { Platform.initSingleton(); // last resort .. _DEBUG[0] = Debug.debug("NativeWindow"); _tmp[0] = Debug.getProperty("nativewindow.ws.name", true); Runtime.getRuntime().addShutdownHook( new Thread(new Runnable() { + @Override public void run() { NativeWindowFactory.shutdown(true); } }, "NativeWindowFactory_ShutdownHook" ) ) ; @@ -318,6 +321,7 @@ public abstract class NativeWindowFactory { ReflectionUtil.isClassAvailable("com.jogamp.nativewindow.awt.AWTGraphicsDevice", cl) ) { Method[] jawtUtilMethods = AccessController.doPrivileged(new PrivilegedAction() { + @Override public Method[] run() { try { Class _jawtUtilClass = Class.forName(JAWTUtilClassName, true, NativeWindowFactory.class.getClassLoader()); diff --git a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java index eb0a6cf04..0af2bdaf9 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java @@ -122,5 +122,6 @@ public interface ProxySurface extends MutableSurface { public void clearUpstreamOptionBits(int v); public StringBuilder toString(StringBuilder sink); + @Override public String toString(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java b/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java index 4ee71ee79..4ed79b1dc 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java +++ b/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java @@ -120,6 +120,7 @@ public interface VisualIDHolder { this.type = type; } + @Override public int compare(VisualIDHolder vid1, VisualIDHolder vid2) { final int id1 = vid1.getVisualID(type); final int id2 = vid2.getVisualID(type); diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java index b8b48a46c..b8dc53c83 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java @@ -45,10 +45,12 @@ public class Dimension implements Cloneable, DimensionImmutable { this.height=height; } + @Override public Object cloneMutable() { return clone(); } + @Override public Object clone() { try { return super.clone(); diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java index 9caa433a6..e6cacf4ff 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/DimensionImmutable.java @@ -59,8 +59,10 @@ public interface DimensionImmutable extends WriteCloneable, Comparabletrue if the two dimensions are equal; * otherwise false. */ + @Override boolean equals(Object obj); + @Override int hashCode(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java index dbd997c60..c84359dcd 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java @@ -45,10 +45,12 @@ public class Insets implements Cloneable, InsetsImmutable { this.b=bottom; } + @Override public Object cloneMutable() { return clone(); } + @Override protected Object clone() { try { return super.clone(); @@ -99,6 +101,7 @@ public class Insets implements Cloneable, InsetsImmutable { return sum3 * (sum3 + 1)/2 + val2; } + @Override public String toString() { return new String("[ l "+l+", r "+r+" - t "+t+", b "+b+" - "+getTotalWidth()+"x"+getTotalHeight()+"]"); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java index 0f99a7861..8256068cd 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/InsetsImmutable.java @@ -59,8 +59,10 @@ public interface InsetsImmutable extends WriteCloneable { * @return true if the two Insets are equal; * otherwise false. */ + @Override boolean equals(Object obj); + @Override int hashCode(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java index aba515d52..57c6fb716 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java @@ -42,10 +42,12 @@ public class Point implements Cloneable, PointImmutable { this(0, 0); } + @Override public Object cloneMutable() { return clone(); } + @Override public Object clone() { try { return super.clone(); @@ -95,6 +97,7 @@ public class Point implements Cloneable, PointImmutable { return hash; } + @Override public String toString() { return new String( x + " / " + y ); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java index f5377e059..08c628cc1 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/PointImmutable.java @@ -54,8 +54,10 @@ public interface PointImmutable extends WriteCloneable, Comparabletrue if the two points are equal; * otherwise false. */ + @Override public boolean equals(Object obj); + @Override public int hashCode(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java index 3a51fb67d..8dc8f4562 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java @@ -47,10 +47,12 @@ public class Rectangle implements Cloneable, RectangleImmutable { this.height=height; } + @Override public Object cloneMutable() { return clone(); } + @Override protected Object clone() { try { return super.clone(); @@ -191,6 +193,7 @@ public class Rectangle implements Cloneable, RectangleImmutable { return sum3 * (sum3 + 1)/2 + val2; } + @Override public String toString() { return new String("[ "+x+" / "+y+" "+width+" x "+height+" ]"); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java index ce735f53f..7ca92ff53 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/RectangleImmutable.java @@ -78,8 +78,10 @@ public interface RectangleImmutable extends WriteCloneable, Comparabletrue if the two rectangles are equal; * otherwise false. */ + @Override boolean equals(Object obj); + @Override int hashCode(); } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java index 917f7e230..f1749dfa6 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java @@ -56,6 +56,7 @@ public class SurfaceSize implements Comparable { return bitsPerPixel; } + @Override public final String toString() { return new String("[ "+resolution+" x "+bitsPerPixel+" bpp ]"); } @@ -89,6 +90,7 @@ public class SurfaceSize implements Comparable { * @return true if the two dimensions are equal; * otherwise false. */ + @Override public final boolean equals(Object obj) { if(this == obj) { return true; } if (obj instanceof SurfaceSize) { @@ -99,6 +101,7 @@ public class SurfaceSize implements Comparable { return false; } + @Override public final int hashCode() { // 31 * x == (x << 5) - x int hash = 31 + getResolution().hashCode(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/Debug.java b/src/nativewindow/classes/jogamp/nativewindow/Debug.java index a7bf536ec..b7197dbca 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/Debug.java +++ b/src/nativewindow/classes/jogamp/nativewindow/Debug.java @@ -54,6 +54,7 @@ public class Debug extends PropertyAccess { static { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { PropertyAccess.addTrustedPrefix("nativewindow."); return null; diff --git a/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java index b3b5d2131..8fb819251 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/DefaultGraphicsConfigurationFactoryImpl.java @@ -36,6 +36,7 @@ package jogamp.nativewindow; import javax.media.nativewindow.*; public class DefaultGraphicsConfigurationFactoryImpl extends GraphicsConfigurationFactory { + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen screen, int nativeVisualID) { return new DefaultGraphicsConfiguration(screen, capsChosen, capsRequested); diff --git a/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java index 5fdbbf697..cadef9bf1 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/GlobalToolkitLock.java @@ -72,6 +72,7 @@ public class GlobalToolkitLock implements ToolkitLock { // nop } + @Override public String toString() { return "GlobalToolkitLock[obj 0x"+Integer.toHexString(hashCode())+", isOwner "+globalLock.isOwner(Thread.currentThread())+", "+globalLock.toString()+"]"; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java index 36a25acfb..e7eb13756 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java @@ -39,6 +39,7 @@ import com.jogamp.common.util.cache.TempJarCache; public class NWJNILibLoader extends JNILibLoaderBase { public static boolean loadNativeWindow(final String ossuffix) { return AccessController.doPrivileged(new PrivilegedAction() { + @Override public Boolean run() { Platform.initSingleton(); final String libName = "nativewindow_"+ossuffix ; diff --git a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java index e3f6ab5ca..22ac3bd94 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java @@ -51,6 +51,7 @@ public class NativeWindowFactoryImpl extends NativeWindowFactory { // This subclass of NativeWindowFactory handles the case of // NativeWindows being passed in + @Override protected NativeWindow getNativeWindowImpl(Object winObj, AbstractGraphicsConfiguration config) throws IllegalArgumentException { if (winObj instanceof NativeWindow) { // Use the NativeWindow directly diff --git a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java index d8ce98acb..bda20522c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/NullToolkitLock.java @@ -64,6 +64,7 @@ public class NullToolkitLock implements ToolkitLock { // nop } + @Override public String toString() { return "NullToolkitLock[]"; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java index 8a1048c6f..097fffead 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java @@ -253,6 +253,7 @@ public abstract class ProxySurfaceImpl implements ProxySurface { return surfaceLock.getOwner(); } + @Override public final StringBuilder getUpstreamOptionBits(StringBuilder sink) { if(null == sink) { sink = new StringBuilder(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java index 51dd58543..f1efb8133 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/ResourceToolkitLock.java @@ -73,6 +73,7 @@ public class ResourceToolkitLock implements ToolkitLock { // nop } + @Override public String toString() { return "ResourceToolkitLock[obj 0x"+Integer.toHexString(hashCode())+", isOwner "+lock.isOwner(Thread.currentThread())+", "+lock.toString()+"]"; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java index e20d3d138..7b74e1f1f 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java +++ b/src/nativewindow/classes/jogamp/nativewindow/SharedResourceToolkitLock.java @@ -142,6 +142,7 @@ public class SharedResourceToolkitLock implements ToolkitLock { } } + @Override public String toString() { return "SharedResourceToolkitLock[refCount "+refCount+", handle 0x"+Long.toHexString(handle)+", obj 0x"+Integer.toHexString(hashCode())+", isOwner "+lock.isOwner(Thread.currentThread())+", "+lock.toString()+"]"; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java b/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java index d11e240fa..1e83232bb 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java +++ b/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java @@ -74,6 +74,7 @@ public class SurfaceUpdatedHelper implements SurfaceUpdatedListener { } } + @Override public void surfaceUpdated(Object updater, NativeSurface ns, long when) { synchronized(surfaceUpdatedListenersLock) { for(int i = 0; i < surfaceUpdatedListeners.size(); i++ ) { diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java index 815facbee..a5da41424 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTJNILibLoader.java @@ -50,6 +50,7 @@ import java.security.PrivilegedAction; public class JAWTJNILibLoader extends NWJNILibLoader { static { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { // Make sure that awt.dll is loaded before loading jawt.dll. Otherwise // a Dialog with "awt.dll not found" might pop up. diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java index 32946fe2d..5a1d915ce 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java @@ -320,6 +320,7 @@ public class JAWTUtil { j2dExist = ok; PrivilegedDataBlob1 pdb1 = (PrivilegedDataBlob1) AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { PrivilegedDataBlob1 d = new PrivilegedDataBlob1(); try { @@ -352,9 +353,11 @@ public class JAWTUtil { jawtLock = LockFactory.createRecursiveLock(); jawtToolkitLock = new ToolkitLock() { + @Override public final void lock() { JAWTUtil.lockToolkit(); } + @Override public final void unlock() { JAWTUtil.unlockToolkit(); } @@ -380,6 +383,7 @@ public class JAWTUtil { } else { final ArrayList> desktophintsBucket = new ArrayList>(1); EventQueue.invokeAndWait(new Runnable() { + @Override public void run() { Map _desktophints = (Map)(Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints")); if(null!=_desktophints) { diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 87e3d3dd8..600aa6cb2 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -88,6 +88,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { OSXUtil.DestroyNSWindow(windowHandle); } OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { if( 0 != rootSurfaceLayer ) { if( 0 != jawtSurfaceLayersHandle) { @@ -106,6 +107,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { @Override protected void attachSurfaceLayerImpl(final long layerHandle) { OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { // AWT position is top-left w/ insets, where CALayer position is bottom/left from root CALayer w/o insets. // Determine p0: components location on screen w/o insets. @@ -167,6 +169,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { @Override protected void detachSurfaceLayerImpl(final long layerHandle, final Runnable detachNotify) { OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { detachNotify.run(); OSXUtil.RemoveCASublayer(rootSurfaceLayer, layerHandle); @@ -183,6 +186,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { return offscreenSurfaceDrawableSet ? offscreenSurfaceDrawable : drawable /* super.getSurfaceHandle() */ ; } + @Override public void setSurfaceHandle(long surfaceHandle) { if( !isOffscreenLayerSurfaceEnabled() ) { throw new java.lang.UnsupportedOperationException("Not using CALAYER"); @@ -194,11 +198,13 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { this.offscreenSurfaceDrawableSet = true; } + @Override protected JAWT fetchJAWTImpl() throws NativeWindowException { // use offscreen if supported and [ applet or requested ] return JAWTUtil.getJAWT(getShallUseOffscreenLayer() || isApplet()); } + @Override protected int lockSurfaceImpl() throws NativeWindowException { int ret = NativeWindow.LOCK_SURFACE_NOT_READY; ds = getJAWT().GetDrawingSurface(component); @@ -223,6 +229,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } if (firstLock) { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { dsi = ds.GetDrawingSurfaceInfo(); return null; @@ -284,6 +291,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { if(null == errMsg) { jawtSurfaceLayersHandle = GetJAWTSurfaceLayersHandle0(dsi.getBuffer()); OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { String errMsg = null; if(0 == rootSurfaceLayer && 0 != jawtSurfaceLayersHandle) { @@ -322,6 +330,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { return ret; } + @Override protected void unlockSurfaceImpl() throws NativeWindowException { if(null!=ds) { if (null!=dsi) { @@ -362,6 +371,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { getLocationOnScreenNonBlocking(storage, component); return storage; } + @Override protected Point getLocationOnScreenNativeImpl(final int x0, final int y0) { return null; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java index 876531151..8b9dfabfd 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java @@ -65,6 +65,7 @@ public class Win32SunJDKReflection { static { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { try { win32GraphicsDeviceClass = Class.forName("sun.awt.Win32GraphicsDevice"); diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java index 64e177155..54bdb34f6 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java @@ -60,14 +60,17 @@ public class WindowsJAWTWindow extends JAWTWindow { super(comp, config); } + @Override protected void invalidateNative() { windowHandle = 0; } + @Override protected JAWT fetchJAWTImpl() throws NativeWindowException { return JAWTUtil.getJAWT(false); // no offscreen } + @Override protected int lockSurfaceImpl() throws NativeWindowException { int ret = NativeWindow.LOCK_SUCCESS; ds = getJAWT().GetDrawingSurface(component); @@ -110,6 +113,7 @@ public class WindowsJAWTWindow extends JAWTWindow { return ret; } + @Override protected void unlockSurfaceImpl() throws NativeWindowException { drawable = 0; // invalid HDC if(null!=ds) { @@ -131,6 +135,7 @@ public class WindowsJAWTWindow extends JAWTWindow { return windowHandle; } + @Override protected Point getLocationOnScreenNativeImpl(int x, int y) { return GDIUtil.GetRelativeLocation( getWindowHandle(), 0 /*root win*/, x, y); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java index b08a7d83a..4599b9021 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java @@ -57,12 +57,15 @@ public class X11JAWTWindow extends JAWTWindow { super(comp, config); } + @Override protected void invalidateNative() { } + @Override protected JAWT fetchJAWTImpl() throws NativeWindowException { return JAWTUtil.getJAWT(false); // no offscreen } + @Override protected int lockSurfaceImpl() throws NativeWindowException { int ret = NativeWindow.LOCK_SUCCESS; ds = getJAWT().GetDrawingSurface(component); @@ -104,6 +107,7 @@ public class X11JAWTWindow extends JAWTWindow { return ret; } + @Override protected void unlockSurfaceImpl() throws NativeWindowException { if(null!=ds) { if (null!=dsi) { @@ -119,6 +123,7 @@ public class X11JAWTWindow extends JAWTWindow { x11dsi = null; } + @Override protected Point getLocationOnScreenNativeImpl(int x, int y) { // surface is locked and hence the device return X11Lib.GetRelativeLocation(getDisplayHandle(), getScreenIndex(), getWindowHandle(), 0 /*root win*/, x, y); diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java index f1104d02f..b2c3a931b 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java @@ -65,6 +65,7 @@ public class X11SunJDKReflection { static { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { try { x11GraphicsDeviceClass = Class.forName("sun.awt.X11GraphicsDevice"); diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java index 004a91a42..bac07b85a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java @@ -271,7 +271,7 @@ public class OSXUtil implements ToolkitProperties { RunLater0(onMain, new RunnableTask( runnable, null, true, System.err ), delay); } - private static Runnable _nop = new Runnable() { public void run() {}; }; + private static Runnable _nop = new Runnable() { @Override public void run() {}; }; /** Issues a {@link #RunOnMainThread(boolean, Runnable)} w/ an NOP runnable, while waiting until done. */ public static void WaitUntilFinish() { diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java index d6e7b5970..6258632cd 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java @@ -51,6 +51,7 @@ public class X11GraphicsConfigurationFactory extends GraphicsConfigurationFactor private X11GraphicsConfigurationFactory() { } + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen screen, int nativeVisualID) throws IllegalArgumentException, NativeWindowException { diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 6431fb3f5..2576c7db1 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -300,10 +300,12 @@ public class X11Util implements ToolkitProperties { } } + @Override public final int hashCode() { return hash32; } + @Override public final boolean equals(Object obj) { if(this == obj) { return true; } if(obj instanceof NamedDisplay) { diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java b/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java index 7b37d3cca..062040232 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java @@ -66,6 +66,7 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac private X11AWTGraphicsConfigurationFactory() { } + @Override protected AbstractGraphicsConfiguration chooseGraphicsConfigurationImpl( CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen, int nativeVisualID) { diff --git a/src/newt/classes/com/jogamp/newt/Display.java b/src/newt/classes/com/jogamp/newt/Display.java index 83383d23c..a0a098481 100644 --- a/src/newt/classes/com/jogamp/newt/Display.java +++ b/src/newt/classes/com/jogamp/newt/Display.java @@ -41,9 +41,11 @@ public abstract class Display { public static final boolean DEBUG = Debug.debug("Display"); /** return precomputed hashCode from FQN {@link #getFQName()} */ + @Override public abstract int hashCode(); /** return true if obj is of type Display and both FQN {@link #getFQName()} equals */ + @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Display) { diff --git a/src/newt/classes/com/jogamp/newt/MonitorDevice.java b/src/newt/classes/com/jogamp/newt/MonitorDevice.java index 625a7b39f..28d9f53a1 100644 --- a/src/newt/classes/com/jogamp/newt/MonitorDevice.java +++ b/src/newt/classes/com/jogamp/newt/MonitorDevice.java @@ -87,6 +87,7 @@ public abstract class MonitorDevice { * *
                            */ + @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof MonitorDevice) { @@ -102,6 +103,7 @@ public abstract class MonitorDevice { *
                          • nativeID
                          • * */ + @Override public final int hashCode() { return nativeId; } @@ -228,6 +230,7 @@ public abstract class MonitorDevice { */ public abstract boolean setCurrentMode(MonitorMode mode); + @Override public String toString() { return "Monitor[Id "+Display.toHexString(nativeId)+", "+sizeMM+" mm, viewport "+viewport+ ", orig "+originalMode+", curr "+currentMode+ ", modeChanged "+modeChanged+", modeCount "+supportedModes.size()+"]"; diff --git a/src/newt/classes/com/jogamp/newt/MonitorMode.java b/src/newt/classes/com/jogamp/newt/MonitorMode.java index 175d6e5f2..59f28e791 100644 --- a/src/newt/classes/com/jogamp/newt/MonitorMode.java +++ b/src/newt/classes/com/jogamp/newt/MonitorMode.java @@ -114,12 +114,14 @@ public class MonitorMode implements Comparable { /** Comparator for 2 {@link MonitorMode}s, following comparison order as described in {@link MonitorMode#compareTo(MonitorMode)}, returning the ascending order. */ public static final Comparator monitorModeComparator = new Comparator() { + @Override public int compare(MonitorMode mm1, MonitorMode mm2) { return mm1.compareTo(mm2); } }; /** Comparator for 2 {@link MonitorMode}s, following comparison order as described in {@link MonitorMode#compareTo(MonitorMode)}, returning the descending order. */ public static final Comparator monitorModeComparatorInv = new Comparator() { + @Override public int compare(MonitorMode mm1, MonitorMode mm2) { return mm2.compareTo(mm1); } }; @@ -172,6 +174,7 @@ public class MonitorMode implements Comparable { } return sb; } + @Override public final String toString() { return new String(surfaceSize+" @ "+refreshRate+" Hz, flags ["+flags2String(flags).toString()+"]"); } @@ -228,6 +231,7 @@ public class MonitorMode implements Comparable { *
                          • flags
                          • * */ + @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof SizeAndRRate) { @@ -247,6 +251,7 @@ public class MonitorMode implements Comparable { *
                          • refreshRate
                          • * */ + @Override public final int hashCode() { return hashCode; } @@ -360,6 +365,7 @@ public class MonitorMode implements Comparable { return getRotatedWH(false); } + @Override public final String toString() { return "[Id "+Display.toHexString(nativeId)+", " + sizeAndRRate + ", " + rotation + " degr]"; } @@ -409,6 +415,7 @@ public class MonitorMode implements Comparable { *
                          • rotation
                          • * */ + @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof MonitorMode) { @@ -428,6 +435,7 @@ public class MonitorMode implements Comparable { *
                          • rotation
                          • * */ + @Override public final int hashCode() { return hashCode; } diff --git a/src/newt/classes/com/jogamp/newt/NewtFactory.java b/src/newt/classes/com/jogamp/newt/NewtFactory.java index 7116877a3..5ae3f3692 100644 --- a/src/newt/classes/com/jogamp/newt/NewtFactory.java +++ b/src/newt/classes/com/jogamp/newt/NewtFactory.java @@ -56,6 +56,7 @@ public class NewtFactory { static { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { NativeWindowFactory.initSingleton(); // last resort .. diff --git a/src/newt/classes/com/jogamp/newt/Screen.java b/src/newt/classes/com/jogamp/newt/Screen.java index 1274b3459..ef62ec95d 100644 --- a/src/newt/classes/com/jogamp/newt/Screen.java +++ b/src/newt/classes/com/jogamp/newt/Screen.java @@ -53,9 +53,11 @@ public abstract class Screen { public static final boolean DEBUG = Debug.debug("Screen"); /** return precomputed hashCode from FQN {@link #getFQName()} */ + @Override public abstract int hashCode(); /** return true if obj is of type Display and both FQN {@link #getFQName()} equals */ + @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Screen) { diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index de1b7224f..1f5c26f27 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -107,10 +107,12 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto private AWTWindowClosingProtocol awtWindowClosingProtocol = new AWTWindowClosingProtocol(this, new Runnable() { + @Override public void run() { NewtCanvasAWT.this.destroyImpl(false /* removeNotify */, true /* windowClosing */); } }, new Runnable() { + @Override public void run() { if( newtChild != null ) { newtChild.sendWindowEvent(WindowEvent.EVENT_WINDOW_DESTROY_NOTIFY); @@ -148,14 +150,17 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto setNEWTChild(child); } + @Override public void setShallUseOffscreenLayer(boolean v) { shallUseOffscreenLayer = v; } + @Override public final boolean getShallUseOffscreenLayer() { return shallUseOffscreenLayer; } + @Override public final boolean isOffscreenLayerSurfaceEnabled() { return jawtWindow.isOffscreenLayerSurfaceEnabled(); } @@ -178,6 +183,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } class FocusAction implements Window.FocusRunnable { + @Override public boolean run() { final boolean isParent = isParent(); final boolean isFullscreen = isFullscreen(); @@ -214,11 +220,13 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto }; class FocusTraversalKeyListener implements KeyListener { + @Override public void keyPressed(KeyEvent e) { if( isParent() && !isFullscreen() ) { handleKey(e, false); } } + @Override public void keyReleased(KeyEvent e) { if( isParent() && !isFullscreen() ) { handleKey(e, true); @@ -263,6 +271,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto private final FocusTraversalKeyListener newtFocusTraversalKeyListener = new FocusTraversalKeyListener(); class FocusPropertyChangeListener implements PropertyChangeListener { + @Override public void propertyChange(PropertyChangeEvent evt) { final Object oldF = evt.getOldValue(); final Object newF = evt.getNewValue(); @@ -358,10 +367,12 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto * or {@link #addNotify()} hasn't been called yet.*/ public NativeWindow getNativeWindow() { return jawtWindow; } + @Override public WindowClosingMode getDefaultCloseOperation() { return awtWindowClosingProtocol.getDefaultCloseOperation(); } + @Override public WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) { return awtWindowClosingProtocol.setDefaultCloseOperation(op); } @@ -745,6 +756,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto } } private final Runnable forceRelayout = new Runnable() { + @Override public void run() { if(DEBUG) { System.err.println("NewtCanvasAWT.forceRelayout.0"); @@ -797,6 +809,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto if (!disableBackgroundEraseInitialized) { try { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { try { Class clazz = getToolkit().getClass(); diff --git a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java index 9b1b82297..409f78307 100644 --- a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java +++ b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java @@ -102,6 +102,7 @@ public class JOGLNewtApplet1Run extends Applet { /** if valid glStandalone:=true (own window) ! */ int glXd=Integer.MAX_VALUE, glYd=Integer.MAX_VALUE, glWidth=Integer.MAX_VALUE, glHeight=Integer.MAX_VALUE; + @Override public void init() { if(DEBUG) { System.err.println("JOGLNewtApplet1Run.init() START"); @@ -223,6 +224,7 @@ public class JOGLNewtApplet1Run extends Applet { } } + @Override public void start() { if(DEBUG) { System.err.println("JOGLNewtApplet1Run.start() START (isVisible "+isVisible()+", isDisplayable "+isDisplayable()+")"); @@ -266,6 +268,7 @@ public class JOGLNewtApplet1Run extends Applet { } } + @Override public void stop() { if(DEBUG) { System.err.println("JOGLNewtApplet1Run.stop() START"); @@ -276,6 +279,7 @@ public class JOGLNewtApplet1Run extends Applet { } } + @Override public void destroy() { if(DEBUG) { System.err.println("JOGLNewtApplet1Run.destroy() START"); diff --git a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java index a6a30a8bf..d17d2e77c 100644 --- a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java +++ b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java @@ -112,6 +112,7 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener { try { final Class clazz = AccessController.doPrivileged(new PrivilegedAction>() { + @Override public Class run() { final ClassLoader cl = Thread.currentThread().getContextClassLoader(); Class clazz = null; @@ -169,6 +170,7 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener { if(null == glWindow.getParent()) { // we may be called directly by the native EDT new Thread(new Runnable() { + @Override public void run() { if( glWindow.isNativeValid() ) { glWindow.reparentWindow(awtParent); @@ -256,6 +258,7 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener { // *********************************************************************************** // *********************************************************************************** + @Override public void init(GLAutoDrawable drawable) { GL _gl = drawable.getGL(); @@ -276,10 +279,13 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener { _gl.setSwapInterval(glSwapInterval); } } + @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } + @Override public void display(GLAutoDrawable drawable) { } + @Override public void dispose(GLAutoDrawable drawable) { } diff --git a/src/newt/classes/com/jogamp/newt/event/DoubleTapScrollGesture.java b/src/newt/classes/com/jogamp/newt/event/DoubleTapScrollGesture.java index 7dda47534..edb2429bb 100644 --- a/src/newt/classes/com/jogamp/newt/event/DoubleTapScrollGesture.java +++ b/src/newt/classes/com/jogamp/newt/event/DoubleTapScrollGesture.java @@ -142,6 +142,7 @@ public class DoubleTapScrollGesture implements GestureHandler { } } + @Override public String toString() { return "DoubleTapScroll[state "+gestureState+", in "+isWithinGesture()+", has "+(null!=hitGestureEvent)+", pc "+pointerDownCount+"]"; } diff --git a/src/newt/classes/com/jogamp/newt/event/InputEvent.java b/src/newt/classes/com/jogamp/newt/event/InputEvent.java index 6520dafcf..f29b632e8 100644 --- a/src/newt/classes/com/jogamp/newt/event/InputEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/InputEvent.java @@ -210,10 +210,12 @@ public abstract class InputEvent extends NEWTEvent return 0 != ( modifiers & BUTTONALL_MASK ); } + @Override public String toString() { return toString(null).toString(); } + @Override public StringBuilder toString(StringBuilder sb) { if(null == sb) { sb = new StringBuilder(); diff --git a/src/newt/classes/com/jogamp/newt/event/KeyAdapter.java b/src/newt/classes/com/jogamp/newt/event/KeyAdapter.java index a89148574..5cef734bb 100644 --- a/src/newt/classes/com/jogamp/newt/event/KeyAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/KeyAdapter.java @@ -31,8 +31,10 @@ package com.jogamp.newt.event; public abstract class KeyAdapter implements KeyListener { + @Override public void keyPressed(KeyEvent e) { } + @Override public void keyReleased(KeyEvent e) { } } diff --git a/src/newt/classes/com/jogamp/newt/event/KeyEvent.java b/src/newt/classes/com/jogamp/newt/event/KeyEvent.java index 81680bf32..49aa4e054 100644 --- a/src/newt/classes/com/jogamp/newt/event/KeyEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/KeyEvent.java @@ -196,10 +196,12 @@ public class KeyEvent extends InputEvent return keyCode; } + @Override public final String toString() { return toString(null).toString(); } + @Override public final StringBuilder toString(StringBuilder sb) { if(null == sb) { sb = new StringBuilder(); diff --git a/src/newt/classes/com/jogamp/newt/event/MonitorEvent.java b/src/newt/classes/com/jogamp/newt/event/MonitorEvent.java index 77c66a2da..03242e147 100644 --- a/src/newt/classes/com/jogamp/newt/event/MonitorEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/MonitorEvent.java @@ -56,10 +56,12 @@ public class MonitorEvent extends OutputEvent { } } + @Override public final String toString() { return toString(null).toString(); } + @Override public final StringBuilder toString(StringBuilder sb) { if(null == sb) { sb = new StringBuilder(); diff --git a/src/newt/classes/com/jogamp/newt/event/MouseAdapter.java b/src/newt/classes/com/jogamp/newt/event/MouseAdapter.java index 652f87d5b..98252fe14 100644 --- a/src/newt/classes/com/jogamp/newt/event/MouseAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/MouseAdapter.java @@ -30,20 +30,28 @@ package com.jogamp.newt.event; public abstract class MouseAdapter implements MouseListener { + @Override public void mouseClicked(MouseEvent e) { } + @Override public void mouseEntered(MouseEvent e) { } + @Override public void mouseExited(MouseEvent e) { } + @Override public void mousePressed(MouseEvent e) { } + @Override public void mouseReleased(MouseEvent e) { } + @Override public void mouseMoved(MouseEvent e) { } + @Override public void mouseDragged(MouseEvent e) { } + @Override public void mouseWheelMoved(MouseEvent e) { } } diff --git a/src/newt/classes/com/jogamp/newt/event/MouseEvent.java b/src/newt/classes/com/jogamp/newt/event/MouseEvent.java index 4d7cc3b36..635bdba52 100644 --- a/src/newt/classes/com/jogamp/newt/event/MouseEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/MouseEvent.java @@ -510,10 +510,12 @@ public class MouseEvent extends InputEvent return rotationScale; } + @Override public final String toString() { return toString(null).toString(); } + @Override public final StringBuilder toString(StringBuilder sb) { if(null == sb) { sb = new StringBuilder(); diff --git a/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java b/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java index 022e2d0e1..af800e61e 100644 --- a/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/NEWTEvent.java @@ -131,6 +131,7 @@ public class NEWTEvent extends java.util.EventObject { } } + @Override public String toString() { return toString(null).toString(); } diff --git a/src/newt/classes/com/jogamp/newt/event/PinchToZoomGesture.java b/src/newt/classes/com/jogamp/newt/event/PinchToZoomGesture.java index d275eab46..b4e1341da 100644 --- a/src/newt/classes/com/jogamp/newt/event/PinchToZoomGesture.java +++ b/src/newt/classes/com/jogamp/newt/event/PinchToZoomGesture.java @@ -75,6 +75,7 @@ public class PinchToZoomGesture implements GestureHandler { this.zoom = 1f; } + @Override public String toString() { return "PinchZoom[1stTouch "+zoomFirstTouch+", in "+isWithinGesture()+", has "+(null!=zoomEvent)+", zoom "+zoom+"]"; } diff --git a/src/newt/classes/com/jogamp/newt/event/TraceKeyAdapter.java b/src/newt/classes/com/jogamp/newt/event/TraceKeyAdapter.java index e826f4a6a..bbc170958 100644 --- a/src/newt/classes/com/jogamp/newt/event/TraceKeyAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/TraceKeyAdapter.java @@ -40,10 +40,12 @@ public class TraceKeyAdapter implements KeyListener { this.downstream = downstream; } + @Override public void keyPressed(KeyEvent e) { System.err.println(e); if(null!=downstream) { downstream.keyPressed(e); } } + @Override public void keyReleased(KeyEvent e) { System.err.println(e); if(null!=downstream) { downstream.keyReleased(e); } diff --git a/src/newt/classes/com/jogamp/newt/event/TraceMouseAdapter.java b/src/newt/classes/com/jogamp/newt/event/TraceMouseAdapter.java index d035091c4..db8376034 100644 --- a/src/newt/classes/com/jogamp/newt/event/TraceMouseAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/TraceMouseAdapter.java @@ -40,34 +40,42 @@ public class TraceMouseAdapter implements MouseListener { this.downstream = downstream; } + @Override public void mouseClicked(MouseEvent e) { System.err.println(e); if(null!=downstream) { downstream.mouseClicked(e); } } + @Override public void mouseEntered(MouseEvent e) { System.err.println(e); if(null!=downstream) { downstream.mouseEntered(e); } } + @Override public void mouseExited(MouseEvent e) { System.err.println(e); if(null!=downstream) { downstream.mouseExited(e); } } + @Override public void mousePressed(MouseEvent e) { System.err.println(e); if(null!=downstream) { downstream.mousePressed(e); } } + @Override public void mouseReleased(MouseEvent e) { System.err.println(e); if(null!=downstream) { downstream.mouseReleased(e); } } + @Override public void mouseMoved(MouseEvent e) { System.err.println(e); if(null!=downstream) { downstream.mouseMoved(e); } } + @Override public void mouseDragged(MouseEvent e) { System.err.println(e); if(null!=downstream) { downstream.mouseDragged(e); } } + @Override public void mouseWheelMoved(MouseEvent e) { System.err.println(e); if(null!=downstream) { downstream.mouseWheelMoved(e); } diff --git a/src/newt/classes/com/jogamp/newt/event/TraceWindowAdapter.java b/src/newt/classes/com/jogamp/newt/event/TraceWindowAdapter.java index 630e85303..7b844f059 100644 --- a/src/newt/classes/com/jogamp/newt/event/TraceWindowAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/TraceWindowAdapter.java @@ -40,30 +40,37 @@ public class TraceWindowAdapter implements WindowListener { this.downstream = downstream; } + @Override public void windowResized(WindowEvent e) { System.err.println(e); if(null!=downstream) { downstream.windowResized(e); } } + @Override public void windowMoved(WindowEvent e) { System.err.println(e); if(null!=downstream) { downstream.windowMoved(e); } } + @Override public void windowDestroyNotify(WindowEvent e) { System.err.println(e); if(null!=downstream) { downstream.windowDestroyNotify(e); } } + @Override public void windowDestroyed(WindowEvent e) { System.err.println(e); if(null!=downstream) { downstream.windowDestroyed(e); } } + @Override public void windowGainedFocus(WindowEvent e) { System.err.println(e); if(null!=downstream) { downstream.windowGainedFocus(e); } } + @Override public void windowLostFocus(WindowEvent e) { System.err.println(e); if(null!=downstream) { downstream.windowLostFocus(e); } } + @Override public void windowRepaint(WindowUpdateEvent e) { System.err.println(e); if(null!=downstream) { downstream.windowRepaint(e); } diff --git a/src/newt/classes/com/jogamp/newt/event/WindowAdapter.java b/src/newt/classes/com/jogamp/newt/event/WindowAdapter.java index e237c0d80..ccc627444 100644 --- a/src/newt/classes/com/jogamp/newt/event/WindowAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/WindowAdapter.java @@ -30,18 +30,25 @@ package com.jogamp.newt.event; public abstract class WindowAdapter implements WindowListener { + @Override public void windowResized(WindowEvent e) { } + @Override public void windowMoved(WindowEvent e) { } + @Override public void windowDestroyNotify(WindowEvent e) { } + @Override public void windowDestroyed(WindowEvent e) { } + @Override public void windowGainedFocus(WindowEvent e) { } + @Override public void windowLostFocus(WindowEvent e) { } + @Override public void windowRepaint(WindowUpdateEvent e) { } } diff --git a/src/newt/classes/com/jogamp/newt/event/WindowEvent.java b/src/newt/classes/com/jogamp/newt/event/WindowEvent.java index 8c7abfe99..2841fd0f6 100644 --- a/src/newt/classes/com/jogamp/newt/event/WindowEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/WindowEvent.java @@ -66,10 +66,12 @@ public class WindowEvent extends NEWTEvent { } } + @Override public String toString() { return toString(null).toString(); } + @Override public StringBuilder toString(StringBuilder sb) { if(null == sb) { sb = new StringBuilder(); diff --git a/src/newt/classes/com/jogamp/newt/event/WindowUpdateEvent.java b/src/newt/classes/com/jogamp/newt/event/WindowUpdateEvent.java index 8a204d234..9044517b5 100644 --- a/src/newt/classes/com/jogamp/newt/event/WindowUpdateEvent.java +++ b/src/newt/classes/com/jogamp/newt/event/WindowUpdateEvent.java @@ -44,10 +44,12 @@ public class WindowUpdateEvent extends WindowEvent { return bounds; } + @Override public String toString() { return toString(null).toString(); } + @Override public StringBuilder toString(StringBuilder sb) { if(null == sb) { sb = new StringBuilder(); diff --git a/src/newt/classes/com/jogamp/newt/event/awt/AWTKeyAdapter.java b/src/newt/classes/com/jogamp/newt/event/awt/AWTKeyAdapter.java index 1b53671ba..f6f11b81f 100644 --- a/src/newt/classes/com/jogamp/newt/event/awt/AWTKeyAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/awt/AWTKeyAdapter.java @@ -49,11 +49,13 @@ public class AWTKeyAdapter extends AWTAdapter implements java.awt.event.KeyListe super(downstream); } + @Override public AWTAdapter addTo(java.awt.Component awtComponent) { awtComponent.addKeyListener(this); return this; } + @Override public AWTAdapter removeFrom(java.awt.Component awtComponent) { awtComponent.removeKeyListener(this); return this; diff --git a/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java b/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java index ab4bf7a3f..73a02c9fc 100644 --- a/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java @@ -46,6 +46,7 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL super(downstream); } + @Override public AWTAdapter addTo(java.awt.Component awtComponent) { awtComponent.addMouseListener(this); awtComponent.addMouseMotionListener(this); @@ -53,6 +54,7 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL return this; } + @Override public AWTAdapter removeFrom(java.awt.Component awtComponent) { awtComponent.removeMouseListener(this); awtComponent.removeMouseMotionListener(this); @@ -60,6 +62,7 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL return this; } + @Override public void mouseClicked(java.awt.event.MouseEvent e) { com.jogamp.newt.event.MouseEvent event = AWTNewtEventFactory.createMouseEvent(e, newtWindow); if(null!=newtListener) { @@ -69,6 +72,7 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL } } + @Override public void mouseEntered(java.awt.event.MouseEvent e) { com.jogamp.newt.event.MouseEvent event = AWTNewtEventFactory.createMouseEvent(e, newtWindow); if(null!=newtListener) { @@ -78,6 +82,7 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL } } + @Override public void mouseExited(java.awt.event.MouseEvent e) { com.jogamp.newt.event.MouseEvent event = AWTNewtEventFactory.createMouseEvent(e, newtWindow); if(null!=newtListener) { @@ -87,6 +92,7 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL } } + @Override public void mousePressed(java.awt.event.MouseEvent e) { com.jogamp.newt.event.MouseEvent event = AWTNewtEventFactory.createMouseEvent(e, newtWindow); if(null!=newtListener) { @@ -96,6 +102,7 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL } } + @Override public void mouseReleased(java.awt.event.MouseEvent e) { com.jogamp.newt.event.MouseEvent event = AWTNewtEventFactory.createMouseEvent(e, newtWindow); if(null!=newtListener) { @@ -105,6 +112,7 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL } } + @Override public void mouseDragged(java.awt.event.MouseEvent e) { com.jogamp.newt.event.MouseEvent event = AWTNewtEventFactory.createMouseEvent(e, newtWindow); if(null!=newtListener) { @@ -114,6 +122,7 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL } } + @Override public void mouseMoved(java.awt.event.MouseEvent e) { com.jogamp.newt.event.MouseEvent event = AWTNewtEventFactory.createMouseEvent(e, newtWindow); if(null!=newtListener) { @@ -123,6 +132,7 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL } } + @Override public void mouseWheelMoved(java.awt.event.MouseWheelEvent e) { com.jogamp.newt.event.MouseEvent event = AWTNewtEventFactory.createMouseEvent(e, newtWindow); if(null!=newtListener) { diff --git a/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java b/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java index 8c9781b77..8a9a2a49f 100644 --- a/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java +++ b/src/newt/classes/com/jogamp/newt/event/awt/AWTWindowAdapter.java @@ -50,6 +50,7 @@ public class AWTWindowAdapter super(downstream); } + @Override public AWTAdapter addTo(java.awt.Component awtComponent) { java.awt.Window win = getWindow(awtComponent); awtComponent.addComponentListener(this); @@ -74,6 +75,7 @@ public class AWTWindowAdapter return this; } + @Override public AWTAdapter removeFrom(java.awt.Component awtComponent) { awtComponent.removeFocusListener(this); awtComponent.removeComponentListener(this); @@ -94,6 +96,7 @@ public class AWTWindowAdapter return null; } + @Override public void focusGained(java.awt.event.FocusEvent e) { com.jogamp.newt.event.WindowEvent event = AWTNewtEventFactory.createWindowEvent(e, newtWindow); if(DEBUG_IMPLEMENTATION) { @@ -106,6 +109,7 @@ public class AWTWindowAdapter } } + @Override public void focusLost(java.awt.event.FocusEvent e) { com.jogamp.newt.event.WindowEvent event = AWTNewtEventFactory.createWindowEvent(e, newtWindow); if(DEBUG_IMPLEMENTATION) { @@ -118,6 +122,7 @@ public class AWTWindowAdapter } } + @Override public void componentResized(java.awt.event.ComponentEvent e) { com.jogamp.newt.event.WindowEvent event = AWTNewtEventFactory.createWindowEvent(e, newtWindow); if(DEBUG_IMPLEMENTATION) { @@ -142,6 +147,7 @@ public class AWTWindowAdapter } } + @Override public void componentMoved(java.awt.event.ComponentEvent e) { com.jogamp.newt.event.WindowEvent event = AWTNewtEventFactory.createWindowEvent(e, newtWindow); if(DEBUG_IMPLEMENTATION) { @@ -154,6 +160,7 @@ public class AWTWindowAdapter } } + @Override public void componentShown(java.awt.event.ComponentEvent e) { final java.awt.Component comp = e.getComponent(); if(DEBUG_IMPLEMENTATION) { @@ -171,6 +178,7 @@ public class AWTWindowAdapter }*/ } + @Override public void componentHidden(java.awt.event.ComponentEvent e) { final java.awt.Component comp = e.getComponent(); if(DEBUG_IMPLEMENTATION) { @@ -188,6 +196,7 @@ public class AWTWindowAdapter }*/ } + @Override public void windowActivated(java.awt.event.WindowEvent e) { com.jogamp.newt.event.WindowEvent event = AWTNewtEventFactory.createWindowEvent(e, newtWindow); if(null!=newtListener) { @@ -197,10 +206,13 @@ public class AWTWindowAdapter } } + @Override public void windowClosed(java.awt.event.WindowEvent e) { } + @Override public void windowClosing(java.awt.event.WindowEvent e) { } + @Override public void windowDeactivated(java.awt.event.WindowEvent e) { com.jogamp.newt.event.WindowEvent event = AWTNewtEventFactory.createWindowEvent(e, newtWindow); if(null!=newtListener) { @@ -210,13 +222,17 @@ public class AWTWindowAdapter } } + @Override public void windowDeiconified(java.awt.event.WindowEvent e) { } + @Override public void windowIconified(java.awt.event.WindowEvent e) { } + @Override public void windowOpened(java.awt.event.WindowEvent e) { } class WindowClosingListener implements java.awt.event.WindowListener { + @Override public void windowClosing(java.awt.event.WindowEvent e) { com.jogamp.newt.event.WindowEvent event = AWTNewtEventFactory.createWindowEvent(e, newtWindow); if(null!=newtListener) { @@ -225,6 +241,7 @@ public class AWTWindowAdapter enqueueEvent(true, event); } } + @Override public void windowClosed(java.awt.event.WindowEvent e) { com.jogamp.newt.event.WindowEvent event = AWTNewtEventFactory.createWindowEvent(e, newtWindow); if(null!=newtListener) { @@ -234,10 +251,15 @@ public class AWTWindowAdapter } } + @Override public void windowActivated(java.awt.event.WindowEvent e) { } + @Override public void windowDeactivated(java.awt.event.WindowEvent e) { } + @Override public void windowDeiconified(java.awt.event.WindowEvent e) { } + @Override public void windowIconified(java.awt.event.WindowEvent e) { } + @Override public void windowOpened(java.awt.event.WindowEvent e) { } } } diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index ac81e8469..8c1110ed3 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -117,6 +117,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind super(null, null, false /* always handle device lifecycle ourselves */); this.window = (WindowImpl) window; this.window.setWindowDestroyNotifyAction( new Runnable() { + @Override public void run() { defaultWindowDestroyNotifyOp(); } } ); @@ -549,6 +550,7 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind anim.stop(); // on anim thread, non-blocking } else { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { if( anim.isAnimating() && null != animThread ) { try { diff --git a/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java index a25b43777..e63a53524 100644 --- a/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java +++ b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java @@ -99,6 +99,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { public static NewtCanvasSWT create(final Composite parent, final int style, final Window child) { final NewtCanvasSWT[] res = new NewtCanvasSWT[] { null }; parent.getDisplay().syncExec( new Runnable() { + @Override public void run() { res[0] = new NewtCanvasSWT( parent, style, child); } @@ -254,10 +255,12 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { /** @return this SWT Canvas NativeWindow representation, may be null in case it has not been realized. */ public NativeWindow getNativeWindow() { return nativeWindow; } + @Override public WindowClosingMode getDefaultCloseOperation() { return newtChildCloseOp; // TODO: implement ?! } + @Override public WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) { return newtChildCloseOp = op; // TODO: implement ?! } diff --git a/src/newt/classes/jogamp/newt/Debug.java b/src/newt/classes/jogamp/newt/Debug.java index 46a354d4a..7ef2d7ffc 100644 --- a/src/newt/classes/jogamp/newt/Debug.java +++ b/src/newt/classes/jogamp/newt/Debug.java @@ -54,6 +54,7 @@ public class Debug extends PropertyAccess { static { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { PropertyAccess.addTrustedPrefix("newt."); return null; diff --git a/src/newt/classes/jogamp/newt/DisplayImpl.java b/src/newt/classes/jogamp/newt/DisplayImpl.java index c6cb706a4..0c29d772a 100644 --- a/src/newt/classes/jogamp/newt/DisplayImpl.java +++ b/src/newt/classes/jogamp/newt/DisplayImpl.java @@ -53,6 +53,7 @@ public abstract class DisplayImpl extends Display { static { NativeWindowFactory.addCustomShutdownHook(true /* head */, new Runnable() { + @Override public void run() { WindowImpl.shutdownAll(); ScreenImpl.shutdownAll(); @@ -147,6 +148,7 @@ public abstract class DisplayImpl extends Display { final DisplayImpl f_dpy = this; try { runOnEDTIfAvail(true, new Runnable() { + @Override public void run() { f_dpy.createNativeImpl(); }}); @@ -244,6 +246,7 @@ public abstract class DisplayImpl extends Display { task.run(); } + @Override public boolean validateEDTStopped() { if( 0==refCount && null == aDevice ) { final EDTUtil _edtUtil = edtUtil; @@ -277,6 +280,7 @@ public abstract class DisplayImpl extends Display { aDevice = null; refCount=0; stopEDT( edtUtil, new Runnable() { // blocks! + @Override public void run() { if ( null != f_aDevice ) { f_dpy.closeNativeImpl(f_aDevice); @@ -308,6 +312,7 @@ public abstract class DisplayImpl extends Display { d.aDevice = null; d.refCount=0; final Runnable closeNativeTask = new Runnable() { + @Override public void run() { if ( null != d.getGraphicsDevice() ) { d.closeNativeImpl(f_aDevice); @@ -329,6 +334,7 @@ public abstract class DisplayImpl extends Display { } } + @Override public synchronized final int addReference() { if(DEBUG) { System.err.println("Display.addReference() ("+DisplayImpl.getThreadName()+"): "+refCount+" -> "+(refCount+1)); @@ -343,6 +349,7 @@ public abstract class DisplayImpl extends Display { } + @Override public synchronized final int removeReference() { if(DEBUG) { System.err.println("Display.removeReference() ("+DisplayImpl.getThreadName()+"): "+refCount+" -> "+(refCount-1)); @@ -355,6 +362,7 @@ public abstract class DisplayImpl extends Display { return refCount; } + @Override public synchronized final int getReferenceCount() { return refCount; } @@ -450,6 +458,7 @@ public abstract class DisplayImpl extends Display { private volatile boolean haveEvents = false; final protected Runnable dispatchMessagesRunnable = new Runnable() { + @Override public void run() { DisplayImpl.this.dispatchMessages(); } }; diff --git a/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java b/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java index f1e212394..9364ada30 100644 --- a/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java +++ b/src/newt/classes/jogamp/newt/NEWTJNILibLoader.java @@ -51,6 +51,7 @@ import com.jogamp.common.util.cache.TempJarCache; public class NEWTJNILibLoader extends JNILibLoaderBase { public static boolean loadNEWT() { return AccessController.doPrivileged(new PrivilegedAction() { + @Override public Boolean run() { Platform.initSingleton(); final String libName = "newt"; diff --git a/src/newt/classes/jogamp/newt/OffscreenWindow.java b/src/newt/classes/jogamp/newt/OffscreenWindow.java index eba844230..2478b1e5d 100644 --- a/src/newt/classes/jogamp/newt/OffscreenWindow.java +++ b/src/newt/classes/jogamp/newt/OffscreenWindow.java @@ -57,6 +57,7 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { static long nextWindowHandle = 0x100; // start here - a marker + @Override protected void createNativeImpl() { if(capsRequested.isOnscreen()) { throw new NativeWindowException("Capabilities is onscreen"); @@ -75,6 +76,7 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { visibleChanged(false, true); } + @Override protected void closeNativeImpl() { // nop } @@ -85,6 +87,7 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { surfaceHandle = 0; } + @Override public void setSurfaceHandle(long handle) { surfaceHandle = handle ; } @@ -94,6 +97,7 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { return surfaceHandle; } + @Override protected void requestFocusImpl(boolean reparented) { } @@ -113,6 +117,7 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { } + @Override protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { sizeChanged(false, width, height, false); if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { @@ -138,10 +143,12 @@ public class OffscreenWindow extends WindowImpl implements MutableSurface { return new Point(0,0); } + @Override protected Point getLocationOnScreenImpl(int x, int y) { return new Point(x,y); } + @Override protected void updateInsetsImpl(Insets insets) { // nop .. } diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index a0ef8816b..5102fd26d 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -207,6 +207,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer /** last mouse button click count */ short lastButtonClickCount = (short)0; + @Override final void clearButton() { super.clearButton(); lastButtonPressTime = 0; @@ -536,12 +537,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer private Object closingListenerLock = new Object(); private WindowClosingMode defaultCloseOperation = WindowClosingMode.DISPOSE_ON_CLOSE; + @Override public WindowClosingMode getDefaultCloseOperation() { synchronized (closingListenerLock) { return defaultCloseOperation; } } + @Override public WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) { synchronized (closingListenerLock) { WindowClosingMode _op = defaultCloseOperation; @@ -956,6 +959,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer this.visible = visible; } + @Override public final void run() { setVisibleActionImpl(visible); } @@ -983,6 +987,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer this.disregardFS = disregardFS; } + @Override public final void run() { final RecursiveLock _lock = windowLock; _lock.lock(); @@ -1035,6 +1040,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } private class DestroyAction implements Runnable { + @Override public final void run() { boolean animatorPaused = false; if(null!=lifecycleHook) { @@ -1188,6 +1194,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer screen = newScreen; } + @Override public final void run() { boolean animatorPaused = false; if(null!=lifecycleHook) { @@ -1462,6 +1469,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } private class ReparentActionRecreate implements Runnable { + @Override public final void run() { final RecursiveLock _lock = windowLock; _lock.lock(); @@ -1514,6 +1522,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer this.undecorated = undecorated; } + @Override public final void run() { final RecursiveLock _lock = windowLock; _lock.lock(); @@ -1559,6 +1568,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer this.alwaysOnTop = alwaysOnTop; } + @Override public final void run() { final RecursiveLock _lock = windowLock; _lock.lock(); @@ -1834,6 +1844,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } private final Runnable requestFocusAction = new Runnable() { + @Override public final void run() { if(DEBUG_IMPLEMENTATION) { System.err.println("Window.RequestFocusAction: force 0 - ("+getThreadName()+"): "+hasFocus+" -> true - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle)); @@ -1842,6 +1853,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } }; private final Runnable requestFocusActionForced = new Runnable() { + @Override public final void run() { if(DEBUG_IMPLEMENTATION) { System.err.println("Window.RequestFocusAction: force 1 - ("+getThreadName()+"): "+hasFocus+" -> true - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle)); @@ -1921,6 +1933,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer this.y = y; } + @Override public final void run() { final RecursiveLock _lock = windowLock; _lock.lock(); @@ -1970,6 +1983,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } public boolean fsOn() { return fullscreen; } + @Override public final void run() { final RecursiveLock _lock = windowLock; _lock.lock(); @@ -2144,6 +2158,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer List _fullscreenMonitors = null; boolean _fullscreenUseMainMonitor = true; + @Override public void monitorModeChangeNotify(MonitorEvent me) { hadFocus = hasFocus(); if(DEBUG_IMPLEMENTATION) { @@ -2164,6 +2179,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } + @Override public void monitorModeChanged(MonitorEvent me, boolean success) { if(DEBUG_IMPLEMENTATION) { System.err.println("Window.monitorModeChanged: hadFocus "+hadFocus+", "+me+", success: "+success+" @ "+Thread.currentThread().getName()); diff --git a/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java b/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java index 325f17278..4bcb0fc82 100644 --- a/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java +++ b/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java @@ -51,16 +51,19 @@ public class AWTParentWindowAdapter extends AWTWindowAdapter implements java.awt this.downstreamParent = downstreamParent; } + @Override public AWTAdapter addTo(java.awt.Component awtComponent) { awtComponent.addHierarchyListener(this); return super.addTo(awtComponent); } + @Override public AWTAdapter removeFrom(java.awt.Component awtComponent) { awtComponent.removeHierarchyListener(this); return super.removeFrom(awtComponent); } + @Override public void focusGained(java.awt.event.FocusEvent e) { // forward focus to NEWT child final com.jogamp.newt.Window newtChild = getNewtWindow(); @@ -78,12 +81,14 @@ public class AWTParentWindowAdapter extends AWTWindowAdapter implements java.awt } } + @Override public void focusLost(java.awt.event.FocusEvent e) { if(DEBUG_IMPLEMENTATION) { System.err.println("AWT: focusLost: "+ e); } } + @Override public void componentResized(java.awt.event.ComponentEvent e) { // Need to resize the NEWT child window // the resized event will be send via the native window feedback. @@ -93,6 +98,7 @@ public class AWTParentWindowAdapter extends AWTWindowAdapter implements java.awt } final Window newtWindow = getNewtWindow(); newtWindow.runOnEDTIfAvail(false, new Runnable() { + @Override public void run() { int cw = comp.getWidth(); int ch = comp.getHeight(); @@ -109,6 +115,7 @@ public class AWTParentWindowAdapter extends AWTWindowAdapter implements java.awt }}); } + @Override public void componentMoved(java.awt.event.ComponentEvent e) { if(DEBUG_IMPLEMENTATION) { System.err.println("AWT: componentMoved: "+e); @@ -119,14 +126,17 @@ public class AWTParentWindowAdapter extends AWTWindowAdapter implements java.awt } } + @Override public void windowActivated(java.awt.event.WindowEvent e) { // no propagation to NEWT child window } + @Override public void windowDeactivated(java.awt.event.WindowEvent e) { // no propagation to NEWT child window } + @Override public void hierarchyChanged(java.awt.event.HierarchyEvent e) { if( null == getNewtEventListener() ) { long bits = e.getChangeFlags(); @@ -137,6 +147,7 @@ public class AWTParentWindowAdapter extends AWTWindowAdapter implements java.awt System.err.println("AWT: hierarchyChanged SHOWING_CHANGED: showing "+showing+", "+changed+", source "+e.getComponent()); } getNewtWindow().runOnEDTIfAvail(false, new Runnable() { + @Override public void run() { if(getNewtWindow().isVisible() != showing) { getNewtWindow().setVisible(showing); diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java b/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java index 14cc9c69d..f7722c91c 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java +++ b/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java @@ -107,6 +107,7 @@ public class AWTCanvas extends Canvas { return res; } + @Override public void addNotify() { /** @@ -160,6 +161,7 @@ public class AWTCanvas extends Canvas { return null != jawtWindow ? jawtWindow.isOffscreenLayerSurfaceEnabled() : false; } + @Override public void removeNotify() { try { dispose(); @@ -195,6 +197,7 @@ public class AWTCanvas extends Canvas { * Overridden to choose a GraphicsConfiguration on a parent container's * GraphicsDevice because both devices */ + @Override public GraphicsConfiguration getGraphicsConfiguration() { /* * Workaround for problems with Xinerama and java.awt.Component.checkGD @@ -324,6 +327,7 @@ public class AWTCanvas extends Canvas { if (!disableBackgroundEraseInitialized) { try { AccessController.doPrivileged(new PrivilegedAction() { + @Override public Object run() { try { Class clazz = getToolkit().getClass(); diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java b/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java index bddb43b30..4a7193306 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java +++ b/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java @@ -218,6 +218,7 @@ public class AWTEDTUtil implements EDTUtil { } try { AWTEDTExecutor.singleton.invoke(true, new Runnable() { + @Override public void run() { } }); } catch (Exception e) { } diff --git a/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java index 9e716d544..d9a4a48e5 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/awt/DisplayDriver.java @@ -46,6 +46,7 @@ public class DisplayDriver extends DisplayImpl { public DisplayDriver() { } + @Override protected void createNativeImpl() { aDevice = AWTGraphicsDevice.createDefault(); } @@ -54,6 +55,7 @@ public class DisplayDriver extends DisplayImpl { aDevice = d; } + @Override protected EDTUtil createEDTUtil() { final EDTUtil def; if(NewtFactory.useEDT()) { @@ -67,10 +69,12 @@ public class DisplayDriver extends DisplayImpl { return def; } + @Override protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { aDevice.close(); } + @Override protected void dispatchMessagesNative() { /* nop */ } } diff --git a/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java index a2430e2bb..a4356707e 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/awt/ScreenDriver.java @@ -49,6 +49,7 @@ public class ScreenDriver extends ScreenImpl { public ScreenDriver() { } + @Override protected void createNativeImpl() { aScreen = new AWTGraphicsScreen((AWTGraphicsDevice)display.getGraphicsDevice()); } @@ -65,8 +66,10 @@ public class ScreenDriver extends ScreenImpl { super.updateVirtualScreenOriginAndSize(); } + @Override protected void closeNativeImpl() { } + @Override protected int validateScreenIndex(int idx) { return idx; // pass through ... } diff --git a/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java index db71695b7..9854524d9 100644 --- a/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/awt/WindowDriver.java @@ -86,6 +86,7 @@ public class WindowDriver extends WindowImpl { private Frame awtFrame = null; private AWTCanvas awtCanvas; + @Override protected void requestFocusImpl(boolean reparented) { awtContainer.requestFocus(); } @@ -97,6 +98,7 @@ public class WindowDriver extends WindowImpl { } } + @Override protected void createNativeImpl() { if(0!=getParentWindowHandle()) { throw new RuntimeException("Window parenting not supported in AWT, use AWTWindow(Frame) cstr for wrapping instead"); @@ -140,6 +142,7 @@ public class WindowDriver extends WindowImpl { } } + @Override protected void closeNativeImpl() { setWindowHandle(0); if(null!=awtContainer) { @@ -176,6 +179,7 @@ public class WindowDriver extends WindowImpl { return res; } + @Override protected void updateInsetsImpl(javax.media.nativewindow.util.Insets insets) { final Insets contInsets = awtContainer.getInsets(); insets.set(contInsets.left, contInsets.right, contInsets.top, contInsets.bottom); @@ -214,6 +218,7 @@ public class WindowDriver extends WindowImpl { awtContainer.validate(); } + @Override protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { if(DEBUG_IMPLEMENTATION) { System.err.println("AWTWindow reconfig: "+x+"/"+y+" "+width+"x"+height+", "+ @@ -266,6 +271,7 @@ public class WindowDriver extends WindowImpl { return true; } + @Override protected Point getLocationOnScreenImpl(int x, int y) { java.awt.Point ap = awtCanvas.getLocationOnScreen(); ap.translate(x, y); diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java index 1b73cb381..9da671d37 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/egl/DisplayDriver.java @@ -61,6 +61,7 @@ public class DisplayDriver extends jogamp.newt.DisplayImpl { public DisplayDriver() { } + @Override protected void createNativeImpl() { final long handle = CreateDisplay(ScreenDriver.fixedWidth, ScreenDriver.fixedHeight); if (handle == EGL.EGL_NO_DISPLAY) { @@ -69,6 +70,7 @@ public class DisplayDriver extends jogamp.newt.DisplayImpl { aDevice = new EGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, handle, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT, null); } + @Override protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { if (aDevice.getHandle() != EGL.EGL_NO_DISPLAY) { DestroyDisplay(aDevice.getHandle()); @@ -76,6 +78,7 @@ public class DisplayDriver extends jogamp.newt.DisplayImpl { aDevice.close(); } + @Override protected void dispatchMessagesNative() { // n/a .. DispatchMessages(); } diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java index 269574adc..d3231557f 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/egl/ScreenDriver.java @@ -53,12 +53,15 @@ public class ScreenDriver extends jogamp.newt.ScreenImpl { public ScreenDriver() { } + @Override protected void createNativeImpl() { aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); } + @Override protected void closeNativeImpl() { } + @Override protected int validateScreenIndex(int idx) { return 0; // only one screen available } @@ -100,6 +103,7 @@ public class ScreenDriver extends jogamp.newt.ScreenImpl { return false; } + @Override protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { vOriginSize.set(0, 0, fixedWidth, fixedHeight); // FIXME } diff --git a/src/newt/classes/jogamp/newt/driver/bcm/egl/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/egl/WindowDriver.java index bed0520ff..39f168e0f 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/egl/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/egl/WindowDriver.java @@ -52,6 +52,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl { public WindowDriver() { } + @Override protected void createNativeImpl() { if(0!=getParentWindowHandle()) { throw new RuntimeException("Window parenting not supported (yet)"); @@ -72,12 +73,14 @@ public class WindowDriver extends jogamp.newt.WindowImpl { } } + @Override protected void closeNativeImpl() { if(0!=windowHandleClose) { CloseWindow(getDisplayHandle(), windowHandleClose); } } + @Override protected void requestFocusImpl(boolean reparented) { } protected void setSizeImpl(int width, int height) { @@ -89,6 +92,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl { } } + @Override protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { if(0!=getWindowHandle()) { if(0 != ( FLAG_CHANGE_FULLSCREEN & flags)) { @@ -117,10 +121,12 @@ public class WindowDriver extends jogamp.newt.WindowImpl { return true; } + @Override protected Point getLocationOnScreenImpl(int x, int y) { return new Point(x,y); } + @Override protected void updateInsetsImpl(Insets insets) { // nop .. } diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java index 52c92a5da..d8d93f123 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java @@ -59,15 +59,18 @@ public class DisplayDriver extends DisplayImpl { public DisplayDriver() { } + @Override protected void createNativeImpl() { // FIXME: map name to EGL_*_DISPLAY aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); } + @Override protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { aDevice.close(); } + @Override protected void dispatchMessagesNative() { DispatchMessages(); } diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java index 5a1917419..dc2a8459a 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/ScreenDriver.java @@ -45,13 +45,16 @@ public class ScreenDriver extends ScreenImpl { public ScreenDriver() { } + @Override protected void createNativeImpl() { aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); initNative(); } + @Override protected void closeNativeImpl() { } + @Override protected int validateScreenIndex(int idx) { return 0; // only one screen available } diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java index 560e49e96..4d4977776 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java @@ -55,6 +55,7 @@ public class WindowDriver extends WindowImpl { public WindowDriver() { } + @Override protected void createNativeImpl() { if(0!=getParentWindowHandle()) { throw new RuntimeException("Window parenting not supported (yet)"); @@ -92,6 +93,7 @@ public class WindowDriver extends WindowImpl { focusChanged(false, true); } + @Override protected void closeNativeImpl() { final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) getGraphicsConfiguration().getScreen().getDevice(); @@ -106,10 +108,12 @@ public class WindowDriver extends WindowImpl { eglDevice.close(); } + @Override protected void requestFocusImpl(boolean reparented) { focusChanged(false, true); } + @Override protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { setVisible0(nativeWindowHandle, 0 != ( FLAG_IS_VISIBLE & flags)); @@ -143,10 +147,12 @@ public class WindowDriver extends WindowImpl { return true; } + @Override protected Point getLocationOnScreenImpl(int x, int y) { return new Point(x,y); } + @Override protected void updateInsetsImpl(Insets insets) { // nop .. } diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java index 4cb566bc2..cc435540f 100644 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/DisplayDriver.java @@ -59,6 +59,7 @@ public class DisplayDriver extends jogamp.newt.DisplayImpl { public DisplayDriver() { } + @Override protected void createNativeImpl() { synchronized(DisplayDriver.class) { if(0==initCounter) { @@ -72,6 +73,7 @@ public class DisplayDriver extends jogamp.newt.DisplayImpl { aDevice = new DefaultGraphicsDevice(NativeWindowFactory.TYPE_DEFAULT, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT, displayHandle); } + @Override protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { if(0==displayHandle) { throw new NativeWindowException("displayHandle null; initCnt "+initCounter); @@ -87,6 +89,7 @@ public class DisplayDriver extends jogamp.newt.DisplayImpl { aDevice.close(); } + @Override protected void dispatchMessagesNative() { if(0!=displayHandle) { DispatchMessages(displayHandle, focusedWindow); diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java index b5202aaf9..44802e348 100644 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/ScreenDriver.java @@ -53,14 +53,17 @@ public class ScreenDriver extends jogamp.newt.ScreenImpl { public ScreenDriver() { } + @Override protected void createNativeImpl() { AbstractGraphicsDevice adevice = getDisplay().getGraphicsDevice(); GetScreenInfo(adevice.getHandle(), screen_idx); aScreen = new DefaultGraphicsScreen(adevice, screen_idx); } + @Override protected void closeNativeImpl() { } + @Override protected int validateScreenIndex(int idx) { return 0; // only one screen available } @@ -102,6 +105,7 @@ public class ScreenDriver extends jogamp.newt.ScreenImpl { return false; } + @Override protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { vOriginSize.set(0, 0, cachedWidth, cachedHeight); } diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java index 80821d4da..0e96c65d0 100644 --- a/src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/WindowDriver.java @@ -48,6 +48,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl { static long nextWindowHandle = 1; + @Override protected void createNativeImpl() { if(0!=getParentWindowHandle()) { throw new NativeWindowException("GDL Window does not support window parenting"); @@ -72,6 +73,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl { } } + @Override protected void closeNativeImpl() { if(0!=surfaceHandle) { synchronized(WindowDriver.class) { @@ -82,6 +84,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl { } } + @Override protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { ScreenDriver screen = (ScreenDriver) getScreen(); @@ -112,6 +115,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl { return true; } + @Override protected void requestFocusImpl(boolean reparented) { ((DisplayDriver)getScreen().getDisplay()).setFocus(this); } @@ -121,10 +125,12 @@ public class WindowDriver extends jogamp.newt.WindowImpl { return surfaceHandle; } + @Override protected Point getLocationOnScreenImpl(int x, int y) { return new Point(x,y); } + @Override protected void updateInsetsImpl(Insets insets) { // nop .. } diff --git a/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java index 1b92ca586..929688b11 100644 --- a/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java @@ -59,15 +59,18 @@ public class DisplayDriver extends DisplayImpl { public DisplayDriver() { } + @Override protected void createNativeImpl() { // FIXME: map name to EGL_*_DISPLAY aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); } + @Override protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { aDevice.close(); } + @Override protected void dispatchMessagesNative() { DispatchMessages(); } diff --git a/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java index 17cc5dd2f..9ebe2629a 100644 --- a/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/kd/ScreenDriver.java @@ -51,12 +51,15 @@ public class ScreenDriver extends ScreenImpl { public ScreenDriver() { } + @Override protected void createNativeImpl() { aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); } + @Override protected void closeNativeImpl() { } + @Override protected int validateScreenIndex(int idx) { return 0; // only one screen available } @@ -98,6 +101,7 @@ public class ScreenDriver extends ScreenImpl { return false; } + @Override protected void calcVirtualScreenOriginAndSize(Rectangle vOriginSize) { vOriginSize.set(0, 0, cachedWidth, cachedHeight); } diff --git a/src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java index d30d4f025..158e6ab2f 100644 --- a/src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/kd/WindowDriver.java @@ -56,6 +56,7 @@ public class WindowDriver extends WindowImpl { public WindowDriver() { } + @Override protected void createNativeImpl() { if(0!=getParentWindowHandle()) { throw new RuntimeException("Window parenting not supported (yet)"); @@ -83,6 +84,7 @@ public class WindowDriver extends WindowImpl { windowHandleClose = eglWindowHandle; } + @Override protected void closeNativeImpl() { if(0!=windowHandleClose) { CloseWindow(windowHandleClose, windowUserData); @@ -90,8 +92,10 @@ public class WindowDriver extends WindowImpl { } } + @Override protected void requestFocusImpl(boolean reparented) { } + @Override protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { setVisible0(eglWindowHandle, 0 != ( FLAG_IS_VISIBLE & flags)); @@ -125,10 +129,12 @@ public class WindowDriver extends WindowImpl { return true; } + @Override protected Point getLocationOnScreenImpl(int x, int y) { return new Point(x,y); } + @Override protected void updateInsetsImpl(Insets insets) { // nop .. } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java index 2dbdfdce7..c44685dc8 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java @@ -64,14 +64,17 @@ public class DisplayDriver extends DisplayImpl { public DisplayDriver() { } + @Override protected void dispatchMessagesNative() { // nop } + @Override protected void createNativeImpl() { aDevice = new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); } + @Override protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { aDevice.close(); } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java index 5d3b7287b..4f3cc691b 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/ScreenDriver.java @@ -52,10 +52,12 @@ public class ScreenDriver extends ScreenImpl { public ScreenDriver() { } + @Override protected void createNativeImpl() { aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx); } + @Override protected void closeNativeImpl() { } private MonitorMode getMonitorModeImpl(MonitorModeProps.Cache cache, int crt_idx, int mode_idx) { @@ -114,6 +116,7 @@ public class ScreenDriver extends ScreenImpl { return setMonitorMode0(monitor.getId(), mode.getId(), mode.getRotation()); } + @Override protected int validateScreenIndex(int idx) { return 0; // big-desktop w/ multiple monitor attached, only one screen available } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java index f36d32772..7db3e2aab 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java @@ -87,6 +87,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl isOffscreenInstance = false; if (0 != handle) { OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { close0( handle ); } } ); @@ -144,6 +145,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl if (isNativeValid()) { if (0 != sscSurfaceHandle) { OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { orderOut0( 0 != getParentWindowHandle() ? getParentWindowHandle() : getWindowHandle() ); } } ); @@ -160,6 +162,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl @Override protected void setTitleImpl(final String title) { OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { setTitle0(getWindowHandle(), title); } } ); @@ -172,6 +175,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl } if(!isOffscreenInstance) { OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { requestFocus0(getWindowHandle(), force); } } ); @@ -187,6 +191,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl } if(!isOffscreenInstance) { OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { resignFocus0(getWindowHandle()); } } ); @@ -209,6 +214,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl System.err.println("MacWindow: updatePosition() parent["+useParent+" "+pX+"/"+pY+"] "+x+"/"+y+" -> "+x+"/"+y+" rel-client-pos, "+p0S+" screen-client-pos"); } OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { setWindowClientTopLeftPoint0(handle, p0S.getX(), p0S.getY(), isVisible()); } } ); @@ -230,6 +236,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl System.err.println("MacWindow: sizeChanged() parent["+useParent+" "+x+"/"+y+"] "+getX()+"/"+getY()+" "+newWidth+"x"+newHeight+" -> "+p0S+" screen-client-pos"); } OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { setWindowClientTopLeftPoint0(getWindowHandle(), p0S.getX(), p0S.getY(), isVisible()); } } ); @@ -275,6 +282,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && !setVisible ) { if ( !isOffscreenInstance ) { OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { orderOut0(getWindowHandle()); visibleChanged(true, false); @@ -297,6 +305,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl if( width>0 && height>0 ) { if( !isOffscreenInstance ) { OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { setWindowClientTopLeftPointAndSize0(getWindowHandle(), pClientLevelOnSreen.getX(), pClientLevelOnSreen.getY(), width, height, setVisible); } } ); @@ -308,6 +317,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) && setVisible ) { if( !isOffscreenInstance ) { OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { orderFront0(getWindowHandle()); visibleChanged(true, true); @@ -476,6 +486,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl throw new NativeWindowException("Internal Error - create w/ window, but no Newt NSView"); } OSXUtil.RunOnMainThread(false, new Runnable() { + @Override public void run() { changeContentView0(parentWinHandle, preWinHandle, 0); close0( preWinHandle ); @@ -502,6 +513,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl final boolean isOpaque = getGraphicsConfiguration().getChosenCapabilities().isBackgroundOpaque() && !offscreenInstance; // Blocking initialization on main-thread! OSXUtil.RunOnMainThread(true, new Runnable() { + @Override public void run() { initWindow0( parentWinHandle, newWin, pS.getX(), pS.getY(), width, height, isOpaque, fullscreen, visible && !offscreenInstance, surfaceHandle); diff --git a/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java index d3c7416cc..d8ff7ecb5 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java @@ -71,16 +71,19 @@ public class DisplayDriver extends DisplayImpl { public DisplayDriver() { } + @Override protected void createNativeImpl() { sharedClass = sharedClassFactory.getSharedClass(); aDevice = new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); } + @Override protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { sharedClassFactory.releaseSharedClass(); aDevice.close(); } + @Override protected void dispatchMessagesNative() { DispatchMessages0(); } diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java index 30405aa05..6e8ac3efa 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java @@ -127,6 +127,7 @@ public class WindowDriver extends WindowImpl { return false; } + @Override protected void createNativeImpl() { final ScreenDriver screen = (ScreenDriver) getScreen(); final DisplayDriver display = (DisplayDriver) screen.getDisplay(); @@ -156,6 +157,7 @@ public class WindowDriver extends WindowImpl { } } + @Override protected void closeNativeImpl() { if(windowHandleClose != 0) { if (hdc != 0) { @@ -183,6 +185,7 @@ public class WindowDriver extends WindowImpl { hdc_old = 0; } + @Override protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { if(DEBUG_IMPLEMENTATION) { System.err.println("WindowsWindow reconfig: "+x+"/"+y+" "+width+"x"+height+", "+ @@ -210,6 +213,7 @@ public class WindowDriver extends WindowImpl { return true; } + @Override protected void requestFocusImpl(boolean force) { requestFocus0(getWindowHandle(), force); } @@ -224,6 +228,7 @@ public class WindowDriver extends WindowImpl { final boolean[] res = new boolean[] { false }; this.runOnEDTIfAvail(true, new Runnable() { + @Override public void run() { res[0] = setPointerVisible0(getWindowHandle(), pointerVisible); } @@ -236,6 +241,7 @@ public class WindowDriver extends WindowImpl { final Boolean[] res = new Boolean[] { Boolean.FALSE }; this.runOnEDTIfAvail(true, new Runnable() { + @Override public void run() { final Point p0 = getLocationOnScreenImpl(0, 0); res[0] = Boolean.valueOf(confinePointer0(getWindowHandle(), confine, @@ -248,6 +254,7 @@ public class WindowDriver extends WindowImpl { @Override protected void warpPointerImpl(final int x, final int y) { this.runOnEDTIfAvail(true, new Runnable() { + @Override public void run() { final Point sPos = getLocationOnScreenImpl(x, y); warpPointer0(getWindowHandle(), sPos.getX(), sPos.getY()); @@ -256,10 +263,12 @@ public class WindowDriver extends WindowImpl { return; } + @Override protected Point getLocationOnScreenImpl(int x, int y) { return GDIUtil.GetRelativeLocation( getWindowHandle(), 0 /*root win*/, x, y); } + @Override protected void updateInsetsImpl(Insets insets) { // nop - using event driven insetsChange(..) } diff --git a/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java index aa8067520..504839797 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/DisplayDriver.java @@ -63,6 +63,7 @@ public class DisplayDriver extends DisplayImpl { public DisplayDriver() { } + @Override public String validateDisplayName(String name, long handle) { return X11Util.validateDisplayName(name, handle); } @@ -72,6 +73,7 @@ public class DisplayDriver extends DisplayImpl { * * We use a private non-shared X11 Display instance for EDT window operations and one for exposed animation, eg. OpenGL. */ + @Override protected void createNativeImpl() { X11Util.setX11ErrorHandler(true, DEBUG ? false : true); // make sure X11 error handler is set long handle = X11Util.openDisplay(name); diff --git a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java index 7f75e03f0..bef7f60ec 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/ScreenDriver.java @@ -74,6 +74,7 @@ public class ScreenDriver extends ScreenImpl { protected void createNativeImpl() { // validate screen index Long handle = runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override public Long run(long dpy) { return new Long(GetScreen0(dpy, screen_idx)); } } ); @@ -180,6 +181,7 @@ public class ScreenDriver extends ScreenImpl { if( null == rAndR ) { return null; } return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override public MonitorMode run(long dpy) { final int[] currentModeProps = rAndR.getCurrentMonitorModeProps(dpy, ScreenDriver.this, monitor.getId()); return MonitorModeProps.streamInMonitorMode(null, null, currentModeProps, 0); @@ -192,6 +194,7 @@ public class ScreenDriver extends ScreenImpl { final long t0 = System.currentTimeMillis(); boolean done = runWithOptTempDisplayHandle( new DisplayImpl.DisplayRunnable() { + @Override public Boolean run(long dpy) { return Boolean.valueOf( rAndR.setCurrentMonitorMode(dpy, ScreenDriver.this, monitor, mode) ); } @@ -205,6 +208,7 @@ public class ScreenDriver extends ScreenImpl { } private DisplayImpl.DisplayRunnable xineramaEnabledQueryWithTemp = new DisplayImpl.DisplayRunnable() { + @Override public Boolean run(long dpy) { return new Boolean(X11Util.XineramaIsEnabled(dpy)); } }; @@ -236,6 +240,7 @@ public class ScreenDriver extends ScreenImpl { } } ); } else */ { runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override public Object run(long dpy) { vOriginSize.set(0, 0, getWidth0(dpy, screen_idx), getHeight0(dpy, screen_idx)); return null; diff --git a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java index 02f80c0c3..5e1f7a6ed 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java @@ -176,6 +176,7 @@ public class WindowDriver extends WindowImpl { final int fflags = flags; final DisplayDriver display = (DisplayDriver) getScreen().getDisplay(); runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override public Object run(long dpy) { reconfigureWindow0( dpy, getScreenIndex(), getParentWindowHandle(), getWindowHandle(), display.getWindowDeleteAtom(), @@ -202,6 +203,7 @@ public class WindowDriver extends WindowImpl { } final DisplayDriver display = (DisplayDriver) getScreen().getDisplay(); runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override public Object run(long dpy) { reconfigureWindow0( dpy, getScreenIndex(), getParentWindowHandle(), getWindowHandle(), display.getWindowDeleteAtom(), @@ -223,6 +225,7 @@ public class WindowDriver extends WindowImpl { @Override protected void requestFocusImpl(final boolean force) { runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override public Object run(long dpy) { requestFocus0(dpy, getWindowHandle(), force); return null; @@ -233,6 +236,7 @@ public class WindowDriver extends WindowImpl { @Override protected void setTitleImpl(final String title) { runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override public Object run(long dpy) { setTitle0(dpy, getWindowHandle(), title); return null; @@ -243,6 +247,7 @@ public class WindowDriver extends WindowImpl { @Override protected boolean setPointerVisibleImpl(final boolean pointerVisible) { return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override public Boolean run(long dpy) { return Boolean.valueOf(setPointerVisible0(dpy, getWindowHandle(), pointerVisible)); } @@ -252,6 +257,7 @@ public class WindowDriver extends WindowImpl { @Override protected boolean confinePointerImpl(final boolean confine) { return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override public Boolean run(long dpy) { return Boolean.valueOf(confinePointer0(dpy, getWindowHandle(), confine)); } @@ -261,6 +267,7 @@ public class WindowDriver extends WindowImpl { @Override protected void warpPointerImpl(final int x, final int y) { runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override public Object run(long dpy) { warpPointer0(dpy, getWindowHandle(), x, y); return null; @@ -271,6 +278,7 @@ public class WindowDriver extends WindowImpl { @Override protected Point getLocationOnScreenImpl(final int x, final int y) { return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override public Point run(long dpy) { return X11Lib.GetRelativeLocation(dpy, getScreenIndex(), getWindowHandle(), 0 /*root win*/, x, y); } diff --git a/src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java b/src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java index 08eacdee5..db89690f4 100644 --- a/src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java +++ b/src/newt/classes/jogamp/newt/swt/SWTEDTUtil.java @@ -54,6 +54,7 @@ public class SWTEDTUtil implements EDTUtil { this.threadGroup = Thread.currentThread().getThreadGroup(); this.name=Thread.currentThread().getName()+"-SWTDisplay-"+newtDisplay.getFQName()+"-EDT-"; this.dispatchMessages = new Runnable() { + @Override public void run() { ((jogamp.newt.DisplayImpl) newtDisplay).dispatchMessages(); } }; @@ -252,6 +253,7 @@ public class SWTEDTUtil implements EDTUtil { } try { swtDisplay.syncExec(new Runnable() { + @Override public void run() { } }); } catch (Exception e) { } -- cgit v1.2.3 From 9b2013182516b77a39123894ad1b71619bd9785b Mon Sep 17 00:00:00 2001 From: Harvey Harrison Date: Fri, 18 Oct 2013 00:16:51 -0700 Subject: jogl: avoid creating a second String object, one is enough One String is already being built, passing it to new String() is just wasteful as the temp String can be returned just as easily. Signed-off-by: Harvey Harrison --- src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java | 2 +- src/nativewindow/classes/javax/media/nativewindow/util/Insets.java | 2 +- src/nativewindow/classes/javax/media/nativewindow/util/Point.java | 2 +- src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java | 2 +- src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java | 2 +- src/newt/classes/com/jogamp/newt/MonitorMode.java | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java index b8dc53c83..24ccc836a 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Dimension.java @@ -87,7 +87,7 @@ public class Dimension implements Cloneable, DimensionImmutable { @Override public String toString() { - return new String(width+" x "+height); + return width + " x " + height; } @Override diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java index c84359dcd..3644916fe 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Insets.java @@ -103,7 +103,7 @@ public class Insets implements Cloneable, InsetsImmutable { @Override public String toString() { - return new String("[ l "+l+", r "+r+" - t "+t+", b "+b+" - "+getTotalWidth()+"x"+getTotalHeight()+"]"); + return "[ l "+l+", r "+r+" - t "+t+", b "+b+" - "+getTotalWidth()+"x"+getTotalHeight()+"]"; } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java index 57c6fb716..331c1388e 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Point.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Point.java @@ -99,7 +99,7 @@ public class Point implements Cloneable, PointImmutable { @Override public String toString() { - return new String( x + " / " + y ); + return x + " / " + y; } public final void set(int x, int y) { this.x = x; this.y = y; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java index 8dc8f4562..d0d8bfb13 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/Rectangle.java @@ -195,7 +195,7 @@ public class Rectangle implements Cloneable, RectangleImmutable { @Override public String toString() { - return new String("[ "+x+" / "+y+" "+width+" x "+height+" ]"); + return "[ "+x+" / "+y+" "+width+" x "+height+" ]"; } } diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java index f1749dfa6..77619731f 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/SurfaceSize.java @@ -58,7 +58,7 @@ public class SurfaceSize implements Comparable { @Override public final String toString() { - return new String("[ "+resolution+" x "+bitsPerPixel+" bpp ]"); + return "[ "+resolution+" x "+bitsPerPixel+" bpp ]"; } /** diff --git a/src/newt/classes/com/jogamp/newt/MonitorMode.java b/src/newt/classes/com/jogamp/newt/MonitorMode.java index 59f28e791..9690f18db 100644 --- a/src/newt/classes/com/jogamp/newt/MonitorMode.java +++ b/src/newt/classes/com/jogamp/newt/MonitorMode.java @@ -176,7 +176,7 @@ public class MonitorMode implements Comparable { } @Override public final String toString() { - return new String(surfaceSize+" @ "+refreshRate+" Hz, flags ["+flags2String(flags).toString()+"]"); + return surfaceSize+" @ "+refreshRate+" Hz, flags ["+flags2String(flags).toString()+"]"; } /** -- cgit v1.2.3 From 946e0b59847de43d3dd51080abe7b9703d431e5f Mon Sep 17 00:00:00 2001 From: Harvey Harrison Date: Fri, 18 Oct 2013 07:55:37 -0700 Subject: jogl: replce more unneeded String() construction Signed-off-by: Harvey Harrison --- .../classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java | 2 +- .../classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java | 9 ++++----- .../classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java | 6 +++--- 3 files changed, 8 insertions(+), 9 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java index 4903e6acd..44fbf1c6d 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java +++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java @@ -137,7 +137,7 @@ public abstract class CompileShader { } String dirname; if (lastSlash < 0) { - dirname = new String(); + dirname = ""; } else { dirname = path.substring(0, lastSlash + 1); } diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java b/src/jogl/classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java index 24198703a..05a94def8 100644 --- a/src/jogl/classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java +++ b/src/jogl/classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java @@ -183,16 +183,15 @@ public class OMXGLMediaPlayer extends EGLMediaPlayerImpl { } private String replaceAll(String orig, String search, String repl) { - String dest=null; + StringBuilder dest = new StringBuilder(); // In case replaceAll / java.util.regex.* is not supported (-> CVM) int i=0,j; - dest = new String(); while((j=orig.indexOf(search, i))>=0) { - dest=dest.concat(orig.substring(i, j)); - dest=dest.concat(repl); + dest.append(orig.substring(i, j)); + dest.append(repl); i=j+1; } - return dest.concat(orig.substring(i, orig.length())); + return dest.append(orig.substring(i, orig.length())).toString(); } private void errorCheckEGL(String s) { diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java index c02fc0a04..eeec66376 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/DirectDataBufferInt.java @@ -70,9 +70,9 @@ public final class DirectDataBufferInt extends DataBuffer { @Override public String toString() { - return new String("BufferedImageInt@"+Integer.toHexString(hashCode()) - +": custom/internal type = "+customImageType+"/"+getType() - +" "+getColorModel()+" "+getRaster()); + return "BufferedImageInt@"+Integer.toHexString(hashCode()) + +": custom/internal type = "+customImageType+"/"+getType() + +" "+getColorModel()+" "+getRaster(); } } -- cgit v1.2.3 From 2e13993b57061e897889a3a6f4a1d44a19c32d11 Mon Sep 17 00:00:00 2001 From: Harvey Harrison Date: Fri, 18 Oct 2013 08:06:46 -0700 Subject: jogl: remove clone() method that only throws Exceptions commit: a4e3f241cfba55e407c68eba91ffcc4beb0758b5 (Analysis of glXMakeCurrent freeze on ATI fglrx 8.78.6; Misc ..) Removed 'implements Clonable' from NamedDisplay, which means Object.clone() will always throw CloneNotSupportedException. Kill clone(). Signed-off-by: Harvey Harrison --- src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java | 5 ----- 1 file changed, 5 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java index 2576c7db1..02e43791c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java +++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java @@ -325,11 +325,6 @@ public class X11Util implements ToolkitProperties { public final boolean isUncloseable() { return unCloseable; } public final Throwable getCreationStack() { return creationStack; } - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - @Override public String toString() { return "NamedX11Display["+name+", 0x"+Long.toHexString(handle)+", refCount "+refCount+", unCloseable "+unCloseable+"]"; -- cgit v1.2.3 From 5a79f9138d3aa72ce683f790988bc686cd87e2e1 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 23 Oct 2013 18:18:44 +0200 Subject: MacOSXJAWTWindow.CALayer DEBUG: Only Dump AWT location-on-screen if property DEBUG_CALAYER_POS_CRITICAL is explicitly set. - DEBUG_CALAYER_POS_CRITICAL = nativewindow.debug.JAWT.OSXCALayerPos Since AWT's location-on-screen query can cause an AWT deadlock, which is the sole purpose of our custom lock-free impl, don't enable it's DEBUG output w/ default DEBUG flags. --- .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java index 600aa6cb2..8d46d805a 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java @@ -54,6 +54,7 @@ import javax.media.nativewindow.util.Point; import com.jogamp.nativewindow.awt.JAWTWindow; +import jogamp.nativewindow.Debug; import jogamp.nativewindow.awt.AWTMisc; import jogamp.nativewindow.jawt.JAWT; import jogamp.nativewindow.jawt.JAWTFactory; @@ -64,6 +65,14 @@ import jogamp.nativewindow.jawt.macosx.JAWT_MacOSXDrawingSurfaceInfo; import jogamp.nativewindow.macosx.OSXUtil; public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { + /** May lead to deadlock, due to AWT pos comparison .. don't enable for Applets! */ + private static final boolean DEBUG_CALAYER_POS_CRITICAL; + + static { + Debug.initSingleton(); + DEBUG_CALAYER_POS_CRITICAL = Debug.isPropertyDefined("nativewindow.debug.JAWT.OSXCALayerPos", true /* jnlpAlias */); + } + public MacOSXJAWTWindow(Object comp, AbstractGraphicsConfiguration config) { super(comp, config); if(DEBUG) { @@ -122,7 +131,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { p1.translate(-outterInsets.left, -outterInsets.top); } - if( DEBUG ) { + if( DEBUG_CALAYER_POS_CRITICAL ) { final java.awt.Point pA0 = component.getLocationOnScreen(); final Point pA1 = new Point(pA0.x, pA0.y); pA1.translate(-outterComp.getX(), -outterComp.getY()); @@ -131,6 +140,8 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { } System.err.println("JAWTWindow.attachSurfaceLayerImpl: "+toHexString(layerHandle) + ", [ins "+outterInsets+"], pA "+pA0+" -> "+pA1+ ", p0 "+p0+" -> "+p1+", bounds "+bounds); + } else if( DEBUG ) { + System.err.println("JAWTWindow.attachSurfaceLayerImpl: "+toHexString(layerHandle) + ", [ins "+outterInsets+"], p0 "+p0+" -> "+p1+", bounds "+bounds); } OSXUtil.AddCASublayer(rootSurfaceLayer, layerHandle, p1.getX(), p1.getY(), getWidth(), getHeight(), JAWTUtil.getOSXCALayerQuirks()); } } ); @@ -152,7 +163,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { p1.translate(-outterInsets.left, -outterInsets.top); } - if( DEBUG ) { + if( DEBUG_CALAYER_POS_CRITICAL ) { final java.awt.Point pA0 = component.getLocationOnScreen(); final Point pA1 = new Point(pA0.x, pA0.y); pA1.translate(-outterComp.getX(), -outterComp.getY()); @@ -162,6 +173,9 @@ public class MacOSXJAWTWindow extends JAWTWindow implements MutableSurface { System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", quirks "+caLayerQuirks+", visible "+visible+ ", [ins "+outterInsets+"], pA "+pA0+" -> "+pA1+ ", p0 "+p0+" -> "+p1+", bounds "+bounds); + } else if( DEBUG ) { + System.err.println("JAWTWindow.layoutSurfaceLayerImpl: "+toHexString(layerHandle) + ", quirks "+caLayerQuirks+", visible "+visible+ + ", [ins "+outterInsets+"], p0 "+p0+" -> "+p1+", bounds "+bounds); } OSXUtil.FixCALayerLayout(rootSurfaceLayer, layerHandle, visible, p1.getX(), p1.getY(), getWidth(), getHeight(), caLayerQuirks); } -- cgit v1.2.3 From 887dbdb34d71a3a266b7854bc9a3842aad1032f9 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 31 Oct 2013 04:34:28 +0100 Subject: Fix Bug 878 - JAWTWindow's HierarchyListener doesn't set component visible (again) on 'addNotify(..)' - GLCanvas in JtabbedPane disappear Regression of commit e33e6374e0be0454f7e9732b5f897f84dbc3c4dc (Fix for Bug 729 and Bug 849) ! +++ JAWTWindow's HierarchyListener doesn't set component visible (again) on 'addNotify(..)' It only renders the component invisible after removeNotify() which is performed implicit anyways .. Case java.awt.event.HierarchyEvent.DISPLAYABILITY_CHANGED shall perform similar as our java.awt.event.HierarchyEvent.SHOWING_CHANGED impl. +++ Tested on Gnu/Linux X11 and OSX incl. re-test Bug 729 and Bug 849 unit tests. --- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 26 +-- ...estBug816JTabbedPanelVisibilityB849B878AWT.java | 175 +++++++++++++++++++++ 2 files changed, 190 insertions(+), 11 deletions(-) create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816JTabbedPanelVisibilityB849B878AWT.java (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 49b2daeae..a99737613 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -124,18 +124,20 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, private boolean globalVisibility = localVisibility; private boolean visibilityPropagation = false; + private String id(Object obj) { return "0x"+Integer.toHexString(obj.hashCode()); } + private String s(ComponentEvent e) { return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"],"+Platform.getNewline()+ - " ** COMP "+e.getComponent()+Platform.getNewline()+ - " ** SOURCE "+e.getSource()+Platform.getNewline()+ + " ** COMP "+id(e.getComponent())+": "+e.getComponent()+Platform.getNewline()+ + " ** SOURCE "+id(e.getSource())+": "+e.getSource()+Platform.getNewline()+ " ** THIS "+component; } private String s(HierarchyEvent e) { return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"], changeBits 0x"+Long.toHexString(e.getChangeFlags())+Platform.getNewline()+ - " ** COMP "+e.getComponent()+Platform.getNewline()+ - " ** SOURCE "+e.getSource()+Platform.getNewline()+ - " ** CHANGED "+e.getChanged()+Platform.getNewline()+ - " ** CHANGEDPARENT "+e.getChangedParent()+Platform.getNewline()+ + " ** COMP "+id(e.getComponent())+": "+e.getComponent()+Platform.getNewline()+ + " ** SOURCE "+id(e.getSource())+": "+e.getSource()+Platform.getNewline()+ + " ** CHANGED "+id(e.getChanged())+": "+e.getChanged()+Platform.getNewline()+ + " ** CHANGEDPARENT "+id(e.getChangedParent())+": "+e.getChangedParent()+Platform.getNewline()+ " ** THIS "+component; } @@ -177,14 +179,16 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, final java.awt.Component changed = e.getChanged(); if( 0 != ( java.awt.event.HierarchyEvent.DISPLAYABILITY_CHANGED & bits ) ) { final boolean displayable = changed.isDisplayable(); - final boolean resetLocalVisibility = changed == component && !displayable && localVisibility != component.isVisible(); - if( resetLocalVisibility ) { - // Reset components local state if detached from parent, i.e. 'removeNotify()' + final boolean propagateDisplayability = changed == component && ( displayable && localVisibility ) != component.isVisible(); + if( propagateDisplayability ) { + // Propagate parent's displayability, i.e. 'removeNotify()' and 'addNotify()' + final boolean _visible = displayable && localVisibility; visibilityPropagation = true; + globalVisibility = displayable; if(DEBUG) { - System.err.println("JAWTWindow.hierarchyChanged DISPLAYABILITY_CHANGED (1): displayable "+displayable+", "+s(e)); + System.err.println("JAWTWindow.hierarchyChanged DISPLAYABILITY_CHANGED (1): displayable "+displayable+" -> visible "+_visible+", "+s(e)); } - component.setVisible(localVisibility); + component.setVisible(_visible); } else if(DEBUG) { System.err.println("JAWTWindow.hierarchyChanged DISPLAYABILITY_CHANGED (x): displayable "+displayable+", "+s(e)); } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816JTabbedPanelVisibilityB849B878AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816JTabbedPanelVisibilityB849B878AWT.java new file mode 100644 index 000000000..f28a034dd --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816JTabbedPanelVisibilityB849B878AWT.java @@ -0,0 +1,175 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.test.junit.jogl.awt; + +import java.awt.BorderLayout; +import java.lang.reflect.InvocationTargetException; + +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLProfile; +import javax.media.opengl.awt.GLCanvas; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; + +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.MiscUtils; +import com.jogamp.opengl.test.junit.util.UITestCase; + +/** + * AWT JFrame w/ JTabbedPanel, Moving GLCanvas between it's tabs while selecting. + *

                            + * Validates bugs: + *

                              + *
                            • Bug 816: OSX CALayer Positioning Bug
                            • + *
                            • Bug 729: OSX CALayer shall honor the Component's visibility state
                            • + *
                            • Bug 849: AWT GLAutoDrawables (JAWTWindow) shall honor it's parent visibility state
                            • + *
                            • Bug 878: JAWTWindow's HierarchyListener doesn't set component visible (again) on 'addNotify(..)' - GLCanvas in JtabbedPane disappear
                            • + *
                            + *

                            + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestBug816JTabbedPanelVisibilityB849B878AWT extends UITestCase { + + static long durationPerTest = 500*4; // ms + static boolean manual = false; + + @Test + public void test() throws InterruptedException, InvocationTargetException { + final JFrame frame = new JFrame("TestBug816OSXCALayerPos03dBug878AWT"); + + final JPanel panel1 = new javax.swing.JPanel(); + final JPanel panel2 = new javax.swing.JPanel(); + + panel1.setLayout(new BorderLayout()); + panel2.setLayout(new BorderLayout()); + + GLProfile profile = GLProfile.get(GLProfile.GL2ES2); + GLCapabilities glCapabilities = new GLCapabilities(profile); + final GLCanvas glCanvas = new GLCanvas(glCapabilities); + glCanvas.setSize(new java.awt.Dimension(640, 480)); + glCanvas.addGLEventListener(new GearsES2(1)); + panel1.add(glCanvas, BorderLayout.CENTER); + + final JTabbedPane tabbedPanel = new JTabbedPane(); + tabbedPanel.addTab("tab1", panel1); + tabbedPanel.addTab("tab2", panel2); + + tabbedPanel.addChangeListener(new javax.swing.event.ChangeListener() { + @Override + public void stateChanged(javax.swing.event.ChangeEvent evt) { + if (tabbedPanel.getSelectedIndex() == 0) { + dumpGLCanvasStats(glCanvas); + panel1.add(glCanvas, BorderLayout.CENTER); + dumpGLCanvasStats(glCanvas); + } else { + System.err.println("XXXX Add GLCanvas Panel1("+id(panel1)+" -> Panel2("+id(panel2)+") START"); + dumpGLCanvasStats(glCanvas); + panel2.add(glCanvas, BorderLayout.CENTER); + dumpGLCanvasStats(glCanvas); + } + } + }); + + frame.setContentPane(tabbedPanel); + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame.pack(); + System.err.println("XXX SetVisible ON XXX GLCanvas on Panel1("+id(panel1)+")"); + frame.setVisible(true); + }}); + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame, true)); + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glCanvas, true)); + dumpGLCanvasStats(glCanvas); + + if(manual) { + for(long w=durationPerTest; w>0; w-=100) { + Thread.sleep(100); + } + } else { + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + System.err.println("XXXX Add GLCanvas Panel2("+id(panel2)+") -> Panel1("+id(panel1)+" START"); + tabbedPanel.setSelectedIndex(0); + }}); + Thread.sleep(durationPerTest/4); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + System.err.println("XXXX Add GLCanvas Panel1("+id(panel1)+" -> Panel2("+id(panel2)+") START"); + tabbedPanel.setSelectedIndex(1); + }}); + Thread.sleep(durationPerTest/4); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + System.err.println("XXXX Add GLCanvas Panel2("+id(panel2)+") -> Panel1("+id(panel1)+" START"); + tabbedPanel.setSelectedIndex(0); + }}); + Thread.sleep(durationPerTest/4); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + System.err.println("XXXX Add GLCanvas Panel1("+id(panel1)+" -> Panel2("+id(panel2)+") START"); + tabbedPanel.setSelectedIndex(1); + }}); + Thread.sleep(durationPerTest/4); + } + + SwingUtilities.invokeLater(new Runnable() { + public void run() { + System.err.println("XXX SetVisible OFF XXX"); + frame.dispose(); + } }); + } + + private static String id(Object obj) { return "0x"+Integer.toHexString(obj.hashCode()); } + + static void dumpGLCanvasStats(GLCanvas glCanvas) { + System.err.println("XXXX GLCanvas: comp "+glCanvas+", visible "+glCanvas.isVisible()+", showing "+glCanvas.isShowing()+ + ", displayable "+glCanvas.isDisplayable()+", "+glCanvas.getWidth()+"x"+glCanvas.getHeight()); + } + + public static void main(String args[]) { + for(int i=0; i Date: Mon, 4 Nov 2013 15:07:14 +0100 Subject: Bug 888 - Validate CPU Runtime Performance: X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(..) X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(..) ran over all FB configs and for each it grabbed native config values separately. Fetching them in bulk mode saves around 7% of this function's cost. Also reuse XRenderPictFormat instance for 'XRenderDirectFormat XRenderFindVisualFormat(..)' call, saving a few NIO creation cycles w/ StructAccessor. Biggest savior is X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationFBConfig()'s fast path w/o chooser and usable 1st FBConfig. Here we only issue 'GLXFBConfig2GLCapabilities(..)' on the first valid entry. Test w/ 50 X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationFBConfig() invocations: - pre change: 1.708 ms - post change: 650 ms Time is no spent almost solely on native glXChooseFBConfig (546ms). --- make/config/jogl/glx-CustomCCode.c | 25 ++++ make/config/jogl/glx-CustomJavaCode.java | 22 ++++ make/config/nativewindow/x11-CustomJavaCode.java | 15 +++ .../x11/glx/X11GLXGraphicsConfiguration.java | 144 +++++++++++++++------ .../glx/X11GLXGraphicsConfigurationFactory.java | 46 ++++--- src/nativewindow/native/x11/Xmisc.c | 15 +++ 6 files changed, 206 insertions(+), 61 deletions(-) (limited to 'src/nativewindow') diff --git a/make/config/jogl/glx-CustomCCode.c b/make/config/jogl/glx-CustomCCode.c index 71dc68b08..5c73dfea6 100644 --- a/make/config/jogl/glx-CustomCCode.c +++ b/make/config/jogl/glx-CustomCCode.c @@ -59,6 +59,31 @@ static void _initClazzAccess(JNIEnv *env) { } } +/* Java->C glue code: + * Java package: jogamp.opengl.x11.glx.GLX + * Java method: int glXGetFBConfigAttributes(long dpy, long config, IntBuffer attributes, IntBuffer values) + */ +JNIEXPORT jint JNICALL +Java_jogamp_opengl_x11_glx_GLX_dispatch_1glXGetFBConfigAttributes(JNIEnv *env, jclass _unused, jlong dpy, jlong config, jint attributeCount, jobject attributes, jint attributes_byte_offset, jobject values, jint values_byte_offset, jlong procAddress) { + typedef int (APIENTRY*_local_PFNGLXGETFBCONFIGATTRIBPROC)(Display * dpy, GLXFBConfig config, int attribute, int * value); + _local_PFNGLXGETFBCONFIGATTRIBPROC ptr_glXGetFBConfigAttrib = (_local_PFNGLXGETFBCONFIGATTRIBPROC) (intptr_t) procAddress; + assert(ptr_glXGetFBConfigAttrib != NULL); + + int err = 0; + if ( attributeCount > 0 && NULL != attributes ) { + int i; + int * attributes_ptr = (int *) (((char*) (*env)->GetDirectBufferAddress(env, attributes)) + attributes_byte_offset); + int * values_ptr = (int *) (((char*) (*env)->GetDirectBufferAddress(env, values)) + values_byte_offset); + for(i=0; 0 == err && iC glue code: * Java package: jogamp.opengl.x11.glx.GLX * Java method: XVisualInfo glXGetVisualFromFBConfig(long dpy, long config) diff --git a/make/config/jogl/glx-CustomJavaCode.java b/make/config/jogl/glx-CustomJavaCode.java index f3e743930..4cce05dda 100644 --- a/make/config/jogl/glx-CustomJavaCode.java +++ b/make/config/jogl/glx-CustomJavaCode.java @@ -1,4 +1,26 @@ + /** + * Returns the GLX error value, i.e. 0 for no error. In case of an error values.get(values.getPosition()) contains the attributes index causing the error. + *

                            + * Entry point to C language function: int glXGetFBConfigAttrib(Display * dpy, GLXFBConfig config, int attribute, int * value);
                            Part of GLX_VERSION_1_3 + *

                            + */ + public static int glXGetFBConfigAttributes(long dpy, long config, IntBuffer attributes, IntBuffer values) { + if( attributes == null || values == null ) { + throw new RuntimeException("arrays buffers are null"); + } + if( !Buffers.isDirect(attributes) || !Buffers.isDirect(values) ) { + throw new RuntimeException("arrays buffers are not direct"); + } + if( attributes.remaining() > values.remaining() ) { + throw new RuntimeException("not enough values "+values+" for attributes "+attributes); + } + final long __addr = glxProcAddressTable._addressof_glXGetFBConfigAttrib; + return dispatch_glXGetFBConfigAttributes(dpy, config, attributes.remaining(), attributes, Buffers.getDirectBufferByteOffset(attributes), + values, Buffers.getDirectBufferByteOffset(values), __addr); + } + private static native int dispatch_glXGetFBConfigAttributes(long dpy, long config, int attributeCount, Object attributes, int attributes_byte_offset, Object values, int valuesOffset, long procAddr); + /** Interface to C language function:
                            - Alias for:
                            XVisualInfo * glXGetVisualFromFBConfigSGIX, glXGetVisualFromFBConfig(Display * dpy, GLXFBConfig config); */ public static XVisualInfo glXGetVisualFromFBConfig(long dpy, long config) { diff --git a/make/config/nativewindow/x11-CustomJavaCode.java b/make/config/nativewindow/x11-CustomJavaCode.java index 4240c5e2f..d1e011184 100644 --- a/make/config/nativewindow/x11-CustomJavaCode.java +++ b/make/config/nativewindow/x11-CustomJavaCode.java @@ -1,4 +1,19 @@ + /** Interface to C language function:
                            XRenderPictFormat * XRenderFindVisualFormat(Display * dpy, const Visual * visual); */ + public static boolean XRenderFindVisualFormat(long dpy, long visual, XRenderPictFormat dest) { + if( dest == null ) { + throw new RuntimeException("dest is null"); + } + final ByteBuffer destBuffer = dest.getBuffer(); + if( !Buffers.isDirect(destBuffer) ) { + throw new RuntimeException("dest buffer is not direct"); + } + return XRenderFindVisualFormat1(dpy, visual, destBuffer); + } + /** Entry point to C language function: XVisualInfo * XGetVisualInfo(Display * , long, XVisualInfo * , int * ); */ + private static native boolean XRenderFindVisualFormat1(long dpy, long visual, ByteBuffer xRenderPictFormat); + + /** Interface to C language function:
                            XVisualInfo * XGetVisualInfo(Display * , long, XVisualInfo * , int * ); */ public static XVisualInfo[] XGetVisualInfo(long arg0, long arg1, XVisualInfo arg2, int[] arg3, int arg3_offset) { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java index 4d1ed3985..ee3e1a3d7 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java @@ -34,6 +34,8 @@ package jogamp.opengl.x11.glx; import java.nio.IntBuffer; +import java.util.ArrayList; +import java.util.List; import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.GraphicsConfigurationFactory; @@ -61,7 +63,7 @@ import com.jogamp.nativewindow.x11.X11GraphicsScreen; public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implements Cloneable { public static final int MAX_ATTRIBS = 128; - private GLCapabilitiesChooser chooser; + private final GLCapabilitiesChooser chooser; X11GLXGraphicsConfiguration(X11GraphicsScreen screen, X11GLCapabilities capsChosen, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser) { @@ -274,15 +276,47 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem } return renderPictFmt.getDirect(); } + static XRenderDirectFormat XVisual2XRenderMask(long dpy, long visual, XRenderPictFormat dest) { + if( !X11Lib.XRenderFindVisualFormat(dpy, visual, dest) ) { + return null; + } else { + return dest.getDirect(); + } + } + + static X11GLCapabilities GLXFBConfig2GLCapabilities(final X11GraphicsDevice device, final GLProfile glp, final long fbcfg, + final int winattrmask, final boolean isMultisampleAvailable) { + final IntBuffer tmp = Buffers.newDirectIntBuffer(1); + final XRenderPictFormat xRenderPictFormat= XRenderPictFormat.create(); + return GLXFBConfig2GLCapabilities(device, glp, fbcfg, winattrmask, isMultisampleAvailable, tmp, xRenderPictFormat); + } - static X11GLCapabilities GLXFBConfig2GLCapabilities(X11GraphicsDevice device, GLProfile glp, long fbcfg, - int winattrmask, boolean isMultisampleAvailable) { + static List GLXFBConfig2GLCapabilities(final X11GraphicsDevice device, final GLProfile glp, final PointerBuffer fbcfgsL, + final int winattrmask, final boolean isMultisampleAvailable, boolean onlyFirstValid) { + final IntBuffer tmp = Buffers.newDirectIntBuffer(1); + final XRenderPictFormat xRenderPictFormat= XRenderPictFormat.create(); + final List result = new ArrayList(); + for (int i = 0; i < fbcfgsL.limit(); i++) { + final long fbcfg = fbcfgsL.get(i); + final GLCapabilitiesImmutable c = GLXFBConfig2GLCapabilities(device, glp, fbcfg, winattrmask, isMultisampleAvailable, tmp, xRenderPictFormat); + if( null != c ) { + result.add(c); + if( onlyFirstValid ) { + break; + } + } + } + return result; + } + static X11GLCapabilities GLXFBConfig2GLCapabilities(final X11GraphicsDevice device, final GLProfile glp, final long fbcfg, + final int winattrmask, final boolean isMultisampleAvailable, + final IntBuffer tmp, final XRenderPictFormat xRenderPictFormat) { + final long display = device.getHandle(); final int allDrawableTypeBits = FBCfgDrawableTypeBits(device, fbcfg); int drawableTypeBits = winattrmask & allDrawableTypeBits; - final long display = device.getHandle(); - int fbcfgid = X11GLXGraphicsConfiguration.glXFBConfig2FBConfigID(display, fbcfg); - XVisualInfo visualInfo = GLX.glXGetVisualFromFBConfig(display, fbcfg); + final int fbcfgid = X11GLXGraphicsConfiguration.glXFBConfig2FBConfigID(display, fbcfg); + final XVisualInfo visualInfo = GLX.glXGetVisualFromFBConfig(display, fbcfg); if(null == visualInfo) { if(DEBUG) { System.err.println("X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities: Null XVisualInfo for FBConfigID 0x" + Integer.toHexString(fbcfgid)); @@ -290,51 +324,87 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem // onscreen must have an XVisualInfo drawableTypeBits &= ~(GLGraphicsConfigurationUtil.WINDOW_BIT | GLGraphicsConfigurationUtil.FBO_BIT); } - if( 0 == drawableTypeBits ) { - return null; + if(DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities: zero drawablebits: winattrmask: "+toHexString(winattrmask)+", offscreen "+(null == visualInfo)); + } + return null; } - final IntBuffer tmp = Buffers.newDirectIntBuffer(1); if(GLX.GLX_BAD_ATTRIBUTE == GLX.glXGetFBConfigAttrib(display, fbcfg, GLX.GLX_RENDER_TYPE, tmp)) { + if(DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities: FBConfig invalid (1): fbcfg: "+toHexString(fbcfg)); + } return null; } if( 0 == ( GLX.GLX_RGBA_BIT & tmp.get(0) ) ) { - return null; // no RGBA -> color index not supported + // no RGBA -> color index not supported + if(DEBUG) { + System.err.println("X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities: FBConfig not RGBA (2): fbcfg: "+toHexString(fbcfg)); + } + return null; } - final X11GLCapabilities res = new X11GLCapabilities(visualInfo, fbcfg, fbcfgid, glp); - if (isMultisampleAvailable) { - res.setSampleBuffers(glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLE_BUFFERS, tmp) != 0); - res.setNumSamples (glXGetFBConfig(display, fbcfg, GLX.GLX_SAMPLES, tmp)); - } + final X11GLCapabilities caps = new X11GLCapabilities(visualInfo, fbcfg, fbcfgid, glp); + final XRenderDirectFormat xrmask = ( null != visualInfo ) ? - XVisual2XRenderMask( display, visualInfo.getVisual() ) : + XVisual2XRenderMask( display, visualInfo.getVisual(), xRenderPictFormat) : null ; + + final int _attributes[] = { + GLX.GLX_SAMPLE_BUFFERS, + GLX.GLX_SAMPLES, + GLX.GLX_DOUBLEBUFFER, + GLX.GLX_STEREO, + GLX.GLX_CONFIG_CAVEAT, + GLX.GLX_RED_SIZE, + GLX.GLX_GREEN_SIZE, + GLX.GLX_BLUE_SIZE, + GLX.GLX_ALPHA_SIZE, + GLX.GLX_ACCUM_RED_SIZE, + GLX.GLX_ACCUM_GREEN_SIZE, + GLX.GLX_ACCUM_BLUE_SIZE, + GLX.GLX_ACCUM_ALPHA_SIZE, + GLX.GLX_DEPTH_SIZE, + GLX.GLX_STENCIL_SIZE + }; + final int offset = isMultisampleAvailable ? 0 : 2; + final IntBuffer attributes = Buffers.newDirectIntBuffer(_attributes); + attributes.position(offset); + final IntBuffer values = Buffers.newDirectIntBuffer(attributes.remaining()); + final int err = GLX.glXGetFBConfigAttributes(display, fbcfg, attributes, values); + if (0 != err) { + throw new GLException("glXGetFBConfig("+toHexString(attributes.get(offset+values.get(0)))+") failed: error code " + glXGetFBConfigErrorCode(err)); + } + int j=0; + if (isMultisampleAvailable) { + caps.setSampleBuffers(values.get(j++) != 0); + caps.setNumSamples (values.get(j++)); + } final int alphaMask = ( null != xrmask ) ? xrmask.getAlphaMask() : 0; - res.setBackgroundOpaque( 0 >= alphaMask ); - if( !res.isBackgroundOpaque() ) { - res.setTransparentRedValue(xrmask.getRedMask()); - res.setTransparentGreenValue(xrmask.getGreenMask()); - res.setTransparentBlueValue(xrmask.getBlueMask()); - res.setTransparentAlphaValue(alphaMask); + caps.setBackgroundOpaque( 0 >= alphaMask ); + if( !caps.isBackgroundOpaque() ) { + caps.setTransparentRedValue(xrmask.getRedMask()); + caps.setTransparentGreenValue(xrmask.getGreenMask()); + caps.setTransparentBlueValue(xrmask.getBlueMask()); + caps.setTransparentAlphaValue(alphaMask); } // ALPHA shall be set at last - due to it's auto setting by the above (!opaque / samples) - res.setDoubleBuffered(glXGetFBConfig(display, fbcfg, GLX.GLX_DOUBLEBUFFER, tmp) != 0); - res.setStereo (glXGetFBConfig(display, fbcfg, GLX.GLX_STEREO, tmp) != 0); - res.setHardwareAccelerated(glXGetFBConfig(display, fbcfg, GLX.GLX_CONFIG_CAVEAT, tmp) != GLX.GLX_SLOW_CONFIG); - res.setRedBits (glXGetFBConfig(display, fbcfg, GLX.GLX_RED_SIZE, tmp)); - res.setGreenBits (glXGetFBConfig(display, fbcfg, GLX.GLX_GREEN_SIZE, tmp)); - res.setBlueBits (glXGetFBConfig(display, fbcfg, GLX.GLX_BLUE_SIZE, tmp)); - res.setAlphaBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ALPHA_SIZE, tmp)); - res.setAccumRedBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_RED_SIZE, tmp)); - res.setAccumGreenBits(glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_GREEN_SIZE, tmp)); - res.setAccumBlueBits (glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_BLUE_SIZE, tmp)); - res.setAccumAlphaBits(glXGetFBConfig(display, fbcfg, GLX.GLX_ACCUM_ALPHA_SIZE, tmp)); - res.setDepthBits (glXGetFBConfig(display, fbcfg, GLX.GLX_DEPTH_SIZE, tmp)); - res.setStencilBits (glXGetFBConfig(display, fbcfg, GLX.GLX_STENCIL_SIZE, tmp)); - - return (X11GLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, res); + caps.setDoubleBuffered(values.get(j++) != 0); + caps.setStereo (values.get(j++) != 0); + caps.setHardwareAccelerated(values.get(j++) != GLX.GLX_SLOW_CONFIG); + caps.setRedBits (values.get(j++)); + caps.setGreenBits (values.get(j++)); + caps.setBlueBits (values.get(j++)); + caps.setAlphaBits (values.get(j++)); + caps.setAccumRedBits (values.get(j++)); + caps.setAccumGreenBits(values.get(j++)); + caps.setAccumBlueBits (values.get(j++)); + caps.setAccumAlphaBits(values.get(j++)); + caps.setDepthBits (values.get(j++)); + caps.setStencilBits (values.get(j++)); + + return (X11GLCapabilities) GLGraphicsConfigurationUtil.fixWinAttribBitsAndHwAccel(device, drawableTypeBits, caps); } private static String glXGetFBConfigErrorCode(int err) { diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java index 6050dabbb..5c84597d5 100644 --- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java @@ -287,24 +287,23 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF final IntBuffer attribs = X11GLXGraphicsConfiguration.GLCapabilities2AttribList(capsChosen, true, isMultisampleAvailable, display, screen); final IntBuffer count = Buffers.newDirectIntBuffer(1); count.put(0, -1); - List availableCaps = new ArrayList(); final int winattrmask = GLGraphicsConfigurationUtil.getExclusiveWinAttributeBits(capsChosen); + List availableCaps; // 1st choice: get GLCapabilities based on users GLCapabilities setting recommendedIndex as preferred choice, // skipped if xvisualID is given + final boolean hasGLXChosenCaps; if( VisualIDHolder.VID_UNDEFINED == xvisualID ) { fbcfgsL = GLX.glXChooseFBConfig(display, screen, attribs, count); + hasGLXChosenCaps = fbcfgsL != null && fbcfgsL.limit()>0; + } else { + hasGLXChosenCaps = false; } - if (fbcfgsL != null && fbcfgsL.limit()>0) { - for (int i = 0; i < fbcfgsL.limit(); i++) { - final GLCapabilitiesImmutable caps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(x11Device, glProfile, fbcfgsL.get(i), winattrmask, isMultisampleAvailable); - if( null != caps ) { - availableCaps.add(caps); - } else if(DEBUG) { - System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: FBConfig invalid (1): ("+x11Screen+","+capsChosen+"): fbcfg: "+toHexString(fbcfgsL.get(i))); - } - } + final boolean useRecommendedIndex = hasGLXChosenCaps && capsChosen.isBackgroundOpaque(); // only use recommended idx if not translucent + final boolean skipCapsChooser = null == chooser && useRecommendedIndex; // fast path: skip choosing if using recommended idx and null chooser is used + if (hasGLXChosenCaps) { + availableCaps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(x11Device, glProfile, fbcfgsL, winattrmask, isMultisampleAvailable, skipCapsChooser /* onlyFirstValid */); if(availableCaps.size() > 0) { - recommendedIndex = capsChosen.isBackgroundOpaque() ? 0 : -1; // only use recommended idx if not translucent + recommendedIndex = useRecommendedIndex ? 0 : -1; if (DEBUG) { System.err.println("glXChooseFBConfig recommended fbcfg " + toHexString(fbcfgsL.get(0)) + ", idx " + recommendedIndex); System.err.println("user caps " + capsChosen); @@ -314,6 +313,8 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF System.err.println("glXChooseFBConfig no caps for recommended fbcfg " + toHexString(fbcfgsL.get(0))); System.err.println("user caps " + capsChosen); } + } else { + availableCaps = new ArrayList(); } // 2nd choice: get all GLCapabilities available, no preferred recommendedIndex available @@ -328,15 +329,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } return null; } - - for (int i = 0; i < fbcfgsL.limit(); i++) { - final GLCapabilitiesImmutable caps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(x11Device, glProfile, fbcfgsL.get(i), winattrmask, isMultisampleAvailable); - if( null != caps ) { - availableCaps.add(caps); - } else if(DEBUG) { - System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: FBConfig invalid (2): ("+x11Screen+"): fbcfg: "+toHexString(fbcfgsL.get(i))); - } - } + availableCaps = X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(x11Device, glProfile, fbcfgsL, winattrmask, isMultisampleAvailable, false /* onlyOneValid */); } if(DEBUG) { @@ -346,9 +339,9 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF } } - if( VisualIDHolder.VID_UNDEFINED != xvisualID ) { + if( VisualIDHolder.VID_UNDEFINED != xvisualID ) { // implies !hasGLXChosenCaps for(int i=0; i chosenIndex ) { if (DEBUG) { System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: failed, return null"); @@ -445,7 +443,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF if( VisualIDHolder.VID_UNDEFINED != xvisualID ) { for(int i=0; i +#include + // #define VERBOSE_ON 1 #ifdef VERBOSE_ON @@ -320,6 +322,19 @@ Java_jogamp_nativewindow_x11_X11Util_setX11ErrorHandler0(JNIEnv *env, jclass _un NativewindowCommon_x11ErrorHandlerEnable(env, NULL, 1, onoff ? 1 : 0, quiet ? 1 : 0, 0 /* no dpy, force, no sync */); } +/* Java->C glue code: + * Java package: jogamp.nativewindow.x11.X11Lib + * Java method: boolean XRenderFindVisualFormat(long dpy, long visual, XRenderPictFormat dest) + */ +JNIEXPORT jboolean JNICALL +Java_jogamp_nativewindow_x11_X11Lib_XRenderFindVisualFormat1(JNIEnv *env, jclass _unused, jlong dpy, jlong visual, jobject xRenderPictFormat) { + XRenderPictFormat * dest = (XRenderPictFormat *) (*env)->GetDirectBufferAddress(env, xRenderPictFormat); + XRenderPictFormat * src = XRenderFindVisualFormat((Display *) (intptr_t) dpy, (Visual *) (intptr_t) visual); + if (NULL == src) return JNI_FALSE; + memcpy(dest, src, sizeof(XRenderPictFormat)); + return JNI_TRUE; +} + /* Java->C glue code: * Java package: jogamp.nativewindow.x11.X11Lib * Java method: XVisualInfo XGetVisualInfo(long arg0, long arg1, XVisualInfo arg2, java.nio.IntBuffer arg3) -- cgit v1.2.3 From 1d426dd08797a3164e0a7cdf6007d3e750650265 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 5 Nov 2013 16:53:18 +0100 Subject: JNI Code: Call DeleteLocalRef(..) manually. --- src/jogl/native/libav/ffmpeg_impl_template.c | 1 + src/nativewindow/native/x11/Xmisc.c | 1 + 2 files changed, 2 insertions(+) (limited to 'src/nativewindow') diff --git a/src/jogl/native/libav/ffmpeg_impl_template.c b/src/jogl/native/libav/ffmpeg_impl_template.c index 34a2baeb7..24fddd2c0 100644 --- a/src/jogl/native/libav/ffmpeg_impl_template.c +++ b/src/jogl/native/libav/ffmpeg_impl_template.c @@ -1275,6 +1275,7 @@ JNIEXPORT jint JNICALL FF_FUNC(readNextPacket0) pNIOBufferCurrent->nioRef = (*env)->NewGlobalRef(env, jSampleData); pNIOBufferCurrent->origPtr = data_ptr; pNIOBufferCurrent->size = data_size; + (*env)->DeleteLocalRef(env, jSampleData); if(pAV->verbose) { fprintf(stderr, "A NIO: Alloc ptr %p / ref %p, %d bytes\n", pNIOBufferCurrent->origPtr, pNIOBufferCurrent->nioRef, pNIOBufferCurrent->size); diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 2bf740233..442d0ceef 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -368,6 +368,7 @@ Java_jogamp_nativewindow_x11_X11Lib_XGetVisualInfo1__JJLjava_nio_ByteBuffer_2Lja jbyteSource = (*env)->NewDirectByteBuffer(env, _res, count * sizeof(XVisualInfo)); jbyteCopy = (*env)->CallStaticObjectMethod(env, clazzBuffers, cstrBuffers, jbyteSource); + (*env)->DeleteLocalRef(env, jbyteSource); XFree(_res); -- cgit v1.2.3 From 35ce176152b7d1e6d4eb52f203882fdce4b465c3 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 6 Nov 2013 07:09:01 +0100 Subject: NativeWindow *GraphicsDevice: Align constructors to simplify call hierarchy for analysis. --- .../com/jogamp/nativewindow/x11/X11GraphicsDevice.java | 8 +------- .../media/nativewindow/DefaultGraphicsDevice.java | 18 ++++-------------- 2 files changed, 5 insertions(+), 21 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index 40d212df3..10e3f7857 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -65,13 +65,7 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl * @see DefaultGraphicsDevice#DefaultGraphicsDevice(String, String, int, long) */ public X11GraphicsDevice(long display, int unitID, boolean owner) { - // FIXME: derive unitID from connection could be buggy, one DISPLAY for all screens for example.. - super(NativeWindowFactory.TYPE_X11, X11Lib.XDisplayString(display), unitID, display); - if(0==display) { - throw new NativeWindowException("null display"); - } - handleOwner = owner; - isXineramaEnabled = X11Util.XineramaIsEnabled(this); + this(display, unitID, NativeWindowFactory.getDefaultToolkitLock(NativeWindowFactory.TYPE_X11, display), owner); } /** diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java index d74954a0d..f916a8ef3 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java @@ -50,12 +50,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice * @param type */ public DefaultGraphicsDevice(String type, String connection, int unitID) { - this.type = type; - this.connection = connection; - this.unitID = unitID; - this.uniqueID = getUniqueID(type, connection, unitID); - this.handle = 0; - this.toolkitLock = NativeWindowFactory.getDefaultToolkitLock(type); + this(type, connection, unitID, 0, NativeWindowFactory.getDefaultToolkitLock(type)); } /** @@ -65,19 +60,14 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice * @param handle */ public DefaultGraphicsDevice(String type, String connection, int unitID, long handle) { - this.type = type; - this.connection = connection; - this.unitID = unitID; - this.uniqueID = getUniqueID(type, connection, unitID); - this.handle = handle; - this.toolkitLock = NativeWindowFactory.getDefaultToolkitLock(type, handle); + this(type, connection, unitID, handle, NativeWindowFactory.getDefaultToolkitLock(type, handle)); } /** - * Create an instance with the given {@link ToolkitLock} instance. + * Create an instance with the given {@link ToolkitLock} instance, or null {@link ToolkitLock} if null. * @param type * @param handle - * @param locker + * @param locker if null, a non blocking null lock is used. */ public DefaultGraphicsDevice(String type, String connection, int unitID, long handle, ToolkitLock locker) { this.type = type; -- cgit v1.2.3 From ce255aba6475c0a7b12f044a8ea700d5184f2b91 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 10 Nov 2013 14:09:00 +0100 Subject: Bug 899: Validate whether we propagate WNDPROC as retrieved from 'getDummyWndProc0()' in RegisteredClassFactory - Result: Yes we do. GDI.initSingleton() dummyWindowClassFactory RegisteredClassFactory[moduleHandle 0x13f3e0000, _dummyWindow_clazz, wndProc 0x6c101de6, shared[refCount 0, class null]] GDI.CreateDummyWindow() dummyWindowClassFactory RegisteredClassFactory[moduleHandle 0x13f3e0000, _dummyWindow_clazz, wndProc 0x6c101de6, shared[refCount 1, class RegisteredClass[handle 0x13f3e0000, _dummyWindow_clazz0]]] GDI.CreateDummyWindow() dummyWindowClass RegisteredClass[handle 0x13f3e0000, _dummyWindow_clazz0] ++ Note: The RegisteredClassFactory mechanism is used for NEWT Windows as well. --- .../classes/jogamp/nativewindow/windows/GDIUtil.java | 7 +++++++ .../jogamp/nativewindow/windows/RegisteredClassFactory.java | 12 ++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index db61b1efd..38a5b5bc6 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -60,6 +60,9 @@ public class GDIUtil implements ToolkitProperties { throw new NativeWindowException("GDI: Could not initialized native stub"); } dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0()); + if(DEBUG) { + System.out.println("GDI.initSingleton() dummyWindowClassFactory "+dummyWindowClassFactory); + } isInit = true; } } @@ -91,6 +94,10 @@ public class GDIUtil implements ToolkitProperties { public static long CreateDummyWindow(int x, int y, int width, int height) { synchronized(dummyWindowSync) { dummyWindowClass = dummyWindowClassFactory.getSharedClass(); + if(DEBUG) { + System.out.println("GDI.CreateDummyWindow() dummyWindowClassFactory "+dummyWindowClassFactory); + System.out.println("GDI.CreateDummyWindow() dummyWindowClass "+dummyWindowClass); + } return CreateDummyWindow0(dummyWindowClass.getHInstance(), dummyWindowClass.getName(), dummyWindowClass.getName(), x, y, width, height); } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java index e033a9f66..19a48d3bf 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java @@ -29,7 +29,9 @@ package jogamp.nativewindow.windows; import jogamp.nativewindow.Debug; + import java.util.ArrayList; + import javax.media.nativewindow.NativeWindowException; public class RegisteredClassFactory { @@ -45,14 +47,20 @@ public class RegisteredClassFactory { registeredFactories = new ArrayList(); } - private String classBaseName; - private long wndProc; + private final String classBaseName; + private final long wndProc; private RegisteredClass sharedClass = null; private int classIter = 0; private int sharedRefCount = 0; private final Object sync = new Object(); + private String toHexString(long l) { return "0x"+Long.toHexString(l); } + + @Override + public final String toString() { return "RegisteredClassFactory[moduleHandle "+toHexString(hInstance)+", "+classBaseName+ + ", wndProc "+toHexString(wndProc)+", shared[refCount "+sharedRefCount+", class "+sharedClass+"]]"; } + /** * Release the {@link RegisteredClass} of all {@link RegisteredClassFactory}. */ -- cgit v1.2.3 From 45ce96db65fa7cbfd3bcb3dd4503bc6251d2e493 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 10 Nov 2013 20:59:03 +0100 Subject: Fix Bug 889 [Related: Bug 816, Bug 849, Bug 729] - GLCanvas disappear when moves between two JFrame When JAWTWindow's visibility tracker updates component's local visibility, it should read it's local visibility state instead 'trusting' the passed state. Make JAWTWindow's visibility tracker DEBUG output more brief for readability. --- make/scripts/tests.sh | 3 +- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 31 ++- .../TestBug816GLCanvasFrameHoppingB849B889AWT.java | 262 +++++++++++++++++++++ .../jogl/awt/TestBug816OSXCALayerPos01AWT.java | 87 ++++--- .../jogl/awt/TestBug816OSXCALayerPos02AWT.java | 43 ++-- .../awt/TestBug816OSXCALayerPos03aB729AWT.java | 35 ++- .../awt/TestBug816OSXCALayerPos03bB849AWT.java | 35 ++- .../awt/TestBug816OSXCALayerPos03cB849AWT.java | 37 ++- 8 files changed, 401 insertions(+), 132 deletions(-) create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816GLCanvasFrameHoppingB849B889AWT.java (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 432f8f346..b7db47e11 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -478,7 +478,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol02NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestGLWindows02NEWTAnimated $* -testnoawt com.jogamp.opengl.test.junit.newt.TestGLWindows03NEWTAnimResize $* +#testnoawt com.jogamp.opengl.test.junit.newt.TestGLWindows03NEWTAnimResize $* #testnoawt com.jogamp.opengl.test.junit.newt.TestGLWindowInvisiblePointer01NEWT $* #testnoawt com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle01NEWT #testnoawt com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle02NEWT @@ -504,6 +504,7 @@ testnoawt com.jogamp.opengl.test.junit.newt.TestGLWindows03NEWTAnimResize $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03bB849AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03cB849AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816JTabbedPanelVisibilityB849B878AWT $* +testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816GLCanvasFrameHoppingB849B889AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04aAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04bAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug675BeansInDesignTimeAWT $* diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index a99737613..87966c9c6 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -124,21 +124,32 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, private boolean globalVisibility = localVisibility; private boolean visibilityPropagation = false; - private String id(Object obj) { return "0x"+Integer.toHexString(obj.hashCode()); } + private String id(Object obj) { return "0x" + ( null!=obj ? Integer.toHexString(obj.hashCode()) : "nil" ); } + private String str(Object obj) { + if( null == obj ) { + return "null"; + } else if( obj instanceof Component ) { + final Component c = (Component)obj; + return c.getClass().getSimpleName()+"[visible "+c.isVisible()+", showing "+c.isShowing()+", valid "+c.isValid()+ + ", displayable "+c.isDisplayable()+", "+c.getX()+"/"+c.getY()+" "+c.getWidth()+"x"+c.getHeight()+"]"; + } else { + return obj.getClass().getSimpleName()+"[..]"; + } + } private String s(ComponentEvent e) { return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"],"+Platform.getNewline()+ - " ** COMP "+id(e.getComponent())+": "+e.getComponent()+Platform.getNewline()+ - " ** SOURCE "+id(e.getSource())+": "+e.getSource()+Platform.getNewline()+ - " ** THIS "+component; + " ** COMP "+id(e.getComponent())+": "+str(e.getComponent())+Platform.getNewline()+ + " ** SOURCE "+id(e.getSource())+": "+str(e.getSource())+Platform.getNewline()+ + " ** THIS "+id(component)+": "+str(component); } private String s(HierarchyEvent e) { return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"], changeBits 0x"+Long.toHexString(e.getChangeFlags())+Platform.getNewline()+ - " ** COMP "+id(e.getComponent())+": "+e.getComponent()+Platform.getNewline()+ - " ** SOURCE "+id(e.getSource())+": "+e.getSource()+Platform.getNewline()+ - " ** CHANGED "+id(e.getChanged())+": "+e.getChanged()+Platform.getNewline()+ - " ** CHANGEDPARENT "+id(e.getChangedParent())+": "+e.getChangedParent()+Platform.getNewline()+ - " ** THIS "+component; + " ** COMP "+id(e.getComponent())+": "+str(e.getComponent())+Platform.getNewline()+ + " ** SOURCE "+id(e.getSource())+": "+str(e.getSource())+Platform.getNewline()+ + " ** CHANGED "+id(e.getChanged())+": "+str(e.getChanged())+Platform.getNewline()+ + " ** CHANGEDPARENT "+id(e.getChangedParent())+": "+str(e.getChangedParent())+Platform.getNewline()+ + " ** THIS "+id(component)+": "+str(component); } @Override @@ -207,7 +218,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } else if( changed == component ) { // Update component's local visibility state if(!visibilityPropagation) { - localVisibility = showing; + localVisibility = component.isVisible(); } visibilityPropagation = false; if(DEBUG) { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816GLCanvasFrameHoppingB849B889AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816GLCanvasFrameHoppingB849B889AWT.java new file mode 100644 index 000000000..51d00a5a1 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816GLCanvasFrameHoppingB849B889AWT.java @@ -0,0 +1,262 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.test.junit.jogl.awt; + +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.lang.reflect.InvocationTargetException; + +import javax.media.opengl.GLCapabilities; +import javax.media.opengl.GLProfile; +import javax.media.opengl.awt.GLCanvas; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; +import com.jogamp.opengl.test.junit.util.AWTRobotUtil; +import com.jogamp.opengl.test.junit.util.MiscUtils; +import com.jogamp.opengl.test.junit.util.UITestCase; + +/** + * Moving GLCanvas between 2 AWT JFrame + *

                            + * Validates bugs: + *

                              + *
                            • Bug 816: OSX CALayer Positioning Bug
                            • + *
                            • Bug 729: OSX CALayer shall honor the Component's visibility state
                            • + *
                            • Bug 849: AWT GLAutoDrawables (JAWTWindow) shall honor it's parent visibility state
                            • + *
                            • Bug 878: JAWTWindow's HierarchyListener doesn't set component visible (again) on 'addNotify(..)' - GLCanvas in JtabbedPane disappear
                            • + *
                            • Bug 889: GLCanvas disappear when moves between two JFrame
                            • + *
                            + *

                            + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestBug816GLCanvasFrameHoppingB849B889AWT extends UITestCase { + static long durationPerTest = 500*4; // ms + static boolean manual = false; + + @Test + public void test01AllVisible() throws InterruptedException, InvocationTargetException { + test(false); + } + + @Test + public void test02VisibleWithCanvas() throws InterruptedException, InvocationTargetException { + test(true); + } + + private void test(final boolean onlyVisibleWithCanvas) throws InterruptedException, InvocationTargetException { + final JFrame frame1 = new JFrame("Bug889 #1"); + final JPanel panel1 = new javax.swing.JPanel(); + panel1.setLayout(new BorderLayout()); + panel1.setSize(new java.awt.Dimension(640, 480)); + frame1.setContentPane(panel1); + frame1.setSize(640, 480); + frame1.setLocation(64, 64); + + final JFrame frame2 = new JFrame("Bug889 #2"); + final JPanel panel2 = new javax.swing.JPanel(); + panel2.setLayout(new BorderLayout()); + panel2.setSize(new java.awt.Dimension(640, 480)); + frame2.setContentPane(panel2); + frame2.setSize(640, 480); + frame2.setLocation(800, 64); + + GLProfile profile = GLProfile.get(GLProfile.GL2ES2); + GLCapabilities glCapabilities = new GLCapabilities(profile); + final GLCanvas glCanvas = new GLCanvas(glCapabilities); + glCanvas.setSize(new java.awt.Dimension(640, 480)); + glCanvas.addGLEventListener(new GearsES2(1)); + panel1.add(glCanvas, BorderLayout.CENTER); + + JButton bMoveP1toP2 = new JButton("Move to Panel2"); + bMoveP1toP2.addActionListener(new ActionListener() { + @Override + public void actionPerformed(java.awt.event.ActionEvent evt) { + System.err.println("XXXX Move P1 -> P2 - START"); + dumpGLCanvasStats(glCanvas); + panel2.add(glCanvas, BorderLayout.CENTER); + if( onlyVisibleWithCanvas ) { + frame1.setVisible(false); + frame2.setVisible(true); + frame2.toFront(); + } else { + frame1.validate(); + frame2.validate(); + } + dumpGLCanvasStats(glCanvas); + System.err.println("XXXX Move P1 -> P2 - END"); + } + }); + panel1.add(bMoveP1toP2, BorderLayout.NORTH); + + JButton bMoveP2toP1 = new JButton("Move to Panel1"); + bMoveP2toP1.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + System.err.println("XXXX Move P2 -> P1 - START"); + dumpGLCanvasStats(glCanvas); + panel1.add(glCanvas, BorderLayout.CENTER); + if( onlyVisibleWithCanvas ) { + frame2.setVisible(false); + frame1.setVisible(true); + frame1.toFront(); + } else { + frame2.validate(); + frame1.validate(); + } + dumpGLCanvasStats(glCanvas); + System.err.println("XXXX Move P2 -> P1 - END"); + } + }); + panel2.add(bMoveP2toP1, BorderLayout.NORTH); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + // frame1.pack(); + System.err.println("XXX SetVisible ON XXX GLCanvas on Panel1("+id(panel1)+")"); + if( onlyVisibleWithCanvas ) { + frame1.setVisible(true); + } else { + frame1.setVisible(true); + frame2.setVisible(true); + } + }}); + Assert.assertEquals(true, AWTRobotUtil.waitForVisible(frame1, true)); + Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glCanvas, true)); + dumpGLCanvasStats(glCanvas); + + if(manual) { + for(long w=durationPerTest; w>0; w-=100) { + Thread.sleep(100); + } + } else { + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + System.err.println("XXXX Add GLCanvas Panel1("+id(panel1)+" -> Panel2("+id(panel2)+") START"); + dumpGLCanvasStats(glCanvas); + panel2.add(glCanvas, BorderLayout.CENTER); + if( onlyVisibleWithCanvas ) { + frame1.setVisible(false); + frame2.setVisible(true); + frame2.toFront(); + } else { + frame1.validate(); + frame2.validate(); + } + dumpGLCanvasStats(glCanvas); + }}); + Thread.sleep(durationPerTest/4); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + System.err.println("XXXX Add GLCanvas Panel2("+id(panel2)+") -> Panel1("+id(panel1)+" START"); + dumpGLCanvasStats(glCanvas); + panel1.add(glCanvas, BorderLayout.CENTER); + if( onlyVisibleWithCanvas ) { + frame2.setVisible(false); + frame1.setVisible(true); + frame1.toFront(); + } else { + frame2.validate(); + frame1.validate(); + } + dumpGLCanvasStats(glCanvas); + }}); + Thread.sleep(durationPerTest/4); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + System.err.println("XXXX Add GLCanvas Panel1("+id(panel1)+" -> Panel2("+id(panel2)+") START"); + dumpGLCanvasStats(glCanvas); + panel2.add(glCanvas, BorderLayout.CENTER); + if( onlyVisibleWithCanvas ) { + frame1.setVisible(false); + frame2.setVisible(true); + frame2.toFront(); + } else { + frame1.validate(); + frame2.validate(); + } + dumpGLCanvasStats(glCanvas); + }}); + Thread.sleep(durationPerTest/4); + + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + System.err.println("XXXX Add GLCanvas Panel2("+id(panel2)+") -> Panel1("+id(panel1)+" START"); + dumpGLCanvasStats(glCanvas); + panel1.add(glCanvas, BorderLayout.CENTER); + if( onlyVisibleWithCanvas ) { + frame2.setVisible(false); + frame1.setVisible(true); + frame1.toFront(); + } else { + frame2.validate(); + frame1.validate(); + } + dumpGLCanvasStats(glCanvas); + }}); + Thread.sleep(durationPerTest/4); + } + + SwingUtilities.invokeLater(new Runnable() { + public void run() { + System.err.println("XXX SetVisible OFF XXX"); + frame1.dispose(); + frame2.dispose(); + } }); + } + + private static String id(Object obj) { return "0x"+Integer.toHexString(obj.hashCode()); } + + static void dumpGLCanvasStats(GLCanvas glCanvas) { + System.err.println("XXXX GLCanvas: comp "+glCanvas+", visible "+glCanvas.isVisible()+", showing "+glCanvas.isShowing()+ + ", displayable "+glCanvas.isDisplayable()+", "+glCanvas.getWidth()+"x"+glCanvas.getHeight()); + } + + public static void main(String args[]) { + for(int i=0; i Date: Sat, 16 Nov 2013 05:00:27 +0100 Subject: Bug 906 - JAWTWindow Component- and HierarchyListener must be detached at JAWTWindow.destroy() - GLCanvas Recreation Case In case a JAWTWindow owner recreates itself, destroying JAWTWindow must detach the Component- and HierarchyListener from the AWT component! Test TestBug816GLCanvasFrameHoppingB849B889AWT shows properly detaching listener at jawtWindow destruction. --- .../classes/javax/media/opengl/awt/GLCanvas.java | 9 ++ .../com/jogamp/nativewindow/awt/JAWTWindow.java | 95 ++++++++++++++-------- 2 files changed, 70 insertions(+), 34 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 01d6a6738..36c0144a9 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -583,6 +583,15 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } } + @Override + public void setVisible(boolean b) { + if(DEBUG) { + System.err.println(getThreadName()+": Info: setVisible("+b+")"); + Thread.dumpStack(); + } + super.setVisible(b); + } + /** Overridden to track when this component is added to a container. Subclasses which override this method must call super.addNotify() in their addNotify() method in order to diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 87966c9c6..9a19a7f7a 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -113,127 +113,153 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, this.component = (Component)comp; this.config = (AWTGraphicsConfiguration) config; this.jawtComponentListener = new JAWTComponentListener(); - this.component.addComponentListener(jawtComponentListener); - this.component.addHierarchyListener(jawtComponentListener); invalidate(); this.isApplet = false; this.offscreenSurfaceLayer = 0; } + private static String id(Object obj) { return "0x" + ( null!=obj ? Integer.toHexString(obj.hashCode()) : "nil" ); } + private String jawtStr() { return "JAWTWindow["+id(JAWTWindow.this)+"]"; } + private class JAWTComponentListener implements ComponentListener, HierarchyListener { private boolean localVisibility = component.isVisible(); private boolean globalVisibility = localVisibility; private boolean visibilityPropagation = false; - private String id(Object obj) { return "0x" + ( null!=obj ? Integer.toHexString(obj.hashCode()) : "nil" ); } private String str(Object obj) { if( null == obj ) { - return "null"; + return "0xnil: null"; } else if( obj instanceof Component ) { final Component c = (Component)obj; - return c.getClass().getSimpleName()+"[visible "+c.isVisible()+", showing "+c.isShowing()+", valid "+c.isValid()+ + return id(obj)+": "+c.getClass().getSimpleName()+"[visible "+c.isVisible()+", showing "+c.isShowing()+", valid "+c.isValid()+ ", displayable "+c.isDisplayable()+", "+c.getX()+"/"+c.getY()+" "+c.getWidth()+"x"+c.getHeight()+"]"; } else { - return obj.getClass().getSimpleName()+"[..]"; + return id(obj)+": "+obj.getClass().getSimpleName()+"[..]"; } } - private String s(ComponentEvent e) { return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"],"+Platform.getNewline()+ - " ** COMP "+id(e.getComponent())+": "+str(e.getComponent())+Platform.getNewline()+ - " ** SOURCE "+id(e.getSource())+": "+str(e.getSource())+Platform.getNewline()+ - " ** THIS "+id(component)+": "+str(component); + " ** COMP "+str(e.getComponent())+Platform.getNewline()+ + " ** SOURCE "+str(e.getSource())+Platform.getNewline()+ + " ** THIS "+str(component)+Platform.getNewline()+ + " ** THREAD "+getThreadName(); } private String s(HierarchyEvent e) { return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"], changeBits 0x"+Long.toHexString(e.getChangeFlags())+Platform.getNewline()+ - " ** COMP "+id(e.getComponent())+": "+str(e.getComponent())+Platform.getNewline()+ - " ** SOURCE "+id(e.getSource())+": "+str(e.getSource())+Platform.getNewline()+ - " ** CHANGED "+id(e.getChanged())+": "+str(e.getChanged())+Platform.getNewline()+ - " ** CHANGEDPARENT "+id(e.getChangedParent())+": "+str(e.getChangedParent())+Platform.getNewline()+ - " ** THIS "+id(component)+": "+str(component); + " ** COMP "+str(e.getComponent())+Platform.getNewline()+ + " ** SOURCE "+str(e.getSource())+Platform.getNewline()+ + " ** CHANGED "+str(e.getChanged())+Platform.getNewline()+ + " ** CHANGEDPARENT "+str(e.getChangedParent())+Platform.getNewline()+ + " ** THIS "+str(component)+Platform.getNewline()+ + " ** THREAD "+getThreadName(); + } + @Override + public final String toString() { + return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"],"+Platform.getNewline()+ + " ** THIS "+str(component)+Platform.getNewline()+ + " ** THREAD "+getThreadName(); + } + + public JAWTComponentListener() { + if(DEBUG) { + System.err.println(jawtStr()+".attach: "+toString()); + } + component.addComponentListener(jawtComponentListener); + component.addHierarchyListener(jawtComponentListener); + } + + public final void detach() { + if(DEBUG) { + System.err.println(jawtStr()+".detach: "+toString()); + } + component.removeComponentListener(jawtComponentListener); + component.removeHierarchyListener(jawtComponentListener); } @Override - public void componentResized(ComponentEvent e) { + public final void componentResized(ComponentEvent e) { if(DEBUG) { - System.err.println("JAWTWindow.componentResized: "+s(e)); + System.err.println(jawtStr()+".componentResized: "+s(e)); } layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); } @Override - public void componentMoved(ComponentEvent e) { + public final void componentMoved(ComponentEvent e) { if(DEBUG) { - System.err.println("JAWTWindow.componentMoved: "+s(e)); + System.err.println(jawtStr()+".componentMoved: "+s(e)); } layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); } @Override - public void componentShown(ComponentEvent e) { + public final void componentShown(ComponentEvent e) { if(DEBUG) { - System.err.println("JAWTWindow.componentShown: "+s(e)); + System.err.println(jawtStr()+".componentShown: "+s(e)); } layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); } @Override - public void componentHidden(ComponentEvent e) { + public final void componentHidden(ComponentEvent e) { if(DEBUG) { - System.err.println("JAWTWindow.componentHidden: "+s(e)); + System.err.println(jawtStr()+".componentHidden: "+s(e)); } layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); } @Override - public void hierarchyChanged(HierarchyEvent e) { + public final void hierarchyChanged(HierarchyEvent e) { final long bits = e.getChangeFlags(); final java.awt.Component changed = e.getChanged(); + final boolean compIsVisible = component.isVisible(); if( 0 != ( java.awt.event.HierarchyEvent.DISPLAYABILITY_CHANGED & bits ) ) { final boolean displayable = changed.isDisplayable(); - final boolean propagateDisplayability = changed == component && ( displayable && localVisibility ) != component.isVisible(); + final boolean propagateDisplayability = changed == component && ( displayable && localVisibility ) != compIsVisible; if( propagateDisplayability ) { // Propagate parent's displayability, i.e. 'removeNotify()' and 'addNotify()' final boolean _visible = displayable && localVisibility; visibilityPropagation = true; globalVisibility = displayable; if(DEBUG) { - System.err.println("JAWTWindow.hierarchyChanged DISPLAYABILITY_CHANGED (1): displayable "+displayable+" -> visible "+_visible+", "+s(e)); + System.err.println(jawtStr()+".hierarchyChanged DISPLAYABILITY_CHANGED (1): displayable "+displayable+" -> visible "+_visible+", "+s(e)); } component.setVisible(_visible); } else if(DEBUG) { - System.err.println("JAWTWindow.hierarchyChanged DISPLAYABILITY_CHANGED (x): displayable "+displayable+", "+s(e)); + System.err.println(jawtStr()+".hierarchyChanged DISPLAYABILITY_CHANGED (x): displayable "+displayable+", "+s(e)); } } else if( 0 != ( java.awt.event.HierarchyEvent.SHOWING_CHANGED & bits ) ) { final boolean showing = changed.isShowing(); - final boolean propagateVisibility = changed != component && ( showing && localVisibility ) != component.isVisible(); + final boolean propagateVisibility = changed != component && ( showing && localVisibility ) != compIsVisible; if( propagateVisibility ) { // Propagate parent's visibility final boolean _visible = showing && localVisibility; visibilityPropagation = true; globalVisibility = showing; if(DEBUG) { - System.err.println("JAWTWindow.hierarchyChanged SHOWING_CHANGED (1): showing "+showing+" -> visible "+_visible+", "+s(e)); + System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (1): showing "+showing+" -> visible "+_visible+", "+s(e)); } component.setVisible(_visible); } else if( changed == component ) { // Update component's local visibility state if(!visibilityPropagation) { - localVisibility = component.isVisible(); + localVisibility = compIsVisible; } visibilityPropagation = false; if(DEBUG) { - System.err.println("JAWTWindow.hierarchyChanged SHOWING_CHANGED (0): showing "+showing+" -> visible "+(showing && localVisibility)+", "+s(e)); + System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (0): showing "+showing+" -> visible "+(showing && localVisibility)+", "+s(e)); } } else if(DEBUG) { - System.err.println("JAWTWindow.hierarchyChanged SHOWING_CHANGED (x): showing "+showing+" -> visible "+(showing && localVisibility)+", "+s(e)); + System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (x): showing "+showing+" -> visible "+(showing && localVisibility)+", "+s(e)); } } } } + private static String getThreadName() { return Thread.currentThread().getName(); } + protected synchronized void invalidate() { if(DEBUG) { - System.err.println("JAWTWindow.invalidate() - "+Thread.currentThread().getName()); + System.err.println(jawtStr()+".invalidate() - "+jawtComponentListener.toString()); if( isSurfaceLayerAttached() ) { System.err.println("OffscreenSurfaceLayer still attached: 0x"+Long.toHexString(offscreenSurfaceLayer)); } @@ -571,6 +597,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, public void destroy() { surfaceLock.lock(); try { + jawtComponentListener.detach(); invalidate(); } finally { surfaceLock.unlock(); @@ -713,7 +740,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("JAWT-Window["); + sb.append(jawtStr()+"["); jawt2String(sb); sb.append( ", shallUseOffscreenLayer "+shallUseOffscreenLayer+", isOffscreenLayerSurface "+isOffscreenLayerSurface+ ", attachedSurfaceLayer "+toHexString(getAttachedSurfaceLayer())+ -- cgit v1.2.3 From c153a453299ef12bdb635dc11574a21bba74f04c Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 17 Nov 2013 05:31:22 +0100 Subject: Fix GLIBC > 2.4 dependency regression of commit 613e33ee8ffc1f2b9c5db1e1b5bb5253a159ed6d Commit 613e33ee8ffc1f2b9c5db1e1b5bb5253a159ed6d introduced 'memcpy' usage in Xmisc.c which could create a GLIBC > 2.4 dependency. Include GlueGen's glibc-compat-symbols.h to remove such dependency. --- src/nativewindow/native/x11/Xmisc.c | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src/nativewindow') diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 442d0ceef..2c0e4e22b 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -35,6 +35,9 @@ #include +/** Remove memcpy GLIBC > 2.4 dependencies */ +#include + // #define VERBOSE_ON 1 #ifdef VERBOSE_ON -- cgit v1.2.3 From 380528f59c4a37429f4fa5f8ac7aa3076d0eaa11 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 17 Nov 2013 17:28:10 +0100 Subject: Nativewindow/NEWT: Fix C Return Statement --- src/nativewindow/native/x11/Xmisc.c | 2 +- src/newt/native/X11RandR11.c | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 2c0e4e22b..7b9dc344b 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -387,7 +387,7 @@ Java_jogamp_nativewindow_x11_X11Lib_GetVisualIDFromWindow(JNIEnv *env, jclass _u if(NULL==dpy) { NativewindowCommon_throwNewRuntimeException(env, "invalid display connection.."); - return; + return 0; } NativewindowCommon_x11ErrorHandlerEnable(env, dpy, 0, 1, errorHandlerQuiet, 1); diff --git a/src/newt/native/X11RandR11.c b/src/newt/native/X11RandR11.c index 53d01a6fe..38d61289b 100644 --- a/src/newt/native/X11RandR11.c +++ b/src/newt/native/X11RandR11.c @@ -335,7 +335,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_RandR11_setCurrentScreenM int rot; do { if ( 0 >= XEventsQueued(dpy, QueuedAfterFlush) ) { - return; + return JNI_FALSE; // not done } XNextEvent(dpy, &evt); @@ -366,5 +366,6 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_RandR11_setCurrentScreenM XSync(dpy, False); + return done ? JNI_TRUE : JNI_FALSE; } -- cgit v1.2.3 From 87fa56ba6f88b3f87199c70324b919dc4ae4e6cf Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 23 Nov 2013 04:03:19 +0100 Subject: AWTWindowClosingProtocol: Hold Window reference impl. is listening to to properly removeClosingListener() (and replace boolean state) --- .../nativewindow/awt/AWTWindowClosingProtocol.java | 31 ++++++++++------------ 1 file changed, 14 insertions(+), 17 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java index 27275c6e0..aadecb455 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java @@ -40,11 +40,11 @@ import jogamp.nativewindow.awt.AWTMisc; public class AWTWindowClosingProtocol implements WindowClosingProtocol { - private Component comp; - private Runnable closingOperationClose; - private Runnable closingOperationNOP; - private boolean closingListenerSet = false; - private Object closingListenerLock = new Object(); + private final Component comp; + private Window listenTo; + private final Runnable closingOperationClose; + private final Runnable closingOperationNOP; + private final Object closingListenerLock = new Object(); private WindowClosingMode defaultCloseOperation = WindowClosingMode.DISPOSE_ON_CLOSE; private boolean defaultCloseOperationSetByUser = false; @@ -55,6 +55,7 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { */ public AWTWindowClosingProtocol(Component comp, Runnable closingOperationClose, Runnable closingOperationNOP) { this.comp = comp; + this.listenTo = null; this.closingOperationClose = closingOperationClose; this.closingOperationNOP = closingOperationNOP; } @@ -86,13 +87,12 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { */ public final boolean addClosingListener() throws IllegalStateException { synchronized(closingListenerLock) { - if(closingListenerSet) { + if(null != listenTo) { throw new IllegalStateException("WindowClosingListener already set"); } - final Window w = AWTMisc.getWindow(comp); - if(null!=w) { - w.addWindowListener(windowClosingAdapter); - closingListenerSet = true; + listenTo = AWTMisc.getWindow(comp); + if(null!=listenTo) { + listenTo.addWindowListener(windowClosingAdapter); return true; } } @@ -101,13 +101,10 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol { public final boolean removeClosingListener() { synchronized(closingListenerLock) { - if(closingListenerSet) { - final Window w = AWTMisc.getWindow(comp); - if(null!=w) { - w.removeWindowListener(windowClosingAdapter); - closingListenerSet = false; - return true; - } + if(null != listenTo) { + listenTo.removeWindowListener(windowClosingAdapter); + listenTo = null; + return true; } } return false; -- cgit v1.2.3 From d5c25aa5584e98416208afef57610c85ac6c254c Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Mon, 25 Nov 2013 04:25:04 +0100 Subject: Bug 672 (NewtCanvasSWT): Reuse SWTAccessor.isOS_TYPE ; Impl NW.getLocationOnScreen(..) for X11 and Windows ; Allow unit test to run on all platforms. - Reuse SWTAccessor.isOS_TYPE (public now) - Impl NW.getLocationOnScreen(..) for X11 and Windows reusing existing native code - Allow unit test to run on all platforms. Note: NewtCanvasSWT unit tests require a 'wait for realized' while SWT dispatching. Otherwise the 'sash unit test' will fail since realiziation happens later, at least on X11. Hence extended AWTRobotUtil.waitForRealized(..) to use a 'waitAction' which is used here w/ special SWT dispatch Runnable. AWTRobotUtil.waitForRealized(..) operates on time-delta instead of iteration-counter, allowing above 'waitAction' Runnable. AWTRobotUtil.waitForRealized(..) removed 2nd 'glad.isRealized()' loop .. --- make/scripts/tests-win.bat | 4 +- make/scripts/tests.sh | 8 +- .../com/jogamp/nativewindow/swt/SWTAccessor.java | 8 +- .../classes/com/jogamp/newt/swt/NewtCanvasSWT.java | 42 ++-- .../jogl/swt/TestBug672NewtCanvasSWTSashForm.java | 210 +++++++------------- .../TestBug672NewtCanvasSWTSashFormComposite.java | 219 ++++++++------------- .../TestNewtCanvasSWTBug628ResizeDeadlockAWT.java | 20 +- .../test/junit/jogl/swt/TestNewtCanvasSWTGLn.java | 74 ++++--- .../opengl/test/junit/util/AWTRobotUtil.java | 82 ++++++-- 9 files changed, 320 insertions(+), 347 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests-win.bat b/make/scripts/tests-win.bat index d0bae1b4b..a8ef44cce 100755 --- a/make/scripts/tests-win.bat +++ b/make/scripts/tests-win.bat @@ -13,7 +13,7 @@ REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGea REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelAWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelsAWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.awt.DemoGLJPanelPerf02AWT %* -scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT %* +REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NewtCanvasAWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl3.newt.TestGeomShader01TextureGL3NEWT %* @@ -146,6 +146,8 @@ REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWT REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTBug628ResizeDeadlock %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTBug643AsyncExec %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT %* +scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.swt.TestBug672NewtCanvasSWTSashForm %* +REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.swt.TestBug672NewtCanvasSWTSashFormComposite %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.TestWindows01NEWT REM scripts\java-win.bat com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 809aceb0c..a27def007 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -204,7 +204,7 @@ function jrun() { #D_ARGS="-Dnativewindow.debug=all" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Java2D -Djogl.debug.GLJPanel" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Java2D -Djogl.debug.GLJPanel -Djogl.gljpanel.noglsl" - D_ARGS="-Djogl.debug.GLJPanel -Djogl.debug.DebugGL" + #D_ARGS="-Djogl.debug.GLJPanel -Djogl.debug.DebugGL" #D_ARGS="-Djogl.gljpanel.noverticalflip" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Animator" #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.X11Util.XSync" @@ -529,7 +529,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAWTActionDeadlock01AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLCanvasAWTActionDeadlock02AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLJPanelTextureStateAWT $* -testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLJPanelResize01AWT $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLJPanelResize01AWT $* #testawt com.jogamp.opengl.test.bugs.Bug735Inv0AppletAWT $* #testawt com.jogamp.opengl.test.bugs.Bug735Inv1AppletAWT $* @@ -542,7 +542,9 @@ testawt com.jogamp.opengl.test.junit.jogl.awt.TestGLJPanelResize01AWT $* # #testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTEclipseGLCanvas01GLn $* #testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLn $* -#testswt com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTGLn $* +testswt com.jogamp.opengl.test.junit.jogl.swt.TestNewtCanvasSWTGLn $* +#testswt com.jogamp.opengl.test.junit.jogl.swt.TestBug672NewtCanvasSWTSashForm $* +#testswt com.jogamp.opengl.test.junit.jogl.swt.TestBug672NewtCanvasSWTSashFormComposite $* # # awtswt (testawtswt) diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java index 361d61c65..36bf646d5 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java @@ -63,10 +63,10 @@ public class SWTAccessor { private static Field swt_osx_view_id = null; private static final String nwt; - private static final boolean isOSX; - private static final boolean isWindows; - private static final boolean isX11; - private static final boolean isX11GTK; + public static final boolean isOSX; + public static final boolean isWindows; + public static final boolean isX11; + public static final boolean isX11GTK; // X11/GTK, Windows/GDI, .. private static final String str_handle = "handle"; diff --git a/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java index 029cee3da..5ed8d9e63 100644 --- a/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java +++ b/src/newt/classes/com/jogamp/newt/swt/NewtCanvasSWT.java @@ -46,6 +46,8 @@ import javax.media.nativewindow.util.Point; import javax.media.opengl.GLCapabilities; import jogamp.nativewindow.macosx.OSXUtil; +import jogamp.nativewindow.windows.GDIUtil; +import jogamp.nativewindow.x11.X11Lib; import jogamp.newt.Debug; import jogamp.newt.swt.SWTEDTUtil; @@ -70,7 +72,6 @@ import com.jogamp.newt.util.EDTUtil; */ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { private static final boolean DEBUG = Debug.debug("Window"); - private static final boolean isOSX = NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false); private final AbstractGraphicsScreen screen; @@ -145,7 +146,9 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { newtChild.setSize(clientArea.width, clientArea.height); postSetSize = false; } - if( isOSX ) newtChild.setPosition(parent.getLocation().x,parent.getLocation().y); + if( SWTAccessor.isOSX ) { + newtChild.setPosition(parent.getLocation().x,parent.getLocation().y); + } newtChild.windowRepaint(0, 0, clientArea.width, clientArea.height); } } @@ -398,7 +401,7 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { public SWTNativeWindow(AbstractGraphicsConfiguration config, long nativeWindowHandle) { this.config = config; this.nativeWindowHandle = nativeWindowHandle; - if(isOSX) { + if( SWTAccessor.isOSX ) { this.insets = OSXUtil.GetInsets(nativeWindowHandle); } else { this.insets = new Insets(0, 0, 0, 0); @@ -501,22 +504,25 @@ public class NewtCanvasSWT extends Canvas implements WindowClosingProtocol { @Override public Point getLocationOnScreen(Point point) { - if( isOSX ) { - final Point los = OSXUtil.GetLocationOnScreen(nativeWindowHandle, false, 0, 0); - // top-level position -> client window position - final Rectangle swtCanvasPosition = getSWTCanvasPosition(); - los.set(swtCanvasPosition.x + los.getX() + insets.getLeftWidth(), swtCanvasPosition.y + los.getY() + insets.getTopHeight()); - if(null!=point) { - return point.translate(los); - } else { - return los; - } + final Point los; // client window location on screen + if( SWTAccessor.isOSX ) { + los = OSXUtil.GetLocationOnScreen(nativeWindowHandle, false, 0, 0); + // top-level position -> client window position: OSX needs to add SWT parent position incl. insets + final Rectangle swtCanvasPosition = getSWTCanvasPosition(); + los.translate(swtCanvasPosition.x + insets.getLeftWidth(), swtCanvasPosition.y + insets.getTopHeight()); + } else if (SWTAccessor.isX11) { + final AbstractGraphicsScreen s = config.getScreen(); + los = X11Lib.GetRelativeLocation(s.getDevice().getHandle(), s.getIndex(), nativeWindowHandle, 0 /*root win*/, 0, 0); + } else if (SWTAccessor.isWindows) { + los = GDIUtil.GetRelativeLocation( nativeWindowHandle, 0 /*root win*/, 0, 0); } else { - // client position on 'normal' windowing systems is 0/0 - if(null == point) { - point = new Point(0, 0); - } - return point; + // fall-back to 0/0 + los = new Point(0, 0); + } + if(null!=point) { + return point.translate(los); + } else { + return los; } } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestBug672NewtCanvasSWTSashForm.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestBug672NewtCanvasSWTSashForm.java index f6f8918a3..4b7537655 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestBug672NewtCanvasSWTSashForm.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestBug672NewtCanvasSWTSashForm.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,12 +20,12 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ - + package com.jogamp.opengl.test.junit.jogl.swt; import java.io.IOException; @@ -43,17 +43,13 @@ import com.jogamp.opengl.test.junit.util.AWTRobotUtil; import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; import com.jogamp.opengl.test.junit.util.QuitAdapter; - import com.jogamp.opengl.util.Animator; - import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; -import javax.media.nativewindow.NativeWindowFactory; import javax.media.nativewindow.util.Dimension; import javax.media.nativewindow.util.Point; import javax.media.nativewindow.util.PointImmutable; import javax.media.nativewindow.util.DimensionImmutable; - import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLProfile; @@ -75,28 +71,15 @@ import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class TestBug672NewtCanvasSWTSashForm extends UITestCase { +public class TestBug672NewtCanvasSWTSashForm extends UITestCase { static int screenIdx = 0; static PointImmutable wpos; static DimensionImmutable wsize, rwsize = null; static long duration = 500; // ms - static boolean opaque = true; - static int forceAlpha = -1; - static boolean fullscreen = false; - static boolean pmvUseBackingArray = true; - static int swapInterval = 1; - static boolean showFPS = false; - static int loops = 1; - static boolean loop_shutdown = false; - static boolean forceES2 = false; - static boolean forceGL3 = false; - static boolean mainRun = false; - static boolean exclusiveContext = false; - + @BeforeClass public static void initClass() { - setTestSupported(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false)); if(null == wsize) { wsize = new Dimension(640, 480); } @@ -109,23 +92,28 @@ public class TestBug672NewtCanvasSWTSashForm extends UITestCase { Display display = null; Shell shell = null; Composite composite = null; + SashForm sash = null; com.jogamp.newt.Display swtNewtDisplay = null; - + @Before public void init() { SWTAccessor.invoke(true, new Runnable() { - public void run() { + public void run() { display = new Display(); Assert.assertNotNull( display ); }}); display.syncExec(new Runnable() { - public void run() { + public void run() { shell = new Shell( display ); Assert.assertNotNull( shell ); shell.setLayout( new FillLayout() ); composite = new Composite( shell, SWT.NONE ); composite.setLayout( new FillLayout() ); Assert.assertNotNull( composite ); + sash = new SashForm(composite, SWT.NONE); + Assert.assertNotNull( sash ); + final org.eclipse.swt.widgets.Label c = new org.eclipse.swt.widgets.Label(sash, SWT.NONE); + c.setText("Left cell"); }}); swtNewtDisplay = NewtFactory.createDisplay(null, false); // no-reuse } @@ -135,9 +123,11 @@ public class TestBug672NewtCanvasSWTSashForm extends UITestCase { Assert.assertNotNull( display ); Assert.assertNotNull( shell ); Assert.assertNotNull( composite ); + Assert.assertNotNull( sash ); try { display.syncExec(new Runnable() { public void run() { + sash.dispose(); composite.dispose(); shell.dispose(); }}); @@ -154,22 +144,38 @@ public class TestBug672NewtCanvasSWTSashForm extends UITestCase { display = null; shell = null; composite = null; + sash = null; + } + + class WaitAction implements Runnable { + private final long sleepMS; + + WaitAction(long sleepMS) { + this.sleepMS = sleepMS; + } + public void run() { + if( !display.readAndDispatch() ) { + // blocks on linux .. display.sleep(); + try { + Thread.sleep(sleepMS); + } catch (InterruptedException e) { } + } + } } - + final WaitAction awtRobotWaitAction = new WaitAction(AWTRobotUtil.TIME_SLICE); + final WaitAction generalWaitAction = new WaitAction(10); + protected void runTestGL(GLCapabilitiesImmutable caps) throws InterruptedException, InvocationTargetException { - System.err.println("requested: vsync "+swapInterval+", "+caps); com.jogamp.newt.Screen screen = NewtFactory.createScreen(swtNewtDisplay, screenIdx); final GLWindow glWindow = GLWindow.create(screen, caps); Assert.assertNotNull(glWindow); - - final GearsES2 demo = new GearsES2(swapInterval); - demo.setPMVUseBackingArray(pmvUseBackingArray); + + final GearsES2 demo = new GearsES2(1); glWindow.addGLEventListener(demo); - + Animator animator = new Animator(); animator.setModeBits(false, Animator.MODE_EXPECT_AWT_RENDERING_THREAD); - animator.setExclusiveContext(exclusiveContext); - + QuitAdapter quitAdapter = new QuitAdapter(); //glWindow.addKeyListener(new TraceKeyAdapter(quitAdapter)); //glWindow.addWindowListener(new TraceWindowAdapter(quitAdapter)); @@ -182,14 +188,14 @@ public class TestBug672NewtCanvasSWTSashForm extends UITestCase { } public void windowMoved(WindowEvent e) { System.err.println("window moved: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()); - } + } }); - + glWindow.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { if( !e.isPrintableKey() || e.isAutoRepeat() ) { return; - } + } if(e.getKeyChar()=='f') { new Thread() { public void run() { @@ -207,10 +213,7 @@ public class TestBug672NewtCanvasSWTSashForm extends UITestCase { animator.start(); Assert.assertTrue(animator.isStarted()); Assert.assertTrue(animator.isAnimating()); - Assert.assertEquals(exclusiveContext ? animator.getThread() : null, glWindow.getExclusiveContextThread()); - final SashForm sash = new SashForm(composite, SWT.NONE); - org.eclipse.swt.widgets.Label c = new org.eclipse.swt.widgets.Label(sash, SWT.NONE); - c.setText("Left cell"); + animator.setUpdateFPSFrames(60, null); final NewtCanvasSWT canvas1 = NewtCanvasSWT.create( sash, 0, glWindow ); Assert.assertNotNull( canvas1 ); @@ -224,116 +227,68 @@ public class TestBug672NewtCanvasSWTSashForm extends UITestCase { shell.open(); } }); - - animator.setUpdateFPSFrames(60, showFPS ? System.err : null); - + Assert.assertTrue("GLWindow didn't become visible natively!", AWTRobotUtil.waitForRealized(glWindow, awtRobotWaitAction, true)); + Assert.assertNotNull( canvas1.getNativeWindow() ); + System.err.println("NW chosen: "+glWindow.getDelegatedWindow().getChosenCapabilities()); System.err.println("GL chosen: "+glWindow.getChosenCapabilities()); - System.err.println("window pos/siz: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", "+glWindow.getInsets()); - + System.err.println("window pos/siz.0: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", "+glWindow.getInsets()); + System.err.println("GLWindow LOS.0: "+glWindow.getLocationOnScreen(null)); + System.err.println("NewtCanvasSWT LOS.0: "+canvas1.getNativeWindow().getLocationOnScreen(null)); + if( null != rwsize ) { for(int i=0; i<50; i++) { // 500 ms dispatched delay - if( !display.readAndDispatch() ) { - // blocks on linux .. display.sleep(); - Thread.sleep(10); - } + generalWaitAction.run(); } display.syncExec( new Runnable() { public void run() { shell.setSize( rwsize.getWidth(), rwsize.getHeight() ); } }); - System.err.println("window resize pos/siz: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", "+glWindow.getInsets()); + System.err.println("window resize pos/siz.1: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", "+glWindow.getInsets()); + System.err.println("GLWindow LOS.1: "+glWindow.getLocationOnScreen(null)); + System.err.println("NewtCanvasSWT LOS.1: "+canvas1.getNativeWindow().getLocationOnScreen(null)); } - - Assert.assertNotNull( canvas1.getNativeWindow() ); - Assert.assertNotEquals( canvas1.getNativeWindow().getLocationOnScreen(null), 0 ); - while(!quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration()= sash-right "+pSashRightClient, pNatWinLOS.compareTo(pSashRightClient) >= 0 ); + Assert.assertTrue( "GLWindow LOS "+pGLWinLOS+" not >= sash-right "+pSashRightClient, pGLWinLOS.compareTo(pSashRightClient) >= 0 ); + + while( !quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration() 0 ); - while(!quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration()= sash-right "+pSashRightClient, pNatWinLOS.compareTo(pSashRightClient) >= 0 ); + Assert.assertTrue( "GLWindow LOS "+pGLWinLOS+" not >= sash-right "+pSashRightClient, pGLWinLOS.compareTo(pSashRightClient) >= 0 ); + + while( !quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration() + * _and_ custom GLCapabilities. + *

                            * Uses JOGL's NewtCanvasSWT, which allows to be a native container of a NEWT Window.
                            * This method allows utilizing custom GLCapability settings, * independent from the already instantiated SWT visual. *

                            *

                            - * Note that {@link SWTAccessor#invoke(boolean, Runnable)} is still used to comply w/ + * Note that {@link SWTAccessor#invoke(boolean, Runnable)} is still used to comply w/ * SWT running on Mac OSX, i.e. to enforce UI action on the main thread. *

                            */ @@ -87,7 +87,7 @@ public class TestNewtCanvasSWTGLn extends UITestCase { Shell shell = null; Composite composite = null; com.jogamp.newt.Display swtNewtDisplay = null; - + @BeforeClass public static void startup() { System.out.println( "GLProfile " + GLProfile.glAvailabilityToString() ); @@ -96,12 +96,12 @@ public class TestNewtCanvasSWTGLn extends UITestCase { @Before public void init() { SWTAccessor.invoke(true, new Runnable() { - public void run() { + public void run() { display = new Display(); Assert.assertNotNull( display ); }}); display.syncExec(new Runnable() { - public void run() { + public void run() { shell = new Shell( display ); Assert.assertNotNull( shell ); shell.setLayout( new FillLayout() ); @@ -138,10 +138,28 @@ public class TestNewtCanvasSWTGLn extends UITestCase { composite = null; } - protected void runTestAGL( GLCapabilitiesImmutable caps, GLEventListener demo, + class WaitAction implements Runnable { + private final long sleepMS; + + WaitAction(long sleepMS) { + this.sleepMS = sleepMS; + } + public void run() { + if( !display.readAndDispatch() ) { + // blocks on linux .. display.sleep(); + try { + Thread.sleep(sleepMS); + } catch (InterruptedException e) { } + } + } + } + final WaitAction awtRobotWaitAction = new WaitAction(AWTRobotUtil.TIME_SLICE); + final WaitAction generalWaitAction = new WaitAction(10); + + protected void runTestAGL( GLCapabilitiesImmutable caps, GLEventListener demo, boolean postAttach, boolean useAnimator ) throws InterruptedException { final GLReadBufferUtil screenshot = new GLReadBufferUtil(false, false); - + final Screen screen = NewtFactory.createScreen(swtNewtDisplay, 0); final GLWindow glWindow1 = GLWindow.create(screen, caps); Assert.assertNotNull(glWindow1); @@ -151,7 +169,7 @@ public class TestNewtCanvasSWTGLn extends UITestCase { glWindow1.addGLEventListener(demo); glWindow1.addGLEventListener(new GLEventListener() { int displayCount = 0; - public void init(final GLAutoDrawable drawable) { } + public void init(final GLAutoDrawable drawable) { } public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) { } public void display(final GLAutoDrawable drawable) { if(displayCount < 3) { @@ -159,8 +177,8 @@ public class TestNewtCanvasSWTGLn extends UITestCase { } } public void dispose(final GLAutoDrawable drawable) { } - }); - + }); + final NewtCanvasSWT canvas1 = NewtCanvasSWT.create( composite, 0, postAttach ? null : glWindow1 ); Assert.assertNotNull( canvas1 ); @@ -171,13 +189,18 @@ public class TestNewtCanvasSWTGLn extends UITestCase { shell.open(); } }); - + if(postAttach) { canvas1.setNEWTChild(glWindow1); } - + + Assert.assertTrue("GLWindow didn't become visible natively!", AWTRobotUtil.waitForRealized(glWindow1, awtRobotWaitAction, true)); + + System.err.println("GLWindow LOS.0: "+glWindow1.getLocationOnScreen(null)); + System.err.println("NewtCanvasSWT LOS.0: "+canvas1.getNativeWindow().getLocationOnScreen(null)); + // canvas1.update(); - + Animator anim; if(useAnimator) { anim = new Animator(glWindow1); @@ -185,15 +208,12 @@ public class TestNewtCanvasSWTGLn extends UITestCase { } else { anim = null; } - + long lStartTime = System.currentTimeMillis(); long lEndTime = lStartTime + duration; try { while( (System.currentTimeMillis() < lEndTime) && !canvas1.isDisposed() ) { - if( !display.readAndDispatch() ) { - // blocks on linux .. display.sleep(); - Thread.sleep(10); - } + generalWaitAction.run(); } } catch( Throwable throwable ) { throwable.printStackTrace(); @@ -202,7 +222,7 @@ public class TestNewtCanvasSWTGLn extends UITestCase { if(null != anim) { anim.stop(); } - + canvas1.dispose(); } @@ -220,7 +240,7 @@ public class TestNewtCanvasSWTGLn extends UITestCase { public void postAttach_WithAnimator() throws InterruptedException { runTestAGL( new GLCapabilities(GLProfile.getGL2ES2()), new GearsES2(), true /* postAttach */, true /* animator */); } - + @Test public void test_MultisampleAndAlpha() throws InterruptedException { GLCapabilities caps = new GLCapabilities(GLProfile.getGL2ES2()); diff --git a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java index cd14835bb..657936adc 100644 --- a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java +++ b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java @@ -682,53 +682,97 @@ public class AWTRobotUtil { } /** + * @param obj the component to wait for + * @param realized true if waiting for component to become realized, otherwise false * @return True if the Component becomes realized (not displayable, native invalid) within TIME_OUT + * @throws InterruptedException */ public static boolean waitForRealized(Object obj, boolean realized) throws InterruptedException { - int wait; + return waitForRealized(obj, null, realized); + } + + /** + * @param obj the component to wait for + * @param waitAction if not null, Runnable shall wait {@link #TIME_SLICE} ms, if appropriate + * @param realized true if waiting for component to become realized, otherwise false + * @return True if the Component becomes realized (not displayable, native invalid) within TIME_OUT + * @throws InterruptedException + */ + public static boolean waitForRealized(Object obj, Runnable waitAction, boolean realized) throws InterruptedException { + long t0 = System.currentTimeMillis(); + long t1 = t0; if(obj instanceof com.jogamp.newt.Screen) { com.jogamp.newt.Screen screen = (com.jogamp.newt.Screen) obj; - for (wait=0; wait drawable.setRealized(true); - if(wait=POLL_DIVIDER) { + if( (t1-t0) >= TIME_OUT ) { // for some reason GLCanvas hasn't been painted yet, force it! System.err.println("XXX: FORCE REPAINT PRE - glad: "+glad); comp.repaint(); - for (wait=0; wait Date: Thu, 28 Nov 2013 14:55:03 +0100 Subject: Bug 907 - Initial patch allowing Jogl to respond to other applications that try to retrieve window names --- .../jogamp/nativewindow/windows/GDIUtil.java | 19 +-- src/nativewindow/native/win32/GDImisc.c | 189 ++++++++++++++++++++- 2 files changed, 194 insertions(+), 14 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index 38a5b5bc6..0cf813ad5 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -59,10 +59,8 @@ public class GDIUtil implements ToolkitProperties { if( !initIDs0() ) { throw new NativeWindowException("GDI: Could not initialized native stub"); } - dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0()); - if(DEBUG) { - System.out.println("GDI.initSingleton() dummyWindowClassFactory "+dummyWindowClassFactory); - } + long a = getDummyWndProc0(); + dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, a); isInit = true; } } @@ -94,11 +92,7 @@ public class GDIUtil implements ToolkitProperties { public static long CreateDummyWindow(int x, int y, int width, int height) { synchronized(dummyWindowSync) { dummyWindowClass = dummyWindowClassFactory.getSharedClass(); - if(DEBUG) { - System.out.println("GDI.CreateDummyWindow() dummyWindowClassFactory "+dummyWindowClassFactory); - System.out.println("GDI.CreateDummyWindow() dummyWindowClass "+dummyWindowClass); - } - return CreateDummyWindow0(dummyWindowClass.getHInstance(), dummyWindowClass.getName(), dummyWindowClass.getName(), x, y, width, height); + return CreateDummyWindowAndMessageLoop(dummyWindowClass.getHInstance(), dummyWindowClass.getName(), dummyWindowClass.getName(), x, y, width, height); } } @@ -108,7 +102,7 @@ public class GDIUtil implements ToolkitProperties { if( null == dummyWindowClass ) { throw new InternalError("GDI Error ("+dummyWindowClassFactory.getSharedRefCount()+"): SharedClass is null"); } - res = GDI.DestroyWindow(hwnd); + res = SendCloseMessage(hwnd); dummyWindowClassFactory.releaseSharedClass(); } return res; @@ -130,10 +124,13 @@ public class GDIUtil implements ToolkitProperties { public static native boolean DestroyWindowClass(long hInstance, String className); private static native boolean initIDs0(); - private static native long getDummyWndProc0(); + static native long getDummyWndProc0(); private static native Object GetRelativeLocation0(long src_win, long dest_win, int src_x, int src_y); private static native boolean IsChild0(long win); private static native boolean IsUndecorated0(long win); static native long CreateDummyWindow0(long hInstance, String className, String windowName, int x, int y, int width, int height); + + static native long CreateDummyWindowAndMessageLoop(long hInstance, String className, String windowName, int x, int y, int width, int height); + static native boolean SendCloseMessage(long win); } diff --git a/src/nativewindow/native/win32/GDImisc.c b/src/nativewindow/native/win32/GDImisc.c index 23be47380..40f42f285 100644 --- a/src/nativewindow/native/win32/GDImisc.c +++ b/src/nativewindow/native/win32/GDImisc.c @@ -31,6 +31,93 @@ static const char * const ClazzNamePointCstrSignature = "(II)V"; static jclass pointClz = NULL; static jmethodID pointCstr = NULL; +static DWORD threadid = 0; + +typedef struct ThreadParam_s +{ + jlong jHInstance; + const TCHAR* wndClassName; + const TCHAR* wndName; + jint x; + jint y; + jint width; + jint height; + volatile HWND *hWndPtr; + volatile BOOL *threadReady; +} ThreadParam; + +#define TM_OPENWIN WM_APP+1 +#define TM_CLOSEWIN WM_APP+2 +#define TM_STOP WM_APP+3 + +DWORD WINAPI ThreadFunc(LPVOID param) +{ + MSG msg; + BOOL bRet; + ThreadParam *startupThreadParam = (ThreadParam*)param; + + /* there can not be any messages for us now, as the creator waits for + threadReady before continuing, but we must use this PeekMessage() to + create the thread message queue */ + PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE); + + /* now we can safely say: we have a qeue and are ready to receive messages */ + *(startupThreadParam->threadReady) = TRUE; + + while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0) + { + if (bRet == -1) + { + return 0; + } + else + { + switch(msg.message) + { + case TM_OPENWIN: + { + ThreadParam *tParam = (ThreadParam*)msg.wParam; + HINSTANCE hInstance = (HINSTANCE) (intptr_t) tParam->jHInstance; + DWORD dwExStyle; + DWORD dwStyle; + + dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; + dwStyle = WS_OVERLAPPEDWINDOW; + + HWND hwnd = CreateWindowEx( dwExStyle, + tParam->wndClassName, + tParam->wndName, + dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, + tParam->x, tParam->y, tParam->width, tParam->height, + NULL, NULL, hInstance, NULL ); + + *(tParam->hWndPtr) = hwnd; + *(tParam->threadReady) = TRUE; + } + break; + case TM_CLOSEWIN: + { + ThreadParam *tParam = (ThreadParam*)msg.wParam; + HWND hwnd = *(tParam->hWndPtr); + DestroyWindow(hwnd); + *(tParam->threadReady) = TRUE; + } + break; + case TM_STOP: + return 0; + break; + default: + TranslateMessage(&msg); + DispatchMessage(&msg); + break; + } + } + } + + return 0; +} /* ThreadFunc */ + + HINSTANCE GetApplicationHandle() { return GetModuleHandle(NULL); } @@ -59,7 +146,7 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass if( GetClassInfo( hInstance, clazzName, &wc ) ) { // registered already res = JNI_TRUE; - } else { + } else { // register now ZeroMemory( &wc, sizeof( wc ) ); wc.style = CS_HREDRAW | CS_VREDRAW ; @@ -81,6 +168,27 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass (*env)->ReleaseStringUTFChars(env, jClazzName, clazzName); #endif + if(res == JNI_TRUE) + { + volatile BOOL threadReady = FALSE; + ThreadParam tParam = {0}; + tParam.threadReady = &threadReady; + + CreateThread(NULL, 0, ThreadFunc, (LPVOID)&tParam, 0, &(threadid)); + if(threadid) + { + while(1) + { + if(threadReady) + break; + } + } + else + { + res = JNI_FALSE; + } + } + return res; } @@ -111,9 +219,58 @@ Java_jogamp_nativewindow_windows_GDIUtil_DestroyWindowClass (*env)->ReleaseStringUTFChars(env, jClazzName, clazzName); #endif + PostThreadMessage(threadid, TM_STOP, 0, 0); + return res; } +/* Java->C glue code: + * Java package: jogamp.nativewindow.windows.GDIUtil + * Java method: long CreateDummyWindowAndMessageLoop(long hInstance, java.lang.String className, java.lang.String windowName, int x, int y, int width, int height) + * C function: HANDLE CreateDummyWindowAndMessageLoop(HANDLE hInstance, LPCSTR className, LPCSTR windowName, int x, int y, int width, int height); + */ +JNIEXPORT jlong JNICALL +Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyWindowAndMessageLoop + (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jWndClassName, jstring jWndName, jint x, jint y, jint width, jint height) +{ + volatile HWND hWnd = 0; + volatile BOOL threadReady = FALSE; + ThreadParam tParam = {0}; + + tParam.jHInstance = jHInstance; + tParam.x = x; + tParam.y = y; + tParam.width = width; + tParam.height = height; + tParam.hWndPtr = &hWnd; + tParam.threadReady = &threadReady; + +#ifdef UNICODE + tParam.wndClassName = NewtCommon_GetNullTerminatedStringChars(env, jWndClassName); + tParam.wndName = NewtCommon_GetNullTerminatedStringChars(env, jWndName); +#else + tParam.wndClassName = (*env)->GetStringUTFChars(env, jWndClassName, NULL); + tParam.wndName = (*env)->GetStringUTFChars(env, jWndName, NULL); +#endif + + PostThreadMessage(threadid, TM_OPENWIN, (WPARAM)&tParam, 0); + + while(1) + { + if(threadReady) + break; + } + +#ifdef UNICODE + free((void*) tParam.wndClassName); + free((void*) tParam.wndName); +#else + (*env)->ReleaseStringUTFChars(env, jWndClassName, tParam.wndClassName); + (*env)->ReleaseStringUTFChars(env, jWndName, tParam.wndName); +#endif + + return (jlong) (intptr_t) hWnd; +} /* Java->C glue code: * Java package: jogamp.nativewindow.windows.GDIUtil @@ -188,7 +345,8 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_initIDs0 return JNI_TRUE; } -LRESULT CALLBACK DummyWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { +LRESULT CALLBACK DummyWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ return DefWindowProc(hWnd,uMsg,wParam,lParam); } @@ -200,7 +358,7 @@ LRESULT CALLBACK DummyWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM l JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_windows_GDIUtil_getDummyWndProc0 (JNIEnv *env, jclass clazz) { - return (jlong) (intptr_t) DummyWndProc; + return (jlong) (intptr_t) DummyWndProc; } /* @@ -250,3 +408,28 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_IsUndecorate return bIsUndecorated ? JNI_TRUE : JNI_FALSE; } +/* + * Class: jogamp_nativewindow_windows_GDIUtil + * Method: SendCloseMessage + */ +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_SendCloseMessage +(JNIEnv *env, jclass unused, jlong jwin) +{ + ThreadParam tParam = {0}; + volatile HWND hwnd = (HWND) (intptr_t) jwin; + volatile BOOL threadReady = FALSE; + + tParam.hWndPtr = &(hwnd); + tParam.threadReady = &(threadReady); + + PostThreadMessage(threadid, TM_CLOSEWIN, (WPARAM)&tParam, 0); + + while(1) + { + if(threadReady) + break; + } + + return JNI_TRUE; +} + -- cgit v1.2.3 From 52c95c19dbd69a7fc6b307d2b2db357ceb43ddf5 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 28 Nov 2013 16:34:15 +0100 Subject: Bug 907 - Cleanup Commit e9c711a86aa05f4f24c69972532833f5a98911a3 Cleanup Commit e9c711a86aa05f4f24c69972532833f5a98911a3: - Fix while loop in SendCloseMessage (native) - static 'threadid' must be volatile - Whitespace - Redundancy - CreateDummyWindow - Scope (java, move JNI funcs back to private) - Remove [invalid] pointer usage (native) - ThreadParam's threadReady and hWndPtr shall not be pointers - invalid - No need to use a threadReady pointer. - Validate threadid (native) TODO: - Make 'native dispatch thread' optional - Store 'native dispatch thread' in window class --- .../jogamp/nativewindow/windows/GDIUtil.java | 21 +- src/nativewindow/native/win32/GDImisc.c | 232 ++++++++++----------- 2 files changed, 125 insertions(+), 128 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index 0cf813ad5..6c639c754 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -59,8 +59,10 @@ public class GDIUtil implements ToolkitProperties { if( !initIDs0() ) { throw new NativeWindowException("GDI: Could not initialized native stub"); } - long a = getDummyWndProc0(); - dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, a); + dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0()); + if(DEBUG) { + System.out.println("GDI.initSingleton() dummyWindowClassFactory "+dummyWindowClassFactory); + } isInit = true; } } @@ -91,7 +93,11 @@ public class GDIUtil implements ToolkitProperties { public static long CreateDummyWindow(int x, int y, int width, int height) { synchronized(dummyWindowSync) { - dummyWindowClass = dummyWindowClassFactory.getSharedClass(); + if(DEBUG) { + System.out.println("GDI.CreateDummyWindow() dummyWindowClassFactory "+dummyWindowClassFactory); + System.out.println("GDI.CreateDummyWindow() dummyWindowClass "+dummyWindowClass); + } + // FIXME return CreateDummyWindow0(dummyWindowClass.getHInstance(), dummyWindowClass.getName(), dummyWindowClass.getName(), x, y, width, height); return CreateDummyWindowAndMessageLoop(dummyWindowClass.getHInstance(), dummyWindowClass.getName(), dummyWindowClass.getName(), x, y, width, height); } } @@ -102,6 +108,7 @@ public class GDIUtil implements ToolkitProperties { if( null == dummyWindowClass ) { throw new InternalError("GDI Error ("+dummyWindowClassFactory.getSharedRefCount()+"): SharedClass is null"); } + // FIXME res = GDI.DestroyWindow(hwnd); res = SendCloseMessage(hwnd); dummyWindowClassFactory.releaseSharedClass(); } @@ -124,13 +131,13 @@ public class GDIUtil implements ToolkitProperties { public static native boolean DestroyWindowClass(long hInstance, String className); private static native boolean initIDs0(); - static native long getDummyWndProc0(); + private static native long getDummyWndProc0(); private static native Object GetRelativeLocation0(long src_win, long dest_win, int src_x, int src_y); private static native boolean IsChild0(long win); private static native boolean IsUndecorated0(long win); - static native long CreateDummyWindow0(long hInstance, String className, String windowName, int x, int y, int width, int height); + private static native long CreateDummyWindow0(long hInstance, String className, String windowName, int x, int y, int width, int height); - static native long CreateDummyWindowAndMessageLoop(long hInstance, String className, String windowName, int x, int y, int width, int height); - static native boolean SendCloseMessage(long win); + private static native long CreateDummyWindowAndMessageLoop(long hInstance, String className, String windowName, int x, int y, int width, int height); + private static native boolean SendCloseMessage(long win); } diff --git a/src/nativewindow/native/win32/GDImisc.c b/src/nativewindow/native/win32/GDImisc.c index 40f42f285..d3ac3873c 100644 --- a/src/nativewindow/native/win32/GDImisc.c +++ b/src/nativewindow/native/win32/GDImisc.c @@ -31,7 +31,7 @@ static const char * const ClazzNamePointCstrSignature = "(II)V"; static jclass pointClz = NULL; static jmethodID pointCstr = NULL; -static DWORD threadid = 0; +static volatile DWORD threadid = 0; typedef struct ThreadParam_s { @@ -42,8 +42,8 @@ typedef struct ThreadParam_s jint y; jint width; jint height; - volatile HWND *hWndPtr; - volatile BOOL *threadReady; + volatile HWND hWnd; + volatile BOOL threadReady; } ThreadParam; #define TM_OPENWIN WM_APP+1 @@ -52,69 +52,60 @@ typedef struct ThreadParam_s DWORD WINAPI ThreadFunc(LPVOID param) { - MSG msg; - BOOL bRet; - ThreadParam *startupThreadParam = (ThreadParam*)param; - - /* there can not be any messages for us now, as the creator waits for - threadReady before continuing, but we must use this PeekMessage() to - create the thread message queue */ - PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE); - - /* now we can safely say: we have a qeue and are ready to receive messages */ - *(startupThreadParam->threadReady) = TRUE; - - while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0) - { - if (bRet == -1) - { - return 0; - } - else - { - switch(msg.message) - { - case TM_OPENWIN: - { - ThreadParam *tParam = (ThreadParam*)msg.wParam; - HINSTANCE hInstance = (HINSTANCE) (intptr_t) tParam->jHInstance; - DWORD dwExStyle; - DWORD dwStyle; - - dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; - dwStyle = WS_OVERLAPPEDWINDOW; - - HWND hwnd = CreateWindowEx( dwExStyle, - tParam->wndClassName, - tParam->wndName, - dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, - tParam->x, tParam->y, tParam->width, tParam->height, - NULL, NULL, hInstance, NULL ); - - *(tParam->hWndPtr) = hwnd; - *(tParam->threadReady) = TRUE; - } - break; - case TM_CLOSEWIN: - { - ThreadParam *tParam = (ThreadParam*)msg.wParam; - HWND hwnd = *(tParam->hWndPtr); - DestroyWindow(hwnd); - *(tParam->threadReady) = TRUE; - } - break; - case TM_STOP: - return 0; - break; - default: - TranslateMessage(&msg); - DispatchMessage(&msg); - break; - } - } + MSG msg; + BOOL bRet; + ThreadParam *startupThreadParam = (ThreadParam*)param; + + /* there can not be any messages for us now, as the creator waits for + threadReady before continuing, but we must use this PeekMessage() to + create the thread message queue */ + PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE); + + /* now we can safely say: we have a qeue and are ready to receive messages */ + startupThreadParam->threadReady = TRUE; + + while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0) { + if (bRet == -1) { + return 0; + } else { + switch(msg.message) { + case TM_OPENWIN: { + ThreadParam *tParam = (ThreadParam*)msg.wParam; + HINSTANCE hInstance = (HINSTANCE) (intptr_t) tParam->jHInstance; + DWORD dwExStyle; + DWORD dwStyle; + + dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; + dwStyle = WS_OVERLAPPEDWINDOW; + + HWND hwnd = CreateWindowEx( dwExStyle, + tParam->wndClassName, + tParam->wndName, + dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, + tParam->x, tParam->y, tParam->width, tParam->height, + NULL, NULL, hInstance, NULL ); + + tParam->hWnd = hwnd; + tParam->threadReady = TRUE; + } + break; + case TM_CLOSEWIN: { + ThreadParam *tParam = (ThreadParam*)msg.wParam; + HWND hwnd = tParam->hWnd; + DestroyWindow(hwnd); + tParam->threadReady = TRUE; + } + break; + case TM_STOP: + return 0; + default: + TranslateMessage(&msg); + DispatchMessage(&msg); + break; + } + } } - - return 0; + return 0; } /* ThreadFunc */ @@ -129,13 +120,18 @@ HINSTANCE GetApplicationHandle() { */ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass - (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jClazzName, jlong wndProc) + (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jClazzName, jlong wndProc) { HINSTANCE hInstance = (HINSTANCE) (intptr_t) jHInstance; const TCHAR* clazzName = NULL; WNDCLASS wc; jboolean res; + if( 0 != threadid ) { + NativewindowCommon_throwNewRuntimeException(env, "Native threadid already created 0x%X", (int)threadid); + return JNI_FALSE; + } + #ifdef UNICODE clazzName = NewtCommon_GetNullTerminatedStringChars(env, jClazzName); #else @@ -146,7 +142,7 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass if( GetClassInfo( hInstance, clazzName, &wc ) ) { // registered already res = JNI_TRUE; - } else { + } else { // register now ZeroMemory( &wc, sizeof( wc ) ); wc.style = CS_HREDRAW | CS_VREDRAW ; @@ -168,26 +164,16 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass (*env)->ReleaseStringUTFChars(env, jClazzName, clazzName); #endif - if(res == JNI_TRUE) - { - volatile BOOL threadReady = FALSE; - ThreadParam tParam = {0}; - tParam.threadReady = &threadReady; - - CreateThread(NULL, 0, ThreadFunc, (LPVOID)&tParam, 0, &(threadid)); - if(threadid) - { - while(1) - { - if(threadReady) - break; - } - } - else - { - res = JNI_FALSE; - } - } + if( JNI_TRUE == res ) { + ThreadParam tParam = {0}; + + CreateThread(NULL, 0, ThreadFunc, (LPVOID)&tParam, 0, (DWORD *)&threadid); + if(threadid) { + while(!tParam.threadReady) { /* nop */ } + } else { + res = JNI_FALSE; + } + } return res; } @@ -219,6 +205,11 @@ Java_jogamp_nativewindow_windows_GDIUtil_DestroyWindowClass (*env)->ReleaseStringUTFChars(env, jClazzName, clazzName); #endif + if( 0 == threadid ) { + NativewindowCommon_throwNewRuntimeException(env, "Native threadid zero 0x%X", (int)threadid); + return JNI_FALSE; + } + PostThreadMessage(threadid, TM_STOP, 0, 0); return res; @@ -233,17 +224,21 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyWindowAndMessageLoop (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jWndClassName, jstring jWndName, jint x, jint y, jint width, jint height) { - volatile HWND hWnd = 0; - volatile BOOL threadReady = FALSE; - ThreadParam tParam = {0}; - - tParam.jHInstance = jHInstance; - tParam.x = x; - tParam.y = y; - tParam.width = width; - tParam.height = height; - tParam.hWndPtr = &hWnd; - tParam.threadReady = &threadReady; + volatile HWND hWnd = 0; + ThreadParam tParam = {0}; + + if( 0 == threadid ) { + NativewindowCommon_throwNewRuntimeException(env, "Native threadid zero 0x%X", (int)threadid); + return JNI_FALSE; + } + + tParam.jHInstance = jHInstance; + tParam.x = x; + tParam.y = y; + tParam.width = width; + tParam.height = height; + tParam.hWnd = hWnd; + tParam.threadReady = FALSE; #ifdef UNICODE tParam.wndClassName = NewtCommon_GetNullTerminatedStringChars(env, jWndClassName); @@ -253,13 +248,9 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyWindowAndMessageLoop tParam.wndName = (*env)->GetStringUTFChars(env, jWndName, NULL); #endif - PostThreadMessage(threadid, TM_OPENWIN, (WPARAM)&tParam, 0); + PostThreadMessage(threadid, TM_OPENWIN, (WPARAM)&tParam, 0); - while(1) - { - if(threadReady) - break; - } + while(!tParam.threadReady) { /* nop */ } #ifdef UNICODE free((void*) tParam.wndClassName); @@ -269,7 +260,7 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyWindowAndMessageLoop (*env)->ReleaseStringUTFChars(env, jWndName, tParam.wndName); #endif - return (jlong) (intptr_t) hWnd; + return (jlong) (intptr_t) hWnd; } /* Java->C glue code: @@ -345,9 +336,8 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_initIDs0 return JNI_TRUE; } -LRESULT CALLBACK DummyWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - return DefWindowProc(hWnd,uMsg,wParam,lParam); +LRESULT CALLBACK DummyWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { + return DefWindowProc(hWnd,uMsg,wParam,lParam); } /* @@ -358,7 +348,7 @@ LRESULT CALLBACK DummyWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lPara JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_windows_GDIUtil_getDummyWndProc0 (JNIEnv *env, jclass clazz) { - return (jlong) (intptr_t) DummyWndProc; + return (jlong) (intptr_t) DummyWndProc; } /* @@ -415,21 +405,21 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_IsUndecorate JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_SendCloseMessage (JNIEnv *env, jclass unused, jlong jwin) { - ThreadParam tParam = {0}; - volatile HWND hwnd = (HWND) (intptr_t) jwin; - volatile BOOL threadReady = FALSE; + ThreadParam tParam = {0}; + volatile HWND hwnd = (HWND) (intptr_t) jwin; - tParam.hWndPtr = &(hwnd); - tParam.threadReady = &(threadReady); + if( 0 == threadid ) { + NativewindowCommon_throwNewRuntimeException(env, "Native threadid zero 0x%X", (int)threadid); + return JNI_FALSE; + } - PostThreadMessage(threadid, TM_CLOSEWIN, (WPARAM)&tParam, 0); + tParam.hWnd = hwnd; + tParam.threadReady = FALSE; - while(1) - { - if(threadReady) - break; - } + PostThreadMessage(threadid, TM_CLOSEWIN, (WPARAM)&tParam, 0); - return JNI_TRUE; + while(!tParam.threadReady) { /* nop */ } + + return JNI_TRUE; } -- cgit v1.2.3 From f52c89e36cccd5eb141882a4b3378efe54aa9576 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 28 Nov 2013 22:04:46 +0100 Subject: Bug 907 - Fix regression of 'cleanup' Commit 52c95c19dbd69a7fc6b307d2b2db357ceb43ddf5 --- src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java | 1 + 1 file changed, 1 insertion(+) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index 6c639c754..bab4b5c6e 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -93,6 +93,7 @@ public class GDIUtil implements ToolkitProperties { public static long CreateDummyWindow(int x, int y, int width, int height) { synchronized(dummyWindowSync) { + dummyWindowClass = dummyWindowClassFactory.getSharedClass(); if(DEBUG) { System.out.println("GDI.CreateDummyWindow() dummyWindowClassFactory "+dummyWindowClassFactory); System.out.println("GDI.CreateDummyWindow() dummyWindowClass "+dummyWindowClass); -- cgit v1.2.3 From 586446311ea1ba87f98236d5347955bf99b465d6 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 29 Nov 2013 02:24:01 +0100 Subject: Bug 907 - Refine DummyDispatchThread (DDT) Handling: Proper OO integration in RegisteredClass; Safe DDT Post/WaitForReady handling and error cases ; ... Proper OO integration of DDT in RegisteredClass - DDT is optional to RegisteredClass[Factory], i.e. NEWT without DDT and DummyWindow with DDT. - Using native type DummyThreadContext per DDT passed as DDT handle to java referenced in RegisteredClass - Passing DDT handle to related native methods, if not null use DDT - otherwise work on current thread. The latter impacts CreateDummyWindow0 and DestroyWindow0. Safe DDT Post/WaitForReady handling and error cases ; ... - Wait until command it complete using a 3s timeout - Terminate thread if errors occur and throw an exception +++ Discussion: DDT Native Implementation Due to original code, the DDT is implemented in native code. Usually we should favor running the DDT from a java thread. However, since it's main purpose is _not_ to interact w/ java and the native implementation has less footprint (performance and memory) we shall be OK w/ it for now - as long the implementation IS SAFE. --- make/scripts/tests-win.bat | 4 +- make/scripts/tests-x64-dbg.bat | 8 +- make/scripts/tests.sh | 27 +- .../jogamp/nativewindow/windows/GDIUtil.java | 21 +- .../nativewindow/windows/RegisteredClass.java | 17 +- .../windows/RegisteredClassFactory.java | 30 +- src/nativewindow/native/NativewindowCommon.c | 7 + src/nativewindow/native/NativewindowCommon.h | 3 + src/nativewindow/native/win32/GDImisc.c | 446 ++++++++++++++------- .../jogamp/newt/driver/windows/DisplayDriver.java | 2 +- 10 files changed, 373 insertions(+), 192 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests-win.bat b/make/scripts/tests-win.bat index fb224c882..d95b0025f 100755 --- a/make/scripts/tests-win.bat +++ b/make/scripts/tests-win.bat @@ -6,7 +6,7 @@ REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.acore.TestMainVersion REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT -time 30000 REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT %* -REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* +scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 4000 -x 10 -y 10 -width 100 -height 100 -screen 0 REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 40000 -width 100 -height 100 -screen 0 %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT -time 5000 @@ -18,7 +18,7 @@ REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLa REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl3.newt.TestGeomShader01TextureGL3NEWT %* -scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple %* +REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.TexCubeES2 %* diff --git a/make/scripts/tests-x64-dbg.bat b/make/scripts/tests-x64-dbg.bat index 851c1dbec..3e56a31a6 100755 --- a/make/scripts/tests-x64-dbg.bat +++ b/make/scripts/tests-x64-dbg.bat @@ -21,16 +21,18 @@ set CP_ALL=.;%BLD_DIR%\jar\jogl-all.jar;%BLD_DIR%\jar\jogl-test.jar;..\..\joal\% echo CP_ALL %CP_ALL% REM set D_ARGS="-Djogamp.debug=all" +set D_ARGS="-Djogl.debug=all" "-Dnativewindow.debug=all" +REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" +REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug=all" "-Djogl.debug.EGLDrawableFactory.DontQuery" +REM set D_ARGS="-Dnativewindow.debug.GDIUtil" "-Dnativewindow.debug.RegisteredClass" REM set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.FBObject" REM set D_ARGS="-Djogl.debug.GLDrawable" "-Djogl.debug.EGLDrawableFactory.DontQuery" REM set D_ARGS="-Djogl.debug.GLDrawable" "-Djogl.debug.EGLDrawableFactory.QueryNativeTK" -REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" REM set D_ARGS="-Djogl.debug.GLDrawable" "-Djogl.debug.GLContext" "-Djogl.debug.GLCanvas" -REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug=all" "-Djogl.debug.EGLDrawableFactory.DontQuery" REM set D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.CapabilitiesChooser -Djogl.debug.GLProfile" REM set D_ARGS="-Djogamp.debug.IOUtil" REM set D_ARGS="-Djogl.debug.GLSLCode" "-Djogl.debug.GLMediaPlayer" -set D_ARGS="-Djogl.debug.GLMediaPlayer" +REM set D_ARGS="-Djogl.debug.GLMediaPlayer" REM set D_ARGS="-Djogl.debug.GLMediaPlayer" "-Djogl.debug.AudioSink" REM set D_ARGS="-Djogl.debug.GLMediaPlayer" "-Djogl.debug.GLMediaPlayer.Native" REM set D_ARGS="-Djogl.debug.GLMediaPlayer.StreamWorker.delay=25" "-Djogl.debug.GLMediaPlayer" diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index ce8005821..56a07e768 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -84,6 +84,17 @@ function jrun() { #D_ARGS="-Djogl.debug.DebugGL" #D_ARGS="-Djogl.debug.TraceGL" #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.TraceGL" + + #D_ARGS="-Djogamp.debug=all" + #D_ARGS="-Dnativewindow.debug=all" + #D_ARGS="-Djogl.debug=all" + #D_ARGS="-Dnewt.debug=all" + #D_ARGS="-Djogl.debug=all -Dnewt.debug=all" + D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all" + #D_ARGS="-Djogamp.debug=all -Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" + #D_ARGS="-Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" + #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all -Djogamp.debug.Lock" + #D_ARGS="-Dnativewindow.debug.X11Util.ATI_HAS_NO_XCLOSEDISPLAY_BUG" #D_ARGS="-Dnativewindow.debug.X11Util.ATI_HAS_NO_MULTITHREADING_BUG" #D_ARGS="-Djogl.disable.opengles" @@ -93,7 +104,7 @@ function jrun() { #D_ARGS="-Djogl.debug.FBObject" #D_ARGS="-Djogl.debug.GLSLCode" #D_ARGS="-Djogl.debug.GLSLCode -Djogl.debug.DebugGL" - #D_ARGS="-Djogl.debug=all -Dnewt.debug=all" + #D_ARGS="-Dnativewindow.debug.X11Util -Dnativewindow.debug.X11Util.TraceDisplayLifecycle -Djogl.debug.EGLDisplayUtil -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.JAWT -Dnewt.debug.Window" #D_ARGS="-Dnativewindow.debug.JAWT -Djogamp.debug.TaskBase.TraceSource" #D_ARGS="-Djogl.debug.GLContext.TraceSwitch" @@ -110,10 +121,6 @@ function jrun() { #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration" #D_ARGS="-Djogl.debug.GLContext" #D_ARGS="-Djogl.debug.GLContext.NoProfileAliasing" - #D_ARGS="-Djogamp.debug=all" - #D_ARGS="-Djogamp.debug=all -Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" - #D_ARGS="-Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all" - #D_ARGS="-Dnativewindow.debug.X11Util -Dnativewindow.debug.X11Util.TraceDisplayLifecycle -Djogl.debug.EGLDisplayUtil -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLDrawable -Dnativewindow.debug.X11Util -Dnativewindow.debug.NativeWindow -Dnewt.debug.Display -Dnewt.debug.Screen -Dnewt.debug.Window" #D_ARGS="-Djogl.debug.Animator -Djogl.debug.GLDrawable -Dnativewindow.debug.NativeWindow" #D_ARGS="-Djogl.debug=all -Dnewt.debug=all" @@ -122,8 +129,6 @@ function jrun() { #D_ARGS="-Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLEventListenerState" #D_ARGS="-Djogl.fbo.force.none" - #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all -Djogamp.debug.Lock" - #D_ARGS="-Djogl.debug=all" #D_ARGS="-Djogl.debug.EGLDrawableFactory.DontQuery -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.EGLDrawableFactory.QueryNativeTK -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLDebugMessageHandler" @@ -137,7 +142,7 @@ function jrun() { #D_ARGS="-Djogamp.debug.IOUtil -Djogl.debug.GLSLCode -Djogl.debug.GLMediaPlayer" #D_ARGS="-Djogl.debug.GLMediaPlayer -Djogl.debug.AudioSink" #D_ARGS="-Djogl.debug.GLMediaPlayer -Djogl.debug.GLMediaPlayer.Native" - D_ARGS="-Djogl.debug.GLMediaPlayer" + #D_ARGS="-Djogl.debug.GLMediaPlayer" #D_ARGS="-Djogl.debug.GLMediaPlayer.StreamWorker.delay=25 -Djogl.debug.GLMediaPlayer" #D_ARGS="-Djogl.debug.GLMediaPlayer.Native" #D_ARGS="-Djogl.debug.AudioSink" @@ -201,7 +206,6 @@ function jrun() { #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Window.MouseEvent -Dnewt.debug.Window.KeyEvent" #D_ARGS="-Dnewt.debug.Window" #D_ARGS="-Xprof" - #D_ARGS="-Dnativewindow.debug=all" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Java2D -Djogl.debug.GLJPanel" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Java2D -Djogl.debug.GLJPanel -Djogl.gljpanel.noglsl" #D_ARGS="-Djogl.debug.GLJPanel -Djogl.debug.DebugGL" @@ -225,7 +229,6 @@ function jrun() { #D_ARGS="-Dnewt.debug=all -Djogamp.debug.Lock -Djogamp.debug.Lock.TraceLock" #D_ARGS="-Djogl.debug.GLContext -Dnewt.debug=all -Djogamp.debug.Lock -Djogamp.common.utils.locks.Lock.timeout=10000" #D_ARGS="-Djogl.debug.GLContext -Dnewt.debug=all" - #D_ARGS="-Dnewt.debug=all" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.GLJPanel -Djogl.debug.TileRenderer -Djogl.debug.TileRenderer.PNG" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.GLJPanel -Djogl.debug.TileRenderer" #D_ARGS="-Djogl.debug.PNGImage" @@ -322,7 +325,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelsAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NewtCanvasAWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile00NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NEWT $* #testawtswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT $* @@ -345,7 +348,7 @@ function testawtswt() { # #testnoawt jogamp.opengl.openal.av.ALDummyUsage $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube $* -testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple $* # # performance tests diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index bab4b5c6e..a872e63d8 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -59,7 +59,7 @@ public class GDIUtil implements ToolkitProperties { if( !initIDs0() ) { throw new NativeWindowException("GDI: Could not initialized native stub"); } - dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0()); + dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0(), true /* useDummyDispatchThread */); if(DEBUG) { System.out.println("GDI.initSingleton() dummyWindowClassFactory "+dummyWindowClassFactory); } @@ -98,8 +98,7 @@ public class GDIUtil implements ToolkitProperties { System.out.println("GDI.CreateDummyWindow() dummyWindowClassFactory "+dummyWindowClassFactory); System.out.println("GDI.CreateDummyWindow() dummyWindowClass "+dummyWindowClass); } - // FIXME return CreateDummyWindow0(dummyWindowClass.getHInstance(), dummyWindowClass.getName(), dummyWindowClass.getName(), x, y, width, height); - return CreateDummyWindowAndMessageLoop(dummyWindowClass.getHInstance(), dummyWindowClass.getName(), dummyWindowClass.getName(), x, y, width, height); + return CreateDummyWindow0(dummyWindowClass.getHInstance(), dummyWindowClass.getName(), dummyWindowClass.getHDispThreadContext(), dummyWindowClass.getName(), x, y, width, height); } } @@ -109,8 +108,7 @@ public class GDIUtil implements ToolkitProperties { if( null == dummyWindowClass ) { throw new InternalError("GDI Error ("+dummyWindowClassFactory.getSharedRefCount()+"): SharedClass is null"); } - // FIXME res = GDI.DestroyWindow(hwnd); - res = SendCloseMessage(hwnd); + res = DestroyWindow0(dummyWindowClass.getHDispThreadContext(), hwnd); dummyWindowClassFactory.releaseSharedClass(); } return res; @@ -128,8 +126,11 @@ public class GDIUtil implements ToolkitProperties { return IsChild0(win); } - public static native boolean CreateWindowClass(long hInstance, String clazzName, long wndProc); - public static native boolean DestroyWindowClass(long hInstance, String className); + private static final void dumpStack() { Thread.dumpStack(); } // Callback for JNI + + static native boolean CreateWindowClass0(long hInstance, String clazzName, long wndProc); + static native boolean DestroyWindowClass0(long hInstance, String className, long dispThreadCtx); + static native long CreateDummyDispatchThread0(); private static native boolean initIDs0(); private static native long getDummyWndProc0(); @@ -137,8 +138,6 @@ public class GDIUtil implements ToolkitProperties { private static native boolean IsChild0(long win); private static native boolean IsUndecorated0(long win); - private static native long CreateDummyWindow0(long hInstance, String className, String windowName, int x, int y, int width, int height); - - private static native long CreateDummyWindowAndMessageLoop(long hInstance, String className, String windowName, int x, int y, int width, int height); - private static native boolean SendCloseMessage(long win); + private static native long CreateDummyWindow0(long hInstance, String className, long dispThreadCtx, String windowName, int x, int y, int width, int height); + private static native boolean DestroyWindow0(long dispThreadCtx, long win); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java index 976693e3a..1f6cb7c05 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClass.java @@ -29,12 +29,14 @@ package jogamp.nativewindow.windows; public class RegisteredClass { - long hInstance; - String className; + private final long hInstance; + private final String className; + private final long hDDTCtx; - RegisteredClass(long hInst, String name) { - hInstance = hInst; - className = name; + RegisteredClass(long hInst, String name, long hDispatchThreadCtx) { + this.hInstance = hInst; + this.className = name; + this.hDDTCtx = hDispatchThreadCtx; } /** Application handle, same as {@link RegisteredClassFactory#getHInstance()}. */ @@ -43,6 +45,9 @@ public class RegisteredClass { /** Unique Window Class Name */ public final String getName() { return className; } + /** Unique associated dispatch thread context for this Window Class, or 0 for none. */ + public final long getHDispThreadContext() { return hDDTCtx; } + @Override - public final String toString() { return "RegisteredClass[handle 0x"+Long.toHexString(hInstance)+", "+className+"]"; } + public final String toString() { return "RegisteredClass[handle 0x"+Long.toHexString(hInstance)+", "+className+", dtx 0x"+Long.toHexString(hDDTCtx)+"]"; } } diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java index 19a48d3bf..ee41fe192 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java @@ -49,6 +49,7 @@ public class RegisteredClassFactory { private final String classBaseName; private final long wndProc; + private final boolean useDummyDispatchThread; private RegisteredClass sharedClass = null; private int classIter = 0; @@ -59,24 +60,29 @@ public class RegisteredClassFactory { @Override public final String toString() { return "RegisteredClassFactory[moduleHandle "+toHexString(hInstance)+", "+classBaseName+ - ", wndProc "+toHexString(wndProc)+", shared[refCount "+sharedRefCount+", class "+sharedClass+"]]"; } + ", wndProc "+toHexString(wndProc)+", useDDT "+useDummyDispatchThread+", shared[refCount "+sharedRefCount+", class "+sharedClass+"]]"; } /** * Release the {@link RegisteredClass} of all {@link RegisteredClassFactory}. */ public static void shutdownSharedClasses() { synchronized(registeredFactories) { + if( DEBUG ) { + System.err.println("RegisteredClassFactory.shutdownSharedClasses: "+registeredFactories.size()); + } for(int j=0; j +#include static const char * const ClazzNameRuntimeException = "java/lang/RuntimeException"; static jclass runtimeExceptionClz=NULL; @@ -106,3 +107,9 @@ JNIEnv* NativewindowCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int as return curEnv; } +int64_t NativewindowCommon_CurrentTimeMillis() { + struct timeval tv; + gettimeofday(&tv,NULL); + return (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000; +} + diff --git a/src/nativewindow/native/NativewindowCommon.h b/src/nativewindow/native/NativewindowCommon.h index a2975f3fd..a23fad9fd 100644 --- a/src/nativewindow/native/NativewindowCommon.h +++ b/src/nativewindow/native/NativewindowCommon.h @@ -4,6 +4,7 @@ #include #include +#include int NativewindowCommon_init(JNIEnv *env); @@ -15,4 +16,6 @@ void NativewindowCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, . JNIEnv* NativewindowCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int asDaemon, int * shallBeDetached); +int64_t NativewindowCommon_CurrentTimeMillis(); + #endif diff --git a/src/nativewindow/native/win32/GDImisc.c b/src/nativewindow/native/win32/GDImisc.c index d3ac3873c..b55988c11 100644 --- a/src/nativewindow/native/win32/GDImisc.c +++ b/src/nativewindow/native/win32/GDImisc.c @@ -20,8 +20,10 @@ #ifdef VERBOSE_ON #define DBG_PRINT(args...) fprintf(stderr, args); + #define DBG_PRINT_FLUSH(args...) fprintf(stderr, args); fflush(stderr); #else #define DBG_PRINT(args...) + #define DBG_PRINT_FLUSH(args...) #endif static const char * const ClazzNamePoint = "javax/media/nativewindow/util/Point"; @@ -30,12 +32,17 @@ static const char * const ClazzNamePointCstrSignature = "(II)V"; static jclass pointClz = NULL; static jmethodID pointCstr = NULL; +static jmethodID dumpStackID = NULL; -static volatile DWORD threadid = 0; +typedef struct { + HANDLE threadHandle; + DWORD threadId; + volatile BOOL threadReady; + volatile BOOL threadDead; +} DummyThreadContext; -typedef struct ThreadParam_s -{ - jlong jHInstance; +typedef struct { + HINSTANCE hInstance; const TCHAR* wndClassName; const TCHAR* wndName; jint x; @@ -44,17 +51,88 @@ typedef struct ThreadParam_s jint height; volatile HWND hWnd; volatile BOOL threadReady; -} ThreadParam; +} DummyThreadCommand; #define TM_OPENWIN WM_APP+1 #define TM_CLOSEWIN WM_APP+2 #define TM_STOP WM_APP+3 -DWORD WINAPI ThreadFunc(LPVOID param) +static const char * sTM_OPENWIN = "TM_OPENWIN"; +static const char * sTM_CLOSEWIN = "TM_CLOSEWIN"; +static const char * sTM_STOP = "TM_STOP"; + +/** 3s timeout */ +static const int64_t TIME_OUT = 3000000; + +static jboolean DDT_CheckAlive(JNIEnv *env, const char *msg, DummyThreadContext *ctx) { + if( ctx->threadDead ) { + NativewindowCommon_throwNewRuntimeException(env, "DDT is dead at %s", msg); + return JNI_FALSE; + } else { + DBG_PRINT_FLUSH("*** DDT-Check ALIVE @ %s\n", msg); + return JNI_TRUE; + } +} + +static jboolean DDT_WaitUntilCreated(JNIEnv *env, DummyThreadContext *ctx, BOOL created) { + const int64_t t0 = NativewindowCommon_CurrentTimeMillis(); + int64_t t1 = t0; + if( created ) { + while( !ctx->threadReady && t1-t0 < TIME_OUT ) { + t1 = NativewindowCommon_CurrentTimeMillis(); + } + if( !ctx->threadReady ) { + NativewindowCommon_throwNewRuntimeException(env, "TIMEOUT (%d ms) while waiting for DDT CREATED", (int)(t1-t0)); + return JNI_FALSE; + } + DBG_PRINT_FLUSH("*** DDT-Check CREATED\n"); + } else { + while( !ctx->threadDead && t1-t0 < TIME_OUT ) { + t1 = NativewindowCommon_CurrentTimeMillis(); + } + if( !ctx->threadDead ) { + NativewindowCommon_throwNewRuntimeException(env, "TIMEOUT (%d ms) while waiting for DDT DESTROYED", (int)(t1-t0)); + return JNI_FALSE; + } + DBG_PRINT_FLUSH("*** DDT-Check DEAD\n"); + } + return JNI_TRUE; +} + +static jboolean DDT_WaitUntilReady(JNIEnv *env, const char *msg, DummyThreadCommand *cmd) { + const int64_t t0 = NativewindowCommon_CurrentTimeMillis(); + int64_t t1 = t0; + while( !cmd->threadReady && t1-t0 < TIME_OUT ) { + t1 = NativewindowCommon_CurrentTimeMillis(); + } + if( !cmd->threadReady ) { + NativewindowCommon_throwNewRuntimeException(env, "TIMEOUT (%d ms) while waiting for DDT %s", (int)(t1-t0), msg); + return JNI_FALSE; + } + DBG_PRINT_FLUSH("*** DDT-Check READY @ %s\n", msg); + return JNI_TRUE; +} + +static HWND DummyWindowCreate + (HINSTANCE hInstance, const TCHAR* wndClassName, const TCHAR* wndName, jint x, jint y, jint width, jint height) +{ + DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; + DWORD dwStyle = WS_OVERLAPPEDWINDOW; + HWND hWnd = CreateWindowEx( dwExStyle, + wndClassName, + wndName, + dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, + x, y, width, height, + NULL, NULL, hInstance, NULL ); + return hWnd; +} + +static DWORD WINAPI DummyDispatchThreadFunc(LPVOID param) { MSG msg; BOOL bRet; - ThreadParam *startupThreadParam = (ThreadParam*)param; + BOOL bEOL=FALSE; + DummyThreadContext *threadContext = (DummyThreadContext*)param; /* there can not be any messages for us now, as the creator waits for threadReady before continuing, but we must use this PeekMessage() to @@ -62,42 +140,40 @@ DWORD WINAPI ThreadFunc(LPVOID param) PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE); /* now we can safely say: we have a qeue and are ready to receive messages */ - startupThreadParam->threadReady = TRUE; - - while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0) { - if (bRet == -1) { - return 0; + // threadContext->threadId = GetCurrentThreadId(); + threadContext->threadDead = FALSE; + threadContext->threadReady = TRUE; + + while( !bEOL && (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0 ) { + if ( -1 == bRet ) { + fprintf(stderr, "DummyDispatchThread (id %d): GetMessage Error %d, werr %d\n", + (int)threadContext->threadId, (int)bRet, (int)GetLastError()); + fflush(stderr); + bEOL = TRUE; + break; // EOL } else { switch(msg.message) { case TM_OPENWIN: { - ThreadParam *tParam = (ThreadParam*)msg.wParam; - HINSTANCE hInstance = (HINSTANCE) (intptr_t) tParam->jHInstance; - DWORD dwExStyle; - DWORD dwStyle; - - dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; - dwStyle = WS_OVERLAPPEDWINDOW; - - HWND hwnd = CreateWindowEx( dwExStyle, - tParam->wndClassName, - tParam->wndName, - dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, - tParam->x, tParam->y, tParam->width, tParam->height, - NULL, NULL, hInstance, NULL ); - - tParam->hWnd = hwnd; + DummyThreadCommand *tParam = (DummyThreadCommand*)msg.wParam; + DBG_PRINT_FLUSH("*** DDT-Dispatch OPENWIN\n"); + tParam->hWnd = DummyWindowCreate(tParam->hInstance, tParam->wndClassName, tParam->wndName, tParam->x, tParam->y, tParam->width, tParam->height); tParam->threadReady = TRUE; } break; case TM_CLOSEWIN: { - ThreadParam *tParam = (ThreadParam*)msg.wParam; - HWND hwnd = tParam->hWnd; - DestroyWindow(hwnd); + DummyThreadCommand *tParam = (DummyThreadCommand*)msg.wParam; + DBG_PRINT_FLUSH("*** DDT-Dispatch CLOSEWIN\n"); + DestroyWindow(tParam->hWnd); tParam->threadReady = TRUE; } break; - case TM_STOP: - return 0; + case TM_STOP: { + DummyThreadCommand *tParam = (DummyThreadCommand*)msg.wParam; + DBG_PRINT_FLUSH("*** DDT-Dispatch STOP -> DEAD\n"); + tParam->threadReady = TRUE; + bEOL = TRUE; + } + break; // EOL default: TranslateMessage(&msg); DispatchMessage(&msg); @@ -105,8 +181,12 @@ DWORD WINAPI ThreadFunc(LPVOID param) } } } + /* dead */ + DBG_PRINT_FLUSH("*** DDT-Dispatch DEAD\n"); + threadContext->threadDead = TRUE; + ExitThread(0); return 0; -} /* ThreadFunc */ +} HINSTANCE GetApplicationHandle() { @@ -115,11 +195,48 @@ HINSTANCE GetApplicationHandle() { /* Java->C glue code: * Java package: jogamp.nativewindow.windows.GDIUtil - * Java method: boolean CreateWindowClass(long hInstance, java.lang.String clazzName, long wndProc) - * C function: BOOL CreateWindowClass(HANDLE hInstance, LPCSTR clazzName, HANDLE wndProc); + * Java method: long CreateDummyDispatchThread0() + */ +JNIEXPORT jlong JNICALL +Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyDispatchThread0 + (JNIEnv *env, jclass _unused) +{ + DWORD threadId = 0; + DummyThreadContext * dispThreadCtx = calloc(1, sizeof(DummyThreadContext)); + + dispThreadCtx->threadHandle = CreateThread(NULL, 0, DummyDispatchThreadFunc, (LPVOID)dispThreadCtx, 0, &threadId); + if( NULL == dispThreadCtx->threadHandle || 0 == threadId ) { + const HANDLE threadHandle = dispThreadCtx->threadHandle; + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT CREATE failed handle %p, id %d, werr %d", + (void*)threadHandle, (int)threadId, (int)GetLastError()); + return (jlong)0; + } + if( JNI_FALSE == DDT_WaitUntilCreated(env, dispThreadCtx, TRUE) ) { + const HANDLE threadHandle = dispThreadCtx->threadHandle; + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT CREATE (ack) failed handle %p, id %d, werr %d", + (void*)threadHandle, (int)threadId, (int)GetLastError()); + return (jlong)0; + } + DBG_PRINT_FLUSH("*** DDT Created %d\n", (int)threadId); + dispThreadCtx->threadId = threadId; + return (jlong) (intptr_t) dispThreadCtx; +} + +/* Java->C glue code: + * Java package: jogamp.nativewindow.windows.GDIUtil + * Java method: boolean CreateWindowClass0(long hInstance, java.lang.String clazzName, long wndProc) + * C function: BOOL CreateWindowClass0(HANDLE hInstance, LPCSTR clazzName, HANDLE wndProc); */ JNIEXPORT jboolean JNICALL -Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass +Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass0 (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jClazzName, jlong wndProc) { HINSTANCE hInstance = (HINSTANCE) (intptr_t) jHInstance; @@ -127,11 +244,6 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass WNDCLASS wc; jboolean res; - if( 0 != threadid ) { - NativewindowCommon_throwNewRuntimeException(env, "Native threadid already created 0x%X", (int)threadid); - return JNI_FALSE; - } - #ifdef UNICODE clazzName = NewtCommon_GetNullTerminatedStringChars(env, jClazzName); #else @@ -164,31 +276,20 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass (*env)->ReleaseStringUTFChars(env, jClazzName, clazzName); #endif - if( JNI_TRUE == res ) { - ThreadParam tParam = {0}; - - CreateThread(NULL, 0, ThreadFunc, (LPVOID)&tParam, 0, (DWORD *)&threadid); - if(threadid) { - while(!tParam.threadReady) { /* nop */ } - } else { - res = JNI_FALSE; - } - } - return res; } /* Java->C glue code: * Java package: jogamp.nativewindow.windows.GDIUtil - * Java method: boolean DestroyWindowClass(long hInstance, java.lang.String className) - * C function: BOOL DestroyWindowClass(HANDLE hInstance, LPCSTR className); + * Java method: boolean DestroyWindowClass0(long hInstance, java.lang.String className, long dispThreadCtx) */ JNIEXPORT jboolean JNICALL -Java_jogamp_nativewindow_windows_GDIUtil_DestroyWindowClass - (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jClazzName) +Java_jogamp_nativewindow_windows_GDIUtil_DestroyWindowClass0 + (JNIEnv *env, jclass gdiClazz, jlong jHInstance, jstring jClazzName, jlong jDispThreadCtx) { HINSTANCE hInstance = (HINSTANCE) (intptr_t) jHInstance; const TCHAR* clazzName = NULL; + DummyThreadContext * dispThreadCtx = (DummyThreadContext *) (intptr_t) jDispThreadCtx; jboolean res; #ifdef UNICODE @@ -205,39 +306,73 @@ Java_jogamp_nativewindow_windows_GDIUtil_DestroyWindowClass (*env)->ReleaseStringUTFChars(env, jClazzName, clazzName); #endif - if( 0 == threadid ) { - NativewindowCommon_throwNewRuntimeException(env, "Native threadid zero 0x%X", (int)threadid); - return JNI_FALSE; - } + if( NULL != dispThreadCtx) { + const HANDLE threadHandle = dispThreadCtx->threadHandle; + const DWORD threadId = dispThreadCtx->threadId; + DummyThreadCommand tParam = {0}; + tParam.threadReady = FALSE; + DBG_PRINT_FLUSH("*** DDT Destroy %d\n", (int)threadId); +#ifdef VERBOSE_ON + (*env)->CallStaticVoidMethod(env, gdiClazz, dumpStackID); +#endif - PostThreadMessage(threadid, TM_STOP, 0, 0); + if( JNI_FALSE == DDT_CheckAlive(env, sTM_STOP, dispThreadCtx) ) { + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT %s (alive) failed handle %p, id %d, werr %d", + sTM_STOP, (void*)threadHandle, (int)threadId, (int)GetLastError()); + return JNI_FALSE; + } + if ( 0 != PostThreadMessage(dispThreadCtx->threadId, TM_STOP, (WPARAM)&tParam, 0) ) { + if( JNI_FALSE == DDT_WaitUntilReady(env, sTM_STOP, &tParam) ) { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s (ack) failed handle %p, id %d, werr %d", + sTM_STOP, (void*)threadHandle, (int)threadId, (int)GetLastError()); + return JNI_FALSE; + } + if( JNI_FALSE == DDT_WaitUntilCreated(env, dispThreadCtx, FALSE) ) { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT KILL %s (ack) failed handle %p, id %d, werr %d", + sTM_STOP, (void*)threadHandle, (int)threadId, (int)GetLastError()); + return JNI_FALSE; + } + free(dispThreadCtx); // free after proper DDT shutdown! + } else { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s failed handle %p, id %d, werr %d", + sTM_STOP, (void*)threadHandle, (int)threadId, (int)GetLastError()); + return JNI_FALSE; + } + } return res; } /* Java->C glue code: * Java package: jogamp.nativewindow.windows.GDIUtil - * Java method: long CreateDummyWindowAndMessageLoop(long hInstance, java.lang.String className, java.lang.String windowName, int x, int y, int width, int height) - * C function: HANDLE CreateDummyWindowAndMessageLoop(HANDLE hInstance, LPCSTR className, LPCSTR windowName, int x, int y, int width, int height); + * Java method: long CreateDummyWindow0(long hInstance, java.lang.String className, jlong dispThreadCtx, java.lang.String windowName, int x, int y, int width, int height) */ JNIEXPORT jlong JNICALL -Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyWindowAndMessageLoop - (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jWndClassName, jstring jWndName, jint x, jint y, jint width, jint height) +Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyWindow0 + (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jWndClassName, jlong jDispThreadCtx, jstring jWndName, jint x, jint y, jint width, jint height) { - volatile HWND hWnd = 0; - ThreadParam tParam = {0}; - - if( 0 == threadid ) { - NativewindowCommon_throwNewRuntimeException(env, "Native threadid zero 0x%X", (int)threadid); - return JNI_FALSE; - } + DummyThreadContext * dispThreadCtx = (DummyThreadContext *) (intptr_t) jDispThreadCtx; + DummyThreadCommand tParam = {0}; - tParam.jHInstance = jHInstance; + tParam.hInstance = (HINSTANCE) (intptr_t) jHInstance; tParam.x = x; tParam.y = y; tParam.width = width; tParam.height = height; - tParam.hWnd = hWnd; + tParam.hWnd = 0; tParam.threadReady = FALSE; #ifdef UNICODE @@ -248,9 +383,37 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyWindowAndMessageLoop tParam.wndName = (*env)->GetStringUTFChars(env, jWndName, NULL); #endif - PostThreadMessage(threadid, TM_OPENWIN, (WPARAM)&tParam, 0); - - while(!tParam.threadReady) { /* nop */ } + if( NULL == dispThreadCtx ) { + tParam.hWnd = DummyWindowCreate(tParam.hInstance, tParam.wndClassName, tParam.wndName, tParam.x, tParam.y, tParam.width, tParam.height); + } else { + const HANDLE threadHandle = dispThreadCtx->threadHandle; + const DWORD threadId = dispThreadCtx->threadId; + if( JNI_FALSE == DDT_CheckAlive(env, sTM_OPENWIN, dispThreadCtx) ) { + free(dispThreadCtx); + NativewindowCommon_throwNewRuntimeException(env, "DDT %s (alive) failed handle %p, id %d, werr %d", + sTM_OPENWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } else { + if( 0 != PostThreadMessage(dispThreadCtx->threadId, TM_OPENWIN, (WPARAM)&tParam, 0) ) { + if( JNI_FALSE == DDT_WaitUntilReady(env, sTM_OPENWIN, &tParam) ) { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + tParam.hWnd = 0; + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s (ack) failed handle %p, id %d, werr %d", + sTM_OPENWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } + } else { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + tParam.hWnd = 0; + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s to handle %p, id %d failed, werr %d", + sTM_OPENWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } + } + } #ifdef UNICODE free((void*) tParam.wndClassName); @@ -260,62 +423,66 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyWindowAndMessageLoop (*env)->ReleaseStringUTFChars(env, jWndName, tParam.wndName); #endif - return (jlong) (intptr_t) hWnd; + return (jlong) (intptr_t) tParam.hWnd; } -/* Java->C glue code: - * Java package: jogamp.nativewindow.windows.GDIUtil - * Java method: long CreateDummyWindow0(long hInstance, java.lang.String className, java.lang.String windowName, int x, int y, int width, int height) - * C function: HANDLE CreateDummyWindow0(HANDLE hInstance, LPCSTR className, LPCSTR windowName, int x, int y, int width, int height); +/* + * Class: jogamp_nativewindow_windows_GDIUtil + * Method: DestroyWindow0 */ -JNIEXPORT jlong JNICALL -Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyWindow0 - (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jWndClassName, jstring jWndName, jint x, jint y, jint width, jint height) +JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_DestroyWindow0 +(JNIEnv *env, jclass unused, jlong jDispThreadCtx, jlong jwin) { - HINSTANCE hInstance = (HINSTANCE) (intptr_t) jHInstance; - const TCHAR* wndClassName = NULL; - const TCHAR* wndName = NULL; - DWORD dwExStyle; - DWORD dwStyle; - HWND hWnd; - -#ifdef UNICODE - wndClassName = NewtCommon_GetNullTerminatedStringChars(env, jWndClassName); - wndName = NewtCommon_GetNullTerminatedStringChars(env, jWndName); -#else - wndClassName = (*env)->GetStringUTFChars(env, jWndClassName, NULL); - wndName = (*env)->GetStringUTFChars(env, jWndName, NULL); -#endif - - dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; - dwStyle = WS_OVERLAPPEDWINDOW; - - hWnd = CreateWindowEx( dwExStyle, - wndClassName, - wndName, - dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, - x, y, width, height, - NULL, NULL, hInstance, NULL ); + jboolean res = JNI_TRUE; + DummyThreadContext * dispThreadCtx = (DummyThreadContext *) (intptr_t) jDispThreadCtx; + HWND hWnd = (HWND) (intptr_t) jwin; + if( NULL == dispThreadCtx ) { + DestroyWindow(hWnd); + } else { + const HANDLE threadHandle = dispThreadCtx->threadHandle; + const DWORD threadId = dispThreadCtx->threadId; + DummyThreadCommand tParam = {0}; -#ifdef UNICODE - free((void*) wndClassName); - free((void*) wndName); -#else - (*env)->ReleaseStringUTFChars(env, jWndClassName, wndClassName); - (*env)->ReleaseStringUTFChars(env, jWndName, wndName); -#endif + tParam.hWnd = hWnd; + tParam.threadReady = FALSE; - return (jlong) (intptr_t) hWnd; + if( JNI_FALSE == DDT_CheckAlive(env, sTM_CLOSEWIN, dispThreadCtx) ) { + free(dispThreadCtx); + res = JNI_FALSE; + NativewindowCommon_throwNewRuntimeException(env, "DDT %s (alive) failed handle %p, id %d, werr %d", + sTM_CLOSEWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } else { + if ( 0 != PostThreadMessage(dispThreadCtx->threadId, TM_CLOSEWIN, (WPARAM)&tParam, 0) ) { + if( JNI_FALSE == DDT_WaitUntilReady(env, sTM_CLOSEWIN, &tParam) ) { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + res = JNI_FALSE; + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s (ack) failed handle %p, id %d, werr %d", + sTM_CLOSEWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } + } else { + if( NULL != threadHandle ) { + TerminateThread(threadHandle, 0); + } + free(dispThreadCtx); + res = JNI_FALSE; + NativewindowCommon_throwNewRuntimeException(env, "DDT Post %s to handle %p, id %d failed, werr %d", + sTM_CLOSEWIN, (void*)threadHandle, (int)threadId, (int)GetLastError()); + } + } + } + return res; } - /* * Class: jogamp_nativewindow_windows_GDIUtil * Method: initIDs0 * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_initIDs0 - (JNIEnv *env, jclass clazz) + (JNIEnv *env, jclass gdiClazz) { if(NativewindowCommon_init(env)) { jclass c = (*env)->FindClass(env, ClazzNamePoint); @@ -332,11 +499,15 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_initIDs0 NativewindowCommon_FatalError(env, "FatalError jogamp_nativewindow_windows_GDIUtil: can't fetch %s.%s %s", ClazzNamePoint, ClazzAnyCstrName, ClazzNamePointCstrSignature); } + dumpStackID = (*env)->GetStaticMethodID(env, gdiClazz, "dumpStack", "()V"); + if(NULL==dumpStackID) { + NativewindowCommon_FatalError(env, "FatalError jogamp_nativewindow_windows_GDIUtil: can't get method dumpStack"); + } } return JNI_TRUE; } -LRESULT CALLBACK DummyWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { +static LRESULT CALLBACK DummyWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hWnd,uMsg,wParam,lParam); } @@ -379,8 +550,8 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_windows_GDIUtil_GetRelativeLo JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_IsChild0 (JNIEnv *env, jclass unused, jlong jwin) { - HWND hwnd = (HWND) (intptr_t) jwin; - LONG style = GetWindowLong(hwnd, GWL_STYLE); + HWND hWnd = (HWND) (intptr_t) jwin; + LONG style = GetWindowLong(hWnd, GWL_STYLE); BOOL bIsChild = 0 != (style & WS_CHILD) ; return bIsChild ? JNI_TRUE : JNI_FALSE; } @@ -392,34 +563,9 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_IsChild0 JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_IsUndecorated0 (JNIEnv *env, jclass unused, jlong jwin) { - HWND hwnd = (HWND) (intptr_t) jwin; - LONG style = GetWindowLong(hwnd, GWL_STYLE); + HWND hWnd = (HWND) (intptr_t) jwin; + LONG style = GetWindowLong(hWnd, GWL_STYLE); BOOL bIsUndecorated = 0 != (style & (WS_CHILD|WS_POPUP)) ; return bIsUndecorated ? JNI_TRUE : JNI_FALSE; } -/* - * Class: jogamp_nativewindow_windows_GDIUtil - * Method: SendCloseMessage - */ -JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_SendCloseMessage -(JNIEnv *env, jclass unused, jlong jwin) -{ - ThreadParam tParam = {0}; - volatile HWND hwnd = (HWND) (intptr_t) jwin; - - if( 0 == threadid ) { - NativewindowCommon_throwNewRuntimeException(env, "Native threadid zero 0x%X", (int)threadid); - return JNI_FALSE; - } - - tParam.hWnd = hwnd; - tParam.threadReady = FALSE; - - PostThreadMessage(threadid, TM_CLOSEWIN, (WPARAM)&tParam, 0); - - while(!tParam.threadReady) { /* nop */ } - - return JNI_TRUE; -} - diff --git a/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java index d8ff7ecb5..c4cfd98b3 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java @@ -51,7 +51,7 @@ public class DisplayDriver extends DisplayImpl { static { NEWTJNILibLoader.loadNEWT(); - sharedClassFactory = new RegisteredClassFactory(newtClassBaseName, WindowDriver.getNewtWndProc0()); + sharedClassFactory = new RegisteredClassFactory(newtClassBaseName, WindowDriver.getNewtWndProc0(), false /* useDummyDispatchThread */); if (!WindowDriver.initIDs0(RegisteredClassFactory.getHInstance())) { throw new NativeWindowException("Failed to initialize WindowsWindow jmethodIDs"); -- cgit v1.2.3 From 166e5da5298b16b0acbf900004964d370cd0aa29 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 18 Dec 2013 21:59:39 +0100 Subject: Bug 928 - JAWTWindow's JAWTComponentListener _not_ attached and original visibility state not restored @ detach Commit ebed9f0322e2a2279a525e04ee3875c9034a7f45 (fix for Bug 906) causes a regression to fix for Bug 816, Bug 849 and Bug 889 (OSX CALayer Positioning and JAWTWindow visibility). The commit adds the JAWTComponentListener instance 'jawtComponentListener' to the component before it's assignment (duh!). +++ Further more, detaching the JAWTComponentListener shall restore the component's original 'local visibility state', which might got overridden by it's 'hierarchyChanged' implementation. +++ --- make/scripts/tests.sh | 8 ++++---- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 22 ++++++++++++++-------- 2 files changed, 18 insertions(+), 12 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index cb60028aa..746985d83 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -192,7 +192,7 @@ function jrun() { #D_ARGS="-Dnewt.debug.EDT" #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT -Djogl.debug.GLContext" #D_ARGS="-Dnewt.debug.Window -Djogl.debug.Animator -Dnewt.debug.Screen" - #D_ARGS="-Dnativewindow.debug.JAWT -Dnewt.debug.Window" + D_ARGS="-Dnativewindow.debug.JAWT -Dnewt.debug.Window" #D_ARGS="-Dnewt.debug.Window.KeyEvent" #D_ARGS="-Dnewt.debug.Window.MouseEvent" #D_ARGS="-Dnewt.debug.Window.MouseEvent -Dnewt.debug.Window.KeyEvent" @@ -345,7 +345,7 @@ function testawtswt() { # #testnoawt jogamp.opengl.openal.av.ALDummyUsage $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube $* -testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple $* # # performance tests @@ -505,8 +505,8 @@ testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03aB729AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03bB849AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03cB849AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816JTabbedPanelVisibilityB849B878AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816GLCanvasFrameHoppingB849B889AWT $* +##testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816JTabbedPanelVisibilityB849B878AWT $* +testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816GLCanvasFrameHoppingB849B889AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04aAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04bAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug675BeansInDesignTimeAWT $* diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 9a19a7f7a..3c660b41b 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -159,20 +159,21 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, " ** THREAD "+getThreadName(); } - public JAWTComponentListener() { + private JAWTComponentListener() { if(DEBUG) { - System.err.println(jawtStr()+".attach: "+toString()); + System.err.println(jawtStr()+".attach @ Thread "+getThreadName()+": "+toString()); } - component.addComponentListener(jawtComponentListener); - component.addHierarchyListener(jawtComponentListener); + component.addComponentListener(this); + component.addHierarchyListener(this); } - public final void detach() { + private final void detach() { if(DEBUG) { - System.err.println(jawtStr()+".detach: "+toString()); + System.err.println(jawtStr()+".detach @ Thread "+getThreadName()+": "+toString()); } - component.removeComponentListener(jawtComponentListener); - component.removeHierarchyListener(jawtComponentListener); + component.removeComponentListener(this); + component.removeHierarchyListener(this); + component.setVisible(localVisibility); // restore component's original local state } @Override @@ -251,6 +252,11 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } else if(DEBUG) { System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (x): showing "+showing+" -> visible "+(showing && localVisibility)+", "+s(e)); } + } else if(DEBUG) { + final boolean displayable = changed.isDisplayable(); + final boolean _visible = displayable && localVisibility; + final boolean showing = changed.isShowing(); + System.err.println(jawtStr()+".hierarchyChanged OTHER: displayable "+displayable+", showing "+showing+" -> visible "+_visible+", "+s(e)); } } } -- cgit v1.2.3 From e7ffa68bce9bb707005be72530b207c732f62c31 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 31 Dec 2013 08:14:21 +0100 Subject: Bug 934, Bug 935: NEWT: Add support for custom Application/Window and Pointer Icons - Utilizing JOGL's PNG decoder for all icons, if available. - Application/window icons: - Providing default application/window icons in 16x16 and 32x32 size - NewtFactory.setWindowIcons(..) or property 'newt.window.icons' maybe used to override default icons. - Using icons at application/window instantiation - Display.PointerIcons: - NativeWindow Win32 WindowClass no more references a default cursor in favor of fine grained cursor control [in NEWT] - Display provides create/destroy methods, where display destruction also releases open PointerIcon references. - Window.setPointerIcon(..) sets custom PointerIcon - Implemented Platforms - X11 - Windows - OSX - Manual Test: TestGearsES2NEWT (Press 'c') --- make/build-jogl.xml | 2 +- make/build-newt.xml | 12 +- .../resources/assets-test/jogamp-pointer-64x64.png | Bin 0 -> 2843 bytes make/resources/assets/newt/data/jogamp-16x16.png | Bin 0 -> 549 bytes make/resources/assets/newt/data/jogamp-32x32.png | Bin 0 -> 1020 bytes make/resources/misc/jogamp-48x48.png | Bin 0 -> 1278 bytes make/resources/misc/jogamp-64x64.png | Bin 0 -> 1833 bytes make/scripts/tests-win.bat | 4 +- make/scripts/tests-x64-dbg.bat | 3 +- make/scripts/tests.sh | 5 +- src/nativewindow/native/win32/GDImisc.c | 2 +- src/newt/classes/com/jogamp/newt/Display.java | 50 +++++++- src/newt/classes/com/jogamp/newt/NewtFactory.java | 33 +++++ src/newt/classes/com/jogamp/newt/Window.java | 15 +++ .../classes/com/jogamp/newt/opengl/GLWindow.java | 11 ++ src/newt/classes/jogamp/newt/DisplayImpl.java | 68 +++++++++- src/newt/classes/jogamp/newt/WindowImpl.java | 22 ++++ src/newt/classes/jogamp/newt/driver/PNGIcon.java | 102 +++++++++++++++ .../jogamp/newt/driver/macosx/DisplayDriver.java | 51 ++++++++ .../jogamp/newt/driver/macosx/WindowDriver.java | 11 ++ .../jogamp/newt/driver/opengl/JoglUtilPNGIcon.java | 139 +++++++++++++++++++++ .../jogamp/newt/driver/windows/DisplayDriver.java | 38 ++++++ .../jogamp/newt/driver/windows/WindowDriver.java | 56 +++++++-- .../jogamp/newt/driver/x11/DisplayDriver.java | 46 +++++++ .../jogamp/newt/driver/x11/WindowDriver.java | 51 +++++++- src/newt/native/MacWindow.m | 73 ++++++++++- src/newt/native/NewtMacWindow.h | 4 +- src/newt/native/NewtMacWindow.m | 41 ++++-- src/newt/native/WindowsWindow.c | 115 ++++++++++++++++- src/newt/native/X11Display.c | 52 ++++++++ src/newt/native/X11Window.c | 35 +++++- .../jogl/demos/es2/newt/TestGearsES2NEWT.java | 29 ++++- 32 files changed, 1027 insertions(+), 43 deletions(-) create mode 100644 make/resources/assets-test/jogamp-pointer-64x64.png create mode 100644 make/resources/assets/newt/data/jogamp-16x16.png create mode 100644 make/resources/assets/newt/data/jogamp-32x32.png create mode 100644 make/resources/misc/jogamp-48x48.png create mode 100644 make/resources/misc/jogamp-64x64.png create mode 100644 src/newt/classes/jogamp/newt/driver/PNGIcon.java create mode 100644 src/newt/classes/jogamp/newt/driver/opengl/JoglUtilPNGIcon.java (limited to 'src/nativewindow') diff --git a/make/build-jogl.xml b/make/build-jogl.xml index 28b738b10..4cdb93f4d 100644 --- a/make/build-jogl.xml +++ b/make/build-jogl.xml @@ -1833,7 +1833,7 @@ - + + value="com/jogamp/newt/opengl/** jogamp/newt/driver/opengl/**"/> @@ -277,12 +277,14 @@ + + @@ -302,6 +304,7 @@ + @@ -309,6 +312,7 @@ + @@ -316,6 +320,7 @@ + @@ -323,6 +328,7 @@ + @@ -332,18 +338,21 @@ + + + @@ -798,6 +807,7 @@ + diff --git a/make/resources/assets-test/jogamp-pointer-64x64.png b/make/resources/assets-test/jogamp-pointer-64x64.png new file mode 100644 index 000000000..a965dcab1 Binary files /dev/null and b/make/resources/assets-test/jogamp-pointer-64x64.png differ diff --git a/make/resources/assets/newt/data/jogamp-16x16.png b/make/resources/assets/newt/data/jogamp-16x16.png new file mode 100644 index 000000000..02df8997f Binary files /dev/null and b/make/resources/assets/newt/data/jogamp-16x16.png differ diff --git a/make/resources/assets/newt/data/jogamp-32x32.png b/make/resources/assets/newt/data/jogamp-32x32.png new file mode 100644 index 000000000..ab21c6e1b Binary files /dev/null and b/make/resources/assets/newt/data/jogamp-32x32.png differ diff --git a/make/resources/misc/jogamp-48x48.png b/make/resources/misc/jogamp-48x48.png new file mode 100644 index 000000000..216f8c0b7 Binary files /dev/null and b/make/resources/misc/jogamp-48x48.png differ diff --git a/make/resources/misc/jogamp-64x64.png b/make/resources/misc/jogamp-64x64.png new file mode 100644 index 000000000..9936616ca Binary files /dev/null and b/make/resources/misc/jogamp-64x64.png differ diff --git a/make/scripts/tests-win.bat b/make/scripts/tests-win.bat index f5417bf7a..d95b0025f 100755 --- a/make/scripts/tests-win.bat +++ b/make/scripts/tests-win.bat @@ -6,7 +6,7 @@ REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.acore.TestMainVersion REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT -time 30000 REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT %* -REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* +scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 4000 -x 10 -y 10 -width 100 -height 100 -screen 0 REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 40000 -width 100 -height 100 -screen 0 %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT -time 5000 @@ -39,7 +39,7 @@ REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.tile.TestTiledPrintin REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLCapabilities01NEWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT %* -scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT %* +REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT %* REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT -time 5000 REM scripts\java-win.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT %* diff --git a/make/scripts/tests-x64-dbg.bat b/make/scripts/tests-x64-dbg.bat index 6e8407f3e..ce2df922c 100755 --- a/make/scripts/tests-x64-dbg.bat +++ b/make/scripts/tests-x64-dbg.bat @@ -55,9 +55,10 @@ REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLC REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.GLJPanel" "-Djogl.debug.TileRenderer" "-Djogl.debug.TileRenderer.PNG" REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.GLJPanel" "-Djogl.debug.TileRenderer" REM set D_ARGS="-Djogl.gljpanel.noverticalflip" +set D_ARGS="-Dnewt.debug=all" REM set D_ARGS="-Dnewt.debug.Window" REM set D_ARGS="-Dnewt.debug.Window.KeyEvent" -set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Window.KeyEvent" "-Dnewt.debug.EDT" +REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Window.KeyEvent" "-Dnewt.debug.EDT" REM set D_ARGS="-Dnewt.debug.Window.MouseEvent" REM set D_ARGS="-Dnewt.debug.Window.MouseEvent" "-Dnewt.debug.Window.KeyEvent" REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display" diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 6cb1966d1..4c084d705 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -312,7 +312,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLCanvasAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile00NEWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $* # # demos (any TK, more user driven tests) @@ -325,7 +325,7 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelsAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NewtCanvasAWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NEWT $* #testawtswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $* @@ -636,6 +636,7 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestJPEGTextureFromFileNEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGImage00NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGImage01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.ToolPNG2CSource $* #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGTextureFromFileAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGTextureFromFileNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite01AWT $* diff --git a/src/nativewindow/native/win32/GDImisc.c b/src/nativewindow/native/win32/GDImisc.c index b55988c11..25b98acf3 100644 --- a/src/nativewindow/native/win32/GDImisc.c +++ b/src/nativewindow/native/win32/GDImisc.c @@ -263,7 +263,7 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass0 wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = NULL; - wc.hCursor = LoadCursor( NULL, IDC_ARROW); + wc.hCursor = NULL; wc.hbrBackground = NULL; // no background paint - GetStockObject(BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = clazzName; diff --git a/src/newt/classes/com/jogamp/newt/Display.java b/src/newt/classes/com/jogamp/newt/Display.java index 4469189a8..ee6dfd080 100644 --- a/src/newt/classes/com/jogamp/newt/Display.java +++ b/src/newt/classes/com/jogamp/newt/Display.java @@ -28,15 +28,21 @@ package com.jogamp.newt; -import com.jogamp.newt.util.EDTUtil; -import jogamp.newt.Debug; - +import java.io.IOException; import java.lang.ref.WeakReference; -import java.util.*; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowException; +import jogamp.newt.Debug; + +import com.jogamp.common.util.IOUtil; +import com.jogamp.newt.util.EDTUtil; + public abstract class Display { public static final boolean DEBUG = Debug.debug("Display"); @@ -55,6 +61,42 @@ public abstract class Display { return false; } + /** + * Native PointerIcon handle. + *

                            + * Instances can be created via {@link Display#createPointerIcon(com.jogamp.common.util.IOUtil.ClassResources, int, int)} + * and released via {@link Display#destroyPointerIcon(PointerIcon)}. + *

                            + *

                            + * PointerIcons can be used via {@link Window#setPointerIcon(PointerIcon)}. + *

                            + */ + public static interface PointerIcon { } + + /** + * Returns the created {@link PointerIcon} or null if not implemented on platform. + * + * @param pngResource PNG resource + * @param hotX pointer hotspot x-coord, origin is upper-left corner + * @param hotY pointer hotspot y-coord, origin is upper-left corner + * @throws MalformedURLException + * @throws InterruptedException + * @throws IOException + * + * @see PointerIcon + * @see #destroyPointerIcon(PointerIcon) + * @see Window#setPointerIcon(PointerIcon) + */ + + public abstract PointerIcon createPointerIcon(final IOUtil.ClassResources pngResource, final int hotX, final int hotY) throws MalformedURLException, InterruptedException, IOException; + + /** + * @param pi + * + * @see #createPointerIcon(com.jogamp.common.util.IOUtil.ClassResources, int, int) + */ + public abstract void destroyPointerIcon(PointerIcon pi); + /** * Manual trigger the native creation, if it is not done yet.
                            * This is useful to be able to request the {@link javax.media.nativewindow.AbstractGraphicsDevice}, via diff --git a/src/newt/classes/com/jogamp/newt/NewtFactory.java b/src/newt/classes/com/jogamp/newt/NewtFactory.java index 157e2bb3c..92339ea73 100644 --- a/src/newt/classes/com/jogamp/newt/NewtFactory.java +++ b/src/newt/classes/com/jogamp/newt/NewtFactory.java @@ -36,6 +36,7 @@ package com.jogamp.newt; import java.security.AccessController; import java.security.PrivilegedAction; +import java.util.Arrays; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; @@ -44,6 +45,8 @@ import javax.media.nativewindow.CapabilitiesImmutable; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowFactory; +import com.jogamp.common.util.IOUtil; + import jogamp.newt.Debug; import jogamp.newt.DisplayImpl; import jogamp.newt.ScreenImpl; @@ -54,15 +57,45 @@ public class NewtFactory { public static final String DRIVER_DEFAULT_ROOT_PACKAGE = "jogamp.newt.driver"; + private static IOUtil.ClassResources defaultWindowIcons; + static { AccessController.doPrivileged(new PrivilegedAction() { @Override public Object run() { NativeWindowFactory.initSingleton(); // last resort .. + { + final String[] paths = Debug.getProperty("newt.window.icons", true, "newt/data/jogamp-16x16.png newt/data/jogamp-32x32.png").split("\\s"); + if( paths.length < 2 ) { + throw new IllegalArgumentException("Property 'newt.window.icons' did not specify at least two PNG icons, but "+Arrays.toString(paths)); + } + final Class clazz = NewtFactory.class; + defaultWindowIcons = new IOUtil.ClassResources(clazz, paths); + } return null; } } ); } + /** + * Returns the application window icon resources to be used. + *

                            + * Property newt.window.icons may define a list of PNG icons separated by a whitespace character. + * Shall reference at least two PNG icons, from lower (16x16) to higher (>= 32x32) resolution. + *

                            + *

                            + * Users may also specify application window icons using {@link #setWindowIcons(com.jogamp.common.util.IOUtil.ClassResources)}. + *

                            + */ + public static IOUtil.ClassResources getWindowIcons() { return defaultWindowIcons; } + + /** + * Allow user to set custom window icons, only applicable at application start before creating any NEWT instance. + *

                            + * Shall reference at least two PNG icons, from lower (16x16) to higher (>= 32x32) resolution. + *

                            + */ + public static void setWindowIcons(IOUtil.ClassResources cres) { defaultWindowIcons = cres; } + public static Class getCustomClass(String packageName, String classBaseName) { Class clazz = null; if(packageName!=null && classBaseName!=null) { diff --git a/src/newt/classes/com/jogamp/newt/Window.java b/src/newt/classes/com/jogamp/newt/Window.java index 5c3bb7889..8e73ba1d2 100644 --- a/src/newt/classes/com/jogamp/newt/Window.java +++ b/src/newt/classes/com/jogamp/newt/Window.java @@ -30,6 +30,7 @@ package com.jogamp.newt; import java.util.List; +import com.jogamp.newt.Display.PointerIcon; import com.jogamp.newt.event.GestureHandler; import com.jogamp.newt.event.WindowEvent; import com.jogamp.newt.event.WindowListener; @@ -307,6 +308,20 @@ public interface Window extends NativeWindow, WindowClosingProtocol { */ void setPointerVisible(boolean pointerVisible); + /** + * Returns the current {@link PointerIcon}, which maybe null for the default. + * @see #setPointerIcon(PointerIcon) + */ + PointerIcon getPointerIcon(); + + /** + * @param pi Valid {@link PointerIcon} reference or null to reset the pointer icon to default. + * + * @see PointerIcon + * @see Display#createPointerIcon(com.jogamp.common.util.IOUtil.ClassResources, int, int) + */ + void setPointerIcon(final PointerIcon pi); + /** @see #confinePointer(boolean) */ boolean isPointerConfined(); diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index 208602aa1..ca8ab6733 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -77,6 +77,7 @@ import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; import com.jogamp.newt.Window; +import com.jogamp.newt.Display.PointerIcon; import com.jogamp.newt.event.GestureHandler; import com.jogamp.newt.event.KeyListener; import com.jogamp.newt.event.MouseListener; @@ -267,6 +268,16 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind window.setPointerVisible(mouseVisible); } + @Override + public final PointerIcon getPointerIcon() { + return window.getPointerIcon(); + } + + @Override + public final void setPointerIcon(final PointerIcon pi) { + window.setPointerIcon(pi); + } + @Override public final boolean isPointerConfined() { return window.isPointerConfined(); diff --git a/src/newt/classes/jogamp/newt/DisplayImpl.java b/src/newt/classes/jogamp/newt/DisplayImpl.java index 0c29d772a..4e9b8b441 100644 --- a/src/newt/classes/jogamp/newt/DisplayImpl.java +++ b/src/newt/classes/jogamp/newt/DisplayImpl.java @@ -34,14 +34,18 @@ package jogamp.newt; +import com.jogamp.common.util.IOUtil; import com.jogamp.newt.Display; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.event.NEWTEvent; import com.jogamp.newt.event.NEWTEventConsumer; import jogamp.newt.event.NEWTEventTask; + import com.jogamp.newt.util.EDTUtil; +import java.io.IOException; +import java.net.MalformedURLException; import java.util.ArrayList; import javax.media.nativewindow.AbstractGraphicsDevice; @@ -62,6 +66,67 @@ public abstract class DisplayImpl extends Display { }); } + public static class PointerIconImpl implements PointerIcon { + public final long handle; + public PointerIconImpl(long handle) { + this.handle=handle; + } + } + + private void addPointerIconToList(final PointerIcon pi) { + synchronized(pointerIconList) { + pointerIconList.add(pi); + } + } + private void delPointerIconFromList(final PointerIcon pi) { + synchronized(pointerIconList) { + pointerIconList.remove(pi); + } + } + private final ArrayList pointerIconList = new ArrayList(); + + /** Executed from EDT! */ + private void destroyAllPointerIconFromList(final long dpy) { + synchronized(pointerIconList) { + for( int i=0; i < pointerIconList.size(); i++ ) { + final PointerIcon item = pointerIconList.get(i); + if( null != item ) { + // destroy! + destroyPointerIconImpl(dpy, item); + } + } + pointerIconList.clear(); + } + } + + @Override + public final PointerIcon createPointerIcon(final IOUtil.ClassResources pngResource, final int hotX, final int hotY) throws MalformedURLException, InterruptedException, IOException { + final PointerIcon res = createPointerIconImpl(pngResource, hotX, hotY); + addPointerIconToList(res); + return res; + } + protected PointerIcon createPointerIconImpl(final IOUtil.ClassResources pngResource, final int hotX, final int hotY) throws MalformedURLException, InterruptedException, IOException { + return null; + } + + @Override + public final void destroyPointerIcon(final PointerIcon pi) { + delPointerIconFromList(pi); + runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override + public Object run(long dpy) { + try { + destroyPointerIconImpl(dpy, pi); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + }); + } + /** Executed from EDT! */ + protected void destroyPointerIconImpl(final long displayHandle, final PointerIcon pi) { } + /** Ensure static init has been run. */ /* pp */static void initSingleton() { } @@ -283,6 +348,7 @@ public abstract class DisplayImpl extends Display { @Override public void run() { if ( null != f_aDevice ) { + f_dpy.destroyAllPointerIconFromList(f_aDevice.getHandle()); f_dpy.closeNativeImpl(f_aDevice); } } @@ -453,7 +519,7 @@ public abstract class DisplayImpl extends Display { /** Dispatch native Toolkit messageges */ protected abstract void dispatchMessagesNative(); - private Object eventsLock = new Object(); + private final Object eventsLock = new Object(); private ArrayList events = new ArrayList(); private volatile boolean haveEvents = false; diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index 7a7e69e48..d078caa3b 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -42,6 +42,7 @@ import java.lang.reflect.Method; import com.jogamp.common.util.ArrayHashSet; import com.jogamp.common.util.IntBitfield; import com.jogamp.common.util.ReflectionUtil; +import com.jogamp.newt.Display.PointerIcon; import com.jogamp.newt.MonitorDevice; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Display; @@ -83,6 +84,7 @@ import javax.media.nativewindow.util.Rectangle; import javax.media.nativewindow.util.RectangleImmutable; import jogamp.nativewindow.SurfaceUpdatedHelper; +import jogamp.newt.DisplayImpl.PointerIconImpl; public abstract class WindowImpl implements Window, NEWTEventConsumer { @@ -170,6 +172,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer private String title = "Newt Window"; private boolean undecorated = false; private boolean alwaysOnTop = false; + private PointerIcon pointerIcon = null; private boolean pointerVisible = true; private boolean pointerConfined = false; private LifecycleHook lifecycleHook = null; @@ -436,6 +439,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer createNativeImpl(); screen.addMonitorModeListener(monitorModeListenerImpl); setTitleImpl(title); + if( null != pointerIcon ) { + setPointerIcon(pointerIcon); + } setPointerVisibleImpl(pointerVisible); confinePointerImpl(pointerConfined); setKeyboardVisible(keyboardVisible); @@ -725,6 +731,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer protected boolean setPointerVisibleImpl(boolean pointerVisible) { return false; } protected boolean confinePointerImpl(boolean confine) { return false; } protected void warpPointerImpl(int x, int y) { } + protected void setPointerIconImpl(final PointerIconImpl pi) { } //---------------------------------------------------------------------- // NativeSurface @@ -1675,6 +1682,21 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } } } + + @Override + public final PointerIcon getPointerIcon() { return pointerIcon; } + + @Override + public final void setPointerIcon(final PointerIcon pi) { + if( this.pointerIcon != pi ) { + setPointerIcon(pointerIcon); + if( isNativeValid() ) { + setPointerIconImpl((PointerIconImpl)pi); + } + this.pointerIcon = pi; + } + } + @Override public final boolean isPointerConfined() { return pointerConfined; diff --git a/src/newt/classes/jogamp/newt/driver/PNGIcon.java b/src/newt/classes/jogamp/newt/driver/PNGIcon.java new file mode 100644 index 000000000..c958f6ec2 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/PNGIcon.java @@ -0,0 +1,102 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package jogamp.newt.driver; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.nio.ByteBuffer; + +import jogamp.newt.Debug; + +import com.jogamp.common.util.IOUtil; +import com.jogamp.common.util.ReflectionUtil; + +public class PNGIcon { + private static final String err0 = "PNG decoder not implemented."; + + private static final boolean avail; + + static { + Debug.initSingleton(); + + final ClassLoader cl = PNGIcon.class.getClassLoader(); + avail = ReflectionUtil.isClassAvailable("jogamp.newt.driver.opengl.JoglUtilPNGIcon", cl) && + ReflectionUtil.isClassAvailable("com.jogamp.opengl.util.texture.spi.PNGImage", cl); + } + + /** Returns true if PNG decoder is available. */ + public static boolean isAvailable() { + return avail; + } + + /** + * Implemented for X11. + * @param resources + * @param data_size + * @param elem_bytesize + * + * @return BGRA8888 bytes with origin at upper-left corner where component B is located on the lowest 8-bit and component A is located on the highest 8-bit. + * + * @throws UnsupportedOperationException if not implemented + * @throws InterruptedException + * @throws IOException + * @throws MalformedURLException + */ + public static ByteBuffer arrayToX11BGRAImages(IOUtil.ClassResources resources, int[] data_size, int[] elem_bytesize) throws UnsupportedOperationException, InterruptedException, IOException, MalformedURLException { + if( avail ) { + return jogamp.newt.driver.opengl.JoglUtilPNGIcon.arrayToX11BGRAImages(resources, data_size, elem_bytesize); + } + throw new UnsupportedOperationException(err0); + } + + /** + * Implemented for Windows. + * @param resources + * @param toBGRA if true, arranges stores in BGRA888 order, otherwise RGBA888 + * @param width + * @param height + * @param data_size + * @param elem_bytesize + * @param resourcesIdx + * @return pixels with origin at upper-left corner. + * If storing RGBA8888, component R is located on the lowest 8-bit. + * If storing BGRA8888, component B is located on the lowest 8-bit. + * Component A is located on the highest 8-bit. + * + * @throws UnsupportedOperationException if not implemented + * @throws InterruptedException + * @throws IOException + * @throws MalformedURLException + */ + public static ByteBuffer singleToRGBAImage(IOUtil.ClassResources resources, int resourceIdx, boolean toBGRA, int[] width, int[] height, int[] data_size, int[] elem_bytesize) throws UnsupportedOperationException, InterruptedException, IOException, MalformedURLException { + if( avail ) { + return jogamp.newt.driver.opengl.JoglUtilPNGIcon.singleToRGBAImage(resources, resourceIdx, toBGRA, width, height, data_size, elem_bytesize); + } + throw new UnsupportedOperationException(err0); + } +} diff --git a/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java index c44685dc8..86c8464a8 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java @@ -34,15 +34,26 @@ package jogamp.newt.driver.macosx; +import java.io.IOException; +import java.net.MalformedURLException; +import java.nio.Buffer; +import java.nio.ByteBuffer; + import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowException; +import com.jogamp.common.util.IOUtil; import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; +import com.jogamp.newt.NewtFactory; import jogamp.newt.DisplayImpl; import jogamp.newt.NEWTJNILibLoader; +import jogamp.newt.driver.PNGIcon; public class DisplayDriver extends DisplayImpl { + private static final int defaultIconWidth, defaultIconHeight; + private static final Buffer defaultIconData; + static { NEWTJNILibLoader.loadNEWT(); @@ -52,6 +63,25 @@ public class DisplayDriver extends DisplayImpl { if(!WindowDriver.initIDs0()) { throw new NativeWindowException("Failed to initialize jmethodIDs"); } + { + final int[] width = { 0 }, height = { 0 }, data_size = { 0 }, elem_bytesize = { 0 }; + Buffer data=null; + if( PNGIcon.isAvailable() ) { + try { + final IOUtil.ClassResources iconRes = NewtFactory.getWindowIcons(); + data = PNGIcon.singleToRGBAImage(iconRes, iconRes.resourceCount()-1, false /* toBGRA */, width, height, data_size, elem_bytesize); + } catch (Exception e) { + e.printStackTrace(); + } + } + defaultIconWidth = width[0]; + defaultIconHeight = height[0]; + defaultIconData = data; + if( null != defaultIconData ) { + DisplayDriver.setAppIcon0(defaultIconData, defaultIconWidth, defaultIconHeight); + } + } + if(DEBUG) { System.err.println("MacDisplay.init App and IDs OK "+Thread.currentThread().getName()); } @@ -79,6 +109,23 @@ public class DisplayDriver extends DisplayImpl { aDevice.close(); } + @Override + protected PointerIcon createPointerIconImpl(final IOUtil.ClassResources pngResource, final int hotX, final int hotY) throws MalformedURLException, InterruptedException, IOException { + if( PNGIcon.isAvailable() ) { + final int[] width = { 0 }, height = { 0 }, data_size = { 0 }, elem_bytesize = { 0 }; + if( null != pngResource && 0 < pngResource.resourceCount() ) { + final ByteBuffer data = PNGIcon.singleToRGBAImage(pngResource, 0, true /* toBGRA */, width, height, data_size, elem_bytesize); + return new PointerIconImpl( createPointerIcon0(data, width[0], height[0], hotX, hotY) ); + } + } + return null; + } + + @Override + protected final void destroyPointerIconImpl(final long displayHandle, final PointerIcon pi) { + destroyPointerIcon0(((PointerIconImpl)pi).handle); + } + public static void runNSApplication() { runNSApplication0(); } @@ -89,5 +136,9 @@ public class DisplayDriver extends DisplayImpl { private static native boolean initNSApplication0(); private static native void runNSApplication0(); private static native void stopNSApplication0(); + /* pp */ static native void setAppIcon0(Object iconData, int iconWidth, int iconHeight); + private static native long createPointerIcon0(Object iconData, int iconWidth, int iconHeight, int hotX, int hotY); + private static native long destroyPointerIcon0(long handle); + } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java index 641d7437c..a55fa915a 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java @@ -46,6 +46,7 @@ import javax.media.nativewindow.util.PointImmutable; import jogamp.nativewindow.macosx.OSXUtil; import jogamp.newt.WindowImpl; +import jogamp.newt.DisplayImpl.PointerIconImpl; import jogamp.newt.driver.DriverClearFocus; import jogamp.newt.driver.DriverUpdatePosition; @@ -391,6 +392,15 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl } } + @Override + protected void setPointerIconImpl(final PointerIconImpl pi) { + OSXUtil.RunOnMainThread(false, new Runnable() { + @Override + public void run() { + setPointerIcon0(getWindowHandle(), null != pi ? pi.handle : 0); + } } ); + } + @Override protected boolean setPointerVisibleImpl(final boolean pointerVisible) { if( !isOffscreenInstance ) { @@ -568,6 +578,7 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl private static native boolean setPointerVisible0(long windowHandle, boolean hasFocus, boolean visible); private static native boolean confinePointer0(long windowHandle, boolean confine); private static native void warpPointer0(long windowHandle, int x, int y); + private static native void setPointerIcon0(long windowHandle, long handle); // Window styles private static final int NSBorderlessWindowMask = 0; diff --git a/src/newt/classes/jogamp/newt/driver/opengl/JoglUtilPNGIcon.java b/src/newt/classes/jogamp/newt/driver/opengl/JoglUtilPNGIcon.java new file mode 100644 index 000000000..ea9029006 --- /dev/null +++ b/src/newt/classes/jogamp/newt/driver/opengl/JoglUtilPNGIcon.java @@ -0,0 +1,139 @@ +/** + * Copyright 2013 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package jogamp.newt.driver.opengl; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URLConnection; +import java.nio.ByteBuffer; + +import com.jogamp.common.nio.Buffers; +import com.jogamp.common.os.Platform; +import com.jogamp.common.util.IOUtil; +import com.jogamp.opengl.util.texture.spi.PNGImage; + +public class JoglUtilPNGIcon { + + public static ByteBuffer arrayToX11BGRAImages(IOUtil.ClassResources resources, int[] data_size, int[] elem_bytesize) throws UnsupportedOperationException, InterruptedException, IOException, MalformedURLException { + final PNGImage[] images = new PNGImage[resources.resourceCount()]; + data_size[0] = 0; + for(int i=0; inull if !{@link #isNativeValid()}, otherwise the Boolean value of {@link X11GraphicsDevice#isXineramaEnabled()}. */ protected Boolean isXineramaEnabled() { return isNativeValid() ? Boolean.valueOf(((X11GraphicsDevice)aDevice).isXineramaEnabled()) : null; } + @Override + protected PointerIcon createPointerIconImpl(final IOUtil.ClassResources pngResource, final int hotX, final int hotY) throws MalformedURLException, InterruptedException, IOException { + if( PNGIcon.isAvailable() ) { + final int[] width = { 0 }, height = { 0 }, data_size = { 0 }, elem_bytesize = { 0 }; + if( null != pngResource && 0 < pngResource.resourceCount() ) { + final ByteBuffer data = PNGIcon.singleToRGBAImage(pngResource, 0, false /* toBGRA */, width, height, data_size, elem_bytesize); + final long handle = runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override + public Long run(long dpy) { + long h = 0; + try { + h = createPointerIcon0(dpy, data, width[0], height[0], hotX, hotY); + } catch (Exception e) { + e.printStackTrace(); + } + return Long.valueOf(h); + } + }).longValue(); + return new PointerIconImpl(handle); + } + } + return null; + } + + @Override + protected final void destroyPointerIconImpl(final long displayHandle, final PointerIcon pi) { + destroyPointerIcon0(displayHandle, ((PointerIconImpl)pi).handle); + } + //---------------------------------------------------------------------- // Internals only // @@ -137,6 +174,15 @@ public class DisplayDriver extends DisplayImpl { private native void DispatchMessages0(long display, long javaObjectAtom, long windowDeleteAtom /* , long kbdHandle */); // XKB disabled for now + static long createPointerIcon0(long display, Buffer data, int width, int height, int hotX, int hotY) { + if( !Buffers.isDirect(data) ) { + throw new IllegalArgumentException("data buffer is not direct "+data); + } + return createPointerIcon0(display, data, Buffers.getDirectBufferByteOffset(data), width, height, hotX, hotY); + } + private static native long createPointerIcon0(long display, Object data, int data_offset, int width, int height, int hotX, int hotY); + static native void destroyPointerIcon0(long display, long handle); + /** X11 Window delete atom marker used on EDT */ private long windowDeleteAtom; diff --git a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java index f2a27b0c9..0ea2c5358 100644 --- a/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/x11/WindowDriver.java @@ -34,11 +34,16 @@ package jogamp.newt.driver.x11; +import java.nio.Buffer; + import jogamp.nativewindow.x11.X11Lib; import jogamp.nativewindow.x11.X11Util; import jogamp.newt.DisplayImpl; import jogamp.newt.DisplayImpl.DisplayRunnable; +import jogamp.newt.DisplayImpl.PointerIconImpl; import jogamp.newt.WindowImpl; +import jogamp.newt.driver.PNGIcon; + import javax.media.nativewindow.*; import javax.media.nativewindow.VisualIDHolder.VIDType; import javax.media.nativewindow.util.Insets; @@ -47,6 +52,7 @@ import javax.media.nativewindow.util.Point; import com.jogamp.nativewindow.x11.X11GraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsScreen; +import com.jogamp.newt.NewtFactory; import com.jogamp.newt.event.InputEvent; import com.jogamp.newt.event.KeyEvent; import com.jogamp.newt.event.MouseEvent; @@ -58,8 +64,29 @@ public class WindowDriver extends WindowImpl { private static final int X11_WHEEL_TWO_UP_BUTTON = 6; private static final int X11_WHEEL_TWO_DOWN_BUTTON = 7; + private static final int defaultIconDataSize; + private static final Buffer defaultIconData; + static { ScreenDriver.initSingleton(); + + int _icon_data_size=0, _icon_elem_bytesize=0; + Buffer _icon_data=null; + if( PNGIcon.isAvailable() ) { + try { + final int[] data_size = { 0 }, elem_bytesize = { 0 }; + _icon_data = PNGIcon.arrayToX11BGRAImages(NewtFactory.getWindowIcons(), data_size, elem_bytesize); + _icon_data_size = data_size[0]; + _icon_elem_bytesize = elem_bytesize[0]; + } catch (Exception e) { + e.printStackTrace(); + } + } + defaultIconDataSize = _icon_data_size; + defaultIconData = _icon_data; + if(DEBUG_IMPLEMENTATION) { + System.err.println("Def. Icon: data_size "+defaultIconDataSize+" * elem_size "+_icon_elem_bytesize+" = data "+defaultIconData); + } } public WindowDriver() { @@ -100,7 +127,8 @@ public class WindowDriver extends WindowImpl { setWindowHandle(CreateWindow0(getParentWindowHandle(), edtDevice.getHandle(), screen.getIndex(), visualID, display.getJavaObjectAtom(), display.getWindowDeleteAtom(), - getX(), getY(), getWidth(), getHeight(), autoPosition(), flags)); + getX(), getY(), getWidth(), getHeight(), autoPosition(), flags, + defaultIconDataSize, defaultIconData)); } finally { edtDevice.unlock(); } @@ -245,6 +273,21 @@ public class WindowDriver extends WindowImpl { }); } + @Override + protected void setPointerIconImpl(final PointerIconImpl pi) { + runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { + @Override + public Object run(long dpy) { + try { + setPointerIcon0(dpy, getWindowHandle(), null != pi ? pi.handle : 0); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + }); + } + @Override protected boolean setPointerVisibleImpl(final boolean pointerVisible) { return runWithLockedDisplayDevice( new DisplayImpl.DisplayRunnable() { @@ -381,13 +424,17 @@ public class WindowDriver extends WindowImpl { private native long CreateWindow0(long parentWindowHandle, long display, int screen_index, int visualID, long javaObjectAtom, long windowDeleteAtom, - int x, int y, int width, int height, boolean autoPosition, int flags); + int x, int y, int width, int height, boolean autoPosition, int flags, + int iconDataSize, Object iconData); private native void CloseWindow0(long display, long windowHandle, long javaObjectAtom, long windowDeleteAtom /*, long kbdHandle*/ ); // XKB disabled for now private native void reconfigureWindow0(long display, int screen_index, long parentWindowHandle, long windowHandle, long windowDeleteAtom, int x, int y, int width, int height, int flags); private native void requestFocus0(long display, long windowHandle, boolean force); private static native void setTitle0(long display, long windowHandle, String title); + + private static native void setPointerIcon0(long display, long windowHandle, long handle); + private static native long getParentWindow0(long display, long windowHandle); private static native boolean setPointerVisible0(long display, long windowHandle, boolean visible); private static native boolean confinePointer0(long display, long windowHandle, boolean grab); diff --git a/src/newt/native/MacWindow.m b/src/newt/native/MacWindow.m index 30d3458ad..16e9814ef 100644 --- a/src/newt/native/MacWindow.m +++ b/src/newt/native/MacWindow.m @@ -285,6 +285,76 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_DisplayDriver_stopNSApplic [pool release]; } +static NSImage * createNSImageFromData(JNIEnv *env, jobject jiconData, jint jiconWidth, jint jiconHeight) { + if( NULL != jiconData ) { + unsigned char * iconData = (unsigned char *) (*env)->GetDirectBufferAddress(env, jiconData); + NSInteger iconWidth = (NSInteger) jiconWidth; + NSInteger iconHeight = (NSInteger) jiconHeight; + const NSInteger bpc = 8 /* bits per component */, spp=4 /* RGBA */, bpp = bpc * spp; + const NSBitmapFormat bfmt = NSAlphaNonpremultipliedBitmapFormat; + const BOOL hasAlpha = YES; + + NSBitmapImageRep* bir = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: &iconData + pixelsWide: iconWidth + pixelsHigh: iconHeight + bitsPerSample: bpc + samplesPerPixel: spp + hasAlpha: hasAlpha + isPlanar: NO + colorSpaceName: NSCalibratedRGBColorSpace + bitmapFormat: bfmt + bytesPerRow: iconWidth*4 + bitsPerPixel: bpp]; + [bir autorelease]; + NSImage* nsImage = [[NSImage alloc] initWithCGImage: [bir CGImage] size:NSZeroSize]; + return nsImage; + } + return NULL; +} + +/* + * Class: jogamp_newt_driver_macosx_DisplayDriver + * Method: setAppIcon0 + */ +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_DisplayDriver_setAppIcon0 + (JNIEnv *env, jobject unused, jobject jiconData, jint jiconWidth, jint jiconHeight) +{ + NSImage * nsImage = createNSImageFromData(env, jiconData, jiconWidth, jiconHeight); + if( NULL != nsImage ) { + [nsImage autorelease]; + [NSApp setApplicationIconImage: nsImage]; + } +} + +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_DisplayDriver_createPointerIcon0 + (JNIEnv *env, jobject unused, jobject jiconData, jint jiconWidth, jint jiconHeight, jint hotX, jint hotY) +{ + NSImage * nsImage = createNSImageFromData(env, jiconData, jiconWidth, jiconHeight); + if( NULL != nsImage ) { + [nsImage autorelease]; + NSPoint hotP = { hotX, hotY }; + NSCursor * c = [[NSCursor alloc] initWithImage: nsImage hotSpot: hotP]; + return (jlong) (intptr_t) c; + } + return 0; +} + +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_DisplayDriver_destroyPointerIcon0 + (JNIEnv *env, jobject unused, jlong handle) +{ + NSCursor * c = (NSCursor*) (intptr_t) handle ; + [c release]; +} + +JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_setPointerIcon0 + (JNIEnv *env, jobject unused, jlong window, jlong handle) +{ + NewtMacWindow *mWin = (NewtMacWindow*) (intptr_t) window; + NSCursor * c = (NSCursor*) (intptr_t) handle ; + + [mWin setCustomCursor: c]; +} + static NSScreen * NewtScreen_getNSScreenByIndex(int screen_idx, BOOL cap) { NSArray *screens = [NSScreen screens]; if( screen_idx<0 || screen_idx>=[screens count] ) { @@ -632,7 +702,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_createView0 [pool release]; - return (jlong) ((intptr_t) myView); + return (jlong) (intptr_t) myView; } /** @@ -674,7 +744,6 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_createWindow backing: (NSBackingStoreType) bufferingType defer: YES isFullscreenWindow: fullscreen]; - // DBG_PRINT( "createWindow0.1 - %p, isVisible %d\n", myWindow, [myWindow isVisible]); DBG_PRINT( "createWindow0.X - %p, isVisible %d\n", myWindow, [myWindow isVisible]); diff --git a/src/newt/native/NewtMacWindow.h b/src/newt/native/NewtMacWindow.h index ba60b5665..1f907f30e 100644 --- a/src/newt/native/NewtMacWindow.h +++ b/src/newt/native/NewtMacWindow.h @@ -114,6 +114,7 @@ BOOL mouseVisible; BOOL mouseInside; BOOL cursorIsHidden; + NSCursor * customCursor; BOOL realized; BOOL modsDown[4]; // shift, ctrl, alt/option, win/command NSPoint lastInsideMousePosition; @@ -151,7 +152,8 @@ - (NSPoint) screenPos2NewtClientWinPos: (NSPoint) p; - (BOOL) isMouseInside; -- (void) cursorHide:(BOOL)v; +- (void) cursorHide:(BOOL)v enter:(int)enterState; +- (void) setCustomCursor:(NSCursor*)c; - (void) setMouseVisible:(BOOL)v hasFocus:(BOOL)focus; - (void) setMouseConfined:(BOOL)v; - (void) setMousePosition:(NSPoint)p; diff --git a/src/newt/native/NewtMacWindow.m b/src/newt/native/NewtMacWindow.m index 4b0198c7e..a7bab9b9d 100644 --- a/src/newt/native/NewtMacWindow.m +++ b/src/newt/native/NewtMacWindow.m @@ -41,6 +41,8 @@ #include +#define PRINTF(...) NSLog(@ __VA_ARGS__) + static jfloat GetDelta(NSEvent *event, jint javaMods[]) { CGEventRef cgEvent = [event CGEvent]; CGFloat deltaY = 0.0; @@ -468,6 +470,7 @@ static UniChar CKCH_CharForKeyCode(jshort keyCode) { defaultPresentationOptions = 0; fullscreenPresentationOptions = 0; } + isFullscreenWindow = isfs; // Why is this necessary? Without it we don't get any of the // delegate methods like resizing and window movement. @@ -484,6 +487,7 @@ static UniChar CKCH_CharForKeyCode(jshort keyCode) { mouseVisible = YES; mouseInside = NO; cursorIsHidden = NO; + customCursor = NULL; realized = YES; DBG_PRINT("NewtWindow::create: %p, realized %d, hasPresentationSwitch %d[defaultOptions 0x%X, fullscreenOptions 0x%X], (refcnt %d)\n", res, realized, (int)hasPresentationSwitch, (int)defaultPresentationOptions, (int)fullscreenPresentationOptions, (int)[res retainCount]); @@ -678,13 +682,36 @@ static UniChar CKCH_CharForKeyCode(jshort keyCode) { DBG_PRINT( "setMouseVisible: confined %d, visible %d (current: %d), mouseInside %d, hasFocus %d\n", mouseConfined, mouseVisible, !cursorIsHidden, mouseInside, focus); if(YES == focus && YES == mouseInside) { - [self cursorHide: !mouseVisible]; + [self cursorHide: !mouseVisible enter: 0]; + } +} + +- (void) setCustomCursor:(NSCursor*)c +{ + if(YES == mouseInside) { + if( NULL != c ) { + DBG_PRINT( "setCustomCursor push: %p\n", c); + [c push]; + } else if( NULL != customCursor && [NSCursor currentCursor] == customCursor ) { + DBG_PRINT( "setCustomCursor pop: %p\n", customCursor); + [customCursor pop]; + } } + customCursor = c; } -- (void) cursorHide:(BOOL)v +- (void) cursorHide:(BOOL)v enter:(int)enterState { - DBG_PRINT( "cursorHide: %d -> %d\n", cursorIsHidden, v); + DBG_PRINT( "cursorHide: %d -> %d, enter %d\n", cursorIsHidden, v, enterState); + if( NULL != customCursor ) { + if( 1 == enterState && [NSCursor currentCursor] != customCursor ) { + DBG_PRINT( "cursorHide.customCursor push: %p\n", customCursor); + [customCursor push]; + } else if( -1 == enterState && [NSCursor currentCursor] == customCursor ) { + DBG_PRINT( "cursorHide.customCursor pop: %p\n", customCursor); + [customCursor pop]; + } + } if(v) { if(!cursorIsHidden) { [NSCursor hide]; @@ -941,7 +968,7 @@ static jint mods2JavaMods(NSUInteger mods) DBG_PRINT( "*************** windowDidBecomeKey\n"); mouseInside = [self isMouseInside]; if(YES == mouseInside) { - [self cursorHide: !mouseVisible]; + [self cursorHide: !mouseVisible enter: 0]; } [self focusChanged: YES]; } @@ -995,7 +1022,7 @@ static jint mods2JavaMods(NSUInteger mods) { DBG_PRINT( "mouseEntered: confined %d, visible %d\n", mouseConfined, mouseVisible); mouseInside = YES; - [self cursorHide: !mouseVisible]; + [self cursorHide: !mouseVisible enter: 1]; if(NO == mouseConfined) { [self sendMouseEvent: theEvent eventType: EVENT_MOUSE_ENTERED]; } @@ -1006,7 +1033,7 @@ static jint mods2JavaMods(NSUInteger mods) DBG_PRINT( "mouseExited: confined %d, visible %d\n", mouseConfined, mouseVisible); if(NO == mouseConfined) { mouseInside = NO; - [self cursorHide: NO]; + [self cursorHide: NO enter: -1]; [self sendMouseEvent: theEvent eventType: EVENT_MOUSE_EXITED]; } else { [self setMousePosition: lastInsideMousePosition]; @@ -1160,7 +1187,7 @@ static jint mods2JavaMods(NSUInteger mods) jboolean closed = JNI_FALSE; NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - [self cursorHide: NO]; + [self cursorHide: NO enter: -1]; NSView* nsview = [self contentView]; if( ! [nsview isKindOfClass:[NewtView class]] ) { diff --git a/src/newt/native/WindowsWindow.c b/src/newt/native/WindowsWindow.c index dd0150e78..2a16dce57 100644 --- a/src/newt/native/WindowsWindow.c +++ b/src/newt/native/WindowsWindow.c @@ -139,7 +139,7 @@ #include "NewtCommon.h" -// #define VERBOSE_ON 1 +#define VERBOSE_ON 1 // #define DEBUG_KEYS 1 #ifdef VERBOSE_ON @@ -186,6 +186,10 @@ typedef struct { int height; /** Tristate: -1 HIDE, 0 NOP, 1 SHOW */ int setPointerVisible; + /** Tristate: -1 RESET, 0 NOP, 1 SET-NEW */ + int setPointerAction; + HCURSOR setPointerHandle; + HCURSOR defPointerHandle; /** Bool: 0 NOP, 1 FULLSCREEN */ int setFullscreen; int pointerCaptured; @@ -1023,10 +1027,22 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP } else /* -1 == wud->setPointerVisible */ { visibilityChangeSuccessful = SafeShowCursor(FALSE); } - useDefWindowProc = visibilityChangeSuccessful ? 1 : 0; DBG_PRINT("*** WindowsWindow: WM_SETCURSOR requested visibility: %d success: %d\n", wud->setPointerVisible, visibilityChangeSuccessful); wud->setPointerVisible = 0; - // own signal, consumed + // own signal, consumed, no further processing + useDefWindowProc = 0; + res = 1; + } else if( 0 != wud->setPointerAction ) { + if( -1 == wud->setPointerAction ) { + wud->setPointerHandle = wud->defPointerHandle; + } + HCURSOR preHandle = SetCursor(wud->setPointerHandle); + DBG_PRINT("*** WindowsWindow: WM_SETCURSOR requested change %d: pre %p -> set %p, def %p\n", + wud->setPointerAction, (void*)preHandle, (void*)wud->setPointerHandle, (void*)wud->defPointerHandle); + wud->setPointerAction = 0; + // own signal, consumed, no further processing + useDefWindowProc = 0; + res = 1; } else { useDefWindowProc = 1; // NOP for us, allow parent to act } @@ -1246,6 +1262,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lP if( 0 == wud->pointerInside ) { wud->pointerInside = 1; NewtWindows_trackPointerLeave(wnd); + SetCursor(wud->setPointerHandle); } (*env)->CallVoidMethod(env, window, sendMouseEventID, (jshort) EVENT_MOUSE_MOVED, @@ -1997,7 +2014,8 @@ static void NewtWindow_setVisiblePosSize(HWND hwnd, BOOL atop, BOOL visible, JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowDriver_CreateWindow0 (JNIEnv *env, jobject obj, jlong hInstance, jstring jWndClassName, jstring jWndName, jint winMajor, jint winMinor, - jlong parent, jint jx, jint jy, jint defaultWidth, jint defaultHeight, jboolean autoPosition, jint flags) + jlong parent, jint jx, jint jy, jint defaultWidth, jint defaultHeight, jboolean autoPosition, jint flags, + jlong iconSmallHandle, jlong iconBigHandle) { HWND parentWindow = (HWND) (intptr_t) parent; const TCHAR* wndClassName = NULL; @@ -2054,6 +2072,9 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowDriver_CreateWindo wud->width = width; wud->height = height; wud->setPointerVisible = 0; + wud->setPointerAction = 0; + wud->defPointerHandle = LoadCursor( NULL, IDC_ARROW); + wud->setPointerHandle = wud->defPointerHandle; wud->setFullscreen = 0; wud->pointerCaptured = 0; wud->pointerInside = 0; @@ -2083,6 +2104,12 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowDriver_CreateWindo RECT rc; RECT * insets; + if( 0 != iconSmallHandle ) { + SendMessage(window, WM_SETICON, ICON_SMALL, (LPARAM) iconSmallHandle ); + } + if( 0 != iconBigHandle ) { + SendMessage(window, WM_SETICON, ICON_BIG, (LPARAM) iconBigHandle ); + } ShowWindow(window, SW_SHOW); // send insets before visibility, allowing java code a proper sync point! @@ -2321,3 +2348,83 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowDriver_warpPointer0 SetCursorPos(x, y); } +JNIEXPORT jlong JNICALL +Java_jogamp_newt_driver_windows_DisplayDriver_createBGRA8888Icon0(JNIEnv *env, jobject _unused, + jobject data, jint data_offset, jint width, jint height, jboolean isCursor, jint hotX, jint hotY) { + + const unsigned char * data_ptr = (const unsigned char *) (*env)->GetDirectBufferAddress(env, data) + data_offset; + const int bytes = 4 * width * height; // BGRA8888 + + DWORD dwWidth, dwHeight; + BITMAPV5HEADER bi; + HBITMAP hBitmap; + void *lpBits; + HICON handle = NULL; + + dwWidth = width; // width of cursor + dwHeight = height; // height of cursor + + ZeroMemory(&bi,sizeof(BITMAPV5HEADER)); + bi.bV5Size = sizeof(BITMAPV5HEADER); + bi.bV5Width = dwWidth; + bi.bV5Height = -1 * dwHeight; + bi.bV5Planes = 1; + bi.bV5BitCount = 32; + bi.bV5Compression = BI_BITFIELDS; + // The following mask specification specifies a supported 32 BPP + // alpha format for Windows XP. + bi.bV5RedMask = 0x00FF0000; + bi.bV5GreenMask = 0x0000FF00; + bi.bV5BlueMask = 0x000000FF; + bi.bV5AlphaMask = 0xFF000000; + + HDC hdc; + hdc = GetDC(NULL); + + // Create the DIB section with an alpha channel. + hBitmap = CreateDIBSection(hdc, (BITMAPINFO *)&bi, DIB_RGB_COLORS, + (void **)&lpBits, NULL, (DWORD)0); + + memcpy(lpBits, data_ptr, bytes); + + ReleaseDC(NULL,hdc); + + // Create an empty mask bitmap. + HBITMAP hMonoBitmap = CreateBitmap(dwWidth,dwHeight,1,1,NULL); + + ICONINFO ii; + ii.fIcon = isCursor ? FALSE : TRUE; + ii.xHotspot = hotX; + ii.yHotspot = hotY; + ii.hbmMask = hMonoBitmap; + ii.hbmColor = hBitmap; + + // Create the alpha cursor with the alpha DIB section. + handle = CreateIconIndirect(&ii); + + DeleteObject(hBitmap); + DeleteObject(hMonoBitmap); + + return (jlong) (intptr_t) handle; +} + +JNIEXPORT void JNICALL +Java_jogamp_newt_driver_windows_DisplayDriver_destroyIcon0(JNIEnv *env, jobject _unused, jlong jhandle) { + HICON handle = (HICON) (intptr_t) jhandle; + DestroyIcon(handle); +} + +JNIEXPORT void JNICALL +Java_jogamp_newt_driver_windows_WindowDriver_setPointerIcon0(JNIEnv *env, jobject _unused, jlong window, jlong iconHandle) { + HWND hwnd = (HWND) (intptr_t) window; + WindowUserData * wud; +#if !defined(__MINGW64__) && ( defined(UNDER_CE) || _MSC_VER <= 1200 ) + wud = (WindowUserData *) GetWindowLong(hwnd, GWL_USERDATA); +#else + wud = (WindowUserData *) GetWindowLongPtr(hwnd, GWLP_USERDATA); +#endif + wud->setPointerAction = 0 != iconHandle ? 1 : -1; + wud->setPointerHandle = (HCURSOR) (intptr_t) iconHandle; + SendMessage(hwnd, WM_SETCURSOR, 0, 0); +} + diff --git a/src/newt/native/X11Display.c b/src/newt/native/X11Display.c index e2392a113..19e733111 100644 --- a/src/newt/native/X11Display.c +++ b/src/newt/native/X11Display.c @@ -28,6 +28,8 @@ #include "X11Common.h" +#include + // #include // XKB disabled for now jclass X11NewtWindowClazz = NULL; @@ -670,4 +672,54 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessage } } +/* + * Class: Java_jogamp_newt_driver_x11_DisplayDriver + * Method: createPointerIcon0 + * Signature: (JJILjava/lang/Object;I)V + */ +JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_createPointerIcon0 + (JNIEnv *env, jclass clazz, jlong display, jobject data, jint data_offset, jint width, jint height, jint hotX, jint hotY) +{ + Cursor c; + + if( 0 != data ) { + Display * dpy = (Display *) (intptr_t) display; + char * data_ptr = (char *) (*env)->GetDirectBufferAddress(env, data) + data_offset; + XcursorImage ci; + ci.version = 1; // XCURSOR_IMAGE_VERSION; + ci.size = width; // nominal size (assume square ..) + ci.width = width; + ci.height = height; + ci.xhot = hotX; + ci.yhot = hotY; + ci.delay = 0; + ci.pixels = (XcursorPixel *)(intptr_t)data_ptr; + + c = XcursorImageLoadCursor (dpy, &ci); + + DBG_PRINT( "X11: createPointerIcon0: %p %dx%d %d/%d -> %p\n", data_ptr, width, height, hotX, hotY, (void *)c); + + } else { + c = 0; + } + return (jlong) (intptr_t) c; +} + +/* + * Class: Java_jogamp_newt_driver_x11_DisplayDriver + * Method: destroyPointerIcon0 + * Signature: (JJILjava/lang/Object;I)V + */ +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_destroyPointerIcon0 + (JNIEnv *env, jclass clazz, jlong display, jlong handle) +{ + Display * dpy = (Display *) (intptr_t) display; + + if( 0 != handle ) { + Cursor c = (Cursor) (intptr_t) handle; + DBG_PRINT( "X11: destroyPointerIcon0: %p\n", (void *)c); + XFreeCursor(dpy, c); + } +} + diff --git a/src/newt/native/X11Window.c b/src/newt/native/X11Window.c index 5f5dddbe0..da2778004 100644 --- a/src/newt/native/X11Window.c +++ b/src/newt/native/X11Window.c @@ -497,6 +497,12 @@ static void NewtWindows_setPosSize(Display *dpy, Window w, jint x, jint y, jint } } +static void NewtWindows_setIcon(Display *dpy, Window w, int data_size, const unsigned char * data_ptr) { + Atom _NET_WM_ICON = XInternAtom(dpy, "_NET_WM_ICON", False); + Atom CARDINAL = XInternAtom(dpy, "CARDINAL", False); + XChangeProperty(dpy, w, _NET_WM_ICON, CARDINAL, 32, PropModeReplace, data_ptr, data_size); +} + /* * Class: jogamp_newt_driver_x11_WindowDriver * Method: CreateWindow @@ -505,7 +511,8 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CreateWindow0 (JNIEnv *env, jobject obj, jlong parent, jlong display, jint screen_index, jint visualID, jlong javaObjectAtom, jlong windowDeleteAtom, - jint x, jint y, jint width, jint height, jboolean autoPosition, int flags) + jint x, jint y, jint width, jint height, jboolean autoPosition, int flags, + jint iconDataSize, jobject iconData) { Display * dpy = (Display *)(intptr_t)display; Atom wm_delete_atom = (Atom)windowDeleteAtom; @@ -626,6 +633,11 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CreateWindow0 XEvent event; int left=0, right=0, top=0, bottom=0; + if( 0 < iconDataSize && NULL != iconData ) { + const unsigned char * iconDataPtr = (const unsigned char *) (*env)->GetDirectBufferAddress(env, iconData); + NewtWindows_setIcon(dpy, window, (int)iconDataSize, iconDataPtr); + } + XMapWindow(dpy, window); XIfEvent( dpy, &event, WaitForMapNotify, (XPointer) window ); // wait to get proper insets values @@ -944,6 +956,27 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_setTitle0 #endif } +/* + * Class: Java_jogamp_newt_driver_x11_WindowDriver + * Method: setPointerIcon0 + * Signature: (JJILjava/lang/Object;I)V + */ +JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_WindowDriver_setPointerIcon0 + (JNIEnv *env, jclass clazz, jlong display, jlong window, jlong handle) +{ + Display * dpy = (Display *) (intptr_t) display; + Window w = (Window)window; + + if( 0 == handle ) { + DBG_PRINT( "X11: setPointerIcon0: reset\n"); + XUndefineCursor(dpy, w); + } else { + Cursor c = (Cursor) (intptr_t) handle; + DBG_PRINT( "X11: setPointerIcon0: %p\n", (void*)c); + XDefineCursor(dpy, w, c); + } +} + /* * Class: Java_jogamp_newt_driver_x11_WindowDriver * Method: setPointerVisible0 diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java index b54a2cd19..efec961de 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java @@ -30,7 +30,9 @@ package com.jogamp.opengl.test.junit.jogl.demos.es2.newt; import java.io.IOException; +import com.jogamp.common.util.IOUtil; import com.jogamp.newt.Display; +import com.jogamp.newt.Display.PointerIcon; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; import com.jogamp.newt.event.KeyAdapter; @@ -44,9 +46,7 @@ import com.jogamp.opengl.test.junit.util.AWTRobotUtil; import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; import com.jogamp.opengl.test.junit.util.QuitAdapter; - import com.jogamp.opengl.util.Animator; - import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; import javax.media.nativewindow.NativeWindowFactory; @@ -54,7 +54,6 @@ import javax.media.nativewindow.util.Dimension; import javax.media.nativewindow.util.Point; import javax.media.nativewindow.util.PointImmutable; import javax.media.nativewindow.util.DimensionImmutable; - import javax.media.opengl.GLAnimatorControl; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; @@ -171,6 +170,20 @@ public class TestGearsES2NEWT extends UITestCase { } }); + final PointerIcon pointerIconOne; + { + PointerIcon _pointerIconOne = null; + final IOUtil.ClassResources res = new IOUtil.ClassResources(glWindow.getClass(), new String[] { "jogamp-pointer-64x64.png" } ); + final Display disp = glWindow.getScreen().getDisplay(); + disp.createNative(); + try { + _pointerIconOne = disp.createPointerIcon(res, 32, 0); + } catch (Exception e) { + e.printStackTrace(); + } + pointerIconOne = _pointerIconOne; + } + glWindow.addKeyListener(new KeyAdapter() { @Override public void keyPressed(final KeyEvent e) { @@ -203,6 +216,16 @@ public class TestGearsES2NEWT extends UITestCase { System.err.println("[set alwaysontop post]: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", f "+glWindow.isFullscreen()+", a "+glWindow.isAlwaysOnTop()+", "+glWindow.getInsets()); glWindow.setExclusiveContextThread(t); } }.start(); + } else if(e.getKeyChar()=='c') { + new Thread() { + public void run() { + final Thread t = glWindow.setExclusiveContextThread(null); + System.err.println("[set pointer-icon pre]"); + final PointerIcon currentPI = glWindow.getPointerIcon(); + glWindow.setPointerIcon( currentPI == pointerIconOne ? null : pointerIconOne); + System.err.println("[set pointer-icon post] "+currentPI+" -> "+glWindow.getPointerIcon()); + glWindow.setExclusiveContextThread(t); + } }.start(); } else if(e.getKeyChar()=='d') { new Thread() { public void run() { -- cgit v1.2.3 From bec29cf970e6a55eb8f720afdae5a3bdc97c1ba2 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 4 Jan 2014 17:18:47 +0100 Subject: Bug 935: NEWT OSX PointerIcon/Pointer-Visibility: Impl. OffscreenLayerSurface (OSX CALayer) w/ JAWTWindow Path Add setCursor(..) and hideCursor() to OffscreenLayerSurface interface, impl. in JAWTWindow w/ AWT. This allows an OSX NEWT Window using CALayer (i.e. NewtCanvasAWT) to have setPointerIcon(..) and setPointerVisible(..) functionality! --- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 28 ++++++++++++++++ .../media/nativewindow/OffscreenLayerSurface.java | 20 ++++++++++++ .../classes/jogamp/nativewindow/awt/AWTMisc.java | 37 ++++++++++++++++++++++ .../jogamp/newt/driver/macosx/WindowDriver.java | 36 +++++++++++++++++++-- 4 files changed, 119 insertions(+), 2 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 3c660b41b..46bdc4d1f 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -38,18 +38,21 @@ package com.jogamp.nativewindow.awt; import com.jogamp.common.os.Platform; +import com.jogamp.common.util.IOUtil; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.nativewindow.MutableGraphicsConfiguration; import java.awt.Component; import java.awt.Container; +import java.awt.Cursor; import java.awt.Window; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.applet.Applet; +import java.io.IOException; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; @@ -63,6 +66,7 @@ import javax.media.nativewindow.SurfaceUpdatedListener; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.InsetsImmutable; import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.util.PointImmutable; import javax.media.nativewindow.util.Rectangle; import javax.media.nativewindow.util.RectangleImmutable; @@ -427,6 +431,30 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return surfaceLock; } + @Override + public final boolean setCursor(IOUtil.ClassResources resources, PointImmutable hotSpot) throws IOException { + final Cursor c; + if( null == resources || null == hotSpot ) { + c = Cursor.getDefaultCursor(); + } else { + final java.awt.Point awtHotspot = new java.awt.Point(hotSpot.getX(), hotSpot.getY()); + c = AWTMisc.getCursor(resources, awtHotspot); + } + if( null != c ) { + component.setCursor(c); + return true; + } else { + return false; + } + } + + @Override + public boolean hideCursor() { + final Cursor c = AWTMisc.getNullCursor(); + component.setCursor(c); + return true; + } + // // SurfaceUpdateListener // diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index 8681422ef..81983a7c2 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -27,6 +27,11 @@ */ package javax.media.nativewindow; +import java.io.IOException; + +import javax.media.nativewindow.util.PointImmutable; + +import com.jogamp.common.util.IOUtil; import com.jogamp.common.util.locks.RecursiveLock; /** @@ -65,4 +70,19 @@ public interface OffscreenLayerSurface { /** Returns the recursive lock object of this surface, which synchronizes multithreaded access. */ public RecursiveLock getLock(); + /** + * Optional method setting cursor in the corresponding on-screen surface/window, if exists. + * + * @param resources maybe null for default cursor + * @param hotSpot maybe null for default cursor + * @return true if successful, i.e. on-screen surface/window w/ cursor capabilities exists. Otherwise false. + * @throws IOException + */ + public boolean setCursor(IOUtil.ClassResources resources, PointImmutable hotSpot) throws IOException; + /** + * Optional method hiding the cursor in the corresponding on-screen surface/window, if exists. + * + * @return true if successful, i.e. on-screen surface/window w/ cursor capabilities exists. Otherwise false. + */ + public boolean hideCursor(); } diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java index 0fa5006cc..31de84137 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java +++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java @@ -27,21 +27,31 @@ */ package jogamp.nativewindow.awt; +import java.awt.Cursor; import java.awt.FocusTraversalPolicy; import java.awt.Insets; +import java.awt.Point; +import java.awt.Toolkit; import java.awt.Window; import java.awt.Component; import java.awt.Container; import java.awt.Frame; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.net.URLConnection; +import java.util.HashMap; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JRootPane; import javax.swing.WindowConstants; +import javax.imageio.ImageIO; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.WindowClosingProtocol; import javax.swing.MenuSelectionManager; +import com.jogamp.common.util.IOUtil; + public class AWTMisc { public static JFrame getJFrame(Component c) { @@ -163,6 +173,33 @@ public class AWTMisc { MenuSelectionManager.defaultManager().clearSelectedPath(); } + static final HashMap cursorMap = new HashMap(); + static final Cursor nulCursor; + static { + final Toolkit toolkit = Toolkit.getDefaultToolkit(); + BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR); + nulCursor = toolkit.createCustomCursor(img, new Point(0,0), "nullCursor"); + } + + public static synchronized Cursor getNullCursor() { return nulCursor; } + + public static synchronized Cursor getCursor(IOUtil.ClassResources resources, Point hotSpot) throws IOException { + final String key = resources.getClass().getName()+":"+resources.resourcePaths[0]; + Cursor cursor = cursorMap.get(key); + if( null == cursor ) { + cursor = createAWTCursor(resources, hotSpot); + cursorMap.put(key, cursor); + } + return cursor; + } + private static synchronized Cursor createAWTCursor(IOUtil.ClassResources resources, Point hotSpot) throws IOException { + final URLConnection urlConn = resources.resolve(0); + BufferedImage img = ImageIO.read(urlConn.getInputStream()); + + final Toolkit toolkit = Toolkit.getDefaultToolkit(); + return toolkit.createCustomCursor(img, hotSpot, resources.resourcePaths[0]); + } + public static WindowClosingProtocol.WindowClosingMode AWT2NWClosingOperation(int awtClosingOperation) { switch (awtClosingOperation) { case WindowConstants.DISPOSE_ON_CLOSE: diff --git a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java index 6f3c95570..748604994 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/WindowDriver.java @@ -39,6 +39,8 @@ import javax.media.nativewindow.GraphicsConfigurationFactory; import javax.media.nativewindow.NativeWindow; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.MutableSurface; +import javax.media.nativewindow.NativeWindowFactory; +import javax.media.nativewindow.OffscreenLayerSurface; import javax.media.nativewindow.VisualIDHolder; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.Point; @@ -403,7 +405,23 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl throw new RuntimeException("Failed: "+pi+", "+WindowDriver.this); } } } ); - } // else may need offscreen solution ? FIXME + } else { + final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(this, true); + if( null != ols ) { + try { + setOLSPointer(ols, pi); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + private static void setOLSPointer(final OffscreenLayerSurface ols, final PointerIconImpl pi) throws Exception { + if( null != pi ) { + ols.setCursor(pi.getResource(), pi.getHotspot()); + } else { + ols.setCursor(null, null); // default + } } @Override @@ -417,7 +435,21 @@ public class WindowDriver extends WindowImpl implements MutableSurface, DriverCl } } } ); return true; // setPointerVisible0 always returns true .. - } // else may need offscreen solution ? FIXME + } else { + final OffscreenLayerSurface ols = NativeWindowFactory.getOffscreenLayerSurface(this, true); + if( null != ols ) { + try { + if( pointerVisible ) { + setOLSPointer(ols, (PointerIconImpl)getPointerIcon()); + } else { + ols.hideCursor(); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + } + } return false; } -- cgit v1.2.3 From 49e9ce7e641cb6923d9907ad66f667b3d3490e49 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 5 Jan 2014 03:38:15 +0100 Subject: Bug 935: NEWT Windows Window-Icon: Use WNDCLASSEX w/ Small/Big Default Icons (NativeWindow GDI / NEWT ) .. this allows using the icon definition of WNDCLASSEX instead of setting them at CreateWindow0(..). - NativeWindow GDIUtil/RegisteredFactory uses WNDCLASSEX and Small/Big Defailt Icons --- .../jogamp/nativewindow/windows/GDIUtil.java | 8 ++++-- .../windows/RegisteredClassFactory.java | 7 +++-- src/nativewindow/native/win32/GDImisc.c | 13 ++++++---- .../jogamp/newt/driver/windows/DisplayDriver.java | 26 +++++++++++++++++-- .../jogamp/newt/driver/windows/WindowDriver.java | 30 ++-------------------- src/newt/native/WindowsWindow.c | 9 +------ 6 files changed, 46 insertions(+), 47 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java index a872e63d8..720ff9bdb 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java @@ -59,7 +59,9 @@ public class GDIUtil implements ToolkitProperties { if( !initIDs0() ) { throw new NativeWindowException("GDI: Could not initialized native stub"); } - dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0(), true /* useDummyDispatchThread */); + dummyWindowClassFactory = new RegisteredClassFactory(dummyWindowClassNameBase, getDummyWndProc0(), + true /* useDummyDispatchThread */, + 0 /* iconSmallHandle */, 0 /* iconBigHandle */); if(DEBUG) { System.out.println("GDI.initSingleton() dummyWindowClassFactory "+dummyWindowClassFactory); } @@ -128,7 +130,9 @@ public class GDIUtil implements ToolkitProperties { private static final void dumpStack() { Thread.dumpStack(); } // Callback for JNI - static native boolean CreateWindowClass0(long hInstance, String clazzName, long wndProc); + /** Creates WNDCLASSEX instance */ + static native boolean CreateWindowClass0(long hInstance, String clazzName, long wndProc, long iconSmallHandle, long iconBigHandle); + /** Destroys WNDCLASSEX instance */ static native boolean DestroyWindowClass0(long hInstance, String className, long dispThreadCtx); static native long CreateDummyDispatchThread0(); diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java index ee41fe192..c4b4d145c 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java +++ b/src/nativewindow/classes/jogamp/nativewindow/windows/RegisteredClassFactory.java @@ -50,6 +50,7 @@ public class RegisteredClassFactory { private final String classBaseName; private final long wndProc; private final boolean useDummyDispatchThread; + private final long iconSmallHandle, iconBigHandle; private RegisteredClass sharedClass = null; private int classIter = 0; @@ -92,10 +93,12 @@ public class RegisteredClassFactory { /** Application handle. */ public static long getHInstance() { return hInstance; } - public RegisteredClassFactory(String classBaseName, long wndProc, boolean useDummyDispatchThread) { + public RegisteredClassFactory(String classBaseName, long wndProc, boolean useDummyDispatchThread, long iconSmallHandle, long iconBigHandle) { this.classBaseName = classBaseName; this.wndProc = wndProc; this.useDummyDispatchThread = useDummyDispatchThread; + this.iconSmallHandle = iconSmallHandle; + this.iconBigHandle = iconBigHandle; synchronized(registeredFactories) { registeredFactories.add(this); } @@ -114,7 +117,7 @@ public class RegisteredClassFactory { // Retry with next clazz name, this could happen if more than one JVM is running clazzName = classBaseName + classIter; classIter++; - registered = GDIUtil.CreateWindowClass0(hInstance, clazzName, wndProc); + registered = GDIUtil.CreateWindowClass0(hInstance, clazzName, wndProc, iconSmallHandle, iconBigHandle); } if( !registered ) { throw new NativeWindowException("Error: Could not create WindowClass: "+clazzName); diff --git a/src/nativewindow/native/win32/GDImisc.c b/src/nativewindow/native/win32/GDImisc.c index 25b98acf3..e28f68e7d 100644 --- a/src/nativewindow/native/win32/GDImisc.c +++ b/src/nativewindow/native/win32/GDImisc.c @@ -237,11 +237,12 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateDummyDispatchThread0 */ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass0 - (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jClazzName, jlong wndProc) + (JNIEnv *env, jclass _unused, jlong jHInstance, jstring jClazzName, jlong wndProc, + jlong iconSmallHandle, jlong iconBigHandle) { HINSTANCE hInstance = (HINSTANCE) (intptr_t) jHInstance; const TCHAR* clazzName = NULL; - WNDCLASS wc; + WNDCLASSEX wc; jboolean res; #ifdef UNICODE @@ -251,23 +252,25 @@ Java_jogamp_nativewindow_windows_GDIUtil_CreateWindowClass0 #endif ZeroMemory( &wc, sizeof( wc ) ); - if( GetClassInfo( hInstance, clazzName, &wc ) ) { + if( GetClassInfoEx( hInstance, clazzName, &wc ) ) { // registered already res = JNI_TRUE; } else { // register now ZeroMemory( &wc, sizeof( wc ) ); + wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW ; wc.lpfnWndProc = (WNDPROC) (intptr_t) wndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; - wc.hIcon = NULL; + wc.hIcon = (HICON) (intptr_t) iconBigHandle; wc.hCursor = NULL; wc.hbrBackground = NULL; // no background paint - GetStockObject(BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = clazzName; - res = ( 0 != RegisterClass( &wc ) ) ? JNI_TRUE : JNI_FALSE ; + wc.hIconSm = (HICON) (intptr_t) iconSmallHandle; + res = ( 0 != RegisterClassEx( &wc ) ) ? JNI_TRUE : JNI_FALSE ; } #ifdef UNICODE diff --git a/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java index 1e9c78a5d..a4db50165 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/windows/DisplayDriver.java @@ -54,16 +54,38 @@ import javax.media.nativewindow.util.Point; import com.jogamp.common.nio.Buffers; import com.jogamp.common.util.IOUtil; import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; +import com.jogamp.newt.NewtFactory; public class DisplayDriver extends DisplayImpl { private static final String newtClassBaseName = "_newt_clazz" ; + private static final long[] defaultIconHandles; private static RegisteredClassFactory sharedClassFactory; static { NEWTJNILibLoader.loadNEWT(); - - sharedClassFactory = new RegisteredClassFactory(newtClassBaseName, WindowDriver.getNewtWndProc0(), false /* useDummyDispatchThread */); + { + long[] _defaultIconHandle = { 0, 0 }; + if( PNGIcon.isAvailable() ) { + try { + final int[] width = { 0 }, height = { 0 }, data_size = { 0 }; + final IOUtil.ClassResources iconRes = NewtFactory.getWindowIcons(); + { + final ByteBuffer icon_data_small = PNGIcon.singleToRGBAImage(iconRes, 0, true /* toBGRA */, width, height, data_size); + _defaultIconHandle[0] = DisplayDriver.createBGRA8888Icon0(icon_data_small, width[0], height[0], false, 0, 0); + } + { + final ByteBuffer icon_data_big = PNGIcon.singleToRGBAImage(iconRes, iconRes.resourceCount()-1, true /* toBGRA */, width, height, data_size); + _defaultIconHandle[1] = DisplayDriver.createBGRA8888Icon0(icon_data_big, width[0], height[0], false, 0, 0); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + defaultIconHandles = _defaultIconHandle; + } + sharedClassFactory = new RegisteredClassFactory(newtClassBaseName, WindowDriver.getNewtWndProc0(), + false /* useDummyDispatchThread */, defaultIconHandles[0], defaultIconHandles[1]); if (!WindowDriver.initIDs0(RegisteredClassFactory.getHInstance())) { throw new NativeWindowException("Failed to initialize WindowsWindow jmethodIDs"); diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java index c8d7c65cc..a48fe2f62 100644 --- a/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/windows/WindowDriver.java @@ -40,7 +40,6 @@ import jogamp.nativewindow.windows.GDI; import jogamp.nativewindow.windows.GDIUtil; import jogamp.newt.PointerIconImpl; import jogamp.newt.WindowImpl; -import jogamp.newt.driver.PNGIcon; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.GraphicsConfigurationFactory; @@ -51,39 +50,16 @@ import javax.media.nativewindow.util.InsetsImmutable; import javax.media.nativewindow.util.Point; import com.jogamp.common.os.Platform; -import com.jogamp.common.util.IOUtil; import com.jogamp.common.util.VersionNumber; -import com.jogamp.newt.NewtFactory; import com.jogamp.newt.event.InputEvent; import com.jogamp.newt.event.KeyEvent; import com.jogamp.newt.event.MouseEvent; import com.jogamp.newt.event.MouseEvent.PointerType; public class WindowDriver extends WindowImpl { - private static final long[] defaultIconHandles; static { DisplayDriver.initSingleton(); - { - long[] _defaultIconHandle = { 0, 0 }; - if( PNGIcon.isAvailable() ) { - try { - final int[] width = { 0 }, height = { 0 }, data_size = { 0 }; - final IOUtil.ClassResources iconRes = NewtFactory.getWindowIcons(); - { - final ByteBuffer icon_data_small = PNGIcon.singleToRGBAImage(iconRes, 0, true /* toBGRA */, width, height, data_size); - _defaultIconHandle[0] = DisplayDriver.createBGRA8888Icon0(icon_data_small, width[0], height[0], false, 0, 0); - } - { - final ByteBuffer icon_data_big = PNGIcon.singleToRGBAImage(iconRes, iconRes.resourceCount()-1, true /* toBGRA */, width, height, data_size); - _defaultIconHandle[1] = DisplayDriver.createBGRA8888Icon0(icon_data_big, width[0], height[0], false, 0, 0); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - defaultIconHandles = _defaultIconHandle; - } } private long hmon; @@ -169,8 +145,7 @@ public class WindowDriver extends WindowImpl { ( FLAG_IS_ALWAYSONTOP | FLAG_IS_UNDECORATED ) ; final long _windowHandle = CreateWindow0(DisplayDriver.getHInstance(), display.getWindowClassName(), display.getWindowClassName(), winVer.getMajor(), winVer.getMinor(), - getParentWindowHandle(), getX(), getY(), getWidth(), getHeight(), autoPosition(), flags, - defaultIconHandles[0], defaultIconHandles[1]); + getParentWindowHandle(), getX(), getY(), getWidth(), getHeight(), autoPosition(), flags); if ( 0 == _windowHandle ) { throw new NativeWindowException("Error creating window"); } @@ -393,8 +368,7 @@ public class WindowDriver extends WindowImpl { protected static native boolean initIDs0(long hInstance); private native long CreateWindow0(long hInstance, String wndClassName, String wndName, int winMajor, int winMinor, - long parentWindowHandle, int x, int y, int width, int height, boolean autoPosition, int flags, - long iconSmallHandle, long iconBigHandle); + long parentWindowHandle, int x, int y, int width, int height, boolean autoPosition, int flags); private native long MonitorFromWindow0(long windowHandle); private native void reconfigureWindow0(long parentWindowHandle, long windowHandle, int x, int y, int width, int height, int flags); diff --git a/src/newt/native/WindowsWindow.c b/src/newt/native/WindowsWindow.c index 8671ee2e0..f193df2b6 100644 --- a/src/newt/native/WindowsWindow.c +++ b/src/newt/native/WindowsWindow.c @@ -2014,8 +2014,7 @@ static void NewtWindow_setVisiblePosSize(HWND hwnd, BOOL atop, BOOL visible, JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowDriver_CreateWindow0 (JNIEnv *env, jobject obj, jlong hInstance, jstring jWndClassName, jstring jWndName, jint winMajor, jint winMinor, - jlong parent, jint jx, jint jy, jint defaultWidth, jint defaultHeight, jboolean autoPosition, jint flags, - jlong iconSmallHandle, jlong iconBigHandle) + jlong parent, jint jx, jint jy, jint defaultWidth, jint defaultHeight, jboolean autoPosition, jint flags) { HWND parentWindow = (HWND) (intptr_t) parent; const TCHAR* wndClassName = NULL; @@ -2104,12 +2103,6 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowDriver_CreateWindo RECT rc; RECT * insets; - if( 0 != iconSmallHandle ) { - SendMessage(window, WM_SETICON, ICON_SMALL, (LPARAM) iconSmallHandle ); - } - if( 0 != iconBigHandle ) { - SendMessage(window, WM_SETICON, ICON_BIG, (LPARAM) iconBigHandle ); - } ShowWindow(window, SW_SHOW); // send insets before visibility, allowing java code a proper sync point! -- cgit v1.2.3 From 20b242387e6c329a2ba6261d39a05ffe9c39c6ab Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 5 Jan 2014 18:09:41 +0100 Subject: NativewindowCommon_init: Add define STDERR_TO_FILE (default undefined) to redirect stderr to file jogamp_stderr.log (Useful for Applets) --- src/nativewindow/native/NativewindowCommon.c | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src/nativewindow') diff --git a/src/nativewindow/native/NativewindowCommon.c b/src/nativewindow/native/NativewindowCommon.c index 212bdf82f..ec7ee7728 100644 --- a/src/nativewindow/native/NativewindowCommon.c +++ b/src/nativewindow/native/NativewindowCommon.c @@ -3,6 +3,8 @@ #include #include +// #define STDERR_TO_FILE 1 + static const char * const ClazzNameRuntimeException = "java/lang/RuntimeException"; static jclass runtimeExceptionClz=NULL; @@ -42,6 +44,11 @@ int NativewindowCommon_init(JNIEnv *env) { if(NULL==runtimeExceptionClz) { NativewindowCommon_FatalError(env, "Nativewindow: can't use %s", ClazzNameRuntimeException); } + #ifdef STDERR_TO_FILE + FILE * old_stderr = stderr; + FILE * new_stderr = freopen("jogamp_stderr.log", "w", stderr); + fprintf(stderr, "STDERR_TO_FILE: %p -> %p\n", old_stderr, new_stderr); + #endif return 1; } return 0; -- cgit v1.2.3 From dd527308f9129c705d82e6421e4822ba1a48abb9 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 5 Jan 2014 18:23:06 +0100 Subject: Bug 935: NEWT PointerIcon/Visibility: Perform JAWTWindow's OffscreenLayerSurface PointerIcon/Visibility tasks async on AWT-EDT setCursor(..) and hideCursor(..) must happen on the AWT-EDT w/o blocking, otherwise we may deadlock the NEWT-EDT. --- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 40 +++++++++++++--------- .../classes/jogamp/nativewindow/awt/AWTMisc.java | 4 +-- 2 files changed, 26 insertions(+), 18 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 46bdc4d1f..b947505cb 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -39,6 +39,7 @@ package com.jogamp.nativewindow.awt; import com.jogamp.common.os.Platform; import com.jogamp.common.util.IOUtil; +import com.jogamp.common.util.awt.AWTEDTExecutor; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.nativewindow.MutableGraphicsConfiguration; @@ -432,26 +433,33 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } @Override - public final boolean setCursor(IOUtil.ClassResources resources, PointImmutable hotSpot) throws IOException { - final Cursor c; - if( null == resources || null == hotSpot ) { - c = Cursor.getDefaultCursor(); - } else { - final java.awt.Point awtHotspot = new java.awt.Point(hotSpot.getX(), hotSpot.getY()); - c = AWTMisc.getCursor(resources, awtHotspot); - } - if( null != c ) { - component.setCursor(c); - return true; - } else { - return false; - } + public final boolean setCursor(final IOUtil.ClassResources resources, final PointImmutable hotSpot) throws IOException { + AWTEDTExecutor.singleton.invoke(false, new Runnable() { + public void run() { + Cursor c = null; + if( null == resources || null == hotSpot ) { + c = Cursor.getDefaultCursor(); + } else { + final java.awt.Point awtHotspot = new java.awt.Point(hotSpot.getX(), hotSpot.getY()); + try { + c = AWTMisc.getCursor(resources, awtHotspot); + } catch (IOException e) { + e.printStackTrace(); + } + } + if( null != c ) { + component.setCursor(c); + } + } } ); + return true; } @Override public boolean hideCursor() { - final Cursor c = AWTMisc.getNullCursor(); - component.setCursor(c); + AWTEDTExecutor.singleton.invoke(false, new Runnable() { + public void run() { + component.setCursor(AWTMisc.getNullCursor()); + } } ); return true; } diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java index 31de84137..b690aff4d 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java +++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java @@ -177,7 +177,7 @@ public class AWTMisc { static final Cursor nulCursor; static { final Toolkit toolkit = Toolkit.getDefaultToolkit(); - BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR); + final BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR); nulCursor = toolkit.createCustomCursor(img, new Point(0,0), "nullCursor"); } @@ -194,7 +194,7 @@ public class AWTMisc { } private static synchronized Cursor createAWTCursor(IOUtil.ClassResources resources, Point hotSpot) throws IOException { final URLConnection urlConn = resources.resolve(0); - BufferedImage img = ImageIO.read(urlConn.getInputStream()); + final BufferedImage img = ImageIO.read(urlConn.getInputStream()); final Toolkit toolkit = Toolkit.getDefaultToolkit(); return toolkit.createCustomCursor(img, hotSpot, resources.resourcePaths[0]); -- cgit v1.2.3 From fe28bc125429b38cdcd016746081f4a6d521c6fd Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 8 Jan 2014 21:27:20 +0100 Subject: Bug 935: NEWT PointerIcon: Add Toolkit Agnostic PixelFormat and Conversion Utilities (Allowing 'arbitrary' PointerIcon data input) To allowing 'arbitrary' PointerIcon data input, i.e. via raw pixels we need to define an agnostic PixelFormat and required conversion utilities. The latter is not hw accelereated (toolkit agnostic), but this shall be expected and satisfying for small amount of 'pixels'. --- .../com/jogamp/opengl/util/GLPixelBuffer.java | 100 ++++++ .../javax/media/nativewindow/util/PixelFormat.java | 196 +++++++++++ .../media/nativewindow/util/PixelFormatUtil.java | 374 +++++++++++++++++++++ .../media/nativewindow/util/PixelRectangle.java | 193 +++++++++++ .../util/texture/TestPixelFormatUtil00NEWT.java | 364 ++++++++++++++++++++ 5 files changed, 1227 insertions(+) create mode 100644 src/nativewindow/classes/javax/media/nativewindow/util/PixelFormat.java create mode 100644 src/nativewindow/classes/javax/media/nativewindow/util/PixelFormatUtil.java create mode 100644 src/nativewindow/classes/javax/media/nativewindow/util/PixelRectangle.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPixelFormatUtil00NEWT.java (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java b/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java index 50124c349..a921a2818 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLPixelBuffer.java @@ -30,11 +30,15 @@ package com.jogamp.opengl.util; import java.nio.Buffer; import java.nio.ByteBuffer; +import javax.media.nativewindow.util.PixelFormat; import javax.media.opengl.GL; +import javax.media.opengl.GL2; import javax.media.opengl.GL2ES2; import javax.media.opengl.GL2ES3; +import javax.media.opengl.GL2GL3; import javax.media.opengl.GLContext; import javax.media.opengl.GLException; +import javax.media.opengl.GLProfile; import com.jogamp.common.nio.Buffers; import com.jogamp.opengl.util.texture.TextureData; @@ -202,6 +206,56 @@ public class GLPixelBuffer { public GLPixelAttributes(int componentCount, int dataFormat, int dataType) { this(componentCount, dataFormat, dataType, true); } + + /** + * Returns the matching {@link GLPixelAttributes} for the given {@link PixelFormat} and {@link GLProfile} if exists, + * otherwise returns null. + */ + public static final GLPixelAttributes convert(PixelFormat pixFmt, GLProfile glp) { + int df = 0; // format + int dt = GL.GL_UNSIGNED_BYTE; // data type + switch(pixFmt) { + case LUMINANCE: + if( glp.isGL3ES3() ) { + // RED is supported on ES3 and >= GL3 [core]; ALPHA/LUMINANCE is deprecated on core + df = GL2ES2.GL_RED; + } else { + // ALPHA/LUMINANCE is supported on ES2 and GL2, i.e. <= GL3 [core] or compatibility + df = GL2ES2.GL_LUMINANCE; + } + break; + case BGR888: + if( glp.isGL2GL3() ) { + df = GL2GL3.GL_BGR; + } + break; + case RGB888: + df = GL.GL_RGB; + break; + case RGBA8888: + df = GL.GL_RGBA; + break; + case ABGR8888: + if( glp.isGL2GL3() ) { + df = GL.GL_RGBA; dt = GL2GL3.GL_UNSIGNED_INT_8_8_8_8; + } + break; + case BGRA8888: + df = GL.GL_BGRA; + break; + case ARGB8888: + if( glp.isGL2GL3() ) { + df = GL.GL_BGRA; dt = GL2GL3.GL_UNSIGNED_INT_8_8_8_8; + } + break; + default: + break; + } + if( 0 != df ) { + return new GLPixelAttributes(pixFmt.componentCount, df, dt, true); + } + return null; + } private GLPixelAttributes(int componentCount, int dataFormat, int dataType, boolean checkArgs) { this.componentCount = componentCount; this.format = dataFormat; @@ -216,6 +270,52 @@ public class GLPixelBuffer { } } } + + /** + * Returns the matching {@link PixelFormat} of this {@link GLPixelAttributes} if exists, + * otherwise returns null. + */ + public final PixelFormat getPixelFormat() { + final PixelFormat pixFmt; + // FIXME: Take 'type' into consideration and complete mapping! + switch(format) { + case GL.GL_ALPHA: + case GL.GL_LUMINANCE: + case GL2ES2.GL_RED: + pixFmt = PixelFormat.LUMINANCE; + break; + case GL.GL_RGB: + pixFmt = PixelFormat.RGB888; + break; + case GL.GL_RGBA: + pixFmt = PixelFormat.RGBA8888; + break; + case GL2.GL_BGR: + pixFmt = PixelFormat.BGR888; + break; + case GL.GL_BGRA: + pixFmt = PixelFormat.BGRA8888; + break; + default: + switch( bytesPerPixel ) { + case 1: + pixFmt = PixelFormat.LUMINANCE; + break; + case 3: + pixFmt = PixelFormat.RGB888; + break; + case 4: + pixFmt = PixelFormat.RGBA8888; + break; + default: + pixFmt = null; + break; + } + break; + } + return pixFmt; + } + @Override public String toString() { return "PixelAttributes[comp "+componentCount+", fmt 0x"+Integer.toHexString(format)+", type 0x"+Integer.toHexString(type)+", bytesPerPixel "+bytesPerPixel+"]"; diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormat.java b/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormat.java new file mode 100644 index 000000000..823496a92 --- /dev/null +++ b/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormat.java @@ -0,0 +1,196 @@ +/** + * Copyright (c) 2014 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ + +package javax.media.nativewindow.util; + +/** + * Basic pixel formats + *

                            + * Notation follows OpenGL notation, i.e. + * name consist of all it's component names + * followed by their bit size. + *

                            + *

                            + * Order of component names is from lowest-bit to highest-bit. + *

                            + *

                            + * In case component-size is 1 byte (e.g. OpenGL data-type GL_UNSIGNED_BYTE), + * component names are ordered from lowest-byte to highest-byte. + * Note that OpenGL applies special interpretation if + * data-type is e.g. GL_UNSIGNED_8_8_8_8_REV or GL_UNSIGNED_8_8_8_8_REV. + *

                            + *

                            + * PixelFormat can be converted to OpenGL GLPixelAttributes + * via + *

                            + *  GLPixelAttributes glpa = GLPixelAttributes.convert(PixelFormat pixFmt, GLProfile glp);
                            + * 
                            + *

                            + *

                            + * See OpenGL Specification 4.3 - February 14, 2013, Core Profile, + * Section 8.4.4 Transfer of Pixel Rectangles, p. 161-174. + * + * + *

                            + */ +public enum PixelFormat { + /** + * Pixel size is 1 bytes (8 bits) with one component of size 1 byte (8 bits). + * Compatible with: + *
                              + *
                            • OpenGL: data-format GL_ALPHA (< GL3), GL_RED (>= GL3), data-type GL_UNSIGNED_BYTE
                            • + *
                            • AWT: none
                            • + *
                            + *

                            + */ + LUMINANCE(1, 8), + + /** + * Pixel size is 3 bytes (24 bits) with each component of size 1 byte (8 bits). + *

                            + * The components are interleaved in the order: + *

                              + *
                            • Low to High: R, G, B
                            • + *
                            + *

                            + *

                            + * Compatible with: + *

                              + *
                            • OpenGL: data-format GL_RGB, data-type GL_UNSIGNED_BYTE
                            • + *
                            • AWT: None
                            • + *
                            + *

                            + */ + RGB888(3, 24), + + /** + * Pixel size is 3 bytes (24 bits) with each component of size 1 byte (8 bits). + *

                            + * The components are interleaved in the order: + *

                              + *
                            • Low to High: B, G, R
                            • + *
                            + *

                            + *

                            + * Compatible with: + *

                              + *
                            • OpenGL: data-format GL_BGR (>= GL2), data-type GL_UNSIGNED_BYTE
                            • + *
                            • AWT: {@link java.awt.image.BufferedImage#TYPE_3BYTE_BGR TYPE_3BYTE_BGR}
                            • + *
                            + *

                            + */ + BGR888(3, 24), + + /** + * Pixel size is 4 bytes (32 bits) with each component of size 1 byte (8 bits). + *

                            + * The components are interleaved in the order: + *

                              + *
                            • Low to High: R, G, B, A
                            • + *
                            + *

                            + *

                            + * Compatible with: + *

                              + *
                            • OpenGL: data-format GL_RGBA, data-type GL_UNSIGNED_BYTE
                            • + *
                            • AWT: None
                            • + *
                            • PointerIcon: X11 (XCURSOR)
                            • + *
                            • PNGJ: Scanlines
                            • + *
                            + *

                            + */ + RGBA8888(4, 32), + + /** + * Pixel size is 4 bytes (32 bits) with each component of size 1 byte (8 bits). + *

                            + * The components are interleaved in the order: + *

                              + *
                            • Low to High: A, B, G, R
                            • + *
                            + *

                            + *

                            + * Compatible with: + *

                              + *
                            • OpenGL: data-format GL_RGBA, data-type GL_UNSIGNED_8_8_8_8
                            • + *
                            • AWT: {@link java.awt.image.BufferedImage#TYPE_4BYTE_ABGR TYPE_4BYTE_ABGR}
                            • + *
                            + *

                            + */ + ABGR8888(4, 32), + + /** + * Pixel size is 4 bytes (32 bits) with each component of size 1 byte (8 bits). + *

                            + * The components are interleaved in the order: + *

                              + *
                            • Low to High: A, R, G, B
                            • + *
                            + *

                            + *

                            + * Compatible with: + *

                              + *
                            • OpenGL: data-format GL_BGRA, data-type GL_UNSIGNED_INT_8_8_8_8
                            • + *
                            • AWT: None
                            • + *
                            + *

                            + */ + ARGB8888(4, 32), + + /** + * Pixel size is 4 bytes (32 bits) with each component of size 1 byte (8 bits). + *

                            + * The components are interleaved in the order: + *

                              + *
                            • Low to High: B, G, R, A
                            • + *
                            + *

                            + *

                            + * Compatible with: + *

                              + *
                            • OpenGL: data-format GL_BGRA, data-type GL_UNSIGNED_BYTE
                            • + *
                            • AWT: {@link java.awt.image.BufferedImage#TYPE_INT_ARGB TYPE_INT_ARGB}
                            • + *
                            • PointerIcon: Win32, OSX (NSBitmapImageRep), AWT
                            • + *
                            • Window Icon: X11, Win32, OSX (NSBitmapImageRep)
                            • + *
                            + *

                            + */ + BGRA8888(4, 32); + + /** Number of components per pixel, e.g. 4 for RGBA. */ + public final int componentCount; + /** Number of bits per pixel, e.g. 32 for RGBA. */ + public final int bitsPerPixel; + /** Number of bytes per pixel, e.g. 4 for RGBA. */ + public final int bytesPerPixel() { return (7+bitsPerPixel)/8; } + + private PixelFormat(int componentCount, int bpp) { + this.componentCount = componentCount; + this.bitsPerPixel = bpp; + } +} diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormatUtil.java b/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormatUtil.java new file mode 100644 index 000000000..361d03446 --- /dev/null +++ b/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormatUtil.java @@ -0,0 +1,374 @@ +/** + * Copyright (c) 2014 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package javax.media.nativewindow.util; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import com.jogamp.common.nio.Buffers; + +/** + * Pixel Rectangle Utilities. + *

                            + * All conversion methods are endian independent. + *

                            + */ +public class PixelFormatUtil { + public static interface PixelSink { + /** Return the sink's destination pixelformat. */ + PixelFormat getPixelformat(); + + /** + * Returns stride in byte-size, i.e. byte count from one line to the next. + *

                            + * Must be >= {@link #getPixelformat()}.{@link PixelFormat#bytesPerPixel() bytesPerPixel()} * {@link #getSize()}.{@link DimensionImmutable#getWidth() getWidth()}. + *

                            + */ + int getStride(); + + /** + * Returns true if the sink's memory is laid out in + * OpenGL's coordinate system, origin at bottom left. + * Otherwise returns false, i.e. origin at top left. + */ + boolean isGLOriented(); + } + /** + * Pixel sink for up-to 32bit. + */ + public static interface PixelSink32 extends PixelSink { + /** + * Will be invoked over all rows top-to down + * and all columns left-to-right. + *

                            + * Shall consider dest pixelformat and only store as much components + * as defined, up to 32bit. + *

                            + *

                            + * Implementation may better write single bytes from low-to-high bits, + * e.g. {@link ByteOrder#LITTLE_ENDIAN} order. + * Otherwise a possible endian conversion must be taken into consideration. + *

                            + * @param x + * @param y + * @param pixel + */ + void store(int x, int y, int pixel); + } + + /** + * Returns the {@link PixelFormat} with reversed components of fmt. + * If no reversed {@link PixelFormat} is available, returns fmt. + */ + public static PixelFormat getReversed(PixelFormat fmt) { + switch(fmt) { + case LUMINANCE: + return PixelFormat.LUMINANCE; + case RGB888: + return PixelFormat.BGR888; + case BGR888: + return PixelFormat.RGB888; + case RGBA8888: + return PixelFormat.ABGR8888; + case ABGR8888: + return PixelFormat.RGBA8888; + case ARGB8888: + return PixelFormat.BGRA8888; + case BGRA8888: + return PixelFormat.ABGR8888; + default: + throw new InternalError("Unhandled format "+fmt); + } + } + + public static int getValue32(PixelFormat src_fmt, ByteBuffer src, int srcOff) { + switch(src_fmt) { + case LUMINANCE: { + final byte c1 = src.get(srcOff++); + return ( 0xff ) << 24 | ( 0xff & c1 ) << 16 | ( 0xff & c1 ) << 8 | ( 0xff & c1 ); + } + case RGB888: + case BGR888: { + final byte c1 = src.get(srcOff++); + final byte c2 = src.get(srcOff++); + final byte c3 = src.get(srcOff++); + return ( 0xff ) << 24 | ( 0xff & c3 ) << 16 | ( 0xff & c2 ) << 8 | ( 0xff & c1 ); + } + case RGBA8888: + case ABGR8888: + case ARGB8888: + case BGRA8888: { + final byte c1 = src.get(srcOff++); + final byte c2 = src.get(srcOff++); + final byte c3 = src.get(srcOff++); + final byte c4 = src.get(srcOff++); + return ( 0xff & c4 ) << 24 | ( 0xff & c3 ) << 16 | ( 0xff & c2 ) << 8 | ( 0xff & c1 ); + } + default: + throw new InternalError("Unhandled format "+src_fmt); + } + } + + public static int convertToInt32(PixelFormat dest_fmt, final byte r, final byte g, final byte b, final byte a) { + switch(dest_fmt) { + case LUMINANCE: { + final byte l = ( byte) ( ( ( ( 0xff & r ) + ( 0xff & g ) + ( 0xff & b ) ) / 3 ) ); + return ( 0xff ) << 24 | ( 0xff & l ) << 16 | ( 0xff & l ) << 8 | ( 0xff & l ); + } + case RGB888: + return ( 0xff ) << 24 | ( 0xff & b ) << 16 | ( 0xff & g ) << 8 | ( 0xff & r ); + case BGR888: + return ( 0xff ) << 24 | ( 0xff & r ) << 16 | ( 0xff & g ) << 8 | ( 0xff & b ); + case RGBA8888: + return ( 0xff & a ) << 24 | ( 0xff & b ) << 16 | ( 0xff & g ) << 8 | ( 0xff & r ); + case ABGR8888: + return ( 0xff & r ) << 24 | ( 0xff & g ) << 16 | ( 0xff & b ) << 8 | ( 0xff & a ); + case ARGB8888: + return ( 0xff & b ) << 24 | ( 0xff & g ) << 16 | ( 0xff & r ) << 8 | ( 0xff & a ); + case BGRA8888: + return ( 0xff & a ) << 24 | ( 0xff & r ) << 16 | ( 0xff & g ) << 8 | ( 0xff & b ); + default: + throw new InternalError("Unhandled format "+dest_fmt); + } + } + + public static int convertToInt32(PixelFormat dest_fmt, PixelFormat src_fmt, ByteBuffer src, int srcOff) { + final byte r, g, b, a; + switch(src_fmt) { + case LUMINANCE: + r = src.get(srcOff++); // R + g = r; // G + b = r; // B + a = (byte) 0xff; // A + break; + case RGB888: + r = src.get(srcOff++); // R + g = src.get(srcOff++); // G + b = src.get(srcOff++); // B + a = (byte) 0xff; // A + break; + case BGR888: + b = src.get(srcOff++); // B + g = src.get(srcOff++); // G + r = src.get(srcOff++); // R + a = (byte) 0xff; // A + break; + case RGBA8888: + r = src.get(srcOff++); // R + g = src.get(srcOff++); // G + b = src.get(srcOff++); // B + a = src.get(srcOff++); // A + break; + case ABGR8888: + a = src.get(srcOff++); // A + b = src.get(srcOff++); // B + g = src.get(srcOff++); // G + r = src.get(srcOff++); // R + break; + case ARGB8888: + a = src.get(srcOff++); // A + r = src.get(srcOff++); // R + g = src.get(srcOff++); // G + b = src.get(srcOff++); // B + break; + case BGRA8888: + b = src.get(srcOff++); // B + g = src.get(srcOff++); // G + r = src.get(srcOff++); // R + a = src.get(srcOff++); // A + break; + default: + throw new InternalError("Unhandled format "+src_fmt); + } + return convertToInt32(dest_fmt, r, g, b, a); + } + + /** + public static int convertToInt32(PixelFormat dest_fmt, PixelFormat src_fmt, final int src_pixel) { + final byte r, g, b, a; + switch(src_fmt) { + case LUMINANCE: + r = (byte) ( src_pixel ); // R + g = r; // G + b = r; // B + a = (byte) 0xff; // A + break; + case RGB888: + r = (byte) ( src_pixel ); // R + g = (byte) ( src_pixel >>> 8 ); // G + b = (byte) ( src_pixel >>> 16 ); // B + a = (byte) 0xff; // A + break; + case BGR888: + b = (byte) ( src_pixel ); // B + g = (byte) ( src_pixel >>> 8 ); // G + r = (byte) ( src_pixel >>> 16 ); // R + a = (byte) 0xff; // A + break; + case RGBA8888: + r = (byte) ( src_pixel ); // R + g = (byte) ( src_pixel >>> 8 ); // G + b = (byte) ( src_pixel >>> 16 ); // B + a = (byte) ( src_pixel >>> 24 ); // A + break; + case ABGR8888: + a = (byte) ( src_pixel ); // A + b = (byte) ( src_pixel >>> 8 ); // B + g = (byte) ( src_pixel >>> 16 ); // G + r = (byte) ( src_pixel >>> 24 ); // R + break; + case ARGB8888: + a = (byte) ( src_pixel ); // A + r = (byte) ( src_pixel >>> 8 ); // R + g = (byte) ( src_pixel >>> 16 ); // G + b = (byte) ( src_pixel >>> 24 ); // B + break; + case BGRA8888: + b = (byte) ( src_pixel ); // B + g = (byte) ( src_pixel >>> 8 ); // G + r = (byte) ( src_pixel >>> 16 ); // R + a = (byte) ( src_pixel >>> 24 ); // A + break; + default: + throw new InternalError("Unhandled format "+src_fmt); + } + return convertToInt32(dest_fmt, r, g, b, a); + } */ + + public static PixelRectangle convert32(final PixelRectangle src, + final PixelFormat destFmt, int ddestStride, final boolean isGLOriented, + final boolean destIsDirect) { + final int width = src.getSize().getWidth(); + final int height = src.getSize().getHeight(); + final int bpp = destFmt.bytesPerPixel(); + final int destStride; + if( 0 != ddestStride ) { + destStride = ddestStride; + if( destStride < bpp * width ) { + throw new IllegalArgumentException("Invalid stride "+destStride+", must be greater than bytesPerPixel "+bpp+" * width "+width); + } + } else { + destStride = bpp * width; + } + final int capacity = destStride*height; + final ByteBuffer bb = destIsDirect ? Buffers.newDirectByteBuffer(capacity) : ByteBuffer.allocate(capacity).order(src.getPixels().order()); + + // System.err.println("XXX: SOURCE "+src); + // System.err.println("XXX: DEST fmt "+destFmt+", stride "+destStride+" ("+ddestStride+"), isGL "+isGLOriented+", "+width+"x"+height+", capacity "+capacity+", "+bb); + + final PixelFormatUtil.PixelSink32 imgSink = new PixelFormatUtil.PixelSink32() { + public void store(int x, int y, int pixel) { + int o = destStride*y+x*bpp; + bb.put(o++, (byte) ( pixel )); // 1 + if( 3 <= bpp ) { + bb.put(o++, (byte) ( pixel >>> 8 )); // 2 + bb.put(o++, (byte) ( pixel >>> 16 )); // 3 + if( 4 <= bpp ) { + bb.put(o++, (byte) ( pixel >>> 24 )); // 4 + } + } + } + @Override + public final PixelFormat getPixelformat() { + return destFmt; + } + @Override + public final int getStride() { + return destStride; + } + @Override + public final boolean isGLOriented() { + return isGLOriented; + } + }; + convert32(imgSink, src); + return new PixelRectangle.GenericPixelRect(destFmt, src.getSize(), destStride, isGLOriented, bb); + } + + public static void convert32(PixelSink32 destInt32, final PixelRectangle src) { + convert32(destInt32, + src.getPixels(), src.getPixelformat(), + src.isGLOriented(), + src.getSize().getWidth(), src.getSize().getHeight(), + src.getStride()); + } + + /** + * + * @param dest32 32bit pixel sink + * @param src_bb + * @param src_fmt + * @param src_glOriented if true, the source memory is laid out in OpenGL's coordinate system, origin at bottom left, + * otherwise origin at top left. + * @param width + * @param height + * @param strideInBytes stride in byte-size, i.e. byte count from one line to the next. + * If zero, stride is set to width * bytes-per-pixel. + * If not zero, value must be >= width * bytes-per-pixel. + * @param stride_bytes stride in byte-size, i.e. byte count from one line to the next. + * Must be >= {@link PixelFormat#bytesPerPixel() src_fmt.bytesPerPixel()} * width. + * @throws IllegalArgumentException if strideInBytes is invalid + */ + public static void convert32(PixelSink32 dest32, + final ByteBuffer src_bb, final PixelFormat src_fmt, final boolean src_glOriented, final int width, final int height, int stride_bytes) { + final int src_bpp = src_fmt.bytesPerPixel(); + if( 0 != stride_bytes ) { + if( stride_bytes < src_bpp * width ) { + throw new IllegalArgumentException("Invalid stride "+stride_bytes+", must be greater than bytesPerPixel "+src_bpp+" * width "+width); + } + } else { + stride_bytes = src_bpp * width; + } + final PixelFormat dest_fmt = dest32.getPixelformat(); + final boolean vert_flip = src_glOriented != dest32.isGLOriented(); + final boolean fast_copy = src_fmt == dest_fmt && dest_fmt.bytesPerPixel() == 4 ; + // System.err.println("XXX: SRC fmt "+src_fmt+", stride "+stride_bytes+", isGL "+src_glOriented+", "+width+"x"+height); + // System.err.println("XXX: DST fmt "+dest_fmt+", fast_copy "+fast_copy); + + if( fast_copy ) { + // Fast copy + for(int y=0; y + * The {@link #getPixels()} are assumed to be immutable. + *

                            + */ +public interface PixelRectangle { + /** + *

                            + * Computes a hash code over: + *

                              + *
                            • pixelformat
                            • + *
                            • size
                            • + *
                            • stride
                            • + *
                            • isGLOriented
                            • + *
                            • pixels
                            • + *
                            + *

                            + *

                            + * The hashCode shall be computed only once with first call + * and stored for later retrieval to enhance performance. + *

                            + *

                            + * {@inheritDoc} + *

                            + */ + @Override + int hashCode(); + + /** Returns the {@link PixelFormat}. */ + PixelFormat getPixelformat(); + + /** Returns the size, i.e. width and height. */ + DimensionImmutable getSize(); + + /** + * Returns stride in byte-size, i.e. byte count from one line to the next. + *

                            + * Must be >= {@link #getPixelformat()}.{@link PixelFormat#bytesPerPixel() bytesPerPixel()} * {@link #getSize()}.{@link DimensionImmutable#getWidth() getWidth()}. + *

                            + */ + int getStride(); + + /** + * Returns true if the memory is laid out in + * OpenGL's coordinate system, origin at bottom left. + * Otherwise returns false, i.e. origin at top left. + */ + public boolean isGLOriented(); + + /** Returns the pixels. */ + ByteBuffer getPixels(); + + @Override + String toString(); + + /** + * Generic PixelRectangle implementation + */ + public static class GenericPixelRect implements PixelRectangle { + protected final PixelFormat pixelformat; + protected final DimensionImmutable size; + protected final int strideInBytes; + protected final boolean isGLOriented; + protected final ByteBuffer pixels; + private int hashCode = 0; + private volatile boolean hashCodeComputed = false; + + /** + * + * @param pixelformat + * @param size + * @param strideInBytes stride in byte-size, i.e. byte count from one line to the next. + * If not zero, value must be >= width * bytes-per-pixel. + * If zero, stride is set to width * bytes-per-pixel. + * @param isGLOriented + * @param pixels + * @throws IllegalArgumentException if strideInBytes is invalid. + * @throws IndexOutOfBoundsException if pixels has insufficient bytes left + */ + public GenericPixelRect(final PixelFormat pixelformat, final DimensionImmutable size, int strideInBytes, final boolean isGLOriented, final ByteBuffer pixels) + throws IllegalArgumentException, IndexOutOfBoundsException + { + if( 0 != strideInBytes ) { + if( strideInBytes < pixelformat.bytesPerPixel() * size.getWidth()) { + throw new IllegalArgumentException("Invalid stride "+strideInBytes+", must be greater than bytesPerPixel "+pixelformat.bytesPerPixel()+" * width "+size.getWidth()); + } + } else { + strideInBytes = pixelformat.bytesPerPixel() * size.getWidth(); + } + final int reqBytes = strideInBytes * size.getHeight(); + if( pixels.limit() < reqBytes ) { + throw new IndexOutOfBoundsException("Dest buffer has insufficient bytes left, needs "+reqBytes+": "+pixels); + } + this.pixelformat = pixelformat; + this.size = size; + this.strideInBytes = strideInBytes; + this.isGLOriented = isGLOriented; + this.pixels = pixels; + } + + /** + * Copy ctor validating src. + * @param src + * @throws IllegalArgumentException if strideInBytes is invalid. + * @throws IndexOutOfBoundsException if pixels has insufficient bytes left + */ + public GenericPixelRect(final PixelRectangle src) + throws IllegalArgumentException, IndexOutOfBoundsException + { + this(src.getPixelformat(), src.getSize(), src.getStride(), src.isGLOriented(), src.getPixels()); + } + + @Override + public int hashCode() { + if( !hashCodeComputed ) { // DBL CHECKED OK VOLATILE + synchronized (this) { + if( !hashCodeComputed ) { + // 31 * x == (x << 5) - x + int hash = 31 + pixelformat.hashCode(); + hash = ((hash << 5) - hash) + size.hashCode(); + hash = ((hash << 5) - hash) + strideInBytes; + hash = ((hash << 5) - hash) + ( isGLOriented ? 1 : 0); + hashCode = ((hash << 5) - hash) + pixels.hashCode(); + } + } + } + return hashCode; + } + + @Override + public PixelFormat getPixelformat() { + return pixelformat; + } + + @Override + public DimensionImmutable getSize() { + return size; + } + + @Override + public int getStride() { + return strideInBytes; + } + + @Override + public boolean isGLOriented() { + return isGLOriented; + } + + @Override + public ByteBuffer getPixels() { + return pixels; + } + + @Override + public final String toString() { + return "PixelRect[obj 0x"+Integer.toHexString(super.hashCode())+", "+pixelformat+", "+size+", stride "+strideInBytes+", isGLOrient "+isGLOriented+", pixels "+pixels+"]"; + } + } +} + diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPixelFormatUtil00NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPixelFormatUtil00NEWT.java new file mode 100644 index 000000000..bfcf9c2d7 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPixelFormatUtil00NEWT.java @@ -0,0 +1,364 @@ +/** + * Copyright 2014 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.test.junit.jogl.util.texture; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.PixelFormat; +import javax.media.nativewindow.util.PixelFormatUtil; +import javax.media.nativewindow.util.PixelRectangle; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.FixMethodOrder; +import org.junit.runners.MethodSorters; + +import com.jogamp.opengl.test.junit.util.UITestCase; + +/** + * Testing PixelFormatUtil's Conversion using synthetic test data + * including strides, endian-order and all PixelFormat conversions. + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestPixelFormatUtil00NEWT extends UITestCase { + @Test + public void testConversion01_srcS000_BE_TL_destS000_TL() throws InterruptedException, IOException, MalformedURLException { + testPNG00Impl(0 /* srcMinStrideInBytes */, ByteOrder.BIG_ENDIAN, false /* srcIsGLOriented */, + 0 /* destMinStrideInBytes */, false /* destIsGLOriented */); + } + @Test + public void testConversion02_srcS000_LE_TL_destS000_TL() throws InterruptedException, IOException, MalformedURLException { + testPNG00Impl(0 /* srcMinStrideInBytes */, ByteOrder.LITTLE_ENDIAN, false /* srcIsGLOriented */, + 0 /* destMinStrideInBytes */, false /* destIsGLOriented */); + } + @Test + public void testConversion03_srcS000_BE_TL_destS259_TL() throws InterruptedException, IOException, MalformedURLException { + testPNG00Impl(0 /* srcMinStrideInBytes */, ByteOrder.BIG_ENDIAN, false /* srcIsGLOriented */, + 259 /* destMinStrideInBytes */, false /* destIsGLOriented */); + } + @Test + public void testConversion04_srcS259_BE_TL_destS259_TL() throws InterruptedException, IOException, MalformedURLException { + testPNG00Impl(259 /* srcMinStrideInBytes */, ByteOrder.BIG_ENDIAN, false /* srcIsGLOriented */, + 259 /* destMinStrideInBytes */, false /* destIsGLOriented */); + } + @Test + public void testConversion05_srcS301_BE_TL_destS259_TL() throws InterruptedException, IOException, MalformedURLException { + testPNG00Impl(301 /* srcMinStrideInBytes */, ByteOrder.BIG_ENDIAN, false /* srcIsGLOriented */, + 259 /* destMinStrideInBytes */, false /* destIsGLOriented */); + } + + static final byte red___val = (byte)0x01; + static final byte green_val = (byte)0x02; + static final byte blue__val = (byte)0x03; + static final byte alpha_val = (byte)0x04; + static final byte undef_val = (byte)0xff; + + static final void getComponents(final int srcComps, final PixelFormat fmt, final byte[] components) { + final byte b1, b2, b3, b4; + if( 1 == srcComps ) { + // LUM -> Fmt Conversion + switch(fmt) { + case LUMINANCE: + b1 = red___val; + b2 = undef_val; + b3 = undef_val; + b4 = undef_val; + break; + case RGB888: + b1 = red___val; + b2 = red___val; + b3 = red___val; + b4 = undef_val; + break; + case BGR888: + b1 = red___val; + b2 = red___val; + b3 = red___val; + b4 = undef_val; + break; + case RGBA8888: + b1 = red___val; + b2 = red___val; + b3 = red___val; + b4 = undef_val; + break; + case ABGR8888: + b1 = undef_val; + b2 = red___val; + b3 = red___val; + b4 = red___val; + break; + case BGRA8888: + b1 = red___val; + b2 = red___val; + b3 = red___val; + b4 = undef_val; + break; + case ARGB8888: + b1 = undef_val; + b2 = red___val; + b3 = red___val; + b4 = red___val; + break; + default: + throw new InternalError("Unhandled format "+fmt); + } + } else { + // 1:1 values + switch(fmt) { + case LUMINANCE: + if( srcComps > 1 ) { + b1 = ( red___val + green_val+ blue__val ) / 3; + b2 = undef_val; + b3 = undef_val; + b4 = undef_val; + } else { + b1 = red___val; + b2 = undef_val; + b3 = undef_val; + b4 = undef_val; + } + break; + case RGB888: + b1 = red___val; + b2 = green_val; + b3 = blue__val; + b4 = undef_val; + break; + case BGR888: + b1 = blue__val; + b2 = green_val; + b3 = red___val; + b4 = undef_val; + break; + case RGBA8888: + b1 = red___val; + b2 = green_val; + b3 = blue__val; + b4 = srcComps > 3 ? alpha_val : undef_val; + break; + case ABGR8888: + b1 = srcComps > 3 ? alpha_val : undef_val; + b2 = blue__val; + b3 = green_val; + b4 = red___val; + break; + case BGRA8888: + b1 = blue__val; + b2 = green_val; + b3 = red___val; + b4 = srcComps > 3 ? alpha_val : undef_val; + break; + case ARGB8888: + b1 = srcComps > 3 ? alpha_val : undef_val; + b2 = red___val; + b3 = green_val; + b4 = blue__val; + break; + default: + throw new InternalError("Unhandled format "+fmt); + } + } + components[0] = b1; + components[1] = b2; + components[2] = b3; + components[3] = b4; + } + private void testPNG00Impl(final int srcMinStrideInBytes, final ByteOrder srcByteOrder, final boolean srcIsGLOriented, + final int destMinStrideInBytes, final boolean destIsGLOriented) + throws InterruptedException, IOException, MalformedURLException + { + System.err.println("Test00: srcMinStrideInBytes "+srcMinStrideInBytes+", srcByteOrder "+srcByteOrder+", srcIsGLOriented "+srcIsGLOriented+ + ", destMinStrideInBytes "+destMinStrideInBytes+", destIsGLOriented "+destIsGLOriented); + + final PixelFormat[] formats = PixelFormat.values(); + final int width = 64, height = 64; + + for(int i=0; i "+destFmt); + + final int destStrideBytes = Math.max(destMinStrideInBytes, width*destFmt.bytesPerPixel()); + final byte[] destComponents = new byte[4]; + getComponents(srcFmt.componentCount, destFmt, destComponents); + final PixelRectangle imageConv1 = PixelFormatUtil.convert32(imageSrc, destFmt, destStrideBytes, destIsGLOriented, false /* nio */); + System.err.println("CONVERT["+i+"]["+j+"]: Conv1: "+imageConv1); + testComponents(imageConv1, 0, 0, destComponents); + testComponents(imageConv1, width-1, height-1, destComponents); + if( PixelFormat.LUMINANCE != srcFmt && PixelFormat.LUMINANCE == destFmt ) { + // Cannot convert: RGB* -> LUM -> RGB* + System.err.println("CONVERT["+i+"]["+j+"]: Conv2: Dropped due to RGB* -> LUM"); + } else if( srcFmt.componentCount > destFmt.componentCount ) { + // Cannot convert back if: src.componentCount > dest.componentCount + System.err.println("CONVERT["+i+"]["+j+"]: Conv2: Dropped due to src.componentCount > dest.componentCount"); + } else { + final PixelRectangle imageConv2 = PixelFormatUtil.convert32(imageConv1, imageSrc.getPixelformat(), imageSrc.getStride(), imageSrc.isGLOriented(), false /* nio */); + System.err.println("CONVERT["+i+"]["+j+"]: Conv2: "+imageConv2); + testComponents(imageConv2, 0, 0, srcComponents); + testComponents(imageConv2, width-1, height-1, srcComponents); + if( imageSrc.getStride() == imageConv1.getStride() ) { + Assert.assertEquals(imageSrc.getPixels(), imageConv2.getPixels()); + } + } + } + } + } + private void dumpComponents(PixelRectangle image, int x1, int y1, int w, int h) { + if( x1 + w >= image.getSize().getWidth() ) { + x1 = image.getSize().getWidth() - w; + } + if( y1 + h >= image.getSize().getHeight() ) { + y1 = image.getSize().getHeight() - h; + } + System.err.print("PixelsBytes "+x1+"/"+y1+" "+w+"x"+h+":"); + final ByteBuffer bb = image.getPixels(); + final int bpp = image.getPixelformat().bytesPerPixel(); + for(int y = y1; y< y1+h; y++) { + System.err.printf("%n[%3d][%3d] ", x1, y); + int o = y * image.getStride()+x1*bpp; + for(int x = x1; x< x1+w; x++) { + switch(bpp) { + case 1: { + final byte a = bb.get(o++); + System.err.printf(" 0x%02X", a); + } + break; + case 2: { + final byte a = bb.get(o++), b = bb.get(o++); + System.err.printf(" 0x%02X%02X", b, a); + } + break; + case 3: { + final byte a = bb.get(o++), b = bb.get(o++), c = bb.get(o++); + System.err.printf(" 0x%02X%02X%02X", c, b, a); + } + break; + case 4: { + final byte a = bb.get(o++), b = bb.get(o++), c = bb.get(o++), d = bb.get(o++); + System.err.printf(" 0x%02X%02X%02X%02X", d, c, b, a); + } + break; + } + } + } + System.err.println(); + } + private void testComponents(PixelRectangle image, int x, int y, byte[] components) { + dumpComponents(image, x, y, 3, 3); + final ByteBuffer bb = image.getPixels(); + final int bpp = image.getPixelformat().bytesPerPixel(); + int o = y * image.getStride()+x*bpp; + switch(bpp) { + case 1: { + final byte c1 = bb.get(o++); + final boolean equal = c1==components[0]; + System.err.printf("Test [%3d][%3d] exp 0x%02X == has 0x%02X : %b%n", + x, y, components[0], c1, equal ); + Assert.assertEquals(components[0], c1); + } + break; + case 2: { + final byte c1 = bb.get(o++), c2 = bb.get(o++); + final boolean equal = c1==components[0] && c2==components[1]; + System.err.printf("Test [%3d][%3d] exp 0x%02X%02X == has 0x%02X%02X : %b%n", + x, components[1], components[0], c2, c1, equal ); + Assert.assertEquals(components[0], c1); + Assert.assertEquals(components[1], c2); + } + break; + case 3: { + final byte c1 = bb.get(o++), c2 = bb.get(o++), c3 = bb.get(o++); + final boolean equal = c1==components[0] && c2==components[1] && c3==components[2]; + System.err.printf("Test [%3d][%3d] exp 0x%02X%02X%02X == has 0x%02X%02X%02X : %b%n", + x, y, components[2], components[1], components[0], c3, c2, c1, equal ); + Assert.assertEquals(components[0], c1); + Assert.assertEquals(components[1], c2); + Assert.assertEquals(components[2], c3); + } + break; + case 4: { + final byte c1 = bb.get(o++), c2 = bb.get(o++), c3 = bb.get(o++), c4 = bb.get(o++); + final boolean equal = c1==components[0] && c2==components[1] && c3==components[2] && c4==components[3]; + System.err.printf("Test [%3d][%3d] exp 0x%02X%02X%02X%02X == has 0x%02X%02X%02X%02X : %b%n", + x, y, components[3], components[2], components[1], components[0], c4, c3, c2, c1, equal ); + Assert.assertEquals(components[0], c1); + Assert.assertEquals(components[1], c2); + Assert.assertEquals(components[2], c3); + Assert.assertEquals(components[3], c4); + } + break; + } + } + + public static void main(String args[]) { + org.junit.runner.JUnitCore.main(TestPixelFormatUtil00NEWT.class.getName()); + } +} -- cgit v1.2.3 From bd98b927b910d9421e63cf0dbc2b746eec019f80 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 8 Jan 2014 21:56:26 +0100 Subject: Bug 935: NEWT PointerIcon: Utilize Toolkit Agnostic PixelFormat and Conversion Utilities (Allowing 'arbitrary' PointerIcon data input) Commit fe28bc125429b38cdcd016746081f4a6d521c6fd added the notion of toolkit agnostic PixelFormat and conversion utilities, utilized and further tested by this patch. +++ - PointerIcon is a PixelRectangle and hence holds the decoded data. This allows on-the-fly conversion if required as well as recreation w/o PNG re-decoding. - Using array-backed PointerIcon data where possible, allowing better performance when converting PixelFormat etc. - NEWT Display adds 'createPointerIcon(final IOUtil.ClassResources pngResource...' method to support agnostic PointerIcon creation. - NEWT Display adds methods to allow users to avoid PixelFormat and Buffer NIO type forced conversion: - PixelFormat getNativePointerIconPixelFormat() - boolean getNativePointerIconForceDirectNIO() +++ PNGImage -> PNGPixelRect Deleted: com.jogamp.opengl.util.texture.spi.PNGImage Added: com.jogamp.opengl.util.PNGPixelRect (We hope nobody was using PNGImage directly since it was a service-plugin for TextureIO) PNGPixelRect is a PixelRectangle PNGPixelRect actually is implemented OpenGL agnostic, however - since our PNGJ support lives under package 'jogamp.opengl.util.pngj' it cannot be moved up (yet). PNGPixelRect now handles all PixelFormat for the target format and also added support for grayscale+alpha (2 channels). The latter is force-converted to RGB* - similar to paletted. Further more, PNGPixelRect allows simply passing an OutputStream to write the PNG data. Used by: TextureIO and NEWT +++ - OffscreenSurfaceLayer's setCursor(..) uses the agnostic PixelRectangle instead of a PNG resource. - AWTMisc uses the PixelRectangle to produce the AWT Cursor and converts it to the required format. Hence same pixels are used for NEWT and AWT pointer/cursor icon. - TestGearsES2Newt and NewtAWTReparentingKeyAdapter 'tests' iterate over 3 custom PointerIcon when pressed 'c'. - JOGLNewtAppletBase uses the new custom PointerIcon 'newt/data/crosshair-lumina-trans-32x32.png', which is included in NEWT (213 bytes only). - --- .../assets-test/crosshair-lumina-trans-64x64.png | Bin 0 -> 424 bytes .../newt/data/crosshair-lumina-trans-32x32.png | Bin 0 -> 213 bytes make/scripts/tests.sh | 9 +- .../com/jogamp/opengl/util/PNGPixelRect.java | 335 +++++++++++++++++++++ .../com/jogamp/opengl/util/texture/TextureIO.java | 63 ++-- .../jogamp/opengl/util/texture/spi/PNGImage.java | 319 -------------------- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 17 +- .../media/nativewindow/OffscreenLayerSurface.java | 10 +- .../classes/jogamp/nativewindow/awt/AWTMisc.java | 48 ++- src/newt/classes/com/jogamp/newt/Display.java | 119 ++++++-- .../jogamp/newt/awt/applet/JOGLNewtAppletBase.java | 4 +- src/newt/classes/jogamp/newt/DisplayImpl.java | 156 +++++++++- src/newt/classes/jogamp/newt/PointerIconImpl.java | 63 +++- src/newt/classes/jogamp/newt/WindowImpl.java | 8 +- src/newt/classes/jogamp/newt/driver/PNGIcon.java | 35 +-- .../jogamp/newt/driver/macosx/DisplayDriver.java | 58 ++-- .../jogamp/newt/driver/opengl/JoglUtilPNGIcon.java | 92 ++---- .../jogamp/newt/driver/windows/DisplayDriver.java | 50 ++- .../jogamp/newt/driver/x11/DisplayDriver.java | 38 +-- .../jogamp/newt/driver/x11/WindowDriver.java | 20 +- src/newt/native/MacWindow.m | 32 +- src/newt/native/WindowsWindow.c | 16 +- src/newt/native/X11Display.c | 15 +- src/newt/native/X11Window.c | 20 +- .../jogl/demos/es2/newt/TestGearsES2NEWT.java | 59 +++- .../test/junit/jogl/util/texture/PNGTstFiles.java | 54 ++++ .../jogl/util/texture/TestPNGImage00NEWT.java | 92 ------ .../jogl/util/texture/TestPNGImage01NEWT.java | 182 ----------- .../jogl/util/texture/TestPNGPixelRect00NEWT.java | 224 ++++++++++++++ .../jogl/util/texture/TestPNGPixelRect01NEWT.java | 198 ++++++++++++ .../util/texture/TestPixelFormatUtil01NEWT.java | 105 +++++++ .../util/texture/crosshair-lumina-trans-32x32.png | Bin 0 -> 213 bytes .../util/texture/crosshair-lumina-trans-64x64.png | Bin 0 -> 424 bytes .../parenting/NewtAWTReparentingKeyAdapter.java | 62 +++- 34 files changed, 1573 insertions(+), 930 deletions(-) create mode 100644 make/resources/assets-test/crosshair-lumina-trans-64x64.png create mode 100644 make/resources/assets/newt/data/crosshair-lumina-trans-32x32.png create mode 100644 src/jogl/classes/com/jogamp/opengl/util/PNGPixelRect.java delete mode 100644 src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/util/texture/PNGTstFiles.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGImage00NEWT.java delete mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGImage01NEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGPixelRect00NEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGPixelRect01NEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPixelFormatUtil01NEWT.java create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/util/texture/crosshair-lumina-trans-32x32.png create mode 100644 src/test/com/jogamp/opengl/test/junit/jogl/util/texture/crosshair-lumina-trans-64x64.png (limited to 'src/nativewindow') diff --git a/make/resources/assets-test/crosshair-lumina-trans-64x64.png b/make/resources/assets-test/crosshair-lumina-trans-64x64.png new file mode 100644 index 000000000..9be285335 Binary files /dev/null and b/make/resources/assets-test/crosshair-lumina-trans-64x64.png differ diff --git a/make/resources/assets/newt/data/crosshair-lumina-trans-32x32.png b/make/resources/assets/newt/data/crosshair-lumina-trans-32x32.png new file mode 100644 index 000000000..92279640b Binary files /dev/null and b/make/resources/assets/newt/data/crosshair-lumina-trans-32x32.png differ diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index db852ce42..55973eb12 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -229,7 +229,7 @@ function jrun() { #D_ARGS="-Djogl.debug.GLContext -Dnewt.debug=all" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.GLJPanel -Djogl.debug.TileRenderer -Djogl.debug.TileRenderer.PNG" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.GLJPanel -Djogl.debug.TileRenderer" - #D_ARGS="-Djogl.debug.PNGImage" + #D_ARGS="-Djogl.debug.PNG -Dnewt.debug.Display.PointerIcon" #D_ARGS="-Djogl.debug.JPEGImage" #D_ARGS="-Djogl.debug.GLDrawable -Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.CapabilitiesChooser" #X_ARGS="-Dsun.java2d.noddraw=True -Dsun.java2d.opengl=True -Dsun.java2d.xrender=false" @@ -634,9 +634,10 @@ testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasA #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestJPEGJoglAWTCompareNewtAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestJPEGJoglAWTBenchmarkNewtAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestJPEGTextureFromFileNEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGImage00NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGImage01NEWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.ToolPNG2CSource $* +#testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGPixelRect00NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGPixelRect01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPixelFormatUtil00NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPixelFormatUtil01NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGTextureFromFileAWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.util.texture.TestPNGTextureFromFileNEWT $* #testawt com.jogamp.opengl.test.junit.jogl.util.texture.TestGLReadBufferUtilTextureIOWrite01AWT $* diff --git a/src/jogl/classes/com/jogamp/opengl/util/PNGPixelRect.java b/src/jogl/classes/com/jogamp/opengl/util/PNGPixelRect.java new file mode 100644 index 000000000..1bbc12f32 --- /dev/null +++ b/src/jogl/classes/com/jogamp/opengl/util/PNGPixelRect.java @@ -0,0 +1,335 @@ +/** + * Copyright 2012 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.util; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; + +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.DimensionImmutable; +import javax.media.nativewindow.util.PixelFormat; +import javax.media.nativewindow.util.PixelRectangle; +import javax.media.nativewindow.util.PixelFormatUtil; + +import jogamp.opengl.Debug; +import jogamp.opengl.util.pngj.ImageInfo; +import jogamp.opengl.util.pngj.ImageLine; +import jogamp.opengl.util.pngj.ImageLineHelper; +import jogamp.opengl.util.pngj.PngReader; +import jogamp.opengl.util.pngj.PngWriter; +import jogamp.opengl.util.pngj.chunks.PngChunkPLTE; +import jogamp.opengl.util.pngj.chunks.PngChunkTRNS; +import jogamp.opengl.util.pngj.chunks.PngChunkTextVar; + +import com.jogamp.common.nio.Buffers; +import com.jogamp.common.util.IOUtil; + +public class PNGPixelRect extends PixelRectangle.GenericPixelRect { + private static final boolean DEBUG = Debug.debug("PNG"); + + /** + * Reads a PNG image from the specified InputStream. + *

                            + * Implicitly converts the image to match the desired: + *

                              + *
                            • {@link PixelFormat}, see {@link #getPixelformat()}
                            • + *
                            • destStrideInBytes, see {@link #getStride()}
                            • + *
                            • destIsGLOriented, see {@link #isGLOriented()}
                            • + *
                            + *

                            + * + * @param in input stream + * @param destFmt desired destination {@link PixelFormat} incl. conversion, maybe null to use source {@link PixelFormat} + * @param destDirectBuffer if true, using a direct NIO buffer, otherwise an array backed buffer + * @param destMinStrideInBytes used if greater than PNG's stride, otherwise using PNG's stride. Stride is width * bytes-per-pixel. + * @param destIsGLOriented + * @return the newly created PNGPixelRect instance + * @throws IOException + */ + public static PNGPixelRect read(final InputStream in, + final PixelFormat ddestFmt, final boolean destDirectBuffer, final int destMinStrideInBytes, + final boolean destIsGLOriented) throws IOException { + final PngReader pngr = new PngReader(new BufferedInputStream(in), null); + final ImageInfo imgInfo = pngr.imgInfo; + final PngChunkPLTE plte = pngr.getMetadata().getPLTE(); + final PngChunkTRNS trns = pngr.getMetadata().getTRNS(); + final boolean indexed = imgInfo.indexed; + final boolean hasAlpha = indexed ? ( trns != null ) : imgInfo.alpha ; + + if(DEBUG) { + System.err.println("PNGPixelRect: "+imgInfo); + } + final int channels = indexed ? ( hasAlpha ? 4 : 3 ) : imgInfo.channels ; + final boolean isGrayAlpha = 2 == channels && imgInfo.greyscale && imgInfo.alpha; + if ( ! ( 1 == channels || 3 == channels || 4 == channels || isGrayAlpha ) ) { + throw new RuntimeException("PNGPixelRect can only handle Lum/RGB/RGBA [1/3/4 channels] or Lum+A (GA) images for now. Channels "+channels + " Paletted: " + indexed); + } + final int bytesPerPixel = indexed ? channels : imgInfo.bytesPixel ; + if ( ! ( 1 == bytesPerPixel || 3 == bytesPerPixel || 4 == bytesPerPixel || isGrayAlpha ) ) { + throw new RuntimeException("PNGPixelRect can only handle Lum/RGB/RGBA [1/3/4 bpp] images for now. BytesPerPixel "+bytesPerPixel); + } + if( channels != bytesPerPixel ) { + throw new RuntimeException("PNGPixelRect currently only handles Channels [1/3/4] == BytePerPixel [1/3/4], channels: "+channels+", bytesPerPixel "+bytesPerPixel); + } + final int width = imgInfo.cols; + final int height = imgInfo.rows; + final double dpiX, dpiY; + { + final double[] dpi = pngr.getMetadata().getDpi(); + dpiX = dpi[0]; + dpiY = dpi[1]; + } + final PixelFormat srcFmt; + if ( indexed ) { + if ( hasAlpha ) { + srcFmt = PixelFormat.RGBA8888; + } else { + srcFmt = PixelFormat.RGB888; + } + } else { + switch( channels ) { + case 1: srcFmt = PixelFormat.LUMINANCE; break; + case 2: srcFmt = isGrayAlpha ? PixelFormat.LUMINANCE : null; break; + case 3: srcFmt = PixelFormat.RGB888; break; + case 4: srcFmt = PixelFormat.RGBA8888; break; + default: srcFmt = null; + } + if( null == srcFmt ) { + throw new InternalError("XXX: channels: "+channels+", bytesPerPixel "+bytesPerPixel); + } + } + final PixelFormat destFmt; + if( null == ddestFmt ) { + if( isGrayAlpha ) { + destFmt = PixelFormat.BGRA8888; // save alpha value on gray-alpha + } else { + destFmt = srcFmt; // 1:1 + } + } else { + destFmt = ddestFmt; // user choice + } + final int destStrideInBytes = Math.max(destMinStrideInBytes, destFmt.bytesPerPixel() * width); + final ByteBuffer destPixels = destDirectBuffer ? Buffers.newDirectByteBuffer(destStrideInBytes * height) : + ByteBuffer.allocate(destStrideInBytes * height); + { + final int reqBytes = destStrideInBytes * height; + if( destPixels.limit() < reqBytes ) { + throw new IndexOutOfBoundsException("Dest buffer has insufficient bytes left, needs "+reqBytes+": "+destPixels); + } + } + final boolean vert_flip = destIsGLOriented; + + int[] rgbaScanline = indexed ? new int[width * channels] : null; + if(DEBUG) { + System.err.println("PNGPixelRect: indexed "+indexed+", alpha "+hasAlpha+", grayscale "+imgInfo.greyscale+", channels "+channels+"/"+imgInfo.channels+ + ", bytesPerPixel "+bytesPerPixel+"/"+imgInfo.bytesPixel+ + ", grayAlpha "+isGrayAlpha+", pixels "+width+"x"+height+", dpi "+dpiX+"x"+dpiY+", format "+srcFmt); + System.err.println("PNGPixelRect: destFormat "+destFmt+" ("+ddestFmt+", bytesPerPixel "+destFmt.bytesPerPixel()+", fast-path "+(destFmt==srcFmt)+"), destDirectBuffer "+destDirectBuffer+", destIsGLOriented (flip) "+destIsGLOriented); + System.err.println("PNGPixelRect: destStrideInBytes "+destStrideInBytes+" (destMinStrideInBytes "+destMinStrideInBytes+")"); + } + + for (int row = 0; row < height; row++) { + final ImageLine l1 = pngr.readRow(row); + int lineOff = 0; + int dataOff = vert_flip ? ( height - 1 - row ) * destStrideInBytes : row * destStrideInBytes; + if( indexed ) { + for (int j = width - 1; j >= 0; j--) { + rgbaScanline = ImageLineHelper.palette2rgb(l1, plte, trns, rgbaScanline); // reuse rgbaScanline and update if resized + dataOff = getPixelRGBA8ToAny(destFmt, destPixels, dataOff, rgbaScanline, lineOff, hasAlpha); + lineOff += bytesPerPixel; + } + } else if( 1 == channels ) { + for (int j = width - 1; j >= 0; j--) { + dataOff = getPixelLUMToAny(destFmt, destPixels, dataOff, (byte)l1.scanline[lineOff++], (byte)0xff); // Luminance, 1 bytesPerPixel + } + } else if( isGrayAlpha ) { + for (int j = width - 1; j >= 0; j--) { + dataOff = getPixelLUMToAny(destFmt, destPixels, dataOff, (byte)l1.scanline[lineOff++], (byte)l1.scanline[lineOff++]); // Luminance+Alpha, 2 bytesPerPixel + } + } else if( srcFmt == destFmt ) { // fast-path + for (int j = width - 1; j >= 0; j--) { + dataOff = getPixelRGBSame(destPixels, dataOff, l1.scanline, lineOff, bytesPerPixel); + lineOff += bytesPerPixel; + } + } else { + for (int j = width - 1; j >= 0; j--) { + dataOff = getPixelRGBA8ToAny(destFmt, destPixels, dataOff, l1.scanline, lineOff, hasAlpha); + lineOff += bytesPerPixel; + } + } + } + pngr.end(); + + return new PNGPixelRect(destFmt, new Dimension(width, height), destStrideInBytes, destIsGLOriented, destPixels, dpiX, dpiY); + } + + private static final int getPixelLUMToAny(PixelFormat dest_fmt, ByteBuffer d, int dOff, byte lum, byte alpha) { + switch(dest_fmt) { + case LUMINANCE: + d.put(dOff++, lum); + break; + case BGR888: + case RGB888: + d.put(dOff++, lum); + d.put(dOff++, lum); + d.put(dOff++, lum); + break; + case ABGR8888: + case ARGB8888: + d.put(dOff++, alpha); // A + d.put(dOff++, lum); + d.put(dOff++, lum); + d.put(dOff++, lum); + break; + case BGRA8888: + case RGBA8888: + d.put(dOff++, lum); + d.put(dOff++, lum); + d.put(dOff++, lum); + d.put(dOff++, alpha); // A + break; + default: + throw new InternalError("Unhandled format "+dest_fmt); + } + return dOff; + } + private static final int getPixelRGBA8ToAny(final PixelFormat dest_fmt, final ByteBuffer d, int dOff, final int[] scanline, final int lineOff, final boolean srcHasAlpha) { + final int p = PixelFormatUtil.convertToInt32(dest_fmt, (byte)scanline[lineOff], // R + (byte)scanline[lineOff+1], // G + (byte)scanline[lineOff+2], // B + srcHasAlpha ? (byte)scanline[lineOff+3] : (byte)0xff); // A + final int dbpp = dest_fmt.bytesPerPixel(); + d.put(dOff++, (byte) ( p )); // 1 + if( 1 < dbpp ) { + d.put(dOff++, (byte) ( p >>> 8 )); // 2 + d.put(dOff++, (byte) ( p >>> 16 )); // 3 + if( 4 == dbpp ) { + d.put(dOff++, (byte) ( p >>> 24 )); // 4 + } + } + return dOff; + } + private static final int getPixelRGBSame(final ByteBuffer d, int dOff, final int[] scanline, final int lineOff, final int bpp) { + d.put(dOff++, (byte)scanline[lineOff]); // R + if( 1 < bpp ) { + d.put(dOff++, (byte)scanline[lineOff + 1]); // G + d.put(dOff++, (byte)scanline[lineOff + 2]); // B + if( 4 == bpp ) { + d.put(dOff++, (byte)scanline[lineOff + 3]); // A + } + } + return dOff; + } + private int setPixelRGBA8(final ImageLine line, final int lineOff, final ByteBuffer d, final int dOff, final int bytesPerPixel, final boolean hasAlpha) { + final int b = hasAlpha ? 4-1 : 3-1; + if( d.limit() <= dOff + b ) { + throw new IndexOutOfBoundsException("Buffer has unsufficient bytes left, needs ["+dOff+".."+(dOff+b)+"]: "+d); + } + final int p = PixelFormatUtil.convertToInt32(hasAlpha ? PixelFormat.RGBA8888 : PixelFormat.RGB888, pixelformat, d, dOff); + line.scanline[lineOff ] = 0xff & p; // R + line.scanline[lineOff + 1] = 0xff & ( p >>> 8 ); // G + line.scanline[lineOff + 2] = 0xff & ( p >>> 16 ); // B + if(hasAlpha) { + line.scanline[lineOff + 3] = 0xff & ( p >>> 24 ); // A + } + return dOff + pixelformat.bytesPerPixel(); + } + + /** + * Creates a PNGPixelRect from data supplied by the end user. Shares + * data with the passed ByteBuffer. + * + * @param pixelformat + * @param size + * @param strideInBytes + * @param isGLOriented see {@link #isGLOriented()}. + * @param pixels + * @param dpiX + * @param dpiY + */ + public PNGPixelRect(final PixelFormat pixelformat, final DimensionImmutable size, + final int strideInBytes, final boolean isGLOriented, final ByteBuffer pixels, + final double dpiX, final double dpiY) { + super(pixelformat, size, strideInBytes, isGLOriented, pixels); + this.dpi = new double[] { dpiX, dpiY }; + } + public PNGPixelRect(final PixelRectangle src, final double dpiX, final double dpiY) { + super(src); + this.dpi = new double[] { dpiX, dpiY }; + } + private final double[] dpi; + + /** Returns the dpi of the image. */ + public double[] getDpi() { return dpi; } + + public void write(final OutputStream outstream, final boolean closeOutstream) throws IOException { + final int width = size.getWidth(); + final int height = size.getHeight(); + final int bytesPerPixel = pixelformat.bytesPerPixel(); + final ImageInfo imi = new ImageInfo(width, height, 8 /* bitdepth */, + (4 == bytesPerPixel) ? true : false /* alpha */, + (1 == bytesPerPixel) ? true : false /* grayscale */, + false /* indexed */); + + // open image for writing to a output stream + try { + final PngWriter png = new PngWriter(outstream, imi); + // add some optional metadata (chunks) + png.getMetadata().setDpi(dpi[0], dpi[1]); + png.getMetadata().setTimeNow(0); // 0 seconds fron now = now + png.getMetadata().setText(PngChunkTextVar.KEY_Title, "JogAmp PNGPixelRect"); + // png.getMetadata().setText("my key", "my text"); + final boolean hasAlpha = 4 == bytesPerPixel; + + final ImageLine l1 = new ImageLine(imi); + for (int row = 0; row < height; row++) { + int dataOff = isGLOriented ? ( height - 1 - row ) * strideInBytes : row * strideInBytes; + int lineOff = 0; + if(1 == bytesPerPixel) { + for (int j = width - 1; j >= 0; j--) { + l1.scanline[lineOff++] = pixels.get(dataOff++); // // Luminance, 1 bytesPerPixel + } + } else { + for (int j = width - 1; j >= 0; j--) { + dataOff = setPixelRGBA8(l1, lineOff, pixels, dataOff, bytesPerPixel, hasAlpha); + lineOff += bytesPerPixel; + } + } + png.writeRow(l1, row); + } + png.end(); + } finally { + if( closeOutstream ) { + IOUtil.close(outstream, false); + } + } + } +} diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java index 67ab5176d..0cde24db4 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java @@ -41,10 +41,12 @@ package com.jogamp.opengl.util.texture; import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.net.URL; import java.nio.Buffer; import java.nio.ByteBuffer; @@ -52,9 +54,10 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.PixelFormat; import javax.media.opengl.GL; import javax.media.opengl.GL2; -import javax.media.opengl.GL2ES2; import javax.media.opengl.GL2GL3; import javax.media.opengl.GLContext; import javax.media.opengl.GLException; @@ -63,11 +66,11 @@ import javax.media.opengl.GLProfile; import jogamp.opengl.Debug; import com.jogamp.common.util.IOUtil; +import com.jogamp.opengl.util.PNGPixelRect; import com.jogamp.opengl.util.GLPixelBuffer.GLPixelAttributes; import com.jogamp.opengl.util.texture.spi.DDSImage; import com.jogamp.opengl.util.texture.spi.JPEGImage; import com.jogamp.opengl.util.texture.spi.NetPbmTextureWriter; -import com.jogamp.opengl.util.texture.spi.PNGImage; import com.jogamp.opengl.util.texture.spi.SGIImage; import com.jogamp.opengl.util.texture.spi.TGAImage; import com.jogamp.opengl.util.texture.spi.TextureProvider; @@ -1166,27 +1169,29 @@ public class TextureIO { boolean mipmap, String fileSuffix) throws IOException { if (PNG.equals(fileSuffix)) { - PNGImage image = PNGImage.read(/*glp, */ stream); - if (pixelFormat == 0) { - pixelFormat = image.getGLFormat(); - } - if (internalFormat == 0) { + final PNGPixelRect image = PNGPixelRect.read(stream, null, true /* directBuffer */, 0 /* destMinStrideInBytes */, true /* destIsGLOriented */); + final GLPixelAttributes glpa = GLPixelAttributes.convert(image.getPixelformat(), glp); + if ( 0 == pixelFormat ) { + pixelFormat = glpa.format; + } // else FIXME: Actually not supported w/ preset pixelFormat! + if ( 0 == internalFormat ) { + final boolean hasAlpha = 4 == glpa.bytesPerPixel; if(glp.isGL2ES3()) { - internalFormat = (image.getBytesPerPixel()==4)?GL.GL_RGBA8:GL.GL_RGB8; + internalFormat = hasAlpha ? GL.GL_RGBA8 : GL.GL_RGB8; } else { - internalFormat = (image.getBytesPerPixel()==4)?GL.GL_RGBA:GL.GL_RGB; + internalFormat = hasAlpha ? GL.GL_RGBA : GL.GL_RGB; } } return new TextureData(glp, internalFormat, - image.getWidth(), - image.getHeight(), + image.getSize().getWidth(), + image.getSize().getHeight(), 0, pixelFormat, - image.getGLType(), + glpa.type, mipmap, false, false, - image.getData(), + image.getPixels(), null); } @@ -1392,29 +1397,7 @@ public class TextureIO { final int pixelFormat = pixelAttribs.format; final int pixelType = pixelAttribs.type; final int bytesPerPixel = pixelAttribs.bytesPerPixel; - final boolean reversedChannels; - switch(pixelFormat) { - case GL.GL_ALPHA: - case GL.GL_LUMINANCE: - case GL2ES2.GL_RED: - reversedChannels=false; - break; - case GL.GL_RGB: - reversedChannels=false; - break; - case GL.GL_RGBA: - reversedChannels=false; - break; - case GL2.GL_BGR: - reversedChannels=true; - break; - case GL.GL_BGRA: - reversedChannels=true; - break; - default: - reversedChannels=false; - break; - } + final PixelFormat pixFmt = pixelAttribs.getPixelFormat(); if ( ( 1 == bytesPerPixel || 3 == bytesPerPixel || 4 == bytesPerPixel) && ( pixelType == GL.GL_BYTE || pixelType == GL.GL_UNSIGNED_BYTE)) { ByteBuffer buf = (ByteBuffer) data.getBuffer(); @@ -1423,9 +1406,11 @@ public class TextureIO { } buf.rewind(); - PNGImage image = PNGImage.createFromData(data.getWidth(), data.getHeight(), -1f, -1f, - bytesPerPixel, reversedChannels, !data.getMustFlipVertically(), buf); - image.write(file, true); + final PNGPixelRect image = new PNGPixelRect(pixFmt, new Dimension(data.getWidth(), data.getHeight()), + 0 /* stride */, true /* isGLOriented */, buf /* pixels */, + -1f, -1f); + final OutputStream outs = new BufferedOutputStream(IOUtil.getFileOutputStream(file, true /* allowOverwrite */)); + image.write(outs, true /* close */); return true; } throw new IOException("PNG writer doesn't support this pixel format 0x"+Integer.toHexString(pixelFormat)+ diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java deleted file mode 100644 index 71cbbf97e..000000000 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java +++ /dev/null @@ -1,319 +0,0 @@ -/** - * Copyright 2012 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ -package com.jogamp.opengl.util.texture.spi; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; - -import javax.media.opengl.GL; - -import jogamp.opengl.Debug; -import jogamp.opengl.util.pngj.ImageInfo; -import jogamp.opengl.util.pngj.ImageLine; -import jogamp.opengl.util.pngj.ImageLineHelper; -import jogamp.opengl.util.pngj.PngReader; -import jogamp.opengl.util.pngj.PngWriter; -import jogamp.opengl.util.pngj.chunks.PngChunkPLTE; -import jogamp.opengl.util.pngj.chunks.PngChunkTRNS; -import jogamp.opengl.util.pngj.chunks.PngChunkTextVar; - -import com.jogamp.common.nio.Buffers; -import com.jogamp.common.util.IOUtil; - -public class PNGImage { - private static final boolean DEBUG = Debug.debug("PNGImage"); - - /** - * Creates a PNGImage from data supplied by the end user. Shares - * data with the passed ByteBuffer. Assumes the data is already in - * the correct byte order for writing to disk, i.e., LUMINANCE, RGB or RGBA. - * Orientation is bottom-to-top (OpenGL coord. default) - * or top-to-bottom depending on isGLOriented. - * - * @param width - * @param height - * @param dpiX - * @param dpiY - * @param bytesPerPixel - * @param reversedChannels - * @param isGLOriented see {@link #isGLOriented()}. - * @param data - * @return - */ - public static PNGImage createFromData(int width, int height, double dpiX, double dpiY, - int bytesPerPixel, boolean reversedChannels, boolean isGLOriented, ByteBuffer data) { - return new PNGImage(width, height, dpiX, dpiY, bytesPerPixel, reversedChannels, isGLOriented, data); - } - - /** - * Reads a PNG image from the specified InputStream. - *

                            - * Implicitly flip image to GL orientation, see {@link #isGLOriented()}. - *

                            - */ - public static PNGImage read(InputStream in) throws IOException { - return new PNGImage(in); - } - - /** Reverse read and store, implicitly flip image to GL orientation, see {@link #isGLOriented()}. */ - private static final int getPixelRGBA8(ByteBuffer d, int dOff, int[] scanline, int lineOff, boolean hasAlpha) { - final int b = hasAlpha ? 4-1 : 3-1; - if( d.limit() <= dOff || dOff - b < 0 ) { - throw new IndexOutOfBoundsException("Buffer has unsufficient bytes left, needs ["+(dOff-b)+".."+dOff+"]: "+d); - } - if(hasAlpha) { - d.put(dOff--, (byte)scanline[lineOff + 3]); // A - } - d.put(dOff--, (byte)scanline[lineOff + 2]); // B - d.put(dOff--, (byte)scanline[lineOff + 1]); // G - d.put(dOff--, (byte)scanline[lineOff ]); // R - return dOff; - } - - /** Reverse write and store, implicitly flip image from current orientation, see {@link #isGLOriented()}. Handle reversed channels (BGR[A]). */ - private int setPixelRGBA8(ImageLine line, int lineOff, ByteBuffer d, int dOff, boolean hasAlpha) { - final int b = hasAlpha ? 4-1 : 3-1; - if( d.limit() <= dOff + b ) { - throw new IndexOutOfBoundsException("Buffer has unsufficient bytes left, needs ["+dOff+".."+(dOff+b)+"]: "+d); - } - if( reversedChannels ) { - if(hasAlpha) { - line.scanline[lineOff + 3] = d.get(dOff++); // A - } - line.scanline[lineOff + 2] = d.get(dOff++); // R - line.scanline[lineOff + 1] = d.get(dOff++); // G - line.scanline[lineOff ] = d.get(dOff++); // B - } else { - line.scanline[lineOff ] = d.get(dOff++); // R - line.scanline[lineOff + 1] = d.get(dOff++); // G - line.scanline[lineOff + 2] = d.get(dOff++); // B - if(hasAlpha) { - line.scanline[lineOff + 3] = d.get(dOff++); // A - } - } - return isGLOriented ? dOff - bytesPerPixel - bytesPerPixel : dOff; - } - - private PNGImage(int width, int height, double dpiX, double dpiY, int bytesPerPixel, boolean reversedChannels, boolean isGLOriented, ByteBuffer data) { - pixelWidth=width; - pixelHeight=height; - dpi = new double[] { dpiX, dpiY }; - if(4 == bytesPerPixel) { - glFormat = GL.GL_RGBA; - } else if (3 == bytesPerPixel) { - glFormat = GL.GL_RGB; - } else { - throw new InternalError("XXX: bytesPerPixel "+bytesPerPixel); - } - this.bytesPerPixel = bytesPerPixel; - this.reversedChannels = reversedChannels; - this.isGLOriented = isGLOriented; - this.data = data; - } - - private PNGImage(InputStream in) { - final PngReader pngr = new PngReader(new BufferedInputStream(in), null); - final ImageInfo imgInfo = pngr.imgInfo; - final PngChunkPLTE plte = pngr.getMetadata().getPLTE(); - final PngChunkTRNS trns = pngr.getMetadata().getTRNS(); - final boolean indexed = imgInfo.indexed; - final boolean hasAlpha = indexed ? ( trns != null ) : imgInfo.alpha ; - - final int channels = indexed ? ( hasAlpha ? 4 : 3 ) : imgInfo.channels ; - if ( ! ( 1 == channels || 3 == channels || 4 == channels ) ) { - throw new RuntimeException("PNGImage can only handle Lum/RGB/RGBA [1/3/4 channels] images for now. Channels "+channels + " Paletted: " + indexed); - } - - bytesPerPixel = indexed ? channels : imgInfo.bytesPixel ; - if ( ! ( 1 == bytesPerPixel || 3 == bytesPerPixel || 4 == bytesPerPixel ) ) { - throw new RuntimeException("PNGImage can only handle Lum/RGB/RGBA [1/3/4 bpp] images for now. BytesPerPixel "+bytesPerPixel); - } - if( channels != bytesPerPixel ) { - throw new RuntimeException("PNGImage currently only handles Channels [1/3/4] == BytePerPixel [1/3/4], channels: "+channels+", bytesPerPixel "+bytesPerPixel); - } - pixelWidth = imgInfo.cols; - pixelHeight = imgInfo.rows; - dpi = new double[2]; - { - final double[] dpi2 = pngr.getMetadata().getDpi(); - dpi[0]=dpi2[0]; - dpi[1]=dpi2[1]; - } - if ( indexed ) { - if ( hasAlpha ) { - glFormat = GL.GL_RGBA; - } else { - glFormat = GL.GL_RGB; - } - } else { - switch( channels ) { - case 1: glFormat = GL.GL_LUMINANCE; break; - case 3: glFormat = GL.GL_RGB; break; - case 4: glFormat = GL.GL_RGBA; break; - default: throw new InternalError("XXX: channels: "+channels+", bytesPerPixel "+bytesPerPixel); - } - } - if(DEBUG) { - System.err.println("PNGImage: "+imgInfo); - System.err.println("PNGImage: indexed "+indexed+", alpha "+hasAlpha+", channels "+channels+"/"+imgInfo.channels+ - ", bytesPerPixel "+bytesPerPixel+"/"+imgInfo.bytesPixel+ - ", pixels "+pixelWidth+"x"+pixelHeight+", dpi "+dpi[0]+"x"+dpi[1]+", glFormat 0x"+Integer.toHexString(glFormat)); - } - - data = Buffers.newDirectByteBuffer(bytesPerPixel * pixelWidth * pixelHeight); - reversedChannels = false; // RGB[A] - isGLOriented = true; - int dataOff = bytesPerPixel * pixelWidth * pixelHeight - 1; // start at end-of-buffer, reverse store - - int[] rgbaScanline = indexed ? new int[imgInfo.cols * channels] : null; - - for (int row = 0; row < pixelHeight; row++) { - final ImageLine l1 = pngr.readRow(row); - int lineOff = ( pixelWidth - 1 ) * bytesPerPixel ; // start w/ last pixel in line, reverse read (PNG top-left -> OpenGL bottom-left origin) - if( indexed ) { - for (int j = pixelWidth - 1; j >= 0; j--) { - rgbaScanline = ImageLineHelper.palette2rgb(l1, plte, trns, rgbaScanline); // reuse rgbaScanline and update if resized - dataOff = getPixelRGBA8(data, dataOff, rgbaScanline, lineOff, hasAlpha); - lineOff -= bytesPerPixel; - } - } else if( 1 == channels ) { - for (int j = pixelWidth - 1; j >= 0; j--) { - data.put(dataOff--, (byte)l1.scanline[lineOff--]); // Luminance, 1 bytesPerPixel - } - } else { - for (int j = pixelWidth - 1; j >= 0; j--) { - dataOff = getPixelRGBA8(data, dataOff, l1.scanline, lineOff, hasAlpha); - lineOff -= bytesPerPixel; - } - } - } - pngr.end(); - } - private final int pixelWidth, pixelHeight, glFormat, bytesPerPixel; - private final boolean reversedChannels; - private final boolean isGLOriented; - private final double[] dpi; - private final ByteBuffer data; - - /** Returns the width of the image. */ - public int getWidth() { return pixelWidth; } - - /** Returns the height of the image. */ - public int getHeight() { return pixelHeight; } - - /** Returns true if data has the channels reversed to BGR or BGRA, otherwise RGB or RGBA is expected. */ - public boolean getHasReversedChannels() { return reversedChannels; } - - /** - * Returns true if the drawable is rendered in - * OpenGL's coordinate system, origin at bottom left. - * Otherwise returns false, i.e. origin at top left. - *

                            - * Default impl. is true, i.e. OpenGL coordinate system. - *

                            - */ - public boolean isGLOriented() { return isGLOriented; } - - /** Returns the dpi of the image. */ - public double[] getDpi() { return dpi; } - - /** Returns the OpenGL format for this texture; e.g. GL.GL_LUMINANCE, GL.GL_RGB or GL.GL_RGBA. */ - public int getGLFormat() { return glFormat; } - - /** Returns the OpenGL data type: GL.GL_UNSIGNED_BYTE. */ - public int getGLType() { return GL.GL_UNSIGNED_BYTE; } - - /** Returns the bytes per pixel */ - public int getBytesPerPixel() { return bytesPerPixel; } - - /** Returns the raw data for this texture in the correct - (bottom-to-top) order for calls to glTexImage2D. */ - public ByteBuffer getData() { return data; } - - public void write(File out, boolean allowOverwrite) throws IOException { - final ImageInfo imi = new ImageInfo(pixelWidth, pixelHeight, 8, (4 == bytesPerPixel) ? true : false); // 8 bits per channel, no alpha - // open image for writing to a output stream - final OutputStream outs = new BufferedOutputStream(IOUtil.getFileOutputStream(out, allowOverwrite)); - try { - final PngWriter png = new PngWriter(outs, imi); - // add some optional metadata (chunks) - png.getMetadata().setDpi(dpi[0], dpi[1]); - png.getMetadata().setTimeNow(0); // 0 seconds fron now = now - png.getMetadata().setText(PngChunkTextVar.KEY_Title, "JogAmp PNGImage"); - // png.getMetadata().setText("my key", "my text"); - final boolean hasAlpha = 4 == bytesPerPixel; - final ImageLine l1 = new ImageLine(imi); - if( isGLOriented ) { - // start at last pixel at end-of-buffer, reverse read (OpenGL bottom-left -> PNG top-left origin) - int dataOff = ( pixelWidth * bytesPerPixel * ( pixelHeight - 1 ) ) + // full lines - 1 line - ( ( pixelWidth - 1 ) * bytesPerPixel ); // one line - 1 pixel - for (int row = 0; row < pixelHeight; row++) { - int lineOff = ( pixelWidth - 1 ) * bytesPerPixel ; // start w/ last pixel in line, reverse store (OpenGL bottom-left -> PNG top-left origin) - if(1 == bytesPerPixel) { - for (int j = pixelWidth - 1; j >= 0; j--) { - l1.scanline[lineOff--] = data.get(dataOff--); // // Luminance, 1 bytesPerPixel - } - } else { - for (int j = pixelWidth - 1; j >= 0; j--) { - dataOff = setPixelRGBA8(l1, lineOff, data, dataOff, hasAlpha); - lineOff -= bytesPerPixel; - } - } - png.writeRow(l1, row); - } - } else { - int dataOff = 0; // start at first pixel at start-of-buffer, normal read (same origin: top-left) - for (int row = 0; row < pixelHeight; row++) { - int lineOff = 0; // start w/ first pixel in line, normal store (same origin: top-left) - if(1 == bytesPerPixel) { - for (int j = pixelWidth - 1; j >= 0; j--) { - l1.scanline[lineOff++] = data.get(dataOff++); // // Luminance, 1 bytesPerPixel - } - } else { - for (int j = pixelWidth - 1; j >= 0; j--) { - dataOff = setPixelRGBA8(l1, lineOff, data, dataOff, hasAlpha); - lineOff += bytesPerPixel; - } - } - png.writeRow(l1, row); - } - } - png.end(); - } finally { - IOUtil.close(outs, false); - } - } - - @Override - public String toString() { return "PNGImage["+pixelWidth+"x"+pixelHeight+", dpi "+dpi[0]+" x "+dpi[1]+", bytesPerPixel "+bytesPerPixel+", reversedChannels "+reversedChannels+", "+data+"]"; } -} diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index b947505cb..ddf513180 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -38,7 +38,6 @@ package com.jogamp.nativewindow.awt; import com.jogamp.common.os.Platform; -import com.jogamp.common.util.IOUtil; import com.jogamp.common.util.awt.AWTEDTExecutor; import com.jogamp.common.util.locks.LockFactory; import com.jogamp.common.util.locks.RecursiveLock; @@ -53,7 +52,6 @@ import java.awt.event.ComponentListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.applet.Applet; -import java.io.IOException; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; @@ -66,6 +64,7 @@ import javax.media.nativewindow.OffscreenLayerSurface; import javax.media.nativewindow.SurfaceUpdatedListener; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.InsetsImmutable; +import javax.media.nativewindow.util.PixelRectangle; import javax.media.nativewindow.util.Point; import javax.media.nativewindow.util.PointImmutable; import javax.media.nativewindow.util.Rectangle; @@ -433,19 +432,19 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } @Override - public final boolean setCursor(final IOUtil.ClassResources resources, final PointImmutable hotSpot) throws IOException { + public final boolean setCursor(final PixelRectangle pixelrect, final PointImmutable hotSpot) { AWTEDTExecutor.singleton.invoke(false, new Runnable() { public void run() { Cursor c = null; - if( null == resources || null == hotSpot ) { + if( null == pixelrect || null == hotSpot ) { c = Cursor.getDefaultCursor(); } else { final java.awt.Point awtHotspot = new java.awt.Point(hotSpot.getX(), hotSpot.getY()); try { - c = AWTMisc.getCursor(resources, awtHotspot); - } catch (IOException e) { - e.printStackTrace(); - } + c = AWTMisc.getCursor(pixelrect, awtHotspot); + } catch (Exception e) { + e.printStackTrace(); + } } if( null != c ) { component.setCursor(c); @@ -455,7 +454,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } @Override - public boolean hideCursor() { + public final boolean hideCursor() { AWTEDTExecutor.singleton.invoke(false, new Runnable() { public void run() { component.setCursor(AWTMisc.getNullCursor()); diff --git a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java index 81983a7c2..cf8cf89d2 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java +++ b/src/nativewindow/classes/javax/media/nativewindow/OffscreenLayerSurface.java @@ -27,11 +27,9 @@ */ package javax.media.nativewindow; -import java.io.IOException; - +import javax.media.nativewindow.util.PixelRectangle; import javax.media.nativewindow.util.PointImmutable; -import com.jogamp.common.util.IOUtil; import com.jogamp.common.util.locks.RecursiveLock; /** @@ -73,12 +71,12 @@ public interface OffscreenLayerSurface { /** * Optional method setting cursor in the corresponding on-screen surface/window, if exists. * - * @param resources maybe null for default cursor + * @param pixelrect cursor pixels, maybe null for default cursor * @param hotSpot maybe null for default cursor * @return true if successful, i.e. on-screen surface/window w/ cursor capabilities exists. Otherwise false. - * @throws IOException */ - public boolean setCursor(IOUtil.ClassResources resources, PointImmutable hotSpot) throws IOException; + public boolean setCursor(PixelRectangle pixelrect, PointImmutable hotSpot); + /** * Optional method hiding the cursor in the corresponding on-screen surface/window, if exists. * diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java index b690aff4d..069cffeb8 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java +++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java @@ -37,21 +37,19 @@ import java.awt.Component; import java.awt.Container; import java.awt.Frame; import java.awt.image.BufferedImage; -import java.io.IOException; -import java.net.URLConnection; import java.util.HashMap; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JRootPane; import javax.swing.WindowConstants; -import javax.imageio.ImageIO; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.WindowClosingProtocol; +import javax.media.nativewindow.util.PixelRectangle; +import javax.media.nativewindow.util.PixelFormat; +import javax.media.nativewindow.util.PixelFormatUtil; import javax.swing.MenuSelectionManager; -import com.jogamp.common.util.IOUtil; - public class AWTMisc { public static JFrame getJFrame(Component c) { @@ -173,7 +171,7 @@ public class AWTMisc { MenuSelectionManager.defaultManager().clearSelectedPath(); } - static final HashMap cursorMap = new HashMap(); + static final HashMap cursorMap = new HashMap(); static final Cursor nulCursor; static { final Toolkit toolkit = Toolkit.getDefaultToolkit(); @@ -183,21 +181,43 @@ public class AWTMisc { public static synchronized Cursor getNullCursor() { return nulCursor; } - public static synchronized Cursor getCursor(IOUtil.ClassResources resources, Point hotSpot) throws IOException { - final String key = resources.getClass().getName()+":"+resources.resourcePaths[0]; + public static synchronized Cursor getCursor(PixelRectangle pixelrect, Point hotSpot) { + // 31 * x == (x << 5) - x + int hash = 31 + pixelrect.hashCode(); + hash = ((hash << 5) - hash) + hotSpot.hashCode(); + final Integer key = Integer.valueOf(hash); + Cursor cursor = cursorMap.get(key); if( null == cursor ) { - cursor = createAWTCursor(resources, hotSpot); + cursor = createCursor(pixelrect, hotSpot); cursorMap.put(key, cursor); } return cursor; } - private static synchronized Cursor createAWTCursor(IOUtil.ClassResources resources, Point hotSpot) throws IOException { - final URLConnection urlConn = resources.resolve(0); - final BufferedImage img = ImageIO.read(urlConn.getInputStream()); - + private static synchronized Cursor createCursor(PixelRectangle pixelrect, Point hotSpot) { + final int width = pixelrect.getSize().getWidth(); + final int height = pixelrect.getSize().getHeight(); + final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // PixelFormat.BGRA8888 + final PixelFormatUtil.PixelSink32 imgSink = new PixelFormatUtil.PixelSink32() { + public void store(int x, int y, int pixel) { + img.setRGB(x, y, pixel); + } + @Override + public final PixelFormat getPixelformat() { + return PixelFormat.BGRA8888; + } + @Override + public int getStride() { + return width*4; + } + @Override + public final boolean isGLOriented() { + return false; + } + }; + PixelFormatUtil.convert32(imgSink, pixelrect); final Toolkit toolkit = Toolkit.getDefaultToolkit(); - return toolkit.createCustomCursor(img, hotSpot, resources.resourcePaths[0]); + return toolkit.createCustomCursor(img, hotSpot, pixelrect.toString()); } public static WindowClosingProtocol.WindowClosingMode AWT2NWClosingOperation(int awtClosingOperation) { diff --git a/src/newt/classes/com/jogamp/newt/Display.java b/src/newt/classes/com/jogamp/newt/Display.java index 8d1445f80..4b38fcca5 100644 --- a/src/newt/classes/com/jogamp/newt/Display.java +++ b/src/newt/classes/com/jogamp/newt/Display.java @@ -30,14 +30,14 @@ package com.jogamp.newt; import java.io.IOException; import java.lang.ref.WeakReference; -import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.util.DimensionImmutable; +import javax.media.nativewindow.util.PixelRectangle; +import javax.media.nativewindow.util.PixelFormat; import javax.media.nativewindow.util.PointImmutable; import jogamp.newt.Debug; @@ -47,6 +47,7 @@ import com.jogamp.newt.util.EDTUtil; public abstract class Display { public static final boolean DEBUG = Debug.debug("Display"); + protected static final boolean DEBUG_POINTER_ICON = Debug.debug("Display.PointerIcon"); /** return precomputed hashCode from FQN {@link #getFQName()} */ @Override @@ -66,7 +67,9 @@ public abstract class Display { /** * Native PointerIcon handle. *

                            - * Instances can be created via {@link Display}'s {@link Display#createPointerIcon(com.jogamp.common.util.IOUtil.ClassResources, int, int) createPointerIcon(..)}. + * Instances can be created via {@link Display}'s + * {@link Display#createPointerIcon(com.jogamp.common.util.IOUtil.ClassResources, int, int) createPointerIcon(pngResource, ..)} + * or {@link Display#createPointerIcon(PixelRectangle, int, int) createPointerIcon(pixelrect, ..)}. *

                            *

                            * Instance is {@link #destroy()}'ed automatically if it's {@link #getDisplay() associated Display} is destroyed. @@ -75,23 +78,65 @@ public abstract class Display { * Instance can be re-validated after destruction via {@link #validate()}. *

                            *

                            + * {@link PointerIcon} must not be {@link #destroy() destroyed} while in use! + *

                            + *

                            * {@link PointerIcon} may be {@link #destroy() destroyed} manually after use, * i.e. when no {@link Window} {@link Window#setPointerIcon(PointerIcon) uses them} anymore. + * However, this is not required. *

                            *

                            * PointerIcons can be used via {@link Window#setPointerIcon(PointerIcon)}. *

                            */ - public static interface PointerIcon { + public static interface PointerIcon extends PixelRectangle { /** - * @return the associated Display + * Always neatly packed, i.e. width * bytes_per_pixel. + *

                            + * {@inheritDoc} + *

                            */ - Display getDisplay(); + @Override + int getStride(); + + /** + * Always false, i.e. origin is TOP-LEFT. + *

                            + * {@inheritDoc} + *

                            + */ + boolean isGLOriented(); + + /** + * Computes a hash code over: + *
                              + *
                            • display
                            • + *
                            • pixelformat
                            • + *
                            • size
                            • + *
                            • stride
                            • + *
                            • isGLOriented
                            • + *
                            • pixels
                            • + *
                            • hotspot
                            • + *
                            + * Dismissing the native handle! + *

                            + * The hashCode shall be computed only once with first call + * and stored for later retrieval to enhance performance. + *

                            + *

                            + * {@inheritDoc} + *

                            + */ + @Override + int hashCode(); /** - * @return the single {@link IOUtil.ClassResources}. + * @return the associated Display */ - IOUtil.ClassResources getResource(); + Display getDisplay(); + + /** Returns the hotspot. */ + PointImmutable getHotspot(); /** * Returns true if valid, otherwise false. @@ -116,35 +161,69 @@ public abstract class Display { *

                            */ void destroy(); + } - /** Returns the size, i.e. width and height. */ - DimensionImmutable getSize(); + /** + * Returns the native platform's {@link PointerIcon.PixelFormat} for pointer-icon pixel data. + *

                            + * Using this value will avoid conversion within {@link #createPointerIcon(PixelRectangle, int, int)}. + *

                            + */ + public abstract PixelFormat getNativePointerIconPixelFormat(); - /** Returns the hotspot. */ - PointImmutable getHotspot(); + /** + * Returns the native platform's direct NIO buffer requirement pointer-icon pixel data. + *

                            + * Using this value will avoid conversion within {@link #createPointerIcon(PixelRectangle, int, int)}. + *

                            + */ + public abstract boolean getNativePointerIconForceDirectNIO(); - @Override - String toString(); - } + /** + * Returns the newly created {@link PointerIcon} or null if not implemented on platform. + *

                            + * See {@link PointerIcon} for lifecycle semantics. + *

                            + * + * @param pngResource single PNG resource for the {@link PointerIcon}. Only the first entry of {@link IOUtil.ClassResources#resourcePaths} is used. + * @param hotX pointer hotspot x-coord, origin is upper-left corner + * @param hotY pointer hotspot y-coord, origin is upper-left corner + * + * @throws IllegalArgumentException if pngResource is null or invalid + * @throws IllegalStateException if this Display instance is not {@link #isNativeValid() valid yet}. + * @throws IOException if the pngResource could not be {@link IOUtil.ClassResources#resolve(int) resolved} + * or via the PNG parser processing the input stream. + * + * @see PointerIcon + * @see Window#setPointerIcon(PointerIcon) + */ + public abstract PointerIcon createPointerIcon(final IOUtil.ClassResources pngResource, final int hotX, final int hotY) + throws IllegalArgumentException, IllegalStateException, IOException; /** * Returns the newly created {@link PointerIcon} or null if not implemented on platform. *

                            * See {@link PointerIcon} for lifecycle semantics. *

                            + *

                            + * In case {@link #getNativePointerIconPixelFormat()} or {@link #getNativePointerIconForceDirectNIO()} + * is not matched by the given pixelrect, the pixelrect is converted + * into the required {@link PixelFormat} and NIO type. + *

                            * - * @param pngResource single PNG resource, only the first entry of {@link IOUtil.ClassResources#resourcePaths} is used. + * @param pixelrect {@link PixelRectangle} source for the {@link PointerIcon} * @param hotX pointer hotspot x-coord, origin is upper-left corner * @param hotY pointer hotspot y-coord, origin is upper-left corner + * + * @throws IllegalArgumentException if pixelrect is null. * @throws IllegalStateException if this Display instance is not {@link #isNativeValid() valid yet}. - * @throws MalformedURLException - * @throws InterruptedException - * @throws IOException * * @see PointerIcon * @see Window#setPointerIcon(PointerIcon) + * @see #getNativePointerIconPixelFormat() + * @see #getNativePointerIconForceDirectNIO() */ - public abstract PointerIcon createPointerIcon(final IOUtil.ClassResources pngResource, final int hotX, final int hotY) throws IllegalStateException, MalformedURLException, InterruptedException, IOException; + public abstract PointerIcon createPointerIcon(final PixelRectangle pixelrect, final int hotX, final int hotY) throws IllegalArgumentException, IllegalStateException; /** * Manual trigger the native creation, if it is not done yet.
                            diff --git a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java index 7ffbc2e83..472672fd9 100644 --- a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java +++ b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java @@ -235,10 +235,10 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener { glWindow.setVisible(true); glWindow.sendWindowEvent(WindowEvent.EVENT_WINDOW_RESIZED); if( null == pointerIconTest ) { - final IOUtil.ClassResources res = new IOUtil.ClassResources(glWindow.getClass(), new String[] { "newt/data/jogamp-32x32.png" } ); + final IOUtil.ClassResources res = new IOUtil.ClassResources(glWindow.getClass(), new String[] { "newt/data/crosshair-lumina-trans-32x32.png" } ); final Display disp = glWindow.getScreen().getDisplay(); try { - pointerIconTest = disp.createPointerIcon(res, 16, 0); + pointerIconTest = disp.createPointerIcon(res, 16, 16); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/newt/classes/jogamp/newt/DisplayImpl.java b/src/newt/classes/jogamp/newt/DisplayImpl.java index 346c03b15..4c7169ec4 100644 --- a/src/newt/classes/jogamp/newt/DisplayImpl.java +++ b/src/newt/classes/jogamp/newt/DisplayImpl.java @@ -34,7 +34,9 @@ package jogamp.newt; +import com.jogamp.common.nio.Buffers; import com.jogamp.common.util.IOUtil; +import com.jogamp.common.util.ReflectionUtil; import com.jogamp.newt.Display; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.event.NEWTEvent; @@ -43,17 +45,25 @@ import com.jogamp.newt.event.NEWTEventConsumer; import jogamp.newt.event.NEWTEventTask; import com.jogamp.newt.util.EDTUtil; +import com.jogamp.opengl.util.PNGPixelRect; import java.io.IOException; -import java.net.MalformedURLException; +import java.net.URLConnection; +import java.nio.ByteBuffer; import java.util.ArrayList; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowException; import javax.media.nativewindow.NativeWindowFactory; +import javax.media.nativewindow.util.PixelFormatUtil; +import javax.media.nativewindow.util.PixelRectangle; +import javax.media.nativewindow.util.PixelFormat; +import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.util.PointImmutable; public abstract class DisplayImpl extends Display { private static int serialno = 1; + private static final boolean pngUtilAvail; static { NativeWindowFactory.addCustomShutdownHook(true /* head */, new Runnable() { @@ -64,8 +74,14 @@ public abstract class DisplayImpl extends Display { DisplayImpl.shutdownAll(); } }); + + final ClassLoader cl = DisplayImpl.class.getClassLoader(); + pngUtilAvail = ReflectionUtil.isClassAvailable("jogamp.opengl.util.pngj.PngReader", cl) && + ReflectionUtil.isClassAvailable("com.jogamp.opengl.util.PNGPixelRect", cl); } + public static final boolean isPNGUtilAvailable() { return pngUtilAvail; } + final ArrayList pointerIconList = new ArrayList(); /** Executed from EDT! */ @@ -86,13 +102,94 @@ public abstract class DisplayImpl extends Display { } @Override - public final PointerIcon createPointerIcon(final IOUtil.ClassResources pngResource, final int hotX, final int hotY) throws MalformedURLException, InterruptedException, IOException { - return createPointerIcon(false /* isTemp */, pngResource, hotX, hotY); + public PixelFormat getNativePointerIconPixelFormat() { return PixelFormat.BGRA8888; } + @Override + public boolean getNativePointerIconForceDirectNIO() { return false; } + + @Override + public final PointerIcon createPointerIcon(final IOUtil.ClassResources pngResource, final int hotX, final int hotY) + throws IllegalArgumentException, IllegalStateException, IOException + { + if( !isNativeValid() ) { + throw new IllegalStateException("Display.createPointerIcon(1): Display invalid "+this); + } + if( null == pngResource || 0 >= pngResource.resourceCount() ) { + throw new IllegalArgumentException("Null or invalid pngResource "+pngResource); + } + if( !pngUtilAvail ) { + return null; + } + final PointerIconImpl[] res = { null }; + runOnEDTIfAvail(true, new Runnable() { + public void run() { + try { + if( !DisplayImpl.this.isNativeValid() ) { + throw new IllegalStateException("Display.createPointerIcon(2): Display invalid "+DisplayImpl.this); + } + final URLConnection urlConn = pngResource.resolve(0); + if( null == urlConn ) { + throw new IOException("Could not resolve "+pngResource.resourcePaths[0]); + } + final PNGPixelRect image = PNGPixelRect.read(urlConn.getInputStream(), + getNativePointerIconPixelFormat(), + getNativePointerIconForceDirectNIO(), + 0 /* destMinStrideInBytes */, false /* destIsGLOriented */); + final long handle = createPointerIconImplChecked(image.getPixelformat(), image.getSize().getWidth(), image.getSize().getHeight(), + image.getPixels(), hotX, hotY); + final PointImmutable hotspot = new Point(hotX, hotY); + if( DEBUG_POINTER_ICON ) { + System.err.println("createPointerIconPNG.0: "+image+", handle: "+toHexString(handle)+", hot "+hotspot); + } + if( 0 != handle ) { + res[0] = new PointerIconImpl(DisplayImpl.this, image, hotspot, handle); + if( DEBUG_POINTER_ICON ) { + System.err.println("createPointerIconPNG.0: "+res[0]); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } } ); + if( null != res[0] ) { + synchronized(pointerIconList) { + pointerIconList.add(res[0]); + } + } + return res[0]; } - PointerIcon createPointerIcon(final boolean isTemp, final IOUtil.ClassResources pngResource, final int hotX, final int hotY) throws MalformedURLException, InterruptedException, IOException { + + @Override + public final PointerIcon createPointerIcon(final PixelRectangle pixelrect, final int hotX, final int hotY) + throws IllegalArgumentException, IllegalStateException + { if( !isNativeValid() ) { throw new IllegalStateException("Display.createPointerIcon(1): Display invalid "+this); } + if( null == pixelrect ) { + throw new IllegalArgumentException("Null or pixelrect"); + } + final PixelRectangle fpixelrect; + if( getNativePointerIconPixelFormat() != pixelrect.getPixelformat() || pixelrect.isGLOriented() ) { + // conversion ! + fpixelrect = PixelFormatUtil.convert32(pixelrect, getNativePointerIconPixelFormat(), + 0 /* ddestStride */, false /* isGLOriented */, getNativePointerIconForceDirectNIO() ); + if( DEBUG_POINTER_ICON ) { + System.err.println("createPointerIconRES.0: Conversion-FMT "+pixelrect+" -> "+fpixelrect); + } + } else if( getNativePointerIconForceDirectNIO() && !Buffers.isDirect(pixelrect.getPixels()) ) { + // transfer to direct NIO + final ByteBuffer sBB = pixelrect.getPixels(); + final ByteBuffer dBB = Buffers.newDirectByteBuffer(sBB.array(), sBB.arrayOffset()); + fpixelrect = new PixelRectangle.GenericPixelRect(pixelrect.getPixelformat(), pixelrect.getSize(), pixelrect.getStride(), pixelrect.isGLOriented(), dBB); + if( DEBUG_POINTER_ICON ) { + System.err.println("createPointerIconRES.0: Conversion-NIO "+pixelrect+" -> "+fpixelrect); + } + } else { + fpixelrect = pixelrect; + if( DEBUG_POINTER_ICON ) { + System.err.println("createPointerIconRES.0: No conversion "+fpixelrect); + } + } final PointerIconImpl[] res = { null }; runOnEDTIfAvail(true, new Runnable() { public void run() { @@ -100,22 +197,63 @@ public abstract class DisplayImpl extends Display { if( !DisplayImpl.this.isNativeValid() ) { throw new IllegalStateException("Display.createPointerIcon(2): Display invalid "+DisplayImpl.this); } - res[0] = createPointerIconImpl(pngResource, hotX, hotY); + if( null != fpixelrect ) { + final long handle = createPointerIconImplChecked(fpixelrect.getPixelformat(), + fpixelrect.getSize().getWidth(), + fpixelrect.getSize().getHeight(), + fpixelrect.getPixels(), hotX, hotY); + if( 0 != handle ) { + res[0] = new PointerIconImpl(DisplayImpl.this, fpixelrect, new Point(hotX, hotY), handle); + } + } } catch (Exception e) { e.printStackTrace(); } } } ); - if( !isTemp ) { + if( null != res[0] ) { synchronized(pointerIconList) { pointerIconList.add(res[0]); } } return res[0]; } - /** Executed from EDT! */ - protected PointerIconImpl createPointerIconImpl(final IOUtil.ClassResources pngResource, final int hotX, final int hotY) throws MalformedURLException, InterruptedException, IOException { - return null; + + /** + * Executed from EDT! + * + * @param pixelformat the pixels's format + * @param width the pixels's width + * @param height the pixels's height + * @param pixels the pixels + * @param hotX the PointerIcon's hot-spot x-coord + * @param hotY the PointerIcon's hot-spot x-coord + * @return if successful a valid handle (not null), otherwise null. + */ + protected final long createPointerIconImplChecked(PixelFormat pixelformat, int width, int height, final ByteBuffer pixels, final int hotX, final int hotY) { + if( getNativePointerIconPixelFormat() != pixelformat ) { + throw new IllegalArgumentException("Pixelformat no "+getNativePointerIconPixelFormat()+", but "+pixelformat); + } + if( getNativePointerIconForceDirectNIO() && !Buffers.isDirect(pixels) ) { + throw new IllegalArgumentException("pixel buffer is not direct "+pixels); + } + return createPointerIconImpl(pixelformat, width, height, pixels, hotX, hotY); + } + + /** + * Executed from EDT! + * + * @param pixelformat the pixels's format + * @param width the pixels's width + * @param height the pixels's height + * @param pixels the pixels + * @param hotX the PointerIcon's hot-spot x-coord + * @param hotY the PointerIcon's hot-spot x-coord + * @return if successful a valid handle (not null), otherwise null. + */ + protected long createPointerIconImpl(PixelFormat pixelformat, int width, int height, final ByteBuffer pixels, final int hotX, final int hotY) { + return 0; } + /** Executed from EDT! */ protected void destroyPointerIconImpl(final long displayHandle, long piHandle) { } diff --git a/src/newt/classes/jogamp/newt/PointerIconImpl.java b/src/newt/classes/jogamp/newt/PointerIconImpl.java index e2388be67..7c8535f20 100644 --- a/src/newt/classes/jogamp/newt/PointerIconImpl.java +++ b/src/newt/classes/jogamp/newt/PointerIconImpl.java @@ -27,27 +27,63 @@ */ package jogamp.newt; +import java.nio.ByteBuffer; + import javax.media.nativewindow.util.DimensionImmutable; +import javax.media.nativewindow.util.PixelFormat; +import javax.media.nativewindow.util.PixelRectangle; import javax.media.nativewindow.util.PointImmutable; -import com.jogamp.common.util.IOUtil; -import com.jogamp.common.util.IOUtil.ClassResources; import com.jogamp.newt.Display; import com.jogamp.newt.Display.PointerIcon; public class PointerIconImpl implements PointerIcon { private final DisplayImpl display; - private final IOUtil.ClassResources resource; + private final PixelFormat pixelformat; private final DimensionImmutable size; + private final ByteBuffer pixels; private final PointImmutable hotspot; private long handle; - public PointerIconImpl(DisplayImpl display, ClassResources resource, final DimensionImmutable size, final PointImmutable hotspot, final long handle) { + private int hashCode = 0; + private volatile boolean hashCodeComputed = false; + + public PointerIconImpl(final DisplayImpl display, final PixelFormat pixelformat, final DimensionImmutable size, final ByteBuffer pixels, final PointImmutable hotspot, final long handle) { this.display = display; - this.resource = resource; + this.pixelformat = pixelformat; this.size = size; + this.pixels = pixels; this.hotspot = hotspot; + this.handle=handle; } + public PointerIconImpl(final DisplayImpl display, final PixelRectangle pixelrect, final PointImmutable hotspot, final long handle) { + this.display = display; + this.pixelformat = pixelrect.getPixelformat(); + this.size = pixelrect.getSize(); + this.pixels = pixelrect.getPixels(); + this.hotspot = hotspot; + this.handle=handle; + } + + @Override + public int hashCode() { + if( !hashCodeComputed ) { // DBL CHECKED OK VOLATILE + synchronized (this) { + if( !hashCodeComputed ) { + // 31 * x == (x << 5) - x + int hash = 31 + display.getFQName().hashCode(); + hash = ((hash << 5) - hash) + pixelformat.hashCode(); + hash = ((hash << 5) - hash) + size.hashCode(); + hash = ((hash << 5) - hash) + getStride(); + hash = ((hash << 5) - hash) + ( isGLOriented() ? 1 : 0); + hash = ((hash << 5) - hash) + pixels.hashCode(); + hashCode = ((hash << 5) - hash) + hotspot.hashCode(); + } + } + } + return hashCode; + } + public synchronized final long getHandle() { return handle; } public synchronized final long validatedHandle() { synchronized(display.pointerIconList) { @@ -57,8 +93,7 @@ public class PointerIconImpl implements PointerIcon { } if( 0 == handle ) { try { - final PointerIconImpl temp = (PointerIconImpl) display.createPointerIcon(true /* isTemp */, resource, hotspot.getX(), hotspot.getY()); - handle = temp.handle; + handle = display.createPointerIconImpl(pixelformat, size.getWidth(), size.getHeight(), pixels, hotspot.getX(), hotspot.getY()); return handle; } catch (Exception e) { e.printStackTrace(); @@ -71,7 +106,9 @@ public class PointerIconImpl implements PointerIcon { @Override public final Display getDisplay() { return display; } @Override - public final IOUtil.ClassResources getResource() { return resource; } + public final PixelFormat getPixelformat() { return pixelformat; } + @Override + public final ByteBuffer getPixels() { return pixels; } @Override public synchronized final boolean isValid() { return 0 != handle; } @Override @@ -116,11 +153,19 @@ public class PointerIconImpl implements PointerIcon { return size; } @Override + public final int getStride() { + return size.getWidth() * pixelformat.bytesPerPixel(); + } + @Override + public final boolean isGLOriented() { + return false; + } + @Override public final PointImmutable getHotspot() { return hotspot; } @Override public final String toString() { - return "PointerIcon["+DisplayImpl.toHexString(super.hashCode())+", "+display.getFQName()+", "+resource.resourcePaths[0]+", 0x"+Long.toHexString(handle)+", "+size+", "+hotspot+"]"; + return "PointerIcon[obj 0x"+Integer.toHexString(super.hashCode())+", "+display.getFQName()+", 0x"+Long.toHexString(handle)+", "+pixelformat+", "+size+", "+hotspot+", pixels "+pixels+"]"; } } \ No newline at end of file diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index 50f30f04d..dc9affd63 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -53,6 +53,7 @@ import javax.media.nativewindow.WindowClosingProtocol; import javax.media.nativewindow.util.DimensionImmutable; import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.InsetsImmutable; +import javax.media.nativewindow.util.PixelRectangle; import javax.media.nativewindow.util.Point; import javax.media.nativewindow.util.PointImmutable; import javax.media.nativewindow.util.Rectangle; @@ -61,7 +62,6 @@ import javax.media.nativewindow.util.RectangleImmutable; import jogamp.nativewindow.SurfaceUpdatedHelper; import com.jogamp.common.util.ArrayHashSet; -import com.jogamp.common.util.IOUtil; import com.jogamp.common.util.IntBitfield; import com.jogamp.common.util.ReflectionUtil; import com.jogamp.common.util.locks.LockFactory; @@ -1700,7 +1700,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } /** * Helper method to delegate {@link #setPointerVisibleImpl(boolean)} to - * {@link OffscreenLayerSurface#hideCursor()} or {@link OffscreenLayerSurface#setCursor(IOUtil.ClassResources, PointImmutable)}. + * {@link OffscreenLayerSurface#hideCursor()} or {@link OffscreenLayerSurface#setCursor(PixelRectangle, PointImmutable)}. *

                            * Note: JAWTWindow is an OffscreenLayerSurface. *

                            @@ -1755,7 +1755,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer } /** * Helper method to delegate {@link #setPointerIconIntern(PointerIconImpl)} to - * {@link OffscreenLayerSurface#setCursor(IOUtil.ClassResources, PointImmutable)}. + * {@link OffscreenLayerSurface#setCursor(PixelRectangle, PointImmutable)} *

                            * Note: JAWTWindow is an OffscreenLayerSurface. *

                            @@ -1777,7 +1777,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer final OffscreenLayerSurface ols = (OffscreenLayerSurface) parent; try { if( null != pi ) { - return ols.setCursor(pi.getResource(), pi.getHotspot()); + return ols.setCursor(pi, pi.getHotspot()); } else { return ols.setCursor(null, null); // default } diff --git a/src/newt/classes/jogamp/newt/driver/PNGIcon.java b/src/newt/classes/jogamp/newt/driver/PNGIcon.java index ffa62978f..967acd413 100644 --- a/src/newt/classes/jogamp/newt/driver/PNGIcon.java +++ b/src/newt/classes/jogamp/newt/driver/PNGIcon.java @@ -32,6 +32,7 @@ import java.net.MalformedURLException; import java.nio.ByteBuffer; import jogamp.newt.Debug; +import jogamp.newt.DisplayImpl; import com.jogamp.common.util.IOUtil; import com.jogamp.common.util.ReflectionUtil; @@ -45,8 +46,7 @@ public class PNGIcon { Debug.initSingleton(); final ClassLoader cl = PNGIcon.class.getClassLoader(); - avail = ReflectionUtil.isClassAvailable("jogamp.newt.driver.opengl.JoglUtilPNGIcon", cl) && - ReflectionUtil.isClassAvailable("com.jogamp.opengl.util.texture.spi.PNGImage", cl); + avail = DisplayImpl.isPNGUtilAvailable() && ReflectionUtil.isClassAvailable("jogamp.newt.driver.opengl.JoglUtilPNGIcon", cl); } /** Returns true if PNG decoder is available. */ @@ -55,7 +55,11 @@ public class PNGIcon { } /** - * Implemented for X11. + * Special implementation for X11 Window Icons + *

                            + * The returned byte buffer is a direct buffer! + *

                            + * * @param resources * @param data_size * @param elem_bytesize @@ -73,29 +77,4 @@ public class PNGIcon { } throw new UnsupportedOperationException(err0); } - - /** - * Implemented for Windows. - * @param resources - * @param toBGRA if true, arranges stores in BGRA888 order, otherwise RGBA888 - * @param width - * @param height - * @param data_size - * @param resourcesIdx - * @return pixels with origin at upper-left corner. - * If storing RGBA8888, component R is located on the lowest 8-bit. - * If storing BGRA8888, component B is located on the lowest 8-bit. - * Component A is located on the highest 8-bit. - * - * @throws UnsupportedOperationException if not implemented - * @throws InterruptedException - * @throws IOException - * @throws MalformedURLException - */ - public static ByteBuffer singleToRGBAImage(IOUtil.ClassResources resources, int resourceIdx, boolean toBGRA, int[] width, int[] height, int[] data_size) throws UnsupportedOperationException, InterruptedException, IOException, MalformedURLException { - if( avail ) { - return jogamp.newt.driver.opengl.JoglUtilPNGIcon.singleToRGBAImage(resources, resourceIdx, toBGRA, width, height, data_size); - } - throw new UnsupportedOperationException(err0); - } } diff --git a/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java index 30583c48c..d850a18af 100644 --- a/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/macosx/DisplayDriver.java @@ -34,28 +34,25 @@ package jogamp.newt.driver.macosx; -import java.io.IOException; -import java.net.MalformedURLException; +import java.net.URLConnection; import java.nio.Buffer; import java.nio.ByteBuffer; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeWindowException; -import javax.media.nativewindow.util.Dimension; -import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.util.PixelFormat; +import com.jogamp.common.nio.Buffers; import com.jogamp.common.util.IOUtil; import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; import com.jogamp.newt.NewtFactory; +import com.jogamp.opengl.util.PNGPixelRect; import jogamp.newt.DisplayImpl; import jogamp.newt.NEWTJNILibLoader; -import jogamp.newt.PointerIconImpl; -import jogamp.newt.driver.PNGIcon; public class DisplayDriver extends DisplayImpl { - private static final int defaultIconWidth, defaultIconHeight; - private static final Buffer defaultIconData; + private static final PNGPixelRect defaultIconData; static { NEWTJNILibLoader.loadNEWT(); @@ -67,21 +64,23 @@ public class DisplayDriver extends DisplayImpl { throw new NativeWindowException("Failed to initialize jmethodIDs"); } { - final int[] width = { 0 }, height = { 0 }, data_size = { 0 }; - Buffer data=null; - if( PNGIcon.isAvailable() ) { + PNGPixelRect image=null; + if( DisplayImpl.isPNGUtilAvailable() ) { try { + // NOTE: MUST BE DIRECT BUFFER, since NSBitmapImageRep uses buffer directly! final IOUtil.ClassResources iconRes = NewtFactory.getWindowIcons(); - data = PNGIcon.singleToRGBAImage(iconRes, iconRes.resourceCount()-1, false /* toBGRA */, width, height, data_size); + final URLConnection urlConn = iconRes.resolve(iconRes.resourceCount()-1); + image = PNGPixelRect.read(urlConn.getInputStream(), PixelFormat.BGRA8888, true /* directBuffer */, 0 /* destMinStrideInBytes */, false /* destIsGLOriented */); } catch (Exception e) { e.printStackTrace(); } } - defaultIconWidth = width[0]; - defaultIconHeight = height[0]; - defaultIconData = data; + defaultIconData = image; if( null != defaultIconData ) { - DisplayDriver.setAppIcon0(defaultIconData, defaultIconWidth, defaultIconHeight); + final Buffer pixels = defaultIconData.getPixels(); + DisplayDriver.setAppIcon0( + pixels, Buffers.getDirectBufferByteOffset(pixels), true /* pixels_is_direct */, + defaultIconData.getSize().getWidth(), defaultIconData.getSize().getHeight()); } } @@ -112,17 +111,20 @@ public class DisplayDriver extends DisplayImpl { aDevice.close(); } + /** + * {@inheritDoc} + *

                            + * NOTE: MUST BE DIRECT BUFFER, since NSBitmapImageRep uses buffer directly! + *

                            + */ @Override - protected PointerIconImpl createPointerIconImpl(final IOUtil.ClassResources pngResource, final int hotX, final int hotY) throws MalformedURLException, InterruptedException, IOException { - if( PNGIcon.isAvailable() ) { - final int[] width = { 0 }, height = { 0 }, data_size = { 0 }; - if( null != pngResource && 0 < pngResource.resourceCount() ) { - final ByteBuffer data = PNGIcon.singleToRGBAImage(pngResource, 0, true /* toBGRA */, width, height, data_size); - return new PointerIconImpl( this, pngResource, new Dimension(width[0], height[0]), - new Point(hotX, hotY), createPointerIcon0(data, width[0], height[0], hotX, hotY)); - } - } - return null; + public final boolean getNativePointerIconForceDirectNIO() { return true; } + + @Override + protected final long createPointerIconImpl(PixelFormat pixelformat, int width, int height, final ByteBuffer pixels, final int hotX, final int hotY) { + return createPointerIcon0( + pixels, Buffers.getDirectBufferByteOffset(pixels), true /* pixels_is_direct */, + width, height, hotX, hotY); } @Override @@ -140,8 +142,8 @@ public class DisplayDriver extends DisplayImpl { private static native boolean initNSApplication0(); private static native void runNSApplication0(); private static native void stopNSApplication0(); - /* pp */ static native void setAppIcon0(Object iconData, int iconWidth, int iconHeight); - private static native long createPointerIcon0(Object iconData, int iconWidth, int iconHeight, int hotX, int hotY); + /* pp */ static native void setAppIcon0(Object pixels, int pixels_byte_offset, boolean pixels_is_direct, int width, int height); + private static native long createPointerIcon0(Object pixels, int pixels_byte_offset, boolean pixels_is_direct, int width, int height, int hotX, int hotY); private static native long destroyPointerIcon0(long handle); } diff --git a/src/newt/classes/jogamp/newt/driver/opengl/JoglUtilPNGIcon.java b/src/newt/classes/jogamp/newt/driver/opengl/JoglUtilPNGIcon.java index 216a0cb20..551929b8d 100644 --- a/src/newt/classes/jogamp/newt/driver/opengl/JoglUtilPNGIcon.java +++ b/src/newt/classes/jogamp/newt/driver/opengl/JoglUtilPNGIcon.java @@ -32,20 +32,22 @@ import java.net.MalformedURLException; import java.net.URLConnection; import java.nio.ByteBuffer; +import javax.media.nativewindow.util.PixelFormat; + import com.jogamp.common.nio.Buffers; import com.jogamp.common.os.Platform; import com.jogamp.common.util.IOUtil; -import com.jogamp.opengl.util.texture.spi.PNGImage; +import com.jogamp.opengl.util.PNGPixelRect; public class JoglUtilPNGIcon { public static ByteBuffer arrayToX11BGRAImages(IOUtil.ClassResources resources, int[] data_size, int[] elem_bytesize) throws UnsupportedOperationException, InterruptedException, IOException, MalformedURLException { - final PNGImage[] images = new PNGImage[resources.resourceCount()]; + final PNGPixelRect[] images = new PNGPixelRect[resources.resourceCount()]; data_size[0] = 0; for(int i=0; iGetDirectBufferAddress(env, jiconData); +static NSImage * createNSImageFromData(JNIEnv *env, unsigned char * iconData, jint jiconWidth, jint jiconHeight) { + if( NULL != iconData ) { NSInteger iconWidth = (NSInteger) jiconWidth; NSInteger iconHeight = (NSInteger) jiconHeight; const NSInteger bpc = 8 /* bits per component */, spp=4 /* RGBA */, bpp = bpc * spp; @@ -319,28 +318,47 @@ static NSImage * createNSImageFromData(JNIEnv *env, jobject jiconData, jint jico * Method: setAppIcon0 */ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_DisplayDriver_setAppIcon0 - (JNIEnv *env, jobject unused, jobject jiconData, jint jiconWidth, jint jiconHeight) + (JNIEnv *env, jobject unused, jobject pixels, jint pixels_byte_offset, jboolean pixels_is_direct, jint width, jint height) { + if( 0 == pixels ) { + return; + } NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - NSImage * nsImage = createNSImageFromData(env, jiconData, jiconWidth, jiconHeight); + // NOTE: MUST BE DIRECT BUFFER, since NSBitmapImageRep uses buffer directly! + unsigned char * pixelPtr = (unsigned char *) ( JNI_TRUE == pixels_is_direct ? + (*env)->GetDirectBufferAddress(env, pixels) : + (*env)->GetPrimitiveArrayCritical(env, pixels, NULL) ); + NSImage * nsImage = createNSImageFromData(env, pixelPtr + pixels_byte_offset, width, height); if( NULL != nsImage ) { [nsImage autorelease]; [NSApp setApplicationIconImage: nsImage]; } + if ( JNI_FALSE == pixels_is_direct ) { + (*env)->ReleasePrimitiveArrayCritical(env, pixels, (void*)pixelPtr, JNI_ABORT); + } [pool release]; } JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_DisplayDriver_createPointerIcon0 - (JNIEnv *env, jobject unused, jobject jiconData, jint jiconWidth, jint jiconHeight, jint hotX, jint hotY) + (JNIEnv *env, jobject unused, jobject pixels, jint pixels_byte_offset, jboolean pixels_is_direct, jint width, jint height, jint hotX, jint hotY) { + if( 0 == pixels ) { + return 0; + } NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - NSImage * nsImage = createNSImageFromData(env, jiconData, jiconWidth, jiconHeight); + unsigned char * pixelPtr = (unsigned char *) ( JNI_TRUE == pixels_is_direct ? + (*env)->GetDirectBufferAddress(env, pixels) : + (*env)->GetPrimitiveArrayCritical(env, pixels, NULL) ); + NSImage * nsImage = createNSImageFromData(env, pixelPtr + pixels_byte_offset, width, height); NSCursor * res = NULL; if( NULL != nsImage ) { [nsImage autorelease]; NSPoint hotP = { hotX, hotY }; res = [[NSCursor alloc] initWithImage: nsImage hotSpot: hotP]; } + if ( JNI_FALSE == pixels_is_direct ) { + (*env)->ReleasePrimitiveArrayCritical(env, pixels, (void*)pixelPtr, JNI_ABORT); + } [pool release]; DBG_PRINT( "createPointerIcon0 %p\n", res); return (jlong) (intptr_t) res; diff --git a/src/newt/native/WindowsWindow.c b/src/newt/native/WindowsWindow.c index 1fd8d0039..c20e156c1 100644 --- a/src/newt/native/WindowsWindow.c +++ b/src/newt/native/WindowsWindow.c @@ -2368,9 +2368,15 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowDriver_warpPointer0 JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_DisplayDriver_createBGRA8888Icon0(JNIEnv *env, jobject _unused, - jobject data, jint data_offset, jint width, jint height, jboolean isCursor, jint hotX, jint hotY) { + jobject pixels, jint pixels_byte_offset, jboolean pixels_is_direct, jint width, jint height, jboolean isCursor, jint hotX, jint hotY) { - const unsigned char * data_ptr = (const unsigned char *) (*env)->GetDirectBufferAddress(env, data) + data_offset; + if( 0 == pixels ) { + return 0; + } + + const unsigned char * pixelPtr = (const unsigned char *) ( JNI_TRUE == pixels_is_direct ? + (*env)->GetDirectBufferAddress(env, pixels) : + (*env)->GetPrimitiveArrayCritical(env, pixels, NULL) ); const int bytes = 4 * width * height; // BGRA8888 DWORD dwWidth, dwHeight; @@ -2403,10 +2409,14 @@ Java_jogamp_newt_driver_windows_DisplayDriver_createBGRA8888Icon0(JNIEnv *env, j hBitmap = CreateDIBSection(hdc, (BITMAPINFO *)&bi, DIB_RGB_COLORS, (void **)&lpBits, NULL, (DWORD)0); - memcpy(lpBits, data_ptr, bytes); + memcpy(lpBits, pixelPtr + pixels_byte_offset, bytes); ReleaseDC(NULL,hdc); + if ( JNI_FALSE == pixels_is_direct ) { + (*env)->ReleasePrimitiveArrayCritical(env, pixels, (void*)pixelPtr, JNI_ABORT); + } + // Create an empty mask bitmap. HBITMAP hMonoBitmap = CreateBitmap(dwWidth,dwHeight,1,1,NULL); diff --git a/src/newt/native/X11Display.c b/src/newt/native/X11Display.c index 19e733111..b62a9b234 100644 --- a/src/newt/native/X11Display.c +++ b/src/newt/native/X11Display.c @@ -678,13 +678,15 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_DispatchMessage * Signature: (JJILjava/lang/Object;I)V */ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_createPointerIcon0 - (JNIEnv *env, jclass clazz, jlong display, jobject data, jint data_offset, jint width, jint height, jint hotX, jint hotY) + (JNIEnv *env, jclass clazz, jlong display, jobject pixels, jint pixels_byte_offset, jboolean pixels_is_direct, jint width, jint height, jint hotX, jint hotY) { Cursor c; - if( 0 != data ) { + if( 0 != pixels ) { Display * dpy = (Display *) (intptr_t) display; - char * data_ptr = (char *) (*env)->GetDirectBufferAddress(env, data) + data_offset; + const unsigned char * pixelPtr = (const unsigned char *) ( JNI_TRUE == pixels_is_direct ? + (*env)->GetDirectBufferAddress(env, pixels) : + (*env)->GetPrimitiveArrayCritical(env, pixels, NULL) ); XcursorImage ci; ci.version = 1; // XCURSOR_IMAGE_VERSION; ci.size = width; // nominal size (assume square ..) @@ -693,11 +695,14 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_DisplayDriver_createPointerI ci.xhot = hotX; ci.yhot = hotY; ci.delay = 0; - ci.pixels = (XcursorPixel *)(intptr_t)data_ptr; + ci.pixels = (XcursorPixel *)(intptr_t)(pixelPtr + pixels_byte_offset); c = XcursorImageLoadCursor (dpy, &ci); - DBG_PRINT( "X11: createPointerIcon0: %p %dx%d %d/%d -> %p\n", data_ptr, width, height, hotX, hotY, (void *)c); + if ( JNI_FALSE == pixels_is_direct ) { + (*env)->ReleasePrimitiveArrayCritical(env, pixels, (void*)pixelPtr, JNI_ABORT); + } + DBG_PRINT( "X11: createPointerIcon0: %p %dx%d %d/%d -> %p\n", (pixelPtr+pixels_byte_offset), width, height, hotX, hotY, (void *)c); } else { c = 0; diff --git a/src/newt/native/X11Window.c b/src/newt/native/X11Window.c index da2778004..54b85c243 100644 --- a/src/newt/native/X11Window.c +++ b/src/newt/native/X11Window.c @@ -512,7 +512,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CreateWindow0 jint visualID, jlong javaObjectAtom, jlong windowDeleteAtom, jint x, jint y, jint width, jint height, jboolean autoPosition, int flags, - jint iconDataSize, jobject iconData) + jint pixelDataSize, jobject pixels, jint pixels_byte_offset, jboolean pixels_is_direct) { Display * dpy = (Display *)(intptr_t)display; Atom wm_delete_atom = (Atom)windowDeleteAtom; @@ -632,10 +632,16 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CreateWindow0 { XEvent event; int left=0, right=0, top=0, bottom=0; - - if( 0 < iconDataSize && NULL != iconData ) { - const unsigned char * iconDataPtr = (const unsigned char *) (*env)->GetDirectBufferAddress(env, iconData); - NewtWindows_setIcon(dpy, window, (int)iconDataSize, iconDataPtr); + const unsigned char * pixelPtr = NULL; + + // NOTE: MUST BE DIRECT BUFFER, since _NET_WM_ICON Atom uses buffer directly! + DBG_PRINT("X11: CreateWindow icon: size %d, pixels %p, offset %d, direct %d\n", pixelDataSize, (void*)pixels, pixels_byte_offset, pixels_is_direct); + if( 0 < pixelDataSize && NULL != pixels ) { + pixelPtr = (const unsigned char *) ( JNI_TRUE == pixels_is_direct ? + (*env)->GetDirectBufferAddress(env, pixels) : + (*env)->GetPrimitiveArrayCritical(env, pixels, NULL) ); + DBG_PRINT("X11: CreateWindow icon: NIO %p\n", pixelPtr); + NewtWindows_setIcon(dpy, window, (int)pixelDataSize, pixelPtr+pixels_byte_offset); } XMapWindow(dpy, window); @@ -643,6 +649,10 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_WindowDriver_CreateWindow0 XSync(dpy, False); + if( JNI_FALSE == pixels_is_direct && NULL != pixelPtr ) { + (*env)->ReleasePrimitiveArrayCritical(env, pixels, (void*)pixelPtr, JNI_ABORT); + } + // send insets before visibility, allowing java code a proper sync point! NewtWindows_updateInsets(env, jwindow, dpy, window, &left, &right, &top, &bottom); (*env)->CallVoidMethod(env, jwindow, visibleChangedID, JNI_FALSE, JNI_TRUE); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java index 8cc676291..780338492 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java @@ -29,6 +29,7 @@ package com.jogamp.opengl.test.junit.jogl.demos.es2.newt; import java.io.IOException; +import java.net.URLConnection; import com.jogamp.common.util.IOUtil; import com.jogamp.newt.Display; @@ -47,6 +48,7 @@ import com.jogamp.opengl.test.junit.util.MiscUtils; import com.jogamp.opengl.test.junit.util.UITestCase; import com.jogamp.opengl.test.junit.util.QuitAdapter; import com.jogamp.opengl.util.Animator; +import com.jogamp.opengl.util.PNGPixelRect; import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2; import javax.media.nativewindow.NativeWindowFactory; @@ -171,25 +173,55 @@ public class TestGearsES2NEWT extends UITestCase { } }); - final PointerIcon pointerIconOne; + final PointerIcon[] pointerIcons = { null, null, null }; { - PointerIcon _pointerIconOne = null; - final IOUtil.ClassResources res = new IOUtil.ClassResources(glWindow.getClass(), new String[] { "jogamp-pointer-64x64.png" } ); final Display disp = glWindow.getScreen().getDisplay(); disp.createNative(); - try { - _pointerIconOne = disp.createPointerIcon(res, 32, 0); - } catch (Exception e) { - e.printStackTrace(); + { + PointerIcon _pointerIcon = null; + final IOUtil.ClassResources res = new IOUtil.ClassResources(glWindow.getClass(), new String[] { "newt/data/crosshair-lumina-trans-32x32.png" } ); + try { + _pointerIcon = disp.createPointerIcon(res, 16, 16); + System.err.println("Create PointerIcon #01: "+_pointerIcon); + } catch (Exception e) { + e.printStackTrace(); + } + pointerIcons[0] = _pointerIcon; + } + { + PointerIcon _pointerIcon = null; + final IOUtil.ClassResources res = new IOUtil.ClassResources(glWindow.getClass(), new String[] { "jogamp-pointer-64x64.png" } ); + try { + _pointerIcon = disp.createPointerIcon(res, 32, 0); + System.err.println("Create PointerIcon #02: "+_pointerIcon); + } catch (Exception e) { + e.printStackTrace(); + } + pointerIcons[1] = _pointerIcon; + } + { + PointerIcon _pointerIcon = null; + final IOUtil.ClassResources res = new IOUtil.ClassResources(glWindow.getClass(), new String[] { "crosshair-lumina-trans-64x64.png" } ); + try { + final URLConnection urlConn = res.resolve(0); + final PNGPixelRect image = PNGPixelRect.read(urlConn.getInputStream(), null, false /* directBuffer */, 0 /* destMinStrideInBytes */, false /* destIsGLOriented */); + System.err.println("Create PointerIcon #03: "+image); + _pointerIcon = disp.createPointerIcon(image, 32, 32); + System.err.println("Create PointerIcon #03: "+_pointerIcon); + } catch (Exception e) { + e.printStackTrace(); + } + pointerIcons[2] = _pointerIcon; } - pointerIconOne = _pointerIconOne; } if( setPointerIcon ) { - glWindow.setPointerIcon(pointerIconOne); + glWindow.setPointerIcon(pointerIcons[0]); System.err.println("Set PointerIcon: "+glWindow.getPointerIcon()); } glWindow.addKeyListener(new KeyAdapter() { + int pointerIconIdx = 0; + @Override public void keyPressed(final KeyEvent e) { if( e.isAutoRepeat() ) { @@ -246,7 +278,14 @@ public class TestGearsES2NEWT extends UITestCase { final Thread t = glWindow.setExclusiveContextThread(null); System.err.println("[set pointer-icon pre]"); final PointerIcon currentPI = glWindow.getPointerIcon(); - glWindow.setPointerIcon( currentPI == pointerIconOne ? null : pointerIconOne); + final PointerIcon newPI; + if( pointerIconIdx >= pointerIcons.length ) { + newPI=null; + pointerIconIdx=0; + } else { + newPI=pointerIcons[pointerIconIdx++]; + } + glWindow.setPointerIcon( newPI ); System.err.println("[set pointer-icon post] "+currentPI+" -> "+glWindow.getPointerIcon()); glWindow.setExclusiveContextThread(t); } }.start(); diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/PNGTstFiles.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/PNGTstFiles.java new file mode 100644 index 000000000..bb9bc42a8 --- /dev/null +++ b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/PNGTstFiles.java @@ -0,0 +1,54 @@ +/** + * Copyright 2014 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ +package com.jogamp.opengl.test.junit.jogl.util.texture; + +public class PNGTstFiles { + static public final String[] allBasenames = { + "test-ntscN_3-01-160x90", + "test-ntscN_4-01-160x90", + "test-ntscNG4-01-160x90", + "test-ntscI_3-01-160x90", + "test-ntscI_4-01-160x90", + "test-ntscIG3-01-160x90", + "test-ntscIG4-01-160x90", + "test-ntscP_3-01-160x90", + "test-ntscP_4-01-160x90", + "grayscale_texture", + "bug724-transparent-grey_orig", + "bug724-transparent-grey_gimpexp", + "crosshair-lumina-trans-32x32", + "crosshair-lumina-trans-64x64", + }; + static public final String[] greyBasenames = { + "grayscale_texture", + "bug724-transparent-grey_orig", + "bug724-transparent-grey_gimpexp", + "crosshair-lumina-trans-32x32", + "crosshair-lumina-trans-64x64", + }; +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGImage00NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGImage00NEWT.java deleted file mode 100644 index 3ace5ab6a..000000000 --- a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGImage00NEWT.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ -package com.jogamp.opengl.test.junit.jogl.util.texture; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URLConnection; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.FixMethodOrder; -import org.junit.runners.MethodSorters; - -import com.jogamp.common.util.IOUtil; -import com.jogamp.opengl.test.junit.util.UITestCase; -import com.jogamp.opengl.util.texture.spi.PNGImage; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class TestPNGImage00NEWT extends UITestCase { - @Test - public void testPNGReadWriteAndCompare() throws InterruptedException, IOException, MalformedURLException { - final File out1_f=new File(getSimpleTestName(".")+"-PNGImageTest1.png"); - final File out2_f=new File(getSimpleTestName(".")+"-PNGImageTest2.png"); - final File out2F_f=new File(getSimpleTestName(".")+"-PNGImageTest2Flipped.png"); - final File out2R_f=new File(getSimpleTestName(".")+"-PNGImageTest2Reversed.png"); - final File out2RF_f=new File(getSimpleTestName(".")+"-PNGImageTest2ReversedFlipped.png"); - final String url_s="jogl/util/data/av/test-ntsc01-57x32.png"; - URLConnection urlConn = IOUtil.getResource(url_s, this.getClass().getClassLoader()); - PNGImage image1 = PNGImage.read(urlConn.getInputStream()); - System.err.println("PNGImage - Orig: "+image1); - image1.write(out1_f, true); - { - Assert.assertEquals(image1.getData(), PNGImage.read(out1_f.toURI().toURL().openStream()).getData()); - } - - final PNGImage image2 = PNGImage.createFromData(image1.getWidth(), image1.getHeight(), - image1.getDpi()[0], image1.getDpi()[1], - image1.getBytesPerPixel(), false /* reverseChannels */, image1.isGLOriented(), image1.getData()); - image2.write(out2_f, true); - { - Assert.assertEquals(image1.getData(), PNGImage.read(out2_f.toURI().toURL().openStream()).getData()); - } - - // flipped - final PNGImage image2F = PNGImage.createFromData(image1.getWidth(), image1.getHeight(), - image1.getDpi()[0], image1.getDpi()[1], - image1.getBytesPerPixel(), false /* reverseChannels */, !image1.isGLOriented(), image1.getData()); - image2F.write(out2F_f, true); - - // reversed channels - final PNGImage image2R = PNGImage.createFromData(image1.getWidth(), image1.getHeight(), - image1.getDpi()[0], image1.getDpi()[1], - image1.getBytesPerPixel(), true /* reverseChannels */, image1.isGLOriented(), image1.getData()); - image2R.write(out2R_f, true); - - // reversed channels and flipped - final PNGImage image2RF = PNGImage.createFromData(image1.getWidth(), image1.getHeight(), - image1.getDpi()[0], image1.getDpi()[1], - image1.getBytesPerPixel(), true /* reverseChannels */, !image1.isGLOriented(), image1.getData()); - image2RF.write(out2RF_f, true); - } - - public static void main(String args[]) { - org.junit.runner.JUnitCore.main(TestPNGImage00NEWT.class.getName()); - } -} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGImage01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGImage01NEWT.java deleted file mode 100644 index 29e041908..000000000 --- a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/TestPNGImage01NEWT.java +++ /dev/null @@ -1,182 +0,0 @@ -/** - * Copyright 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: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of JogAmp Community. - */ -package com.jogamp.opengl.test.junit.jogl.util.texture; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URLConnection; - -import javax.media.opengl.GL; -import javax.media.opengl.GLAutoDrawable; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLEventListener; -import javax.media.opengl.GLProfile; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.FixMethodOrder; -import org.junit.runners.MethodSorters; - -import com.jogamp.common.util.IOUtil; -import com.jogamp.newt.opengl.GLWindow; -import com.jogamp.opengl.test.junit.jogl.demos.TextureDraw01Accessor; -import com.jogamp.opengl.test.junit.jogl.demos.es2.TextureDraw01ES2Listener; -import com.jogamp.opengl.test.junit.util.MiscUtils; -import com.jogamp.opengl.test.junit.util.QuitAdapter; -import com.jogamp.opengl.test.junit.util.UITestCase; -import com.jogamp.opengl.util.Animator; -import com.jogamp.opengl.util.GLReadBufferUtil; -import com.jogamp.opengl.util.GLPixelBuffer.GLPixelAttributes; -import com.jogamp.opengl.util.texture.TextureData; -import com.jogamp.opengl.util.texture.TextureIO; -import com.jogamp.opengl.util.texture.spi.PNGImage; - -/** - * Test reading and displaying a PNG image. - *

                            - * Main function accepts arbitrary PNG file name for manual tests. - *

                            - */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class TestPNGImage01NEWT extends UITestCase { - - static boolean showFPS = false; - static long duration = 200; // ms - - public void testImpl(final InputStream istream) throws InterruptedException, IOException { - final PNGImage image = PNGImage.read(istream); - Assert.assertNotNull(image); - final boolean hasAlpha = 4 == image.getBytesPerPixel(); - System.err.println("PNGImage: "+image); - - final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false); - final GLProfile glp = GLProfile.getGL2ES2(); - final GLCapabilities caps = new GLCapabilities(glp); - if( hasAlpha ) { - caps.setAlphaBits(1); - } - - final int internalFormat; - if(glp.isGL2ES3()) { - internalFormat = hasAlpha ? GL.GL_RGBA8 : GL.GL_RGB8; - } else { - internalFormat = hasAlpha ? GL.GL_RGBA : GL.GL_RGB; - } - final TextureData texData = new TextureData(glp, internalFormat, - image.getWidth(), - image.getHeight(), - 0, - new GLPixelAttributes(image.getGLFormat(), image.getGLType()), - false /* mipmap */, - false /* compressed */, - false /* must flip-vert */, - image.getData(), - null); - - // final TextureData texData = TextureIO.newTextureData(glp, istream, false /* mipmap */, TextureIO.PNG); - System.err.println("TextureData: "+texData); - - final GLWindow glad = GLWindow.create(caps); - glad.setTitle("TestPNGImage01NEWT"); - // Size OpenGL to Video Surface - glad.setSize(texData.getWidth(), texData.getHeight()); - - // load texture from file inside current GL context to match the way - // the bug submitter was doing it - final TextureDraw01ES2Listener gle = new TextureDraw01ES2Listener( texData, 0 ) ; - // gle.setClearColor(new float[] { 1.0f, 0.0f, 0.0f, 1.0f } ); - - glad.addGLEventListener(gle); - glad.addGLEventListener(new GLEventListener() { - boolean shot = false; - - @Override public void init(GLAutoDrawable drawable) { - System.err.println("Chosen Caps: " + drawable.getChosenGLCapabilities()); - System.err.println("GL ctx: " + drawable.getGL().getContext()); - } - - @Override public void display(GLAutoDrawable drawable) { - // 1 snapshot - if(null!=((TextureDraw01Accessor)gle).getTexture() && !shot) { - shot = true; - snapshot(0, null, drawable.getGL(), screenshot, TextureIO.PNG, null); - } - } - - @Override public void dispose(GLAutoDrawable drawable) { } - @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } - }); - - Animator animator = new Animator(glad); - animator.setUpdateFPSFrames(60, showFPS ? System.err : null); - QuitAdapter quitAdapter = new QuitAdapter(); - glad.addKeyListener(quitAdapter); - glad.addWindowListener(quitAdapter); - glad.setVisible(true); - animator.start(); - - while(!quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration() + * Main function accepts arbitrary PNG file name for manual tests. + *

                            + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestPNGPixelRect01NEWT extends UITestCase { + static boolean showFPS = false; + static long duration = 200; // ms + + public void testImpl(final int num, final String basename, final InputStream istream, final PixelFormat destFmt) throws InterruptedException, IOException { + final GLProfile glp = GLProfile.getGL2ES2(); + final PNGPixelRect image = PNGPixelRect.read(istream, destFmt, true /* directBuffer */, 0 /* destMinStrideInBytes */, true /* destIsGLOriented */); + Assert.assertNotNull(image); + final GLPixelAttributes glpa = GLPixelAttributes.convert(image.getPixelformat(), glp); + final boolean hasAlpha = 4 == glpa.bytesPerPixel; + System.err.println("PNGPixelRect: "+basename+", "+image+", glpa "+glpa); + + final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false); + final GLCapabilities caps = new GLCapabilities(glp); + if( hasAlpha ) { + caps.setAlphaBits(1); + } + + final int internalFormat; + if(glp.isGL2ES3()) { + internalFormat = hasAlpha ? GL.GL_RGBA8 : GL.GL_RGB8; + } else { + internalFormat = hasAlpha ? GL.GL_RGBA : GL.GL_RGB; + } + final TextureData texData = new TextureData(glp, internalFormat, + image.getSize().getWidth(), + image.getSize().getHeight(), + 0, + glpa, + false /* mipmap */, + false /* compressed */, + false /* must flip-vert */, + image.getPixels(), + null); + + // final TextureData texData = TextureIO.newTextureData(glp, istream, false /* mipmap */, TextureIO.PNG); + System.err.println("TextureData: "+texData); + + final GLWindow glad = GLWindow.create(caps); + glad.setTitle(this.getSimpleTestName(".")); + // Size OpenGL to Video Surface + glad.setSize(texData.getWidth(), texData.getHeight()); + + // load texture from file inside current GL context to match the way + // the bug submitter was doing it + final TextureDraw01ES2Listener gle = new TextureDraw01ES2Listener( texData, 0 ) ; + // gle.setClearColor(new float[] { 1.0f, 0.0f, 0.0f, 1.0f } ); + + glad.addGLEventListener(gle); + glad.addGLEventListener(new GLEventListener() { + boolean shot = false; + + @Override public void init(GLAutoDrawable drawable) { + System.err.println("Chosen Caps: " + drawable.getChosenGLCapabilities()); + System.err.println("GL ctx: " + drawable.getGL().getContext()); + } + + @Override public void display(GLAutoDrawable drawable) { + // 1 snapshot + if(null!=((TextureDraw01Accessor)gle).getTexture() && !shot) { + shot = true; + snapshot(num, basename, drawable.getGL(), screenshot, TextureIO.PNG, null); + } + } + + @Override public void dispose(GLAutoDrawable drawable) { } + @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } + }); + + Animator animator = new Animator(glad); + animator.setUpdateFPSFrames(60, showFPS ? System.err : null); + QuitAdapter quitAdapter = new QuitAdapter(); + glad.addKeyListener(quitAdapter); + glad.addWindowListener(quitAdapter); + glad.setVisible(true); + animator.start(); + + while(!quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration() "+destFmt); + final PixelRectangle imageConv1 = PixelFormatUtil.convert32(image1, destFmt, destMinStrideInBytes, destIsGLOriented, false /* nio */); + System.err.println("PNGPixelRect - Conv1: "+imageConv1); + final PixelRectangle imageConv2 = PixelFormatUtil.convert32(imageConv1, image1.getPixelformat(), image1.getStride(), image1.isGLOriented(), false /* nio */); + System.err.println("PNGPixelRect - Conv2: "+imageConv2); + Assert.assertEquals(image1.getPixels(), imageConv2.getPixels()); + } + } + + public static void main(String args[]) { + org.junit.runner.JUnitCore.main(TestPixelFormatUtil01NEWT.class.getName()); + } +} diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/crosshair-lumina-trans-32x32.png b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/crosshair-lumina-trans-32x32.png new file mode 100644 index 000000000..92279640b Binary files /dev/null and b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/crosshair-lumina-trans-32x32.png differ diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/crosshair-lumina-trans-64x64.png b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/crosshair-lumina-trans-64x64.png new file mode 100644 index 000000000..9be285335 Binary files /dev/null and b/src/test/com/jogamp/opengl/test/junit/jogl/util/texture/crosshair-lumina-trans-64x64.png differ diff --git a/src/test/com/jogamp/opengl/test/junit/newt/parenting/NewtAWTReparentingKeyAdapter.java b/src/test/com/jogamp/opengl/test/junit/newt/parenting/NewtAWTReparentingKeyAdapter.java index 69874df6b..70d01ae66 100644 --- a/src/test/com/jogamp/opengl/test/junit/newt/parenting/NewtAWTReparentingKeyAdapter.java +++ b/src/test/com/jogamp/opengl/test/junit/newt/parenting/NewtAWTReparentingKeyAdapter.java @@ -28,25 +28,27 @@ package com.jogamp.opengl.test.junit.newt.parenting; import java.awt.Frame; +import java.net.URLConnection; import javax.media.nativewindow.util.InsetsImmutable; import com.jogamp.common.util.IOUtil; import com.jogamp.newt.Display; -import com.jogamp.newt.Window; import com.jogamp.newt.Display.PointerIcon; import com.jogamp.newt.awt.NewtCanvasAWT; import com.jogamp.newt.event.KeyAdapter; import com.jogamp.newt.event.KeyEvent; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.test.junit.util.QuitAdapter; +import com.jogamp.opengl.util.PNGPixelRect; public class NewtAWTReparentingKeyAdapter extends KeyAdapter { final Frame frame; final NewtCanvasAWT newtCanvasAWT; final GLWindow glWindow; final QuitAdapter quitAdapter; - PointerIcon pointerIconTest = null; + PointerIcon[] pointerIcons = null; + int pointerIconIdx = 0; public NewtAWTReparentingKeyAdapter(Frame frame, NewtCanvasAWT newtCanvasAWT, GLWindow glWindow, QuitAdapter quitAdapter) { this.frame = frame; @@ -144,13 +146,46 @@ public class NewtAWTReparentingKeyAdapter extends KeyAdapter { } } }.start(); } else if(e.getKeySymbol() == KeyEvent.VK_C ) { - if( null == pointerIconTest ) { - final IOUtil.ClassResources res = new IOUtil.ClassResources(glWindow.getClass(), new String[] { "newt/data/jogamp-32x32.png" } ); - final Display disp = glWindow.getScreen().getDisplay(); - try { - pointerIconTest = disp.createPointerIcon(res, 16, 0); - } catch (Exception err) { - err.printStackTrace(); + if( null == pointerIcons ) { + { + pointerIcons = new PointerIcon[3]; + final Display disp = glWindow.getScreen().getDisplay(); + { + PointerIcon _pointerIcon = null; + final IOUtil.ClassResources res = new IOUtil.ClassResources(glWindow.getClass(), new String[] { "newt/data/crosshair-lumina-trans-32x32.png" } ); + try { + _pointerIcon = disp.createPointerIcon(res, 16, 16); + System.err.println("Create PointerIcon #01: "+_pointerIcon); + } catch (Exception ex) { + ex.printStackTrace(); + } + pointerIcons[0] = _pointerIcon; + } + { + PointerIcon _pointerIcon = null; + final IOUtil.ClassResources res = new IOUtil.ClassResources(glWindow.getClass(), new String[] { "jogamp-pointer-64x64.png" } ); + try { + _pointerIcon = disp.createPointerIcon(res, 32, 0); + System.err.println("Create PointerIcon #02: "+_pointerIcon); + } catch (Exception ex) { + ex.printStackTrace(); + } + pointerIcons[1] = _pointerIcon; + } + { + PointerIcon _pointerIcon = null; + final IOUtil.ClassResources res = new IOUtil.ClassResources(glWindow.getClass(), new String[] { "crosshair-lumina-trans-64x64.png" } ); + try { + final URLConnection urlConn = res.resolve(0); + final PNGPixelRect image = PNGPixelRect.read(urlConn.getInputStream(), null, false /* directBuffer */, 0 /* destMinStrideInBytes */, false /* destIsGLOriented */); + System.err.println("Create PointerIcon #03: "+image); + _pointerIcon = disp.createPointerIcon(image, 32, 32); + System.err.println("Create PointerIcon #03: "+_pointerIcon); + } catch (Exception ex) { + ex.printStackTrace(); + } + pointerIcons[2] = _pointerIcon; + } } } new Thread() { @@ -158,7 +193,14 @@ public class NewtAWTReparentingKeyAdapter extends KeyAdapter { final Thread t = glWindow.setExclusiveContextThread(null); System.err.println("[set pointer-icon pre]"); final PointerIcon currentPI = glWindow.getPointerIcon(); - glWindow.setPointerIcon( currentPI == pointerIconTest ? null : pointerIconTest); + final PointerIcon newPI; + if( pointerIconIdx >= pointerIcons.length ) { + newPI=null; + pointerIconIdx=0; + } else { + newPI=pointerIcons[pointerIconIdx++]; + } + glWindow.setPointerIcon( newPI ); System.err.println("[set pointer-icon post] "+currentPI+" -> "+glWindow.getPointerIcon()); glWindow.setExclusiveContextThread(t); } }.start(); -- cgit v1.2.3 From d38fbf00efa47834f754306441cb99f2ef967a21 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 9 Jan 2014 10:33:16 +0100 Subject: PixelRectangle.GenericPixelRect: hashCode() impl. didn't set volatile hashCodeComputed := true (always re-computes hash code - duh!) --- .../classes/javax/media/nativewindow/util/PixelRectangle.java | 1 + 1 file changed, 1 insertion(+) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/PixelRectangle.java b/src/nativewindow/classes/javax/media/nativewindow/util/PixelRectangle.java index 493c712bb..96c1f7b33 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/PixelRectangle.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/PixelRectangle.java @@ -153,6 +153,7 @@ public interface PixelRectangle { hash = ((hash << 5) - hash) + strideInBytes; hash = ((hash << 5) - hash) + ( isGLOriented ? 1 : 0); hashCode = ((hash << 5) - hash) + pixels.hashCode(); + hashCodeComputed = true; } } } -- cgit v1.2.3 From 5ef83c2b8576ccd764ffc4953eea506bd96277c3 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 11 Jan 2014 00:04:18 +0100 Subject: X11: Harden usage of 'XGetWindowProperty(..)' and 'XGetVisualInfo' - Add missing XFree(..) calls and argument checks. --- src/nativewindow/native/x11/Xmisc.c | 36 ++++++++++---------- src/newt/native/X11Window.c | 66 +++++++++++++++++++++---------------- 2 files changed, 55 insertions(+), 47 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 7b9dc344b..5e6909f6e 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -219,7 +219,6 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, (int)e->request_code, (int)e->minor_code, reqCodeStr); } - if (shallBeDetached) { (*jvmHandle)->DetachCurrentThread(jvmHandle); } @@ -347,25 +346,24 @@ JNIEXPORT jobject JNICALL Java_jogamp_nativewindow_x11_X11Lib_XGetVisualInfo1__JJLjava_nio_ByteBuffer_2Ljava_lang_Object_2I(JNIEnv *env, jclass _unused, jlong arg0, jlong arg1, jobject arg2, jobject arg3, jint arg3_byte_offset) { XVisualInfo * _ptr2 = NULL; int * _ptr3 = NULL; - XVisualInfo * _res; - int count; - jobject jbyteSource; - jobject jbyteCopy; - if(0==arg0) { - NativewindowCommon_FatalError(env, "invalid display connection.."); - } - if (arg2 != NULL) { - _ptr2 = (XVisualInfo *) (((char*) (*env)->GetDirectBufferAddress(env, arg2)) + 0); - } - if (arg3 != NULL) { - _ptr3 = (int *) (((char*) (*env)->GetPrimitiveArrayCritical(env, arg3, NULL)) + arg3_byte_offset); + XVisualInfo * _res = NULL; + int count = 0; + jobject jbyteSource = NULL; + jobject jbyteCopy = NULL; + if( 0 == arg0 || 0 == arg2 || 0 == arg3 ) { + NativewindowCommon_FatalError(env, "invalid display connection, vinfo_template or nitems_return"); + return NULL; } - NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 1, errorHandlerQuiet, 0); - _res = XGetVisualInfo((Display *) (intptr_t) arg0, (long) arg1, (XVisualInfo *) _ptr2, (int *) _ptr3); - // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 0, errorHandlerQuiet, 0); - count = _ptr3[0]; - if (arg3 != NULL) { - (*env)->ReleasePrimitiveArrayCritical(env, arg3, _ptr3, 0); + _ptr2 = (XVisualInfo *) (((char*) (*env)->GetDirectBufferAddress(env, arg2)) + 0); + if( NULL != _ptr2 ) { + _ptr3 = (int *) (((char*) (*env)->GetPrimitiveArrayCritical(env, arg3, NULL)) + arg3_byte_offset); + if( NULL != _ptr3 ) { + NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 1, errorHandlerQuiet, 0); + _res = XGetVisualInfo((Display *) (intptr_t) arg0, (long) arg1, (XVisualInfo *) _ptr2, (int *) _ptr3); + // NativewindowCommon_x11ErrorHandlerEnable(env, (Display *) (intptr_t) arg0, 0, 0, errorHandlerQuiet, 0); + count = _ptr3[0]; + (*env)->ReleasePrimitiveArrayCritical(env, arg3, _ptr3, 0); + } } if (_res == NULL) return NULL; diff --git a/src/newt/native/X11Window.c b/src/newt/native/X11Window.c index 54b85c243..2cc66c78d 100644 --- a/src/newt/native/X11Window.c +++ b/src/newt/native/X11Window.c @@ -98,11 +98,11 @@ static void setJavaWindowProperty(JNIEnv *env, Display *dpy, Window window, jlon } jobject getJavaWindowProperty(JNIEnv *env, Display *dpy, Window window, jlong javaObjectAtom, Bool showWarning) { - Atom actual_type; - int actual_format; + Atom actual_type = 0; + int actual_format = 0; int nitems_32 = ( sizeof(uintptr_t) == 8 ) ? 2 : 1 ; unsigned char * jogl_java_object_data_pp = NULL; - jobject jwindow; + jobject jwindow = 0; { unsigned long nitems= 0; @@ -122,7 +122,9 @@ jobject getJavaWindowProperty(JNIEnv *env, Display *dpy, Window window, jlong ja } if(actual_type!=(Atom)javaObjectAtom || nitems= PROP_MWM_HINTS_ELEMENTS) { // unsigned long mwmhints[PROP_MWM_HINTS_ELEMENTS] = { MWM_HINTS_DECORATIONS, 0, decorated, 0, 0 }; // flags, functions, decorations, input_mode, status unsigned long *hints = (unsigned long *) wm_data; decor = ( 0 != (hints[0] & MWM_HINTS_DECORATIONS) ) && ( 0 != hints[2] ); } + if( NULL != wm_data ) { + XFree(wm_data); + } } #endif @@ -319,27 +326,30 @@ static int NewtWindows_getSupportedStackingEWMHFlags(Display *dpy, Window w) { Atom _NET_WM_ALLOWED_ACTIONS = XInternAtom( dpy, "_NET_WM_ALLOWED_ACTIONS", False ); Atom _NET_WM_ACTION_FULLSCREEN = XInternAtom( dpy, "_NET_WM_ACTION_FULLSCREEN", False ); Atom _NET_WM_ACTION_ABOVE = XInternAtom( dpy, "_NET_WM_ACTION_ABOVE", False ); - Atom * actions; - Atom type; - unsigned long action_len, remain; - int res = 0, form, i; + Atom * actions = NULL; + Atom type = 0; + unsigned long action_len = 0, remain = 0; + int res = 0, form = 0, i = 0; Status s; if ( Success == (s = XGetWindowProperty(dpy, w, _NET_WM_ALLOWED_ACTIONS, 0, 1024, False, AnyPropertyType, &type, &form, &action_len, &remain, (unsigned char**)&actions)) ) { - for(i=0; i Date: Sat, 11 Jan 2014 02:11:47 +0100 Subject: [Jogl|Nativewindow|Newt]Common: Align all *Common_GetJNIEnv()/_ReleaseJNIEnv() Methods and Usage / Check arguments .. Since we still don't use inter-module native code sharing, align the JNIEnv get/release methods and usage. Most beneficary here is OSX and the GLDebugMessageHandle, both managed the JVM handle on their own - removed now. Also ensuring that *Common_init(..) is called for all modules on all platforms. --- src/jogl/native/GLContext.c | 2 +- src/jogl/native/GLDebugMessageHandler.c | 95 ++++--------- src/jogl/native/JoglCommon.c | 97 ++++++------- src/jogl/native/JoglCommon.h | 55 ++++++-- src/jogl/native/libav/ffmpeg_impl_template.c | 4 +- .../macosx/MacOSXWindowSystemInterface-calayer.m | 1 + .../jogamp_opengl_util_av_impl_OMXGLMediaPlayer.c | 5 +- src/nativewindow/native/NativewindowCommon.c | 110 ++++++++++----- src/nativewindow/native/NativewindowCommon.h | 61 ++++++++- src/nativewindow/native/macosx/OSXmisc.m | 34 ++--- src/nativewindow/native/win32/GDImisc.c | 2 +- src/nativewindow/native/x11/Xmisc.c | 126 +++++++---------- src/newt/native/MacWindow.m | 13 +- src/newt/native/NewtCommon.c | 96 +++++++++---- src/newt/native/NewtCommon.h | 26 ++-- src/newt/native/NewtMacWindow.h | 10 -- src/newt/native/NewtMacWindow.m | 152 ++++++--------------- 17 files changed, 431 insertions(+), 458 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/native/GLContext.c b/src/jogl/native/GLContext.c index f10d0e421..9be9f82af 100644 --- a/src/jogl/native/GLContext.c +++ b/src/jogl/native/GLContext.c @@ -19,7 +19,7 @@ Java_jogamp_opengl_GLContextImpl_glGetStringInt(JNIEnv *env, jclass _unused, jin assert(ptr_glGetString != NULL); _res = (* ptr_glGetString) ((unsigned int) name); if (NULL == _res) return NULL; - return (*env)->NewStringUTF(env, _res); + return (*env)->NewStringUTF(env, (const char *)_res); } /* diff --git a/src/jogl/native/GLDebugMessageHandler.c b/src/jogl/native/GLDebugMessageHandler.c index 2e9d6033a..0aa7a01e7 100644 --- a/src/jogl/native/GLDebugMessageHandler.c +++ b/src/jogl/native/GLDebugMessageHandler.c @@ -49,8 +49,6 @@ JNIEXPORT jboolean JNICALL Java_jogamp_opengl_GLDebugMessageHandler_initIDs0 } typedef struct { - JavaVM *vm; - int version; jobject obj; int extType; } DebugHandlerType; @@ -60,39 +58,21 @@ typedef struct { static void GLDebugMessageARBCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, GLvoid *userParam) { DebugHandlerType * handle = (DebugHandlerType*) (intptr_t) userParam; - JavaVM *vm = handle->vm; - int version = handle->version; jobject obj = handle->obj; - JNIEnv *curEnv = NULL; - JNIEnv *newEnv = NULL; - int envRes ; - DBG_PRINT("GLDebugMessageARBCallback: 00 - %s, vm %p, version 0x%X, jobject %p, extType %d\n", - message, handle->vm, handle->version, (void*)handle->obj, handle->extType); - - // retrieve this thread's JNIEnv curEnv - or detect it's detached - envRes = (*vm)->GetEnv(vm, (void **) &curEnv, version) ; - DBG_PRINT("GLDebugMessageARBCallback: 01 - JVM Env: curEnv %p, res 0x%X\n", curEnv, envRes); - if( JNI_EDETACHED == envRes ) { - // detached thread - attach to JVM - if( JNI_OK != ( envRes = (*vm)->AttachCurrentThread(vm, (void**) &newEnv, NULL) ) ) { - fprintf(stderr, "GLDebugMessageARBCallback: can't attach thread: %d\n", envRes); - return; - } - curEnv = newEnv; - DBG_PRINT("GLDebugMessageARBCallback: 02 - attached .. \n"); - } else if( JNI_OK != envRes ) { - // oops .. - fprintf(stderr, "GLDebugMessageARBCallback: can't GetEnv: %d\n", envRes); + JNIEnv *env = NULL; + int shallBeDetached ; + DBG_PRINT("GLDebugMessageARBCallback: 00 - %s, jobject %p, extType %d\n", message, (void*)handle->obj, handle->extType); + + env = JoglCommon_GetJNIEnv (1 /* asDaemon */, &shallBeDetached); + if( NULL == env ) { + DBG_PRINT("GLDebugMessageARBCallback: Null JNIEnv\n"); return; } - (*curEnv)->CallVoidMethod(curEnv, obj, glDebugMessageARB, + (*env)->CallVoidMethod(env, obj, glDebugMessageARB, (jint) source, (jint) type, (jint) id, (jint) severity, - (*curEnv)->NewStringUTF(curEnv, message)); - if( NULL != newEnv ) { - // detached attached thread - (*vm)->DetachCurrentThread(vm); - DBG_PRINT("GLDebugMessageARBCallback: 04 - detached .. \n"); - } + (*env)->NewStringUTF(env, message)); + // detaching thread not required - daemon + // JoglCommon_ReleaseJNIEnv(shallBeDetached); DBG_PRINT("GLDebugMessageARBCallback: 0X\n"); /** * On Java 32bit on 64bit Windows and w/ GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB disables, @@ -104,39 +84,21 @@ static void GLDebugMessageARBCallback(GLenum source, GLenum type, GLuint id, GLe static void GLDebugMessageAMDCallback(GLuint id, GLenum category, GLenum severity, GLsizei length, const GLchar *message, GLvoid *userParam) { DebugHandlerType * handle = (DebugHandlerType*) (intptr_t) userParam; - JavaVM *vm = handle->vm; - int version = handle->version; jobject obj = handle->obj; - JNIEnv *curEnv = NULL; - JNIEnv *newEnv = NULL; - int envRes ; - DBG_PRINT("GLDebugMessageAMDCallback: 00 - %s, vm %p, version 0x%X, jobject %p, extType %d\n", - message, handle->vm, handle->version, (void*)handle->obj, handle->extType); - - // retrieve this thread's JNIEnv curEnv - or detect it's detached - envRes = (*vm)->GetEnv(vm, (void **) &curEnv, version) ; - DBG_PRINT("GLDebugMessageAMDCallback: 01 - JVM Env: curEnv %p, res 0x%X\n", curEnv, envRes); - if( JNI_EDETACHED == envRes ) { - // detached thread - attach to JVM - if( JNI_OK != ( envRes = (*vm)->AttachCurrentThread(vm, (void**) &newEnv, NULL) ) ) { - fprintf(stderr, "GLDebugMessageAMDCallback: can't attach thread: %d\n", envRes); - return; - } - curEnv = newEnv; - DBG_PRINT("GLDebugMessageAMDCallback: 02 - attached .. \n"); - } else if( JNI_OK != envRes ) { - // oops .. - fprintf(stderr, "GLDebugMessageAMDCallback: can't GetEnv: %d\n", envRes); + JNIEnv *env = NULL; + int shallBeDetached ; + DBG_PRINT("GLDebugMessageAMDCallback: 00 - %s, jobject %p, extType %d\n", message, (void*)handle->obj, handle->extType); + + env = JoglCommon_GetJNIEnv (1 /* asDaemon */, &shallBeDetached); + if( NULL == env ) { + DBG_PRINT("GLDebugMessageARBCallback: Null JNIEnv\n"); return; } - (*curEnv)->CallVoidMethod(curEnv, obj, glDebugMessageAMD, + (*env)->CallVoidMethod(env, obj, glDebugMessageAMD, (jint) id, (jint) category, (jint) severity, - (*curEnv)->NewStringUTF(curEnv, message)); - if( NULL != newEnv ) { - // detached attached thread - (*vm)->DetachCurrentThread(vm); - DBG_PRINT("GLDebugMessageAMDCallback: 04 - detached .. \n"); - } + (*env)->NewStringUTF(env, message)); + // detached attached thread not required - daemon + // JoglCommon_ReleaseJNIEnv(shallBeDetached); DBG_PRINT("GLDebugMessageAMDCallback: 0X\n"); /** * On Java 32bit on 64bit Windows, @@ -153,18 +115,10 @@ static void GLDebugMessageAMDCallback(GLuint id, GLenum category, GLenum severit JNIEXPORT jlong JNICALL Java_jogamp_opengl_GLDebugMessageHandler_register0 (JNIEnv *env, jobject obj, jlong procAddress, jint extType) { - JavaVM *vm; DebugHandlerType * handle = malloc(sizeof(DebugHandlerType)); - if(0 != (*env)->GetJavaVM(env, &vm)) { - vm = NULL; - JoglCommon_throwNewRuntimeException(env, "GetJavaVM failed"); - } - handle->vm = vm; - handle->version = (*env)->GetVersion(env); handle->obj = (*env)->NewGlobalRef(env, obj); handle->extType = extType; - DBG_PRINT("GLDebugMessageHandler.register0: vm %p, version 0x%X, jobject %p, extType %d\n", - handle->vm, handle->version, (void*)handle->obj, handle->extType); + DBG_PRINT("GLDebugMessageHandler.register0: jobject %p, extType %d\n", (void*)handle->obj, handle->extType); if(jogamp_opengl_GLDebugMessageHandler_EXT_ARB == extType) { _local_PFNGLDEBUGMESSAGECALLBACKARBPROC ptr_glDebugMessageCallbackARB; @@ -191,8 +145,7 @@ JNIEXPORT void JNICALL Java_jogamp_opengl_GLDebugMessageHandler_unregister0 { DebugHandlerType * handle = (DebugHandlerType*) (intptr_t) jhandle; - DBG_PRINT("GLDebugMessageHandler.unregister0: vm %p, version 0x%X, jobject %p, extType %d\n", - handle->vm, handle->version, (void*)handle->obj, handle->extType); + DBG_PRINT("GLDebugMessageHandler.unregister0: jobject %p, extType %d\n", (void*)handle->obj, handle->extType); if(JNI_FALSE == (*env)->IsSameObject(env, obj, handle->obj)) { JoglCommon_throwNewRuntimeException(env, "wrong handle (obj doesn't match)"); diff --git a/src/jogl/native/JoglCommon.c b/src/jogl/native/JoglCommon.c index 4170b13ec..e9984ada2 100644 --- a/src/jogl/native/JoglCommon.c +++ b/src/jogl/native/JoglCommon.c @@ -11,42 +11,38 @@ static JavaVM *_jvmHandle = NULL; static int _jvmVersion = 0; void JoglCommon_init(JNIEnv *env) { - if(NULL==runtimeExceptionClz) { + if(NULL==_jvmHandle) { + if(0 != (*env)->GetJavaVM(env, &_jvmHandle)) { + JoglCommon_FatalError(env, "JOGL: Can't fetch JavaVM handle"); + } else { + _jvmVersion = (*env)->GetVersion(env); + } jclass c = (*env)->FindClass(env, ClazzNameRuntimeException); if(NULL==c) { - JoglCommon_FatalError(env, "JOGL: can't find %s", ClazzNameRuntimeException); + JoglCommon_FatalError(env, "JOGL: Can't find %s", ClazzNameRuntimeException); } runtimeExceptionClz = (jclass)(*env)->NewGlobalRef(env, c); (*env)->DeleteLocalRef(env, c); if(NULL==runtimeExceptionClz) { - JoglCommon_FatalError(env, "JOGL: can't use %s", ClazzNameRuntimeException); + JoglCommon_FatalError(env, "JOGL: Can't use %s", ClazzNameRuntimeException); } } - if(0 != (*env)->GetJavaVM(env, &_jvmHandle)) { - JoglCommon_FatalError(env, "JOGL: can't fetch JavaVM handle"); - } else { - _jvmVersion = (*env)->GetVersion(env); - } } void JoglCommon_FatalError(JNIEnv *env, const char* msg, ...) { char buffer[512]; va_list ap; - int shallBeDetached = 0; - - if(NULL == env) { - env = JoglCommon_GetJNIEnv (&shallBeDetached); - } - va_start(ap, msg); - vsnprintf(buffer, sizeof(buffer), msg, ap); - va_end(ap); + if( NULL != msg ) { + va_start(ap, msg); + vsnprintf(buffer, sizeof(buffer), msg, ap); + va_end(ap); - fprintf(stderr, "%s\n", buffer); - if(NULL != env) { - (*env)->FatalError(env, buffer); - JoglCommon_ReleaseJNIEnv (shallBeDetached); + fprintf(stderr, "%s\n", buffer); + if(NULL != env) { + (*env)->FatalError(env, buffer); + } } } @@ -54,48 +50,42 @@ void JoglCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...) { char buffer[512]; va_list ap; - int shallBeDetached = 0; - if(NULL == env) { - env = JoglCommon_GetJNIEnv (&shallBeDetached); + if(NULL==_jvmHandle) { + JoglCommon_FatalError(env, "JOGL: NULL JVM handle, call JoglCommon_init 1st\n"); + return; } - va_start(ap, msg); - vsnprintf(buffer, sizeof(buffer), msg, ap); - va_end(ap); + if( NULL != msg ) { + va_start(ap, msg); + vsnprintf(buffer, sizeof(buffer), msg, ap); + va_end(ap); - if(NULL != env) { - (*env)->ThrowNew(env, runtimeExceptionClz, buffer); - JoglCommon_ReleaseJNIEnv (shallBeDetached); + if(NULL != env) { + (*env)->ThrowNew(env, runtimeExceptionClz, buffer); + } } } -JavaVM *JoglCommon_GetJVMHandle() { - return _jvmHandle; -} - -int JoglCommon_GetJVMVersion() { - return _jvmVersion; -} - jchar* JoglCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str) { jchar* strChars = NULL; - strChars = calloc((*env)->GetStringLength(env, str) + 1, sizeof(jchar)); - if (strChars != NULL) { - (*env)->GetStringRegion(env, str, 0, (*env)->GetStringLength(env, str), strChars); + if( NULL != env && 0 != str ) { + strChars = calloc((*env)->GetStringLength(env, str) + 1, sizeof(jchar)); + if (strChars != NULL) { + (*env)->GetStringRegion(env, str, 0, (*env)->GetStringLength(env, str), strChars); + } } return strChars; } -JNIEnv* JoglCommon_GetJNIEnv (int * shallBeDetached) -{ +JNIEnv* JoglCommon_GetJNIEnv (int asDaemon, int * shallBeDetached) { JNIEnv* curEnv = NULL; JNIEnv* newEnv = NULL; int envRes; - if(NULL == _jvmHandle) { - fprintf(stderr, "JOGL: No JavaVM handle registered, call JoglCommon_init(..) 1st"); + if(NULL==_jvmHandle) { + fprintf(stderr, "JOGL GetJNIEnv: NULL JVM handle, call JoglCommon_init 1st\n"); return NULL; } @@ -103,18 +93,23 @@ JNIEnv* JoglCommon_GetJNIEnv (int * shallBeDetached) envRes = (*_jvmHandle)->GetEnv(_jvmHandle, (void **) &curEnv, _jvmVersion) ; if( JNI_EDETACHED == envRes ) { // detached thread - attach to JVM - if( JNI_OK != ( envRes = (*_jvmHandle)->AttachCurrentThread(_jvmHandle, (void**) &newEnv, NULL) ) ) { - fprintf(stderr, "JNIEnv: can't attach thread: %d\n", envRes); + if( asDaemon ) { + envRes = (*_jvmHandle)->AttachCurrentThreadAsDaemon(_jvmHandle, (void**) &newEnv, NULL); + } else { + envRes = (*_jvmHandle)->AttachCurrentThread(_jvmHandle, (void**) &newEnv, NULL); + } + if( JNI_OK != envRes ) { + fprintf(stderr, "JOGL GetJNIEnv: Can't attach thread: %d\n", envRes); return NULL; } curEnv = newEnv; } else if( JNI_OK != envRes ) { // oops .. - fprintf(stderr, "can't GetEnv: %d\n", envRes); + fprintf(stderr, "JOGL GetJNIEnv: Can't GetEnv: %d\n", envRes); return NULL; } if (curEnv==NULL) { - fprintf(stderr, "env is NULL\n"); + fprintf(stderr, "JOGL GetJNIEnv: env is NULL\n"); return NULL; } *shallBeDetached = NULL != newEnv; @@ -123,10 +118,8 @@ JNIEnv* JoglCommon_GetJNIEnv (int * shallBeDetached) void JoglCommon_ReleaseJNIEnv (int shallBeDetached) { if(NULL == _jvmHandle) { - fprintf(stderr, "JOGL: No JavaVM handle registered, call JoglCommon_init(..) 1st"); - } - - if(shallBeDetached) { + fprintf(stderr, "JOGL ReleaseJNIEnv: No JavaVM handle registered, call JoglCommon_init(..) 1st"); + } else if(shallBeDetached) { (*_jvmHandle)->DetachCurrentThread(_jvmHandle); } } diff --git a/src/jogl/native/JoglCommon.h b/src/jogl/native/JoglCommon.h index 023b4be03..2aeaf7d1d 100644 --- a/src/jogl/native/JoglCommon.h +++ b/src/jogl/native/JoglCommon.h @@ -1,3 +1,30 @@ +/** + * Copyright 2011 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ #ifndef JOGL_COMMON_H #define JOGL_COMMON_H 1 @@ -7,29 +34,25 @@ void JoglCommon_init(JNIEnv *env); -/** Set by JoglCommon_init */ -JavaVM *JoglCommon_GetJVMHandle(); - -/** Set by JoglCommon_init */ -int JoglCommon_GetJVMVersion(); - jchar* JoglCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str); -/** env may be NULL, in which case JoglCommon_GetJNIEnv() is being used. */ void JoglCommon_FatalError(JNIEnv *env, const char* msg, ...); - -/** env may be NULL, in which case JoglCommon_GetJNIEnv() is being used. */ void JoglCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...); /** * - * 1) Store jvmHandle and jvmVersion is done by 'JoglCommon_init(JNIEnv*)' - * and internally used by 'JoglCommon_GetJNIEnv(..)' and 'JoglCommon_ReleaseJNIEnv(..)'. + * 1) Init static jvmHandle, jvmVersion and clazz references + * from an early initialization call w/ valid 'JNIEnv * env' + + JoglCommon_init(env); + * * 2) Use current thread JNIEnv or attach current thread to JVM, generating new JNIEnv * + + int asDaemon = 0; int shallBeDetached = 0; - JNIEnv* env = NewtCommon_GetJNIEnv(&shallBeDetached); + JNIEnv* env = JoglCommon_GetJNIEnv(asDaemon, &shallBeDetached); if(NULL==env) { DBG_PRINT("drawRect: null JNIEnv\n"); return; @@ -41,11 +64,13 @@ void JoglCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...); .. your JNIEnv code here .. * - * 4) Detach thread from JVM, if required + * 4) Detach thread from JVM if required, i.e. not attached as daemon! + * Not recommended for recurring _daemon_ threads (performance) * - JoglCommon_ReleaseJNIEnv (shallBeDetached); + JoglCommon_ReleaseJNIEnv(shallBeDetached); */ -JNIEnv* JoglCommon_GetJNIEnv (int * shallBeDetached); +JNIEnv* JoglCommon_GetJNIEnv (int asDaemon, int * shallBeDetached); + void JoglCommon_ReleaseJNIEnv (int shallBeDetached); #endif diff --git a/src/jogl/native/libav/ffmpeg_impl_template.c b/src/jogl/native/libav/ffmpeg_impl_template.c index 44acfe46a..e86b2a542 100644 --- a/src/jogl/native/libav/ffmpeg_impl_template.c +++ b/src/jogl/native/libav/ffmpeg_impl_template.c @@ -1499,7 +1499,7 @@ JNIEXPORT jint JNICALL FF_FUNC(seek0) int64_t pts1 = (int64_t) (pos1 * (int64_t) time_base.den) / (1000 * (int64_t) time_base.num); if(pAV->verbose) { - fprintf(stderr, "SEEK: vid %d, aid %d, pos0 %d, pos1 %d, pts: %"PRId64" -> %"PRId64"\n", pAV->vid, pAV->aid, pos0, pos1, pts0, pts1); + fprintf(stderr, "SEEK: vid %d, aid %d, pos0 %"PRId64", pos1 %d, pts: %"PRId64" -> %"PRId64"\n", pAV->vid, pAV->aid, pos0, pos1, pts0, pts1); } int flags = 0; if(pos1 < pos0) { @@ -1508,7 +1508,7 @@ JNIEXPORT jint JNICALL FF_FUNC(seek0) int res = -2; if(HAS_FUNC(sp_av_seek_frame)) { if(pAV->verbose) { - fprintf(stderr, "SEEK.0: pre : s %d / %"PRId64" -> t %d / %"PRId64"\n", pos0, pts0, pos1, pts1); + fprintf(stderr, "SEEK.0: pre : s %"PRId64" / %"PRId64" -> t %d / %"PRId64"\n", pos0, pts0, pos1, pts1); } sp_av_seek_frame(pAV->pFormatCtx, streamID, pts1, flags); } else if(HAS_FUNC(sp_avformat_seek_file)) { diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m index 75917d2dc..7ce8c58cf 100644 --- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m +++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-calayer.m @@ -578,6 +578,7 @@ static const GLfloat gl_verts[] = { quirks, dedicatedFramePosSet, dedicatedFrameSizeSet, dedicatedLayoutSet, self, texWidth, texHeight, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, dFrame.origin.x, dFrame.origin.y, dFrame.size.width, dFrame.size.height); + (void)lRect; // silence if( dedicatedFrameSet ) { [super setFrame: dedicatedFrame]; diff --git a/src/jogl/native/openmax/jogamp_opengl_util_av_impl_OMXGLMediaPlayer.c b/src/jogl/native/openmax/jogamp_opengl_util_av_impl_OMXGLMediaPlayer.c index ec68a24aa..3166306ba 100644 --- a/src/jogl/native/openmax/jogamp_opengl_util_av_impl_OMXGLMediaPlayer.c +++ b/src/jogl/native/openmax/jogamp_opengl_util_av_impl_OMXGLMediaPlayer.c @@ -67,7 +67,7 @@ void OMXInstance_UpdateJavaAttributes(OMXToolBasicAV_t *pAV) return; } int shallBeDetached = 0; - JNIEnv * env = JoglCommon_GetJNIEnv (&shallBeDetached); + JNIEnv * env = JoglCommon_GetJNIEnv (1 /* daemon */, &shallBeDetached); if(NULL!=env) { (*env)->CallVoidMethod(env, (jobject)pAV->jni_instance, jni_mid_updateAttributes, pAV->width, pAV->height, @@ -75,7 +75,8 @@ void OMXInstance_UpdateJavaAttributes(OMXToolBasicAV_t *pAV) pAV->framerate, (uint32_t)(pAV->length*pAV->framerate), pAV->length, (*env)->NewStringUTF(env, pAV->videoCodec), (*env)->NewStringUTF(env, pAV->audioCodec) ); - JoglCommon_ReleaseJNIEnv (shallBeDetached); + // detaching thread not required - daemon + // JoglCommon_ReleaseJNIEnv(shallBeDetached); } } diff --git a/src/nativewindow/native/NativewindowCommon.c b/src/nativewindow/native/NativewindowCommon.c index ec7ee7728..e65f87272 100644 --- a/src/nativewindow/native/NativewindowCommon.c +++ b/src/nativewindow/native/NativewindowCommon.c @@ -8,41 +8,24 @@ static const char * const ClazzNameRuntimeException = "java/lang/RuntimeException"; static jclass runtimeExceptionClz=NULL; -void NativewindowCommon_FatalError(JNIEnv *env, const char* msg, ...) -{ - char buffer[512]; - va_list ap; - - va_start(ap, msg); - vsnprintf(buffer, sizeof(buffer), msg, ap); - va_end(ap); - - fprintf(stderr, "%s\n", buffer); - (*env)->FatalError(env, buffer); -} - -void NativewindowCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...) -{ - char buffer[512]; - va_list ap; - - va_start(ap, msg); - vsnprintf(buffer, sizeof(buffer), msg, ap); - va_end(ap); - - (*env)->ThrowNew(env, runtimeExceptionClz, buffer); -} +static JavaVM *_jvmHandle = NULL; +static int _jvmVersion = 0; int NativewindowCommon_init(JNIEnv *env) { - if(NULL==runtimeExceptionClz) { + if(NULL==_jvmHandle) { + if(0 != (*env)->GetJavaVM(env, &_jvmHandle)) { + NativewindowCommon_FatalError(env, "Nativewindow: Can't fetch JavaVM handle"); + } else { + _jvmVersion = (*env)->GetVersion(env); + } jclass c = (*env)->FindClass(env, ClazzNameRuntimeException); if(NULL==c) { - NativewindowCommon_FatalError(env, "Nativewindow: can't find %s", ClazzNameRuntimeException); + NativewindowCommon_FatalError(env, "Nativewindow: Can't find %s", ClazzNameRuntimeException); } runtimeExceptionClz = (jclass)(*env)->NewGlobalRef(env, c); (*env)->DeleteLocalRef(env, c); if(NULL==runtimeExceptionClz) { - NativewindowCommon_FatalError(env, "Nativewindow: can't use %s", ClazzNameRuntimeException); + NativewindowCommon_FatalError(env, "Nativewindow: Can't use %s", ClazzNameRuntimeException); } #ifdef STDERR_TO_FILE FILE * old_stderr = stderr; @@ -54,6 +37,44 @@ int NativewindowCommon_init(JNIEnv *env) { return 0; } +void NativewindowCommon_FatalError(JNIEnv *env, const char* msg, ...) +{ + char buffer[512]; + va_list ap; + + if( NULL != msg ) { + va_start(ap, msg); + vsnprintf(buffer, sizeof(buffer), msg, ap); + va_end(ap); + + fprintf(stderr, "%s\n", buffer); + if(NULL != env) { + (*env)->FatalError(env, buffer); + } + } +} + +void NativewindowCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...) +{ + char buffer[512]; + va_list ap; + + if(NULL==_jvmHandle) { + NativewindowCommon_FatalError(env, "Nativewindow: NULL JVM handle, call NativewindowCommon_init 1st\n"); + return; + } + + if( NULL != msg ) { + va_start(ap, msg); + vsnprintf(buffer, sizeof(buffer), msg, ap); + va_end(ap); + + if(NULL != env) { + (*env)->ThrowNew(env, runtimeExceptionClz, buffer); + } + } +} + const char * NativewindowCommon_GetStaticStringMethod(JNIEnv *jniEnv, jclass clazz, jmethodID jGetStrID, char *dest, int destSize, const char *altText) { if(NULL != jniEnv && NULL != clazz && NULL != jGetStrID) { jstring jstr = (jstring) (*jniEnv)->CallStaticObjectMethod(jniEnv, clazz, jGetStrID); @@ -75,45 +96,60 @@ const char * NativewindowCommon_GetStaticStringMethod(JNIEnv *jniEnv, jclass cla jchar* NativewindowCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str) { jchar* strChars = NULL; - strChars = calloc((*env)->GetStringLength(env, str) + 1, sizeof(jchar)); - if (strChars != NULL) { - (*env)->GetStringRegion(env, str, 0, (*env)->GetStringLength(env, str), strChars); + if( NULL != env && 0 != str ) { + strChars = calloc((*env)->GetStringLength(env, str) + 1, sizeof(jchar)); + if (strChars != NULL) { + (*env)->GetStringRegion(env, str, 0, (*env)->GetStringLength(env, str), strChars); + } } return strChars; } -JNIEnv* NativewindowCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int asDaemon, int * shallBeDetached) { +JNIEnv* NativewindowCommon_GetJNIEnv (int asDaemon, int * shallBeDetached) { JNIEnv* curEnv = NULL; JNIEnv* newEnv = NULL; int envRes; + if(NULL==_jvmHandle) { + fprintf(stderr, "Nativewindow GetJNIEnv: NULL JVM handle, call NativewindowCommon_init 1st\n"); + return NULL; + } + // retrieve this thread's JNIEnv curEnv - or detect it's detached - envRes = (*jvmHandle)->GetEnv(jvmHandle, (void **) &curEnv, jvmVersion) ; + envRes = (*_jvmHandle)->GetEnv(_jvmHandle, (void **) &curEnv, _jvmVersion) ; if( JNI_EDETACHED == envRes ) { // detached thread - attach to JVM if( asDaemon ) { - envRes = (*jvmHandle)->AttachCurrentThreadAsDaemon(jvmHandle, (void**) &newEnv, NULL); + envRes = (*_jvmHandle)->AttachCurrentThreadAsDaemon(_jvmHandle, (void**) &newEnv, NULL); } else { - envRes = (*jvmHandle)->AttachCurrentThread(jvmHandle, (void**) &newEnv, NULL); + envRes = (*_jvmHandle)->AttachCurrentThread(_jvmHandle, (void**) &newEnv, NULL); } if( JNI_OK != envRes ) { - fprintf(stderr, "JNIEnv: can't attach thread: %d\n", envRes); + fprintf(stderr, "Nativewindow GetJNIEnv: Can't attach thread: %d\n", envRes); return NULL; } curEnv = newEnv; } else if( JNI_OK != envRes ) { // oops .. - fprintf(stderr, "can't GetEnv: %d\n", envRes); + fprintf(stderr, "Nativewindow GetJNIEnv: Can't GetEnv: %d\n", envRes); return NULL; } if (curEnv==NULL) { - fprintf(stderr, "env is NULL\n"); + fprintf(stderr, "Nativewindow GetJNIEnv: env is NULL\n"); return NULL; } *shallBeDetached = NULL != newEnv; return curEnv; } +void NativewindowCommon_ReleaseJNIEnv (int shallBeDetached) { + if(NULL == _jvmHandle) { + fprintf(stderr, "Nativewindow ReleaseJNIEnv: No JavaVM handle registered, call NativewindowCommon_init(..) 1st"); + } else if(shallBeDetached) { + (*_jvmHandle)->DetachCurrentThread(_jvmHandle); + } +} + int64_t NativewindowCommon_CurrentTimeMillis() { struct timeval tv; gettimeofday(&tv,NULL); diff --git a/src/nativewindow/native/NativewindowCommon.h b/src/nativewindow/native/NativewindowCommon.h index a23fad9fd..f19552e33 100644 --- a/src/nativewindow/native/NativewindowCommon.h +++ b/src/nativewindow/native/NativewindowCommon.h @@ -1,3 +1,30 @@ +/** + * Copyright 2011 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: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of JogAmp Community. + */ #ifndef NATIVEWINDOW_COMMON_H #define NATIVEWINDOW_COMMON_H 1 @@ -14,7 +41,39 @@ jchar* NativewindowCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str) void NativewindowCommon_FatalError(JNIEnv *env, const char* msg, ...); void NativewindowCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...); -JNIEnv* NativewindowCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int asDaemon, int * shallBeDetached); +/** + * + * 1) Init static jvmHandle, jvmVersion and clazz references + * from an early initialization call w/ valid 'JNIEnv * env' + + NativewindowCommon_init(env); + + * + * 2) Use current thread JNIEnv or attach current thread to JVM, generating new JNIEnv + * + + int asDaemon = 0; + int shallBeDetached = 0; + JNIEnv* env = NewtCommon_GetJNIEnv(asDaemon, &shallBeDetached); + if(NULL==env) { + DBG_PRINT("drawRect: null JNIEnv\n"); + return; + } + + * + * 3) Use JNIEnv .. + * + .. your JNIEnv code here .. + + * + * 4) Detach thread from JVM if required, i.e. not attached as daemon! + * Not recommended for recurring _daemon_ threads (performance) + * + NewtCommon_ReleaseJNIEnv(shallBeDetached); + */ +JNIEnv* NativewindowCommon_GetJNIEnv (int asDaemon, int * shallBeDetached); + +void NativewindowCommon_ReleaseJNIEnv (int shallBeDetached); int64_t NativewindowCommon_CurrentTimeMillis(); diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 6a7952eaf..4887cc3cf 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -75,11 +75,9 @@ static const char * const ClazzNameInsetsCstrSignature = "(IIII)V"; static jclass insetsClz = NULL; static jmethodID insetsCstr = NULL; -static int _initialized=0; - JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_initIDs0(JNIEnv *env, jclass _unused) { - if(0==_initialized) { + if( NativewindowCommon_init(env) ) { jclass c; c = (*env)->FindClass(env, ClazzNamePoint); if(NULL==c) { @@ -119,7 +117,6 @@ Java_jogamp_nativewindow_macosx_OSXUtil_initIDs0(JNIEnv *env, jclass _unused) { if(NULL==runnableRunID) { NativewindowCommon_FatalError(env, "FatalError Java_jogamp_newt_driver_macosx_MacWindow_initIDs0: can't fetch %s.run()V", ClazzNameRunnable); } - _initialized=1; } return JNI_TRUE; } @@ -775,12 +772,10 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Uns @interface MainRunnable : NSObject { - JavaVM *jvmHandle; - int jvmVersion; jobject runnableObj; } -- (id) initWithRunnable: (jobject)runnable jvmHandle: (JavaVM*)jvm jvmVersion: (int)jvmVers; +- (id) initWithRunnable: (jobject)runnable; - (void) jRun; #ifdef DBG_LIFECYCLE @@ -794,10 +789,8 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Uns @implementation MainRunnable -- (id) initWithRunnable: (jobject)runnable jvmHandle: (JavaVM*)jvm jvmVersion: (int)jvmVers +- (id) initWithRunnable: (jobject)runnable { - jvmHandle = jvm; - jvmVersion = jvmVers; runnableObj = runnable; return [super init]; } @@ -805,7 +798,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Uns - (void) jRun { int shallBeDetached = 0; - JNIEnv* env = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, 1 /* asDaemon */, &shallBeDetached); + JNIEnv* env = NativewindowCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached); DBG_PRINT2("MainRunnable.1 env: %d\n", (int)(NULL!=env)); if(NULL!=env) { DBG_PRINT2("MainRunnable.1.0\n"); @@ -813,11 +806,9 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_Uns DBG_PRINT2("MainRunnable.1.1\n"); (*env)->DeleteGlobalRef(env, runnableObj); - if (shallBeDetached) { - DBG_PRINT2("MainRunnable.1.3\n"); - // Keep attached on main thread ! - // (*jvmHandle)->DetachCurrentThread(jvmHandle); - } + DBG_PRINT2("MainRunnable.1.3\n"); + // detaching thread not required - daemon + // NativewindowCommon_ReleaseJNIEnv(shallBeDetached); } DBG_PRINT2("MainRunnable.X\n"); } @@ -861,17 +852,8 @@ static void RunOnThread (JNIEnv *env, jobject runnable, BOOL onMain, jint delayI if ( forkOnMain ) { jobject runnableObj = (*env)->NewGlobalRef(env, runnable); - JavaVM *jvmHandle = NULL; - int jvmVersion = 0; - - if(0 != (*env)->GetJavaVM(env, &jvmHandle)) { - jvmHandle = NULL; - } else { - jvmVersion = (*env)->GetVersion(env); - } - DBG_PRINT2( "RunOnThread.1.0\n"); - MainRunnable * mr = [[MainRunnable alloc] initWithRunnable: runnableObj jvmHandle: jvmHandle jvmVersion: jvmVersion]; + MainRunnable * mr = [[MainRunnable alloc] initWithRunnable: runnableObj]; if( onMain ) { [mr performSelectorOnMainThread:@selector(jRun) withObject:nil waitUntilDone:NO]; diff --git a/src/nativewindow/native/win32/GDImisc.c b/src/nativewindow/native/win32/GDImisc.c index e28f68e7d..bec1d4922 100644 --- a/src/nativewindow/native/win32/GDImisc.c +++ b/src/nativewindow/native/win32/GDImisc.c @@ -487,7 +487,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_DestroyWindo JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_windows_GDIUtil_initIDs0 (JNIEnv *env, jclass gdiClazz) { - if(NativewindowCommon_init(env)) { + if( NativewindowCommon_init(env) ) { jclass c = (*env)->FindClass(env, ClazzNamePoint); if(NULL==c) { NativewindowCommon_FatalError(env, "FatalError jogamp_nativewindow_windows_GDIUtil: can't find %s", ClazzNamePoint); diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c index 5e6909f6e..247dc1311 100644 --- a/src/nativewindow/native/x11/Xmisc.c +++ b/src/nativewindow/native/x11/Xmisc.c @@ -113,68 +113,56 @@ static jmethodID pointCstr = NULL; static void _initClazzAccess(JNIEnv *env) { jclass c; - if(!NativewindowCommon_init(env)) return; - - getCurrentThreadNameID = (*env)->GetStaticMethodID(env, X11UtilClazz, "getCurrentThreadName", "()Ljava/lang/String;"); - if(NULL==getCurrentThreadNameID) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't get method getCurrentThreadName"); - } - dumpStackID = (*env)->GetStaticMethodID(env, X11UtilClazz, "dumpStack", "()V"); - if(NULL==dumpStackID) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't get method dumpStack"); - } - - c = (*env)->FindClass(env, ClazzNameBuffers); - if(NULL==c) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNameBuffers); - } - clazzBuffers = (jclass)(*env)->NewGlobalRef(env, c); - (*env)->DeleteLocalRef(env, c); - if(NULL==clazzBuffers) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNameBuffers); - } - c = (*env)->FindClass(env, ClazzNameByteBuffer); - if(NULL==c) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNameByteBuffer); - } - clazzByteBuffer = (jclass)(*env)->NewGlobalRef(env, c); - (*env)->DeleteLocalRef(env, c); - if(NULL==c) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNameByteBuffer); - } - - cstrBuffers = (*env)->GetStaticMethodID(env, clazzBuffers, - ClazzNameBuffersStaticCstrName, ClazzNameBuffersStaticCstrSignature); - if(NULL==cstrBuffers) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't create %s.%s %s", - ClazzNameBuffers, ClazzNameBuffersStaticCstrName, ClazzNameBuffersStaticCstrSignature); - } + if( NativewindowCommon_init(env) ) { + getCurrentThreadNameID = (*env)->GetStaticMethodID(env, X11UtilClazz, "getCurrentThreadName", "()Ljava/lang/String;"); + if(NULL==getCurrentThreadNameID) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't get method getCurrentThreadName"); + } + dumpStackID = (*env)->GetStaticMethodID(env, X11UtilClazz, "dumpStack", "()V"); + if(NULL==dumpStackID) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't get method dumpStack"); + } - c = (*env)->FindClass(env, ClazzNamePoint); - if(NULL==c) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNamePoint); - } - pointClz = (jclass)(*env)->NewGlobalRef(env, c); - (*env)->DeleteLocalRef(env, c); - if(NULL==pointClz) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNamePoint); - } - pointCstr = (*env)->GetMethodID(env, pointClz, ClazzAnyCstrName, ClazzNamePointCstrSignature); - if(NULL==pointCstr) { - NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't fetch %s.%s %s", - ClazzNamePoint, ClazzAnyCstrName, ClazzNamePointCstrSignature); - } -} + c = (*env)->FindClass(env, ClazzNameBuffers); + if(NULL==c) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNameBuffers); + } + clazzBuffers = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==clazzBuffers) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNameBuffers); + } + c = (*env)->FindClass(env, ClazzNameByteBuffer); + if(NULL==c) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNameByteBuffer); + } + clazzByteBuffer = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==c) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNameByteBuffer); + } -static JavaVM *jvmHandle = NULL; -static int jvmVersion = 0; + cstrBuffers = (*env)->GetStaticMethodID(env, clazzBuffers, + ClazzNameBuffersStaticCstrName, ClazzNameBuffersStaticCstrSignature); + if(NULL==cstrBuffers) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't create %s.%s %s", + ClazzNameBuffers, ClazzNameBuffersStaticCstrName, ClazzNameBuffersStaticCstrSignature); + } -static void setupJVMVars(JNIEnv * env) { - if( NULL != env && NULL == jvmHandle ) { - if(0 != (*env)->GetJavaVM(env, &jvmHandle)) { - jvmHandle = NULL; + c = (*env)->FindClass(env, ClazzNamePoint); + if(NULL==c) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't find %s", ClazzNamePoint); + } + pointClz = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==pointClz) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't use %s", ClazzNamePoint); + } + pointCstr = (*env)->GetMethodID(env, pointClz, ClazzAnyCstrName, ClazzNamePointCstrSignature); + if(NULL==pointCstr) { + NativewindowCommon_FatalError(env, "FatalError Java_jogamp_nativewindow_x11_X11Lib: can't fetch %s.%s %s", + ClazzNamePoint, ClazzAnyCstrName, ClazzNamePointCstrSignature); } - jvmVersion = (*env)->GetVersion(env); } } @@ -201,8 +189,8 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) (int)e->request_code, (int)e->minor_code, reqCodeStr); fflush(stderr); - if( NULL != jvmHandle && ( errorHandlerDebug || errorHandlerThrowException ) ) { - jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, 0 /* asDaemon */, &shallBeDetached); + if( errorHandlerDebug || errorHandlerThrowException ) { + jniEnv = NativewindowCommon_GetJNIEnv(0 /* asDaemon */, &shallBeDetached); if(NULL == jniEnv) { fprintf(stderr, "Nativewindow X11 Error: null JNIEnv"); fflush(stderr); @@ -219,9 +207,7 @@ static int x11ErrorHandler(Display *dpy, XErrorEvent *e) e->error_code, errCodeStr, e->display, (int)e->resourceid, (int)e->serial, (int)e->request_code, (int)e->minor_code, reqCodeStr); } - if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } + NativewindowCommon_ReleaseJNIEnv(shallBeDetached); } } @@ -233,7 +219,6 @@ static void NativewindowCommon_x11ErrorHandlerEnable(JNIEnv * env, Display *dpy, if(onoff) { if(force || NULL==origErrorHandler) { XErrorHandler prevErrorHandler; - setupJVMVars(env); prevErrorHandler = XSetErrorHandler(x11ErrorHandler); if(x11ErrorHandler != prevErrorHandler) { // if forced don't overwrite w/ orig w/ our handler origErrorHandler = prevErrorHandler; @@ -265,14 +250,10 @@ static int x11IOErrorHandler(Display *dpy) fprintf(stderr, "Nativewindow X11 IOError: Display %p (%s): %s\n", dpy, dpyName, errnoStr); fflush(stderr); - if( NULL != jvmHandle ) { - jniEnv = NativewindowCommon_GetJNIEnv(jvmHandle, jvmVersion, 0 /* asDaemon */, &shallBeDetached); - if (NULL != jniEnv) { - NativewindowCommon_FatalError(jniEnv, "Nativewindow X11 IOError: Display %p (%s): %s", dpy, dpyName, errnoStr); - if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } - } + jniEnv = NativewindowCommon_GetJNIEnv(0 /* asDaemon */, &shallBeDetached); + if (NULL != jniEnv) { + NativewindowCommon_FatalError(jniEnv, "Nativewindow X11 IOError: Display %p (%s): %s", dpy, dpyName, errnoStr); + NativewindowCommon_ReleaseJNIEnv(shallBeDetached); } if(NULL!=origIOErrorHandler) { origIOErrorHandler(dpy); @@ -283,7 +264,6 @@ static int x11IOErrorHandler(Display *dpy) static void x11IOErrorHandlerEnable(int onoff, JNIEnv * env) { if(onoff) { if(NULL==origIOErrorHandler) { - setupJVMVars(env); origIOErrorHandler = XSetIOErrorHandler(x11IOErrorHandler); } } else { diff --git a/src/newt/native/MacWindow.m b/src/newt/native/MacWindow.m index c6fd805a5..130b2e3e3 100644 --- a/src/newt/native/MacWindow.m +++ b/src/newt/native/MacWindow.m @@ -113,18 +113,6 @@ static void setJavaWindowObject(JNIEnv *env, jobject newJavaWindowObject, NewtVi DBG_PRINT( "setJavaWindowObject.2: View %p - Set new javaWindowObject %p\n", view, newJavaWindowObject); jobject globJavaWindowObject = (*env)->NewGlobalRef(env, newJavaWindowObject); [view setJavaWindowObject: globJavaWindowObject]; - { - JavaVM *jvmHandle = NULL; - int jvmVersion = 0; - - if(0 != (*env)->GetJavaVM(env, &jvmHandle)) { - jvmHandle = NULL; - } else { - jvmVersion = (*env)->GetVersion(env); - } - [view setJVMHandle: jvmHandle]; - [view setJVMVersion: jvmVersion]; - } } DBG_PRINT( "setJavaWindowObject.X: View %p\n", view); } @@ -979,6 +967,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_WindowDriver_close0 BOOL isNewtWin = [mWin isKindOfClass:[NewtMacWindow class]]; NSWindow *pWin = [mWin parentWindow]; DBG_PRINT( "windowClose.0 - %p [isNSWindow %d, isNewtWin %d], parent %p\n", mWin, isNSWin, isNewtWin, pWin); + (void)isNSWin; // silence if( !isNewtWin ) { NewtCommon_throwNewRuntimeException(env, "Not a NewtMacWindow %p", mWin); return; diff --git a/src/newt/native/NewtCommon.c b/src/newt/native/NewtCommon.c index c294b6e0b..231d6182f 100644 --- a/src/newt/native/NewtCommon.c +++ b/src/newt/native/NewtCommon.c @@ -5,17 +5,43 @@ static const char * const ClazzNameRuntimeException = "java/lang/RuntimeException"; static jclass runtimeExceptionClz=NULL; +static JavaVM *_jvmHandle = NULL; +static int _jvmVersion = 0; + +void NewtCommon_init(JNIEnv *env) { + if(NULL==_jvmHandle) { + if(0 != (*env)->GetJavaVM(env, &_jvmHandle)) { + NewtCommon_FatalError(env, "NEWT: Can't fetch JavaVM handle"); + } else { + _jvmVersion = (*env)->GetVersion(env); + } + jclass c = (*env)->FindClass(env, ClazzNameRuntimeException); + if(NULL==c) { + NewtCommon_FatalError(env, "NEWT: Can't find %s", ClazzNameRuntimeException); + } + runtimeExceptionClz = (jclass)(*env)->NewGlobalRef(env, c); + (*env)->DeleteLocalRef(env, c); + if(NULL==runtimeExceptionClz) { + NewtCommon_FatalError(env, "NEWT: Can't use %s", ClazzNameRuntimeException); + } + } +} + void NewtCommon_FatalError(JNIEnv *env, const char* msg, ...) { char buffer[512]; va_list ap; - va_start(ap, msg); - vsnprintf(buffer, sizeof(buffer), msg, ap); - va_end(ap); + if( NULL != msg ) { + va_start(ap, msg); + vsnprintf(buffer, sizeof(buffer), msg, ap); + va_end(ap); - fprintf(stderr, "%s\n", buffer); - (*env)->FatalError(env, buffer); + fprintf(stderr, "%s\n", buffer); + if(NULL != env) { + (*env)->FatalError(env, buffer); + } + } } void NewtCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...) @@ -23,23 +49,18 @@ void NewtCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...) char buffer[512]; va_list ap; - va_start(ap, msg); - vsnprintf(buffer, sizeof(buffer), msg, ap); - va_end(ap); + if(NULL==_jvmHandle) { + NewtCommon_FatalError(env, "NEWT: NULL JVM handle, call NewtCommon_init 1st\n"); + return; + } - (*env)->ThrowNew(env, runtimeExceptionClz, buffer); -} + if( NULL != msg ) { + va_start(ap, msg); + vsnprintf(buffer, sizeof(buffer), msg, ap); + va_end(ap); -void NewtCommon_init(JNIEnv *env) { - if(NULL==runtimeExceptionClz) { - jclass c = (*env)->FindClass(env, ClazzNameRuntimeException); - if(NULL==c) { - NewtCommon_FatalError(env, "NEWT: can't find %s", ClazzNameRuntimeException); - } - runtimeExceptionClz = (jclass)(*env)->NewGlobalRef(env, c); - (*env)->DeleteLocalRef(env, c); - if(NULL==runtimeExceptionClz) { - NewtCommon_FatalError(env, "NEWT: can't use %s", ClazzNameRuntimeException); + if(NULL != env) { + (*env)->ThrowNew(env, runtimeExceptionClz, buffer); } } } @@ -65,42 +86,57 @@ const char * NewtCommon_GetStaticStringMethod(JNIEnv *jniEnv, jclass clazz, jmet jchar* NewtCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str) { jchar* strChars = NULL; - strChars = calloc((*env)->GetStringLength(env, str) + 1, sizeof(jchar)); - if (strChars != NULL) { - (*env)->GetStringRegion(env, str, 0, (*env)->GetStringLength(env, str), strChars); + if( NULL != env && 0 != str ) { + strChars = calloc((*env)->GetStringLength(env, str) + 1, sizeof(jchar)); + if (strChars != NULL) { + (*env)->GetStringRegion(env, str, 0, (*env)->GetStringLength(env, str), strChars); + } } return strChars; } -JNIEnv* NewtCommon_GetJNIEnv(JavaVM * jvmHandle, int jvmVersion, int asDaemon, int * shallBeDetached) { +JNIEnv* NewtCommon_GetJNIEnv(int asDaemon, int * shallBeDetached) { JNIEnv* curEnv = NULL; JNIEnv* newEnv = NULL; int envRes; + if(NULL==_jvmHandle) { + fprintf(stderr, "NEWT GetJNIEnv: NULL JVM handle, call NewtCommon_init 1st\n"); + return NULL; + } + // retrieve this thread's JNIEnv curEnv - or detect it's detached - envRes = (*jvmHandle)->GetEnv(jvmHandle, (void **) &curEnv, jvmVersion) ; + envRes = (*_jvmHandle)->GetEnv(_jvmHandle, (void **) &curEnv, _jvmVersion) ; if( JNI_EDETACHED == envRes ) { // detached thread - attach to JVM if( asDaemon ) { - envRes = (*jvmHandle)->AttachCurrentThreadAsDaemon(jvmHandle, (void**) &newEnv, NULL); + envRes = (*_jvmHandle)->AttachCurrentThreadAsDaemon(_jvmHandle, (void**) &newEnv, NULL); } else { - envRes = (*jvmHandle)->AttachCurrentThread(jvmHandle, (void**) &newEnv, NULL); + envRes = (*_jvmHandle)->AttachCurrentThread(_jvmHandle, (void**) &newEnv, NULL); } if( JNI_OK != envRes ) { - fprintf(stderr, "JNIEnv: can't attach thread: %d\n", envRes); + fprintf(stderr, "NEWT GetJNIEnv: Can't attach thread: %d\n", envRes); return NULL; } curEnv = newEnv; } else if( JNI_OK != envRes ) { // oops .. - fprintf(stderr, "can't GetEnv: %d\n", envRes); + fprintf(stderr, "NEWT GetJNIEnv: Can't GetEnv: %d\n", envRes); return NULL; } if (curEnv==NULL) { - fprintf(stderr, "env is NULL\n"); + fprintf(stderr, "NEWT GetJNIEnv: env is NULL\n"); return NULL; } *shallBeDetached = NULL != newEnv; return curEnv; } +void NewtCommon_ReleaseJNIEnv (int shallBeDetached) { + if(NULL == _jvmHandle) { + fprintf(stderr, "NEWT ReleaseJNIEnv: No JavaVM handle registered, call NewtCommon_init(..) 1st"); + } else if(shallBeDetached) { + (*_jvmHandle)->DetachCurrentThread(_jvmHandle); + } +} + diff --git a/src/newt/native/NewtCommon.h b/src/newt/native/NewtCommon.h index 9cc9e93a6..43db72b5b 100644 --- a/src/newt/native/NewtCommon.h +++ b/src/newt/native/NewtCommon.h @@ -42,23 +42,18 @@ void NewtCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...); /** * - * 1) Store jvmHandle and jvmVersion + * 1) Init static jvmHandle, jvmVersion and clazz references + * from an early initialization call w/ valid 'JNIEnv * env' - JavaVM *jvmHandle = NULL; - int jvmVersion = 0; - - if(0 != (*env)->GetJavaVM(env, &jvmHandle)) { - jvmHandle = NULL; - } else { - jvmVersion = (*env)->GetVersion(env); - } + NewtCommon_init(env); * * 2) Use current thread JNIEnv or attach current thread to JVM, generating new JNIEnv * + int asDaemon = 0; int shallBeDetached = 0; - JNIEnv* env = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached); + JNIEnv* env = NewtCommon_GetJNIEnv(asDaemon, &shallBeDetached); if(NULL==env) { DBG_PRINT("drawRect: null JNIEnv\n"); return; @@ -70,12 +65,13 @@ void NewtCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...); .. your JNIEnv code here .. * - * 4) Detach thread from JVM, if required + * 4) Detach thread from JVM if required, i.e. not attached as daemon! + * Not recommended for recurring _daemon_ threads (performance) * - if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } + NativewindowCommon_ReleaseJNIEnv(shallBeDetached); */ -JNIEnv* NewtCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int asDaemon, int * shallBeDetached); +JNIEnv* NewtCommon_GetJNIEnv (int asDaemon, int * shallBeDetached); + +void NewtCommon_ReleaseJNIEnv (int shallBeDetached); #endif diff --git a/src/newt/native/NewtMacWindow.h b/src/newt/native/NewtMacWindow.h index daf75bec7..8f6362ac2 100644 --- a/src/newt/native/NewtMacWindow.h +++ b/src/newt/native/NewtMacWindow.h @@ -53,10 +53,6 @@ { jobject javaWindowObject; - // This is set while messages are being dispatched and cleared afterward - JavaVM *jvmHandle; - int jvmVersion; - volatile BOOL destroyNotifySent; volatile int softLockCount; pthread_mutex_t softLockSync; @@ -80,12 +76,6 @@ #endif - (void) dealloc; -/* Set during event dispatching cycle */ -- (void) setJVMHandle: (JavaVM*) vm; -- (JavaVM*) getJVMHandle; -- (void) setJVMVersion: (int) ver; -- (int) getJVMVersion; - /* Register or deregister (NULL) the java Window object, ie, if NULL, no events are send */ - (void) setJavaWindowObject: (jobject) javaWindowObj; diff --git a/src/newt/native/NewtMacWindow.m b/src/newt/native/NewtMacWindow.m index 5ccd9c658..b4133ac7e 100644 --- a/src/newt/native/NewtMacWindow.m +++ b/src/newt/native/NewtMacWindow.m @@ -193,8 +193,6 @@ static jmethodID windowRepaintID = NULL; id res = [super initWithFrame:frameRect]; javaWindowObject = NULL; - jvmHandle = NULL; - jvmVersion = 0; destroyNotifySent = NO; softLockCount = 0; @@ -244,25 +242,6 @@ static jmethodID windowRepaintID = NULL; [super dealloc]; } -- (void) setJVMHandle: (JavaVM*) vm -{ - jvmHandle = vm; -} -- (JavaVM*) getJVMHandle -{ - return jvmHandle; -} - -- (void) setJVMVersion: (int) ver -{ - jvmVersion = ver; -} - -- (int) getJVMVersion -{ - return jvmVersion; -} - - (void) setJavaWindowObject: (jobject) javaWindowObj { javaWindowObject = javaWindowObj; @@ -342,7 +321,7 @@ static jmethodID windowRepaintID = NULL; return; } int shallBeDetached = 0; - JNIEnv* env = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, 1 /* asDaemon */, &shallBeDetached); + JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached); if(NULL==env) { DBG_PRINT("drawRect: null JNIEnv\n"); return; @@ -354,9 +333,8 @@ static jmethodID windowRepaintID = NULL; dirtyRect.origin.x, viewFrame.size.height - dirtyRect.origin.y, dirtyRect.size.width, dirtyRect.size.height); - /* if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } */ + // detaching thread not required - daemon + // NewtCommon_ReleaseJNIEnv(shallBeDetached); } - (void) viewDidHide @@ -366,7 +344,7 @@ static jmethodID windowRepaintID = NULL; return; } int shallBeDetached = 0; - JNIEnv* env = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, 1 /* asDaemon */, &shallBeDetached); + JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached); if(NULL==env) { DBG_PRINT("viewDidHide: null JNIEnv\n"); return; @@ -374,9 +352,8 @@ static jmethodID windowRepaintID = NULL; (*env)->CallVoidMethod(env, javaWindowObject, visibleChangedID, JNI_FALSE, JNI_FALSE); - /* if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } */ + // detaching thread not required - daemon + // NewtCommon_ReleaseJNIEnv(shallBeDetached); [super viewDidHide]; } @@ -388,7 +365,7 @@ static jmethodID windowRepaintID = NULL; return; } int shallBeDetached = 0; - JNIEnv* env = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, 1 /* asDaemon */, &shallBeDetached); + JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached); if(NULL==env) { DBG_PRINT("viewDidUnhide: null JNIEnv\n"); return; @@ -396,9 +373,8 @@ static jmethodID windowRepaintID = NULL; (*env)->CallVoidMethod(env, javaWindowObject, visibleChangedID, JNI_FALSE, JNI_TRUE); - /* if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } */ + // detaching thread not required - daemon + // NewtCommon_ReleaseJNIEnv(shallBeDetached); [super viewDidUnhide]; } @@ -645,14 +621,9 @@ static jmethodID windowRepaintID = NULL; return; } int shallBeDetached = 0; - JNIEnv* env; - if( NULL != jvmHandle ) { - env = NewtCommon_GetJNIEnv(jvmHandle, [self getJVMVersion], 1 /* asDaemon */, &shallBeDetached); - } else { - env = NULL; - } + JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached); if(NULL==env) { - DBG_PRINT("sendMouseEvent: JVM %p JNIEnv %p\n", jvmHandle, env); + DBG_PRINT("sendMouseEvent: null JNIEnv\n"); return; } jint javaMods[] = { 0 } ; @@ -700,9 +671,8 @@ static jmethodID windowRepaintID = NULL; (jint) location.x, (jint) location.y, javaButtonNum, scrollDeltaY); - /* if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } */ + // detaching thread not required - daemon + // NewtCommon_ReleaseJNIEnv(shallBeDetached); } - (NSPoint) screenPos2NewtClientWinPos: (NSPoint) p @@ -754,14 +724,9 @@ static jmethodID windowRepaintID = NULL; return; } int shallBeDetached = 0; - JNIEnv* env; - if( NULL != jvmHandle ) { - env = NewtCommon_GetJNIEnv(jvmHandle, [self getJVMVersion], 1 /* asDaemon */, &shallBeDetached); - } else { - env = NULL; - } + JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached); if(NULL==env) { - DBG_PRINT("sendKeyEvent: JVM %p JNIEnv %p\n", jvmHandle, env); + DBG_PRINT("sendKeyEvent: null JNIEnv\n"); return; } @@ -792,9 +757,8 @@ static jmethodID windowRepaintID = NULL; evType, javaMods, keyCode, keyChar, keyChar); } - /* if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } */ + // detaching thread not required - daemon + // NewtCommon_ReleaseJNIEnv(shallBeDetached); } @end @@ -1038,23 +1002,16 @@ static jmethodID windowRepaintID = NULL; return; } int shallBeDetached = 0; - JavaVM *jvmHandle = [newtView getJVMHandle]; - JNIEnv* env; - if( NULL != jvmHandle ) { - env = NewtCommon_GetJNIEnv(jvmHandle, [newtView getJVMVersion], 1 /* asDaemon */, &shallBeDetached); - } else { - env = NULL; - } + JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached); if(NULL==env) { - DBG_PRINT("focusChanged: JVM %p JNIEnv %p\n", jvmHandle, env); + DBG_PRINT("focusChanged: null JNIEnv\n"); return; } (*env)->CallVoidMethod(env, javaWindowObject, focusChangedID, JNI_FALSE, (gained == YES) ? JNI_TRUE : JNI_FALSE); - /* if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } */ + // detaching thread not required - daemon + // NewtCommon_ReleaseJNIEnv(shallBeDetached); } - (void) keyDown: (NSEvent*) theEvent @@ -1147,37 +1104,31 @@ static jmethodID windowRepaintID = NULL; - (void)windowDidResize: (NSNotification*) notification { - JNIEnv* env = NULL; jobject javaWindowObject = NULL; int shallBeDetached = 0; - JavaVM *jvmHandle = NULL; + JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached); + if( NULL == env ) { + DBG_PRINT("windowDidResize: null JNIEnv\n"); + return; + } NewtView* newtView = (NewtView *) [self contentView]; if( [newtView isKindOfClass:[NewtView class]] ) { javaWindowObject = [newtView getJavaWindowObject]; - if (javaWindowObject != NULL) { - jvmHandle = [newtView getJVMHandle]; - if( NULL != jvmHandle ) { - env = NewtCommon_GetJNIEnv(jvmHandle, [newtView getJVMVersion], 1 /* asDaemon */, &shallBeDetached); - } - } } + if( NULL != javaWindowObject ) { + // update insets on every window resize for lack of better hook place + [self updateInsets: env jwin:javaWindowObject]; - // update insets on every window resize for lack of better hook place - [self updateInsets: env jwin:javaWindowObject]; - - if( NULL != env && NULL != javaWindowObject ) { NSRect frameRect = [self frame]; NSRect contentRect = [self contentRectForFrameRect: frameRect]; (*env)->CallVoidMethod(env, javaWindowObject, sizeChangedID, JNI_FALSE, (jint) contentRect.size.width, (jint) contentRect.size.height, JNI_FALSE); - - /* if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } */ } + // detaching thread not required - daemon + // NewtCommon_ReleaseJNIEnv(shallBeDetached); } - (void)windowDidMove: (NSNotification*) notification @@ -1192,15 +1143,9 @@ static jmethodID windowRepaintID = NULL; return; } int shallBeDetached = 0; - JavaVM *jvmHandle = [newtView getJVMHandle]; - JNIEnv* env; - if( NULL != jvmHandle ) { - env = NewtCommon_GetJNIEnv(jvmHandle, [newtView getJVMVersion], 1 /* asDaemon */, &shallBeDetached); - } else { - env = NULL; - } + JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached); if(NULL==env) { - DBG_PRINT("windowDidMove: JVM %p JNIEnv %p\n", jvmHandle, env); + DBG_PRINT("windowDidMove: null JNIEnv\n"); return; } @@ -1208,9 +1153,8 @@ static jmethodID windowRepaintID = NULL; p0 = [self getLocationOnScreen: p0]; (*env)->CallVoidMethod(env, javaWindowObject, positionChangedID, JNI_FALSE, (jint) p0.x, (jint) p0.y); - /* if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } */ + // detaching thread not required - daemon + // NewtCommon_ReleaseJNIEnv(shallBeDetached); } - (BOOL)windowShouldClose: (id) sender @@ -1226,13 +1170,12 @@ static jmethodID windowRepaintID = NULL; - (BOOL) windowClosingImpl: (BOOL) force { jboolean closed = JNI_FALSE; - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; NewtView* newtView = (NewtView *) [self contentView]; if( ! [newtView isKindOfClass:[NewtView class]] ) { return NO; } - + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; [newtView cursorHide: NO enter: -1]; if( false == [newtView getDestroyNotifySent] ) { @@ -1240,26 +1183,16 @@ static jmethodID windowRepaintID = NULL; DBG_PRINT( "*************** windowWillClose.0: %p\n", (void *)(intptr_t)javaWindowObject); if (javaWindowObject == NULL) { DBG_PRINT("windowWillClose: null javaWindowObject\n"); + [pool release]; return NO; } int shallBeDetached = 0; - JavaVM *jvmHandle = [newtView getJVMHandle]; - JNIEnv* env = NULL; -NS_DURING - if( NULL != jvmHandle ) { - env = NewtCommon_GetJNIEnv(jvmHandle, [newtView getJVMVersion], 1 /* asDaemon */, &shallBeDetached); - } -NS_HANDLER - jvmHandle = NULL; - env = NULL; - [newtView setJVMHandle: NULL]; - DBG_PRINT("windowWillClose: JVMHandler Exception\n"); -NS_ENDHANDLER - DBG_PRINT("windowWillClose: JVM %p JNIEnv %p\n", jvmHandle, env); + JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached); if(NULL==env) { + DBG_PRINT("windowWillClose: null JNIEnv\n"); + [pool release]; return NO; } - [newtView setDestroyNotifySent: true]; // earmark assumption of being closed closed = (*env)->CallBooleanMethod(env, javaWindowObject, windowDestroyNotifyID, force ? JNI_TRUE : JNI_FALSE); if(!force && !closed) { @@ -1267,9 +1200,8 @@ NS_ENDHANDLER [newtView setDestroyNotifySent: false]; } - /* if (shallBeDetached) { - (*jvmHandle)->DetachCurrentThread(jvmHandle); - } */ + // detaching thread not required - daemon + // NewtCommon_ReleaseJNIEnv(shallBeDetached); DBG_PRINT( "*************** windowWillClose.X: %p, closed %d\n", (void *)(intptr_t)javaWindowObject, (int)closed); } else { DBG_PRINT( "*************** windowWillClose (skip)\n"); -- cgit v1.2.3 From 6ea03078e162eed89653ae123d172b6fca7c6d61 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sat, 11 Jan 2014 07:27:15 +0100 Subject: Misc Cleanup: JAWTWindow: Reusing visible in HIERARCHY listener; Remove obsolete 'getPrivateGraphicsConfiguration()' --- .../classes/jogamp/opengl/GLDrawableHelper.java | 10 ++++---- .../classes/jogamp/opengl/GLFBODrawableImpl.java | 4 ++-- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 27 ++++++++++------------ .../jogamp/nativewindow/ProxySurfaceImpl.java | 6 +---- src/newt/classes/jogamp/newt/WindowImpl.java | 7 ------ 5 files changed, 20 insertions(+), 34 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java index 61735c487..c0bf43d2c 100644 --- a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java +++ b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java @@ -336,7 +336,7 @@ public class GLDrawableHelper { } final NativeSurface ns = drawable.getNativeSurface(); final int lockRes = ns.lockSurface(); - if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { + if ( NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes ) { throw new NativeWindowException("Could not lock surface of drawable: "+drawable); } boolean validateSize = true; @@ -345,10 +345,10 @@ public class GLDrawableHelper { System.err.println("WARNING: Odd size detected: "+newWidth+"x"+newHeight+", using safe size 1x1. Drawable "+drawable); Thread.dumpStack(); } - if(0>=newWidth) { newWidth = 1; validateSize=false; } - if(0>=newHeight) { newHeight = 1; validateSize=false; } + if( 0 >= newWidth ) { newWidth = 1; validateSize=false; } + if( 0 >= newHeight ) { newHeight = 1; validateSize=false; } // propagate new size - if(ns instanceof ProxySurface) { + if( ns instanceof ProxySurface ) { final ProxySurface ps = (ProxySurface) ns; final UpstreamSurfaceHook ush = ps.getUpstreamSurfaceHook(); if(ush instanceof UpstreamSurfaceHook.MutableSize) { @@ -359,7 +359,7 @@ public class GLDrawableHelper { } else if(DEBUG) { // we have to assume surface contains the new size already, hence size check @ bottom System.err.println("GLDrawableHelper.resizeOffscreenDrawable: Drawable's offscreen surface n.a. ProxySurface, but "+ns.getClass().getName()+": "+ns); } - if(drawable instanceof GLFBODrawable) { + if( drawable instanceof GLFBODrawable ) { if( null != context && context.isCreated() ) { ((GLFBODrawable) drawable).resetSize(context.getGL()); } diff --git a/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java index ab318927c..0e9d142ba 100644 --- a/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLFBODrawableImpl.java @@ -90,7 +90,7 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { this.initialized = false; this.parent = parent; - this.origParentChosenCaps = (GLCapabilitiesImmutable) getChosenGLCapabilities(); // just to avoid null, will be reset at initialize(..) + this.origParentChosenCaps = getChosenGLCapabilities(); // just to avoid null, will be reset at initialize(..) this.texUnit = textureUnit; this.samples = fboCaps.getNumSamples(); fboResetQuirk = false; @@ -552,7 +552,7 @@ public class GLFBODrawableImpl extends GLDrawableImpl implements GLFBODrawable { ",\n\tfboI back "+fboIBack+", front "+fboIFront+", num "+(initialized ? fbos.length : 0)+ ",\n\tFBO front read "+getDefaultReadFramebuffer()+", "+getFBObject(GL.GL_FRONT)+ ",\n\tFBO back write "+getDefaultDrawFramebuffer()+", "+getFBObject(GL.GL_BACK)+ - ",\n\tSurface "+getNativeSurface()+ + ",\n\tSurface "+surface+ "]"; } diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index ddf513180..ed25a497f 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -220,30 +220,31 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if( 0 != ( java.awt.event.HierarchyEvent.DISPLAYABILITY_CHANGED & bits ) ) { final boolean displayable = changed.isDisplayable(); final boolean propagateDisplayability = changed == component && ( displayable && localVisibility ) != compIsVisible; + final boolean visible = displayable && localVisibility; + final boolean propagateDisplayability = changed == component && visible != compIsVisible; if( propagateDisplayability ) { // Propagate parent's displayability, i.e. 'removeNotify()' and 'addNotify()' - final boolean _visible = displayable && localVisibility; visibilityPropagation = true; globalVisibility = displayable; if(DEBUG) { - System.err.println(jawtStr()+".hierarchyChanged DISPLAYABILITY_CHANGED (1): displayable "+displayable+" -> visible "+_visible+", "+s(e)); + System.err.println(jawtStr()+".hierarchyChanged DISPLAYABILITY_CHANGED (1): displayable "+displayable+" -> visible "+visible+", "+s(e)); } - component.setVisible(_visible); + component.setVisible(visible); } else if(DEBUG) { System.err.println(jawtStr()+".hierarchyChanged DISPLAYABILITY_CHANGED (x): displayable "+displayable+", "+s(e)); } } else if( 0 != ( java.awt.event.HierarchyEvent.SHOWING_CHANGED & bits ) ) { final boolean showing = changed.isShowing(); - final boolean propagateVisibility = changed != component && ( showing && localVisibility ) != compIsVisible; + final boolean visible = showing && localVisibility; + final boolean propagateVisibility = changed != component && visible != compIsVisible; if( propagateVisibility ) { // Propagate parent's visibility - final boolean _visible = showing && localVisibility; visibilityPropagation = true; globalVisibility = showing; if(DEBUG) { - System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (1): showing "+showing+" -> visible "+_visible+", "+s(e)); + System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (1): showing "+showing+" -> visible "+visible+", "+s(e)); } - component.setVisible(_visible); + component.setVisible(visible); } else if( changed == component ) { // Update component's local visibility state if(!visibilityPropagation) { @@ -251,10 +252,10 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } visibilityPropagation = false; if(DEBUG) { - System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (0): showing "+showing+" -> visible "+(showing && localVisibility)+", "+s(e)); + System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (0): showing "+showing+" -> visible "+visible+", "+s(e)); } } else if(DEBUG) { - System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (x): showing "+showing+" -> visible "+(showing && localVisibility)+", "+s(e)); + System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (x): showing "+showing+" -> visible "+visible+", "+s(e)); } } else if(DEBUG) { final boolean displayable = changed.isDisplayable(); @@ -423,7 +424,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, @Override public final void setChosenCapabilities(CapabilitiesImmutable caps) { ((MutableGraphicsConfiguration)getGraphicsConfiguration()).setChosenCapabilities(caps); - getPrivateGraphicsConfiguration().setChosenCapabilities(caps); + config.setChosenCapabilities(caps); } @Override @@ -601,10 +602,6 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return drawable; } - public final AWTGraphicsConfiguration getPrivateGraphicsConfiguration() { - return config; - } - @Override public final AbstractGraphicsConfiguration getGraphicsConfiguration() { return config.getNativeGraphicsConfiguration(); @@ -792,7 +789,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, sb.append(", pos "+getX()+"/"+getY()+", size "+getWidth()+"x"+getHeight()+ ", visible "+component.isVisible()); sb.append(", lockedExt "+isSurfaceLockedByOtherThread()+ - ",\n\tconfig "+getPrivateGraphicsConfiguration()+ + ",\n\tconfig "+config+ ",\n\tawtComponent "+getAWTComponent()+ ",\n\tsurfaceLock "+surfaceLock+"]"); diff --git a/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java index 097fffead..fbff7128e 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java +++ b/src/nativewindow/classes/jogamp/nativewindow/ProxySurfaceImpl.java @@ -45,7 +45,7 @@ public abstract class ProxySurfaceImpl implements ProxySurface { private AbstractGraphicsConfiguration config; // control access due to delegation private UpstreamSurfaceHook upstream; private long surfaceHandle_old; - private RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); + private final RecursiveLock surfaceLock = LockFactory.createRecursiveLock(); private int implBitfield; private boolean upstreamSurfaceHookLifecycleEnabled; @@ -122,10 +122,6 @@ public abstract class ProxySurfaceImpl implements ProxySurface { throw new InternalError("UpstreamSurfaceHook given, but required method not implemented."); } - protected final AbstractGraphicsConfiguration getPrivateGraphicsConfiguration() { - return config; - } - @Override public final AbstractGraphicsConfiguration getGraphicsConfiguration() { return config.getNativeGraphicsConfiguration(); diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index f3bbd7a24..260ae4dd8 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -1927,13 +1927,6 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer windowDestroyNotifyAction = r; } - /** - * Returns the non delegated {@link AbstractGraphicsConfiguration}, - * see {@link #getGraphicsConfiguration()}. */ - public final AbstractGraphicsConfiguration getPrivateGraphicsConfiguration() { - return config; - } - protected final long getParentWindowHandle() { return isFullscreen() ? 0 : parentWindowHandle; } -- cgit v1.2.3 From 071bdd6ce9f8c41ccecdbf8bc74f276ccd7ff651 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Sun, 12 Jan 2014 07:27:55 +0100 Subject: Bug 937 - JAWTWindow: Unsatisfying Visibility Computation Simplify JAWTComponentListener's HierarchyListener: - Don't interfere w/ Component's visibility anymore! This shall reduce sideeffects. Utilize 'isShowing' in each Component specialization, i.e. GLCanvas. - On SHOWING_CHANGED if a parent caused a change of the tracked components showing state, propagate it to the offscreen-layer! - Remove all other complicated states! GLCanvas, GLJPanel: - Instead of 'isVisible()' use 'showing state', since only the 'showing state' reflects 'true' visibility throughout the hierarchy. - Add HierarchyListener and track volatile showing state to be used instead of 'isVisible'. Using a cached showing state is more efficient than quering 'isShowing()' all the time! NewtCanvasAWT: - Use 'isShowing()' instead of 'isVisible(), see above --- make/scripts/tests.sh | 50 +++++++++-- .../classes/javax/media/opengl/awt/GLCanvas.java | 30 ++++--- .../classes/javax/media/opengl/awt/GLJPanel.java | 20 ++++- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 78 +++++------------- .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java | 4 +- .../TestAWTCardLayoutAnimatorStartStopBug532.java | 92 +++++++++++++-------- .../awt/TestBug664GLCanvasSetVisibleSwingAWT.java | 96 +++++++++++----------- ...estBug816JTabbedPanelVisibilityB849B878AWT.java | 47 +++++++---- .../awt/TestBug816OSXCALayerPos03aB729AWT.java | 6 +- .../awt/TestBug816OSXCALayerPos03bB849AWT.java | 6 +- .../awt/TestBug816OSXCALayerPos03cB849AWT.java | 6 +- 11 files changed, 249 insertions(+), 186 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index bf9eba958..b99f7866c 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -107,6 +107,7 @@ function jrun() { #D_ARGS="-Djogl.debug.GLSLCode -Djogl.debug.DebugGL" #D_ARGS="-Dnativewindow.debug.X11Util -Dnativewindow.debug.X11Util.TraceDisplayLifecycle -Djogl.debug.EGLDisplayUtil -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.JAWT -Dnewt.debug.Window" + #D_ARGS="-Dnativewindow.debug.JAWT -Djogl.debug.GLCanvas" #D_ARGS="-Dnativewindow.debug.JAWT -Djogamp.debug.TaskBase.TraceSource" #D_ARGS="-Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch" @@ -193,7 +194,7 @@ function jrun() { #D_ARGS="-Dnewt.debug.EDT" #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT -Djogl.debug.GLContext" #D_ARGS="-Dnewt.debug.Window -Djogl.debug.Animator -Dnewt.debug.Screen" - #D_ARGS="-Dnativewindow.debug.JAWT -Dnewt.debug.Window" + D_ARGS="-Dnativewindow.debug.JAWT -Dnewt.debug.Window" #D_ARGS="-Dnewt.debug.Window.KeyEvent" #D_ARGS="-Dnewt.debug.Window.MouseEvent" #D_ARGS="-Dnewt.debug.Window.MouseEvent -Dnewt.debug.Window.KeyEvent" @@ -325,7 +326,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelsAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NewtCanvasAWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NEWT $* #testawtswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $* @@ -466,7 +467,6 @@ testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.anim.TestAnimatorGLWindow01NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.acore.anim.TestAnimatorGLJPanel01AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.acore.anim.TestAWTCardLayoutAnimatorStartStopBug532 $* #testawt com.jogamp.opengl.test.junit.jogl.acore.anim.Bug898AnimatorFromEDTAWT $* # @@ -500,15 +500,52 @@ testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* # # AWT # -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos01AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos02AWT $* + +# +# OSX CALayer Position and Visibility (OSX CALayer, ..) +# +# + +# +# Simple GLCanvas setVisible on/off +# OK (X11, OSX) +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug664GLCanvasSetVisibleSwingAWT $* + +# +# GLCanvas moving between CardLayout's JPanels +# OK (X11, OSX) +#testawt com.jogamp.opengl.test.junit.jogl.acore.anim.TestAWTCardLayoutAnimatorStartStopBug532 $* + +# +# GLCanvas moving between JTabbedPanel's tabs +# OK (X11, OSX) +testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816JTabbedPanelVisibilityB849B878AWT $* + +# +# GLCanvas/AWT Checkbox Visibility +# OK (X11, OSX) #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03aB729AWT $* + +# +# GLCanvas/AWT Checkbox Visibility (on parent's Panel) +# OK (X11, OSX) #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03bB849AWT $* +# +# GLCanvas/Swing Checkbox Visibility (on parent's JPanel) +# OK (X11, OSX) #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03cB849AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816JTabbedPanelVisibilityB849B878AWT $* + +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos01AWT $* +#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos02AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816GLCanvasFrameHoppingB849B889AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04aAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04bAWT $* + +# +# OSX CALayer Position and Visibility (OSX CALayer, ..) +# +# + #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug675BeansInDesignTimeAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug551AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug572AWT $* @@ -519,7 +556,6 @@ testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWT02WindowClosing #testawt com.jogamp.opengl.test.junit.jogl.awt.TestJScrollPaneMixHwLw01AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug642JSplitPaneMixHwLw01AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug664GLCanvasSetVisibleSwingAWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestIsRealizedConcurrency01AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.text.TestAWTTextRendererUseVertexArrayBug464 #testawt com.jogamp.opengl.test.junit.jogl.glu.TestBug463ScaleImageMemoryAWT $* diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java index 0bc002f8e..7ea216dd9 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java @@ -52,6 +52,8 @@ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; +import java.awt.event.HierarchyEvent; +import java.awt.event.HierarchyListener; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Rectangle2D; import java.awt.EventQueue; @@ -173,6 +175,14 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing private final GraphicsDevice device; private boolean shallUseOffscreenLayer = false; + private volatile boolean isShowing; + private final HierarchyListener hierarchyListener = new HierarchyListener() { + @Override + public void hierarchyChanged(HierarchyEvent e) { + isShowing = GLCanvas.this.isShowing(); + } + }; + private final AWTWindowClosingProtocol awtWindowClosingProtocol = new AWTWindowClosingProtocol(this, new Runnable() { @Override @@ -294,6 +304,9 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing helper.setSharedContext(null, shareWith); } this.device = device; + + this.addHierarchyListener(hierarchyListener); + this.isShowing = isShowing(); } @Override @@ -524,7 +537,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } return; // not yet available .. } - if( isVisible() && !printActive ) { + if( isShowing && !printActive ) { Threading.invoke(true, displayOnEDTAction, getTreeLock()); } } @@ -583,15 +596,6 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing } } - @Override - public void setVisible(boolean b) { - if(DEBUG) { - System.err.println(getThreadName()+": Info: setVisible("+b+")"); - Thread.dumpStack(); - } - super.setVisible(b); - } - /** Overridden to track when this component is added to a container. Subclasses which override this method must call super.addNotify() in their addNotify() method in order to @@ -814,9 +818,9 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing printActive = false; return; // not yet available .. } - if( !isVisible() ) { + if( !isShowing ) { if(DEBUG) { - System.err.println(getThreadName()+": Info: GLCanvas setupPrint - skipped GL render, drawable visible"); + System.err.println(getThreadName()+": Info: GLCanvas setupPrint - skipped GL render, drawable valid, canvas not showing"); } printActive = false; return; // not yet available .. @@ -1148,7 +1152,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing ",\n\thandle 0x"+Long.toHexString(getHandle())+ ",\n\tDrawable size "+dw+"x"+dh+ ",\n\tAWT pos "+getX()+"/"+getY()+", size "+getWidth()+"x"+getHeight()+ - ",\n\tvisible "+isVisible()+", displayable "+isDisplayable()+ + ",\n\tvisible "+isVisible()+", displayable "+isDisplayable()+", showing "+isShowing+ ",\n\t"+awtConfig+"]"; } diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java index a71b47c64..f7200186b 100644 --- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java +++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java @@ -48,6 +48,8 @@ import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; +import java.awt.event.HierarchyEvent; +import java.awt.event.HierarchyListener; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; @@ -265,6 +267,14 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing return null == customPixelBufferProvider && useJava2DGLPipeline && java2DGLPipelineOK; } + private volatile boolean isShowing; + private final HierarchyListener hierarchyListener = new HierarchyListener() { + @Override + public void hierarchyChanged(HierarchyEvent e) { + isShowing = GLJPanel.this.isShowing(); + } + }; + private final AWTWindowClosingProtocol awtWindowClosingProtocol = new AWTWindowClosingProtocol(this, new Runnable() { @Override @@ -346,6 +356,8 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing helper.setSharedContext(null, shareWith); } this.setFocusable(true); // allow keyboard input! + this.addHierarchyListener(hierarchyListener); + this.isShowing = isShowing(); } /** @@ -418,7 +430,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing @Override public void display() { - if( isVisible() ) { + if( isShowing ) { if (EventQueue.isDispatchThread()) { // Want display() to be synchronous, so call paintImmediately() paintImmediately(0, 0, getWidth(), getHeight()); @@ -521,7 +533,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing sendReshape = handleReshape(); } - if( isVisible() ) { + if( isShowing ) { updater.setGraphics(g); backend.doPaintComponent(g); } @@ -608,9 +620,9 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing printActive = false; return; // not yet available .. } - if( !isVisible() ) { + if( !isShowing ) { if(DEBUG) { - System.err.println(getThreadName()+": Info: GLJPanel setupPrint - skipped GL render, drawable visible"); + System.err.println(getThreadName()+": Info: GLJPanel setupPrint - skipped GL render, drawable valid, panel not showing"); } printActive = false; return; // not yet available .. diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index ed25a497f..4b0ae5d20 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -125,9 +125,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, private String jawtStr() { return "JAWTWindow["+id(JAWTWindow.this)+"]"; } private class JAWTComponentListener implements ComponentListener, HierarchyListener { - private boolean localVisibility = component.isVisible(); - private boolean globalVisibility = localVisibility; - private boolean visibilityPropagation = false; + private boolean isShowing; private String str(Object obj) { if( null == obj ) { @@ -141,14 +139,14 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } } private String s(ComponentEvent e) { - return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"],"+Platform.getNewline()+ + return "visible[isShowing "+isShowing+"],"+Platform.getNewline()+ " ** COMP "+str(e.getComponent())+Platform.getNewline()+ " ** SOURCE "+str(e.getSource())+Platform.getNewline()+ " ** THIS "+str(component)+Platform.getNewline()+ " ** THREAD "+getThreadName(); } private String s(HierarchyEvent e) { - return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"], changeBits 0x"+Long.toHexString(e.getChangeFlags())+Platform.getNewline()+ + return "visible[isShowing "+isShowing+"], changeBits 0x"+Long.toHexString(e.getChangeFlags())+Platform.getNewline()+ " ** COMP "+str(e.getComponent())+Platform.getNewline()+ " ** SOURCE "+str(e.getSource())+Platform.getNewline()+ " ** CHANGED "+str(e.getChanged())+Platform.getNewline()+ @@ -158,12 +156,13 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } @Override public final String toString() { - return "visible[local "+localVisibility+", global "+globalVisibility+", propag. "+visibilityPropagation+"],"+Platform.getNewline()+ + return "visible[isShowing "+isShowing+"],"+Platform.getNewline()+ " ** THIS "+str(component)+Platform.getNewline()+ " ** THREAD "+getThreadName(); } private JAWTComponentListener() { + isShowing = component.isShowing(); if(DEBUG) { System.err.println(jawtStr()+".attach @ Thread "+getThreadName()+": "+toString()); } @@ -177,7 +176,6 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, } component.removeComponentListener(this); component.removeHierarchyListener(this); - component.setVisible(localVisibility); // restore component's original local state } @Override @@ -185,7 +183,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if(DEBUG) { System.err.println(jawtStr()+".componentResized: "+s(e)); } - layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); + layoutSurfaceLayerIfEnabled(isShowing); } @Override @@ -193,7 +191,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if(DEBUG) { System.err.println(jawtStr()+".componentMoved: "+s(e)); } - layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); + layoutSurfaceLayerIfEnabled(isShowing); } @Override @@ -201,7 +199,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if(DEBUG) { System.err.println(jawtStr()+".componentShown: "+s(e)); } - layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); + layoutSurfaceLayerIfEnabled(isShowing); } @Override @@ -209,59 +207,27 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if(DEBUG) { System.err.println(jawtStr()+".componentHidden: "+s(e)); } - layoutSurfaceLayerIfEnabled(globalVisibility && localVisibility); + layoutSurfaceLayerIfEnabled(isShowing); } @Override public final void hierarchyChanged(HierarchyEvent e) { - final long bits = e.getChangeFlags(); - final java.awt.Component changed = e.getChanged(); - final boolean compIsVisible = component.isVisible(); - if( 0 != ( java.awt.event.HierarchyEvent.DISPLAYABILITY_CHANGED & bits ) ) { - final boolean displayable = changed.isDisplayable(); - final boolean propagateDisplayability = changed == component && ( displayable && localVisibility ) != compIsVisible; - final boolean visible = displayable && localVisibility; - final boolean propagateDisplayability = changed == component && visible != compIsVisible; - if( propagateDisplayability ) { - // Propagate parent's displayability, i.e. 'removeNotify()' and 'addNotify()' - visibilityPropagation = true; - globalVisibility = displayable; - if(DEBUG) { - System.err.println(jawtStr()+".hierarchyChanged DISPLAYABILITY_CHANGED (1): displayable "+displayable+" -> visible "+visible+", "+s(e)); - } - component.setVisible(visible); - } else if(DEBUG) { - System.err.println(jawtStr()+".hierarchyChanged DISPLAYABILITY_CHANGED (x): displayable "+displayable+", "+s(e)); + final boolean wasAWTCompShowing = isShowing; + isShowing = component.isShowing(); + int action = 0; + if( 0 != ( java.awt.event.HierarchyEvent.SHOWING_CHANGED & e.getChangeFlags() ) ) { + if( e.getChanged() != component && wasAWTCompShowing != isShowing ) { + // A parent component changed and caused a 'showing' state change, + // propagate to offscreen-layer! + layoutSurfaceLayerIfEnabled(isShowing); + action = 1; } - } else if( 0 != ( java.awt.event.HierarchyEvent.SHOWING_CHANGED & bits ) ) { - final boolean showing = changed.isShowing(); - final boolean visible = showing && localVisibility; - final boolean propagateVisibility = changed != component && visible != compIsVisible; - if( propagateVisibility ) { - // Propagate parent's visibility - visibilityPropagation = true; - globalVisibility = showing; - if(DEBUG) { - System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (1): showing "+showing+" -> visible "+visible+", "+s(e)); - } - component.setVisible(visible); - } else if( changed == component ) { - // Update component's local visibility state - if(!visibilityPropagation) { - localVisibility = compIsVisible; - } - visibilityPropagation = false; - if(DEBUG) { - System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (0): showing "+showing+" -> visible "+visible+", "+s(e)); - } - } else if(DEBUG) { - System.err.println(jawtStr()+".hierarchyChanged SHOWING_CHANGED (x): showing "+showing+" -> visible "+visible+", "+s(e)); - } - } else if(DEBUG) { + } + if(DEBUG) { + final java.awt.Component changed = e.getChanged(); final boolean displayable = changed.isDisplayable(); - final boolean _visible = displayable && localVisibility; final boolean showing = changed.isShowing(); - System.err.println(jawtStr()+".hierarchyChanged OTHER: displayable "+displayable+", showing "+showing+" -> visible "+_visible+", "+s(e)); + System.err.println(jawtStr()+".hierarchyChanged: action "+action+", displayable "+displayable+", showing [changed "+showing+", comp "+isShowing+"], "+s(e)); } } } diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java index 00c3f1eb7..1ed628435 100644 --- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java +++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java @@ -621,9 +621,9 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto printActive = false; return; // not yet available .. } - if( !isVisible() ) { + if( !isShowing() ) { if(DEBUG) { - System.err.println(currentThreadName()+": Info: NewtCanvasAWT setupPrint - skipped GL render, drawable visible"); + System.err.println(currentThreadName()+": Info: NewtCanvasAWT setupPrint - skipped GL render, drawable valid, canvas not showing"); } printActive = false; return; // not yet available .. diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/anim/TestAWTCardLayoutAnimatorStartStopBug532.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/anim/TestAWTCardLayoutAnimatorStartStopBug532.java index 7f861d89b..3790a87f7 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/anim/TestAWTCardLayoutAnimatorStartStopBug532.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/anim/TestAWTCardLayoutAnimatorStartStopBug532.java @@ -2,6 +2,7 @@ package com.jogamp.opengl.test.junit.jogl.acore.anim; import java.awt.BorderLayout; import java.awt.CardLayout; +import java.awt.Component; import java.awt.Dimension; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; @@ -30,55 +31,60 @@ import com.jogamp.opengl.util.FPSAnimator; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestAWTCardLayoutAnimatorStartStopBug532 extends UITestCase { - static final String LABEL = "Label"; + static final String LABEL = "Label"; static final String CANVAS = "GLCanvas"; - + public enum AnimatorControlBehavior { StartStop, PauseResume, Continue; } - - static long durationPerTest = 200*4; // ms + + static long durationPerTest = 200*4; // ms static boolean manual = false; static volatile boolean shouldStop = false; - + private String selected = LABEL; - + @Test public void testFPSAnimatorStartStop() throws InterruptedException, InvocationTargetException { testImpl(AnimatorControlBehavior.StartStop, true); } - + @Test public void testFPSAnimatorResumePause() throws InterruptedException, InvocationTargetException { testImpl(AnimatorControlBehavior.PauseResume, true); } - + @Test public void testFPSAnimatorContinue() throws InterruptedException, InvocationTargetException { testImpl(AnimatorControlBehavior.Continue, true); } - + @Test public void testAnimatorStartStop() throws InterruptedException, InvocationTargetException { testImpl(AnimatorControlBehavior.StartStop, false); } - + @Test public void testAnimatorResumePause() throws InterruptedException, InvocationTargetException { testImpl(AnimatorControlBehavior.PauseResume, false); } - + @Test public void testAnimatorContinue() throws InterruptedException, InvocationTargetException { testImpl(AnimatorControlBehavior.Continue, false); } - + + private static String id(Object obj) { return "0x" + ( null!=obj ? Integer.toHexString(obj.hashCode()) : "nil" ); } + private static String str(Component c) { + return id(c)+": "+c.getClass().getSimpleName()+"[visible "+c.isVisible()+", showing "+c.isShowing()+", valid "+c.isValid()+ + ", displayable "+c.isDisplayable()+", "+c.getX()+"/"+c.getY()+" "+c.getWidth()+"x"+c.getHeight()+"]"; + } void testImpl(final AnimatorControlBehavior animCtrl, boolean useFPSAnimator) throws InterruptedException, InvocationTargetException { - final GLProfile glp = GLProfile.get(GLProfile.GL2); - final GLCapabilities caps = new GLCapabilities(glp); - final GLCanvas canvas = new GLCanvas(caps); + final GLProfile glp = GLProfile.get(GLProfile.GL2); + final GLCapabilities caps = new GLCapabilities(glp); + final GLCanvas canvas = new GLCanvas(caps); canvas.setPreferredSize(new Dimension(640, 480)); - + final GLAnimatorControl animatorCtrl = useFPSAnimator ? new FPSAnimator(canvas, 60) : new Animator(canvas); animatorCtrl.setUpdateFPSFrames(60, null);// System.err); switch (animCtrl) { @@ -95,7 +101,7 @@ public class TestAWTCardLayoutAnimatorStartStopBug532 extends UITestCase { canvas.addGLEventListener(new GearsES2(1)); /* if(Platform.OS_TYPE == Platform.OSType.WINDOWS) { canvas.addGLEventListener(new GLEventListener() { - public void init(GLAutoDrawable drawable) { } + public void init(GLAutoDrawable drawable) { } public void dispose(GLAutoDrawable drawable) { } public void display(GLAutoDrawable drawable) { final NativeWindow win = (NativeWindow) drawable.getNativeSurface(); @@ -112,15 +118,17 @@ public class TestAWTCardLayoutAnimatorStartStopBug532 extends UITestCase { final JFrame frame = new JFrame(); frame.setTitle(getSimpleTestName(" - ")); - frame.addWindowListener(new WindowAdapter() { + frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { animatorCtrl.stop(); shouldStop = true; - } + } }); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - - final JPanel cards = new JPanel(new CardLayout()); + + final JLabel label = new JLabel("A label to cover the canvas"); + + final JPanel cards = new JPanel(new CardLayout()); final JPanel comboBoxPanel = new JPanel(); // nicer look .. final JComboBox comboBox = new JComboBox(new String[] { LABEL, CANVAS }); comboBox.setEditable(false); @@ -131,7 +139,13 @@ public class TestAWTCardLayoutAnimatorStartStopBug532 extends UITestCase { if(!newSelection.equals(selected)) { final String oldSelected = selected; if(newSelection.equals(CANVAS)) { - cl.show(cards, CANVAS); + System.err.println("XXX Card.SHOW Canvas PRE: "); + System.err.println(" CANVAS "+str(canvas)); + System.err.println(" LABEL "+str(label)); + cl.show(cards, CANVAS); + System.err.println("XXX Card.SHOW Canvas POST: "); + System.err.println(" CANVAS "+str(canvas)); + System.err.println(" LABEL "+str(label)); switch (animCtrl) { case StartStop: animatorCtrl.start(); @@ -152,31 +166,37 @@ public class TestAWTCardLayoutAnimatorStartStopBug532 extends UITestCase { break; default: } - cl.show(cards, LABEL); + System.err.println("XXX Card.SHOW Label PRE: "); + System.err.println(" CANVAS "+str(canvas)); + System.err.println(" LABEL "+str(label)); + cl.show(cards, LABEL); + System.err.println("XXX Card.SHOW Label POST: "); + System.err.println(" CANVAS "+str(canvas)); + System.err.println(" LABEL "+str(label)); selected = LABEL; } else { throw new RuntimeException("oops .. unexpected item: "+evt); } - System.err.println("Item Change: "+oldSelected+" -> "+selected+", "+animatorCtrl); + System.err.println("Item Change: "+oldSelected+" -> "+selected+", "+animatorCtrl); } else { System.err.println("Item Stays: "+selected+", "+animatorCtrl); } } }); - comboBoxPanel.add(comboBox); + comboBoxPanel.add(comboBox); - cards.add(new JLabel("A label to cover the canvas"), LABEL); + cards.add(label, LABEL); cards.add(canvas, CANVAS); - + frame.add(comboBoxPanel, BorderLayout.PAGE_START); frame.add(cards, BorderLayout.CENTER); - + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { - frame.pack(); + frame.pack(); frame.setVisible(true); }}); - + if(manual) { for(long w=durationPerTest; !shouldStop && w>0; w-=100) { Thread.sleep(100); @@ -187,34 +207,34 @@ public class TestAWTCardLayoutAnimatorStartStopBug532 extends UITestCase { comboBox.setSelectedItem(LABEL); }}); Thread.sleep(durationPerTest/4); - + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { comboBox.setSelectedItem(CANVAS); }}); Thread.sleep(durationPerTest/4); - + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { comboBox.setSelectedItem(LABEL); }}); Thread.sleep(durationPerTest/4); - + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { comboBox.setSelectedItem(CANVAS); }}); Thread.sleep(durationPerTest/4); } - + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { frame.setVisible(false); frame.dispose(); }}); - + } - + public static void main(String args[]) { for(int i=0; i= frameCountT1 - frameCountT0); - + + System.err.println("XXXX Visible Part 3/3"); setComponentVisible(glc, true); Assert.assertTrue("Component didn't become visible", AWTRobotUtil.waitForVisible(glc, true)); anim.resetFPSCounter(); - System.err.println("Visible Part 3/3"); - + while( anim.getTotalFPSDuration() < durationPerTest ) { Thread.sleep(60); } - + System.err.println("GLCanvas isOffscreenLayerSurfaceEnabled: "+glc.isOffscreenLayerSurfaceEnabled()+": "+glc.getChosenGLCapabilities()); - - dispose(top[0]); + + dispose(top[0]); } } @@ -258,7 +258,7 @@ public class TestBug664GLCanvasSetVisibleSwingAWT extends UITestCase { } runTestGL(false, caps); } - + public static void main(String args[]) throws IOException { for(int i=0; i Panel1("+id(panel1)+") START"); dumpGLCanvasStats(glCanvas); panel1.add(glCanvas, BorderLayout.CENTER); dumpGLCanvasStats(glCanvas); - } else { + } else if (tabbedPanel.getSelectedIndex() == 1) { System.err.println("XXXX Add GLCanvas Panel1("+id(panel1)+" -> Panel2("+id(panel2)+") START"); dumpGLCanvasStats(glCanvas); panel2.add(glCanvas, BorderLayout.CENTER); dumpGLCanvasStats(glCanvas); + } else { + System.err.println("XXXX NOP"); + dumpGLCanvasStats(glCanvas); } } }); @@ -119,33 +127,44 @@ public class TestBug816JTabbedPanelVisibilityB849B878AWT extends UITestCase { Thread.sleep(100); } } else { + Thread.sleep(durationPerTest/6); javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { - System.err.println("XXXX Add GLCanvas Panel2("+id(panel2)+") -> Panel1("+id(panel1)+" START"); - tabbedPanel.setSelectedIndex(0); + System.err.println("XXXX Panel1("+id(panel1)+" -> Panel2("+id(panel2)+") START"); + tabbedPanel.setSelectedIndex(1); }}); - Thread.sleep(durationPerTest/4); + Thread.sleep(durationPerTest/6); javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { - System.err.println("XXXX Add GLCanvas Panel1("+id(panel1)+" -> Panel2("+id(panel2)+") START"); - tabbedPanel.setSelectedIndex(1); + System.err.println("XXXX Panel2("+id(panel2)+") -> Panel3("+id(panel3)+" START"); + tabbedPanel.setSelectedIndex(2); }}); - Thread.sleep(durationPerTest/4); + Thread.sleep(durationPerTest/6); javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { - System.err.println("XXXX Add GLCanvas Panel2("+id(panel2)+") -> Panel1("+id(panel1)+" START"); + System.err.println("XXXX Panel3("+id(panel3)+") -> Panel1("+id(panel1)+" START"); tabbedPanel.setSelectedIndex(0); }}); - Thread.sleep(durationPerTest/4); + // one loop done + + Thread.sleep(durationPerTest/6); javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { - System.err.println("XXXX Add GLCanvas Panel1("+id(panel1)+" -> Panel2("+id(panel2)+") START"); + System.err.println("XXXX Panel1("+id(panel1)+" -> Panel2("+id(panel2)+") START"); tabbedPanel.setSelectedIndex(1); }}); - Thread.sleep(durationPerTest/4); + + Thread.sleep(durationPerTest/6); + javax.swing.SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + System.err.println("XXXX Panel2("+id(panel2)+") -> Panel1("+id(panel1)+" START"); + tabbedPanel.setSelectedIndex(0); + }}); + + Thread.sleep(durationPerTest/6); } SwingUtilities.invokeLater(new Runnable() { diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03aB729AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03aB729AWT.java index e1a0944e1..29dc9a190 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03aB729AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03aB729AWT.java @@ -95,8 +95,10 @@ public class TestBug816OSXCALayerPos03aB729AWT extends UITestCase { final Checkbox checkbox = new Checkbox("Visible canvas", true); checkbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { - glCanvas1.setVisible(checkbox.getState()); - System.out.println("Canvas visible: "+glCanvas1.isVisible()); + final boolean visible = checkbox.getState(); + System.err.println("XXXX Canvas setVisible "+visible); + glCanvas1.setVisible(visible); + System.err.println("XXXX Canvas visible: "+glCanvas1.isVisible()); if( glCanvas1.isVisible() ) { frame.validate(); // take care of resized frame while hidden } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03bB849AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03bB849AWT.java index b9ee6a4f6..3e60c8b47 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03bB849AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03bB849AWT.java @@ -101,8 +101,10 @@ public class TestBug816OSXCALayerPos03bB849AWT extends UITestCase { final Checkbox checkbox = new Checkbox("Visible canvas", true); checkbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { - panel.setVisible(checkbox.getState()); - System.out.println("Visible: [panel "+panel.isVisible()+", canvas "+glCanvas1.isVisible()+"]; Displayable: [panel "+panel.isDisplayable()+", canvas "+glCanvas1.isDisplayable()+"]"); + final boolean visible = checkbox.getState(); + System.err.println("XXXX Panel setVisible "+visible); + panel.setVisible(visible); + System.err.println("XXXX Visible: [panel "+panel.isVisible()+", canvas "+glCanvas1.isVisible()+"]; Displayable: [panel "+panel.isDisplayable()+", canvas "+glCanvas1.isDisplayable()+"]"); if( panel.isVisible() ) { frame.validate(); // take care of resized frame while hidden } diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03cB849AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03cB849AWT.java index 9a536d50c..24f9de961 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03cB849AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos03cB849AWT.java @@ -103,8 +103,10 @@ public class TestBug816OSXCALayerPos03cB849AWT extends UITestCase { final JCheckBox checkbox = new JCheckBox("Visible canvas", true); checkbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { - panel.setVisible(checkbox.getSelectedObjects()!=null); - System.out.println("Visible: [panel "+panel.isVisible()+", canvas "+glCanvas1.isVisible()+"]; Displayable: [panel "+panel.isDisplayable()+", canvas "+glCanvas1.isDisplayable()+"]"); + final boolean visible = checkbox.getSelectedObjects()!=null; + System.err.println("XXXX Panel setVisible "+visible); + panel.setVisible(visible); + System.err.println("XXXX Visible: [panel "+panel.isVisible()+", canvas "+glCanvas1.isVisible()+"]; Displayable: [panel "+panel.isDisplayable()+", canvas "+glCanvas1.isDisplayable()+"]"); if( panel.isVisible() ) { frame.validate(); // take care of resized frame while hidden } -- cgit v1.2.3 From 9dcaf86ad6ae08e60c68abd4c069f3ab19807854 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Mon, 13 Jan 2014 06:35:52 +0100 Subject: JAWTWindow.JAWTComponentListener: Minor Cleanup --- .../classes/com/jogamp/nativewindow/awt/JAWTWindow.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 4b0ae5d20..8765f58d0 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -127,7 +127,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, private class JAWTComponentListener implements ComponentListener, HierarchyListener { private boolean isShowing; - private String str(Object obj) { + private String str(final Object obj) { if( null == obj ) { return "0xnil: null"; } else if( obj instanceof Component ) { @@ -138,14 +138,14 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return id(obj)+": "+obj.getClass().getSimpleName()+"[..]"; } } - private String s(ComponentEvent e) { + private String s(final ComponentEvent e) { return "visible[isShowing "+isShowing+"],"+Platform.getNewline()+ " ** COMP "+str(e.getComponent())+Platform.getNewline()+ " ** SOURCE "+str(e.getSource())+Platform.getNewline()+ " ** THIS "+str(component)+Platform.getNewline()+ " ** THREAD "+getThreadName(); } - private String s(HierarchyEvent e) { + private String s(final HierarchyEvent e) { return "visible[isShowing "+isShowing+"], changeBits 0x"+Long.toHexString(e.getChangeFlags())+Platform.getNewline()+ " ** COMP "+str(e.getComponent())+Platform.getNewline()+ " ** SOURCE "+str(e.getSource())+Platform.getNewline()+ @@ -212,11 +212,11 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, @Override public final void hierarchyChanged(HierarchyEvent e) { - final boolean wasAWTCompShowing = isShowing; + final boolean wasShowing = isShowing; isShowing = component.isShowing(); int action = 0; if( 0 != ( java.awt.event.HierarchyEvent.SHOWING_CHANGED & e.getChangeFlags() ) ) { - if( e.getChanged() != component && wasAWTCompShowing != isShowing ) { + if( e.getChanged() != component && wasShowing != isShowing ) { // A parent component changed and caused a 'showing' state change, // propagate to offscreen-layer! layoutSurfaceLayerIfEnabled(isShowing); -- cgit v1.2.3 From 367b704b448b4ebabcfc62cc29e61fa5760514d1 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Mon, 13 Jan 2014 06:37:24 +0100 Subject: OSXMisc CALayer::FixCALayerLayout: Fix visible:=false case, i.e. don'r override cached visibleOpacity w/ forced zero when called twice --- src/nativewindow/native/macosx/OSXmisc.m | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m index 4887cc3cf..d95d1cdbf 100644 --- a/src/nativewindow/native/macosx/OSXmisc.m +++ b/src/nativewindow/native/macosx/OSXmisc.m @@ -334,6 +334,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 BOOL fixedFrameSet; CGRect fixedFrame; float visibleOpacity; + BOOL visibleOpacityZeroed; } - (id)init; #ifdef DBG_LIFECYCLE @@ -357,6 +358,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 o->fixedFrameSet = 0; o->fixedFrame = CGRectMake(0, 0, 0, 0); o->visibleOpacity = 1.0; + o->visibleOpacityZeroed = 0; DBG_PRINT("MyCALayer::init.X: new %p\n", o); return o; } @@ -461,12 +463,16 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 [self setOpacity: visibleOpacity]; [self setHidden: NO]; [subLayer setHidden: NO]; + visibleOpacityZeroed = 0; } else { [subLayer setHidden: YES]; [self setHidden: YES]; - visibleOpacity = [self opacity]; + if( !visibleOpacityZeroed ) { + visibleOpacity = [self opacity]; + } [subLayer setOpacity: 0.0]; [self setOpacity: 0.0]; + visibleOpacityZeroed = 1; } int posQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_POSITION & caLayerQuirks ) && ( lFrame.origin.x!=0 || lFrame.origin.y!=0 ); int sizeQuirk = 0 != ( NW_DEDICATEDFRAME_QUIRK_SIZE & caLayerQuirks ) && ( lFrame.size.width!=width || lFrame.size.height!=height ); @@ -488,8 +494,8 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 fixedFrame.size.width = width; fixedFrame.size.height = height; } - DBG_PRINT("CALayer::FixCALayerLayout0.0: Quirks [%d, pos %d, size %d, lout %d], Super %p frame %lf/%lf %lfx%lf, Root %p frame %lf/%lf %lfx%lf, usr %d/%d %dx%d -> %lf/%lf %lfx%lf\n", - caLayerQuirks, posQuirk, sizeQuirk, loutQuirk, + DBG_PRINT("CALayer::FixCALayerLayout0.0: Visible %d, Quirks [%d, pos %d, size %d, lout %d, force %d], Super %p frame %lf/%lf %lfx%lf, Root %p frame %lf/%lf %lfx%lf, usr %d/%d %dx%d -> %lf/%lf %lfx%lf\n", + (int)visible, caLayerQuirks, posQuirk, sizeQuirk, loutQuirk, (int)force, superLayer, superFrame.origin.x, superFrame.origin.y, superFrame.size.width, superFrame.size.height, self, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height, x, y, width, height, fixedFrame.origin.x, fixedFrame.origin.y, fixedFrame.size.width, fixedFrame.size.height); @@ -514,8 +520,9 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_GetNSWindow0 _w = width; _h = height; } - DBG_PRINT("CALayer::FixCALayerLayout1.0: Quirks [%d, pos %d, size %d, lout %d], SubL %p frame %lf/%lf %lfx%lf, usr %dx%d -> %lf/%lf %lfx%lf\n", - caLayerQuirks, posQuirk, sizeQuirk, loutQuirk, subLayer, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height, + DBG_PRINT("CALayer::FixCALayerLayout1.0: Visible %d, Quirks [%d, pos %d, size %d, lout %d, force %d], SubL %p frame %lf/%lf %lfx%lf, usr %dx%d -> %lf/%lf %lfx%lf\n", + (int)visible, caLayerQuirks, posQuirk, sizeQuirk, loutQuirk, (int)force, + subLayer, lFrame.origin.x, lFrame.origin.y, lFrame.size.width, lFrame.size.height, width, height, _x, _y, _w, _h); if( force || posQuirk || sizeQuirk || loutQuirk ) { lFrame.origin.x = _x; -- cgit v1.2.3 From 961930f9e2cd40dc4de736201bcfa68c1ff09909 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Tue, 14 Jan 2014 19:18:52 +0100 Subject: JAWTWindow DEBUG: Dump all JAVA_VERSION* information --- make/scripts/tests.sh | 5 +-- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 3 ++ .../jogl/awt/TestBug816OSXCALayerPos01AWT.java | 41 +++++++++------------- 3 files changed, 22 insertions(+), 27 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 3c79e3209..649256393 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -109,6 +109,7 @@ function jrun() { #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.JAWT -Dnewt.debug.Window" #D_ARGS="-Dnativewindow.debug.JAWT -Djogl.debug.GLCanvas" #D_ARGS="-Dnativewindow.debug.JAWT -Djogamp.debug.TaskBase.TraceSource" + D_ARGS="-Dnativewindow.debug.JAWT" #D_ARGS="-Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogl.debug.FixedFuncPipeline -Djogl.debug.GLSLCode" @@ -389,7 +390,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug00NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMapBufferRead01NEWT $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMapBufferRead01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestBug669RecursiveGLContext01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestBug669RecursiveGLContext02NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestBug692GL3VAONEWT $* @@ -535,7 +536,7 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMapBufferRead01NEWT $* # OK (X11, OSX) #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos03cB849AWT $* -#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos01AWT $* +testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos01AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos02AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816GLCanvasFrameHoppingB849B889AWT $* #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug816OSXCALayerPos04aAWT $* diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index 8765f58d0..a4dfe1c04 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -730,6 +730,9 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, if( null == sb ) { sb = new StringBuilder(); } + sb.append("JVM version: ").append(Platform.JAVA_VERSION).append(" ("). + append(Platform.JAVA_VERSION_NUMBER). + append(" update ").append(Platform.JAVA_VERSION_UPDATE).append(")").append(Platform.getNewline()); if(null != jawt) { sb.append("JAWT version: 0x").append(Integer.toHexString(jawt.getCachedVersion())). append(", CA_LAYER: ").append(JAWTUtil.isJAWTUsingOffscreenLayer(jawt)). diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos01AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos01AWT.java index 5a7c5c9eb..ace578e7a 100644 --- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos01AWT.java +++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug816OSXCALayerPos01AWT.java @@ -63,8 +63,6 @@ import java.lang.reflect.InvocationTargetException; import org.junit.Assert; import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.AfterClass; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; @@ -80,23 +78,12 @@ public class TestBug816OSXCALayerPos01AWT extends UITestCase { public enum FrameLayout { None, Flow, DoubleBorderCenterSurrounded, Box, Split }; static long duration = 1600; // ms - static int width, height; + static final int width = 640, height = 480; static boolean forceES2 = false; static boolean forceGL3 = false; static int swapInterval = 1; - static java.awt.Dimension rwsize; - - @BeforeClass - public static void initClass() { - width = 640; - height = 480; - rwsize = new Dimension(800, 600); - } - - @AfterClass - public static void releaseClass() { - } + static java.awt.Dimension rwsize = new Dimension(800, 600); static void setComponentSize(final Frame frame, final Component comp1, final java.awt.Dimension new_sz1, final Component comp2, final java.awt.Dimension new_sz2) { try { @@ -278,16 +265,18 @@ public class TestBug816OSXCALayerPos01AWT extends UITestCase { } Thread.sleep(Math.max(1000, duration/2)); - final Dimension compRSizeHalf = new Dimension(rwsize.width/2, rwsize.height); - final Dimension frameRSizeHalf = new Dimension(twoCanvas ? rwsize.width + 64: rwsize.width/2 + 64, rwsize.height + 64); - if( resizeByComp ) { - setComponentSize(frame, glCanvas1, compRSizeHalf, glCanvas2, compRSizeHalf); - } else { - setFrameSize(frame, true, frameRSizeHalf); - } - System.err.println("resize canvas1 pos/siz: "+glCanvas1.getX()+"/"+glCanvas1.getY()+" "+glCanvas1.getWidth()+"x"+glCanvas1.getHeight()); - if( twoCanvas ) { - System.err.println("resize canvas2 pos/siz: "+glCanvas2.getX()+"/"+glCanvas2.getY()+" "+glCanvas2.getWidth()+"x"+glCanvas2.getHeight()); + if( null != rwsize ) { + final Dimension compRSizeHalf = new Dimension(rwsize.width/2, rwsize.height); + final Dimension frameRSizeHalf = new Dimension(twoCanvas ? rwsize.width + 64: rwsize.width/2 + 64, rwsize.height + 64); + if( resizeByComp ) { + setComponentSize(frame, glCanvas1, compRSizeHalf, glCanvas2, compRSizeHalf); + } else { + setFrameSize(frame, true, frameRSizeHalf); + } + System.err.println("resize canvas1 pos/siz: "+glCanvas1.getX()+"/"+glCanvas1.getY()+" "+glCanvas1.getWidth()+"x"+glCanvas1.getHeight()); + if( twoCanvas ) { + System.err.println("resize canvas2 pos/siz: "+glCanvas2.getX()+"/"+glCanvas2.getY()+" "+glCanvas2.getWidth()+"x"+glCanvas2.getHeight()); + } } final long t0 = System.currentTimeMillis(); @@ -465,6 +454,8 @@ public class TestBug816OSXCALayerPos01AWT extends UITestCase { } else if(args[i].equals("-test")) { i++; testNum = MiscUtils.atoi(args[i], 0); + } else if(args[i].equals("-noresize")) { + rwsize = null; } else if(args[i].equals("-es2")) { forceES2 = true; } else if(args[i].equals("-gl3")) { -- cgit v1.2.3 From 9a642c08f9ee818a89d5eab8ce16ca8e0ee7f9d9 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 23 Jan 2014 18:00:04 +0100 Subject: EGLDisplayUtil.eglCreateEGLGraphicsDevice(..): Don't open() device implicit; EGLDrawableFactory.mapAvailableEGLESConfig(..): Clarify --- .../classes/jogamp/opengl/egl/EGLDisplayUtil.java | 35 ++-- .../jogamp/opengl/egl/EGLDrawableFactory.java | 46 ++--- .../opengl/egl/EGLDynamicLibraryBundleInfo.java | 3 + .../egl/EGLGraphicsConfigurationFactory.java | 9 +- .../jogamp/opengl/egl/EGLUpstreamSurfaceHook.java | 1 + .../jogamp/nativewindow/egl/EGLGraphicsDevice.java | 12 ++ .../jogamp/newt/driver/android/DisplayDriver.java | 11 +- .../jogamp/newt/driver/android/WindowDriver.java | 217 +++++++++++---------- .../newt/driver/bcm/vc/iv/DisplayDriver.java | 1 + .../jogamp/newt/driver/bcm/vc/iv/WindowDriver.java | 1 + .../jogamp/newt/driver/kd/DisplayDriver.java | 1 + 11 files changed, 182 insertions(+), 155 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java index 0577124eb..a1899e032 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java @@ -188,6 +188,11 @@ public class EGLDisplayUtil { } /** + * Attempts to {@link #eglGetDisplayAndInitialize(long, long[], int[], IntBuffer, IntBuffer)} with given nativeDisplayID. + * If this fails, method retries with nativeDisplayID {@link EGL#EGL_DEFAULT_DISPLAY} - the fallback mechanism. + * The actual used nativeDisplayID is returned in it's in/out array. + * + * @throws GLException if {@link EGL#eglGetDisplay(long)} or {@link EGL#eglInitialize(long, int[], int, int[], int)} fails incl fallback * @param nativeDisplayID in/out array of size 1, passing the requested nativeVisualID, may return a different revised nativeVisualID handle * @return the initialized EGL display ID * @throws GLException if not successful @@ -261,24 +266,34 @@ public class EGLDisplayUtil { }; /** + * Returns an uninitialized {@link EGLGraphicsDevice}. User needs to issue {@link EGLGraphicsDevice#open()} before usage. + *

                            + * Using {@link #eglGetDisplayAndInitialize(long[])} for the {@link EGLGraphicsDevice#open()} implementation + * and {@link #eglTerminate(long)} for {@link EGLGraphicsDevice#close()}. + *

                            + *

                            * Using the default {@link ToolkitLock}, via {@link NativeWindowFactory#getDefaultToolkitLock(String, long)}. + *

                            * @param nativeDisplayID * @param connection * @param unitID - * @return an initialized EGLGraphicsDevice - * @throws GLException if {@link EGL#eglGetDisplay(long)} or {@link EGL#eglInitialize(long, int[], int, int[], int)} fails - * @see EGLGraphicsDevice#EGLGraphicsDevice(long, long, String, int, com.jogamp.nativewindow.egl.EGLGraphicsDevice.EGLDisplayLifecycleCallback) + * @return an uninitialized {@link EGLGraphicsDevice} */ public static EGLGraphicsDevice eglCreateEGLGraphicsDevice(long nativeDisplayID, String connection, int unitID) { - final EGLGraphicsDevice eglDisplay = new EGLGraphicsDevice(nativeDisplayID, EGL.EGL_NO_DISPLAY, connection, unitID, eglLifecycleCallback); - eglDisplay.open(); - return eglDisplay; + return new EGLGraphicsDevice(nativeDisplayID, EGL.EGL_NO_DISPLAY, connection, unitID, eglLifecycleCallback); } /** + * Returns an uninitialized {@link EGLGraphicsDevice}. User needs to issue {@link EGLGraphicsDevice#open()} before usage. + *

                            + * Using {@link #eglGetDisplayAndInitialize(long[])} for the {@link EGLGraphicsDevice#open()} implementation + * and {@link #eglTerminate(long)} for {@link EGLGraphicsDevice#close()}. + *

                            + *

                            + * Using the default {@link ToolkitLock}, via {@link NativeWindowFactory#getDefaultToolkitLock(String, long)}. + *

                            * @param surface - * @return an initialized EGLGraphicsDevice - * @throws GLException if {@link EGL#eglGetDisplay(long)} or {@link EGL#eglInitialize(long, int[], int, int[], int)} fails incl fallback + * @return an uninitialized EGLGraphicsDevice */ public static EGLGraphicsDevice eglCreateEGLGraphicsDevice(NativeSurface surface) { final long nativeDisplayID; @@ -288,8 +303,6 @@ public class EGLDisplayUtil { nativeDisplayID = surface.getDisplayHandle(); // 0 == EGL.EGL_DEFAULT_DISPLAY } final AbstractGraphicsDevice adevice = surface.getGraphicsConfiguration().getScreen().getDevice(); - final EGLGraphicsDevice eglDevice = new EGLGraphicsDevice(nativeDisplayID, EGL.EGL_NO_DISPLAY, adevice.getConnection(), adevice.getUnitID(), eglLifecycleCallback); - eglDevice.open(); - return eglDevice; + return new EGLGraphicsDevice(nativeDisplayID, EGL.EGL_NO_DISPLAY, adevice.getConnection(), adevice.getUnitID(), eglLifecycleCallback); } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index 1ff16fff8..3651d71a9 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -192,8 +192,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } sharedMap = new HashMap(); sharedMapCreateAttempt = new HashSet(); - - // FIXME: Following triggers eglInitialize(..) which crashed on Windows w/ Chrome/Angle, FF/Angle! + // FIXME: defaultDevice.open() triggers eglInitialize(..) which crashed on Windows w/ Chrome/ANGLE, FF/ANGLE! defaultDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); } } @@ -394,8 +393,8 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { EGLGraphicsDevice eglDevice = null; NativeSurface surface = null; ProxySurface upstreamSurface = null; // X11, GLX, .. + ProxySurface downstreamSurface = null; // EGL boolean success = false; - boolean deviceFromUpstreamSurface = false; try { final GLCapabilities reqCapsAny = new GLCapabilities(glp); reqCapsAny.setRedBits(5); reqCapsAny.setGreenBits(5); reqCapsAny.setBlueBits(5); reqCapsAny.setAlphaBits(0); @@ -404,6 +403,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { if( mapsADeviceToDefaultDevice ) { // In this branch, any non EGL device is mapped to EGL default shared resources (default behavior). // Only one default shared resource instance is ever be created. + defaultDevice.open(); final GLCapabilitiesImmutable reqCapsPBuffer = GLGraphicsConfigurationUtil.fixGLPBufferGLCapabilities(reqCapsAny); final List availablePBufferCapsL = getAvailableEGLConfigs(defaultDevice, reqCapsPBuffer); hasPBuffer[0] = availablePBufferCapsL.size() > 0; @@ -445,20 +445,19 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { // attempt to created the default shared resources .. - eglDevice = defaultDevice; // reuse - if( hasPBuffer[0] ) { // 2nd case create defaultDevice shared resource using pbuffer surface - surface = createDummySurfaceImpl(eglDevice, false, reqCapsPBuffer, reqCapsPBuffer, null, 64, 64); // egl pbuffer offscreen - upstreamSurface = (ProxySurface)surface; - upstreamSurface.createNotify(); - deviceFromUpstreamSurface = false; + downstreamSurface = createDummySurfaceImpl(defaultDevice, false, reqCapsPBuffer, reqCapsPBuffer, null, 64, 64); // egl pbuffer offscreen + if( null != downstreamSurface ) { + downstreamSurface.createNotify(); + } + surface = downstreamSurface; } else { // 3rd case fake creation of defaultDevice shared resource, no pbuffer available - final List capsAnyL = getAvailableEGLConfigs(eglDevice, reqCapsAny); + final List capsAnyL = getAvailableEGLConfigs(defaultDevice, reqCapsAny); if(capsAnyL.size() > 0) { final GLCapabilitiesImmutable chosenCaps = capsAnyL.get(0); - EGLContext.mapStaticGLESVersion(eglDevice, chosenCaps); + EGLContext.mapStaticGLESVersion(defaultDevice, chosenCaps); success = true; } if(DEBUG) { @@ -466,15 +465,16 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { EGLGraphicsConfigurationFactory.printCaps("!PBufferCaps", capsAnyL, System.err); } } + eglDevice = defaultDevice; // reuse } else { // 4th case always creates a true mapping of given device to EGL - surface = desktopFactory.createDummySurface(adevice, reqCapsAny, null, 64, 64); // X11, WGL, .. dummy window - upstreamSurface = ( surface instanceof ProxySurface ) ? (ProxySurface)surface : null ; + upstreamSurface = desktopFactory.createDummySurface(adevice, reqCapsAny, null, 64, 64); // X11, WGL, .. dummy window if(null != upstreamSurface) { upstreamSurface.createNotify(); } + surface = upstreamSurface; eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface); - deviceFromUpstreamSurface = true; + eglDevice.open(); hasPBuffer[0] = true; } @@ -521,24 +521,16 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } success = false; } finally { - if(eglDevice == defaultDevice) { - if(null != upstreamSurface) { - upstreamSurface.destroyNotify(); - } - } else if( deviceFromUpstreamSurface ) { + if(null != downstreamSurface) { + downstreamSurface.destroyNotify(); + } + if( defaultDevice != eglDevice ) { // don't close default device if(null != eglDevice) { eglDevice.close(); } if(null != upstreamSurface) { upstreamSurface.destroyNotify(); } - } else { - if(null != upstreamSurface) { - upstreamSurface.destroyNotify(); - } - if(null != eglDevice) { - eglDevice.close(); - } } } return success; @@ -734,6 +726,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { final long nativeDisplayID = ( deviceReq instanceof EGLGraphicsDevice) ? ( (EGLGraphicsDevice) deviceReq ).getNativeDisplayID() : deviceReq.getHandle() ; device = EGLDisplayUtil.eglCreateEGLGraphicsDevice(nativeDisplayID, deviceReq.getConnection(), deviceReq.getUnitID()); + device.open(); ownDevice = true; } else { device = (EGLGraphicsDevice) deviceReq; @@ -792,6 +785,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { protected ProxySurface createProxySurfaceImpl(AbstractGraphicsDevice deviceReq, int screenIdx, long windowHandle, GLCapabilitiesImmutable capsRequested, GLCapabilitiesChooser chooser, UpstreamSurfaceHook upstream) { final EGLGraphicsDevice eglDeviceReq = (EGLGraphicsDevice) deviceReq; final EGLGraphicsDevice device = EGLDisplayUtil.eglCreateEGLGraphicsDevice(eglDeviceReq.getNativeDisplayID(), deviceReq.getConnection(), deviceReq.getUnitID()); + device.open(); final DefaultGraphicsScreen screen = new DefaultGraphicsScreen(device, screenIdx); final EGLGraphicsConfiguration cfg = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED, false); return new WrappedSurface(cfg, windowHandle, upstream, true); diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java index ac880ebc0..ebe8f49c8 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java @@ -55,6 +55,9 @@ public abstract class EGLDynamicLibraryBundleInfo extends GLDynamicLibraryBundle /** * Returns true on Android, * and false otherwise. + *

                            + * {@inheritDoc} + *

                            */ @Override public final boolean shallLookupGlobal() { diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java index 8802c3c7d..5cfa378cb 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java @@ -182,16 +182,15 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact } protected static List getAvailableCapabilities(EGLDrawableFactory factory, AbstractGraphicsDevice device) { - EGLDrawableFactory.SharedResource sharedResource = factory.getOrCreateSharedResourceImpl(device); + final EGLDrawableFactory.SharedResource sharedResource = factory.getOrCreateSharedResourceImpl(device); if(null == sharedResource) { throw new GLException("Shared resource for device n/a: "+device); } - EGLGraphicsDevice eglDevice = sharedResource.getDevice(); - long eglDisplay = eglDevice.getHandle(); + final EGLGraphicsDevice eglDevice = sharedResource.getDevice(); + final long eglDisplay = eglDevice.getHandle(); if(0 == eglDisplay) { throw new GLException("null eglDisplay"); } - List availableCaps = null; IntBuffer numConfigs = Buffers.newDirectIntBuffer(1); @@ -213,7 +212,6 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact Collections.sort(availableCaps, EglCfgIDComparator); } } - return availableCaps; } @@ -244,6 +242,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact ownEGLDisplay = false; } else { eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(absDevice.getHandle(), absDevice.getConnection(), absDevice.getUnitID()); + eglDevice.open(); ownEGLDisplay = true; } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java b/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java index dac85e753..5b911576e 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLUpstreamSurfaceHook.java @@ -125,6 +125,7 @@ public class EGLUpstreamSurfaceHook implements UpstreamSurfaceHook.MutableSize { } } else { eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(upstreamSurface); + eglDevice.open(); aConfig = upstreamConfig; isEGLSurfaceValid = false; surface.addUpstreamOptionBits( ProxySurface.OPT_PROXY_OWNS_UPSTREAM_DEVICE ); diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java index c83814907..6dc52a702 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java @@ -86,6 +86,12 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl return super.clone(); } + /** + * Opens the EGL device if handle is null and it's {@link EGLDisplayLifecycleCallback} is valid. + *

                            + * {@inheritDoc} + *

                            + */ @Override public boolean open() { if(null != eglLifecycleCallback && 0 == handle) { @@ -101,6 +107,12 @@ public class EGLGraphicsDevice extends DefaultGraphicsDevice implements Cloneabl return false; } + /** + * Closes the EGL device if handle is not null and it's {@link EGLDisplayLifecycleCallback} is valid. + *

                            + * {@inheritDoc} + *

                            + */ @Override public boolean close() { if(null != eglLifecycleCallback && 0 != handle) { diff --git a/src/newt/classes/jogamp/newt/driver/android/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/android/DisplayDriver.java index a2877dba2..32bd970a1 100644 --- a/src/newt/classes/jogamp/newt/driver/android/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/android/DisplayDriver.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -53,6 +53,7 @@ public class DisplayDriver extends jogamp.newt.DisplayImpl { protected void createNativeImpl() { // EGL Device aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + aDevice.open(); } protected void closeNativeImpl(AbstractGraphicsDevice aDevice) { @@ -61,6 +62,6 @@ public class DisplayDriver extends jogamp.newt.DisplayImpl { protected void dispatchMessagesNative() { // n/a .. DispatchMessages(); - } + } } diff --git a/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java index 653cbf945..9af455445 100644 --- a/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/android/WindowDriver.java @@ -3,14 +3,14 @@ * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * + * * 2. 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. - * + * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR @@ -20,7 +20,7 @@ * 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. - * + * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. @@ -74,50 +74,50 @@ import android.view.SurfaceView; import android.view.KeyEvent; -public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { +public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { static { DisplayDriver.initSingleton(); } /** - * First stage of selecting an Android PixelFormat, - * at construction via {@link SurfaceHolder#setFormat(int)} + * First stage of selecting an Android PixelFormat, + * at construction via {@link SurfaceHolder#setFormat(int)} * before native realization! - * + * * @param rCaps requested Capabilities * @return An Android PixelFormat number suitable for {@link SurfaceHolder#setFormat(int)}. */ public static final int getSurfaceHolderFormat(CapabilitiesImmutable rCaps) { int fmt = PixelFormat.UNKNOWN; - + if( !rCaps.isBackgroundOpaque() ) { fmt = PixelFormat.TRANSLUCENT; } else if( rCaps.getRedBits()<=5 && rCaps.getGreenBits()<=6 && rCaps.getBlueBits()<=5 && rCaps.getAlphaBits()==0 ) { - fmt = PixelFormat.RGB_565; + fmt = PixelFormat.RGB_565; } else if( rCaps.getAlphaBits()==0 ) { fmt = PixelFormat.RGB_888; - } else { + } else { fmt = PixelFormat.RGBA_8888; } Log.d(MD.TAG, "getSurfaceHolderFormat: requested: "+rCaps); Log.d(MD.TAG, "getSurfaceHolderFormat: returned: "+fmt); - + return fmt; } - - + + public static final int NATIVE_WINDOW_FORMAT_RGBA_8888 = 1; public static final int NATIVE_WINDOW_FORMAT_RGBX_8888 = 2; public static final int NATIVE_WINDOW_FORMAT_RGB_565 = 4; /** - * Second stage of selecting an Android PixelFormat, + * Second stage of selecting an Android PixelFormat, * at right after native (surface) realization at {@link Callback2#surfaceChanged(SurfaceHolder, int, int, int)}. * Selection happens via {@link #setSurfaceVisualID0(long, int)} before native EGL creation. - * + * * @param androidPixelFormat An Android PixelFormat delivered via {@link Callback2#surfaceChanged(SurfaceHolder, int, int, int)} params. * @return A native Android PixelFormat number suitable for {@link #setSurfaceVisualID0(long, int)}. */ @@ -127,40 +127,40 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { case PixelFormat.RGBA_8888: case PixelFormat.RGBA_5551: case PixelFormat.RGBA_4444: - nativePixelFormat = NATIVE_WINDOW_FORMAT_RGBA_8888; + nativePixelFormat = NATIVE_WINDOW_FORMAT_RGBA_8888; break; - + case PixelFormat.RGBX_8888: - case PixelFormat.RGB_888: - nativePixelFormat = NATIVE_WINDOW_FORMAT_RGBX_8888; + case PixelFormat.RGB_888: + nativePixelFormat = NATIVE_WINDOW_FORMAT_RGBX_8888; break; - - case PixelFormat.RGB_565: - case PixelFormat.RGB_332: - nativePixelFormat = NATIVE_WINDOW_FORMAT_RGB_565; + + case PixelFormat.RGB_565: + case PixelFormat.RGB_332: + nativePixelFormat = NATIVE_WINDOW_FORMAT_RGB_565; break; default: nativePixelFormat = NATIVE_WINDOW_FORMAT_RGBA_8888; } Log.d(MD.TAG, "getANativeWindowFormat: android: "+androidPixelFormat+" -> native "+nativePixelFormat); return nativePixelFormat; } - + /** - * Final stage of Android PixelFormat operation, - * match the requested Capabilities w/ Android PixelFormat number. + * Final stage of Android PixelFormat operation, + * match the requested Capabilities w/ Android PixelFormat number. * This is done at native realization @ {@link Callback2#surfaceChanged(SurfaceHolder, int, int, int)}. - * + * * @param matchFormatPrecise * @param format * @param rCaps requested Capabilities * @return The fixed Capabilities - */ + */ public static final CapabilitiesImmutable fixCaps(boolean matchFormatPrecise, int format, CapabilitiesImmutable rCaps) { - PixelFormat pf = new PixelFormat(); + PixelFormat pf = new PixelFormat(); PixelFormat.getPixelFormatInfo(format, pf); - final CapabilitiesImmutable res; + final CapabilitiesImmutable res; int r, g, b, a; - + switch(format) { case PixelFormat.RGBA_8888: r=8; g=8; b=8; a=8; break; // NATIVE_WINDOW_FORMAT_RGBA_8888 case PixelFormat.RGBX_8888: r=8; g=8; b=8; a=0; break; // NATIVE_WINDOW_FORMAT_RGBX_8888 @@ -176,24 +176,24 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { rCaps.getGreenBits() > g && rCaps.getBlueBits() > b && rCaps.getAlphaBits() > a ; - + if(change) { Capabilities nCaps = (Capabilities) rCaps.cloneMutable(); nCaps.setRedBits(r); nCaps.setGreenBits(g); nCaps.setBlueBits(b); nCaps.setAlphaBits(a); - res = nCaps; + res = nCaps; } else { res = rCaps; } Log.d(MD.TAG, "fixCaps: format: "+format); Log.d(MD.TAG, "fixCaps: requested: "+rCaps); Log.d(MD.TAG, "fixCaps: chosen: "+res); - + return res; } - + public static final boolean isAndroidFormatTransparent(int aFormat) { switch (aFormat) { case PixelFormat.TRANSLUCENT: @@ -202,15 +202,15 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { } return false; } - + public static Class[] getCustomConstructorArgumentTypes() { return new Class[] { Context.class } ; } - + public WindowDriver() { reset(); } - + public void registerActivity(Activity activity) { this.activity = activity; } @@ -227,15 +227,15 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { eglSurface = 0; definePosition(0, 0); // default to 0/0 defineSize(0, 0); // default size -> TBD ! - + setBrokenFocusChange(true); } - + private final void setupInputListener(final boolean enable) { Log.d(MD.TAG, "setupInputListener(enable "+enable+") - "+Thread.currentThread().getName()); - - final AndroidNewtEventTranslator eventTranslator = - enable ? new AndroidNewtEventTranslator(this, androidView.getContext(), androidView.getHandler()) : null; + + final AndroidNewtEventTranslator eventTranslator = + enable ? new AndroidNewtEventTranslator(this, androidView.getContext(), androidView.getHandler()) : null; androidView.setOnTouchListener(eventTranslator); androidView.setOnKeyListener(eventTranslator); androidView.setOnFocusChangeListener(eventTranslator); @@ -252,47 +252,47 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { } } ); } } - + private final void setupAndroidView(Context ctx) { androidView = new MSurfaceView(ctx); - + final SurfaceHolder sh = androidView.getHolder(); - sh.addCallback(WindowDriver.this); - sh.setFormat(getSurfaceHolderFormat(getRequestedCapabilities())); + sh.addCallback(WindowDriver.this); + sh.setFormat(getSurfaceHolderFormat(getRequestedCapabilities())); } - + public final SurfaceView getAndroidView() { return androidView; } - + @Override protected final void instantiationFinished() { Log.d(MD.TAG, "instantiationFinished() - "+Thread.currentThread().getName()); - - final Context ctx = StaticContext.getContext(); + + final Context ctx = StaticContext.getContext(); if(null == ctx) { throw new NativeWindowException("No static [Application] Context has been set. Call StaticContext.setContext(Context) first."); } - + if( null != Looper.myLooper() ) { setupAndroidView(ctx); } } - + @Override protected final boolean canCreateNativeImpl() { Log.d(MD.TAG, "canCreateNativeImpl.0: surfaceHandle ready "+(0!=surfaceHandle)+" - on thread "+Thread.currentThread().getName()); if(WindowImpl.DEBUG_IMPLEMENTATION) { Thread.dumpStack(); } - + if( isFullscreen() ) { final MonitorDevice mainMonitor = getMainMonitor(); final RectangleImmutable viewport = mainMonitor.getViewport(); definePosition(viewport.getX(), viewport.getY()); defineSize(viewport.getWidth(), viewport.getHeight()); } - + final boolean b; - + if( 0 == surfaceHandle ) { // Static ViewGroup, i.e. self contained main code final ViewGroup viewGroup = StaticContext.getContentViewGroup(); @@ -305,20 +305,20 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { setupAndroidView( StaticContext.getContext() ); } viewGroup.addView(androidView, new android.widget.FrameLayout.LayoutParams(getWidth(), getHeight(), Gravity.BOTTOM|Gravity.RIGHT)); - Log.d(MD.TAG, "canCreateNativeImpl: added to static ViewGroup - on thread "+Thread.currentThread().getName()); + Log.d(MD.TAG, "canCreateNativeImpl: added to static ViewGroup - on thread "+Thread.currentThread().getName()); } }); for(long sleep = TIMEOUT_NATIVEWINDOW; 0 * Accessible protected method! *

                            - * + * * {@inheritDoc} */ @Override public final void focusChanged(boolean defer, boolean focusGained) { super.focusChanged(defer, focusGained); } - + @Override - protected final void requestFocusImpl(boolean reparented) { + protected final void requestFocusImpl(boolean reparented) { if(null != androidView) { Log.d(MD.TAG, "requestFocusImpl: reparented "+reparented); androidView.post(new Runnable() { @@ -450,9 +451,9 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { } @Override - protected final boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { + protected final boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) { boolean res = true; - + if( 0 != ( FLAG_CHANGE_FULLSCREEN & flags) ) { Log.d(MD.TAG, "reconfigureWindowImpl.setFullscreen post creation (setContentView()) n/a"); return false; @@ -474,7 +475,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { } } if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) { - visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); + visibleChanged(false, 0 != ( FLAG_IS_VISIBLE & flags)); } return res; } @@ -486,22 +487,22 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { @Override protected final void updateInsetsImpl(Insets insets) { - // nop .. + // nop .. } - + //---------------------------------------------------------------------- - // Virtual On-Screen Keyboard / SoftInput + // Virtual On-Screen Keyboard / SoftInput // - + private class KeyboardVisibleReceiver extends ResultReceiver { public KeyboardVisibleReceiver() { super(null); } - - @Override + + @Override public void onReceiveResult(int r, Bundle data) { boolean v = false; - + switch(r) { case InputMethodManager.RESULT_UNCHANGED_SHOWN: case InputMethodManager.RESULT_SHOWN: @@ -510,14 +511,14 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { case InputMethodManager.RESULT_HIDDEN: case InputMethodManager.RESULT_UNCHANGED_HIDDEN: v = false; - break; + break; } Log.d(MD.TAG, "keyboardVisible: "+v); keyboardVisibilityChanged(v); } } - private KeyboardVisibleReceiver keyboardVisibleReceiver = new KeyboardVisibleReceiver(); - + private final KeyboardVisibleReceiver keyboardVisibleReceiver = new KeyboardVisibleReceiver(); + @Override protected final boolean setKeyboardVisibleImpl(boolean visible) { if(null != androidView) { @@ -536,13 +537,13 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { return false; // nop } } - + //---------------------------------------------------------------------- - // Surface Callbacks + // Surface Callbacks // - + @Override - public final void surfaceCreated(SurfaceHolder holder) { + public final void surfaceCreated(SurfaceHolder holder) { Log.d(MD.TAG, "surfaceCreated: "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()+" - on thread "+Thread.currentThread().getName()); } @@ -570,14 +571,14 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { if(0>getX() || 0>getY()) { positionChanged(false, 0, 0); } - + if(0 == surfaceHandle) { androidFormat = aFormat; surface = aHolder.getSurface(); surfaceHandle = getSurfaceHandle0(surface); acquire0(surfaceHandle); final int aNativeWindowFormat = getANativeWindowFormat(androidFormat); - setSurfaceVisualID0(surfaceHandle, aNativeWindowFormat); + setSurfaceVisualID0(surfaceHandle, aNativeWindowFormat); nativeFormat = getSurfaceVisualID0(surfaceHandle); Log.d(MD.TAG, "surfaceChanged: androidFormat "+androidFormat+" -- (set-native "+aNativeWindowFormat+") --> nativeFormat "+nativeFormat); @@ -585,12 +586,12 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { final int nHeight = getHeight0(surfaceHandle); capsByFormat = (GLCapabilitiesImmutable) fixCaps(true /* matchFormatPrecise */, nativeFormat, getRequestedCapabilities()); sizeChanged(false, nWidth, nHeight, false); - + Log.d(MD.TAG, "surfaceRealized: isValid: "+surface.isValid()+ ", new surfaceHandle 0x"+Long.toHexString(surfaceHandle)+ ", format [a "+androidFormat+"/n "+nativeFormat+"], "+ getX()+"/"+getY()+" "+nWidth+"x"+nHeight+", visible: "+isVisible()); - + if(isVisible()) { setVisible(false, true); } @@ -599,7 +600,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { windowRepaint(0, 0, aWidth, aHeight); Log.d(MD.TAG, "surfaceChanged: X"); } - + @Override public final void surfaceDestroyed(SurfaceHolder holder) { Log.d(MD.TAG, "surfaceDestroyed - on thread "+Thread.currentThread().getName()); @@ -612,14 +613,14 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { Log.d(MD.TAG, "surfaceRedrawNeeded - on thread "+Thread.currentThread().getName()); windowRepaint(0, 0, getWidth(), getHeight()); } - + protected boolean handleKeyCodeBack(KeyEvent.DispatcherState state, android.view.KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { Log.d(MD.TAG, "handleKeyCodeBack.0 : "+event); state.startTracking(event, this); } else if (event.getAction() == KeyEvent.ACTION_UP && !event.isCanceled() && state.isTracking(event)) { - // Since we cannot trust the visibility state 'completly', - // assume an already invisible state if the invisible operation fails. + // Since we cannot trust the visibility state 'completly', + // assume an already invisible state if the invisible operation fails. final boolean wasVisible = setKeyboardVisibleImpl(false); Log.d(MD.TAG, "handleKeyCodeBack.1 : wasVisible "+wasVisible+": "+event); keyboardVisibilityChanged(false); @@ -635,7 +636,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { } else { Log.d(MD.TAG, "handleKeyCodeBack.X1 : "+event); windowDestroyNotify(true); - // -> default BACK action, usually activity.finish() + // -> default BACK action, usually activity.finish() } } return false; // continue w/ further processing @@ -646,7 +647,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { enqueueEvent(false, eDown); enqueueEvent(false, eUp); } - + @Override protected void consumeKeyEvent(com.jogamp.newt.event.KeyEvent e) { super.consumeKeyEvent(e); // consume event, i.e. call all KeyListener @@ -659,7 +660,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { triggerHome(); } } - } + } private void triggerHome() { Context ctx = StaticContext.getContext(); if(null == ctx) { @@ -669,7 +670,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { showOptions.addCategory(Intent.CATEGORY_HOME); ctx.startActivity(showOptions); } - + private boolean added2StaticViewGroup; private MSurfaceView androidView; private int nativeFormat; // chosen current native PixelFormat (suitable for EGL) @@ -678,7 +679,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { private Surface surface; private volatile long surfaceHandle; private long eglSurface; - + class MSurfaceView extends SurfaceView { public MSurfaceView (Context ctx) { super(ctx); @@ -696,7 +697,7 @@ public class WindowDriver extends jogamp.newt.WindowImpl implements Callback2 { } } return false; // cont. processing - } + } } //---------------------------------------------------------------------- // Internals only diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java index 3d563d88f..178bb70f7 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/DisplayDriver.java @@ -92,6 +92,7 @@ public class DisplayDriver extends DisplayImpl { // FIXME: map name to EGL_*_DISPLAY bcmHandle = OpenBCMDisplay0(); aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + aDevice.open(); defaultPointerIcon = (PointerIconImpl) createPointerIcon(defaultPointerIconImage, 0, 0); if( DEBUG_POINTER_ICON ) { diff --git a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java index e91c67813..c3cb8a84c 100644 --- a/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java +++ b/src/newt/classes/jogamp/newt/driver/bcm/vc/iv/WindowDriver.java @@ -96,6 +96,7 @@ public class WindowDriver extends WindowImpl { final AbstractGraphicsScreen aScreen = screen.getGraphicsScreen(); final EGLGraphicsDevice aDevice = (EGLGraphicsDevice) aScreen.getDevice(); final EGLGraphicsDevice eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(aDevice.getNativeDisplayID(), aDevice.getConnection(), aDevice.getUnitID()); + eglDevice.open(); final DefaultGraphicsScreen eglScreen = new DefaultGraphicsScreen(eglDevice, aScreen.getIndex()); final AbstractGraphicsConfiguration cfg = GraphicsConfigurationFactory.getFactory(getScreen().getDisplay().getGraphicsDevice(), capsRequested).chooseGraphicsConfiguration( diff --git a/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java b/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java index 929688b11..6c706148a 100644 --- a/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java +++ b/src/newt/classes/jogamp/newt/driver/kd/DisplayDriver.java @@ -63,6 +63,7 @@ public class DisplayDriver extends DisplayImpl { protected void createNativeImpl() { // FIXME: map name to EGL_*_DISPLAY aDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(EGL.EGL_DEFAULT_DISPLAY, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + aDevice.open(); } @Override -- cgit v1.2.3 From fbe00e6f5dca8043b40dd96f096fecc9424e0cc3 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 24 Jan 2014 05:16:05 +0100 Subject: Bug 948 - NVIDIA 331.38 (Linux X11) EGL impl. only supports _one_ EGL Display via eglGetDisplay(..) NVIDIA 331.38 (Linux X11) EGL impl. only supports _one_ EGL Display via eglGetDisplay. - Subsequent eglGetDisplay(..) calls fail. - Using the same 'global' egl-display does work though Remedy: Add 'GLRendererQuirks.SingletonEGLDisplayOnly' Detection of quirk is done as usual in GLContextImpl.setRendererQuirks(..), and EGLDrawableFactory passes the quirk, if detected, down to EGLDisplayUtil. The latter implements the singleton eglDisplay handle. EGLDisplayUtil: Cleaned up .. - EGLDisplayRef employs the reference handling incl. eglInitialize(..) and eglTerminate(), as well as the new singleton quirk. - Mark all internal methods 'private', to remove possible [untested] sideffects. --- make/scripts/tests.sh | 35 ++-- .../com/jogamp/opengl/GLRendererQuirks.java | 51 +++++- src/jogl/classes/jogamp/opengl/GLContextImpl.java | 54 ++++-- .../classes/jogamp/opengl/egl/EGLDisplayUtil.java | 184 ++++++++++++--------- .../jogamp/opengl/egl/EGLDrawableFactory.java | 18 ++ .../media/nativewindow/DefaultGraphicsDevice.java | 2 +- 6 files changed, 234 insertions(+), 110 deletions(-) (limited to 'src/nativewindow') diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh index 6bc1d4eb3..1b93ff7ae 100644 --- a/make/scripts/tests.sh +++ b/make/scripts/tests.sh @@ -109,7 +109,6 @@ function jrun() { #D_ARGS="-Djogl.debug.GLBufferObjectTracker -Djogl.debug.GLArrayData -Djogl.debug.TraceGL -Djogl.debug.DebugGL" #D_ARGS="-Djogl.debug.GLSLCode" #D_ARGS="-Djogl.debug.GLSLCode -Djogl.debug.DebugGL" - #D_ARGS="-Dnativewindow.debug.X11Util -Dnativewindow.debug.X11Util.TraceDisplayLifecycle -Djogl.debug.EGLDisplayUtil -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLContext -Dnativewindow.debug.JAWT -Dnewt.debug.Window" #D_ARGS="-Dnativewindow.debug.JAWT -Djogl.debug.GLCanvas" #D_ARGS="-Dnativewindow.debug.JAWT -Djogamp.debug.TaskBase.TraceSource" @@ -131,13 +130,10 @@ function jrun() { #D_ARGS="-Djogl.debug.GLDrawable -Dnativewindow.debug.X11Util -Dnativewindow.debug.NativeWindow -Dnewt.debug.Display -Dnewt.debug.Screen -Dnewt.debug.Window" #D_ARGS="-Djogl.debug.Animator -Djogl.debug.GLDrawable -Dnativewindow.debug.NativeWindow" #D_ARGS="-Djogl.debug=all -Dnewt.debug=all" - #D_ARGS="-Djogl.debug.EGLDisplayUtil -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.GLCanvas" #D_ARGS="-Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLEventListenerState" #D_ARGS="-Djogl.fbo.force.none" - #D_ARGS="-Djogl.debug.EGLDrawableFactory.DontQuery -Djogl.debug.GLDrawable" - #D_ARGS="-Djogl.debug.EGLDrawableFactory.QueryNativeTK -Djogl.debug.GLDrawable" #D_ARGS="-Djogl.debug.GLDebugMessageHandler" #D_ARGS="-Djogl.debug.GLDebugMessageHandler -Djogl.debug.DebugGL" #D_ARGS="-Djogl.debug.GLDebugMessageHandler -Djogl.debug.TraceGL -Djogl.debug.DebugGL -Djogl.debug.GLSLCode -Djogl.debug.GLSLState" @@ -146,30 +142,29 @@ function jrun() { #D_ARGS="-Djogl.1thread=false -Djogl.debug.Threading" #D_ARGS="-Djogl.1thread=true -Djogl.debug.Threading" #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.TraceGL -Djogl.debug.GLContext.TraceSwitch -Djogl.debug=all" - #D_ARGS="-Djogamp.debug.IOUtil -Djogl.debug.GLSLCode -Djogl.debug.GLMediaPlayer" - #D_ARGS="-Djogl.debug.GLMediaPlayer -Djogl.debug.AudioSink" - #D_ARGS="-Djogl.debug.GLMediaPlayer -Djogl.debug.GLMediaPlayer.Native" - #D_ARGS="-Djogl.debug.GLMediaPlayer" - #D_ARGS="-Djogl.debug.GLMediaPlayer.StreamWorker.delay=25 -Djogl.debug.GLMediaPlayer" - #D_ARGS="-Djogl.debug.GLMediaPlayer.Native" #D_ARGS="-Djogl.debug.AudioSink" #D_ARGS="-Djogl.debug.GLArrayData" - #D_ARGS="-Djogl.debug.EGLDisplayUtil -Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable" - #D_ARGS="-Djogl.debug.EGLDisplayUtil -Dnativewindow.debug.X11Util" #D_ARGS="-Dnewt.debug.Screen -Dnewt.debug.Window" #D_ARGS="-Dnewt.debug.Screen" #D_ARGS="-Dnewt.test.Screen.disableRandR13" #D_ARGS="-Dnewt.test.Screen.disableScreenMode -Dnewt.debug.Screen" #D_ARGS="-Dnewt.debug.Screen -Djogl.debug.Animator" #D_ARGS="-Djogamp.debug.ProcAddressHelper -Djogamp.debug.NativeLibrary -Djogamp.debug.NativeLibrary.Lookup -Djogamp.debug.JNILibLoader -Djogamp.debug.TempJarCache -Djogamp.debug.JarUtil" + #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile" + #D_ARGS="-Djogl.debug.GLProfile" #D_ARGS="-Djogl.debug.GLContext -Djogamp.debug.NativeLibrary -Djogamp.debug.JNILibLoader -Djogl.debug.DebugGL -Djogl.debug.GLDebugMessageHandler" #D_ARGS="-Dnewt.debug.MainThread" #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Dnativewindow.debug.NativeWindow" #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Animator -Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch" #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.ExtensionAvailabilityCache" - #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile -Djogl.debug.GLDrawable -Djogl.debug.EGLDisplayUtil" - #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile" - #D_ARGS="-Djogl.debug.GLProfile" + #D_ARGS="-Djogl.debug.EGLDrawableFactory.QueryNativeTK -Djogl.debug.GLDrawable" + #D_ARGS="-Djogamp.debug.ProcAddressHelper -Djogamp.debug.NativeLibrary -Djogamp.debug.NativeLibrary.Lookup -Djogamp.debug.JNILibLoader -Djogamp.debug.TempJarCache -Djogamp.debug.JarUtil" + #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile -Djogl.debug.GLDrawable -Djogl.debug.EGLDisplayUtil -Dnativewindow.debug.GraphicsDevice" + #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile -Djogl.debug.GLDrawable -Djogl.debug.EGLDisplayUtil -Djogl.debug.EGLDrawableFactory.QueryNativeTK" + #D_ARGS="-Djogl.debug.EGLDisplayUtil -Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable" + #D_ARGS="-Djogl.debug.EGLDisplayUtil -Dnativewindow.debug.X11Util" + #D_ARGS="-Dnativewindow.debug.X11Util -Dnativewindow.debug.X11Util.TraceDisplayLifecycle -Djogl.debug.EGLDisplayUtil -Djogl.debug.GLDrawable" + #D_ARGS="-Djogl.debug.EGLDisplayUtil -Djogl.debug.GLDrawable" #D_ARGS="-Dnativewindow.debug.NativeWindow -Dnewt.debug.Window -Dnewt.debug.Screen -Dnewt.debug.Display" #D_ARGS="-Djogl.debug.GLCanvas -Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT -Djogl.debug.Animator" #D_ARGS="-Dnewt.debug.Display -Dnewt.debug.EDT -Dnewt.debug.Window" @@ -244,6 +239,12 @@ function jrun() { #X_ARGS="-verbose:jni" #X_ARGS="-Xrs" #X_ARGS="-Dsun.awt.disableMixing=true" + #D_ARGS="-Djogamp.debug.IOUtil -Djogl.debug.GLSLCode -Djogl.debug.GLMediaPlayer" + #D_ARGS="-Djogl.debug.GLMediaPlayer -Djogl.debug.AudioSink" + #D_ARGS="-Djogl.debug.GLMediaPlayer -Djogl.debug.GLMediaPlayer.Native" + #D_ARGS="-Djogl.debug.GLMediaPlayer" + #D_ARGS="-Djogl.debug.GLMediaPlayer.StreamWorker.delay=25 -Djogl.debug.GLMediaPlayer" + #D_ARGS="-Djogl.debug.GLMediaPlayer.Native" if [ $awton -eq 1 ] ; then export CLASSPATH=$JOGAMP_ALL_AWT_CLASSPATH @@ -332,7 +333,7 @@ function testawtswt() { #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2GLJPanelsAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasAWT $* #testawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NewtCanvasAWT $* -#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* +testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestLandscapeES2NEWT $* #testawtswt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NewtCanvasSWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $* @@ -400,7 +401,7 @@ function testawtswt() { #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT0 $* -testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT3 $* +#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT3 $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestBug669RecursiveGLContext01NEWT $* #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestBug669RecursiveGLContext02NEWT $* diff --git a/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java b/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java index daa0d94dd..0ac0c0f03 100644 --- a/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java +++ b/src/jogl/classes/com/jogamp/opengl/GLRendererQuirks.java @@ -31,6 +31,8 @@ import java.util.IdentityHashMap; import javax.media.nativewindow.AbstractGraphicsDevice; +import com.jogamp.common.os.Platform; + import jogamp.opengl.egl.EGL; import jogamp.opengl.egl.EGLExt; @@ -70,7 +72,13 @@ public class GLRendererQuirks { /** SIGSEGV on setSwapInterval() after changing the context's drawable w/ 'Mesa 8.0.4' dri2SetSwapInterval/DRI2 (soft & intel) */ public static final int NoSetSwapIntervalPostRetarget = 4; - /** GLSL discard command leads to undefined behavior or won't get compiled if being used. Appears to have happened on Nvidia Tegra2, but seems to be fine now. FIXME: Constrain version. */ + /** + * GLSL discard command leads to undefined behavior or won't get compiled if being used. + *

                            + * Appears to have happened on Nvidia Tegra2, but seems to be fine now.
                            + * FIXME: Constrain version. + *

                            + */ public static final int GLSLBuggyDiscard = 5; /** @@ -256,15 +264,36 @@ public class GLRendererQuirks { */ public static final int GLES3ViaEGLES2Config = 15; + /** + * Bug 948 - NVIDIA 331.38 (Linux X11) EGL impl. only supports _one_ EGL Device via {@link EGL#eglGetDisplay(long)}. + *

                            + * Subsequent calls to {@link EGL#eglGetDisplay(long)} fail. + *

                            + *

                            + * Reusing global EGL display works. + *

                            + *
                              + *
                            • EGL_VENDOR NVIDIA
                            • + *
                            • EGL_VERSION 1.4
                            • + *
                            • GL_VENDOR NVIDIA Corporation
                            • + *
                            • Platform X11
                            • + *
                            • CPU Family {@link Platform.CPUFamily#X86}
                            • + *
                            + *

                            + * FIXME: Constrain driver version. + *

                            + */ + public static final int SingletonEGLDisplayOnly = 16; + /** Number of quirks known. */ - public static final int COUNT = 16; + public static final int COUNT = 17; private static final String[] _names = new String[] { "NoDoubleBufferedPBuffer", "NoDoubleBufferedBitmap", "NoSetSwapInterval", "NoOffscreenBitmap", "NoSetSwapIntervalPostRetarget", "GLSLBuggyDiscard", "GLNonCompliant", "GLFlushBeforeRelease", "DontCloseX11Display", "NeedCurrCtx4ARBPixFmtQueries", "NeedCurrCtx4ARBCreateContext", "NoFullFBOSupport", "GLSLNonCompliant", "GL4NeedsGL3Request", - "GLSharedContextBuggy", "GLES3ViaEGLES2Config" + "GLSharedContextBuggy", "GLES3ViaEGLES2Config", "SingletonEGLDisplayOnly" }; private static final IdentityHashMap stickyDeviceQuirks = new IdentityHashMap(); @@ -272,8 +301,12 @@ public class GLRendererQuirks { /** * Retrieval of sticky {@link AbstractGraphicsDevice}'s {@link GLRendererQuirks}. *

                            + * The {@link AbstractGraphicsDevice}s are mapped via their {@link AbstractGraphicsDevice#getUniqueID()}. + *

                            + *

                            * Not thread safe. *

                            + * @see #areSameStickyDevice(AbstractGraphicsDevice, AbstractGraphicsDevice) */ public static GLRendererQuirks getStickyDeviceQuirks(AbstractGraphicsDevice device) { final String key = device.getUniqueID(); @@ -288,11 +321,20 @@ public class GLRendererQuirks { return res; } + /** + * Returns true if both devices have the same {@link AbstractGraphicsDevice#getUniqueID()}, + * otherwise false. + */ + public static boolean areSameStickyDevice(AbstractGraphicsDevice device1, AbstractGraphicsDevice device2) { + return device1.getUniqueID() == device2.getUniqueID(); + } + /** * {@link #addQuirks(int[], int, int) Adding given quirks} of sticky {@link AbstractGraphicsDevice}'s {@link GLRendererQuirks}. *

                            * Not thread safe. *

                            + * @see #getStickyDeviceQuirks(AbstractGraphicsDevice) */ public static void addStickyDeviceQuirks(AbstractGraphicsDevice device, int[] quirks, int offset, int len) throws IllegalArgumentException { final GLRendererQuirks sq = getStickyDeviceQuirks(device); @@ -303,6 +345,7 @@ public class GLRendererQuirks { *

                            * Not thread safe. *

                            + * @see #getStickyDeviceQuirks(AbstractGraphicsDevice) */ public static void addStickyDeviceQuirks(AbstractGraphicsDevice device, GLRendererQuirks quirks) throws IllegalArgumentException { final GLRendererQuirks sq = getStickyDeviceQuirks(device); @@ -313,6 +356,7 @@ public class GLRendererQuirks { *

                            * Not thread safe. However, use after changing the sticky quirks is safe. *

                            + * @see #getStickyDeviceQuirks(AbstractGraphicsDevice) */ public static boolean existStickyDeviceQuirk(AbstractGraphicsDevice device, int quirk) { return getStickyDeviceQuirks(device).exist(quirk); @@ -323,6 +367,7 @@ public class GLRendererQuirks { *

                            * Not thread safe. However, use after changing the sticky quirks is safe. *

                            + * @see #getStickyDeviceQuirks(AbstractGraphicsDevice) */ public static void pushStickyDeviceQuirks(AbstractGraphicsDevice device, GLRendererQuirks dest) { dest.addQuirks(getStickyDeviceQuirks(device)); diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index 417dbd011..652fc6ba9 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -1548,7 +1548,9 @@ public abstract class GLContextImpl extends GLContext { final VersionNumberString vendorVersion = GLVersionNumber.createVendorVersion(glVersion); - setRendererQuirks(adevice, reqGLVersion.getMajor(), reqGLVersion.getMinor(), reqCtxProfileBits, major, minor, ctxProfileBits, vendorVersion, withinGLVersionsMapping); + setRendererQuirks(adevice, getDrawableImpl().getFactoryImpl(), + reqGLVersion.getMajor(), reqGLVersion.getMinor(), reqCtxProfileBits, + major, minor, ctxProfileBits, vendorVersion, withinGLVersionsMapping); if( strictMatch && glRendererQuirks.exist(GLRendererQuirks.GLNonCompliant) ) { if(DEBUG) { @@ -1665,7 +1667,7 @@ public abstract class GLContextImpl extends GLContext { return true; } - private final void setRendererQuirks(final AbstractGraphicsDevice adevice, + private final void setRendererQuirks(final AbstractGraphicsDevice adevice, final GLDrawableFactoryImpl factory, int reqMajor, int reqMinor, int reqCTP, int major, int minor, int ctp, final VersionNumberString vendorVersion, boolean withinGLVersionsMapping) { @@ -1688,16 +1690,26 @@ public abstract class GLContextImpl extends GLContext { // General Quirks // if( esCtx ) { - final int quirk = GLRendererQuirks.GLES3ViaEGLES2Config; - if( GLRendererQuirks.existStickyDeviceQuirk( GLDrawableFactory.getEGLFactory().getDefaultDevice(), GLRendererQuirks.GLES3ViaEGLES2Config) ) { - // Merge default sticky quirk! + if( 2 == reqMajor && 2 < major ) { + final int quirk = GLRendererQuirks.GLES3ViaEGLES2Config; if(DEBUG) { - System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: Default EGL Device"); + System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: ES req "+reqMajor+" and 2 < "+major); } quirks[i++] = quirk; - } else if( 2 == reqMajor && 2 < major ) { + if( withinGLVersionsMapping ) { + // Thread safe due to single threaded initialization! + GLRendererQuirks.addStickyDeviceQuirks(adevice, quirks, i-1, 1); + } else { + // FIXME: Remove when moving EGL/ES to ARB ctx creation + synchronized(GLContextImpl.class) { + GLRendererQuirks.addStickyDeviceQuirks(adevice, quirks, i-1, 1); + } + } + } + if( isX11 && isDriverNVIDIAGeForce && Platform.CPUFamily.X86 == Platform.getCPUFamily() ) { + final int quirk = GLRendererQuirks.SingletonEGLDisplayOnly; if(DEBUG) { - System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: ES req "+reqMajor+" and 2 < "+major); + System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: ES, X11, CPUFamily AMD/Intel, [Vendor "+glVendor+" or Renderer "+glRenderer+"]"); } quirks[i++] = quirk; if( withinGLVersionsMapping ) { @@ -1794,14 +1806,14 @@ public abstract class GLContextImpl extends GLContext { if( glRenderer.contains("PowerVR") ) { final int quirk = GLRendererQuirks.NoSetSwapInterval; if(DEBUG) { - System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: OS "+Platform.getOSType() + " / Renderer " + glRenderer); + System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: OS "+Platform.getOSType() + ", Renderer " + glRenderer); } quirks[i++] = quirk; } if( glRenderer.contains("Immersion.16") ) { final int quirk = GLRendererQuirks.GLSharedContextBuggy; if(DEBUG) { - System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: OS "+Platform.getOSType() + " / Renderer " + glRenderer); + System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: OS "+Platform.getOSType() + ", Renderer " + glRenderer); } quirks[i++] = quirk; } @@ -1906,9 +1918,27 @@ public abstract class GLContextImpl extends GLContext { } glRendererQuirks = new GLRendererQuirks(quirks, 0, i); - GLRendererQuirks.pushStickyDeviceQuirks(adevice, glRendererQuirks); // Thread safe due to single threaded initialization! if(DEBUG) { - System.err.println("Quirks local: "+glRendererQuirks); + System.err.println("Quirks local.0: "+glRendererQuirks); + } + { + // Merge sticky quirks, thread safe due to single threaded initialization! + GLRendererQuirks.pushStickyDeviceQuirks(adevice, glRendererQuirks); + + final AbstractGraphicsDevice factoryDefaultDevice = factory.getDefaultDevice(); + if( !GLRendererQuirks.areSameStickyDevice(factoryDefaultDevice, adevice) ) { + GLRendererQuirks.pushStickyDeviceQuirks(factoryDefaultDevice, glRendererQuirks); + } + if( esCtx ) { + final AbstractGraphicsDevice eglFactoryDefaultDevice = GLDrawableFactory.getEGLFactory().getDefaultDevice(); + if( !GLRendererQuirks.areSameStickyDevice(eglFactoryDefaultDevice, adevice) && + !GLRendererQuirks.areSameStickyDevice(eglFactoryDefaultDevice, factoryDefaultDevice) ) { + GLRendererQuirks.pushStickyDeviceQuirks(eglFactoryDefaultDevice, glRendererQuirks); + } + } + } + if(DEBUG) { + System.err.println("Quirks local.X: "+glRendererQuirks); System.err.println("Quirks sticky on "+adevice+": "+GLRendererQuirks.getStickyDeviceQuirks(adevice)); } } diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java index a1899e032..c5f76f667 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java @@ -49,57 +49,120 @@ import com.jogamp.nativewindow.egl.EGLGraphicsDevice; * and eglTerminate(..) is issued only for the last call. *

                            * This class is required, due to implementation bugs within EGL where {@link EGL#eglTerminate(long)} - * does not mark the resource for deletion when still in use, bug releases them immediatly. + * does not mark the resource for deletion when still in use, bug releases them immediately. *

                            */ public class EGLDisplayUtil { - protected static final boolean DEBUG = Debug.debug("EGLDisplayUtil"); + private static final boolean DEBUG = Debug.debug("EGLDisplayUtil"); + private static boolean useSingletonEGLDisplay = false; + private static EGLDisplayRef singletonEGLDisplay = null; - private static class DpyCounter { + private static class EGLDisplayRef { final long eglDisplay; final Throwable createdStack; - int refCount; + int initRefCount; - private DpyCounter(long eglDisplay) { + /** + * Returns an already opened {@link EGLDisplayRef} or opens a new {@link EGLDisplayRef}. + *

                            + * Opened {@link EGLDisplayRef}s are mapped against their eglDisplay handle. + *

                            + *

                            + * Method utilizes {@link EGLDisplayRef}'s reference counter, i.e. increases it. + *

                            + *

                            + * An {@link EGLDisplayRef} is opened via {@link EGL#eglInitialize(long, IntBuffer, IntBuffer)}. + *

                            + */ + static EGLDisplayRef getOrCreateOpened(final long eglDisplay, final IntBuffer major, final IntBuffer minor) { + EGLDisplayRef o = (EGLDisplayRef) openEGLDisplays.get(eglDisplay); + if( null == o ) { + if( EGL.eglInitialize(eglDisplay, major, minor) ) { + final EGLDisplayRef n = new EGLDisplayRef(eglDisplay); + openEGLDisplays.put(eglDisplay, n); + n.initRefCount++; + if( null == singletonEGLDisplay ) { + singletonEGLDisplay = n; + } + return n; + } else { + return null; + } + } else { + o.initRefCount++; + return o; + } + } + + /** + * Closes an already opened {@link EGLDisplayRef}. + *

                            + * Method decreases a reference counter and closes the {@link EGLDisplayRef} if it reaches zero. + *

                            + *

                            + * An {@link EGLDisplayRef} is closed via {@link EGL#eglTerminate(long)}. + *

                            + */ + static EGLDisplayRef closeOpened(final long eglDisplay, final boolean[] res) { + final EGLDisplayRef o = (EGLDisplayRef) openEGLDisplays.get(eglDisplay); + res[0] = true; + if( null != o ) { + if( 0 < o.initRefCount ) { // no negative refCount + o.initRefCount--; + if( 0 == o.initRefCount ) { + res[0] = EGL.eglTerminate(eglDisplay); + if( o == singletonEGLDisplay ) { + singletonEGLDisplay = null; + } + } + } + if( 0 >= o.initRefCount ) { + openEGLDisplays.remove(eglDisplay); + } + } + return o; + } + + private EGLDisplayRef(long eglDisplay) { this.eglDisplay = eglDisplay; - this.refCount = 0; + this.initRefCount = 0; this.createdStack = DEBUG ? new Throwable() : null; } @Override public String toString() { - return "EGLDisplay[0x"+Long.toHexString(eglDisplay)+": refCnt "+refCount+"]"; + return "EGLDisplayRef[0x"+Long.toHexString(eglDisplay)+": refCnt "+initRefCount+"]"; } } - static final LongObjectHashMap eglDisplayCounter; + private static final LongObjectHashMap openEGLDisplays; static { - eglDisplayCounter = new LongObjectHashMap(); - eglDisplayCounter.setKeyNotFoundValue(null); + openEGLDisplays = new LongObjectHashMap(); + openEGLDisplays.setKeyNotFoundValue(null); } /** * @return number of unclosed EGL Displays.
                            */ public static int shutdown(boolean verbose) { - if(DEBUG || verbose || eglDisplayCounter.size() > 0 ) { - System.err.println("EGLDisplayUtil.EGLDisplays: Shutdown (open: "+eglDisplayCounter.size()+")"); + if(DEBUG || verbose || openEGLDisplays.size() > 0 ) { + System.err.println("EGLDisplayUtil.EGLDisplays: Shutdown (open: "+openEGLDisplays.size()+")"); if(DEBUG) { Thread.dumpStack(); } - if( eglDisplayCounter.size() > 0) { + if( openEGLDisplays.size() > 0) { dumpOpenDisplayConnections(); } } - return eglDisplayCounter.size(); + return openEGLDisplays.size(); } public static void dumpOpenDisplayConnections() { - System.err.println("EGLDisplayUtil: Open EGL Display Connections: "+eglDisplayCounter.size()); + System.err.println("EGLDisplayUtil: Open EGL Display Connections: "+openEGLDisplays.size()); int i=0; - for(Iterator iter = eglDisplayCounter.iterator(); iter.hasNext(); i++) { + for(Iterator iter = openEGLDisplays.iterator(); iter.hasNext(); i++) { final LongObjectHashMap.Entry e = iter.next(); - final DpyCounter v = (DpyCounter) e.value; + final EGLDisplayRef v = (EGLDisplayRef) e.value; System.err.println("EGLDisplayUtil: Open["+i+"]: 0x"+Long.toHexString(e.key)+": "+v); if(null != v.createdStack) { v.createdStack.printStackTrace(); @@ -107,12 +170,22 @@ public class EGLDisplayUtil { } } - public static long eglGetDisplay(long nativeDisplay_id) { + /* pp */ static synchronized void setSingletonEGLDisplayOnly(boolean v) { useSingletonEGLDisplay = v; } + + private static synchronized long eglGetDisplay(long nativeDisplay_id) { + if( useSingletonEGLDisplay && null != singletonEGLDisplay ) { + if(DEBUG) { + System.err.println("EGLDisplayUtil.eglGetDisplay.s: eglDisplay("+EGLContext.toHexString(nativeDisplay_id)+"): "+ + EGLContext.toHexString(singletonEGLDisplay.eglDisplay)+ + ", "+((EGL.EGL_NO_DISPLAY != singletonEGLDisplay.eglDisplay)?"OK":"Failed")+", singletonEGLDisplay "+singletonEGLDisplay+" (use "+useSingletonEGLDisplay+")"); + } + return singletonEGLDisplay.eglDisplay; + } final long eglDisplay = EGL.eglGetDisplay(nativeDisplay_id); if(DEBUG) { - System.err.println("EGLDisplayUtil.eglGetDisplay(): eglDisplay("+EGLContext.toHexString(nativeDisplay_id)+"): "+ + System.err.println("EGLDisplayUtil.eglGetDisplay.X: eglDisplay("+EGLContext.toHexString(nativeDisplay_id)+"): "+ EGLContext.toHexString(eglDisplay)+ - ", "+((EGL.EGL_NO_DISPLAY != eglDisplay)?"OK":"Failed")); + ", "+((EGL.EGL_NO_DISPLAY != eglDisplay)?"OK":"Failed")+", singletonEGLDisplay "+singletonEGLDisplay+" (use "+useSingletonEGLDisplay+")"); } return eglDisplay; } @@ -125,39 +198,16 @@ public class EGLDisplayUtil { * * @see EGL#eglInitialize(long, IntBuffer, IntBuffer) */ - public static synchronized boolean eglInitialize(long eglDisplay, IntBuffer major, IntBuffer minor) { + private static synchronized boolean eglInitialize(long eglDisplay, IntBuffer major, IntBuffer minor) { if( EGL.EGL_NO_DISPLAY == eglDisplay) { return false; } - final int refCnt; - final DpyCounter d; - { - DpyCounter _d = (DpyCounter) eglDisplayCounter.get(eglDisplay); - if(null == _d) { - _d = new DpyCounter(eglDisplay); - refCnt = 1; // 1st init - } else { - refCnt = _d.refCount + 1; - } - d = _d; - } - final boolean res; - if(1==refCnt) { // only initialize once - res = EGL.eglInitialize(eglDisplay, major, minor); - } else { - res = true; - } - if(res) { // update refCount and map if successfully initialized, only - d.refCount = refCnt; - if(1 == refCnt) { - eglDisplayCounter.put(eglDisplay, d); - } - } + final EGLDisplayRef d = EGLDisplayRef.getOrCreateOpened(eglDisplay, major, minor); if(DEBUG) { - System.err.println("EGLDisplayUtil.eglInitialize("+EGLContext.toHexString(eglDisplay)+" ...): #"+refCnt+", "+d+" = "+res); + System.err.println("EGLDisplayUtil.eglInitialize("+EGLContext.toHexString(eglDisplay)+" ...): "+d+" = "+(null != d)+", singletonEGLDisplay "+singletonEGLDisplay+" (use "+useSingletonEGLDisplay+")"); // Thread.dumpStack(); } - return res; + return null != d; } /** @@ -172,14 +222,14 @@ public class EGLDisplayUtil { * @see #eglGetDisplay(long) * @see #eglInitialize(long, IntBuffer, IntBuffer) */ - public static synchronized int eglGetDisplayAndInitialize(long nativeDisplayID, long[] eglDisplay, int[] eglErr, IntBuffer major, IntBuffer minor) { + private static synchronized int eglGetDisplayAndInitialize(long nativeDisplayID, long[] eglDisplay, int[] eglErr, IntBuffer major, IntBuffer minor) { eglDisplay[0] = EGL.EGL_NO_DISPLAY; - final long _eglDisplay = EGLDisplayUtil.eglGetDisplay( nativeDisplayID ); + final long _eglDisplay = eglGetDisplay( nativeDisplayID ); if ( EGL.EGL_NO_DISPLAY == _eglDisplay ) { eglErr[0] = EGL.eglGetError(); return EGL.EGL_BAD_DISPLAY; } - if ( !EGLDisplayUtil.eglInitialize( _eglDisplay, major, minor) ) { + if ( !eglInitialize( _eglDisplay, major, minor) ) { eglErr[0] = EGL.eglGetError(); return EGL.EGL_NOT_INITIALIZED; } @@ -197,7 +247,7 @@ public class EGLDisplayUtil { * @return the initialized EGL display ID * @throws GLException if not successful */ - public static synchronized long eglGetDisplayAndInitialize(long[] nativeDisplayID) { + private static synchronized long eglGetDisplayAndInitialize(long[] nativeDisplayID) { final long[] eglDisplay = new long[1]; final int[] eglError = new int[1]; int eglRes = EGLDisplayUtil.eglGetDisplayAndInitialize(nativeDisplayID[0], eglDisplay, eglError, null, null); @@ -221,40 +271,20 @@ public class EGLDisplayUtil { * @param eglDisplay the EGL display handle * @return true if the eglDisplay is valid and it's reference counter becomes zero and {@link EGL#eglTerminate(long)} was successful, otherwise false */ - public static synchronized boolean eglTerminate(long eglDisplay) { + private static synchronized boolean eglTerminate(long eglDisplay) { if( EGL.EGL_NO_DISPLAY == eglDisplay) { return false; } - final boolean res; - final int refCnt; - final DpyCounter d; - { - DpyCounter _d = (DpyCounter) eglDisplayCounter.get(eglDisplay); - if(null == _d) { - _d = null; - refCnt = -1; // n/a - } else { - refCnt = _d.refCount - 1; // 1 - 1 = 0 -> final terminate - } - d = _d; - } - if( 0 == refCnt ) { // no terminate if still in use or already terminated - res = EGL.eglTerminate(eglDisplay); - eglDisplayCounter.remove(eglDisplay); - } else { - if(0 < refCnt) { // no negative refCount - d.refCount = refCnt; - } - res = true; - } + final boolean[] res = new boolean[1]; + final EGLDisplayRef d = EGLDisplayRef.closeOpened(eglDisplay, res); if(DEBUG) { - System.err.println("EGLDisplayUtil.eglTerminate("+EGLContext.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res); + System.err.println("EGLDisplayUtil.eglTerminate.X("+EGLContext.toHexString(eglDisplay)+" ...): "+d+" = "+res[0]+", singletonEGLDisplay "+singletonEGLDisplay+" (use "+useSingletonEGLDisplay+")"); // Thread.dumpStack(); } - return res; + return res[0]; } - public static final EGLGraphicsDevice.EGLDisplayLifecycleCallback eglLifecycleCallback = new EGLGraphicsDevice.EGLDisplayLifecycleCallback() { + private static final EGLGraphicsDevice.EGLDisplayLifecycleCallback eglLifecycleCallback = new EGLGraphicsDevice.EGLDisplayLifecycleCallback() { @Override public long eglGetAndInitDisplay(long[] nativeDisplayID) { return eglGetDisplayAndInitialize(nativeDisplayID); diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java index 3651d71a9..65ce98e07 100644 --- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java +++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java @@ -361,6 +361,13 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { return new ArrayList(0); } + private static void dumpEGLInfo(final String prefix, final long eglDisplay) { + final String eglVendor = EGL.eglQueryString(eglDisplay, EGL.EGL_VENDOR); + final String eglClientAPIs = EGL.eglQueryString(eglDisplay, EGL.EGL_CLIENT_APIS); + final String eglVersion = EGL.eglQueryString(eglDisplay, EGL.EGL_VERSION); + System.err.println(prefix+"EGL vendor "+eglVendor+", version "+eglVersion+", clientAPIs "+eglClientAPIs); + } + private boolean mapAvailableEGLESConfig(AbstractGraphicsDevice adevice, int[] esProfile, boolean[] hasPBuffer, GLRendererQuirks[] rendererQuirks, int[] ctp) { final String profileString; @@ -404,6 +411,10 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { // In this branch, any non EGL device is mapped to EGL default shared resources (default behavior). // Only one default shared resource instance is ever be created. defaultDevice.open(); + if( DEBUG ) { + dumpEGLInfo("EGLDrawableFactory.mapAvailableEGLESConfig: ", defaultDevice.getHandle()); + } + final GLCapabilitiesImmutable reqCapsPBuffer = GLGraphicsConfigurationUtil.fixGLPBufferGLCapabilities(reqCapsAny); final List availablePBufferCapsL = getAvailableEGLConfigs(defaultDevice, reqCapsPBuffer); hasPBuffer[0] = availablePBufferCapsL.size() > 0; @@ -475,6 +486,9 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { surface = upstreamSurface; eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface); eglDevice.open(); + if( DEBUG ) { + dumpEGLInfo("EGLDrawableFactory.mapAvailableEGLESConfig: ", eglDevice.getHandle()); + } hasPBuffer[0] = true; } @@ -533,6 +547,10 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl { } } } + if( null != rendererQuirks[0] && rendererQuirks[0].exist(GLRendererQuirks.SingletonEGLDisplayOnly) ) { + EGLDisplayUtil.setSingletonEGLDisplayOnly(true); + } + return success; } diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java index f916a8ef3..15ff2b1ac 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java +++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsDevice.java @@ -247,7 +247,7 @@ public class DefaultGraphicsDevice implements Cloneable, AbstractGraphicsDevice * Returns a unique String object using {@link String#intern()} for the given arguments, * which object reference itself can be used as a key. */ - protected static String getUniqueID(String type, String connection, int unitID) { + private static String getUniqueID(String type, String connection, int unitID) { final String r = (type + separator + connection + separator + unitID).intern(); return r.intern(); } -- cgit v1.2.3 From b7fafd30ffc5eac73880b264043582d74175a394 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Mon, 27 Jan 2014 14:12:41 +0100 Subject: Bug 952 - JAWTWindow.JAWTComponentListener's ctor() and detach() may deadlock due to AWTTreeLock acquisition while add/remove AWT listener The AWTTreeLock is acquired by Component.removeHierarchyListener and as for _every_ AWT component, modifications shall happen on the AWT-EDT. IMHO the user shall offload AWT modifications to the AWT-EDT similar to what JOGL's GLCanvas and NEWTCanvasAWT does. However, since JAWTWindow also represents a NativeWindow instance we shall offload AWTTreeLock methods ourselves! --- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 31 +++++++++++++++------- 1 file changed, 21 insertions(+), 10 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index a4dfe1c04..a57dafc92 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -163,19 +163,27 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, private JAWTComponentListener() { isShowing = component.isShowing(); - if(DEBUG) { - System.err.println(jawtStr()+".attach @ Thread "+getThreadName()+": "+toString()); - } - component.addComponentListener(this); - component.addHierarchyListener(this); + AWTEDTExecutor.singleton.invoke(false, new Runnable() { // Bug 952: Avoid deadlock via AWTTreeLock acquisition .. + @Override + public void run() { + if(DEBUG) { + System.err.println(jawtStr()+".attach @ Thread "+getThreadName()+": "+JAWTComponentListener.this.toString()); + } + component.addComponentListener(JAWTComponentListener.this); + component.addHierarchyListener(JAWTComponentListener.this); + } } ); } private final void detach() { - if(DEBUG) { - System.err.println(jawtStr()+".detach @ Thread "+getThreadName()+": "+toString()); - } - component.removeComponentListener(this); - component.removeHierarchyListener(this); + AWTEDTExecutor.singleton.invoke(false, new Runnable() { // Bug 952: Avoid deadlock via AWTTreeLock acquisition .. + @Override + public void run() { + if(DEBUG) { + System.err.println(jawtStr()+".detach @ Thread "+getThreadName()+": "+JAWTComponentListener.this.toString()); + } + component.removeComponentListener(JAWTComponentListener.this); + component.removeHierarchyListener(JAWTComponentListener.this); + } } ); } @Override @@ -601,6 +609,9 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, public void destroy() { surfaceLock.lock(); try { + if(DEBUG) { + System.err.println(jawtStr()+".destroy @ Thread "+getThreadName()); + } jawtComponentListener.detach(); invalidate(); } finally { -- cgit v1.2.3 From c60f114c322b11c09101839f7464946daec84cfd Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 30 Jan 2014 11:36:03 +0100 Subject: NativeWindowFactory: Add Support for creating a platform agnostic wrapped AbstractGraphicsDevice/NativeWindow --- .../jogamp/nativewindow/x11/X11GraphicsDevice.java | 15 ++++ .../media/nativewindow/NativeWindowFactory.java | 46 +++++++++++ .../classes/jogamp/nativewindow/WrappedWindow.java | 88 ++++++++++++++++++++++ 3 files changed, 149 insertions(+) create mode 100644 src/nativewindow/classes/jogamp/nativewindow/WrappedWindow.java (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java index 10e3f7857..863e53bde 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java @@ -82,6 +82,21 @@ public class X11GraphicsDevice extends DefaultGraphicsDevice implements Cloneabl isXineramaEnabled = X11Util.XineramaIsEnabled(this); } + /** + * Constructs a new X11GraphicsDevice corresponding to the given display connection. + *

                            + * The constructor opens the native connection and takes ownership. + *

                            + * @param displayConnection the semantic display connection name + * @param locker custom {@link javax.media.nativewindow.ToolkitLock}, eg to force null locking w/ private connection + * @see DefaultGraphicsDevice#DefaultGraphicsDevice(String, String, int, long, ToolkitLock) + */ + public X11GraphicsDevice(String displayConnection, int unitID, ToolkitLock locker) { + super(NativeWindowFactory.TYPE_X11, displayConnection, unitID, 0, locker); + handleOwner = true; + open(); + isXineramaEnabled = X11Util.XineramaIsEnabled(this); + } private static int getDefaultScreenImpl(long dpy) { return X11Lib.DefaultScreen(dpy); diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 6962ce505..1dce05192 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -47,11 +47,15 @@ import jogamp.nativewindow.Debug; import jogamp.nativewindow.NativeWindowFactoryImpl; import jogamp.nativewindow.ToolkitProperties; import jogamp.nativewindow.ResourceToolkitLock; +import jogamp.nativewindow.WrappedWindow; import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; import com.jogamp.nativewindow.awt.AWTGraphicsDevice; import com.jogamp.nativewindow.awt.AWTGraphicsScreen; +import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; +import com.jogamp.nativewindow.windows.WindowsGraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsDevice; import com.jogamp.nativewindow.x11.X11GraphicsScreen; @@ -627,4 +631,46 @@ public abstract class NativeWindowFactory { VisualIDHolder.VID_UNDEFINED != visualID ; } + /** + * Creates a native device type, following {@link #getNativeWindowType(boolean) getNativeWindowType(true)}. + *

                            + * The device will be opened if own is true, otherwise no native handle will ever be acquired. + *

                            + */ + public static AbstractGraphicsDevice createDevice(String displayConnection, boolean own) { + final String nwt = NativeWindowFactory.getNativeWindowType(true); + if( NativeWindowFactory.TYPE_X11 == nwt ) { + if( own ) { + return new X11GraphicsDevice(displayConnection, AbstractGraphicsDevice.DEFAULT_UNIT, null /* ToolkitLock */); + } else { + return new X11GraphicsDevice(displayConnection, AbstractGraphicsDevice.DEFAULT_UNIT); + } + } else if( NativeWindowFactory.TYPE_WINDOWS == nwt ) { + return new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); + } else if( NativeWindowFactory.TYPE_MACOSX == nwt ) { + return new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); + } + throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); + } + + /** + * Creates a wrapped {@link NativeWindow} with given native handles and {@link AbstractGraphicsScreen}. + *

                            + * The given {@link UpstreamSurfaceHookMutableSize} maybe used to reflect resizes of the native window. + *

                            + *

                            + * The {@link AbstractGraphicsScreen} may be created via {@link #createScreen(AbstractGraphicsDevice, int)}. + *

                            + *

                            + * The {@link AbstractGraphicsScreen} may have an underlying open {@link AbstractGraphicsDevice} + * or a simple dummy instance, see {@link #createDevice(String, boolean)}. + *

                            + */ + public static NativeWindow createWrappedWindow(AbstractGraphicsScreen aScreen, long surfaceHandle, long windowHandle, + UpstreamSurfaceHookMutableSize hook) { + final CapabilitiesImmutable caps = new Capabilities(); + final AbstractGraphicsConfiguration config = new DefaultGraphicsConfiguration(aScreen, caps, caps); + return new WrappedWindow(config, surfaceHandle, hook, true, windowHandle); + } + } diff --git a/src/nativewindow/classes/jogamp/nativewindow/WrappedWindow.java b/src/nativewindow/classes/jogamp/nativewindow/WrappedWindow.java new file mode 100644 index 000000000..d5a977240 --- /dev/null +++ b/src/nativewindow/classes/jogamp/nativewindow/WrappedWindow.java @@ -0,0 +1,88 @@ +package jogamp.nativewindow; + +import javax.media.nativewindow.AbstractGraphicsConfiguration; +import javax.media.nativewindow.AbstractGraphicsDevice; +import javax.media.nativewindow.NativeWindow; +import javax.media.nativewindow.ProxySurface; +import javax.media.nativewindow.UpstreamSurfaceHook; +import javax.media.nativewindow.util.Insets; +import javax.media.nativewindow.util.InsetsImmutable; +import javax.media.nativewindow.util.Point; + +public class WrappedWindow extends WrappedSurface implements NativeWindow { + private final long windowHandle; + private final InsetsImmutable insets = new Insets(0, 0, 0, 0); + + /** + * Utilizes a {@link UpstreamSurfaceHook.MutableSize} to hold the size information, + * which is being passed to the {@link ProxySurface} instance. + * + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param surfaceHandle the wrapped pre-existing native surface handle, maybe 0 if not yet determined + * @param initialWidth + * @param initialHeight + * @param ownsDevice true if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise false. Owning the device implies closing it at {@link #destroyNotify()}. + */ + public WrappedWindow(AbstractGraphicsConfiguration cfg, long surfaceHandle, int initialWidth, int initialHeight, boolean ownsDevice, long windowHandle) { + super(cfg, surfaceHandle, initialWidth, initialHeight, ownsDevice); + this.windowHandle = windowHandle; + } + + /** + * @param cfg the {@link AbstractGraphicsConfiguration} to be used + * @param surfaceHandle the wrapped pre-existing native surface handle, maybe 0 if not yet determined + * @param upstream the {@link UpstreamSurfaceHook} to be used + * @param ownsDevice true if this {@link ProxySurface} instance + * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, + * otherwise false. + */ + public WrappedWindow(AbstractGraphicsConfiguration cfg, long surfaceHandle, UpstreamSurfaceHook upstream, boolean ownsDevice, long windowHandle) { + super(cfg, surfaceHandle, upstream, ownsDevice); + this.windowHandle = windowHandle; + } + + @Override + public void destroy() { + } + + @Override + public NativeWindow getParent() { + return null; + } + + @Override + public long getWindowHandle() { + return windowHandle; + } + + @Override + public InsetsImmutable getInsets() { + return insets; + } + + @Override + public int getX() { + return 0; + } + + @Override + public int getY() { + return 0; + } + + @Override + public Point getLocationOnScreen(Point point) { + if(null!=point) { + return point; + } else { + return new Point(0, 0); + } + } + + @Override + public boolean hasFocus() { + return false; + } +} -- cgit v1.2.3 From 6280428d85cdcbbc8b83b73111ccf20fe786564f Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 31 Jan 2014 10:55:19 +0100 Subject: Add NativeWindowFactory.getLocationOnScreen(NativeWindow nw) to retrieve the NativeWindow location on screen --- .../javax/media/nativewindow/NativeWindowFactory.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 1dce05192..7c491a9ee 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -43,11 +43,17 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.media.nativewindow.util.Point; +import javax.media.nativewindow.util.PointImmutable; + import jogamp.nativewindow.Debug; import jogamp.nativewindow.NativeWindowFactoryImpl; import jogamp.nativewindow.ToolkitProperties; import jogamp.nativewindow.ResourceToolkitLock; import jogamp.nativewindow.WrappedWindow; +import jogamp.nativewindow.macosx.OSXUtil; +import jogamp.nativewindow.windows.GDIUtil; +import jogamp.nativewindow.x11.X11Lib; import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; @@ -673,4 +679,17 @@ public abstract class NativeWindowFactory { return new WrappedWindow(config, surfaceHandle, hook, true, windowHandle); } + public static PointImmutable getLocationOnScreen(NativeWindow nw) { + final String nwt = NativeWindowFactory.getNativeWindowType(true); + if( NativeWindowFactory.TYPE_X11 == nwt ) { + return X11Lib.GetRelativeLocation(nw.getDisplayHandle(), nw.getScreenIndex(), nw.getWindowHandle(), 0, 0, 0); + } else if( NativeWindowFactory.TYPE_WINDOWS == nwt ) { + return GDIUtil.GetRelativeLocation(nw.getWindowHandle(), 0, 0, 0); + } else if( NativeWindowFactory.TYPE_MACOSX == nwt ) { + return OSXUtil.GetLocationOnScreen(nw.getWindowHandle(), null == nw.getParent(), 0, 0); + } + throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); + } + + } -- cgit v1.2.3 From 103939990df5c74ddb813fb03b2dbf6c12d825f5 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Fri, 31 Jan 2014 10:57:22 +0100 Subject: NativeWindowFactory.createWrappedWindow [WrappedWindow]: Using UpstreamSurfaceHookMutableSizePos to take position into account; WrappedWindow: invalidate and destroy - display device could be opened. --- .../UpstreamSurfaceHookMutableSizePos.java | 36 ++++++++++++++++++++++ .../media/nativewindow/NativeWindowFactory.java | 6 ++-- .../classes/jogamp/nativewindow/WrappedWindow.java | 26 +++++++++++----- 3 files changed, 57 insertions(+), 11 deletions(-) create mode 100644 src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSizePos.java (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSizePos.java b/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSizePos.java new file mode 100644 index 000000000..e6fcc049c --- /dev/null +++ b/src/nativewindow/classes/com/jogamp/nativewindow/UpstreamSurfaceHookMutableSizePos.java @@ -0,0 +1,36 @@ +package com.jogamp.nativewindow; + +public class UpstreamSurfaceHookMutableSizePos extends UpstreamSurfaceHookMutableSize { + int x, y; + + /** + * @param width initial width + * @param height initial height + */ + public UpstreamSurfaceHookMutableSizePos(int x, int y, int width, int height) { + super(width, height); + this.x= x; + this.y= y; + } + + // @Override + public final void setPos(int x, int y) { + this.x= x; + this.y= y; + } + + public final int getX() { + return x; + } + + public final int getY() { + return y; + } + + @Override + public String toString() { + return getClass().getSimpleName()+"[ "+ x + "/" + y + " " + width + "x" + height + "]"; + } + +} + diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 7c491a9ee..15a43cff8 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -57,7 +57,7 @@ import jogamp.nativewindow.x11.X11Lib; import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; -import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSize; +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSizePos; import com.jogamp.nativewindow.awt.AWTGraphicsDevice; import com.jogamp.nativewindow.awt.AWTGraphicsScreen; import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice; @@ -662,7 +662,7 @@ public abstract class NativeWindowFactory { /** * Creates a wrapped {@link NativeWindow} with given native handles and {@link AbstractGraphicsScreen}. *

                            - * The given {@link UpstreamSurfaceHookMutableSize} maybe used to reflect resizes of the native window. + * The given {@link UpstreamSurfaceHookMutableSizePos} maybe used to reflect resizes and repositioning of the native window. *

                            *

                            * The {@link AbstractGraphicsScreen} may be created via {@link #createScreen(AbstractGraphicsDevice, int)}. @@ -673,7 +673,7 @@ public abstract class NativeWindowFactory { *

                            */ public static NativeWindow createWrappedWindow(AbstractGraphicsScreen aScreen, long surfaceHandle, long windowHandle, - UpstreamSurfaceHookMutableSize hook) { + UpstreamSurfaceHookMutableSizePos hook) { final CapabilitiesImmutable caps = new Capabilities(); final AbstractGraphicsConfiguration config = new DefaultGraphicsConfiguration(aScreen, caps, caps); return new WrappedWindow(config, surfaceHandle, hook, true, windowHandle); diff --git a/src/nativewindow/classes/jogamp/nativewindow/WrappedWindow.java b/src/nativewindow/classes/jogamp/nativewindow/WrappedWindow.java index d5a977240..edb65eb06 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/WrappedWindow.java +++ b/src/nativewindow/classes/jogamp/nativewindow/WrappedWindow.java @@ -9,25 +9,28 @@ import javax.media.nativewindow.util.Insets; import javax.media.nativewindow.util.InsetsImmutable; import javax.media.nativewindow.util.Point; +import com.jogamp.nativewindow.UpstreamSurfaceHookMutableSizePos; + public class WrappedWindow extends WrappedSurface implements NativeWindow { - private final long windowHandle; private final InsetsImmutable insets = new Insets(0, 0, 0, 0); + private long windowHandle; /** - * Utilizes a {@link UpstreamSurfaceHook.MutableSize} to hold the size information, + * Utilizes a {@link UpstreamSurfaceHookMutableSizePos} to hold the size and postion information, * which is being passed to the {@link ProxySurface} instance. * * @param cfg the {@link AbstractGraphicsConfiguration} to be used * @param surfaceHandle the wrapped pre-existing native surface handle, maybe 0 if not yet determined + * @param initialX + * @param initialY * @param initialWidth * @param initialHeight * @param ownsDevice true if this {@link ProxySurface} instance * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, * otherwise false. Owning the device implies closing it at {@link #destroyNotify()}. */ - public WrappedWindow(AbstractGraphicsConfiguration cfg, long surfaceHandle, int initialWidth, int initialHeight, boolean ownsDevice, long windowHandle) { - super(cfg, surfaceHandle, initialWidth, initialHeight, ownsDevice); - this.windowHandle = windowHandle; + public WrappedWindow(AbstractGraphicsConfiguration cfg, long surfaceHandle, int initialX, int initialY, int initialWidth, int initialHeight, boolean ownsDevice, long windowHandle) { + this(cfg, surfaceHandle, new UpstreamSurfaceHookMutableSizePos(initialX, initialY, initialWidth, initialHeight), ownsDevice, windowHandle); } /** @@ -38,13 +41,20 @@ public class WrappedWindow extends WrappedSurface implements NativeWindow { * owns the {@link AbstractGraphicsConfiguration}'s {@link AbstractGraphicsDevice}, * otherwise false. */ - public WrappedWindow(AbstractGraphicsConfiguration cfg, long surfaceHandle, UpstreamSurfaceHook upstream, boolean ownsDevice, long windowHandle) { + public WrappedWindow(AbstractGraphicsConfiguration cfg, long surfaceHandle, UpstreamSurfaceHookMutableSizePos upstream, boolean ownsDevice, long windowHandle) { super(cfg, surfaceHandle, upstream, ownsDevice); this.windowHandle = windowHandle; } + @Override + protected void invalidateImpl() { + super.invalidateImpl(); + windowHandle = 0; + } + @Override public void destroy() { + destroyNotify(); } @Override @@ -64,12 +74,12 @@ public class WrappedWindow extends WrappedSurface implements NativeWindow { @Override public int getX() { - return 0; + return ((UpstreamSurfaceHookMutableSizePos)getUpstreamSurfaceHook()).getX(); } @Override public int getY() { - return 0; + return ((UpstreamSurfaceHookMutableSizePos)getUpstreamSurfaceHook()).getY(); } @Override -- cgit v1.2.3 From 84930529068062d29d48924b37953ecb1ee30bdd Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 12 Feb 2014 02:54:50 +0100 Subject: Bug 973: NativeWindowFactory: Needs service provider interface (SPI) for TK specific implementations (Scaling) Add FIXME note .. --- .../media/nativewindow/NativeWindowFactory.java | 23 ++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 15a43cff8..2090f1c16 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -43,7 +43,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.media.nativewindow.util.Point; import javax.media.nativewindow.util.PointImmutable; import jogamp.nativewindow.Debug; @@ -462,7 +461,7 @@ public abstract class NativeWindowFactory { * @see #getDefaultToolkitLock(java.lang.String) */ public static ToolkitLock getDefaultToolkitLock() { - return getDefaultToolkitLock(getNativeWindowType(false)); + return getDefaultToolkitLock(nativeWindowingTypePure); } /** @@ -655,8 +654,16 @@ public abstract class NativeWindowFactory { return new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT); } else if( NativeWindowFactory.TYPE_MACOSX == nwt ) { return new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); + /** + * FIXME: Move implementation to a impl. depending plug-in system (SPI) + } else if( NativeWindowFactory.TYPE_BCM_VC_IV == nwt ) { + } else if( NativeWindowFactory.TYPE_ANDROID== nwt ) { + } else if( NativeWindowFactory.TYPE_EGL == nwt ) { + } else if( NativeWindowFactory.TYPE_BCM_VC_IV == nwt ) { + } else if( NativeWindowFactory.TYPE_AWT == nwt ) { + */ } - throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); + throw new UnsupportedOperationException("n/a for windowing system: "+nwt); } /** @@ -687,8 +694,16 @@ public abstract class NativeWindowFactory { return GDIUtil.GetRelativeLocation(nw.getWindowHandle(), 0, 0, 0); } else if( NativeWindowFactory.TYPE_MACOSX == nwt ) { return OSXUtil.GetLocationOnScreen(nw.getWindowHandle(), null == nw.getParent(), 0, 0); + /** + * FIXME: Move implementation to a impl. depending plug-in system (SPI) + } else if( NativeWindowFactory.TYPE_BCM_VC_IV == nwt ) { + } else if( NativeWindowFactory.TYPE_ANDROID== nwt ) { + } else if( NativeWindowFactory.TYPE_EGL == nwt ) { + } else if( NativeWindowFactory.TYPE_BCM_VC_IV == nwt ) { + } else if( NativeWindowFactory.TYPE_AWT == nwt ) { + */ } - throw new UnsupportedOperationException("n/a for this windowing system: "+nwt); + throw new UnsupportedOperationException("n/a for windowing system: "+nwt); } -- cgit v1.2.3 From 0666a9ee8332e8ab59d533c65552dae8c58cf267 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 12 Feb 2014 02:55:14 +0100 Subject: Bug 973: NativeWindowFactory: Needs service provider interface (SPI) for TK specific implementations (Scaling) --- .../classes/javax/media/nativewindow/NativeWindowFactory.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java index 2090f1c16..034bf2456 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java +++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java @@ -655,7 +655,7 @@ public abstract class NativeWindowFactory { } else if( NativeWindowFactory.TYPE_MACOSX == nwt ) { return new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT); /** - * FIXME: Move implementation to a impl. depending plug-in system (SPI) + * FIXME: Needs service provider interface (SPI) for TK dependent implementation } else if( NativeWindowFactory.TYPE_BCM_VC_IV == nwt ) { } else if( NativeWindowFactory.TYPE_ANDROID== nwt ) { } else if( NativeWindowFactory.TYPE_EGL == nwt ) { @@ -695,7 +695,7 @@ public abstract class NativeWindowFactory { } else if( NativeWindowFactory.TYPE_MACOSX == nwt ) { return OSXUtil.GetLocationOnScreen(nw.getWindowHandle(), null == nw.getParent(), 0, 0); /** - * FIXME: Move implementation to a impl. depending plug-in system (SPI) + * FIXME: Needs service provider interface (SPI) for TK dependent implementation } else if( NativeWindowFactory.TYPE_BCM_VC_IV == nwt ) { } else if( NativeWindowFactory.TYPE_ANDROID== nwt ) { } else if( NativeWindowFactory.TYPE_EGL == nwt ) { -- cgit v1.2.3 From 21b68a5e73a672da34b37b5641b779aa1e3fa41d Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 13 Feb 2014 00:17:09 +0100 Subject: TextureIO: Support PNGTextureWriter w/ TextureData IntBuffer (via PNGPixelRect and PixelFormatUtil) TextureData IntBuffer could be caused by AWT read-pixels but is not seamlessly supported via PNGPixelRect since the latter uses a hardcoded ByteBuffer. Add static PNGPixelRect.write(..) supporting IntBuffer to support this case for now. PNGPixelRect instances do not support any Buffer type to avoid a bloated implementation. PixelFormatUtil adds support for int32 pixel format conversion. --- .../com/jogamp/opengl/util/PNGPixelRect.java | 80 ++++++++++++++++++++-- .../com/jogamp/opengl/util/texture/TextureIO.java | 40 ++++++++--- .../media/nativewindow/util/PixelFormatUtil.java | 3 +- 3 files changed, 103 insertions(+), 20 deletions(-) (limited to 'src/nativewindow') diff --git a/src/jogl/classes/com/jogamp/opengl/util/PNGPixelRect.java b/src/jogl/classes/com/jogamp/opengl/util/PNGPixelRect.java index 1bbc12f32..fd8f54152 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/PNGPixelRect.java +++ b/src/jogl/classes/com/jogamp/opengl/util/PNGPixelRect.java @@ -32,6 +32,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; +import java.nio.IntBuffer; import javax.media.nativewindow.util.Dimension; import javax.media.nativewindow.util.DimensionImmutable; @@ -248,19 +249,29 @@ public class PNGPixelRect extends PixelRectangle.GenericPixelRect { } return dOff; } - private int setPixelRGBA8(final ImageLine line, final int lineOff, final ByteBuffer d, final int dOff, final int bytesPerPixel, final boolean hasAlpha) { + private int setPixelRGBA8(final ImageLine line, final int lineOff, final ByteBuffer src, final int srcOff, final int bytesPerPixel, final boolean hasAlpha) { final int b = hasAlpha ? 4-1 : 3-1; - if( d.limit() <= dOff + b ) { - throw new IndexOutOfBoundsException("Buffer has unsufficient bytes left, needs ["+dOff+".."+(dOff+b)+"]: "+d); + if( src.limit() <= srcOff + b ) { + throw new IndexOutOfBoundsException("Buffer has unsufficient bytes left, needs ["+srcOff+".."+(srcOff+b)+"]: "+src); } - final int p = PixelFormatUtil.convertToInt32(hasAlpha ? PixelFormat.RGBA8888 : PixelFormat.RGB888, pixelformat, d, dOff); + final int p = PixelFormatUtil.convertToInt32(hasAlpha ? PixelFormat.RGBA8888 : PixelFormat.RGB888, pixelformat, src, srcOff); + line.scanline[lineOff ] = 0xff & p; // R + line.scanline[lineOff + 1] = 0xff & ( p >>> 8 ); // G + line.scanline[lineOff + 2] = 0xff & ( p >>> 16 ); // B + if(hasAlpha) { + line.scanline[lineOff + 3] = 0xff & ( p >>> 24 ); // A + } + return srcOff + pixelformat.bytesPerPixel(); + } + + private static void setPixelRGBA8(final PixelFormat pixelformat, final ImageLine line, final int lineOff, final int srcPix, final int bytesPerPixel, final boolean hasAlpha) { + final int p = PixelFormatUtil.convertToInt32(hasAlpha ? PixelFormat.RGBA8888 : PixelFormat.RGB888, pixelformat, srcPix); line.scanline[lineOff ] = 0xff & p; // R line.scanline[lineOff + 1] = 0xff & ( p >>> 8 ); // G line.scanline[lineOff + 2] = 0xff & ( p >>> 16 ); // B if(hasAlpha) { line.scanline[lineOff + 3] = 0xff & ( p >>> 24 ); // A } - return dOff + pixelformat.bytesPerPixel(); } /** @@ -304,9 +315,8 @@ public class PNGPixelRect extends PixelRectangle.GenericPixelRect { final PngWriter png = new PngWriter(outstream, imi); // add some optional metadata (chunks) png.getMetadata().setDpi(dpi[0], dpi[1]); - png.getMetadata().setTimeNow(0); // 0 seconds fron now = now + png.getMetadata().setTimeNow(0); // 0 seconds from now = now png.getMetadata().setText(PngChunkTextVar.KEY_Title, "JogAmp PNGPixelRect"); - // png.getMetadata().setText("my key", "my text"); final boolean hasAlpha = 4 == bytesPerPixel; final ImageLine l1 = new ImageLine(imi); @@ -332,4 +342,60 @@ public class PNGPixelRect extends PixelRectangle.GenericPixelRect { } } } + + public static void write(final PixelFormat pixelformat, final DimensionImmutable size, + int strideInPixels, final boolean isGLOriented, final IntBuffer pixels, + final double dpiX, final double dpiY, + final OutputStream outstream, final boolean closeOutstream) throws IOException { + final int width = size.getWidth(); + final int height = size.getHeight(); + final int bytesPerPixel = pixelformat.bytesPerPixel(); + final ImageInfo imi = new ImageInfo(width, height, 8 /* bitdepth */, + (4 == bytesPerPixel) ? true : false /* alpha */, + (1 == bytesPerPixel) ? true : false /* grayscale */, + false /* indexed */); + if( 0 != strideInPixels ) { + if( strideInPixels < size.getWidth()) { + throw new IllegalArgumentException("Invalid stride "+bytesPerPixel+", must be greater than width "+size.getWidth()); + } + } else { + strideInPixels = size.getWidth(); + } + final int reqPixels = strideInPixels * size.getHeight(); + if( pixels.limit() < reqPixels ) { + throw new IndexOutOfBoundsException("Dest buffer has insufficient pixels left, needs "+reqPixels+": "+pixels); + } + + // open image for writing to a output stream + try { + final PngWriter png = new PngWriter(outstream, imi); + // add some optional metadata (chunks) + png.getMetadata().setDpi(dpiX, dpiY); + png.getMetadata().setTimeNow(0); // 0 seconds from now = now + png.getMetadata().setText(PngChunkTextVar.KEY_Title, "JogAmp PNGPixelRect"); + final boolean hasAlpha = 4 == bytesPerPixel; + + final ImageLine l1 = new ImageLine(imi); + for (int row = 0; row < height; row++) { + int dataOff = isGLOriented ? ( height - 1 - row ) * strideInPixels : row * strideInPixels; + int lineOff = 0; + if(1 == bytesPerPixel) { + for (int j = width - 1; j >= 0; j--) { + l1.scanline[lineOff++] = pixels.get(dataOff++); // // Luminance, 1 bytesPerPixel + } + } else { + for (int j = width - 1; j >= 0; j--) { + setPixelRGBA8(pixelformat, l1, lineOff, pixels.get(dataOff++), bytesPerPixel, hasAlpha); + lineOff += bytesPerPixel; + } + } + png.writeRow(l1, row); + } + png.end(); + } finally { + if( closeOutstream ) { + IOUtil.close(outstream, false); + } + } + } } diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java index 0cde24db4..c29bd9af2 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java +++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java @@ -50,11 +50,13 @@ import java.io.OutputStream; import java.net.URL; import java.nio.Buffer; import java.nio.ByteBuffer; +import java.nio.IntBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.media.nativewindow.util.Dimension; +import javax.media.nativewindow.util.DimensionImmutable; import javax.media.nativewindow.util.PixelFormat; import javax.media.opengl.GL; import javax.media.opengl.GL2; @@ -1400,18 +1402,34 @@ public class TextureIO { final PixelFormat pixFmt = pixelAttribs.getPixelFormat(); if ( ( 1 == bytesPerPixel || 3 == bytesPerPixel || 4 == bytesPerPixel) && ( pixelType == GL.GL_BYTE || pixelType == GL.GL_UNSIGNED_BYTE)) { - ByteBuffer buf = (ByteBuffer) data.getBuffer(); - if (null == buf) { - buf = (ByteBuffer) data.getMipmapData()[0]; + Buffer buf0 = data.getBuffer(); + if (null == buf0) { + buf0 = data.getMipmapData()[0]; + } + if( null == buf0 ) { + throw new IOException("Pixel storage buffer is null"); + } + final DimensionImmutable size = new Dimension(data.getWidth(), data.getHeight()); + if( buf0 instanceof ByteBuffer ) { + final ByteBuffer buf = (ByteBuffer) buf0; + buf.rewind(); + final PNGPixelRect image = new PNGPixelRect(pixFmt, size, + 0 /* stride */, true /* isGLOriented */, buf /* pixels */, + -1f, -1f); + final OutputStream outs = new BufferedOutputStream(IOUtil.getFileOutputStream(file, true /* allowOverwrite */)); + image.write(outs, true /* close */); + return true; + } else if( buf0 instanceof IntBuffer ) { + final IntBuffer buf = (IntBuffer) buf0; + buf.rewind(); + final OutputStream outs = new BufferedOutputStream(IOUtil.getFileOutputStream(file, true /* allowOverwrite */)); + PNGPixelRect.write(pixFmt, size, + 0 /* stride */, true /* isGLOriented */, buf /* pixels */, + -1f, -1f, outs, true /* closeOutstream */); + return true; + } else { + throw new IOException("PNG writer doesn't support pixel storage buffer of type "+buf0.getClass().getName()); } - buf.rewind(); - - final PNGPixelRect image = new PNGPixelRect(pixFmt, new Dimension(data.getWidth(), data.getHeight()), - 0 /* stride */, true /* isGLOriented */, buf /* pixels */, - -1f, -1f); - final OutputStream outs = new BufferedOutputStream(IOUtil.getFileOutputStream(file, true /* allowOverwrite */)); - image.write(outs, true /* close */); - return true; } throw new IOException("PNG writer doesn't support this pixel format 0x"+Integer.toHexString(pixelFormat)+ " / type 0x"+Integer.toHexString(pixelFormat)+" (only GL_RGB/A, GL_BGR/A + bytes)"); diff --git a/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormatUtil.java b/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormatUtil.java index 361d03446..87a9ca4fc 100644 --- a/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormatUtil.java +++ b/src/nativewindow/classes/javax/media/nativewindow/util/PixelFormatUtil.java @@ -208,7 +208,6 @@ public class PixelFormatUtil { return convertToInt32(dest_fmt, r, g, b, a); } - /** public static int convertToInt32(PixelFormat dest_fmt, PixelFormat src_fmt, final int src_pixel) { final byte r, g, b, a; switch(src_fmt) { @@ -258,7 +257,7 @@ public class PixelFormatUtil { throw new InternalError("Unhandled format "+src_fmt); } return convertToInt32(dest_fmt, r, g, b, a); - } */ + } public static PixelRectangle convert32(final PixelRectangle src, final PixelFormat destFmt, int ddestStride, final boolean isGLOriented, -- cgit v1.2.3 From 8be9d9b5bd71854f4da15294b47125a8a4975e31 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 13 Feb 2014 18:12:27 +0100 Subject: SurfaceUpdatedListener: Order methods in impl. Class; SurfaceUpdatedListener: Mark methods final, use volatile 'isEmpty' to bail out early @ surfaceUpdated. --- .../com/jogamp/nativewindow/awt/JAWTWindow.java | 44 ++++++++++------------ .../jogamp/nativewindow/SurfaceUpdatedHelper.java | 25 +++++++----- .../classes/com/jogamp/newt/opengl/GLWindow.java | 40 ++++++++++---------- src/newt/classes/jogamp/newt/WindowImpl.java | 43 ++++++++++----------- 4 files changed, 76 insertions(+), 76 deletions(-) (limited to 'src/nativewindow') diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java index a57dafc92..20ab7a2ee 100644 --- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java +++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java @@ -437,30 +437,6 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return true; } - // - // SurfaceUpdateListener - // - - @Override - public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { - surfaceUpdatedHelper.addSurfaceUpdatedListener(l); - } - - @Override - public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { - surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); - } - - @Override - public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { - surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); - } - - @Override - public void surfaceUpdated(Object updater, NativeSurface ns, long when) { - surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); - } - // // NativeSurface // @@ -571,6 +547,26 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, return false; } + @Override + public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { + surfaceUpdatedHelper.addSurfaceUpdatedListener(l); + } + + @Override + public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { + surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); + } + + @Override + public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { + surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); + } + + @Override + public void surfaceUpdated(Object updater, NativeSurface ns, long when) { + surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); + } + @Override public long getSurfaceHandle() { return drawable; diff --git a/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java b/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java index 1e83232bb..0b033955e 100644 --- a/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java +++ b/src/nativewindow/classes/jogamp/nativewindow/SurfaceUpdatedHelper.java @@ -36,22 +36,23 @@ import javax.media.nativewindow.SurfaceUpdatedListener; public class SurfaceUpdatedHelper implements SurfaceUpdatedListener { private final Object surfaceUpdatedListenersLock = new Object(); private final ArrayList surfaceUpdatedListeners = new ArrayList(); + private volatile boolean isEmpty = true; // // Management Utils // - public int size() { return surfaceUpdatedListeners.size(); } - public SurfaceUpdatedListener get(int i) { return surfaceUpdatedListeners.get(i); } + public final int size() { return surfaceUpdatedListeners.size(); } + public final SurfaceUpdatedListener get(int i) { return surfaceUpdatedListeners.get(i); } // // Implementation of NativeSurface SurfaceUpdatedListener methods // - public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { + public final void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { addSurfaceUpdatedListener(-1, l); } - public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) + public final void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { if(l == null) { @@ -62,23 +63,29 @@ public class SurfaceUpdatedHelper implements SurfaceUpdatedListener { index = surfaceUpdatedListeners.size(); } surfaceUpdatedListeners.add(index, l); + isEmpty = false; } } - public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { + public final boolean removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { if (l == null) { - return; + return false; } synchronized(surfaceUpdatedListenersLock) { - surfaceUpdatedListeners.remove(l); + final boolean res = surfaceUpdatedListeners.remove(l); + isEmpty = 0 == surfaceUpdatedListeners.size(); + return res; } } @Override - public void surfaceUpdated(Object updater, NativeSurface ns, long when) { + public final void surfaceUpdated(Object updater, NativeSurface ns, long when) { + if( isEmpty ) { + return; + } synchronized(surfaceUpdatedListenersLock) { for(int i = 0; i < surfaceUpdatedListeners.size(); i++ ) { - SurfaceUpdatedListener l = surfaceUpdatedListeners.get(i); + final SurfaceUpdatedListener l = surfaceUpdatedListeners.get(i); l.surfaceUpdated(updater, ns, when); } } diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java index ca8ab6733..4b740927b 100644 --- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java +++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java @@ -682,21 +682,6 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind window.runOnEDTIfAvail(wait, task); } - @Override - public final void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { - window.removeSurfaceUpdatedListener(l); - } - - @Override - public final void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { - window.addSurfaceUpdatedListener(l); - } - - @Override - public final void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { - window.addSurfaceUpdatedListener(index, l); - } - @Override public void sendWindowEvent(int eventType) { window.sendWindowEvent(eventType); @@ -850,6 +835,26 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind return window.surfaceSwap(); } + @Override + public final void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { + window.removeSurfaceUpdatedListener(l); + } + + @Override + public final void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { + window.addSurfaceUpdatedListener(l); + } + + @Override + public final void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { + window.addSurfaceUpdatedListener(index, l); + } + + @Override + public final void surfaceUpdated(Object updater, NativeSurface ns, long when) { + window.surfaceUpdated(updater, ns, when); + } + @Override public final long getWindowHandle() { return window.getWindowHandle(); @@ -877,11 +882,6 @@ public class GLWindow extends GLAutoDrawableBase implements GLAutoDrawable, Wind return window.getScreenIndex(); } - @Override - public final void surfaceUpdated(Object updater, NativeSurface ns, long when) { - window.surfaceUpdated(updater, ns, when); - } - /** * A most simple JOGL AWT test entry */ diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java index 1e2291c8f..7f7cb61a9 100644 --- a/src/newt/classes/jogamp/newt/WindowImpl.java +++ b/src/newt/classes/jogamp/newt/WindowImpl.java @@ -810,6 +810,26 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer return false; } + @Override + public final void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { + surfaceUpdatedHelper.addSurfaceUpdatedListener(l); + } + + @Override + public final void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { + surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); + } + + @Override + public final void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { + surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); + } + + @Override + public final void surfaceUpdated(Object updater, NativeSurface ns, long when) { + surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); + } + @Override public final AbstractGraphicsConfiguration getGraphicsConfiguration() { return config.getNativeGraphicsConfiguration(); @@ -2506,29 +2526,6 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer return true; } - // - // SurfaceUpdatedListener Support - // - @Override - public final void addSurfaceUpdatedListener(SurfaceUpdatedListener l) { - surfaceUpdatedHelper.addSurfaceUpdatedListener(l); - } - - @Override - public final void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException { - surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l); - } - - @Override - public final void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) { - surfaceUpdatedHelper.removeSurfaceUpdatedListener(l); - } - - @Override - public final void surfaceUpdated(Object updater, NativeSurface ns, long when) { - surfaceUpdatedHelper.surfaceUpdated(updater, ns, when); - } - // // MouseListener/Event Support // -- cgit v1.2.3