From 488170c4c598cfce0edf363ad17e3fc3113732df Mon Sep 17 00:00:00 2001 From: Kenneth Russel Date: Sun, 15 Jan 2006 03:24:40 +0000 Subject: Moved GlueGen out of the JOGL workspace and into its own project. Restructured JOGL and JOAL build processes to separately invoke GlueGen's main build.xml before using it to generate their code. Refactored OS/CPU detection code into gluegen-cpptasks.xml build file in GlueGen workspace, which is now imported by both the JOGL and JOAL build processes. Unfortunately it seems to be somewhat difficult to completely factor out the C compiler configuration into the GlueGen workspace so this has been left for a later date. Added missed ALProcAddressLookup file to JOAL workspace. Updated JOGL and JOAL build documentation. More documentation for the GlueGen workspace is forthcoming. git-svn-id: file:///usr/local/projects/SUN/JOGL/git-svn/../svn-server-sync/gluegen/trunk@3 a78bb65f-1512-4460-ba86-f6dc96a7bf27 --- .../com/sun/gluegen/opengl/GLConfiguration.java | 198 +++++++++++++++++++++ 1 file changed, 198 insertions(+) create mode 100755 src/java/com/sun/gluegen/opengl/GLConfiguration.java (limited to 'src/java/com/sun/gluegen/opengl/GLConfiguration.java') diff --git a/src/java/com/sun/gluegen/opengl/GLConfiguration.java b/src/java/com/sun/gluegen/opengl/GLConfiguration.java new file mode 100755 index 000000000..a44f3fe9f --- /dev/null +++ b/src/java/com/sun/gluegen/opengl/GLConfiguration.java @@ -0,0 +1,198 @@ +/* + * 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 + * 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.sun.gluegen.opengl; + +import java.io.*; +import java.util.*; + +import com.sun.gluegen.*; +import com.sun.gluegen.procaddress.*; + +public class GLConfiguration extends ProcAddressConfiguration { + // The following data members support ignoring an entire extension at a time + private List/**/ glHeaders = new ArrayList(); + private Set/**/ ignoredExtensions = new HashSet(); + private BuildStaticGLInfo glInfo; + // Maps function names to the kind of buffer object it deals with + private Map/**/ bufferObjectKinds = new HashMap(); + private GLEmitter emitter; + + public GLConfiguration(GLEmitter emitter) { + super(); + this.emitter = emitter; + try { + setProcAddressNameExpr("PFN $UPPERCASE({0}) PROC"); + } catch (NoSuchElementException e) { + throw new RuntimeException("Error configuring ProcAddressNameExpr", e); + } + } + + protected void dispatch(String cmd, StringTokenizer tok, File file, String filename, int lineNo) throws IOException { + if (cmd.equalsIgnoreCase("IgnoreExtension")) + { + String sym = readString("IgnoreExtension", tok, filename, lineNo); + ignoredExtensions.add(sym); + } + else if (cmd.equalsIgnoreCase("GLHeader")) + { + String sym = readString("GLHeader", tok, filename, lineNo); + glHeaders.add(sym); + } + else if (cmd.equalsIgnoreCase("BufferObjectKind")) + { + readBufferObjectKind(tok, filename, lineNo); + } + else + { + super.dispatch(cmd,tok,file,filename,lineNo); + } + } + + protected void readBufferObjectKind(StringTokenizer tok, String filename, int lineNo) { + try { + String kindString = tok.nextToken(); + GLEmitter.BufferObjectKind kind = null; + String target = tok.nextToken(); + if (kindString.equalsIgnoreCase("UnpackPixel")) { + kind = GLEmitter.BufferObjectKind.UNPACK_PIXEL; + } else if (kindString.equalsIgnoreCase("PackPixel")) { + kind = GLEmitter.BufferObjectKind.PACK_PIXEL; + } else if (kindString.equalsIgnoreCase("Array")) { + kind = GLEmitter.BufferObjectKind.ARRAY; + } else if (kindString.equalsIgnoreCase("Element")) { + kind = GLEmitter.BufferObjectKind.ELEMENT; + } else { + throw new RuntimeException("Error parsing \"BufferObjectKind\" command at line " + lineNo + + " in file \"" + filename + "\": illegal BufferObjectKind \"" + + kindString + "\", expected one of UnpackPixel, PackPixel, Array, or Element"); + } + + bufferObjectKinds.put(target, kind); + } catch (NoSuchElementException e) { + throw new RuntimeException("Error parsing \"BufferObjectKind\" command at line " + lineNo + + " in file \"" + filename + "\"", e); + } + } + + /** Overrides javaPrologueForMethod in superclass and + automatically generates prologue code for functions associated + with buffer objects. */ + public List/**/ javaPrologueForMethod(MethodBinding binding, + boolean forImplementingMethodCall, + boolean eraseBufferAndArrayTypes) { + List/**/ res = super.javaPrologueForMethod(binding, + forImplementingMethodCall, + eraseBufferAndArrayTypes); + GLEmitter.BufferObjectKind kind = getBufferObjectKind(binding.getName()); + if (kind != null) { + // Need to generate appropriate prologue based on both buffer + // object kind and whether this variant of the MethodBinding + // is the one accepting a "long" as argument + if (res == null) { + res = new ArrayList(); + } + + String prologue = "check"; + + if (kind == GLEmitter.BufferObjectKind.UNPACK_PIXEL) { + prologue = prologue + "UnpackPBO"; + } else if (kind == GLEmitter.BufferObjectKind.PACK_PIXEL) { + prologue = prologue + "PackPBO"; + } else if (kind == GLEmitter.BufferObjectKind.ARRAY) { + prologue = prologue + "ArrayVBO"; + } else if (kind == GLEmitter.BufferObjectKind.ELEMENT) { + prologue = prologue + "ElementVBO"; + } else { + throw new RuntimeException("Unknown BufferObjectKind " + kind); + } + + if (emitter.isBufferObjectMethodBinding(binding)) { + prologue = prologue + "Enabled"; + } else { + prologue = prologue + "Disabled"; + } + + prologue = prologue + "();"; + + res.add(0, prologue); + } + + return res; + } + + public boolean shouldIgnore(String symbol) { + // Check ignored extensions based on our knowledge of the static GL info + if (glInfo != null) { + String extension = glInfo.getExtension(symbol); + if (extension != null && + ignoredExtensions.contains(extension)) { + return true; + } + } + + return super.shouldIgnore(symbol); + } + + /** Returns the kind of buffer object this function deals with, or + null if none. */ + public GLEmitter.BufferObjectKind getBufferObjectKind(String name) { + return (GLEmitter.BufferObjectKind) bufferObjectKinds.get(name); + } + + public boolean isBufferObjectFunction(String name) { + return (getBufferObjectKind(name) != null); + } + + /** Parses any GL headers specified in the configuration file for + the purpose of being able to ignore an extension at a time. */ + public void parseGLHeaders(GlueEmitterControls controls) throws IOException { + if (!glHeaders.isEmpty()) { + glInfo = new BuildStaticGLInfo(); + for (Iterator iter = glHeaders.iterator(); iter.hasNext(); ) { + String file = (String) iter.next(); + String fullPath = controls.findHeaderFile(file); + if (fullPath == null) { + throw new IOException("Unable to locate header file \"" + file + "\""); + } + glInfo.parse(fullPath); + } + } + } +} -- cgit v1.2.3 From 327d57dcc8f36e9dcce5764367e2bb759e207d92 Mon Sep 17 00:00:00 2001 From: Kenneth Russel Date: Sun, 5 Feb 2006 18:09:23 +0000 Subject: Intermediate checkin for FBO support in Java2D/JOGL bridge. Needed to keep track of server-side OpenGL objects, like textures and display lists, created by the end user to preserve the illusion of independent contexts even though they will all share textures and display lists with the Java2D OpenGL context in order to access its FBO. Added GLObjectTracker class to track creation and destruction of these objects and to support cleanup when the last referring context has been destroyed. Modified GLContextShareSet to create and install GLObjectTrackers when necessary and GLContext to ref and unref tracker appropriately. Changed GlueGen's JavaPrologue and JavaEpilogue directives (and their documentation) to perform argument name substitution. Wrote documentation section on argument name substitution and specified behavior for primitive arrays (converts to string "array_name, array_name_offset" in substitution). Rephrased GlueGen's RangeCheck directives in terms of JavaPrologue directives and deleted old specialized code. Fixed bug in handling of VBO support in GLConfiguration when JavaPrologue was present for affected functions. Added JavaPrologue and JavaEpilogue directives to all existing OpenGL routines creating server-side objects (though it's possible some were missed) to call GLObjectTracker when necessary. Added RangeCheck directives for these routines as well. Worked around bug in JOGL demos where shutdownDemo() was being called more than once. git-svn-id: file:///usr/local/projects/SUN/JOGL/git-svn/../svn-server-sync/gluegen/trunk@13 a78bb65f-1512-4460-ba86-f6dc96a7bf27 --- src/java/com/sun/gluegen/opengl/GLConfiguration.java | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'src/java/com/sun/gluegen/opengl/GLConfiguration.java') diff --git a/src/java/com/sun/gluegen/opengl/GLConfiguration.java b/src/java/com/sun/gluegen/opengl/GLConfiguration.java index a44f3fe9f..e331d16a4 100755 --- a/src/java/com/sun/gluegen/opengl/GLConfiguration.java +++ b/src/java/com/sun/gluegen/opengl/GLConfiguration.java @@ -125,9 +125,14 @@ public class GLConfiguration extends ProcAddressConfiguration { // Need to generate appropriate prologue based on both buffer // object kind and whether this variant of the MethodBinding // is the one accepting a "long" as argument - if (res == null) { - res = new ArrayList(); + // + // NOTE we MUST NOT mutate the array returned from the super + // call! + ArrayList res2 = new ArrayList(); + if (res != null) { + res2.addAll(res); } + res = res2; String prologue = "check"; @@ -152,6 +157,17 @@ public class GLConfiguration extends ProcAddressConfiguration { prologue = prologue + "();"; res.add(0, prologue); + + // Must also filter out bogus rangeCheck directives for VBO/PBO + // variants + if (emitter.isBufferObjectMethodBinding(binding)) { + for (Iterator iter = res.iterator(); iter.hasNext(); ) { + String line = (String) iter.next(); + if (line.indexOf("BufferFactory.rangeCheck") >= 0) { + iter.remove(); + } + } + } } return res; -- cgit v1.2.3 From 683dad39d72b99794096f5dbfdc2e70f443f2cf6 Mon Sep 17 00:00:00 2001 From: Kenneth Russel Date: Mon, 15 Jun 2009 22:39:33 +0000 Subject: Deleted obsolete source code in preparation for copying JOGL_2_SANDBOX on to trunk git-svn-id: file:///usr/local/projects/SUN/JOGL/git-svn/../svn-server-sync/gluegen/trunk@146 a78bb65f-1512-4460-ba86-f6dc96a7bf27 --- .../gluegen/opengl/BuildComposablePipeline.java | 607 --------------------- .../com/sun/gluegen/opengl/BuildStaticGLInfo.java | 320 ----------- .../com/sun/gluegen/opengl/GLConfiguration.java | 214 -------- src/java/com/sun/gluegen/opengl/GLEmitter.java | 179 ------ .../gluegen/opengl/GLJavaMethodBindingEmitter.java | 99 ---- 5 files changed, 1419 deletions(-) delete mode 100644 src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java delete mode 100644 src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java delete mode 100755 src/java/com/sun/gluegen/opengl/GLConfiguration.java delete mode 100644 src/java/com/sun/gluegen/opengl/GLEmitter.java delete mode 100755 src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java (limited to 'src/java/com/sun/gluegen/opengl/GLConfiguration.java') diff --git a/src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java b/src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java deleted file mode 100644 index 818f0ce2f..000000000 --- a/src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java +++ /dev/null @@ -1,607 +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 com.sun.gluegen.opengl; - -import com.sun.gluegen.*; - -import java.lang.reflect.*; -import java.io.*; -import java.util.*; -import java.util.regex.*; - -public class BuildComposablePipeline -{ - private String outputDirectory; - private Class classToComposeAround; - - // Only desktop OpenGL has immediate mode glBegin / glEnd - private boolean hasImmediateMode; - - // Desktop OpenGL and GLES1 have GL_STACK_OVERFLOW and GL_STACK_UNDERFLOW errors - private boolean hasStackOverflow; - - public static void main(String[] args) - { - String nameOfClassToComposeAround = args[0]; - Class classToComposeAround; - try { - classToComposeAround = Class.forName(nameOfClassToComposeAround); - } catch (Exception e) { - throw new RuntimeException( - "Could not find class \"" + nameOfClassToComposeAround + "\"", e); - } - - String outputDir = args[1]; - - BuildComposablePipeline composer = - new BuildComposablePipeline(classToComposeAround, outputDir); - - try - { - composer.emit(); - } - catch (IOException e) - { - throw new RuntimeException( - "Error generating composable pipeline source files", e); - } - } - - protected BuildComposablePipeline(Class classToComposeAround, String outputDirectory) - { - this.outputDirectory = outputDirectory; - this.classToComposeAround = classToComposeAround; - - if (! classToComposeAround.isInterface()) - { - throw new IllegalArgumentException( - classToComposeAround.getName() + " is not an interface class"); - } - - try { - hasImmediateMode = - (classToComposeAround.getMethod("glBegin", new Class[] { Integer.TYPE }) != null); - } catch (Exception e) { - } - - try { - hasStackOverflow = - (classToComposeAround.getField("GL_STACK_OVERFLOW") != null); - } catch (Exception e) { - } - } - - /** - * Emit the java source code for the classes that comprise the composable - * pipeline. - */ - public void emit() throws IOException - { - String pDir = outputDirectory; - String pInterface = classToComposeAround.getName(); - List/**/ publicMethods = Arrays.asList(classToComposeAround.getMethods()); - - (new DebugPipeline(pDir, pInterface)).emit(publicMethods); - (new TracePipeline(pDir, pInterface)).emit(publicMethods); - } - - //------------------------------------------------------- - - /** - * Emits a Java source file that represents one element of the composable - * pipeline. - */ - protected abstract class PipelineEmitter - { - private File file; - private String basePackage; - private String baseName; // does not include package! - private String outputDir; - - /** - * @param outputDir the directory into which the pipeline classes will be - * generated. - * @param baseInterfaceClassName the full class name (including package, - * e.g. "java.lang.String") of the interface that the pipeline wraps - * @exception IllegalArgumentException if classToComposeAround is not an - * interface. - */ - public PipelineEmitter(String outputDir, String baseInterfaceClassName) - { - int lastDot = baseInterfaceClassName.lastIndexOf('.'); - if (lastDot == -1) - { - // no package, class is at root level - this.baseName = baseInterfaceClassName; - this.basePackage = null; - } - else - { - this.baseName = baseInterfaceClassName.substring(lastDot+1); - this.basePackage = baseInterfaceClassName.substring(0, lastDot); - } - - this.outputDir = outputDir; - } - - public void emit(List/**/ methodsToWrap) throws IOException - { - String pipelineClassName = getPipelineName(); - this.file = new File(outputDir + File.separatorChar + pipelineClassName + ".java"); - String parentDir = file.getParent(); - if (parentDir != null) - { - File pDirFile = new File(parentDir); - pDirFile.mkdirs(); - } - - PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(file))); - - CodeGenUtils.emitJavaHeaders(output, - basePackage, - pipelineClassName, - "com.sun.gluegen.runtime", // FIXME: should make configurable - true, - new String[] { "java.io.*" }, - new String[] { "public" }, - new String[] { baseName }, - null, - new CodeGenUtils.EmissionCallback() { - public void emit(PrintWriter w) { emitClassDocComment(w); } - } - ); - - preMethodEmissionHook(output); - - constructorHook(output); - - for (int i = 0; i < methodsToWrap.size(); ++i) - { - Method m = (Method)methodsToWrap.get(i); - emitMethodDocComment(output, m); - emitSignature(output, m); - emitBody(output, m); - } - - postMethodEmissionHook(output); - - output.println(); - output.print(" private " + baseName + " " + getDownstreamObjectName() + ";"); - - // end the class - output.println(); - output.print("} // end class "); - output.println(pipelineClassName); - - output.flush(); - output.close(); - } - - /** Get the name of the object through which API calls should be routed. */ - protected String getDownstreamObjectName() - { - return "downstream" + baseName; - } - - protected void emitMethodDocComment(PrintWriter output, Method m) - { - } - - protected void emitSignature(PrintWriter output, Method m) - { - output.print(" public "); - output.print(' '); - output.print(JavaType.createForClass(m.getReturnType()).getName()); - output.print(' '); - output.print(m.getName()); - output.print('('); - output.print(getArgListAsString(m, true, true)); - output.println(")"); - } - - protected void emitBody(PrintWriter output, Method m) - { - output.println(" {"); - output.print(" "); - Class retType = m.getReturnType(); - - preDownstreamCallHook(output, m); - - if (retType != Void.TYPE) - { - output.print(JavaType.createForClass(retType).getName()); - output.print(" _res = "); - } - output.print(getDownstreamObjectName()); - output.print('.'); - output.print(m.getName()); - output.print('('); - output.print(getArgListAsString(m, false, true)); - output.println(");"); - - postDownstreamCallHook(output, m); - - if (retType != Void.TYPE) - { - output.println(" return _res;"); - } - output.println(" }"); - - } - - private String getArgListAsString(Method m, boolean includeArgTypes, boolean includeArgNames) - { - StringBuffer buf = new StringBuffer(256); - if (!includeArgNames && !includeArgTypes) - { - throw new IllegalArgumentException( - "Cannot generate arglist without both arg types and arg names"); - } - - Class[] argTypes = m.getParameterTypes(); - for (int i = 0; i < argTypes.length; ++i) - { - if (includeArgTypes) - { - buf.append(JavaType.createForClass(argTypes[i]).getName()); - buf.append(' '); - } - - if (includeArgNames) - { - buf.append("arg"); - buf.append(i); - } - if (i < argTypes.length-1) { buf.append(','); } - } - - return buf.toString(); - } - - /** The name of the class around which this pipeline is being - * composed. E.g., if this pipeline was constructed with - * "java.util.Set" as the baseInterfaceClassName, then this method will - * return "Set". - */ - protected String getBaseInterfaceName() - { - return baseName; - } - - /** Get the name for this pipeline class. */ - protected abstract String getPipelineName(); - - /** - * Called after the class headers have been generated, but before any - * method wrappers have been generated. - */ - protected abstract void preMethodEmissionHook(PrintWriter output); - - /** - * Emits the constructor for the pipeline; called after the preMethodEmissionHook. - */ - protected void constructorHook(PrintWriter output) { - output.print( " public " + getPipelineName() + "(" + baseName + " "); - output.println(getDownstreamObjectName() + ")"); - output.println(" {"); - output.println(" if (" + getDownstreamObjectName() + " == null) {"); - output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");"); - output.println(" }"); - output.print( " this." + getDownstreamObjectName()); - output.println(" = " + getDownstreamObjectName() + ";"); - output.println(" // Fetch GLContext object for better error checking (if possible)"); - output.println(" // FIXME: should probably put this method in GL rather than GLImpl"); - output.println(" if (" + getDownstreamObjectName() + " instanceof com.sun.opengl.impl.GLImpl) {"); - output.println(" _context = ((com.sun.opengl.impl.GLImpl) " + getDownstreamObjectName() + ").getContext();"); - output.println(" }"); - output.println(" }"); - output.println(); - } - - /** - * Called after the method wrappers have been generated, but before the - * closing parenthesis of the class is emitted. - */ - protected abstract void postMethodEmissionHook(PrintWriter output); - - /** - * Called before the pipeline routes the call to the downstream object. - */ - protected abstract void preDownstreamCallHook(PrintWriter output, Method m); - - /** - * Called after the pipeline has routed the call to the downstream object, - * but before the calling function exits or returns a value. - */ - protected abstract void postDownstreamCallHook(PrintWriter output, Method m); - - /** Emit a Javadoc comment for this pipeline class. */ - protected abstract void emitClassDocComment(PrintWriter output); - - } // end class PipelineEmitter - - //------------------------------------------------------- - - protected class DebugPipeline extends PipelineEmitter - { - String className; - String baseInterfaceClassName; - public DebugPipeline(String outputDir, String baseInterfaceClassName) - { - super(outputDir, baseInterfaceClassName); - className = "Debug" + getBaseInterfaceName(); - } - - protected String getPipelineName() - { - return className; - } - - protected void preMethodEmissionHook(PrintWriter output) - { - } - - protected void postMethodEmissionHook(PrintWriter output) - { - output.println(" private void checkGLGetError(String caller)"); - output.println(" {"); - if (hasImmediateMode) { - output.println(" if (insideBeginEndPair) {"); - output.println(" return;"); - output.println(" }"); - output.println(); - } - output.println(" // Debug code to make sure the pipeline is working; leave commented out unless testing this class"); - output.println(" //System.err.println(\"Checking for GL errors " + - "after call to \" + caller + \"()\");"); - output.println(); - output.println(" int err = " + - getDownstreamObjectName() + - ".glGetError();"); - output.println(" if (err == GL_NO_ERROR) { return; }"); - output.println(); - output.println(" StringBuffer buf = new StringBuffer("); - output.println(" \"glGetError() returned the following error codes " + - "after a call to \" + caller + \"(): \");"); - output.println(); - output.println(" // Loop repeatedly to allow for distributed GL implementations,"); - output.println(" // as detailed in the glGetError() specification"); - output.println(" int recursionDepth = 10;"); - output.println(" do {"); - output.println(" switch (err) {"); - output.println(" case GL_INVALID_ENUM: buf.append(\"GL_INVALID_ENUM \"); break;"); - output.println(" case GL_INVALID_VALUE: buf.append(\"GL_INVALID_VALUE \"); break;"); - output.println(" case GL_INVALID_OPERATION: buf.append(\"GL_INVALID_OPERATION \"); break;"); - if (hasStackOverflow) { - output.println(" case GL_STACK_OVERFLOW: buf.append(\"GL_STACK_OVERFLOW \"); break;"); - output.println(" case GL_STACK_UNDERFLOW: buf.append(\"GL_STACK_UNDERFLOW \"); break;"); - } - output.println(" case GL_OUT_OF_MEMORY: buf.append(\"GL_OUT_OF_MEMORY \"); break;"); - output.println(" case GL_NO_ERROR: throw new InternalError(\"Should not be treating GL_NO_ERROR as error\");"); - output.println(" default: throw new InternalError(\"Unknown glGetError() return value: \" + err);"); - output.println(" }"); - output.println(" } while ((--recursionDepth >= 0) && (err = " + - getDownstreamObjectName() + - ".glGetError()) != GL_NO_ERROR);"); - output.println(" throw new GLException(buf.toString());"); - output.println(" }"); - if (hasImmediateMode) { - output.println(" /** True if the pipeline is inside a glBegin/glEnd pair.*/"); - output.println(" private boolean insideBeginEndPair = false;"); - output.println(); - } - output.println(" private void checkContext() {"); - output.println(" GLContext currentContext = GLContext.getCurrent();"); - output.println(" if (currentContext == null) {"); - output.println(" throw new GLException(\"No OpenGL context is current on this thread\");"); - output.println(" }"); - output.println(" if ((_context != null) && (_context != currentContext)) {"); - output.println(" throw new GLException(\"This GL object is being incorrectly used with a different GLContext than that which created it\");"); - output.println(" }"); - output.println(" }"); - output.println(" private GLContext _context;"); - } - - protected void emitClassDocComment(PrintWriter output) - { - output.println("/**

Composable pipeline which wraps an underlying {@link GL} implementation,"); - output.println(" providing error checking after each OpenGL method call. If an error occurs,"); - output.println(" causes a {@link GLException} to be thrown at exactly the point of failure."); - output.println(" Sample code which installs this pipeline:

"); - output.println(); - output.println("
");
-      output.println("     drawable.setGL(new DebugGL(drawable.getGL()));");
-      output.println("
"); - output.println("*/"); - } - - protected void preDownstreamCallHook(PrintWriter output, Method m) - { - output.println(" checkContext();"); - } - - protected void postDownstreamCallHook(PrintWriter output, Method m) - { - if (m.getName().equals("glBegin")) - { - output.println(" insideBeginEndPair = true;"); - output.println(" // NOTE: can't check glGetError(); it's not allowed inside glBegin/glEnd pair"); - } - else - { - if (m.getName().equals("glEnd")) - { - output.println(" insideBeginEndPair = false;"); - } - - // calls to glGetError() are only allowed outside of glBegin/glEnd pairs - output.println(" checkGLGetError(\"" + m.getName() + "\");"); - } - } - - } // end class DebugPipeline - - //------------------------------------------------------- - - protected class TracePipeline extends PipelineEmitter - { - String className; - String baseInterfaceClassName; - public TracePipeline(String outputDir, String baseInterfaceClassName) - { - super(outputDir, baseInterfaceClassName); - className = "Trace" + getBaseInterfaceName(); - } - - protected String getPipelineName() - { - return className; - } - - protected void preMethodEmissionHook(PrintWriter output) - { - } - - protected void constructorHook(PrintWriter output) { - output.print( " public " + getPipelineName() + "(" + getBaseInterfaceName() + " "); - output.println(getDownstreamObjectName() + ", PrintStream " + getOutputStreamName() + ")"); - output.println(" {"); - output.println(" if (" + getDownstreamObjectName() + " == null) {"); - output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");"); - output.println(" }"); - output.print( " this." + getDownstreamObjectName()); - output.println(" = " + getDownstreamObjectName() + ";"); - output.print( " this." + getOutputStreamName()); - output.println(" = " + getOutputStreamName() + ";"); - output.println(" }"); - output.println(); - } - - protected void postMethodEmissionHook(PrintWriter output) - { - output.println("private PrintStream " + getOutputStreamName() + ";"); - output.println("private int indent = 0;"); - output.println("protected String dumpArray(Object obj)"); - output.println("{"); - output.println(" if (obj == null) return \"[null]\";"); - output.println(" StringBuffer sb = new StringBuffer(\"[\");"); - output.println(" int len = java.lang.reflect.Array.getLength(obj);"); - output.println(" int count = Math.min(len,16);"); - output.println(" for ( int i =0; i < count; i++ ) {"); - output.println(" sb.append(java.lang.reflect.Array.get(obj,i));"); - output.println(" if (i < count-1)"); - output.println(" sb.append(',');"); - output.println(" }"); - output.println(" if ( len > 16 )"); - output.println(" sb.append(\"...\").append(len);"); - output.println(" sb.append(']');"); - output.println(" return sb.toString();"); - output.println("}"); - output.println("protected void print(String str)"); - output.println("{"); - output.println(" "+getOutputStreamName()+".print(str);"); - output.println("}"); - output.println("protected void println(String str)"); - output.println("{"); - output.println(" "+getOutputStreamName()+".println(str);"); - output.println("}"); - output.println("protected void printIndent()"); - output.println("{"); - output.println(" for( int i =0; i < indent; i++) {"+getOutputStreamName()+".print(' ');}"); - output.println("}"); - } - protected void emitClassDocComment(PrintWriter output) - { - output.println("/**

Composable pipeline which wraps an underlying {@link GL} implementation,"); - output.println(" providing tracing information to a user-specified {@link java.io.PrintStream}"); - output.println(" before and after each OpenGL method call. Sample code which installs this pipeline:

"); - output.println(); - output.println("
");
-      output.println("     drawable.setGL(new TraceGL(drawable.getGL(), System.err));");
-      output.println("
"); - output.println("*/"); - } - - protected void preDownstreamCallHook(PrintWriter output, Method m) - { - Class[] params = m.getParameterTypes(); - if ( m.getName().equals("glEnd") || m.getName().equals("glEndList")) - { - output.println("indent-=2;"); - output.println(" printIndent();"); - } - else - { - output.println("printIndent();"); - } - - output.print(" print(\"" + m.getName() + "(\""); - for ( int i =0; i < params.length; i++ ) - { - if ( params[i].isArray() ) - output.print("+dumpArray(arg"+i+")"); - else - output.print("+arg"+i); - if ( i < params.length-1) - output.print("+\",\""); - } - output.println("+\")\");"); - output.print(" "); - } - - protected void postDownstreamCallHook(PrintWriter output, Method m) - { - Class ret = m.getReturnType(); - if ( ret != Void.TYPE ) - { - output.println(" println(\" = \"+_res);"); - } - else - { - output.println(" println(\"\");"); - } - } - - private String getOutputStreamName() { - return "stream"; - } - - } // end class TracePipeline -} diff --git a/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java b/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java deleted file mode 100644 index 52b9fde51..000000000 --- a/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java +++ /dev/null @@ -1,320 +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 com.sun.gluegen.opengl; - -import java.io.*; -import java.util.*; -import java.util.regex.*; - - /** - * Builds the StaticGLInfo class from the OpenGL header files (i.e., gl.h - * and glext.h) whose paths were passed as arguments to {@link - * #main(String[])}. - * - * It relies upon the assumption that a function's membership is scoped by - * preprocessor blocks in the header files that match the following pattern: - *
- * - *
-   * 
-   * #ifndef GL_XXXX
-   * GLAPI   glFuncName()
-   * #endif GL_XXXX
-   *
-   * 
- * - * 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 *);
-   * GLAPI void   glFuncName()
-   * #endif GL_VERSION_1_3
-   *
-   * #ifndef GL_ARB_texture_compression
-   * 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 - * glActiveTexture and - * glMultiTexCoord1dv - * with the symbol - * GL_VERSION_1_3 , - * and associate - * glCompressedTexImage2DARB and - * glCompressedTexImage3DARB - * with the symbol - * GL_ARB_texture_compression . - * */ -public class BuildStaticGLInfo -{ - // Handles function pointer - protected static Pattern funcPattern = - Pattern.compile("^(GLAPI|extern)?(\\s*)(\\w+)(\\*)?(\\s+)(GLAPIENTRY|APIENTRY|WINAPI)?(\\s*)([w]?gl\\w+)\\s?(\\(.*)"); - protected static Pattern associationPattern = - Pattern.compile("\\#ifndef ([W]?GL[X]?_[A-Za-z0-9_]+)"); - protected static Pattern definePattern = - Pattern.compile("\\#define ([W]?GL[X]?_[A-Za-z0-9_]+)\\s*([A-Za-z0-9_]+)"); - // Maps function / #define names to the names of the extensions they're declared in - protected Map declarationToExtensionMap = new HashMap(); - // Maps extension names to Set of identifiers (both #defines and - // function names) this extension declares - protected Map/**/ extensionToDeclarationMap = new HashMap(); - - /** - * The first argument is the package to which the StaticGLInfo class - * belongs, the second is the path to the directory in which that package's - * classes reside, and the remaining arguments are paths to the C header - * files that should be parsed - */ - public static void main(String[] args) throws IOException - { - if (args.length > 0 && args[0].equals("-test")) { - BuildStaticGLInfo builder = new BuildStaticGLInfo(); - String[] newArgs = new String[args.length - 1]; - System.arraycopy(args, 1, newArgs, 0, args.length - 1); - builder.parse(newArgs); - builder.dump(); - System.exit(0); - } - - String packageName = args[0]; - String packageDir = args[1]; - - String[] cHeaderFilePaths = new String[args.length-2]; - System.arraycopy(args, 2, cHeaderFilePaths, 0, cHeaderFilePaths.length); - - BuildStaticGLInfo builder = new BuildStaticGLInfo(); - try { - builder.parse(cHeaderFilePaths); - - File file = new File(packageDir + File.separatorChar + "StaticGLInfo.java"); - String parentDir = file.getParent(); - if (parentDir != null) { - File pDirFile = new File(parentDir); - pDirFile.mkdirs(); - } - - PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file))); - builder.emitJavaCode(writer, packageName); - - writer.flush(); - writer.close(); - } - catch (Exception e) - { - StringBuffer buf = new StringBuffer("{ "); - for (int i = 0; i < cHeaderFilePaths.length; ++i) - { - buf.append(cHeaderFilePaths[i]); - buf.append(" "); - } - buf.append('}'); - throw new RuntimeException( - "Error building StaticGLInfo.java from " + buf.toString(), e); - } - } - - - /** Parses the supplied C header files and adds the function - associations contained therein to the internal map. */ - public void parse(String[] cHeaderFilePaths) throws IOException { - for (int i = 0; i < cHeaderFilePaths.length; i++) { - parse(cHeaderFilePaths[i]); - } - } - - /** Parses the supplied C header file and adds the function - associations contained therein to the internal map. */ - public void parse(String cHeaderFilePath) throws IOException { - BufferedReader reader = new BufferedReader(new FileReader(cHeaderFilePath)); - String line, activeAssociation = null; - Matcher m = null; - while ((line = reader.readLine()) != null) { - // see if we're inside a #ifndef GL_XXX block and matching a function - if (activeAssociation != null) { - String identifier = null; - if ((m = funcPattern.matcher(line)).matches()) { - identifier = m.group(8); - } else if ((m = definePattern.matcher(line)).matches()) { - identifier = m.group(1); - } else if (line.startsWith("#endif")) { - activeAssociation = null; - } - if ((identifier != null) && - (activeAssociation != null) && - // Handles #ifndef GL_... #define GL_... - !identifier.equals(activeAssociation)) { - addAssociation(identifier, activeAssociation); - } - } else if ((m = associationPattern.matcher(line)).matches()) { - // found a new #ifndef GL_XXX block - activeAssociation = m.group(1); - - //System.err.println("FOUND NEW ASSOCIATION BLOCK: " + activeAssociation); - } - } - reader.close(); - } - - public void dump() { - for (Iterator i1 = extensionToDeclarationMap.keySet().iterator(); i1.hasNext(); ) { - String name = (String) i1.next(); - Set decls = (Set) extensionToDeclarationMap.get(name); - System.out.println(name + ":"); - List l = new ArrayList(); - l.addAll(decls); - Collections.sort(l); - for (Iterator i2 = l.iterator(); i2.hasNext(); ) { - System.out.println(" " + (String) i2.next()); - } - } - } - - public String getExtension(String identifier) { - return (String) declarationToExtensionMap.get(identifier); - } - - public Set getDeclarations(String extension) { - return (Set) extensionToDeclarationMap.get(extension); - } - - public void emitJavaCode(PrintWriter output, String packageName) { - output.println("package " + packageName + ";"); - output.println(); - output.println("import java.util.*;"); - output.println(); - output.println("public final class StaticGLInfo"); - output.println("{"); - - output.println(" // maps function names to the extension string or OpenGL"); - output.println(" // specification version string to which they correspond."); - output.println(" private static HashMap funcToAssocMap;"); - output.println(); - - output.println(" /**"); - output.println(" * Returns the OpenGL extension string or GL_VERSION string with which the"); - output.println(" * given function is associated.

"); - output.println(" *"); - output.println(" * If the"); - output.println(" * function is part of the OpenGL core, the returned value will be"); - output.println(" * GL_VERSION_XXX where XXX represents the OpenGL version of which the"); - output.println(" * function is a member (XXX will be of the form \"A\" or \"A_B\" or \"A_B_C\";"); - output.println(" * e.g., GL_VERSION_1_2_1 for OpenGL version 1.2.1)."); - output.println(" *"); - output.println(" * If the function is an extension function, the returned value will the"); - output.println(" * OpenGL extension string for the extension to which the function"); - output.println(" * corresponds. For example, if glLoadTransposeMatrixfARB is the argument,"); - output.println(" * GL_ARB_transpose_matrix will be the value returned."); - output.println(" * Please see http://oss.sgi.com/projects/ogl-sample/registry/index.html for"); - output.println(" * a list of extension names and the functions they expose."); - output.println(" *"); - output.println(" * If the function specified is not part of any known OpenGL core version or"); - output.println(" * extension, then NULL will be returned."); - output.println(" */"); - output.println(" public static String getFunctionAssociation(String glFunctionName)"); - output.println(" {"); - output.println(" return (String)funcToAssocMap.get(glFunctionName);"); - output.println(" }"); - output.println(); - - output.println(" static"); - output.println(" {"); - - // Compute max capacity - int maxCapacity = 0; - for (Iterator iter = declarationToExtensionMap.keySet().iterator(); iter.hasNext(); ) { - String name = (String) iter.next(); - if (!name.startsWith("GL")) { - ++maxCapacity; - } - } - - output.println(" funcToAssocMap = new HashMap(" + maxCapacity + "); // approximate max capacity"); - output.println(" String group;"); - ArrayList sets = new ArrayList(extensionToDeclarationMap.keySet()); - Collections.sort(sets); - for (Iterator iter = sets.iterator(); iter.hasNext(); ) { - String groupName = (String) iter.next(); - Set funcs = (Set) extensionToDeclarationMap.get(groupName); - List l = new ArrayList(); - l.addAll(funcs); - Collections.sort(l); - Iterator funcIter = l.iterator(); - boolean printedHeader = false; - while (funcIter.hasNext()) { - String funcName = (String)funcIter.next(); - if (!funcName.startsWith("GL")) { - if (!printedHeader) { - output.println(); - output.println(" //----------------------------------------------------------------"); - output.println(" // " + groupName); - output.println(" //----------------------------------------------------------------"); - output.println(" group = \"" + groupName + "\";"); - printedHeader = true; - } - - output.println(" funcToAssocMap.put(\"" + funcName + "\", group);"); - } - } - } - output.println(" }"); - output.println("} // end class StaticGLInfo"); - } - - //---------------------------------------------------------------------- - // Internals only below this point - // - - protected void addAssociation(String identifier, String association) { - declarationToExtensionMap.put(identifier, association); - Set/**/ identifiers = (Set) extensionToDeclarationMap.get(association); - if (identifiers == null) { - identifiers = new HashSet/**/(); - extensionToDeclarationMap.put(association, identifiers); - } - identifiers.add(identifier); - } -} diff --git a/src/java/com/sun/gluegen/opengl/GLConfiguration.java b/src/java/com/sun/gluegen/opengl/GLConfiguration.java deleted file mode 100755 index e331d16a4..000000000 --- a/src/java/com/sun/gluegen/opengl/GLConfiguration.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * 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 - * 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.sun.gluegen.opengl; - -import java.io.*; -import java.util.*; - -import com.sun.gluegen.*; -import com.sun.gluegen.procaddress.*; - -public class GLConfiguration extends ProcAddressConfiguration { - // The following data members support ignoring an entire extension at a time - private List/**/ glHeaders = new ArrayList(); - private Set/**/ ignoredExtensions = new HashSet(); - private BuildStaticGLInfo glInfo; - // Maps function names to the kind of buffer object it deals with - private Map/**/ bufferObjectKinds = new HashMap(); - private GLEmitter emitter; - - public GLConfiguration(GLEmitter emitter) { - super(); - this.emitter = emitter; - try { - setProcAddressNameExpr("PFN $UPPERCASE({0}) PROC"); - } catch (NoSuchElementException e) { - throw new RuntimeException("Error configuring ProcAddressNameExpr", e); - } - } - - protected void dispatch(String cmd, StringTokenizer tok, File file, String filename, int lineNo) throws IOException { - if (cmd.equalsIgnoreCase("IgnoreExtension")) - { - String sym = readString("IgnoreExtension", tok, filename, lineNo); - ignoredExtensions.add(sym); - } - else if (cmd.equalsIgnoreCase("GLHeader")) - { - String sym = readString("GLHeader", tok, filename, lineNo); - glHeaders.add(sym); - } - else if (cmd.equalsIgnoreCase("BufferObjectKind")) - { - readBufferObjectKind(tok, filename, lineNo); - } - else - { - super.dispatch(cmd,tok,file,filename,lineNo); - } - } - - protected void readBufferObjectKind(StringTokenizer tok, String filename, int lineNo) { - try { - String kindString = tok.nextToken(); - GLEmitter.BufferObjectKind kind = null; - String target = tok.nextToken(); - if (kindString.equalsIgnoreCase("UnpackPixel")) { - kind = GLEmitter.BufferObjectKind.UNPACK_PIXEL; - } else if (kindString.equalsIgnoreCase("PackPixel")) { - kind = GLEmitter.BufferObjectKind.PACK_PIXEL; - } else if (kindString.equalsIgnoreCase("Array")) { - kind = GLEmitter.BufferObjectKind.ARRAY; - } else if (kindString.equalsIgnoreCase("Element")) { - kind = GLEmitter.BufferObjectKind.ELEMENT; - } else { - throw new RuntimeException("Error parsing \"BufferObjectKind\" command at line " + lineNo + - " in file \"" + filename + "\": illegal BufferObjectKind \"" + - kindString + "\", expected one of UnpackPixel, PackPixel, Array, or Element"); - } - - bufferObjectKinds.put(target, kind); - } catch (NoSuchElementException e) { - throw new RuntimeException("Error parsing \"BufferObjectKind\" command at line " + lineNo + - " in file \"" + filename + "\"", e); - } - } - - /** Overrides javaPrologueForMethod in superclass and - automatically generates prologue code for functions associated - with buffer objects. */ - public List/**/ javaPrologueForMethod(MethodBinding binding, - boolean forImplementingMethodCall, - boolean eraseBufferAndArrayTypes) { - List/**/ res = super.javaPrologueForMethod(binding, - forImplementingMethodCall, - eraseBufferAndArrayTypes); - GLEmitter.BufferObjectKind kind = getBufferObjectKind(binding.getName()); - if (kind != null) { - // Need to generate appropriate prologue based on both buffer - // object kind and whether this variant of the MethodBinding - // is the one accepting a "long" as argument - // - // NOTE we MUST NOT mutate the array returned from the super - // call! - ArrayList res2 = new ArrayList(); - if (res != null) { - res2.addAll(res); - } - res = res2; - - String prologue = "check"; - - if (kind == GLEmitter.BufferObjectKind.UNPACK_PIXEL) { - prologue = prologue + "UnpackPBO"; - } else if (kind == GLEmitter.BufferObjectKind.PACK_PIXEL) { - prologue = prologue + "PackPBO"; - } else if (kind == GLEmitter.BufferObjectKind.ARRAY) { - prologue = prologue + "ArrayVBO"; - } else if (kind == GLEmitter.BufferObjectKind.ELEMENT) { - prologue = prologue + "ElementVBO"; - } else { - throw new RuntimeException("Unknown BufferObjectKind " + kind); - } - - if (emitter.isBufferObjectMethodBinding(binding)) { - prologue = prologue + "Enabled"; - } else { - prologue = prologue + "Disabled"; - } - - prologue = prologue + "();"; - - res.add(0, prologue); - - // Must also filter out bogus rangeCheck directives for VBO/PBO - // variants - if (emitter.isBufferObjectMethodBinding(binding)) { - for (Iterator iter = res.iterator(); iter.hasNext(); ) { - String line = (String) iter.next(); - if (line.indexOf("BufferFactory.rangeCheck") >= 0) { - iter.remove(); - } - } - } - } - - return res; - } - - public boolean shouldIgnore(String symbol) { - // Check ignored extensions based on our knowledge of the static GL info - if (glInfo != null) { - String extension = glInfo.getExtension(symbol); - if (extension != null && - ignoredExtensions.contains(extension)) { - return true; - } - } - - return super.shouldIgnore(symbol); - } - - /** Returns the kind of buffer object this function deals with, or - null if none. */ - public GLEmitter.BufferObjectKind getBufferObjectKind(String name) { - return (GLEmitter.BufferObjectKind) bufferObjectKinds.get(name); - } - - public boolean isBufferObjectFunction(String name) { - return (getBufferObjectKind(name) != null); - } - - /** Parses any GL headers specified in the configuration file for - the purpose of being able to ignore an extension at a time. */ - public void parseGLHeaders(GlueEmitterControls controls) throws IOException { - if (!glHeaders.isEmpty()) { - glInfo = new BuildStaticGLInfo(); - for (Iterator iter = glHeaders.iterator(); iter.hasNext(); ) { - String file = (String) iter.next(); - String fullPath = controls.findHeaderFile(file); - if (fullPath == null) { - throw new IOException("Unable to locate header file \"" + file + "\""); - } - glInfo.parse(fullPath); - } - } - } -} diff --git a/src/java/com/sun/gluegen/opengl/GLEmitter.java b/src/java/com/sun/gluegen/opengl/GLEmitter.java deleted file mode 100644 index 8e7484a73..000000000 --- a/src/java/com/sun/gluegen/opengl/GLEmitter.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * 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 - * 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.sun.gluegen.opengl; - -import java.io.*; -import java.text.MessageFormat; -import java.util.*; -import com.sun.gluegen.*; -import com.sun.gluegen.cgram.types.*; -import com.sun.gluegen.procaddress.*; -import com.sun.gluegen.runtime.*; - -/** - * A subclass of ProcAddressEmitter with special OpenGL-specific - * configuration abilities. - */ -public class GLEmitter extends ProcAddressEmitter -{ - // Keeps track of which MethodBindings were created for handling - // Buffer Object variants. Used as a Set rather than a Map. - private Map/**/ bufferObjectMethodBindings = new IdentityHashMap(); - - static class BufferObjectKind { - private BufferObjectKind() {} - - static final BufferObjectKind UNPACK_PIXEL = new BufferObjectKind(); - static final BufferObjectKind PACK_PIXEL = new BufferObjectKind(); - static final BufferObjectKind ARRAY = new BufferObjectKind(); - static final BufferObjectKind ELEMENT = new BufferObjectKind(); - } - - public void beginEmission(GlueEmitterControls controls) throws IOException - { - getGLConfig().parseGLHeaders(controls); - super.beginEmission(controls); - } - - protected JavaConfiguration createConfig() { - return new GLConfiguration(this); - } - - /** In order to implement Buffer Object variants of certain - functions we generate another MethodBinding which maps the void* - argument to a Java long. The generation of emitters then takes - place as usual. We do however need to keep track of the modified - MethodBinding object so that we can also modify the emitters - later to inform them that their argument has changed. We might - want to push this functionality down into the MethodBinding - (i.e., mutators for argument names). We also would need to - inform the CMethodBindingEmitter that it is overloaded in this - case (though we default to true currently). */ - protected List/**/ expandMethodBinding(MethodBinding binding) { - List/**/ bindings = super.expandMethodBinding(binding); - - if (!getGLConfig().isBufferObjectFunction(binding.getName())) { - return bindings; - } - - List/**/ newBindings = new ArrayList(); - newBindings.addAll(bindings); - - // Need to expand each one of the generated bindings to take a - // Java long instead of a Buffer for each void* argument - for (Iterator iter = bindings.iterator(); iter.hasNext(); ) { - MethodBinding cur = (MethodBinding) iter.next(); - - // Some of these routines (glBitmap) take strongly-typed - // primitive pointers as arguments which are expanded into - // non-void* arguments - // This test (rather than !signatureUsesNIO) is used to catch - // more unexpected situations - if (cur.signatureUsesJavaPrimitiveArrays()) { - continue; - } - - MethodBinding result = cur; - for (int i = 0; i < cur.getNumArguments(); i++) { - if (cur.getJavaArgumentType(i).isNIOBuffer()) { - result = result.replaceJavaArgumentType(i, JavaType.createForClass(Long.TYPE)); - } - } - - if (result == cur) { - throw new RuntimeException("Error: didn't find any void* arguments for BufferObject function " + - binding.getName()); - } - - newBindings.add(result); - // Now need to flag this MethodBinding so that we generate the - // correct flags in the emitters later - bufferObjectMethodBindings.put(result, result); - } - - return newBindings; - } - - protected boolean needsModifiedEmitters(FunctionSymbol sym) { - if ((!needsProcAddressWrapper(sym) && !needsBufferObjectVariant(sym)) || - getConfig().isUnimplemented(sym.getName())) { - return false; - } - - return true; - } - - public boolean isBufferObjectMethodBinding(MethodBinding binding) { - return bufferObjectMethodBindings.containsKey(binding); - } - - //---------------------------------------------------------------------- - // Internals only below this point - // - - protected void generateModifiedEmitters(JavaMethodBindingEmitter baseJavaEmitter, List emitters) { - List superEmitters = new ArrayList(); - super.generateModifiedEmitters(baseJavaEmitter, superEmitters); - - // See whether this is one of the Buffer Object variants - boolean bufferObjectVariant = bufferObjectMethodBindings.containsKey(baseJavaEmitter.getBinding()); - - if (bufferObjectVariant) { - for (Iterator iter = superEmitters.iterator(); iter.hasNext(); ) { - JavaMethodBindingEmitter emitter = (JavaMethodBindingEmitter) iter.next(); - if (emitter instanceof ProcAddressJavaMethodBindingEmitter) { - emitters.add(new GLJavaMethodBindingEmitter((ProcAddressJavaMethodBindingEmitter) emitter, bufferObjectVariant)); - } else { - emitters.add(emitter); - } - } - } else { - emitters.addAll(superEmitters); - } - } - - protected boolean needsBufferObjectVariant(FunctionSymbol sym) { - return getGLConfig().isBufferObjectFunction(sym.getName()); - } - - protected GLConfiguration getGLConfig() { - return (GLConfiguration) getConfig(); - } -} diff --git a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java deleted file mode 100755 index 8512f38f9..000000000 --- a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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 - * 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.sun.gluegen.opengl; - -import java.io.*; -import java.util.*; -import com.sun.gluegen.*; -import com.sun.gluegen.cgram.types.*; -import com.sun.gluegen.procaddress.*; - -/** A specialization of the proc address emitter which knows how to - change argument names to take into account Vertex Buffer Object / - Pixel Buffer Object variants. */ - -public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmitter { - protected boolean bufferObjectVariant; - - public GLJavaMethodBindingEmitter(JavaMethodBindingEmitter methodToWrap, - boolean callThroughProcAddress, - String getProcAddressTableExpr, - boolean changeNameAndArguments, - boolean bufferObjectVariant, - GLEmitter emitter) { - super(methodToWrap, - callThroughProcAddress, - getProcAddressTableExpr, - changeNameAndArguments, - emitter); - this.bufferObjectVariant = bufferObjectVariant; - } - - public GLJavaMethodBindingEmitter(ProcAddressJavaMethodBindingEmitter methodToWrap, - boolean bufferObjectVariant) { - super(methodToWrap); - this.bufferObjectVariant = bufferObjectVariant; - } - - public GLJavaMethodBindingEmitter(GLJavaMethodBindingEmitter methodToWrap) { - this(methodToWrap, methodToWrap.bufferObjectVariant); - } - - protected String getArgumentName(int i) { - String name = super.getArgumentName(i); - - if (!bufferObjectVariant) { - return name; - } - - // Emitters for VBO/PBO-related routines change the outgoing - // argument name for the buffer - if (binding.getJavaArgumentType(i).isLong()) { - Type cType = binding.getCArgumentType(i); - if (cType.isPointer() && - (cType.asPointer().getTargetType().isVoid() || - cType.asPointer().getTargetType().isPrimitive())) { - return name + "_buffer_offset"; - } - } - - return name; - } -} -- cgit v1.2.3 From 62444f682ec7a1a279d0f63af8848a8494ad9977 Mon Sep 17 00:00:00 2001 From: Kenneth Russel Date: Mon, 15 Jun 2009 22:42:48 +0000 Subject: Copied JOGL_2_SANDBOX r145 on to trunk; JOGL_2_SANDBOX branch is now closed git-svn-id: file:///usr/local/projects/SUN/JOGL/git-svn/../svn-server-sync/gluegen/trunk@147 a78bb65f-1512-4460-ba86-f6dc96a7bf27 --- .../gluegen/opengl/BuildComposablePipeline.java | 1104 ++++++++++++++++++++ .../com/sun/gluegen/opengl/BuildStaticGLInfo.java | 333 ++++++ .../com/sun/gluegen/opengl/GLConfiguration.java | 297 ++++++ src/java/com/sun/gluegen/opengl/GLEmitter.java | 407 ++++++++ .../gluegen/opengl/GLJavaMethodBindingEmitter.java | 103 ++ .../gluegen/runtime/opengl/GLExtensionNames.java | 187 ++++ 6 files changed, 2431 insertions(+) create mode 100644 src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java create mode 100644 src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java create mode 100755 src/java/com/sun/gluegen/opengl/GLConfiguration.java create mode 100644 src/java/com/sun/gluegen/opengl/GLEmitter.java create mode 100755 src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java create mode 100644 src/java/com/sun/gluegen/runtime/opengl/GLExtensionNames.java (limited to 'src/java/com/sun/gluegen/opengl/GLConfiguration.java') diff --git a/src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java b/src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java new file mode 100644 index 000000000..89176f557 --- /dev/null +++ b/src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java @@ -0,0 +1,1104 @@ +/* + * 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 com.sun.gluegen.opengl; + +import com.sun.gluegen.*; + +import java.lang.reflect.*; +import java.io.*; +import java.util.*; +import java.util.regex.*; + +public class BuildComposablePipeline +{ + public static final int GEN_DEBUG = 1 << 0 ; // default + public static final int GEN_TRACE = 1 << 1 ; // default + public static final int GEN_CUSTOM = 1 << 2 ; + public static final int GEN_PROLOG_XOR_DOWNSTREAM = 1 << 3 ; + + int mode; + private String outputDir; + private String outputPackage; + private String outputName; + private Class classToComposeAround; + private Class classPrologOpt; + private Class classDownstream; + private String basePackage; + private String baseName; // does not include package! + private String downstreamPackage; + private String downstreamName; // does not include package! + + // Only desktop OpenGL has immediate mode glBegin / glEnd + private boolean hasImmediateMode; + + // Desktop OpenGL and GLES1 have GL_STACK_OVERFLOW and GL_STACK_UNDERFLOW errors + private boolean hasStackOverflow; + + public static Class getClass(String name) { + Class clazz=null; + try { + clazz = Class.forName(name); + } catch (Exception e) { + throw new RuntimeException( + "Could not find class \"" + name + "\"", e); + } + return clazz; + } + + public static Method getMethod(Class clazz, Method m) { + Method res = null; + try { + res = clazz.getMethod(m.getName(), m.getParameterTypes()); + } catch (Exception e) { } + return res; + } + + public static void main(String[] args) + { + String classToComposeAroundName = args[0]; + Class classPrologOpt, classDownstream; + Class classToComposeAround = getClass(classToComposeAroundName); + + String outputDir = args[1]; + String outputPackage, outputName; + int mode; + + if(args.length>2) { + String outputClazzName = args[2]; + outputPackage = getPackageName(outputClazzName); + outputName = getBaseClassName(outputClazzName); + classPrologOpt = getClass(args[3]); + classDownstream = getClass(args[4]); + mode = GEN_CUSTOM; + if(args.length>5) { + if(args[5].equals("prolog_xor_downstream")) { + mode |= GEN_PROLOG_XOR_DOWNSTREAM; + } + } + } else { + outputPackage = getPackageName(classToComposeAroundName); + outputName = null; // TBD .. + classPrologOpt = null; + classDownstream = classToComposeAround; + mode = GEN_DEBUG | GEN_TRACE; + } + + BuildComposablePipeline composer = + new BuildComposablePipeline(mode, outputDir, outputPackage, outputName, classToComposeAround, classPrologOpt, classDownstream); + + try + { + composer.emit(); + } + catch (IOException e) + { + throw new RuntimeException( + "Error generating composable pipeline source files", e); + } + } + + protected BuildComposablePipeline(int mode, String outputDir, String outputPackage, String outputName, + Class classToComposeAround, Class classPrologOpt, Class classDownstream) + { + this.mode=mode; + this.outputDir=outputDir; + this.outputPackage=outputPackage; + this.outputName=outputName; + this.classToComposeAround=classToComposeAround; + this.classPrologOpt=classPrologOpt; + this.classDownstream=classDownstream; + + if (! classToComposeAround.isInterface()) + { + throw new IllegalArgumentException( + classToComposeAround.getName() + " is not an interface class"); + } + + try { + hasImmediateMode = + (classToComposeAround.getMethod("glBegin", new Class[] { Integer.TYPE }) != null); + } catch (Exception e) { + } + + try { + hasStackOverflow = + (classToComposeAround.getField("GL_STACK_OVERFLOW") != null); + } catch (Exception e) { + } + } + + /** + * Emit the java source code for the classes that comprise the composable + * pipeline. + */ + public void emit() throws IOException + { + List/**/ publicMethodsRaw = new ArrayList(); + publicMethodsRaw.addAll(Arrays.asList(classToComposeAround.getMethods())); + Set/**/ publicMethodsPlain = new HashSet(); + for (Iterator iter=publicMethodsRaw.iterator(); iter.hasNext(); ) { + Method method = (Method) iter.next(); + // Don't hook methods which aren't real GL methods, + // such as the synthetic "isGL2ES2" "getGL2ES2" + String name = method.getName(); + boolean runHooks = name.startsWith("gl"); + if (!name.startsWith("getGL") && !name.startsWith("isGL") && !name.equals("toString")) { + publicMethodsPlain.add(new PlainMethod(method, runHooks)); + } + } + + if(0!=(mode&GEN_DEBUG)) { + (new DebugPipeline(outputDir, outputPackage, classToComposeAround, classDownstream)).emit(publicMethodsPlain.iterator()); + } + if(0!=(mode&GEN_TRACE)) { + (new TracePipeline(outputDir, outputPackage, classToComposeAround, classDownstream)).emit(publicMethodsPlain.iterator()); + } + if(0!=(mode&GEN_CUSTOM)) { + (new CustomPipeline(mode, outputDir, outputPackage, outputName, classToComposeAround, classPrologOpt, classDownstream)).emit(publicMethodsPlain.iterator()); + } + } + + public static String getPackageName(String clazzName) { + int lastDot = clazzName.lastIndexOf('.'); + if (lastDot == -1) + { + // no package, class is at root level + return null; + } + return clazzName.substring(0, lastDot); + } + + public static String getBaseClassName(String clazzName) { + int lastDot = clazzName.lastIndexOf('.'); + if (lastDot == -1) + { + // no package, class is at root level + return clazzName; + } + return clazzName.substring(lastDot+1); + } + + //------------------------------------------------------- + + protected class PlainMethod + { + Method m; + boolean runHooks; + + public PlainMethod(Method m, boolean runHooks) { + this.m=m; + this.runHooks = runHooks; + } + + public Method getWrappedMethod() { return m; } + + public boolean runHooks() { return runHooks; } + + public boolean equals(Object obj) { + if(obj instanceof PlainMethod) { + PlainMethod b = (PlainMethod)obj; + boolean res = + m.getName().equals(b.m.getName()) && + m.getModifiers() == b.m.getModifiers() && + m.getReturnType().equals(b.m.getReturnType()) && + Arrays.equals( m.getParameterTypes() , b.m.getParameterTypes() ) ; + return res; + } + return false; + } + + public int hashCode() { + int hash = m.getName().hashCode() ^ m.getModifiers() ^ m.getReturnType().hashCode(); + Class[] args = m.getParameterTypes(); + for(int i=0; i 0) + argsString.append(", "); + argsString.append(args[i].getName()); + } + argsString.append(")"); + return m.toString() + + "\n\tname: " + m.getName() + + "\n\tmods: " + m.getModifiers() + + "\n\tretu: " + m.getReturnType() + + "\n\targs[" + args.length + "]: "+argsString.toString(); + } + } + + /** + * Emits a Java source file that represents one element of the composable + * pipeline. + */ + protected abstract class PipelineEmitter + { + private File file; + protected String basePackage; + protected String baseName; // does not include package! + protected String downstreamPackage; + protected String downstreamName; // does not include package! + protected String prologPackageOpt=null; + protected String prologNameOpt=null; // does not include package! + + protected String outputDir; + protected String outputPackage; + protected Class baseInterfaceClass; + protected Class prologClassOpt=null; + protected Class downstreamClass; + + /** + * @param outputDir the directory into which the pipeline classes will be + * generated. + * @param baseInterfaceClassName the full class name (including package, + * e.g. "java.lang.String") of the interface that the pipeline wraps + * @exception IllegalArgumentException if classToComposeAround is not an + * interface. + */ + public PipelineEmitter(String outputDir, String outputPackage, Class baseInterfaceClass, Class prologClassOpt, Class downstreamClass) + { + this.outputDir=outputDir; + this.outputPackage=outputPackage; + this.baseInterfaceClass=baseInterfaceClass; + this.prologClassOpt=prologClassOpt; + this.downstreamClass=downstreamClass; + + basePackage = getPackageName(baseInterfaceClass.getName()); + baseName = getBaseClassName(baseInterfaceClass.getName()); + downstreamPackage = getPackageName(downstreamClass.getName()); + downstreamName = getBaseClassName(downstreamClass.getName()); + if(null!=prologClassOpt) { + prologPackageOpt = getPackageName(prologClassOpt.getName()); + prologNameOpt = getBaseClassName(prologClassOpt.getName()); + } + } + + public void emit(Iterator/**/ methodsToWrap) throws IOException + { + String outputClassName = getOutputName(); + this.file = new File(outputDir + File.separatorChar + outputClassName + ".java"); + String parentDir = file.getParent(); + if (parentDir != null) + { + File pDirFile = new File(parentDir); + pDirFile.mkdirs(); + } + + PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(file))); + + HashSet clazzList = new HashSet(); + clazzList.add(baseInterfaceClass); + clazzList.addAll(Arrays.asList(baseInterfaceClass.getInterfaces())); + + String[] ifNames = new String[clazzList.size()]; + { + int i=0; + for (Iterator iter=clazzList.iterator(); iter.hasNext(); ) { + ifNames[i++] = new String(((Class)iter.next()).getName()); + } + } + + clazzList.add(downstreamClass); + if(null!=prologClassOpt) { + clazzList.add(prologClassOpt); + } + + String[] importNames = new String[clazzList.size()+2]; + { + int i=0; + importNames[i++] = new String("java.io.*"); + importNames[i++] = new String("javax.media.opengl.*"); + for (Iterator iter=clazzList.iterator(); iter.hasNext(); ) { + importNames[i++] = new String(((Class)iter.next()).getName()); + } + } + + CodeGenUtils.emitJavaHeaders(output, + outputPackage, + outputClassName, + "com.sun.gluegen.runtime", // FIXME: should make configurable + true, + importNames, + new String[] { "public" }, + ifNames, + null, + new CodeGenUtils.EmissionCallback() { + public void emit(PrintWriter w) { emitClassDocComment(w); } + } + ); + + preMethodEmissionHook(output); + + constructorHook(output); + + emitGLIsMethods(output); + emitGLGetMethods(output); + + while (methodsToWrap.hasNext()) + { + PlainMethod pm = (PlainMethod)methodsToWrap.next(); + Method m = pm.getWrappedMethod(); + emitMethodDocComment(output, m); + emitSignature(output, m); + emitBody(output, m, pm.runHooks()); + } + + postMethodEmissionHook(output); + + output.println(); + output.print(" private " + downstreamName + " " + getDownstreamObjectName() + ";"); + + // end the class + output.println(); + output.print("} // end class "); + output.println(outputClassName); + + output.flush(); + output.close(); + + System.out.println("wrote to file: "+file); // JAU + } + + /** Get the name of the object through which API calls should be routed. */ + protected String getDownstreamObjectName() + { + return "downstream" + downstreamName; + } + + /** Get the name of the object which shall be called as a prolog. */ + protected String getPrologObjectNameOpt() + { + if(null!=prologNameOpt) { + return "prolog" + prologNameOpt; + } + return null; + } + + protected void emitMethodDocComment(PrintWriter output, Method m) + { + } + + protected void emitSignature(PrintWriter output, Method m) + { + output.print(" public "); + output.print(' '); + output.print(JavaType.createForClass(m.getReturnType()).getName()); + output.print(' '); + output.print(m.getName()); + output.print('('); + output.print(getArgListAsString(m, true, true)); + output.println(")"); + } + + protected void emitBody(PrintWriter output, Method m, boolean runHooks) + { + output.println(" {"); + output.print(" "); + Class retType = m.getReturnType(); + + boolean callPreDownstreamHook = runHooks && hasPreDownstreamCallHook(m); + boolean callPostDownstreamHook = runHooks && hasPostDownstreamCallHook(m); + boolean callDownstream = (null!=getMethod(downstreamClass, m)) && + !( 0!=(GEN_PROLOG_XOR_DOWNSTREAM&getMode()) && callPreDownstreamHook ) ; + boolean hasResult = (retType != Void.TYPE); + + if(!callDownstream) { + if(!emptyDownstreamAllowed()) { + throw new RuntimeException("Method "+m+" has no downstream ("+downstreamName+")"); + } + } + + if(!callPreDownstreamHook && !callPostDownstreamHook && !callDownstream) { + if(!emptyMethodAllowed()) { + throw new RuntimeException("Method "+m+" is empty, no downstream ("+downstreamName+") nor prolog ("+prologNameOpt+")."); + } else { + output.print(" if(DEBUG) { System.out.println(\"WARNING: No prolog, no downstream, empty: \"+"); + printFunctionCallString(output, m); + output.println("); } "); + } + } + + if (callPreDownstreamHook) { + if(hasResult && !callDownstream) { + if(callPostDownstreamHook) { + output.print(" "+JavaType.createForClass(retType).getName()); + output.print(" _res = "); + } else { + output.print(" return "); + } + } + preDownstreamCallHook(output, m); + } + + if(callDownstream) { + if (hasResult) { + if(callPostDownstreamHook) { + output.print(" "+JavaType.createForClass(retType).getName()); + output.print(" _res = "); + } else { + output.print(" return "); + } + } + output.print(getDownstreamObjectName()); + output.print('.'); + output.print(m.getName()); + output.print('('); + output.print(getArgListAsString(m, false, true)); + output.println(");"); + } + + if (callPostDownstreamHook) { + postDownstreamCallHook(output, m); + } + + if (hasResult && callDownstream && callPostDownstreamHook) { + output.println(" return _res;"); + } + output.println(" }"); + + } + + protected String getArgListAsString(Method m, boolean includeArgTypes, boolean includeArgNames) + { + StringBuffer buf = new StringBuffer(256); + if (!includeArgNames && !includeArgTypes) + { + throw new IllegalArgumentException( + "Cannot generate arglist without both arg types and arg names"); + } + + Class[] argTypes = m.getParameterTypes(); + for (int i = 0; i < argTypes.length; ++i) + { + if (includeArgTypes) + { + buf.append(JavaType.createForClass(argTypes[i]).getName()); + buf.append(' '); + } + + if (includeArgNames) + { + buf.append("arg"); + buf.append(i); + } + if (i < argTypes.length-1) { buf.append(','); } + } + + return buf.toString(); + } + + /** The name of the class around which this pipeline is being + * composed. E.g., if this pipeline was constructed with + * "java.util.Set" as the baseInterfaceClassName, then this method will + * return "Set". + */ + protected String getBaseInterfaceName() + { + return baseName; + } + + /** Get the output name for this pipeline class. */ + protected abstract String getOutputName(); + + /** + * Called after the class headers have been generated, but before any + * method wrappers have been generated. + */ + protected void preMethodEmissionHook(PrintWriter output) { + output.println(" public static final boolean DEBUG = com.sun.opengl.impl.Debug.debug(\""+getOutputName()+"\");"); + } + + /** + * Emits the constructor for the pipeline; called after the preMethodEmissionHook. + */ + protected abstract void constructorHook(PrintWriter output); + + /** + * Called after the method wrappers have been generated, but before the + * closing parenthesis of the class is emitted. + */ + protected void postMethodEmissionHook(PrintWriter output) { + output.println( " public String toString() {"); + output.println( " StringBuffer sb = new StringBuffer();"); + output.println( " sb.append(\""+getOutputName()+" [ implementing "+baseInterfaceClass.getName()+",\\n\\t\");"); + if(null!=prologClassOpt) { + output.println( " sb.append(\" prolog: \"+"+getPrologObjectNameOpt()+".toString()+\",\\n\\t\");"); + } + output.println( " sb.append(\" downstream: \"+"+getDownstreamObjectName()+".toString()+\"\\n\\t]\");"); + output.println( " return sb.toString();"); + output.println( " }"); + } + + /** + * Called before the pipeline routes the call to the downstream object. + */ + protected abstract void preDownstreamCallHook(PrintWriter output, Method m); + protected abstract boolean hasPreDownstreamCallHook(Method m); + + /** + * Called after the pipeline has routed the call to the downstream object, + * but before the calling function exits or returns a value. + */ + protected abstract void postDownstreamCallHook(PrintWriter output, Method m); + + protected abstract boolean hasPostDownstreamCallHook(Method m); + + protected abstract int getMode(); + protected abstract boolean emptyMethodAllowed(); + protected abstract boolean emptyDownstreamAllowed(); + + /** Emit a Javadoc comment for this pipeline class. */ + protected abstract void emitClassDocComment(PrintWriter output); + + /** + * Emits one of the isGL* methods. + */ + protected void emitGLIsMethod(PrintWriter output, String type) { + output.println(" public boolean is" + type + "() {"); + Class clazz = BuildComposablePipeline.getClass("javax.media.opengl." + type); + if (clazz.isAssignableFrom(baseInterfaceClass)) { + output.println(" return true;"); + } else { + output.println(" return false;"); + } + output.println(" }"); + } + + /** + * Emits all of the isGL* methods. + */ + protected void emitGLIsMethods(PrintWriter output) { + emitGLIsMethod(output, "GL"); + emitGLIsMethod(output, "GL3"); + emitGLIsMethod(output, "GL2"); + emitGLIsMethod(output, "GLES1"); + emitGLIsMethod(output, "GLES2"); + emitGLIsMethod(output, "GL2ES1"); + emitGLIsMethod(output, "GL2ES2"); + output.println(" public boolean isGLES() {"); + output.println(" return isGLES2() || isGLES1();"); + output.println(" }"); + } + /** + * Emits one of the getGL* methods. + */ + protected void emitGLGetMethod(PrintWriter output, String type) { + output.println(" public javax.media.opengl." + type + " get" + type + "() {"); + Class clazz = BuildComposablePipeline.getClass("javax.media.opengl." + type); + if (clazz.isAssignableFrom(baseInterfaceClass)) { + output.println(" return this;"); + } else { + output.println(" throw new GLException(\"Not a " + type + " implementation\");"); + } + output.println(" }"); + } + + /** + * Emits all of the getGL* methods. + */ + protected void emitGLGetMethods(PrintWriter output) { + emitGLGetMethod(output, "GL"); + emitGLGetMethod(output, "GL3"); + emitGLGetMethod(output, "GL2"); + emitGLGetMethod(output, "GLES1"); + emitGLGetMethod(output, "GLES2"); + emitGLGetMethod(output, "GL2ES1"); + emitGLGetMethod(output, "GL2ES2"); + output.println(" public GLProfile getGLProfile() {"); + output.println(" return "+getDownstreamObjectName()+".getGLProfile();"); + output.println(" }"); + } + } // end class PipelineEmitter + + //------------------------------------------------------- + + protected class CustomPipeline extends PipelineEmitter + { + String className; + int mode; + + public CustomPipeline(int mode, String outputDir, String outputPackage, String outputName, Class baseInterfaceClass, Class prologClassOpt, Class downstreamClass) + { + super(outputDir, outputPackage, baseInterfaceClass, prologClassOpt, downstreamClass); + className = outputName; + this.mode = mode; + } + + protected String getOutputName() + { + return className; + } + + protected int getMode() { return mode; } + + protected boolean emptyMethodAllowed() { + return true; + } + protected boolean emptyDownstreamAllowed() { + return true; + } + + protected void preMethodEmissionHook(PrintWriter output) + { + super.preMethodEmissionHook(output); + } + + protected void constructorHook(PrintWriter output) { + output.print( " public " + getOutputName() + "(" ); + output.print( downstreamName + " " + getDownstreamObjectName() ); + if(null!=prologNameOpt) { + output.println( ", " + prologNameOpt + " " + getPrologObjectNameOpt() + ")"); + } else { + output.println(")"); + } + output.println(" {"); + output.println(" if (" + getDownstreamObjectName() + " == null) {"); + output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");"); + output.println(" }"); + output.print( " this." + getDownstreamObjectName()); + output.println(" = " + getDownstreamObjectName() + ";"); + if(null!=prologNameOpt) { + output.print( " this." + getPrologObjectNameOpt()); + output.println(" = " + getPrologObjectNameOpt() + ";"); + } + output.println(" }"); + output.println(); + } + + protected void postMethodEmissionHook(PrintWriter output) + { + super.postMethodEmissionHook(output); + if(null!=prologNameOpt) { + output.print(" private " + prologNameOpt + " " + getPrologObjectNameOpt() + ";"); + } + } + + protected void emitClassDocComment(PrintWriter output) + { + output.println("/**"); + output.println(" * Composable pipeline {@link "+outputPackage+"."+outputName+"}, implementing the interface"); + output.println(" * {@link "+baseInterfaceClass.getName()+"}"); + output.println(" *

"); + output.println(" * Each method follows the call graph

    "); + if(null!=prologClassOpt) { + output.println(" *
  • call prolog {@link "+prologClassOpt.getName()+"} if available"); + } + output.println(" *
  • call downstream {@link "+downstreamClass.getName()+"} if available"); + if(null!=prologClassOpt && 0!=(GEN_PROLOG_XOR_DOWNSTREAM&getMode())) { + output.println(" * and if no call to {@link "+prologClassOpt.getName()+"} is made"); + } + output.println(" *

"); + output.println(" * "); + output.println(" *

    "); + output.println(" *
  • Interface {@link "+baseInterfaceClass.getName()+"}"); + if(null!=prologClassOpt) { + output.println(" *
  • Prolog {@link "+prologClassOpt.getName()+"}"); + } + output.println(" *
  • Downstream {@link "+downstreamClass.getName()+"}"); + output.println(" *

"); + output.println(" * Sample code which installs this pipeline:

"); + output.println(" * "); + output.println("
");
+      if(null!=prologNameOpt) {
+          output.println("     drawable.setGL( new "+className+"( drawable.getGL().getGL2ES2(), new "+prologNameOpt+"( drawable.getGL().getGL2ES2() ) ) );");
+      } else {
+          output.println("     drawable.setGL( new "+className+"( drawable.getGL().getGL2ES2() ) );");
+      }
+      output.println("
"); + output.println("*/"); + } + + protected boolean hasPreDownstreamCallHook(Method m) { + return null!=getMethod(prologClassOpt, m); + } + + protected void preDownstreamCallHook(PrintWriter output, Method m) + { + if(null!=prologNameOpt) { + output.print(getPrologObjectNameOpt()); + output.print('.'); + output.print(m.getName()); + output.print('('); + output.print(getArgListAsString(m, false, true)); + output.println(");"); + } + } + + protected boolean hasPostDownstreamCallHook(Method m) { + return false; + } + + protected void postDownstreamCallHook(PrintWriter output, Method m) + { + } + + } // end class CustomPipeline + + protected class DebugPipeline extends PipelineEmitter + { + String className; + public DebugPipeline(String outputDir, String outputPackage, Class baseInterfaceClass, Class downstreamClass) + { + super(outputDir, outputPackage, baseInterfaceClass, null, downstreamClass); + className = "Debug" + getBaseInterfaceName(); + } + + protected String getOutputName() + { + return className; + } + + protected int getMode() { return 0; } + + protected boolean emptyMethodAllowed() { + return false; + } + protected boolean emptyDownstreamAllowed() { + return false; + } + + protected void preMethodEmissionHook(PrintWriter output) + { + super.preMethodEmissionHook(output); + } + + protected void constructorHook(PrintWriter output) { + output.print( " public " + getOutputName() + "(" ); + output.println( downstreamName + " " + getDownstreamObjectName() + ")"); + output.println(" {"); + output.println(" if (" + getDownstreamObjectName() + " == null) {"); + output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");"); + output.println(" }"); + output.print( " this." + getDownstreamObjectName()); + output.println(" = " + getDownstreamObjectName() + ";"); + if(null!=prologNameOpt) { + output.print( " this." + getPrologObjectNameOpt()); + output.println(" = " + getPrologObjectNameOpt() + ";"); + } + output.println(" // Fetch GLContext object for better error checking (if possible)"); + output.println(" _context = " + getDownstreamObjectName() + ".getContext();"); + output.println(" }"); + output.println(); + } + + protected void postMethodEmissionHook(PrintWriter output) + { + super.postMethodEmissionHook(output); + output.println(" private void checkGLGetError(String caller)"); + output.println(" {"); + if (hasImmediateMode) { + output.println(" if (insideBeginEndPair) {"); + output.println(" return;"); + output.println(" }"); + output.println(); + } + output.println(" // Debug code to make sure the pipeline is working; leave commented out unless testing this class"); + output.println(" //System.err.println(\"Checking for GL errors " + + "after call to \" + caller);"); + output.println(); + output.println(" int err = " + + getDownstreamObjectName() + + ".glGetError();"); + output.println(" if (err == GL_NO_ERROR) { return; }"); + output.println(); + output.println(" StringBuffer buf = new StringBuffer(Thread.currentThread()+"); + output.println(" \" glGetError() returned the following error codes " + + "after a call to \" + caller + \": \");"); + output.println(); + output.println(" // Loop repeatedly to allow for distributed GL implementations,"); + output.println(" // as detailed in the glGetError() specification"); + output.println(" int recursionDepth = 10;"); + output.println(" do {"); + output.println(" switch (err) {"); + output.println(" case GL_INVALID_ENUM: buf.append(\"GL_INVALID_ENUM \"); break;"); + output.println(" case GL_INVALID_VALUE: buf.append(\"GL_INVALID_VALUE \"); break;"); + output.println(" case GL_INVALID_OPERATION: buf.append(\"GL_INVALID_OPERATION \"); break;"); + if (hasStackOverflow) { + output.println(" case GL_STACK_OVERFLOW: buf.append(\"GL_STACK_OVERFLOW \"); break;"); + output.println(" case GL_STACK_UNDERFLOW: buf.append(\"GL_STACK_UNDERFLOW \"); break;"); + } + output.println(" case GL_OUT_OF_MEMORY: buf.append(\"GL_OUT_OF_MEMORY \"); break;"); + output.println(" case GL_NO_ERROR: throw new InternalError(\"Should not be treating GL_NO_ERROR as error\");"); + output.println(" default: buf.append(\"Unknown glGetError() return value: \");"); + output.println(" }"); + output.println(" buf.append(\"( \" + err + \" 0x\"+Integer.toHexString(err).toUpperCase() + \"), \");"); + output.println(" } while ((--recursionDepth >= 0) && (err = " + + getDownstreamObjectName() + + ".glGetError()) != GL_NO_ERROR);"); + output.println(" throw new GLException(buf.toString());"); + output.println(" }"); + if (hasImmediateMode) { + output.println(" /** True if the pipeline is inside a glBegin/glEnd pair.*/"); + output.println(" private boolean insideBeginEndPair = false;"); + output.println(); + } + output.println(" private void checkContext() {"); + output.println(" GLContext currentContext = GLContext.getCurrent();"); + output.println(" if (currentContext == null) {"); + output.println(" throw new GLException(\"No OpenGL context is current on this thread\");"); + output.println(" }"); + output.println(" if ((_context != null) && (_context != currentContext)) {"); + output.println(" throw new GLException(\"This GL object is being incorrectly used with a different GLContext than that which created it\");"); + output.println(" }"); + output.println(" }"); + output.println(" private GLContext _context;"); + } + + protected void emitClassDocComment(PrintWriter output) + { + output.println("/**

Composable pipeline which wraps an underlying {@link GL} implementation,"); + output.println(" providing error checking after each OpenGL method call. If an error occurs,"); + output.println(" causes a {@link GLException} to be thrown at exactly the point of failure."); + output.println(" Sample code which installs this pipeline:

"); + output.println(); + output.println("
");
+      output.println("     drawable.setGL(new DebugGL(drawable.getGL()));");
+      output.println("
"); + output.println("*/"); + } + + protected boolean hasPreDownstreamCallHook(Method m) { + return true; + } + + protected void preDownstreamCallHook(PrintWriter output, Method m) + { + output.println(" checkContext();"); + } + + protected boolean hasPostDownstreamCallHook(Method m) { + return true; + } + + protected void postDownstreamCallHook(PrintWriter output, Method m) + { + if (m.getName().equals("glBegin")) + { + output.println(" insideBeginEndPair = true;"); + output.println(" // NOTE: can't check glGetError(); it's not allowed inside glBegin/glEnd pair"); + } + else + { + if (m.getName().equals("glEnd")) + { + output.println(" insideBeginEndPair = false;"); + } + + output.println(" String txt = new String(\""+ m.getName() + "(\" +"); + Class[] params = m.getParameterTypes() ; + for(int i=0; params!=null && i 0x\"+Integer.toHexString(arg"+i+").toUpperCase() +"); + } else { + output.println(" \"<"+params[i].getName()+">\" +"); + } + if(i 16 )"); + output.println(" sb.append(\"...\").append(len);"); + output.println(" sb.append(']');"); + output.println(" return sb.toString();"); + output.println("}"); + output.println("protected void print(String str)"); + output.println("{"); + output.println(" "+getOutputStreamName()+".print(str);"); + output.println("}"); + output.println("protected void println(String str)"); + output.println("{"); + output.println(" "+getOutputStreamName()+".println(str);"); + output.println("}"); + output.println("protected void printIndent()"); + output.println("{"); + output.println(" for( int i =0; i < indent; i++) {"+getOutputStreamName()+".print(' ');}"); + output.println("}"); + } + protected void emitClassDocComment(PrintWriter output) + { + output.println("/**

Composable pipeline which wraps an underlying {@link GL} implementation,"); + output.println(" providing tracing information to a user-specified {@link java.io.PrintStream}"); + output.println(" before and after each OpenGL method call. Sample code which installs this pipeline:

"); + output.println(); + output.println("
");
+      output.println("     drawable.setGL(new TraceGL(drawable.getGL(), System.err));");
+      output.println("
"); + output.println("*/"); + } + + protected boolean hasPreDownstreamCallHook(Method m) { + return true; + } + + protected void preDownstreamCallHook(PrintWriter output, Method m) + { + if ( m.getName().equals("glEnd") || m.getName().equals("glEndList")) + { + output.println("indent-=2;"); + output.println(" printIndent();"); + } + else + { + output.println("printIndent();"); + } + + output.print(" println("); + printFunctionCallString(output, m); + output.println(");"); + } + + protected boolean hasPostDownstreamCallHook(Method m) { + return true; + } + + protected void postDownstreamCallHook(PrintWriter output, Method m) + { + Class ret = m.getReturnType(); + if ( ret != Void.TYPE ) + { + output.println(" println(\" = \"+_res);"); + } + else + { + output.println(" println(\"\");"); + } + } + + private String getOutputStreamName() { + return "stream"; + } + + } // end class TracePipeline + + public static final void printFunctionCallString(PrintWriter output, Method m) { + Class[] params = m.getParameterTypes(); + output.print(" \"" + m.getName() + "(\""); + for ( int i =0; i < params.length; i++ ) + { + if ( params[i].isArray() ) { + output.print("+\"<"+params[i].getName()+">\""); + } else if(params[i].equals(int.class)) { + output.print("+\"<"+params[i].getName()+"> 0x\"+Integer.toHexString(arg"+i+").toUpperCase()"); + } else { + output.print("+\"<"+params[i].getName()+">\"+arg"+i); + } + if ( i < params.length-1) { + output.print("+\",\""); + } + } + output.print("+\")\""); + } +} diff --git a/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java b/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java new file mode 100644 index 000000000..4226f4612 --- /dev/null +++ b/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java @@ -0,0 +1,333 @@ +/* + * 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 com.sun.gluegen.opengl; + +import java.io.*; +import java.util.*; +import java.util.regex.*; + + /** + * Builds the StaticGLInfo class from the OpenGL header files (i.e., gl.h + * and glext.h) whose paths were passed as arguments to {@link + * #main(String[])}. + * + * It relies upon the assumption that a function's membership is scoped by + * preprocessor blocks in the header files that match the following pattern: + *
+ * + *
+   * 
+   * #ifndef GL_XXXX
+   * GLAPI   glFuncName()
+   * #endif GL_XXXX
+   *
+   * 
+ * + * 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 *);
+   * GLAPI void   glFuncName()
+   * #endif GL_VERSION_1_3
+   *
+   * #ifndef GL_ARB_texture_compression
+   * 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 + * glActiveTexture and + * glMultiTexCoord1dv + * with the symbol + * GL_VERSION_1_3 , + * and associate + * glCompressedTexImage2DARB and + * glCompressedTexImage3DARB + * with the symbol + * GL_ARB_texture_compression . + * */ +public class BuildStaticGLInfo +{ + // Handles function pointer + protected static Pattern funcPattern = + Pattern.compile("^(GLAPI|GL_API|GL_APICALL|EGLAPI|extern)?(\\s*)(\\w+)(\\*)?(\\s+)(GLAPIENTRY|GL_APIENTRY|APIENTRY|EGLAPIENTRY|WINAPI)?(\\s*)([ew]?gl\\w+)\\s?(\\(.*)"); + protected static Pattern associationPattern = + Pattern.compile("\\#ifndef ([EW]?GL[X]?_[A-Za-z0-9_]+)"); + protected static Pattern definePattern = + Pattern.compile("\\#define ([EW]?GL[X]?_[A-Za-z0-9_]+)\\s*([A-Za-z0-9_]+)"); + // Maps function / #define names to the names of the extensions they're declared in + protected Map declarationToExtensionMap = new HashMap(); + // Maps extension names to Set of identifiers (both #defines and + // function names) this extension declares + protected Map/**/ extensionToDeclarationMap = new HashMap(); + + /** + * The first argument is the package to which the StaticGLInfo class + * belongs, the second is the path to the directory in which that package's + * classes reside, and the remaining arguments are paths to the C header + * files that should be parsed + */ + public static void main(String[] args) throws IOException + { + if (args.length > 0 && args[0].equals("-test")) { + BuildStaticGLInfo builder = new BuildStaticGLInfo(); + String[] newArgs = new String[args.length - 1]; + System.arraycopy(args, 1, newArgs, 0, args.length - 1); + builder.parse(newArgs); + builder.dump(); + System.exit(0); + } + + String packageName = args[0]; + String packageDir = args[1]; + + String[] cHeaderFilePaths = new String[args.length-2]; + System.arraycopy(args, 2, cHeaderFilePaths, 0, cHeaderFilePaths.length); + + BuildStaticGLInfo builder = new BuildStaticGLInfo(); + try { + builder.parse(cHeaderFilePaths); + + File file = new File(packageDir + File.separatorChar + "StaticGLInfo.java"); + String parentDir = file.getParent(); + if (parentDir != null) { + File pDirFile = new File(parentDir); + pDirFile.mkdirs(); + } + + PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file))); + builder.emitJavaCode(writer, packageName); + + writer.flush(); + writer.close(); + } + catch (Exception e) + { + StringBuffer buf = new StringBuffer("{ "); + for (int i = 0; i < cHeaderFilePaths.length; ++i) + { + buf.append(cHeaderFilePaths[i]); + buf.append(" "); + } + buf.append('}'); + throw new RuntimeException( + "Error building StaticGLInfo.java from " + buf.toString(), e); + } + } + + + /** Parses the supplied C header files and adds the function + associations contained therein to the internal map. */ + public void parse(String[] cHeaderFilePaths) throws IOException { + for (int i = 0; i < cHeaderFilePaths.length; i++) { + parse(cHeaderFilePaths[i]); + } + } + + /** Parses the supplied C header file and adds the function + associations contained therein to the internal map. */ + public void parse(String cHeaderFilePath) throws IOException { + BufferedReader reader = new BufferedReader(new FileReader(cHeaderFilePath)); + String line, activeAssociation = null; + Matcher m = null; + while ((line = reader.readLine()) != null) { + // see if we're inside a #ifndef GL_XXX block and matching a function + if (activeAssociation != null) { + String identifier = null; + if ((m = funcPattern.matcher(line)).matches()) { + identifier = m.group(8); + } else if ((m = definePattern.matcher(line)).matches()) { + identifier = m.group(1); + } else if (line.startsWith("#endif")) { + activeAssociation = null; + } + if ((identifier != null) && + (activeAssociation != null) && + // Handles #ifndef GL_... #define GL_... + !identifier.equals(activeAssociation)) { + addAssociation(identifier, activeAssociation); + // System.err.println(" ADDING ASSOCIATION: " + identifier + " " + activeAssociation); + } + } else if ((m = associationPattern.matcher(line)).matches()) { + // found a new #ifndef GL_XXX block + activeAssociation = m.group(1); + + // System.err.println("FOUND NEW ASSOCIATION BLOCK: " + activeAssociation); + } + } + reader.close(); + } + + public void dump() { + for (Iterator i1 = extensionToDeclarationMap.keySet().iterator(); i1.hasNext(); ) { + String name = (String) i1.next(); + Set decls = (Set) extensionToDeclarationMap.get(name); + System.out.println(name + ":"); + List l = new ArrayList(); + l.addAll(decls); + Collections.sort(l); + for (Iterator i2 = l.iterator(); i2.hasNext(); ) { + System.out.println(" " + (String) i2.next()); + } + } + } + + public String getExtension(String identifier) { + return (String) declarationToExtensionMap.get(identifier); + } + + public Set/**/ getDeclarations(String extension) { + return (Set) extensionToDeclarationMap.get(extension); + } + + public Set/**/ getExtensions() { + return extensionToDeclarationMap.keySet(); + } + + public void emitJavaCode(PrintWriter output, String packageName) { + output.println("package " + packageName + ";"); + output.println(); + output.println("import java.util.*;"); + output.println(); + output.println("public final class StaticGLInfo"); + output.println("{"); + + output.println(" // maps function names to the extension string or OpenGL"); + output.println(" // specification version string to which they correspond."); + output.println(" private static HashMap funcToAssocMap;"); + output.println(); + + output.println(" /**"); + output.println(" * Returns the OpenGL extension string or GL_VERSION string with which the"); + output.println(" * given function is associated.

"); + output.println(" *"); + output.println(" * If the"); + output.println(" * function is part of the OpenGL core, the returned value will be"); + output.println(" * GL_VERSION_XXX where XXX represents the OpenGL version of which the"); + output.println(" * function is a member (XXX will be of the form \"A\" or \"A_B\" or \"A_B_C\";"); + output.println(" * e.g., GL_VERSION_1_2_1 for OpenGL version 1.2.1)."); + output.println(" *"); + output.println(" * If the function is an extension function, the returned value will the"); + output.println(" * OpenGL extension string for the extension to which the function"); + output.println(" * corresponds. For example, if glLoadTransposeMatrixfARB is the argument,"); + output.println(" * GL_ARB_transpose_matrix will be the value returned."); + output.println(" * Please see http://oss.sgi.com/projects/ogl-sample/registry/index.html for"); + output.println(" * a list of extension names and the functions they expose."); + output.println(" *"); + output.println(" * If the function specified is not part of any known OpenGL core version or"); + output.println(" * extension, then NULL will be returned."); + output.println(" */"); + output.println(" public static String getFunctionAssociation(String glFunctionName)"); + output.println(" {"); + output.println(" String mappedName = null;"); + output.println(" int funcNamePermNum = com.sun.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutationNumber(glFunctionName);"); + output.println(" for(int i = 0; null==mappedName && i < funcNamePermNum; i++) {"); + output.println(" String tmp = com.sun.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutation(glFunctionName, i);"); + output.println(" try {"); + output.println(" mappedName = (String)funcToAssocMap.get(tmp);"); + output.println(" } catch (Exception e) { }"); + output.println(" }"); + output.println(" return mappedName;"); + output.println(" }"); + output.println(); + + output.println(" static"); + output.println(" {"); + + // Compute max capacity + int maxCapacity = 0; + for (Iterator iter = declarationToExtensionMap.keySet().iterator(); iter.hasNext(); ) { + String name = (String) iter.next(); + if (!name.startsWith("GL")) { + ++maxCapacity; + } + } + + output.println(" funcToAssocMap = new HashMap(" + maxCapacity + "); // approximate max capacity"); + output.println(" String group;"); + ArrayList sets = new ArrayList(extensionToDeclarationMap.keySet()); + Collections.sort(sets); + for (Iterator iter = sets.iterator(); iter.hasNext(); ) { + String groupName = (String) iter.next(); + Set funcs = (Set) extensionToDeclarationMap.get(groupName); + List l = new ArrayList(); + l.addAll(funcs); + Collections.sort(l); + Iterator funcIter = l.iterator(); + boolean printedHeader = false; + while (funcIter.hasNext()) { + String funcName = (String)funcIter.next(); + if (!funcName.startsWith("GL")) { + if (!printedHeader) { + output.println(); + output.println(" //----------------------------------------------------------------"); + output.println(" // " + groupName); + output.println(" //----------------------------------------------------------------"); + output.println(" group = \"" + groupName + "\";"); + printedHeader = true; + } + + output.println(" funcToAssocMap.put(\"" + funcName + "\", group);"); + } + } + } + output.println(" }"); + output.println("} // end class StaticGLInfo"); + } + + //---------------------------------------------------------------------- + // Internals only below this point + // + + protected void addAssociation(String identifier, String association) { + declarationToExtensionMap.put(identifier, association); + Set/**/ identifiers = (Set) extensionToDeclarationMap.get(association); + if (identifiers == null) { + identifiers = new HashSet/**/(); + extensionToDeclarationMap.put(association, identifiers); + } + identifiers.add(identifier); + } +} diff --git a/src/java/com/sun/gluegen/opengl/GLConfiguration.java b/src/java/com/sun/gluegen/opengl/GLConfiguration.java new file mode 100755 index 000000000..3013848dc --- /dev/null +++ b/src/java/com/sun/gluegen/opengl/GLConfiguration.java @@ -0,0 +1,297 @@ +/* + * 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 + * 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.sun.gluegen.opengl; + +import java.io.*; +import java.util.*; + +import com.sun.gluegen.*; +import com.sun.gluegen.procaddress.*; +import com.sun.gluegen.runtime.opengl.GLExtensionNames; + +public class GLConfiguration extends ProcAddressConfiguration { + // The following data members support ignoring an entire extension at a time + private List/**/ glHeaders = new ArrayList(); + private Set/**/ ignoredExtensions = new HashSet(); + private Set/**/ extensionsRenamedIntoCore = new HashSet(); + private BuildStaticGLInfo glInfo; + // Maps function names to the kind of buffer object it deals with + private Map/**/ bufferObjectKinds = new HashMap(); + private GLEmitter emitter; + private Set/*String*/ dropUniqVendorExtensions = new HashSet(); + // This directive is off by default but can help automatically + // indicate which extensions have been folded into the core OpenGL + // namespace, and if not, then why not + private boolean autoUnifyExtensions; + + public GLConfiguration(GLEmitter emitter) { + super(); + this.emitter = emitter; + try { + setProcAddressNameExpr("PFN $UPPERCASE({0}) PROC"); + } catch (NoSuchElementException e) { + throw new RuntimeException("Error configuring ProcAddressNameExpr", e); + } + } + + protected void dispatch(String cmd, StringTokenizer tok, File file, String filename, int lineNo) throws IOException { + if (cmd.equalsIgnoreCase("IgnoreExtension")) + { + String sym = readString("IgnoreExtension", tok, filename, lineNo); + ignoredExtensions.add(sym); + } + else if (cmd.equalsIgnoreCase("RenameExtensionIntoCore")) + { + String sym = readString("RenameExtensionIntoCore", tok, filename, lineNo); + extensionsRenamedIntoCore.add(sym); + } + else if (cmd.equalsIgnoreCase("AutoUnifyExtensions")) + { + autoUnifyExtensions = readBoolean("AutoUnifyExtensions", tok, filename, lineNo).booleanValue(); + } + else if (cmd.equalsIgnoreCase("GLHeader")) + { + String sym = readString("GLHeader", tok, filename, lineNo); + glHeaders.add(sym); + } + else if (cmd.equalsIgnoreCase("BufferObjectKind")) + { + readBufferObjectKind(tok, filename, lineNo); + } + else if (cmd.equalsIgnoreCase("DropUniqVendorExtensions")) + { + String sym = readString("DropUniqVendorExtensions", tok, filename, lineNo); + dropUniqVendorExtensions.add(sym); + } + else + { + super.dispatch(cmd,tok,file,filename,lineNo); + } + } + + protected void readBufferObjectKind(StringTokenizer tok, String filename, int lineNo) { + try { + String kindString = tok.nextToken(); + GLEmitter.BufferObjectKind kind = null; + String target = tok.nextToken(); + if (kindString.equalsIgnoreCase("UnpackPixel")) { + kind = GLEmitter.BufferObjectKind.UNPACK_PIXEL; + } else if (kindString.equalsIgnoreCase("PackPixel")) { + kind = GLEmitter.BufferObjectKind.PACK_PIXEL; + } else if (kindString.equalsIgnoreCase("Array")) { + kind = GLEmitter.BufferObjectKind.ARRAY; + } else if (kindString.equalsIgnoreCase("Element")) { + kind = GLEmitter.BufferObjectKind.ELEMENT; + } else { + throw new RuntimeException("Error parsing \"BufferObjectKind\" command at line " + lineNo + + " in file \"" + filename + "\": illegal BufferObjectKind \"" + + kindString + "\", expected one of UnpackPixel, PackPixel, Array, or Element"); + } + + bufferObjectKinds.put(target, kind); + } catch (NoSuchElementException e) { + throw new RuntimeException("Error parsing \"BufferObjectKind\" command at line " + lineNo + + " in file \"" + filename + "\"", e); + } + } + + /** Overrides javaPrologueForMethod in superclass and + automatically generates prologue code for functions associated + with buffer objects. */ + public List/**/ javaPrologueForMethod(MethodBinding binding, + boolean forImplementingMethodCall, + boolean eraseBufferAndArrayTypes) { + List/**/ res = super.javaPrologueForMethod(binding, + forImplementingMethodCall, + eraseBufferAndArrayTypes); + GLEmitter.BufferObjectKind kind = getBufferObjectKind(binding.getName()); + if (kind != null) { + // Need to generate appropriate prologue based on both buffer + // object kind and whether this variant of the MethodBinding + // is the one accepting a "long" as argument + // + // NOTE we MUST NOT mutate the array returned from the super + // call! + ArrayList res2 = new ArrayList(); + if (res != null) { + res2.addAll(res); + } + res = res2; + + String prologue = "check"; + + if (kind == GLEmitter.BufferObjectKind.UNPACK_PIXEL) { + prologue = prologue + "UnpackPBO"; + } else if (kind == GLEmitter.BufferObjectKind.PACK_PIXEL) { + prologue = prologue + "PackPBO"; + } else if (kind == GLEmitter.BufferObjectKind.ARRAY) { + prologue = prologue + "ArrayVBO"; + } else if (kind == GLEmitter.BufferObjectKind.ELEMENT) { + prologue = prologue + "ElementVBO"; + } else { + throw new RuntimeException("Unknown BufferObjectKind " + kind); + } + + if (emitter.isBufferObjectMethodBinding(binding)) { + prologue = prologue + "Enabled"; + } else { + prologue = prologue + "Disabled"; + } + + prologue = prologue + "(true);"; + + res.add(0, prologue); + + // Must also filter out bogus rangeCheck directives for VBO/PBO + // variants + if (emitter.isBufferObjectMethodBinding(binding)) { + for (Iterator iter = res.iterator(); iter.hasNext(); ) { + String line = (String) iter.next(); + if (line.indexOf("BufferFactory.rangeCheck") >= 0) { + iter.remove(); + } + } + } + } + + return res; + } + + public void dumpIgnores() { + System.err.println("GL Ignored extensions: "); + for (Iterator iter = ignoredExtensions.iterator(); iter.hasNext(); ) { + System.err.println("\t"+(String)iter.next()); + } + super.dumpIgnores(); + } + + protected boolean shouldIgnoreExtension(String symbol, boolean criteria) { + if (criteria && glInfo != null) { + String extension = glInfo.getExtension(symbol); + if (extension != null && + ignoredExtensions.contains(extension)) { + return true; + } + boolean isGLFunc = GLExtensionNames.isGLFunction(symbol); + boolean isGLEnum = GLExtensionNames.isGLEnumeration(symbol); + if(isGLFunc || isGLEnum) { + if(GLExtensionNames.isExtensionVEN(symbol, isGLFunc)) { + String extSuffix = GLExtensionNames.getExtensionSuffix(symbol, isGLFunc); + if( getDropUniqVendorExtensions(extSuffix) ) { + if(DEBUG_IGNORES) { + System.err.println("Ignore UniqVendorEXT: "+symbol); + } + return true; + } + } + } + } + return false; + } + + public boolean shouldIgnoreInInterface(String symbol) { + return shouldIgnoreInInterface(symbol, true); + } + + public boolean shouldIgnoreInInterface(String symbol, boolean checkEXT) { + return shouldIgnoreExtension(symbol, checkEXT) || super.shouldIgnoreInInterface(symbol); + } + + public boolean shouldIgnoreInImpl(String symbol) { + return shouldIgnoreInImpl(symbol, true); + } + + public boolean shouldIgnoreInImpl(String symbol, boolean checkEXT) { + return shouldIgnoreExtension(symbol, checkEXT) || super.shouldIgnoreInImpl(symbol); + } + + /** Should we automatically ignore extensions that have already been + fully subsumed into the OpenGL core namespace, and if they have + not been, indicate which definition is not already in the core? */ + public boolean getAutoUnifyExtensions() { + return autoUnifyExtensions; + } + + /** shall the non unified (uniq) vendor extensions be dropped ? */ + public boolean getDropUniqVendorExtensions(String extName) { + return dropUniqVendorExtensions.contains(extName); + } + + /** Returns the kind of buffer object this function deals with, or + null if none. */ + public GLEmitter.BufferObjectKind getBufferObjectKind(String name) { + return (GLEmitter.BufferObjectKind) bufferObjectKinds.get(name); + } + + public boolean isBufferObjectFunction(String name) { + return (getBufferObjectKind(name) != null); + } + + /** Parses any GL headers specified in the configuration file for + the purpose of being able to ignore an extension at a time. */ + public void parseGLHeaders(GlueEmitterControls controls) throws IOException { + if (!glHeaders.isEmpty()) { + glInfo = new BuildStaticGLInfo(); + for (Iterator iter = glHeaders.iterator(); iter.hasNext(); ) { + String file = (String) iter.next(); + String fullPath = controls.findHeaderFile(file); + if (fullPath == null) { + throw new IOException("Unable to locate header file \"" + file + "\""); + } + glInfo.parse(fullPath); + } + } + } + + /** Returns the information about the association between #defines, + function symbols and the OpenGL extensions they are defined + in. */ + public BuildStaticGLInfo getGLInfo() { + return glInfo; + } + + /** Returns the OpenGL extensions that should have all of their + constant definitions and functions renamed into the core + namespace; for example, glGenFramebuffersEXT to + glGenFramebuffers and GL_FRAMEBUFFER_EXT to GL_FRAMEBUFFER. */ + public Set/**/ getExtensionsRenamedIntoCore() { + return extensionsRenamedIntoCore; + } +} diff --git a/src/java/com/sun/gluegen/opengl/GLEmitter.java b/src/java/com/sun/gluegen/opengl/GLEmitter.java new file mode 100644 index 000000000..fff9d7e94 --- /dev/null +++ b/src/java/com/sun/gluegen/opengl/GLEmitter.java @@ -0,0 +1,407 @@ +/* + * 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 + * 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.sun.gluegen.opengl; + +import java.io.*; +import java.text.MessageFormat; +import java.util.*; +import com.sun.gluegen.*; +import com.sun.gluegen.cgram.types.*; +import com.sun.gluegen.procaddress.*; +import com.sun.gluegen.runtime.*; +import com.sun.gluegen.runtime.opengl.GLExtensionNames; + +/** + * A subclass of ProcAddressEmitter with special OpenGL-specific + * configuration abilities. + */ +public class GLEmitter extends ProcAddressEmitter +{ + // Keeps track of which MethodBindings were created for handling + // Buffer Object variants. Used as a Set rather than a Map. + private Map/**/ bufferObjectMethodBindings = new IdentityHashMap(); + + static class BufferObjectKind { + private BufferObjectKind() {} + + static final BufferObjectKind UNPACK_PIXEL = new BufferObjectKind(); + static final BufferObjectKind PACK_PIXEL = new BufferObjectKind(); + static final BufferObjectKind ARRAY = new BufferObjectKind(); + static final BufferObjectKind ELEMENT = new BufferObjectKind(); + } + + public void beginEmission(GlueEmitterControls controls) throws IOException + { + getGLConfig().parseGLHeaders(controls); + renameExtensionsIntoCore(); + if (getGLConfig().getAutoUnifyExtensions()) { + unifyExtensions(controls); + } + super.beginEmission(controls); + } + + protected void renameExtensionsIntoCore() { + // This method handles renaming of entire extensions into the + // OpenGL core namespace. For example, it is used to move certain + // OpenGL ES (OES) extensions into the core namespace which are + // already in the core namespace in desktop OpenGL. It builds upon + // renaming mechanisms that are built elsewhere. + + GLConfiguration config = getGLConfig(); + BuildStaticGLInfo glInfo = config.getGLInfo(); + for (Iterator iter = config.getExtensionsRenamedIntoCore().iterator(); + iter.hasNext(); ) { + String extension = (String) iter.next(); + Set/**/ declarations = glInfo.getDeclarations(extension); + if (declarations != null) { + for (Iterator i2 = declarations.iterator(); i2.hasNext(); ) { + String decl = (String) i2.next(); + boolean isGLFunction = GLExtensionNames.isGLFunction(decl); + boolean isGLEnumeration = false; + if (!isGLFunction) { + isGLEnumeration = GLExtensionNames.isGLEnumeration(decl); + } + if (isGLFunction || isGLEnumeration) { + String renamed = GLExtensionNames.normalize(decl, isGLFunction); + if(!renamed.equals(decl)) { + config.addJavaSymbolRename(decl, renamed); + } + } + } + } + } + } + + class ExtensionUnifier implements SymbolFilter { + private List/**/ constants; + private List/**/ functions; + + public void filterSymbols(List/**/ constants, + List/**/ functions) { + this.constants = constants; + this.functions = functions; + doWork(); + } + + public List/**/ getConstants() { + return constants; + } + + public List/**/ getFunctions() { + return functions; + } + + private void doWork() { + BuildStaticGLInfo glInfo = getGLConfig().getGLInfo(); + if (glInfo == null) { + return; + } + // Try to retain a "good" ordering for these symbols + Map/**/ constantMap = new LinkedHashMap(); + Map/**/ functionMap = new LinkedHashMap(); + for (Iterator iter = constants.iterator(); iter.hasNext(); ) { + ConstantDefinition def = (ConstantDefinition) iter.next(); + constantMap.put(def.getName(), def); + } + for (Iterator iter = functions.iterator(); iter.hasNext(); ) { + FunctionSymbol sym = (FunctionSymbol) iter.next(); + functionMap.put(sym.getName(), sym); + } + // Go through all of the declared extensions. + // For each extension, look at its #define and function symbols. + // If we find all of the extension's symbols in the core API under + // non-ARB (or whatever is the suffix) names, then remove this extension + // from the public API. If it turns out that we are running on hardware + // that doesn't support the core version of these APIs, the runtime + // will take care of looking up the extension version of these entry + // points. + Set/**/ extensionNames = glInfo.getExtensions(); + for (Iterator iter1 = extensionNames.iterator(); iter1.hasNext(); ) { + String extension = (String) iter1.next(); + Set/**/ declarations = glInfo.getDeclarations(extension); + boolean isExtension = true; + boolean shouldUnify = true; + String cause = null; + for (Iterator iter2 = declarations.iterator(); iter2.hasNext(); ) { + String decl = (String) iter2.next(); + boolean isFunc = !decl.startsWith("GL_"); + if (!GLExtensionNames.isExtension(decl, isFunc)) { + isExtension = false; + break; + } + // See whether we're emitting glue code for this + // entry point or definition at all + if (isFunc) { + if (!functionMap.containsKey(decl)) { + isExtension = false; + break; + } + } else { + if (!constantMap.containsKey(decl)) { + isExtension = false; + break; + } + } + cause = decl; + String unifiedName = GLExtensionNames.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 + // headers that actually contain the core entry + // point. Think of the case where we are parsing the + // GLES2 gl2.h, which contains certain desktop + // OpenGL extensions that have been moved into the + // core, but later generating the implementing glue + // code (not the interface) for the desktop gl.h / + // glext.h. + shouldUnify = (glInfo.getExtension(unifiedName) != null); + // if (isFunc) { + // shouldUnify = functionMap.containsKey(unifiedName); + // } else { + // shouldUnify = constantMap.containsKey(unifiedName); + // } + if (!shouldUnify) { + break; + } + } + if (isExtension) { + if (shouldUnify) { + for (Iterator iter2 = declarations.iterator(); iter2.hasNext(); ) { + String decl = (String) iter2.next(); + boolean isFunc = !decl.startsWith("GL_"); + if (isFunc) { + functionMap.remove(decl); + } else { + constantMap.remove(decl); + } + } + System.err.println("INFO: unified extension " + extension + " into core API"); + } else { + System.err.println("INFO: didn't unify extension " + extension + " into core API because of " + cause); + } + } + } + constants = new ArrayList(); + for (Iterator iter = constantMap.keySet().iterator(); iter.hasNext(); ) { + constants.add(constantMap.get(iter.next())); + } + functions = new ArrayList(); + for (Iterator iter = functionMap.keySet().iterator(); iter.hasNext(); ) { + functions.add(functionMap.get(iter.next())); + } + } + } + + private void unifyExtensions(GlueEmitterControls controls) { + controls.runSymbolFilter(new ExtensionUnifier()); + } + + protected JavaConfiguration createConfig() { + return new GLConfiguration(this); + } + + /** In order to implement Buffer Object variants of certain + functions we generate another MethodBinding which maps the void* + argument to a Java long. The generation of emitters then takes + place as usual. We do however need to keep track of the modified + MethodBinding object so that we can also modify the emitters + later to inform them that their argument has changed. We might + want to push this functionality down into the MethodBinding + (i.e., mutators for argument names). We also would need to + inform the CMethodBindingEmitter that it is overloaded in this + case (though we default to true currently). */ + protected List/**/ expandMethodBinding(MethodBinding binding) { + List/**/ bindings = super.expandMethodBinding(binding); + + if (!getGLConfig().isBufferObjectFunction(binding.getName())) { + return bindings; + } + + List/**/ newBindings = new ArrayList(); + newBindings.addAll(bindings); + + // Need to expand each one of the generated bindings to take a + // Java long instead of a Buffer for each void* argument + for (Iterator iter = bindings.iterator(); iter.hasNext(); ) { + MethodBinding cur = (MethodBinding) iter.next(); + + // Some of these routines (glBitmap) take strongly-typed + // primitive pointers as arguments which are expanded into + // non-void* arguments + // This test (rather than !signatureUsesNIO) is used to catch + // more unexpected situations + if (cur.signatureUsesJavaPrimitiveArrays()) { + continue; + } + + MethodBinding result = cur; + for (int i = 0; i < cur.getNumArguments(); i++) { + if (cur.getJavaArgumentType(i).isNIOBuffer()) { + result = result.replaceJavaArgumentType(i, JavaType.createForClass(Long.TYPE)); + } + } + + if (result == cur) { + throw new RuntimeException("Error: didn't find any void* arguments for BufferObject function " + + binding.getName()); + } + + newBindings.add(result); + // Now need to flag this MethodBinding so that we generate the + // correct flags in the emitters later + bufferObjectMethodBindings.put(result, result); + } + + return newBindings; + } + + protected boolean needsModifiedEmitters(FunctionSymbol sym) { + if ((!needsProcAddressWrapper(sym) && !needsBufferObjectVariant(sym)) || + getConfig().isUnimplemented(sym.getName())) { + return false; + } + + return true; + } + + public boolean isBufferObjectMethodBinding(MethodBinding binding) { + return bufferObjectMethodBindings.containsKey(binding); + } + + //---------------------------------------------------------------------- + // Internals only below this point + // + + protected void generateModifiedEmitters(JavaMethodBindingEmitter baseJavaEmitter, List emitters) { + List superEmitters = new ArrayList(); + super.generateModifiedEmitters(baseJavaEmitter, superEmitters); + + // See whether this is one of the Buffer Object variants + boolean bufferObjectVariant = bufferObjectMethodBindings.containsKey(baseJavaEmitter.getBinding()); + + for (Iterator iter = superEmitters.iterator(); iter.hasNext(); ) { + JavaMethodBindingEmitter emitter = (JavaMethodBindingEmitter) iter.next(); + if (emitter instanceof ProcAddressJavaMethodBindingEmitter) { + emitters.add(new GLJavaMethodBindingEmitter((ProcAddressJavaMethodBindingEmitter) emitter, this, bufferObjectVariant)); + } else { + emitters.add(emitter); + } + } + } + + protected boolean needsBufferObjectVariant(FunctionSymbol sym) { + return getGLConfig().isBufferObjectFunction(sym.getName()); + } + + protected GLConfiguration getGLConfig() { + return (GLConfiguration) getConfig(); + } + + protected void endProcAddressTable() throws Exception + { + PrintWriter w = tableWriter; + + w.println(" /**"); + w.println(" * This is a convenience method to get (by name) the native function"); + w.println(" * pointer for a given function. It lets you avoid having to"); + w.println(" * manually compute the "" + PROCADDRESS_VAR_PREFIX + " + "); + w.println(" * <functionName>" member variable name and look it up via"); + w.println(" * reflection; it also will throw an exception if you try to get the"); + w.println(" * address of an unknown function, or one that is statically linked"); + w.println(" * and therefore does not have a function pointer in this table."); + w.println(" *"); + w.println(" * @throws RuntimeException if the function pointer was not found in"); + w.println(" * this table, either because the function was unknown or because"); + w.println(" * it was statically linked."); + w.println(" */"); + w.println(" public long getAddressFor(String functionNameUsr) {"); + w.println(" String functionNameBase = com.sun.gluegen.runtime.opengl.GLExtensionNames.normalizeVEN(com.sun.gluegen.runtime.opengl.GLExtensionNames.normalizeARB(functionNameUsr, true), true);"); + w.println(" String addressFieldNameBase = " + getProcAddressConfig().gluegenRuntimePackage() + ".ProcAddressHelper.PROCADDRESS_VAR_PREFIX + functionNameBase;"); + w.println(" java.lang.reflect.Field addressField = null;"); + w.println(" int funcNamePermNum = com.sun.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutationNumber(functionNameBase);"); + w.println(" for(int i = 0; null==addressField && i < funcNamePermNum; i++) {"); + w.println(" String addressFieldName = com.sun.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutation(addressFieldNameBase, i);"); + w.println(" try {"); + w.println(" addressField = getClass().getField(addressFieldName);"); + w.println(" } catch (Exception e) { }"); + w.println(" }"); + w.println(""); + w.println(" if(null==addressField) {"); + w.println(" // The user is calling a bogus function or one which is not"); + w.println(" // runtime linked"); + w.println(" throw new RuntimeException("); + w.println(" \"WARNING: Address field query failed for \\\"\" + functionNameBase + \"\\\"/\\\"\" + functionNameUsr +"); + w.println(" \"\\\"; it's either statically linked or address field is not a known \" +"); + w.println(" \"function\");"); + w.println(" } "); + w.println(" try {"); + w.println(" return addressField.getLong(this);"); + w.println(" } catch (Exception e) {"); + w.println(" throw new RuntimeException("); + w.println(" \"WARNING: Address query failed for \\\"\" + functionNameBase + \"\\\"/\\\"\" + functionNameUsr +"); + w.println(" \"\\\"; it's either statically linked or is not a known \" +"); + w.println(" \"function\", e);"); + w.println(" }"); + w.println(" }"); + + w.println("} // end of class " + tableClassName); + w.flush(); + w.close(); + } + + protected void emitProcAddressTableEntryForSymbol(FunctionSymbol cFunc) + { + emitProcAddressTableEntryForString(cFunc.getName()); + } + + protected void emitProcAddressTableEntryForString(String str) + { + // Deal gracefully with forced proc address generation in the face + // of having the function pointer typedef in the header file too + if (emittedTableEntries.contains(str)) + return; + emittedTableEntries.add(str); + tableWriter.print(" public long "); + tableWriter.print(PROCADDRESS_VAR_PREFIX); + tableWriter.print(str); + tableWriter.println(";"); + } + +} diff --git a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java new file mode 100755 index 000000000..c6a030935 --- /dev/null +++ b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java @@ -0,0 +1,103 @@ +/* + * 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 + * 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.sun.gluegen.opengl; + +import java.io.*; +import java.util.*; +import com.sun.gluegen.*; +import com.sun.gluegen.cgram.types.*; +import com.sun.gluegen.procaddress.*; + +/** A specialization of the proc address emitter which knows how to + change argument names to take into account Vertex Buffer Object / + Pixel Buffer Object variants. */ + +public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmitter { + protected boolean bufferObjectVariant; + protected GLEmitter glEmitter; + + public GLJavaMethodBindingEmitter(JavaMethodBindingEmitter methodToWrap, + boolean callThroughProcAddress, + String getProcAddressTableExpr, + boolean changeNameAndArguments, + boolean bufferObjectVariant, + GLEmitter emitter) { + super(methodToWrap, + callThroughProcAddress, + getProcAddressTableExpr, + changeNameAndArguments, + emitter); + this.bufferObjectVariant = bufferObjectVariant; + this.glEmitter=emitter; + } + + public GLJavaMethodBindingEmitter(ProcAddressJavaMethodBindingEmitter methodToWrap, + GLEmitter emitter, + boolean bufferObjectVariant) { + super(methodToWrap); + this.bufferObjectVariant = bufferObjectVariant; + this.glEmitter=emitter; + } + + public GLJavaMethodBindingEmitter(GLJavaMethodBindingEmitter methodToWrap) { + this(methodToWrap, methodToWrap.glEmitter, methodToWrap.bufferObjectVariant); + } + + protected String getArgumentName(int i) { + String name = super.getArgumentName(i); + + if (!bufferObjectVariant) { + return name; + } + + // Emitters for VBO/PBO-related routines change the outgoing + // argument name for the buffer + if (binding.getJavaArgumentType(i).isLong()) { + Type cType = binding.getCArgumentType(i); + if (cType.isPointer() && + (cType.asPointer().getTargetType().isVoid() || + cType.asPointer().getTargetType().isPrimitive())) { + return name + "_buffer_offset"; + } + } + + return name; + } +} diff --git a/src/java/com/sun/gluegen/runtime/opengl/GLExtensionNames.java b/src/java/com/sun/gluegen/runtime/opengl/GLExtensionNames.java new file mode 100644 index 000000000..3c6f6002a --- /dev/null +++ b/src/java/com/sun/gluegen/runtime/opengl/GLExtensionNames.java @@ -0,0 +1,187 @@ +/* + * 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 + * 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.sun.gluegen.runtime.opengl; + +import java.util.*; +import com.sun.gluegen.runtime.*; + +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", + "APPLE", + "ATI", + "EXT", + "HP", + "IBM", + "MESA", + "MESAX", + "NV", + "SGI", + "SGIS", + "SGIX", + "SUN", + "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 Date: Sun, 2 Aug 2009 17:25:30 -0700 Subject: OpenGL: Add comment: Part of --- src/java/com/sun/gluegen/opengl/GLConfiguration.java | 7 +++++++ src/java/com/sun/gluegen/opengl/GLEmitter.java | 20 +++++++++++++++++--- .../gluegen/opengl/GLJavaMethodBindingEmitter.java | 17 +++++++++++++++++ 3 files changed, 41 insertions(+), 3 deletions(-) (limited to 'src/java/com/sun/gluegen/opengl/GLConfiguration.java') diff --git a/src/java/com/sun/gluegen/opengl/GLConfiguration.java b/src/java/com/sun/gluegen/opengl/GLConfiguration.java index 3013848dc..923dcf52d 100755 --- a/src/java/com/sun/gluegen/opengl/GLConfiguration.java +++ b/src/java/com/sun/gluegen/opengl/GLConfiguration.java @@ -202,6 +202,13 @@ public class GLConfiguration extends ProcAddressConfiguration { super.dumpIgnores(); } + protected String getExtension(String symbol) { + if (glInfo != null) { + return glInfo.getExtension(symbol); + } + return null; + } + protected boolean shouldIgnoreExtension(String symbol, boolean criteria) { if (criteria && glInfo != null) { String extension = glInfo.getExtension(symbol); diff --git a/src/java/com/sun/gluegen/opengl/GLEmitter.java b/src/java/com/sun/gluegen/opengl/GLEmitter.java index fff9d7e94..83e688eec 100644 --- a/src/java/com/sun/gluegen/opengl/GLEmitter.java +++ b/src/java/com/sun/gluegen/opengl/GLEmitter.java @@ -305,6 +305,21 @@ public class GLEmitter extends ProcAddressEmitter return bufferObjectMethodBindings.containsKey(binding); } + public void emitDefine(String name, String value, String optionalComment) throws Exception { + String extensionName = getGLConfig().getExtension(name); + StringBuffer newComment = new StringBuffer(); + if(null!=extensionName) { + newComment.append("Part of "+extensionName+""); + } else { + newComment.append("Part of unknown extension"); + } + if(null!=optionalComment) { + newComment.append(" "); + newComment.append(optionalComment); + } + super.emitDefine(name, value, newComment.toString()); + } + //---------------------------------------------------------------------- // Internals only below this point // @@ -319,10 +334,9 @@ public class GLEmitter extends ProcAddressEmitter for (Iterator iter = superEmitters.iterator(); iter.hasNext(); ) { JavaMethodBindingEmitter emitter = (JavaMethodBindingEmitter) iter.next(); if (emitter instanceof ProcAddressJavaMethodBindingEmitter) { - emitters.add(new GLJavaMethodBindingEmitter((ProcAddressJavaMethodBindingEmitter) emitter, this, bufferObjectVariant)); - } else { - emitters.add(emitter); + emitter = new GLJavaMethodBindingEmitter((ProcAddressJavaMethodBindingEmitter) emitter, this, bufferObjectVariant); } + emitters.add(emitter); } } diff --git a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java index c6a030935..b952272f3 100755 --- a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java +++ b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java @@ -52,6 +52,7 @@ import com.sun.gluegen.procaddress.*; public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmitter { protected boolean bufferObjectVariant; protected GLEmitter glEmitter; + protected CommentEmitter glCommentEmitter = new GLCommentEmitter(); public GLJavaMethodBindingEmitter(JavaMethodBindingEmitter methodToWrap, boolean callThroughProcAddress, @@ -66,6 +67,7 @@ public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmit emitter); this.bufferObjectVariant = bufferObjectVariant; this.glEmitter=emitter; + setCommentEmitter(glCommentEmitter); } public GLJavaMethodBindingEmitter(ProcAddressJavaMethodBindingEmitter methodToWrap, @@ -74,6 +76,7 @@ public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmit super(methodToWrap); this.bufferObjectVariant = bufferObjectVariant; this.glEmitter=emitter; + setCommentEmitter(glCommentEmitter); } public GLJavaMethodBindingEmitter(GLJavaMethodBindingEmitter methodToWrap) { @@ -100,4 +103,18 @@ public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmit return name; } + + protected class GLCommentEmitter + extends JavaMethodBindingEmitter.DefaultCommentEmitter + { + protected void emitBindingCSignature(MethodBinding binding, PrintWriter writer) { + super.emitBindingCSignature(binding, writer); + String extensionName = glEmitter.getGLConfig().getExtension(binding.getCSymbol().getName()); + if(null!=extensionName) { + writer.print("
Part of "+extensionName+""); + } else { + writer.print("
Part of unknown extension"); + } + } + } } -- cgit v1.2.3 From ae26bd0aac4a98c26aceb95584988defae970dde Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 5 Aug 2009 07:31:49 -0700 Subject: Cleanup for a better OpenGL 3.2 integration, for subsuming extensions: - Allow RenameExtensionIntoCore generate duplicate names, ie those will not be generated. - Add proper comment showing the extension of the symbol. - Fail if no 'GLHeader' is specified, but we are processing a GL/ProcAddress config - Fail if a GL function is not part of an extension MethodBinding, ConstantDefinition cleanup: - getName() returns the renamed name - getOrigName() returns the original - getAliasedNames() returns the aliased ones MethodBinding: - Change: equals() operates on renamed name - Add: hashCode() function - same criteria as equals() Impact: - All config options etc shall trigger with the renamed name, but ignore, rename etc. - Generated Java impl. uses the renamed base name as well Change: emitDefine() uses the ConstantDefinition Add: JavaConfiguration: dumpRenames() Change JavaConfiguration.shouldIgnoreInInterface/Impl(): - respect the renamed symbol name as well Change JavaEmitter.emitFunctions(): - only emit a generated MethodBinding once, therefor store emitted method bindings in a HashSet Fix BuildStaticGLInfo: - Allow white space at the end of #ifndef and #define - Trim strings - Allow 'const' qualifier in function pattern Fix GLEmitter: - Fail if no 'GLHeader' is specified, but a RenameIntoCore option .. - Don't emit marker defines, marking an extension (ie not part of an extension) Fix GLJavaMethodBindingEmitter: - Fail if a GL function is not part of an extension Fix PCPP: - Pass constant type qualifiers for hex-constants: 'l' 'L' ... Fix ProcAddressEmitter: - Operate on the aliased/renamed name for querying ProcAddress usage and generating code. --- .../com/sun/gluegen/opengl/BuildStaticGLInfo.java | 40 +++++++--- .../com/sun/gluegen/opengl/GLConfiguration.java | 11 +-- src/java/com/sun/gluegen/opengl/GLEmitter.java | 92 +++++++++++++++------- .../gluegen/opengl/GLJavaMethodBindingEmitter.java | 19 +++-- 4 files changed, 110 insertions(+), 52 deletions(-) (limited to 'src/java/com/sun/gluegen/opengl/GLConfiguration.java') diff --git a/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java b/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java index 4226f4612..f5193dcdf 100644 --- a/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java +++ b/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java @@ -91,17 +91,23 @@ import java.util.regex.*; public class BuildStaticGLInfo { // Handles function pointer + protected static int funcIdentifierGroup = 9; protected static Pattern funcPattern = - Pattern.compile("^(GLAPI|GL_API|GL_APICALL|EGLAPI|extern)?(\\s*)(\\w+)(\\*)?(\\s+)(GLAPIENTRY|GL_APIENTRY|APIENTRY|EGLAPIENTRY|WINAPI)?(\\s*)([ew]?gl\\w+)\\s?(\\(.*)"); + Pattern.compile("^(GLAPI|GL_API|GL_APICALL|EGLAPI|extern)?(\\s*)(const\\s+)?(\\w+)(\\s*\\*)?(\\s+)(GLAPIENTRY|GL_APIENTRY|APIENTRY|EGLAPIENTRY|WINAPI)?(\\s*)([ew]?gl\\w+)\\s?(\\(.*)"); + protected static Pattern associationPattern = - Pattern.compile("\\#ifndef ([EW]?GL[X]?_[A-Za-z0-9_]+)"); + Pattern.compile("\\#ifndef ([EW]?GL[X]?_[A-Za-z0-9_]+)\\s*"); + + protected static int defineIdentifierGroup = 1; protected static Pattern definePattern = - Pattern.compile("\\#define ([EW]?GL[X]?_[A-Za-z0-9_]+)\\s*([A-Za-z0-9_]+)"); + Pattern.compile("\\#define ([EW]?GL[X]?_[A-Za-z0-9_]+)\\s*([A-Za-z0-9_]+)\\s*"); + // Maps function / #define names to the names of the extensions they're declared in protected Map declarationToExtensionMap = new HashMap(); // Maps extension names to Set of identifiers (both #defines and // function names) this extension declares protected Map/**/ extensionToDeclarationMap = new HashMap(); + protected boolean debug = false; /** * The first argument is the package to which the StaticGLInfo class @@ -113,6 +119,7 @@ public class BuildStaticGLInfo { if (args.length > 0 && args[0].equals("-test")) { BuildStaticGLInfo builder = new BuildStaticGLInfo(); + builder.setDebug(true); String[] newArgs = new String[args.length - 1]; System.arraycopy(args, 1, newArgs, 0, args.length - 1); builder.parse(newArgs); @@ -157,6 +164,9 @@ public class BuildStaticGLInfo } } + public void setDebug(boolean v) { + debug = v; + } /** Parses the supplied C header files and adds the function associations contained therein to the internal map. */ @@ -173,14 +183,20 @@ public class BuildStaticGLInfo String line, activeAssociation = null; Matcher m = null; while ((line = reader.readLine()) != null) { + int type = 0; // 1-define, 2-function // see if we're inside a #ifndef GL_XXX block and matching a function if (activeAssociation != null) { String identifier = null; if ((m = funcPattern.matcher(line)).matches()) { - identifier = m.group(8); + identifier = m.group(funcIdentifierGroup).trim(); + type =2; } else if ((m = definePattern.matcher(line)).matches()) { - identifier = m.group(1); + identifier = m.group(defineIdentifierGroup).trim(); + type =1; } else if (line.startsWith("#endif")) { + if(debug) { + System.err.println("END ASSOCIATION BLOCK: <" + activeAssociation + ">"); + } activeAssociation = null; } if ((identifier != null) && @@ -188,13 +204,17 @@ public class BuildStaticGLInfo // Handles #ifndef GL_... #define GL_... !identifier.equals(activeAssociation)) { addAssociation(identifier, activeAssociation); - // System.err.println(" ADDING ASSOCIATION: " + identifier + " " + activeAssociation); + if(debug) { + System.err.println(" ADDING ASSOCIATION: <" + identifier + "> <" + activeAssociation + "> ; type "+type); + } } } else if ((m = associationPattern.matcher(line)).matches()) { // found a new #ifndef GL_XXX block - activeAssociation = m.group(1); + activeAssociation = m.group(1).trim(); - // System.err.println("FOUND NEW ASSOCIATION BLOCK: " + activeAssociation); + if(debug) { + System.err.println("BEGIN ASSOCIATION BLOCK: <" + activeAssociation + ">"); + } } } reader.close(); @@ -204,12 +224,12 @@ public class BuildStaticGLInfo for (Iterator i1 = extensionToDeclarationMap.keySet().iterator(); i1.hasNext(); ) { String name = (String) i1.next(); Set decls = (Set) extensionToDeclarationMap.get(name); - System.out.println(name + ":"); + System.out.println("<"+name+"> :"); List l = new ArrayList(); l.addAll(decls); Collections.sort(l); for (Iterator i2 = l.iterator(); i2.hasNext(); ) { - System.out.println(" " + (String) i2.next()); + System.out.println(" <" + (String) i2.next() + ">"); } } } diff --git a/src/java/com/sun/gluegen/opengl/GLConfiguration.java b/src/java/com/sun/gluegen/opengl/GLConfiguration.java index 923dcf52d..4e8c0c369 100755 --- a/src/java/com/sun/gluegen/opengl/GLConfiguration.java +++ b/src/java/com/sun/gluegen/opengl/GLConfiguration.java @@ -202,13 +202,6 @@ public class GLConfiguration extends ProcAddressConfiguration { super.dumpIgnores(); } - protected String getExtension(String symbol) { - if (glInfo != null) { - return glInfo.getExtension(symbol); - } - return null; - } - protected boolean shouldIgnoreExtension(String symbol, boolean criteria) { if (criteria && glInfo != null) { String extension = glInfo.getExtension(symbol); @@ -216,14 +209,14 @@ public class GLConfiguration extends ProcAddressConfiguration { ignoredExtensions.contains(extension)) { return true; } - boolean isGLFunc = GLExtensionNames.isGLFunction(symbol); boolean isGLEnum = GLExtensionNames.isGLEnumeration(symbol); + boolean isGLFunc = GLExtensionNames.isGLFunction(symbol); if(isGLFunc || isGLEnum) { if(GLExtensionNames.isExtensionVEN(symbol, isGLFunc)) { String extSuffix = GLExtensionNames.getExtensionSuffix(symbol, isGLFunc); if( getDropUniqVendorExtensions(extSuffix) ) { if(DEBUG_IGNORES) { - System.err.println("Ignore UniqVendorEXT: "+symbol); + System.err.println("Ignore UniqVendorEXT: "+symbol+", vendor "+extSuffix); } return true; } diff --git a/src/java/com/sun/gluegen/opengl/GLEmitter.java b/src/java/com/sun/gluegen/opengl/GLEmitter.java index 83e688eec..9e3202658 100644 --- a/src/java/com/sun/gluegen/opengl/GLEmitter.java +++ b/src/java/com/sun/gluegen/opengl/GLEmitter.java @@ -85,9 +85,15 @@ public class GLEmitter extends ProcAddressEmitter // renaming mechanisms that are built elsewhere. GLConfiguration config = getGLConfig(); + Set extensionsRenamedIntoCore = config.getExtensionsRenamedIntoCore(); BuildStaticGLInfo glInfo = config.getGLInfo(); - for (Iterator iter = config.getExtensionsRenamedIntoCore().iterator(); - iter.hasNext(); ) { + if(null==glInfo) { + if(extensionsRenamedIntoCore.size()>0) { + throw new RuntimeException("ExtensionRenamedIntoCore (num: "+extensionsRenamedIntoCore.size()+"), but no GLHeader"); + } + return; + } + for (Iterator iter = extensionsRenamedIntoCore.iterator(); iter.hasNext(); ) { String extension = (String) iter.next(); Set/**/ declarations = glInfo.getDeclarations(extension); if (declarations != null) { @@ -305,19 +311,68 @@ public class GLEmitter extends ProcAddressEmitter return bufferObjectMethodBindings.containsKey(binding); } - public void emitDefine(String name, String value, String optionalComment) throws Exception { - String extensionName = getGLConfig().getExtension(name); + public void emitDefine(ConstantDefinition def, String optionalComment) throws Exception { + BuildStaticGLInfo glInfo = getGLConfig().getGLInfo(); + if(null==glInfo) { + throw new Exception("No GLInfo for: "+def); + } + String symbolRenamed = def.getName(); StringBuffer newComment = new StringBuffer(); - if(null!=extensionName) { - newComment.append("Part of "+extensionName+""); - } else { - newComment.append("Part of unknown extension"); + newComment.append("Part of "); + if(0==addExtensionsOfSymbols2Buffer(newComment, ", ", symbolRenamed, def.getAliasedNames())) { + // Note: All GL enums must be contained within an extension marker ! + // #ifndef GL_EXT_lala + // #define GL_EXT_lala 1 + // ... + // #endif + if(JavaConfiguration.DEBUG_IGNORES) { + StringBuffer sb = new StringBuffer(); + JavaEmitter.addStrings2Buffer(sb, ", ", symbolRenamed, def.getAliasedNames()); + System.err.println("Dropping marker: "+sb.toString()); + } + return; } + newComment.append(""); + if(null!=optionalComment) { newComment.append(" "); newComment.append(optionalComment); } - super.emitDefine(name, value, newComment.toString()); + + super.emitDefine(def, newComment.toString()); + } + + public int addExtensionsOfSymbols2Buffer(StringBuffer buf, String sep, String first, Collection col) { + BuildStaticGLInfo glInfo = getGLConfig().getGLInfo(); + if(null==glInfo) { + throw new RuntimeException("No GLInfo for: "+first); + } + int num = 0; + if(null==buf) buf=new StringBuffer(); + String extensionName; + + Iterator iter=col.iterator(); + if(null!=first) { + extensionName = glInfo.getExtension(first); + if(null!=extensionName) { + buf.append(extensionName); + if( iter.hasNext() ) { + buf.append(sep); + } + num++; + } + } + while( iter.hasNext() ) { + extensionName = glInfo.getExtension((String)iter.next()); + if(null!=extensionName) { + buf.append(extensionName); + if( iter.hasNext() ) { + buf.append(sep); + } + num++; + } + } + return num; } //---------------------------------------------------------------------- @@ -399,23 +454,4 @@ public class GLEmitter extends ProcAddressEmitter w.flush(); w.close(); } - - protected void emitProcAddressTableEntryForSymbol(FunctionSymbol cFunc) - { - emitProcAddressTableEntryForString(cFunc.getName()); - } - - protected void emitProcAddressTableEntryForString(String str) - { - // Deal gracefully with forced proc address generation in the face - // of having the function pointer typedef in the header file too - if (emittedTableEntries.contains(str)) - return; - emittedTableEntries.add(str); - tableWriter.print(" public long "); - tableWriter.print(PROCADDRESS_VAR_PREFIX); - tableWriter.print(str); - tableWriter.println(";"); - } - } diff --git a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java index b952272f3..5e8bada0d 100755 --- a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java +++ b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java @@ -109,12 +109,21 @@ public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmit { protected void emitBindingCSignature(MethodBinding binding, PrintWriter writer) { super.emitBindingCSignature(binding, writer); - String extensionName = glEmitter.getGLConfig().getExtension(binding.getCSymbol().getName()); - if(null!=extensionName) { - writer.print("
Part of "+extensionName+""); - } else { - writer.print("
Part of unknown extension"); + + String symbolRenamed = binding.getName(); + StringBuffer newComment = new StringBuffer(); + newComment.append("Part of "); + if(0==glEmitter.addExtensionsOfSymbols2Buffer(newComment, ", ", symbolRenamed, binding.getAliasedNames())) { + StringBuffer sb = new StringBuffer(); + JavaEmitter.addStrings2Buffer(sb, ", ", symbolRenamed, binding.getAliasedNames()); + RuntimeException ex = new RuntimeException("Couldn't find extension to: "+binding+" ; "+sb.toString()); + ex.printStackTrace(); + glEmitter.getGLConfig().getGLInfo().dump(); + // glEmitter.getGLConfig().dumpRenames(); + throw ex; } + newComment.append(""); + writer.print(newComment.toString()); } } } -- cgit v1.2.3 From a3ce5e8e3bfae850a638c0b40679ed885bceea82 Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Wed, 5 Aug 2009 10:29:26 -0700 Subject: Fix: Remove PFD_ defines. Add GL Option: AllowNonGLExtensions to allow non GL extensions to be passed. Allow ifndef/define pattern to have any characters at the end --- .../com/sun/gluegen/opengl/BuildStaticGLInfo.java | 4 ++-- .../com/sun/gluegen/opengl/GLConfiguration.java | 14 +++++++++++- src/java/com/sun/gluegen/opengl/GLEmitter.java | 26 +++++++++++++--------- .../gluegen/opengl/GLJavaMethodBindingEmitter.java | 18 +++++++++------ 4 files changed, 41 insertions(+), 21 deletions(-) (limited to 'src/java/com/sun/gluegen/opengl/GLConfiguration.java') diff --git a/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java b/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java index a31a98760..a6c0cfc97 100644 --- a/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java +++ b/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java @@ -96,11 +96,11 @@ public class BuildStaticGLInfo Pattern.compile("^(GLAPI|GL_API|GL_APICALL|EGLAPI|extern)?(\\s*)((unsigned|const)\\s+)?(\\w+)(\\s*\\*)?(\\s+)(GLAPIENTRY|GL_APIENTRY|APIENTRY|EGLAPIENTRY|WINAPI)?(\\s*)([ew]?gl\\w+)\\s?(\\(.*)"); protected static Pattern associationPattern = - Pattern.compile("\\#ifndef ([CEW]?GL[XU]?_[A-Za-z0-9_]+)\\s*"); + Pattern.compile("\\#ifndef ([CEW]?GL[XU]?_[A-Za-z0-9_]+)(.*)"); protected static int defineIdentifierGroup = 1; protected static Pattern definePattern = - Pattern.compile("\\#define (([CEW]?GL[XU]?|PFD)_[A-Za-z0-9_]+)\\s*([A-Za-z0-9_]+)\\s*"); + Pattern.compile("\\#define ([CEW]?GL[XU]?_[A-Za-z0-9_]+)\\s*([A-Za-z0-9_]+)(.*)"); // Maps function / #define names to the names of the extensions they're declared in protected Map declarationToExtensionMap = new HashMap(); diff --git a/src/java/com/sun/gluegen/opengl/GLConfiguration.java b/src/java/com/sun/gluegen/opengl/GLConfiguration.java index 4e8c0c369..9352bcba2 100755 --- a/src/java/com/sun/gluegen/opengl/GLConfiguration.java +++ b/src/java/com/sun/gluegen/opengl/GLConfiguration.java @@ -59,7 +59,8 @@ public class GLConfiguration extends ProcAddressConfiguration { // This directive is off by default but can help automatically // indicate which extensions have been folded into the core OpenGL // namespace, and if not, then why not - private boolean autoUnifyExtensions; + private boolean autoUnifyExtensions=false; + private boolean allowNonGLExtensions=false; public GLConfiguration(GLEmitter emitter) { super(); @@ -82,6 +83,10 @@ public class GLConfiguration extends ProcAddressConfiguration { String sym = readString("RenameExtensionIntoCore", tok, filename, lineNo); extensionsRenamedIntoCore.add(sym); } + else if (cmd.equalsIgnoreCase("AllowNonGLExtensions")) + { + allowNonGLExtensions = readBoolean("AllowNonGLExtensions", tok, filename, lineNo).booleanValue(); + } else if (cmd.equalsIgnoreCase("AutoUnifyExtensions")) { autoUnifyExtensions = readBoolean("AutoUnifyExtensions", tok, filename, lineNo).booleanValue(); @@ -249,6 +254,13 @@ public class GLConfiguration extends ProcAddressConfiguration { return autoUnifyExtensions; } + /** If true, accept all non encapsulated defines and functions, + * as it is mandatory for GL declarations. */ + public boolean getAllowNonGLExtensions() { + return allowNonGLExtensions; + } + + /** shall the non unified (uniq) vendor extensions be dropped ? */ public boolean getDropUniqVendorExtensions(String extName) { return dropUniqVendorExtensions.contains(extName); diff --git a/src/java/com/sun/gluegen/opengl/GLEmitter.java b/src/java/com/sun/gluegen/opengl/GLEmitter.java index 935706bd2..ffe1ed61c 100644 --- a/src/java/com/sun/gluegen/opengl/GLEmitter.java +++ b/src/java/com/sun/gluegen/opengl/GLEmitter.java @@ -325,20 +325,24 @@ public class GLEmitter extends ProcAddressEmitter if(null!=enumName) { newComment.append(enumName); } else { - newComment.append("ENUM"); + newComment.append("CORE ENUM"); } } else { - // Note: All GL defines must be contained within an extension marker ! - // #ifndef GL_EXT_lala - // #define GL_EXT_lala 1 - // ... - // #endif - if(JavaConfiguration.DEBUG_IGNORES) { - StringBuffer sb = new StringBuffer(); - JavaEmitter.addStrings2Buffer(sb, ", ", symbolRenamed, def.getAliasedNames()); - System.err.println("Dropping marker: "+sb.toString()); + if(getGLConfig().getAllowNonGLExtensions()) { + newComment.append("CORE DEF"); + } else { + // Note: All GL defines must be contained within an extension marker ! + // #ifndef GL_EXT_lala + // #define GL_EXT_lala 1 + // ... + // #endif + if(JavaConfiguration.DEBUG_IGNORES) { + StringBuffer sb = new StringBuffer(); + JavaEmitter.addStrings2Buffer(sb, ", ", symbolRenamed, def.getAliasedNames()); + System.err.println("Dropping marker: "+sb.toString()); + } + return; } - return; } } newComment.append(""); diff --git a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java index 5e8bada0d..8f5258e0b 100755 --- a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java +++ b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java @@ -114,13 +114,17 @@ public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmit StringBuffer newComment = new StringBuffer(); newComment.append("Part of "); if(0==glEmitter.addExtensionsOfSymbols2Buffer(newComment, ", ", symbolRenamed, binding.getAliasedNames())) { - StringBuffer sb = new StringBuffer(); - JavaEmitter.addStrings2Buffer(sb, ", ", symbolRenamed, binding.getAliasedNames()); - RuntimeException ex = new RuntimeException("Couldn't find extension to: "+binding+" ; "+sb.toString()); - ex.printStackTrace(); - glEmitter.getGLConfig().getGLInfo().dump(); - // glEmitter.getGLConfig().dumpRenames(); - throw ex; + if(glEmitter.getGLConfig().getAllowNonGLExtensions()) { + newComment.append("CORE FUNC"); + } else { + StringBuffer sb = new StringBuffer(); + JavaEmitter.addStrings2Buffer(sb, ", ", symbolRenamed, binding.getAliasedNames()); + RuntimeException ex = new RuntimeException("Couldn't find extension to: "+binding+" ; "+sb.toString()); + ex.printStackTrace(); + glEmitter.getGLConfig().getGLInfo().dump(); + // glEmitter.getGLConfig().dumpRenames(); + throw ex; + } } newComment.append(""); writer.print(newComment.toString()); -- cgit v1.2.3 From 44f869b292f858cf9ad8c893ae30d39fadda1102 Mon Sep 17 00:00:00 2001 From: Michael Bien Date: Wed, 2 Dec 2009 00:14:46 +0100 Subject: continued with code cleanup in com.sun.gluegen.cgram and com.sun.gluegen.opengl packages. --- .../com/sun/gluegen/opengl/BuildStaticGLInfo.java | 44 +++++---- .../com/sun/gluegen/opengl/GLConfiguration.java | 104 +++++++++------------ src/java/com/sun/gluegen/opengl/GLEmitter.java | 45 +++++---- .../gluegen/opengl/GLJavaMethodBindingEmitter.java | 8 +- 4 files changed, 92 insertions(+), 109 deletions(-) (limited to 'src/java/com/sun/gluegen/opengl/GLConfiguration.java') diff --git a/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java b/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java index a6c0cfc97..8653b076e 100644 --- a/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java +++ b/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java @@ -103,10 +103,11 @@ public class BuildStaticGLInfo Pattern.compile("\\#define ([CEW]?GL[XU]?_[A-Za-z0-9_]+)\\s*([A-Za-z0-9_]+)(.*)"); // Maps function / #define names to the names of the extensions they're declared in - protected Map declarationToExtensionMap = new HashMap(); + protected Map declarationToExtensionMap = new HashMap(); + // Maps extension names to Set of identifiers (both #defines and // function names) this extension declares - protected Map/**/ extensionToDeclarationMap = new HashMap(); + protected Map> extensionToDeclarationMap = new HashMap>(); protected boolean debug = false; /** @@ -221,28 +222,27 @@ public class BuildStaticGLInfo } public void dump() { - for (Iterator i1 = extensionToDeclarationMap.keySet().iterator(); i1.hasNext(); ) { - String name = (String) i1.next(); - Set decls = (Set) extensionToDeclarationMap.get(name); + for (String name : extensionToDeclarationMap.keySet()) { + Set decls = extensionToDeclarationMap.get(name); System.out.println("<"+name+"> :"); - List l = new ArrayList(); + List l = new ArrayList(); l.addAll(decls); Collections.sort(l); - for (Iterator i2 = l.iterator(); i2.hasNext(); ) { - System.out.println(" <" + (String) i2.next() + ">"); + for (String str : l) { + System.out.println(" <" + str + ">"); } } } public String getExtension(String identifier) { - return (String) declarationToExtensionMap.get(identifier); + return declarationToExtensionMap.get(identifier); } - public Set/**/ getDeclarations(String extension) { - return (Set) extensionToDeclarationMap.get(extension); + public Set getDeclarations(String extension) { + return extensionToDeclarationMap.get(extension); } - public Set/**/ getExtensions() { + public Set getExtensions() { return extensionToDeclarationMap.keySet(); } @@ -298,8 +298,7 @@ public class BuildStaticGLInfo // Compute max capacity int maxCapacity = 0; - for (Iterator iter = declarationToExtensionMap.keySet().iterator(); iter.hasNext(); ) { - String name = (String) iter.next(); + for (String name : declarationToExtensionMap.keySet()) { if (!name.startsWith("GL")) { ++maxCapacity; } @@ -307,18 +306,17 @@ public class BuildStaticGLInfo output.println(" funcToAssocMap = new HashMap(" + maxCapacity + "); // approximate max capacity"); output.println(" String group;"); - ArrayList sets = new ArrayList(extensionToDeclarationMap.keySet()); + ArrayList sets = new ArrayList(extensionToDeclarationMap.keySet()); Collections.sort(sets); - for (Iterator iter = sets.iterator(); iter.hasNext(); ) { - String groupName = (String) iter.next(); - Set funcs = (Set) extensionToDeclarationMap.get(groupName); - List l = new ArrayList(); + for (String groupName : sets) { + Set funcs = extensionToDeclarationMap.get(groupName); + List l = new ArrayList(); l.addAll(funcs); Collections.sort(l); - Iterator funcIter = l.iterator(); + Iterator funcIter = l.iterator(); boolean printedHeader = false; while (funcIter.hasNext()) { - String funcName = (String)funcIter.next(); + String funcName = funcIter.next(); if (!funcName.startsWith("GL")) { if (!printedHeader) { output.println(); @@ -343,9 +341,9 @@ public class BuildStaticGLInfo protected void addAssociation(String identifier, String association) { declarationToExtensionMap.put(identifier, association); - Set/**/ identifiers = (Set) extensionToDeclarationMap.get(association); + Set identifiers = extensionToDeclarationMap.get(association); if (identifiers == null) { - identifiers = new HashSet/**/(); + identifiers = new HashSet(); extensionToDeclarationMap.put(association, identifiers); } identifiers.add(identifier); diff --git a/src/java/com/sun/gluegen/opengl/GLConfiguration.java b/src/java/com/sun/gluegen/opengl/GLConfiguration.java index 9352bcba2..5e7ef7a89 100755 --- a/src/java/com/sun/gluegen/opengl/GLConfiguration.java +++ b/src/java/com/sun/gluegen/opengl/GLConfiguration.java @@ -48,14 +48,14 @@ import com.sun.gluegen.runtime.opengl.GLExtensionNames; public class GLConfiguration extends ProcAddressConfiguration { // The following data members support ignoring an entire extension at a time - private List/**/ glHeaders = new ArrayList(); - private Set/**/ ignoredExtensions = new HashSet(); - private Set/**/ extensionsRenamedIntoCore = new HashSet(); + private List glHeaders = new ArrayList(); + private Set ignoredExtensions = new HashSet(); + private Set extensionsRenamedIntoCore = new HashSet(); private BuildStaticGLInfo glInfo; // Maps function names to the kind of buffer object it deals with - private Map/**/ bufferObjectKinds = new HashMap(); + private Map bufferObjectKinds = new HashMap(); private GLEmitter emitter; - private Set/*String*/ dropUniqVendorExtensions = new HashSet(); + private Set dropUniqVendorExtensions = new HashSet(); // This directive is off by default but can help automatically // indicate which extensions have been folded into the core OpenGL // namespace, and if not, then why not @@ -72,44 +72,30 @@ public class GLConfiguration extends ProcAddressConfiguration { } } - protected void dispatch(String cmd, StringTokenizer tok, File file, String filename, int lineNo) throws IOException { - if (cmd.equalsIgnoreCase("IgnoreExtension")) - { - String sym = readString("IgnoreExtension", tok, filename, lineNo); - ignoredExtensions.add(sym); - } - else if (cmd.equalsIgnoreCase("RenameExtensionIntoCore")) - { - String sym = readString("RenameExtensionIntoCore", tok, filename, lineNo); - extensionsRenamedIntoCore.add(sym); - } - else if (cmd.equalsIgnoreCase("AllowNonGLExtensions")) - { - allowNonGLExtensions = readBoolean("AllowNonGLExtensions", tok, filename, lineNo).booleanValue(); - } - else if (cmd.equalsIgnoreCase("AutoUnifyExtensions")) - { - autoUnifyExtensions = readBoolean("AutoUnifyExtensions", tok, filename, lineNo).booleanValue(); - } - else if (cmd.equalsIgnoreCase("GLHeader")) - { - String sym = readString("GLHeader", tok, filename, lineNo); - glHeaders.add(sym); - } - else if (cmd.equalsIgnoreCase("BufferObjectKind")) - { - readBufferObjectKind(tok, filename, lineNo); - } - else if (cmd.equalsIgnoreCase("DropUniqVendorExtensions")) - { - String sym = readString("DropUniqVendorExtensions", tok, filename, lineNo); - dropUniqVendorExtensions.add(sym); - } - else - { - super.dispatch(cmd,tok,file,filename,lineNo); - } - } + @Override + protected void dispatch(String cmd, StringTokenizer tok, File file, String filename, int lineNo) throws IOException { + if (cmd.equalsIgnoreCase("IgnoreExtension")) { + String sym = readString("IgnoreExtension", tok, filename, lineNo); + ignoredExtensions.add(sym); + } else if (cmd.equalsIgnoreCase("RenameExtensionIntoCore")) { + String sym = readString("RenameExtensionIntoCore", tok, filename, lineNo); + extensionsRenamedIntoCore.add(sym); + } else if (cmd.equalsIgnoreCase("AllowNonGLExtensions")) { + allowNonGLExtensions = readBoolean("AllowNonGLExtensions", tok, filename, lineNo).booleanValue(); + } else if (cmd.equalsIgnoreCase("AutoUnifyExtensions")) { + autoUnifyExtensions = readBoolean("AutoUnifyExtensions", tok, filename, lineNo).booleanValue(); + } else if (cmd.equalsIgnoreCase("GLHeader")) { + String sym = readString("GLHeader", tok, filename, lineNo); + glHeaders.add(sym); + } else if (cmd.equalsIgnoreCase("BufferObjectKind")) { + readBufferObjectKind(tok, filename, lineNo); + } else if (cmd.equalsIgnoreCase("DropUniqVendorExtensions")) { + String sym = readString("DropUniqVendorExtensions", tok, filename, lineNo); + dropUniqVendorExtensions.add(sym); + } else { + super.dispatch(cmd, tok, file, filename, lineNo); + } + } protected void readBufferObjectKind(StringTokenizer tok, String filename, int lineNo) { try { @@ -140,12 +126,10 @@ public class GLConfiguration extends ProcAddressConfiguration { /** Overrides javaPrologueForMethod in superclass and automatically generates prologue code for functions associated with buffer objects. */ - public List/**/ javaPrologueForMethod(MethodBinding binding, - boolean forImplementingMethodCall, - boolean eraseBufferAndArrayTypes) { - List/**/ res = super.javaPrologueForMethod(binding, - forImplementingMethodCall, - eraseBufferAndArrayTypes); + @Override + public List javaPrologueForMethod(MethodBinding binding, boolean forImplementingMethodCall, boolean eraseBufferAndArrayTypes) { + + List res = super.javaPrologueForMethod(binding, forImplementingMethodCall, eraseBufferAndArrayTypes); GLEmitter.BufferObjectKind kind = getBufferObjectKind(binding.getName()); if (kind != null) { // Need to generate appropriate prologue based on both buffer @@ -154,7 +138,7 @@ public class GLConfiguration extends ProcAddressConfiguration { // // NOTE we MUST NOT mutate the array returned from the super // call! - ArrayList res2 = new ArrayList(); + ArrayList res2 = new ArrayList(); if (res != null) { res2.addAll(res); } @@ -187,8 +171,8 @@ public class GLConfiguration extends ProcAddressConfiguration { // Must also filter out bogus rangeCheck directives for VBO/PBO // variants if (emitter.isBufferObjectMethodBinding(binding)) { - for (Iterator iter = res.iterator(); iter.hasNext(); ) { - String line = (String) iter.next(); + for (Iterator iter = res.iterator(); iter.hasNext(); ) { + String line = iter.next(); if (line.indexOf("BufferFactory.rangeCheck") >= 0) { iter.remove(); } @@ -199,10 +183,11 @@ public class GLConfiguration extends ProcAddressConfiguration { return res; } + @Override public void dumpIgnores() { System.err.println("GL Ignored extensions: "); - for (Iterator iter = ignoredExtensions.iterator(); iter.hasNext(); ) { - System.err.println("\t"+(String)iter.next()); + for (String str : ignoredExtensions) { + System.err.println("\t"+str); } super.dumpIgnores(); } @@ -231,6 +216,7 @@ public class GLConfiguration extends ProcAddressConfiguration { return false; } + @Override public boolean shouldIgnoreInInterface(String symbol) { return shouldIgnoreInInterface(symbol, true); } @@ -239,6 +225,7 @@ public class GLConfiguration extends ProcAddressConfiguration { return shouldIgnoreExtension(symbol, checkEXT) || super.shouldIgnoreInInterface(symbol); } + @Override public boolean shouldIgnoreInImpl(String symbol) { return shouldIgnoreInImpl(symbol, true); } @@ -268,8 +255,8 @@ public class GLConfiguration extends ProcAddressConfiguration { /** Returns the kind of buffer object this function deals with, or null if none. */ - public GLEmitter.BufferObjectKind getBufferObjectKind(String name) { - return (GLEmitter.BufferObjectKind) bufferObjectKinds.get(name); + GLEmitter.BufferObjectKind getBufferObjectKind(String name) { + return bufferObjectKinds.get(name); } public boolean isBufferObjectFunction(String name) { @@ -281,8 +268,7 @@ public class GLConfiguration extends ProcAddressConfiguration { public void parseGLHeaders(GlueEmitterControls controls) throws IOException { if (!glHeaders.isEmpty()) { glInfo = new BuildStaticGLInfo(); - for (Iterator iter = glHeaders.iterator(); iter.hasNext(); ) { - String file = (String) iter.next(); + for (String file : glHeaders) { String fullPath = controls.findHeaderFile(file); if (fullPath == null) { throw new IOException("Unable to locate header file \"" + file + "\""); @@ -303,7 +289,7 @@ public class GLConfiguration extends ProcAddressConfiguration { constant definitions and functions renamed into the core namespace; for example, glGenFramebuffersEXT to glGenFramebuffers and GL_FRAMEBUFFER_EXT to GL_FRAMEBUFFER. */ - public Set/**/ getExtensionsRenamedIntoCore() { + public Set getExtensionsRenamedIntoCore() { return extensionsRenamedIntoCore; } } diff --git a/src/java/com/sun/gluegen/opengl/GLEmitter.java b/src/java/com/sun/gluegen/opengl/GLEmitter.java index 4ca2e698b..ff307c432 100644 --- a/src/java/com/sun/gluegen/opengl/GLEmitter.java +++ b/src/java/com/sun/gluegen/opengl/GLEmitter.java @@ -45,20 +45,20 @@ import java.util.*; import com.sun.gluegen.*; import com.sun.gluegen.cgram.types.*; import com.sun.gluegen.procaddress.*; -import com.sun.gluegen.runtime.*; import com.sun.gluegen.runtime.opengl.GLExtensionNames; /** * A subclass of ProcAddressEmitter with special OpenGL-specific * configuration abilities. */ -public class GLEmitter extends ProcAddressEmitter -{ +public class GLEmitter extends ProcAddressEmitter { + // Keeps track of which MethodBindings were created for handling // Buffer Object variants. Used as a Set rather than a Map. - private Map/**/ bufferObjectMethodBindings = new IdentityHashMap(); + private Map bufferObjectMethodBindings = new IdentityHashMap(); static class BufferObjectKind { + private BufferObjectKind() {} static final BufferObjectKind UNPACK_PIXEL = new BufferObjectKind(); @@ -67,8 +67,8 @@ public class GLEmitter extends ProcAddressEmitter static final BufferObjectKind ELEMENT = new BufferObjectKind(); } - public void beginEmission(GlueEmitterControls controls) throws IOException - { + @Override + public void beginEmission(GlueEmitterControls controls) throws IOException { getGLConfig().parseGLHeaders(controls); renameExtensionsIntoCore(); if (getGLConfig().getAutoUnifyExtensions()) { @@ -85,7 +85,7 @@ public class GLEmitter extends ProcAddressEmitter // renaming mechanisms that are built elsewhere. GLConfiguration config = getGLConfig(); - Set extensionsRenamedIntoCore = config.getExtensionsRenamedIntoCore(); + Set extensionsRenamedIntoCore = config.getExtensionsRenamedIntoCore(); BuildStaticGLInfo glInfo = config.getGLInfo(); if(null==glInfo) { if(extensionsRenamedIntoCore.size()>0) { @@ -93,9 +93,8 @@ public class GLEmitter extends ProcAddressEmitter } return; } - for (Iterator iter = extensionsRenamedIntoCore.iterator(); iter.hasNext(); ) { - String extension = (String) iter.next(); - Set/**/ declarations = glInfo.getDeclarations(extension); + for (String extension : extensionsRenamedIntoCore) { + Set declarations = glInfo.getDeclarations(extension); if (declarations != null) { for (Iterator i2 = declarations.iterator(); i2.hasNext(); ) { String decl = (String) i2.next(); @@ -116,21 +115,21 @@ public class GLEmitter extends ProcAddressEmitter } class ExtensionUnifier implements SymbolFilter { - private List/**/ constants; - private List/**/ functions; + private List constants; + private List functions; - public void filterSymbols(List/**/ constants, - List/**/ functions) { + public void filterSymbols(List constants, + List functions) { this.constants = constants; this.functions = functions; doWork(); } - public List/**/ getConstants() { + public List getConstants() { return constants; } - public List/**/ getFunctions() { + public List getFunctions() { return functions; } @@ -140,8 +139,8 @@ public class GLEmitter extends ProcAddressEmitter return; } // Try to retain a "good" ordering for these symbols - Map/**/ constantMap = new LinkedHashMap(); - Map/**/ functionMap = new LinkedHashMap(); + Map constantMap = new LinkedHashMap(); + Map functionMap = new LinkedHashMap(); for (Iterator iter = constants.iterator(); iter.hasNext(); ) { ConstantDefinition def = (ConstantDefinition) iter.next(); constantMap.put(def.getName(), def); @@ -158,10 +157,10 @@ public class GLEmitter extends ProcAddressEmitter // that doesn't support the core version of these APIs, the runtime // will take care of looking up the extension version of these entry // points. - Set/**/ extensionNames = glInfo.getExtensions(); + Set extensionNames = glInfo.getExtensions(); for (Iterator iter1 = extensionNames.iterator(); iter1.hasNext(); ) { String extension = (String) iter1.next(); - Set/**/ declarations = glInfo.getDeclarations(extension); + Set declarations = glInfo.getDeclarations(extension); boolean isExtension = true; boolean shouldUnify = true; String cause = null; @@ -253,14 +252,14 @@ public class GLEmitter extends ProcAddressEmitter (i.e., mutators for argument names). We also would need to inform the CMethodBindingEmitter that it is overloaded in this case (though we default to true currently). */ - protected List/**/ expandMethodBinding(MethodBinding binding) { - List/**/ bindings = super.expandMethodBinding(binding); + protected List expandMethodBinding(MethodBinding binding) { + List bindings = super.expandMethodBinding(binding); if (!getGLConfig().isBufferObjectFunction(binding.getName())) { return bindings; } - List/**/ newBindings = new ArrayList(); + List newBindings = new ArrayList(); newBindings.addAll(bindings); // Need to expand each one of the generated bindings to take a diff --git a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java index 662e75b51..33f94fb19 100755 --- a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java +++ b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java @@ -40,7 +40,6 @@ package com.sun.gluegen.opengl; import java.io.*; -import java.util.*; import com.sun.gluegen.*; import com.sun.gluegen.cgram.types.*; import com.sun.gluegen.procaddress.*; @@ -83,6 +82,7 @@ public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmit this(methodToWrap, methodToWrap.glEmitter, methodToWrap.bufferObjectVariant); } + @Override protected String getArgumentName(int i) { String name = super.getArgumentName(i); @@ -104,9 +104,9 @@ public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmit return name; } - protected class GLCommentEmitter - extends JavaMethodBindingEmitter.DefaultCommentEmitter - { + protected class GLCommentEmitter extends JavaMethodBindingEmitter.DefaultCommentEmitter { + + @Override protected void emitBindingCSignature(MethodBinding binding, PrintWriter writer) { super.emitBindingCSignature(binding, writer); -- cgit v1.2.3 From 48360cccc3e995160a6966618bb173a84ebd101d Mon Sep 17 00:00:00 2001 From: Michael Bien Date: Sat, 27 Mar 2010 02:26:27 +0100 Subject: renamed com.sun.gluegen.runtime -> com.jogamp.gluegen.runtime. --- .../gluegen/runtime/opengl/GLExtensionNames.java | 187 +++++++++++++++++++++ .../gluegen/opengl/BuildComposablePipeline.java | 2 +- .../com/sun/gluegen/opengl/BuildStaticGLInfo.java | 4 +- .../com/sun/gluegen/opengl/GLConfiguration.java | 2 +- src/java/com/sun/gluegen/opengl/GLEmitter.java | 8 +- .../gluegen/runtime/opengl/GLExtensionNames.java | 187 --------------------- 6 files changed, 195 insertions(+), 195 deletions(-) create mode 100644 src/java/com/jogamp/gluegen/runtime/opengl/GLExtensionNames.java delete mode 100644 src/java/com/sun/gluegen/runtime/opengl/GLExtensionNames.java (limited to 'src/java/com/sun/gluegen/opengl/GLConfiguration.java') diff --git a/src/java/com/jogamp/gluegen/runtime/opengl/GLExtensionNames.java b/src/java/com/jogamp/gluegen/runtime/opengl/GLExtensionNames.java new file mode 100644 index 000000000..b07a96fbf --- /dev/null +++ b/src/java/com/jogamp/gluegen/runtime/opengl/GLExtensionNames.java @@ -0,0 +1,187 @@ +/* + * 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 + * 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; + +import java.util.*; +import com.jogamp.gluegen.runtime.*; + +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", + "APPLE", + "ATI", + "EXT", + "HP", + "IBM", + "MESA", + "MESAX", + "NV", + "SGI", + "SGIS", + "SGIX", + "SUN", + "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 Date: Mon, 29 Mar 2010 04:02:08 +0200 Subject: renamed BufferFactory into Buffers. --- src/java/com/sun/gluegen/opengl/GLConfiguration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/java/com/sun/gluegen/opengl/GLConfiguration.java') diff --git a/src/java/com/sun/gluegen/opengl/GLConfiguration.java b/src/java/com/sun/gluegen/opengl/GLConfiguration.java index 19cf85a74..6d08a10a2 100755 --- a/src/java/com/sun/gluegen/opengl/GLConfiguration.java +++ b/src/java/com/sun/gluegen/opengl/GLConfiguration.java @@ -173,7 +173,7 @@ public class GLConfiguration extends ProcAddressConfiguration { if (emitter.isBufferObjectMethodBinding(binding)) { for (Iterator iter = res.iterator(); iter.hasNext(); ) { String line = iter.next(); - if (line.indexOf("BufferFactory.rangeCheck") >= 0) { + if (line.indexOf("Buffers.rangeCheck") >= 0) { iter.remove(); } } -- cgit v1.2.3 From af9ff963c4120731ec65ed1a9628e82d1f5b66e1 Mon Sep 17 00:00:00 2001 From: Michael Bien Date: Wed, 31 Mar 2010 19:05:36 +0200 Subject: refactoring and code cleanup in gluegen.opengl and gluegen.procaddress package. --- .../gluegen/opengl/BuildComposablePipeline.java | 1942 ++++++++++---------- .../com/sun/gluegen/opengl/BuildStaticGLInfo.java | 419 +++-- .../com/sun/gluegen/opengl/GLConfiguration.java | 419 ++--- src/java/com/sun/gluegen/opengl/GLEmitter.java | 756 ++++---- .../gluegen/opengl/GLJavaMethodBindingEmitter.java | 146 +- 5 files changed, 1808 insertions(+), 1874 deletions(-) (limited to 'src/java/com/sun/gluegen/opengl/GLConfiguration.java') diff --git a/src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java b/src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java index cbc0d894c..9750c13df 100644 --- a/src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java +++ b/src/java/com/sun/gluegen/opengl/BuildComposablePipeline.java @@ -36,7 +36,6 @@ * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ - package com.sun.gluegen.opengl; import com.sun.gluegen.*; @@ -44,1079 +43,1042 @@ import com.sun.gluegen.*; import java.lang.reflect.*; import java.io.*; import java.util.*; -import java.util.regex.*; - -public class BuildComposablePipeline -{ - public static final int GEN_DEBUG = 1 << 0 ; // default - public static final int GEN_TRACE = 1 << 1 ; // default - public static final int GEN_CUSTOM = 1 << 2 ; - public static final int GEN_PROLOG_XOR_DOWNSTREAM = 1 << 3 ; - - int mode; - private String outputDir; - private String outputPackage; - private String outputName; - private Class classToComposeAround; - private Class classPrologOpt; - private Class classDownstream; - private String basePackage; - private String baseName; // does not include package! - private String downstreamPackage; - private String downstreamName; // does not include package! - - // Only desktop OpenGL has immediate mode glBegin / glEnd - private boolean hasImmediateMode; - - // Desktop OpenGL and GLES1 have GL_STACK_OVERFLOW and GL_STACK_UNDERFLOW errors - private boolean hasStackOverflow; - - public static Class getClass(String name) { - Class clazz=null; - try { - clazz = Class.forName(name); - } catch (Exception e) { - throw new RuntimeException( - "Could not find class \"" + name + "\"", e); - } - return clazz; - } - - public static Method getMethod(Class clazz, Method m) { - Method res = null; - try { - res = clazz.getMethod(m.getName(), m.getParameterTypes()); - } catch (Exception e) { } - return res; - } - - public static void main(String[] args) - { - String classToComposeAroundName = args[0]; - Class classPrologOpt, classDownstream; - Class classToComposeAround = getClass(classToComposeAroundName); - - String outputDir = args[1]; - String outputPackage, outputName; + +public class BuildComposablePipeline { + + public static final int GEN_DEBUG = 1 << 0; // default + public static final int GEN_TRACE = 1 << 1; // default + public static final int GEN_CUSTOM = 1 << 2; + public static final int GEN_PROLOG_XOR_DOWNSTREAM = 1 << 3; int mode; + private String outputDir; + private String outputPackage; + private String outputName; + private Class classToComposeAround; + private Class classPrologOpt; + private Class classDownstream; + // Only desktop OpenGL has immediate mode glBegin / glEnd + private boolean hasImmediateMode; + // Desktop OpenGL and GLES1 have GL_STACK_OVERFLOW and GL_STACK_UNDERFLOW errors + private boolean hasStackOverflow; + + public static Class getClass(String name) { + Class clazz = null; + try { + clazz = Class.forName(name); + } catch (Exception e) { + throw new RuntimeException( + "Could not find class \"" + name + "\"", e); + } + return clazz; + } - if(args.length>2) { - String outputClazzName = args[2]; - outputPackage = getPackageName(outputClazzName); - outputName = getBaseClassName(outputClazzName); - classPrologOpt = getClass(args[3]); - classDownstream = getClass(args[4]); - mode = GEN_CUSTOM; - if(args.length>5) { - if(args[5].equals("prolog_xor_downstream")) { - mode |= GEN_PROLOG_XOR_DOWNSTREAM; + public static Method getMethod(Class clazz, Method m) { + Method res = null; + try { + res = clazz.getMethod(m.getName(), m.getParameterTypes()); + } catch (Exception e) { + } + return res; + } + + public static void main(String[] args) { + String classToComposeAroundName = args[0]; + Class classPrologOpt, classDownstream; + Class classToComposeAround = getClass(classToComposeAroundName); + + String outputDir = args[1]; + String outputPackage, outputName; + int mode; + + if (args.length > 2) { + String outputClazzName = args[2]; + outputPackage = getPackageName(outputClazzName); + outputName = getBaseClassName(outputClazzName); + classPrologOpt = getClass(args[3]); + classDownstream = getClass(args[4]); + mode = GEN_CUSTOM; + if (args.length > 5) { + if (args[5].equals("prolog_xor_downstream")) { + mode |= GEN_PROLOG_XOR_DOWNSTREAM; + } } + } else { + outputPackage = getPackageName(classToComposeAroundName); + outputName = null; // TBD .. + classPrologOpt = null; + classDownstream = classToComposeAround; + mode = GEN_DEBUG | GEN_TRACE; } - } else { - outputPackage = getPackageName(classToComposeAroundName); - outputName = null; // TBD .. - classPrologOpt = null; - classDownstream = classToComposeAround; - mode = GEN_DEBUG | GEN_TRACE; - } - BuildComposablePipeline composer = - new BuildComposablePipeline(mode, outputDir, outputPackage, outputName, classToComposeAround, classPrologOpt, classDownstream); + BuildComposablePipeline composer = + new BuildComposablePipeline(mode, outputDir, outputPackage, outputName, classToComposeAround, classPrologOpt, classDownstream); - try - { - composer.emit(); - } - catch (IOException e) - { - throw new RuntimeException( - "Error generating composable pipeline source files", e); - } - } - - protected BuildComposablePipeline(int mode, String outputDir, String outputPackage, String outputName, - Class classToComposeAround, Class classPrologOpt, Class classDownstream) - { - this.mode=mode; - this.outputDir=outputDir; - this.outputPackage=outputPackage; - this.outputName=outputName; - this.classToComposeAround=classToComposeAround; - this.classPrologOpt=classPrologOpt; - this.classDownstream=classDownstream; - - if (! classToComposeAround.isInterface()) - { - throw new IllegalArgumentException( - classToComposeAround.getName() + " is not an interface class"); - } - - try { - hasImmediateMode = - (classToComposeAround.getMethod("glBegin", new Class[] { Integer.TYPE }) != null); - } catch (Exception e) { + try { + composer.emit(); + } catch (IOException e) { + throw new RuntimeException( + "Error generating composable pipeline source files", e); + } } - try { - hasStackOverflow = - (classToComposeAround.getField("GL_STACK_OVERFLOW") != null); - } catch (Exception e) { - } - } - - /** - * Emit the java source code for the classes that comprise the composable - * pipeline. - */ - public void emit() throws IOException - { - List/**/ publicMethodsRaw = new ArrayList(); - publicMethodsRaw.addAll(Arrays.asList(classToComposeAround.getMethods())); - Set/**/ publicMethodsPlain = new HashSet(); - for (Iterator iter=publicMethodsRaw.iterator(); iter.hasNext(); ) { - Method method = (Method) iter.next(); - // Don't hook methods which aren't real GL methods, - // such as the synthetic "isGL2ES2" "getGL2ES2" - String name = method.getName(); - boolean runHooks = name.startsWith("gl"); - if (!name.startsWith("getGL") && !name.startsWith("isGL") && !name.equals("toString")) { - publicMethodsPlain.add(new PlainMethod(method, runHooks)); + protected BuildComposablePipeline(int mode, String outputDir, String outputPackage, String outputName, + Class classToComposeAround, Class classPrologOpt, Class classDownstream) { + this.mode = mode; + this.outputDir = outputDir; + this.outputPackage = outputPackage; + this.outputName = outputName; + this.classToComposeAround = classToComposeAround; + this.classPrologOpt = classPrologOpt; + this.classDownstream = classDownstream; + + if (!classToComposeAround.isInterface()) { + throw new IllegalArgumentException( + classToComposeAround.getName() + " is not an interface class"); + } + + try { + hasImmediateMode = + (classToComposeAround.getMethod("glBegin", new Class[]{Integer.TYPE}) != null); + } catch (Exception e) { } - } - if(0!=(mode&GEN_DEBUG)) { - (new DebugPipeline(outputDir, outputPackage, classToComposeAround, classDownstream)).emit(publicMethodsPlain.iterator()); + try { + hasStackOverflow = + (classToComposeAround.getField("GL_STACK_OVERFLOW") != null); + } catch (Exception e) { + } } - if(0!=(mode&GEN_TRACE)) { - (new TracePipeline(outputDir, outputPackage, classToComposeAround, classDownstream)).emit(publicMethodsPlain.iterator()); + + /** + * Emit the java source code for the classes that comprise the composable + * pipeline. + */ + public void emit() throws IOException { + + List publicMethodsRaw = Arrays.asList(classToComposeAround.getMethods()); + + Set publicMethodsPlain = new HashSet(); + for (Iterator iter = publicMethodsRaw.iterator(); iter.hasNext();) { + Method method = iter.next(); + // Don't hook methods which aren't real GL methods, + // such as the synthetic "isGL2ES2" "getGL2ES2" + String name = method.getName(); + boolean runHooks = name.startsWith("gl"); + if (!name.startsWith("getGL") && !name.startsWith("isGL") && !name.equals("toString")) { + publicMethodsPlain.add(new PlainMethod(method, runHooks)); + } + } + + if (0 != (mode & GEN_DEBUG)) { + (new DebugPipeline(outputDir, outputPackage, classToComposeAround, classDownstream)).emit(publicMethodsPlain.iterator()); + } + if (0 != (mode & GEN_TRACE)) { + (new TracePipeline(outputDir, outputPackage, classToComposeAround, classDownstream)).emit(publicMethodsPlain.iterator()); + } + if (0 != (mode & GEN_CUSTOM)) { + (new CustomPipeline(mode, outputDir, outputPackage, outputName, classToComposeAround, classPrologOpt, classDownstream)).emit(publicMethodsPlain.iterator()); + } } - if(0!=(mode&GEN_CUSTOM)) { - (new CustomPipeline(mode, outputDir, outputPackage, outputName, classToComposeAround, classPrologOpt, classDownstream)).emit(publicMethodsPlain.iterator()); + + public static String getPackageName(String clazzName) { + int lastDot = clazzName.lastIndexOf('.'); + if (lastDot == -1) { + // no package, class is at root level + return null; + } + return clazzName.substring(0, lastDot); } - } - - public static String getPackageName(String clazzName) { - int lastDot = clazzName.lastIndexOf('.'); - if (lastDot == -1) - { - // no package, class is at root level - return null; - } - return clazzName.substring(0, lastDot); - } - - public static String getBaseClassName(String clazzName) { - int lastDot = clazzName.lastIndexOf('.'); - if (lastDot == -1) - { - // no package, class is at root level - return clazzName; - } - return clazzName.substring(lastDot+1); - } - - //------------------------------------------------------- - - protected class PlainMethod - { - Method m; - boolean runHooks; - - public PlainMethod(Method m, boolean runHooks) { - this.m=m; - this.runHooks = runHooks; + + public static String getBaseClassName(String clazzName) { + int lastDot = clazzName.lastIndexOf('.'); + if (lastDot == -1) { + // no package, class is at root level + return clazzName; + } + return clazzName.substring(lastDot + 1); } - public Method getWrappedMethod() { return m; } + //------------------------------------------------------- + protected class PlainMethod { - public boolean runHooks() { return runHooks; } + Method m; + boolean runHooks; - public boolean equals(Object obj) { - if(obj instanceof PlainMethod) { - PlainMethod b = (PlainMethod)obj; - boolean res = - m.getName().equals(b.m.getName()) && - m.getModifiers() == b.m.getModifiers() && - m.getReturnType().equals(b.m.getReturnType()) && - Arrays.equals( m.getParameterTypes() , b.m.getParameterTypes() ) ; - return res; + PlainMethod(Method m, boolean runHooks) { + this.m = m; + this.runHooks = runHooks; } - return false; - } - public int hashCode() { - int hash = m.getName().hashCode() ^ m.getModifiers() ^ m.getReturnType().hashCode(); - Class[] args = m.getParameterTypes(); - for(int i=0; i 0) - argsString.append(", "); - argsString.append(args[i].getName()); - } - argsString.append(")"); - return m.toString() + - "\n\tname: " + m.getName() + - "\n\tmods: " + m.getModifiers() + - "\n\tretu: " + m.getReturnType() + - "\n\targs[" + args.length + "]: "+argsString.toString(); + public boolean runHooks() { + return runHooks; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof PlainMethod) { + PlainMethod b = (PlainMethod) obj; + boolean res = + m.getName().equals(b.m.getName()) + && m.getModifiers() == b.m.getModifiers() + && m.getReturnType().equals(b.m.getReturnType()) + && Arrays.equals(m.getParameterTypes(), b.m.getParameterTypes()); + return res; + } + return false; + } + + @Override + public int hashCode() { + int hash = m.getName().hashCode() ^ m.getModifiers() ^ m.getReturnType().hashCode(); + Class[] args = m.getParameterTypes(); + for (int i = 0; i < args.length; i++) { + hash ^= args[i].hashCode(); + } + return hash; + } + + @Override + public String toString() { + Class[] args = m.getParameterTypes(); + StringBuilder argsString = new StringBuilder(); + argsString.append("("); + for (int i = 0; i < args.length; i++) { + if (i > 0) { + argsString.append(", "); + } + argsString.append(args[i].getName()); + } + argsString.append(")"); + return m.toString() + + "\n\tname: " + m.getName() + + "\n\tmods: " + m.getModifiers() + + "\n\tretu: " + m.getReturnType() + + "\n\targs[" + args.length + "]: " + argsString.toString(); + } } - } - - /** - * Emits a Java source file that represents one element of the composable - * pipeline. - */ - protected abstract class PipelineEmitter - { - private File file; - protected String basePackage; - protected String baseName; // does not include package! - protected String downstreamPackage; - protected String downstreamName; // does not include package! - protected String prologPackageOpt=null; - protected String prologNameOpt=null; // does not include package! - - protected String outputDir; - protected String outputPackage; - protected Class baseInterfaceClass; - protected Class prologClassOpt=null; - protected Class downstreamClass; /** - * @param outputDir the directory into which the pipeline classes will be - * generated. - * @param baseInterfaceClassName the full class name (including package, - * e.g. "java.lang.String") of the interface that the pipeline wraps - * @exception IllegalArgumentException if classToComposeAround is not an - * interface. + * Emits a Java source file that represents one element of the composable + * pipeline. */ - public PipelineEmitter(String outputDir, String outputPackage, Class baseInterfaceClass, Class prologClassOpt, Class downstreamClass) - { - this.outputDir=outputDir; - this.outputPackage=outputPackage; - this.baseInterfaceClass=baseInterfaceClass; - this.prologClassOpt=prologClassOpt; - this.downstreamClass=downstreamClass; - - basePackage = getPackageName(baseInterfaceClass.getName()); - baseName = getBaseClassName(baseInterfaceClass.getName()); - downstreamPackage = getPackageName(downstreamClass.getName()); - downstreamName = getBaseClassName(downstreamClass.getName()); - if(null!=prologClassOpt) { - prologPackageOpt = getPackageName(prologClassOpt.getName()); - prologNameOpt = getBaseClassName(prologClassOpt.getName()); - } - } + protected abstract class PipelineEmitter { + + private File file; + protected String basePackage; + protected String baseName; // does not include package! + protected String downstreamPackage; + protected String downstreamName; // does not include package! + protected String prologPackageOpt = null; + protected String prologNameOpt = null; // does not include package! + protected String outputDir; + protected String outputPackage; + protected Class baseInterfaceClass; + protected Class prologClassOpt = null; + protected Class downstreamClass; + + /** + * @param outputDir the directory into which the pipeline classes will be + * generated. + * @param baseInterfaceClassName the full class name (including package, + * e.g. "java.lang.String") of the interface that the pipeline wraps + * @exception IllegalArgumentException if classToComposeAround is not an + * interface. + */ + PipelineEmitter(String outputDir, String outputPackage, Class baseInterfaceClass, Class prologClassOpt, Class downstreamClass) { + this.outputDir = outputDir; + this.outputPackage = outputPackage; + this.baseInterfaceClass = baseInterfaceClass; + this.prologClassOpt = prologClassOpt; + this.downstreamClass = downstreamClass; + + basePackage = getPackageName(baseInterfaceClass.getName()); + baseName = getBaseClassName(baseInterfaceClass.getName()); + downstreamPackage = getPackageName(downstreamClass.getName()); + downstreamName = getBaseClassName(downstreamClass.getName()); + if (null != prologClassOpt) { + prologPackageOpt = getPackageName(prologClassOpt.getName()); + prologNameOpt = getBaseClassName(prologClassOpt.getName()); + } + } + + public void emit(Iterator methodsToWrap) throws IOException { + String outputClassName = getOutputName(); + this.file = new File(outputDir + File.separatorChar + outputClassName + ".java"); + String parentDir = file.getParent(); + if (parentDir != null) { + File pDirFile = new File(parentDir); + pDirFile.mkdirs(); + } - public void emit(Iterator/**/ methodsToWrap) throws IOException - { - String outputClassName = getOutputName(); - this.file = new File(outputDir + File.separatorChar + outputClassName + ".java"); - String parentDir = file.getParent(); - if (parentDir != null) - { - File pDirFile = new File(parentDir); - pDirFile.mkdirs(); - } - - PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(file))); - - List baseInterfaces = Arrays.asList(baseInterfaceClass.getInterfaces()); - HashSet clazzList = new HashSet(); - clazzList.add(baseInterfaceClass); - clazzList.addAll(baseInterfaces); - int ifNamesNumber = clazzList.size(); - - // keep original order .. - clazzList.clear(); - String[] ifNames = new String[ifNamesNumber]; - { - int i=0; - - for (Iterator iter=baseInterfaces.iterator(); iter.hasNext(); ) { - Class ifClass = (Class)iter.next(); - if(!clazzList.contains(ifClass)) { - ifNames[i++] = new String(ifClass.getName()); - clazzList.add(ifClass); + PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(file))); + + List> baseInterfaces = Arrays.asList(baseInterfaceClass.getInterfaces()); + HashSet> clazzList = new HashSet>(); + clazzList.add(baseInterfaceClass); + clazzList.addAll(baseInterfaces); + int ifNamesNumber = clazzList.size(); + + // keep original order .. + clazzList.clear(); + String[] ifNames = new String[ifNamesNumber]; + { + int i = 0; + + for (Iterator> iter = baseInterfaces.iterator(); iter.hasNext();) { + Class ifClass = iter.next(); + if (!clazzList.contains(ifClass)) { + ifNames[i++] = ifClass.getName(); + clazzList.add(ifClass); + } } - } - - if(null!=baseInterfaceClass && !clazzList.contains(baseInterfaceClass)) { - ifNames[i++] = new String(baseInterfaceClass.getName()); - clazzList.add(baseInterfaceClass); - } - } - - clazzList.add(downstreamClass); - if(null!=prologClassOpt) { - clazzList.add(prologClassOpt); - } - - String[] importNames = new String[clazzList.size()+2]; - { - int i=0; - importNames[i++] = new String("java.io.*"); - importNames[i++] = new String("javax.media.opengl.*"); - for (Iterator iter=clazzList.iterator(); iter.hasNext(); ) { - importNames[i++] = new String(((Class)iter.next()).getName()); - } - } - - CodeGenUtils.emitJavaHeaders(output, - outputPackage, - outputClassName, - "com.jogamp.gluegen.runtime", // FIXME: should make configurable - true, - importNames, - new String[] { "public" }, - ifNames, - null, - new CodeGenUtils.EmissionCallback() { - public void emit(PrintWriter w) { emitClassDocComment(w); } - } - ); - - preMethodEmissionHook(output); - - constructorHook(output); - - emitGLIsMethods(output); - emitGLGetMethods(output); - - while (methodsToWrap.hasNext()) - { - PlainMethod pm = (PlainMethod)methodsToWrap.next(); - Method m = pm.getWrappedMethod(); - emitMethodDocComment(output, m); - emitSignature(output, m); - emitBody(output, m, pm.runHooks()); - } - - postMethodEmissionHook(output); - - output.println(); - output.print(" private " + downstreamName + " " + getDownstreamObjectName() + ";"); - - // end the class - output.println(); - output.print("} // end class "); - output.println(outputClassName); - - output.flush(); - output.close(); - - System.out.println("wrote to file: "+file); // JAU - } - /** Get the name of the object through which API calls should be routed. */ - protected String getDownstreamObjectName() - { - return "downstream" + downstreamName; - } - - /** Get the name of the object which shall be called as a prolog. */ - protected String getPrologObjectNameOpt() - { - if(null!=prologNameOpt) { - return "prolog" + prologNameOpt; - } - return null; - } - - protected void emitMethodDocComment(PrintWriter output, Method m) - { - } - - protected void emitSignature(PrintWriter output, Method m) - { - output.print(" public "); - output.print(' '); - output.print(JavaType.createForClass(m.getReturnType()).getName()); - output.print(' '); - output.print(m.getName()); - output.print('('); - output.print(getArgListAsString(m, true, true)); - output.println(")"); - } - - protected void emitBody(PrintWriter output, Method m, boolean runHooks) - { - output.println(" {"); - output.print(" "); - Class retType = m.getReturnType(); - - boolean callPreDownstreamHook = runHooks && hasPreDownstreamCallHook(m); - boolean callPostDownstreamHook = runHooks && hasPostDownstreamCallHook(m); - boolean callDownstream = (null!=getMethod(downstreamClass, m)) && - !( 0!=(GEN_PROLOG_XOR_DOWNSTREAM&getMode()) && callPreDownstreamHook ) ; - boolean hasResult = (retType != Void.TYPE); - - if(!callDownstream) { - if(!emptyDownstreamAllowed()) { - throw new RuntimeException("Method "+m+" has no downstream ("+downstreamName+")"); - } - } - - if(!callPreDownstreamHook && !callPostDownstreamHook && !callDownstream) { - if(!emptyMethodAllowed()) { - throw new RuntimeException("Method "+m+" is empty, no downstream ("+downstreamName+") nor prolog ("+prologNameOpt+")."); - } else { - output.print(" if(DEBUG) { System.out.println(\"WARNING: No prolog, no downstream, empty: \"+"); - printFunctionCallString(output, m); - output.println("); } "); + if (null != baseInterfaceClass && !clazzList.contains(baseInterfaceClass)) { + ifNames[i++] = baseInterfaceClass.getName(); + clazzList.add(baseInterfaceClass); + } + } + + clazzList.add(downstreamClass); + if (null != prologClassOpt) { + clazzList.add(prologClassOpt); + } + + String[] importNames = new String[clazzList.size() + 2]; + { + int i = 0; + importNames[i++] = "java.io.*"; + importNames[i++] = "javax.media.opengl.*"; + for (Iterator> iter = clazzList.iterator(); iter.hasNext();) { + importNames[i++] = iter.next().getName(); + } + } + + CodeGenUtils.emitJavaHeaders(output, + outputPackage, + outputClassName, + "com.jogamp.gluegen.runtime", // FIXME: should make configurable + true, + importNames, + new String[]{"public"}, + ifNames, + null, + new CodeGenUtils.EmissionCallback() { + public void emit(PrintWriter w) { + emitClassDocComment(w); + } + }); + + preMethodEmissionHook(output); + + constructorHook(output); + + emitGLIsMethods(output); + emitGLGetMethods(output); + + while (methodsToWrap.hasNext()) { + PlainMethod pm = methodsToWrap.next(); + Method m = pm.getWrappedMethod(); + emitMethodDocComment(output, m); + emitSignature(output, m); + emitBody(output, m, pm.runHooks()); + } + + postMethodEmissionHook(output); + + output.println(); + output.print(" private " + downstreamName + " " + getDownstreamObjectName() + ";"); + + // end the class + output.println(); + output.print("} // end class "); + output.println(outputClassName); + + output.flush(); + output.close(); + + System.out.println("wrote to file: " + file); // JAU } - } - if (callPreDownstreamHook) { - if(hasResult && !callDownstream) { - if(callPostDownstreamHook) { - output.print(" "+JavaType.createForClass(retType).getName()); - output.print(" _res = "); - } else { - output.print(" return "); + /** Get the name of the object through which API calls should be routed. */ + protected String getDownstreamObjectName() { + return "downstream" + downstreamName; + } + + /** Get the name of the object which shall be called as a prolog. */ + protected String getPrologObjectNameOpt() { + if (null != prologNameOpt) { + return "prolog" + prologNameOpt; } - } - preDownstreamCallHook(output, m); - } - - if(callDownstream) { - if (hasResult) { - if(callPostDownstreamHook) { - output.print(" "+JavaType.createForClass(retType).getName()); - output.print(" _res = "); - } else { - output.print(" return "); + return null; + } + + protected void emitMethodDocComment(PrintWriter output, Method m) { + } + + protected void emitSignature(PrintWriter output, Method m) { + output.print(" public "); + output.print(' '); + output.print(JavaType.createForClass(m.getReturnType()).getName()); + output.print(' '); + output.print(m.getName()); + output.print('('); + output.print(getArgListAsString(m, true, true)); + output.println(")"); + } + + protected void emitBody(PrintWriter output, Method m, boolean runHooks) { + output.println(" {"); + output.print(" "); + Class retType = m.getReturnType(); + + boolean callPreDownstreamHook = runHooks && hasPreDownstreamCallHook(m); + boolean callPostDownstreamHook = runHooks && hasPostDownstreamCallHook(m); + boolean callDownstream = (null != getMethod(downstreamClass, m)) + && !(0 != (GEN_PROLOG_XOR_DOWNSTREAM & getMode()) && callPreDownstreamHook); + boolean hasResult = (retType != Void.TYPE); + + if (!callDownstream) { + if (!emptyDownstreamAllowed()) { + throw new RuntimeException("Method " + m + " has no downstream (" + downstreamName + ")"); + } } - } - output.print(getDownstreamObjectName()); - output.print('.'); - output.print(m.getName()); - output.print('('); - output.print(getArgListAsString(m, false, true)); - output.println(");"); - } - - if (callPostDownstreamHook) { - postDownstreamCallHook(output, m); - } - - if (hasResult && callDownstream && callPostDownstreamHook) { - output.println(" return _res;"); - } - output.println(" }"); - } + if (!callPreDownstreamHook && !callPostDownstreamHook && !callDownstream) { + if (!emptyMethodAllowed()) { + throw new RuntimeException("Method " + m + " is empty, no downstream (" + downstreamName + ") nor prolog (" + prologNameOpt + ")."); + } else { + output.print(" if(DEBUG) { System.out.println(\"WARNING: No prolog, no downstream, empty: \"+"); + printFunctionCallString(output, m); + output.println("); } "); + } + } - protected String getArgListAsString(Method m, boolean includeArgTypes, boolean includeArgNames) - { - StringBuffer buf = new StringBuffer(256); - if (!includeArgNames && !includeArgTypes) - { - throw new IllegalArgumentException( - "Cannot generate arglist without both arg types and arg names"); - } - - Class[] argTypes = m.getParameterTypes(); - for (int i = 0; i < argTypes.length; ++i) - { - if (includeArgTypes) - { - buf.append(JavaType.createForClass(argTypes[i]).getName()); - buf.append(' '); - } - - if (includeArgNames) - { - buf.append("arg"); - buf.append(i); - } - if (i < argTypes.length-1) { buf.append(','); } - } - - return buf.toString(); - } - - /** The name of the class around which this pipeline is being - * composed. E.g., if this pipeline was constructed with - * "java.util.Set" as the baseInterfaceClassName, then this method will - * return "Set". - */ - protected String getBaseInterfaceName() - { - return baseName; - } - - /** Get the output name for this pipeline class. */ - protected abstract String getOutputName(); + if (callPreDownstreamHook) { + if (hasResult && !callDownstream) { + if (callPostDownstreamHook) { + output.print(" " + JavaType.createForClass(retType).getName()); + output.print(" _res = "); + } else { + output.print(" return "); + } + } + preDownstreamCallHook(output, m); + } - /** - * Called after the class headers have been generated, but before any - * method wrappers have been generated. - */ - protected void preMethodEmissionHook(PrintWriter output) { - output.println(" public static final boolean DEBUG = com.jogamp.opengl.impl.Debug.debug(\""+getOutputName()+"\");"); - } + if (callDownstream) { + if (hasResult) { + if (callPostDownstreamHook) { + output.print(" " + JavaType.createForClass(retType).getName()); + output.print(" _res = "); + } else { + output.print(" return "); + } + } + output.print(getDownstreamObjectName()); + output.print('.'); + output.print(m.getName()); + output.print('('); + output.print(getArgListAsString(m, false, true)); + output.println(");"); + } - /** - * Emits the constructor for the pipeline; called after the preMethodEmissionHook. - */ - protected abstract void constructorHook(PrintWriter output); + if (callPostDownstreamHook) { + postDownstreamCallHook(output, m); + } - /** - * Called after the method wrappers have been generated, but before the - * closing parenthesis of the class is emitted. - */ - protected void postMethodEmissionHook(PrintWriter output) { - output.println( " public String toString() {"); - output.println( " StringBuffer sb = new StringBuffer();"); - output.println( " sb.append(\""+getOutputName()+" [ implementing "+baseInterfaceClass.getName()+",\\n\\t\");"); - if(null!=prologClassOpt) { - output.println( " sb.append(\" prolog: \"+"+getPrologObjectNameOpt()+".toString()+\",\\n\\t\");"); - } - output.println( " sb.append(\" downstream: \"+"+getDownstreamObjectName()+".toString()+\"\\n\\t]\");"); - output.println( " return sb.toString();"); - output.println( " }"); - } + if (hasResult && callDownstream && callPostDownstreamHook) { + output.println(" return _res;"); + } + output.println(" }"); - /** - * Called before the pipeline routes the call to the downstream object. - */ - protected abstract void preDownstreamCallHook(PrintWriter output, Method m); - protected abstract boolean hasPreDownstreamCallHook(Method m); + } - /** - * Called after the pipeline has routed the call to the downstream object, - * but before the calling function exits or returns a value. - */ - protected abstract void postDownstreamCallHook(PrintWriter output, Method m); + protected String getArgListAsString(Method m, boolean includeArgTypes, boolean includeArgNames) { + StringBuilder buf = new StringBuilder(256); + if (!includeArgNames && !includeArgTypes) { + throw new IllegalArgumentException( + "Cannot generate arglist without both arg types and arg names"); + } - protected abstract boolean hasPostDownstreamCallHook(Method m); + Class[] argTypes = m.getParameterTypes(); + for (int i = 0; i < argTypes.length; ++i) { + if (includeArgTypes) { + buf.append(JavaType.createForClass(argTypes[i]).getName()); + buf.append(' '); + } - protected abstract int getMode(); - protected abstract boolean emptyMethodAllowed(); - protected abstract boolean emptyDownstreamAllowed(); + if (includeArgNames) { + buf.append("arg"); + buf.append(i); + } + if (i < argTypes.length - 1) { + buf.append(','); + } + } - /** Emit a Javadoc comment for this pipeline class. */ - protected abstract void emitClassDocComment(PrintWriter output); + return buf.toString(); + } - /** - * Emits one of the isGL* methods. - */ - protected void emitGLIsMethod(PrintWriter output, String type) { - output.println(" public boolean is" + type + "() {"); - Class clazz = BuildComposablePipeline.getClass("javax.media.opengl." + type); - if (clazz.isAssignableFrom(baseInterfaceClass)) { - output.println(" return true;"); - } else { - output.println(" return false;"); - } - output.println(" }"); - } + /** The name of the class around which this pipeline is being + * composed. E.g., if this pipeline was constructed with + * "java.util.Set" as the baseInterfaceClassName, then this method will + * return "Set". + */ + protected String getBaseInterfaceName() { + return baseName; + } - /** - * Emits all of the isGL* methods. - */ - protected void emitGLIsMethods(PrintWriter output) { - emitGLIsMethod(output, "GL"); - emitGLIsMethod(output, "GL3bc"); - emitGLIsMethod(output, "GL3"); - emitGLIsMethod(output, "GL2"); - emitGLIsMethod(output, "GLES1"); - emitGLIsMethod(output, "GLES2"); - emitGLIsMethod(output, "GL2ES1"); - emitGLIsMethod(output, "GL2ES2"); - emitGLIsMethod(output, "GL2GL3"); - output.println(" public boolean isGLES() {"); - output.println(" return isGLES2() || isGLES1();"); - output.println(" }"); - } - /** - * Emits one of the getGL* methods. - */ - protected void emitGLGetMethod(PrintWriter output, String type) { - output.println(" public javax.media.opengl." + type + " get" + type + "() {"); - Class clazz = BuildComposablePipeline.getClass("javax.media.opengl." + type); - if (clazz.isAssignableFrom(baseInterfaceClass)) { - output.println(" return this;"); - } else { - output.println(" throw new GLException(\"Not a " + type + " implementation\");"); - } - output.println(" }"); - } + /** Get the output name for this pipeline class. */ + protected abstract String getOutputName(); - /** - * Emits all of the getGL* methods. - */ - protected void emitGLGetMethods(PrintWriter output) { - emitGLGetMethod(output, "GL"); - emitGLGetMethod(output, "GL3bc"); - emitGLGetMethod(output, "GL3"); - emitGLGetMethod(output, "GL2"); - emitGLGetMethod(output, "GLES1"); - emitGLGetMethod(output, "GLES2"); - emitGLGetMethod(output, "GL2ES1"); - emitGLGetMethod(output, "GL2ES2"); - emitGLGetMethod(output, "GL2GL3"); - output.println(" public GLProfile getGLProfile() {"); - output.println(" return "+getDownstreamObjectName()+".getGLProfile();"); - output.println(" }"); - } - } // end class PipelineEmitter + /** + * Called after the class headers have been generated, but before any + * method wrappers have been generated. + */ + protected void preMethodEmissionHook(PrintWriter output) { + output.println(" public static final boolean DEBUG = com.jogamp.opengl.impl.Debug.debug(\"" + getOutputName() + "\");"); + } - //------------------------------------------------------- + /** + * Emits the constructor for the pipeline; called after the preMethodEmissionHook. + */ + protected abstract void constructorHook(PrintWriter output); + + /** + * Called after the method wrappers have been generated, but before the + * closing parenthesis of the class is emitted. + */ + protected void postMethodEmissionHook(PrintWriter output) { + output.println(" public String toString() {"); + output.println(" StringBuffer sb = new StringBuffer();"); + output.println(" sb.append(\"" + getOutputName() + " [ implementing " + baseInterfaceClass.getName() + ",\\n\\t\");"); + if (null != prologClassOpt) { + output.println(" sb.append(\" prolog: \"+" + getPrologObjectNameOpt() + ".toString()+\",\\n\\t\");"); + } + output.println(" sb.append(\" downstream: \"+" + getDownstreamObjectName() + ".toString()+\"\\n\\t]\");"); + output.println(" return sb.toString();"); + output.println(" }"); + } - protected class CustomPipeline extends PipelineEmitter - { - String className; - int mode; + /** + * Called before the pipeline routes the call to the downstream object. + */ + protected abstract void preDownstreamCallHook(PrintWriter output, Method m); - public CustomPipeline(int mode, String outputDir, String outputPackage, String outputName, Class baseInterfaceClass, Class prologClassOpt, Class downstreamClass) - { - super(outputDir, outputPackage, baseInterfaceClass, prologClassOpt, downstreamClass); - className = outputName; - this.mode = mode; - } + protected abstract boolean hasPreDownstreamCallHook(Method m); - protected String getOutputName() - { - return className; - } + /** + * Called after the pipeline has routed the call to the downstream object, + * but before the calling function exits or returns a value. + */ + protected abstract void postDownstreamCallHook(PrintWriter output, Method m); - protected int getMode() { return mode; } + protected abstract boolean hasPostDownstreamCallHook(Method m); - protected boolean emptyMethodAllowed() { - return true; - } - protected boolean emptyDownstreamAllowed() { - return true; - } + protected abstract int getMode(); - protected void preMethodEmissionHook(PrintWriter output) - { - super.preMethodEmissionHook(output); - } + protected abstract boolean emptyMethodAllowed(); - protected void constructorHook(PrintWriter output) { - output.print( " public " + getOutputName() + "(" ); - output.print( downstreamName + " " + getDownstreamObjectName() ); - if(null!=prologNameOpt) { - output.println( ", " + prologNameOpt + " " + getPrologObjectNameOpt() + ")"); - } else { - output.println(")"); - } - output.println(" {"); - output.println(" if (" + getDownstreamObjectName() + " == null) {"); - output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");"); - output.println(" }"); - output.print( " this." + getDownstreamObjectName()); - output.println(" = " + getDownstreamObjectName() + ";"); - if(null!=prologNameOpt) { - output.print( " this." + getPrologObjectNameOpt()); - output.println(" = " + getPrologObjectNameOpt() + ";"); - } - output.println(" }"); - output.println(); - } + protected abstract boolean emptyDownstreamAllowed(); - protected void postMethodEmissionHook(PrintWriter output) - { - super.postMethodEmissionHook(output); - if(null!=prologNameOpt) { - output.print(" private " + prologNameOpt + " " + getPrologObjectNameOpt() + ";"); - } - } + /** Emit a Javadoc comment for this pipeline class. */ + protected abstract void emitClassDocComment(PrintWriter output); - protected void emitClassDocComment(PrintWriter output) - { - output.println("/**"); - output.println(" * Composable pipeline {@link "+outputPackage+"."+outputName+"}, implementing the interface"); - output.println(" * {@link "+baseInterfaceClass.getName()+"}"); - output.println(" *

"); - output.println(" * Each method follows the call graph

    "); - if(null!=prologClassOpt) { - output.println(" *
  • call prolog {@link "+prologClassOpt.getName()+"} if available"); - } - output.println(" *
  • call downstream {@link "+downstreamClass.getName()+"} if available"); - if(null!=prologClassOpt && 0!=(GEN_PROLOG_XOR_DOWNSTREAM&getMode())) { - output.println(" * and if no call to {@link "+prologClassOpt.getName()+"} is made"); - } - output.println(" *

"); - output.println(" * "); - output.println(" *

    "); - output.println(" *
  • Interface {@link "+baseInterfaceClass.getName()+"}"); - if(null!=prologClassOpt) { - output.println(" *
  • Prolog {@link "+prologClassOpt.getName()+"}"); - } - output.println(" *
  • Downstream {@link "+downstreamClass.getName()+"}"); - output.println(" *

"); - output.println(" * Sample code which installs this pipeline:

"); - output.println(" * "); - output.println("
");
-      if(null!=prologNameOpt) {
-          output.println("     GL gl = drawable.setGL( new "+className+"( drawable.getGL().getGL2ES2(), new "+prologNameOpt+"( drawable.getGL().getGL2ES2() ) ) );");
-      } else {
-          output.println("     GL gl = drawable.setGL( new "+className+"( drawable.getGL().getGL2ES2() ) );");
-      }
-      output.println("
"); - output.println("*/"); - } - - protected boolean hasPreDownstreamCallHook(Method m) { - return null!=getMethod(prologClassOpt, m); - } + /** + * Emits one of the isGL* methods. + */ + protected void emitGLIsMethod(PrintWriter output, String type) { + output.println(" public boolean is" + type + "() {"); + Class clazz = BuildComposablePipeline.getClass("javax.media.opengl." + type); + if (clazz.isAssignableFrom(baseInterfaceClass)) { + output.println(" return true;"); + } else { + output.println(" return false;"); + } + output.println(" }"); + } - protected void preDownstreamCallHook(PrintWriter output, Method m) - { - if(null!=prologNameOpt) { - output.print(getPrologObjectNameOpt()); - output.print('.'); - output.print(m.getName()); - output.print('('); - output.print(getArgListAsString(m, false, true)); - output.println(");"); - } - } + /** + * Emits all of the isGL* methods. + */ + protected void emitGLIsMethods(PrintWriter output) { + emitGLIsMethod(output, "GL"); + emitGLIsMethod(output, "GL3bc"); + emitGLIsMethod(output, "GL3"); + emitGLIsMethod(output, "GL2"); + emitGLIsMethod(output, "GLES1"); + emitGLIsMethod(output, "GLES2"); + emitGLIsMethod(output, "GL2ES1"); + emitGLIsMethod(output, "GL2ES2"); + emitGLIsMethod(output, "GL2GL3"); + output.println(" public boolean isGLES() {"); + output.println(" return isGLES2() || isGLES1();"); + output.println(" }"); + } - protected boolean hasPostDownstreamCallHook(Method m) { - return false; - } + /** + * Emits one of the getGL* methods. + */ + protected void emitGLGetMethod(PrintWriter output, String type) { + output.println(" public javax.media.opengl." + type + " get" + type + "() {"); + Class clazz = BuildComposablePipeline.getClass("javax.media.opengl." + type); + if (clazz.isAssignableFrom(baseInterfaceClass)) { + output.println(" return this;"); + } else { + output.println(" throw new GLException(\"Not a " + type + " implementation\");"); + } + output.println(" }"); + } - protected void postDownstreamCallHook(PrintWriter output, Method m) - { - } + /** + * Emits all of the getGL* methods. + */ + protected void emitGLGetMethods(PrintWriter output) { + emitGLGetMethod(output, "GL"); + emitGLGetMethod(output, "GL3bc"); + emitGLGetMethod(output, "GL3"); + emitGLGetMethod(output, "GL2"); + emitGLGetMethod(output, "GLES1"); + emitGLGetMethod(output, "GLES2"); + emitGLGetMethod(output, "GL2ES1"); + emitGLGetMethod(output, "GL2ES2"); + emitGLGetMethod(output, "GL2GL3"); + output.println(" public GLProfile getGLProfile() {"); + output.println(" return " + getDownstreamObjectName() + ".getGLProfile();"); + output.println(" }"); + } + } // end class PipelineEmitter - } // end class CustomPipeline + //------------------------------------------------------- + protected class CustomPipeline extends PipelineEmitter { - protected class DebugPipeline extends PipelineEmitter - { - String className; - public DebugPipeline(String outputDir, String outputPackage, Class baseInterfaceClass, Class downstreamClass) - { - super(outputDir, outputPackage, baseInterfaceClass, null, downstreamClass); - className = "Debug" + getBaseInterfaceName(); - } + String className; + int mode; - protected String getOutputName() - { - return className; - } + CustomPipeline(int mode, String outputDir, String outputPackage, String outputName, Class baseInterfaceClass, Class prologClassOpt, Class downstreamClass) { + super(outputDir, outputPackage, baseInterfaceClass, prologClassOpt, downstreamClass); + className = outputName; + this.mode = mode; + } - protected int getMode() { return 0; } + protected String getOutputName() { + return className; + } - protected boolean emptyMethodAllowed() { - return false; - } - protected boolean emptyDownstreamAllowed() { - return false; - } + protected int getMode() { + return mode; + } - protected void preMethodEmissionHook(PrintWriter output) - { - super.preMethodEmissionHook(output); - } + protected boolean emptyMethodAllowed() { + return true; + } - protected void constructorHook(PrintWriter output) { - output.print( " public " + getOutputName() + "(" ); - output.println( downstreamName + " " + getDownstreamObjectName() + ")"); - output.println(" {"); - output.println(" if (" + getDownstreamObjectName() + " == null) {"); - output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");"); - output.println(" }"); - output.print( " this." + getDownstreamObjectName()); - output.println(" = " + getDownstreamObjectName() + ";"); - if(null!=prologNameOpt) { - output.print( " this." + getPrologObjectNameOpt()); - output.println(" = " + getPrologObjectNameOpt() + ";"); - } - output.println(" // Fetch GLContext object for better error checking (if possible)"); - output.println(" _context = " + getDownstreamObjectName() + ".getContext();"); - output.println(" }"); - output.println(); - } + protected boolean emptyDownstreamAllowed() { + return true; + } - protected void postMethodEmissionHook(PrintWriter output) - { - super.postMethodEmissionHook(output); - output.println(" private void checkGLGetError(String caller)"); - output.println(" {"); - if (hasImmediateMode) { - output.println(" if (insideBeginEndPair) {"); - output.println(" return;"); - output.println(" }"); - output.println(); - } - output.println(" // Debug code to make sure the pipeline is working; leave commented out unless testing this class"); - output.println(" //System.err.println(\"Checking for GL errors " + - "after call to \" + caller);"); - output.println(); - output.println(" int err = " + - getDownstreamObjectName() + - ".glGetError();"); - output.println(" if (err == GL_NO_ERROR) { return; }"); - output.println(); - output.println(" StringBuffer buf = new StringBuffer(Thread.currentThread()+"); - output.println(" \" glGetError() returned the following error codes " + - "after a call to \" + caller + \": \");"); - output.println(); - output.println(" // Loop repeatedly to allow for distributed GL implementations,"); - output.println(" // as detailed in the glGetError() specification"); - output.println(" int recursionDepth = 10;"); - output.println(" do {"); - output.println(" switch (err) {"); - output.println(" case GL_INVALID_ENUM: buf.append(\"GL_INVALID_ENUM \"); break;"); - output.println(" case GL_INVALID_VALUE: buf.append(\"GL_INVALID_VALUE \"); break;"); - output.println(" case GL_INVALID_OPERATION: buf.append(\"GL_INVALID_OPERATION \"); break;"); - if (hasStackOverflow) { - output.println(" case GL_STACK_OVERFLOW: buf.append(\"GL_STACK_OVERFLOW \"); break;"); - output.println(" case GL_STACK_UNDERFLOW: buf.append(\"GL_STACK_UNDERFLOW \"); break;"); - } - output.println(" case GL_OUT_OF_MEMORY: buf.append(\"GL_OUT_OF_MEMORY \"); break;"); - output.println(" case GL_NO_ERROR: throw new InternalError(\"Should not be treating GL_NO_ERROR as error\");"); - output.println(" default: buf.append(\"Unknown glGetError() return value: \");"); - output.println(" }"); - output.println(" buf.append(\"( \" + err + \" 0x\"+Integer.toHexString(err).toUpperCase() + \"), \");"); - output.println(" } while ((--recursionDepth >= 0) && (err = " + - getDownstreamObjectName() + - ".glGetError()) != GL_NO_ERROR);"); - output.println(" throw new GLException(buf.toString());"); - output.println(" }"); - if (hasImmediateMode) { - output.println(" /** True if the pipeline is inside a glBegin/glEnd pair.*/"); - output.println(" private boolean insideBeginEndPair = false;"); - output.println(); - } - output.println(" private void checkContext() {"); - output.println(" GLContext currentContext = GLContext.getCurrent();"); - output.println(" if (currentContext == null) {"); - output.println(" throw new GLException(\"No OpenGL context is current on this thread\");"); - output.println(" }"); - output.println(" if ((_context != null) && (_context != currentContext)) {"); - output.println(" throw new GLException(\"This GL object is being incorrectly used with a different GLContext than that which created it\");"); - output.println(" }"); - output.println(" }"); - output.println(" private GLContext _context;"); - } + @Override + protected void preMethodEmissionHook(PrintWriter output) { + super.preMethodEmissionHook(output); + } - protected void emitClassDocComment(PrintWriter output) - { - output.println("/**

Composable pipeline which wraps an underlying {@link GL} implementation,"); - output.println(" providing error checking after each OpenGL method call. If an error occurs,"); - output.println(" causes a {@link GLException} to be thrown at exactly the point of failure."); - output.println(" Sample code which installs this pipeline:

"); - output.println(); - output.println("
");
-      output.println("     GL gl = drawable.setGL(new DebugGL(drawable.getGL()));");
-      output.println("
"); - output.println("*/"); - } - - protected boolean hasPreDownstreamCallHook(Method m) { - return true; - } + protected void constructorHook(PrintWriter output) { + output.print(" public " + getOutputName() + "("); + output.print(downstreamName + " " + getDownstreamObjectName()); + if (null != prologNameOpt) { + output.println(", " + prologNameOpt + " " + getPrologObjectNameOpt() + ")"); + } else { + output.println(")"); + } + output.println(" {"); + output.println(" if (" + getDownstreamObjectName() + " == null) {"); + output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");"); + output.println(" }"); + output.print(" this." + getDownstreamObjectName()); + output.println(" = " + getDownstreamObjectName() + ";"); + if (null != prologNameOpt) { + output.print(" this." + getPrologObjectNameOpt()); + output.println(" = " + getPrologObjectNameOpt() + ";"); + } + output.println(" }"); + output.println(); + } - protected void preDownstreamCallHook(PrintWriter output, Method m) - { - output.println(" checkContext();"); - } + @Override + protected void postMethodEmissionHook(PrintWriter output) { + super.postMethodEmissionHook(output); + if (null != prologNameOpt) { + output.print(" private " + prologNameOpt + " " + getPrologObjectNameOpt() + ";"); + } + } - protected boolean hasPostDownstreamCallHook(Method m) { - return true; - } + protected void emitClassDocComment(PrintWriter output) { + output.println("/**"); + output.println(" * Composable pipeline {@link " + outputPackage + "." + outputName + "}, implementing the interface"); + output.println(" * {@link " + baseInterfaceClass.getName() + "}"); + output.println(" *

"); + output.println(" * Each method follows the call graph

    "); + if (null != prologClassOpt) { + output.println(" *
  • call prolog {@link " + prologClassOpt.getName() + "} if available"); + } + output.println(" *
  • call downstream {@link " + downstreamClass.getName() + "} if available"); + if (null != prologClassOpt && 0 != (GEN_PROLOG_XOR_DOWNSTREAM & getMode())) { + output.println(" * and if no call to {@link " + prologClassOpt.getName() + "} is made"); + } + output.println(" *

"); + output.println(" * "); + output.println(" *

    "); + output.println(" *
  • Interface {@link " + baseInterfaceClass.getName() + "}"); + if (null != prologClassOpt) { + output.println(" *
  • Prolog {@link " + prologClassOpt.getName() + "}"); + } + output.println(" *
  • Downstream {@link " + downstreamClass.getName() + "}"); + output.println(" *

"); + output.println(" * Sample code which installs this pipeline:

"); + output.println(" * "); + output.println("
");
+            if (null != prologNameOpt) {
+                output.println("     GL gl = drawable.setGL( new " + className + "( drawable.getGL().getGL2ES2(), new " + prologNameOpt + "( drawable.getGL().getGL2ES2() ) ) );");
+            } else {
+                output.println("     GL gl = drawable.setGL( new " + className + "( drawable.getGL().getGL2ES2() ) );");
+            }
+            output.println("
"); + output.println("*/"); + } - protected void postDownstreamCallHook(PrintWriter output, Method m) - { - if (m.getName().equals("glBegin")) - { - output.println(" insideBeginEndPair = true;"); - output.println(" // NOTE: can't check glGetError(); it's not allowed inside glBegin/glEnd pair"); - } - else - { - if (m.getName().equals("glEnd")) - { - output.println(" insideBeginEndPair = false;"); - } - - output.println(" String txt = new String(\""+ m.getName() + "(\" +"); - Class[] params = m.getParameterTypes() ; - for(int i=0; params!=null && i 0x\"+Integer.toHexString(arg"+i+").toUpperCase() +"); - } else { - output.println(" \"<"+params[i].getName()+">\" +"); - } - if(i baseInterfaceClass, Class downstreamClass) { + super(outputDir, outputPackage, baseInterfaceClass, null, downstreamClass); + className = "Debug" + getBaseInterfaceName(); + } - protected void preMethodEmissionHook(PrintWriter output) - { - super.preMethodEmissionHook(output); - } + protected String getOutputName() { + return className; + } - protected void constructorHook(PrintWriter output) { - output.print( " public " + getOutputName() + "(" ); - output.println( downstreamName + " " + getDownstreamObjectName() + ", PrintStream " + getOutputStreamName() + ")"); - output.println(" {"); - output.println(" if (" + getDownstreamObjectName() + " == null) {"); - output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");"); - output.println(" }"); - output.print( " this." + getDownstreamObjectName()); - output.println(" = " + getDownstreamObjectName() + ";"); - output.print( " this." + getOutputStreamName()); - output.println(" = " + getOutputStreamName() + ";"); - output.println(" }"); - output.println(); - } + protected int getMode() { + return 0; + } - protected void postMethodEmissionHook(PrintWriter output) - { - super.postMethodEmissionHook(output); - output.println("private PrintStream " + getOutputStreamName() + ";"); - output.println("private int indent = 0;"); - output.println("protected String dumpArray(Object obj)"); - output.println("{"); - output.println(" if (obj == null) return \"[null]\";"); - output.println(" StringBuffer sb = new StringBuffer(\"[\");"); - output.println(" int len = java.lang.reflect.Array.getLength(obj);"); - output.println(" int count = Math.min(len,16);"); - output.println(" for ( int i =0; i < count; i++ ) {"); - output.println(" sb.append(java.lang.reflect.Array.get(obj,i));"); - output.println(" if (i < count-1)"); - output.println(" sb.append(',');"); - output.println(" }"); - output.println(" if ( len > 16 )"); - output.println(" sb.append(\"...\").append(len);"); - output.println(" sb.append(']');"); - output.println(" return sb.toString();"); - output.println("}"); - output.println("protected void print(String str)"); - output.println("{"); - output.println(" "+getOutputStreamName()+".print(str);"); - output.println("}"); - output.println("protected void println(String str)"); - output.println("{"); - output.println(" "+getOutputStreamName()+".println(str);"); - output.println("}"); - output.println("protected void printIndent()"); - output.println("{"); - output.println(" for( int i =0; i < indent; i++) {"+getOutputStreamName()+".print(' ');}"); - output.println("}"); - } - protected void emitClassDocComment(PrintWriter output) - { - output.println("/**

Composable pipeline which wraps an underlying {@link GL} implementation,"); - output.println(" providing tracing information to a user-specified {@link java.io.PrintStream}"); - output.println(" before and after each OpenGL method call. Sample code which installs this pipeline:

"); - output.println(); - output.println("
");
-      output.println("     GL gl = drawable.setGL(new TraceGL(drawable.getGL(), System.err));");
-      output.println("
"); - output.println("*/"); - } - - protected boolean hasPreDownstreamCallHook(Method m) { - return true; - } + protected boolean emptyMethodAllowed() { + return false; + } - protected void preDownstreamCallHook(PrintWriter output, Method m) - { - if ( m.getName().equals("glEnd") || m.getName().equals("glEndList")) - { - output.println("indent-=2;"); - output.println(" printIndent();"); - } - else - { - output.println("printIndent();"); - } - - output.print(" print("); - printFunctionCallString(output, m); - output.println(");"); - } + protected boolean emptyDownstreamAllowed() { + return false; + } - protected boolean hasPostDownstreamCallHook(Method m) { - return true; - } + @Override + protected void preMethodEmissionHook(PrintWriter output) { + super.preMethodEmissionHook(output); + } - protected void postDownstreamCallHook(PrintWriter output, Method m) - { - Class ret = m.getReturnType(); - if ( ret != Void.TYPE ) - { - output.println(" println(\" = \"+_res);"); - } - else - { - output.println(" println(\"\");"); - } - } + protected void constructorHook(PrintWriter output) { + output.print(" public " + getOutputName() + "("); + output.println(downstreamName + " " + getDownstreamObjectName() + ")"); + output.println(" {"); + output.println(" if (" + getDownstreamObjectName() + " == null) {"); + output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");"); + output.println(" }"); + output.print(" this." + getDownstreamObjectName()); + output.println(" = " + getDownstreamObjectName() + ";"); + if (null != prologNameOpt) { + output.print(" this." + getPrologObjectNameOpt()); + output.println(" = " + getPrologObjectNameOpt() + ";"); + } + output.println(" // Fetch GLContext object for better error checking (if possible)"); + output.println(" _context = " + getDownstreamObjectName() + ".getContext();"); + output.println(" }"); + output.println(); + } - private String getOutputStreamName() { - return "stream"; - } + @Override + protected void postMethodEmissionHook(PrintWriter output) { + super.postMethodEmissionHook(output); + output.println(" private void checkGLGetError(String caller)"); + output.println(" {"); + if (hasImmediateMode) { + output.println(" if (insideBeginEndPair) {"); + output.println(" return;"); + output.println(" }"); + output.println(); + } + output.println(" // Debug code to make sure the pipeline is working; leave commented out unless testing this class"); + output.println(" //System.err.println(\"Checking for GL errors " + + "after call to \" + caller);"); + output.println(); + output.println(" int err = " + + getDownstreamObjectName() + + ".glGetError();"); + output.println(" if (err == GL_NO_ERROR) { return; }"); + output.println(); + output.println(" StringBuffer buf = new StringBuffer(Thread.currentThread()+"); + output.println(" \" glGetError() returned the following error codes after a call to \" + caller + \": \");"); + output.println(); + output.println(" // Loop repeatedly to allow for distributed GL implementations,"); + output.println(" // as detailed in the glGetError() specification"); + output.println(" int recursionDepth = 10;"); + output.println(" do {"); + output.println(" switch (err) {"); + output.println(" case GL_INVALID_ENUM: buf.append(\"GL_INVALID_ENUM \"); break;"); + output.println(" case GL_INVALID_VALUE: buf.append(\"GL_INVALID_VALUE \"); break;"); + output.println(" case GL_INVALID_OPERATION: buf.append(\"GL_INVALID_OPERATION \"); break;"); + if (hasStackOverflow) { + output.println(" case GL_STACK_OVERFLOW: buf.append(\"GL_STACK_OVERFLOW \"); break;"); + output.println(" case GL_STACK_UNDERFLOW: buf.append(\"GL_STACK_UNDERFLOW \"); break;"); + } + output.println(" case GL_OUT_OF_MEMORY: buf.append(\"GL_OUT_OF_MEMORY \"); break;"); + output.println(" case GL_NO_ERROR: throw new InternalError(\"Should not be treating GL_NO_ERROR as error\");"); + output.println(" default: buf.append(\"Unknown glGetError() return value: \");"); + output.println(" }"); + output.println(" buf.append(\"( \" + err + \" 0x\"+Integer.toHexString(err).toUpperCase() + \"), \");"); + output.println(" } while ((--recursionDepth >= 0) && (err = " + + getDownstreamObjectName() + + ".glGetError()) != GL_NO_ERROR);"); + output.println(" throw new GLException(buf.toString());"); + output.println(" }"); + if (hasImmediateMode) { + output.println(" /** True if the pipeline is inside a glBegin/glEnd pair.*/"); + output.println(" private boolean insideBeginEndPair = false;"); + output.println(); + } + output.println(" private void checkContext() {"); + output.println(" GLContext currentContext = GLContext.getCurrent();"); + output.println(" if (currentContext == null) {"); + output.println(" throw new GLException(\"No OpenGL context is current on this thread\");"); + output.println(" }"); + output.println(" if ((_context != null) && (_context != currentContext)) {"); + output.println(" throw new GLException(\"This GL object is being incorrectly used with a different GLContext than that which created it\");"); + output.println(" }"); + output.println(" }"); + output.println(" private GLContext _context;"); + } - } // end class TracePipeline - - public static final void printFunctionCallString(PrintWriter output, Method m) { - Class[] params = m.getParameterTypes(); - output.print(" \"" + m.getName() + "(\""); - for ( int i =0; i < params.length; i++ ) - { - if ( params[i].isArray() ) { - output.print("+\"<"+params[i].getName()+">\""); - } else if(params[i].equals(int.class)) { - output.print("+\"<"+params[i].getName()+"> 0x\"+Integer.toHexString(arg"+i+").toUpperCase()"); - } else { - output.print("+\"<"+params[i].getName()+"> \"+arg"+i); + protected void emitClassDocComment(PrintWriter output) { + output.println("/**

Composable pipeline which wraps an underlying {@link GL} implementation,"); + output.println(" providing error checking after each OpenGL method call. If an error occurs,"); + output.println(" causes a {@link GLException} to be thrown at exactly the point of failure."); + output.println(" Sample code which installs this pipeline:

"); + output.println(); + output.println("
");
+            output.println("     GL gl = drawable.setGL(new DebugGL(drawable.getGL()));");
+            output.println("
"); + output.println("*/"); + } + + protected boolean hasPreDownstreamCallHook(Method m) { + return true; + } + + protected void preDownstreamCallHook(PrintWriter output, Method m) { + output.println(" checkContext();"); + } + + protected boolean hasPostDownstreamCallHook(Method m) { + return true; + } + + protected void postDownstreamCallHook(PrintWriter output, Method m) { + if (m.getName().equals("glBegin")) { + output.println(" insideBeginEndPair = true;"); + output.println(" // NOTE: can't check glGetError(); it's not allowed inside glBegin/glEnd pair"); + } else { + if (m.getName().equals("glEnd")) { + output.println(" insideBeginEndPair = false;"); + } + + output.println(" String txt = new String(\"" + m.getName() + "(\" +"); + Class[] params = m.getParameterTypes(); + for (int i = 0; params != null && i < params.length; i++) { + if (params[i].equals(int.class)) { + output.println(" \"<" + params[i].getName() + "> 0x\"+Integer.toHexString(arg" + i + ").toUpperCase() +"); + } else { + output.println(" \"<" + params[i].getName() + ">\" +"); + } + if (i < params.length - 1) { + output.println(" \", \" +"); + } + } + output.println(" \")\");"); + // calls to glGetError() are only allowed outside of glBegin/glEnd pairs + output.println(" checkGLGetError( txt );"); + } + } + } // end class DebugPipeline + + //------------------------------------------------------- + protected class TracePipeline extends PipelineEmitter { + + String className; + + TracePipeline(String outputDir, String outputPackage, Class baseInterfaceClass, Class downstreamClass) { + super(outputDir, outputPackage, baseInterfaceClass, null, downstreamClass); + className = "Trace" + getBaseInterfaceName(); + } + + protected String getOutputName() { + return className; + } + + protected int getMode() { + return 0; } - if ( i < params.length-1) { - output.print("+\", \""); + + protected boolean emptyMethodAllowed() { + return false; } - } - output.print("+\")\""); - } + + protected boolean emptyDownstreamAllowed() { + return false; + } + + @Override + protected void preMethodEmissionHook(PrintWriter output) { + super.preMethodEmissionHook(output); + } + + protected void constructorHook(PrintWriter output) { + output.print(" public " + getOutputName() + "("); + output.println(downstreamName + " " + getDownstreamObjectName() + ", PrintStream " + getOutputStreamName() + ")"); + output.println(" {"); + output.println(" if (" + getDownstreamObjectName() + " == null) {"); + output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");"); + output.println(" }"); + output.print(" this." + getDownstreamObjectName()); + output.println(" = " + getDownstreamObjectName() + ";"); + output.print(" this." + getOutputStreamName()); + output.println(" = " + getOutputStreamName() + ";"); + output.println(" }"); + output.println(); + } + + @Override + protected void postMethodEmissionHook(PrintWriter output) { + super.postMethodEmissionHook(output); + output.println("private PrintStream " + getOutputStreamName() + ";"); + output.println("private int indent = 0;"); + output.println("protected String dumpArray(Object obj)"); + output.println("{"); + output.println(" if (obj == null) return \"[null]\";"); + output.println(" StringBuffer sb = new StringBuffer(\"[\");"); + output.println(" int len = java.lang.reflect.Array.getLength(obj);"); + output.println(" int count = Math.min(len,16);"); + output.println(" for ( int i =0; i < count; i++ ) {"); + output.println(" sb.append(java.lang.reflect.Array.get(obj,i));"); + output.println(" if (i < count-1)"); + output.println(" sb.append(',');"); + output.println(" }"); + output.println(" if ( len > 16 )"); + output.println(" sb.append(\"...\").append(len);"); + output.println(" sb.append(']');"); + output.println(" return sb.toString();"); + output.println("}"); + output.println("protected void print(String str)"); + output.println("{"); + output.println(" " + getOutputStreamName() + ".print(str);"); + output.println("}"); + output.println("protected void println(String str)"); + output.println("{"); + output.println(" " + getOutputStreamName() + ".println(str);"); + output.println("}"); + output.println("protected void printIndent()"); + output.println("{"); + output.println(" for( int i =0; i < indent; i++) {" + getOutputStreamName() + ".print(' ');}"); + output.println("}"); + } + + protected void emitClassDocComment(PrintWriter output) { + output.println("/**

Composable pipeline which wraps an underlying {@link GL} implementation,"); + output.println(" providing tracing information to a user-specified {@link java.io.PrintStream}"); + output.println(" before and after each OpenGL method call. Sample code which installs this pipeline:

"); + output.println(); + output.println("
");
+            output.println("     GL gl = drawable.setGL(new TraceGL(drawable.getGL(), System.err));");
+            output.println("
"); + output.println("*/"); + } + + protected boolean hasPreDownstreamCallHook(Method m) { + return true; + } + + protected void preDownstreamCallHook(PrintWriter output, Method m) { + if (m.getName().equals("glEnd") || m.getName().equals("glEndList")) { + output.println("indent-=2;"); + output.println(" printIndent();"); + } else { + output.println("printIndent();"); + } + + output.print(" print("); + printFunctionCallString(output, m); + output.println(");"); + } + + protected boolean hasPostDownstreamCallHook(Method m) { + return true; + } + + protected void postDownstreamCallHook(PrintWriter output, Method m) { + Class ret = m.getReturnType(); + if (ret != Void.TYPE) { + output.println(" println(\" = \"+_res);"); + } else { + output.println(" println(\"\");"); + } + } + + private String getOutputStreamName() { + return "stream"; + } + } // end class TracePipeline + + public static final void printFunctionCallString(PrintWriter output, Method m) { + Class[] params = m.getParameterTypes(); + output.print(" \"" + m.getName() + "(\""); + for (int i = 0; i < params.length; i++) { + if (params[i].isArray()) { + output.print("+\"<" + params[i].getName() + ">\""); + } else if (params[i].equals(int.class)) { + output.print("+\"<" + params[i].getName() + "> 0x\"+Integer.toHexString(arg" + i + ").toUpperCase()"); + } else { + output.print("+\"<" + params[i].getName() + "> \"+arg" + i); + } + if (i < params.length - 1) { + output.print("+\", \""); + } + } + output.print("+\")\""); + } } diff --git a/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java b/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java index f7a7fe030..2be5519fe 100644 --- a/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java +++ b/src/java/com/sun/gluegen/opengl/BuildStaticGLInfo.java @@ -88,8 +88,8 @@ import java.util.regex.*; * with the symbol * GL_ARB_texture_compression . * */ -public class BuildStaticGLInfo -{ +public class BuildStaticGLInfo { + // Handles function pointer protected static int funcIdentifierGroup = 10; protected static Pattern funcPattern = @@ -110,242 +110,237 @@ public class BuildStaticGLInfo protected Map> extensionToDeclarationMap = new HashMap>(); protected boolean debug = false; - /** - * The first argument is the package to which the StaticGLInfo class - * belongs, the second is the path to the directory in which that package's - * classes reside, and the remaining arguments are paths to the C header - * files that should be parsed - */ - public static void main(String[] args) throws IOException - { - if (args.length > 0 && args[0].equals("-test")) { - BuildStaticGLInfo builder = new BuildStaticGLInfo(); - builder.setDebug(true); - String[] newArgs = new String[args.length - 1]; - System.arraycopy(args, 1, newArgs, 0, args.length - 1); - builder.parse(newArgs); - builder.dump(); - System.exit(0); - } + /** + * The first argument is the package to which the StaticGLInfo class + * belongs, the second is the path to the directory in which that package's + * classes reside, and the remaining arguments are paths to the C header + * files that should be parsed + */ + public static void main(String[] args) throws IOException { + if (args.length > 0 && args[0].equals("-test")) { + BuildStaticGLInfo builder = new BuildStaticGLInfo(); + builder.setDebug(true); + String[] newArgs = new String[args.length - 1]; + System.arraycopy(args, 1, newArgs, 0, args.length - 1); + builder.parse(newArgs); + builder.dump(); + System.exit(0); + } - String packageName = args[0]; - String packageDir = args[1]; + String packageName = args[0]; + String packageDir = args[1]; - String[] cHeaderFilePaths = new String[args.length-2]; - System.arraycopy(args, 2, cHeaderFilePaths, 0, cHeaderFilePaths.length); - - BuildStaticGLInfo builder = new BuildStaticGLInfo(); - try { - builder.parse(cHeaderFilePaths); + String[] cHeaderFilePaths = new String[args.length - 2]; + System.arraycopy(args, 2, cHeaderFilePaths, 0, cHeaderFilePaths.length); - File file = new File(packageDir + File.separatorChar + "StaticGLInfo.java"); - String parentDir = file.getParent(); - if (parentDir != null) { - File pDirFile = new File(parentDir); - pDirFile.mkdirs(); - } + BuildStaticGLInfo builder = new BuildStaticGLInfo(); + try { + builder.parse(cHeaderFilePaths); - PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file))); - builder.emitJavaCode(writer, packageName); + File file = new File(packageDir + File.separatorChar + "StaticGLInfo.java"); + String parentDir = file.getParent(); + if (parentDir != null) { + File pDirFile = new File(parentDir); + pDirFile.mkdirs(); + } - writer.flush(); - writer.close(); - } - catch (Exception e) - { - StringBuffer buf = new StringBuffer("{ "); - for (int i = 0; i < cHeaderFilePaths.length; ++i) - { - buf.append(cHeaderFilePaths[i]); - buf.append(" "); - } - buf.append('}'); - throw new RuntimeException( - "Error building StaticGLInfo.java from " + buf.toString(), e); + PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file))); + builder.emitJavaCode(writer, packageName); + + writer.flush(); + writer.close(); + } catch (Exception e) { + StringBuilder buf = new StringBuilder("{ "); + for (int i = 0; i < cHeaderFilePaths.length; ++i) { + buf.append(cHeaderFilePaths[i]); + buf.append(" "); + } + buf.append('}'); + throw new RuntimeException( + "Error building StaticGLInfo.java from " + buf.toString(), e); + } } - } - public void setDebug(boolean v) { - debug = v; - } - - /** Parses the supplied C header files and adds the function - associations contained therein to the internal map. */ - public void parse(String[] cHeaderFilePaths) throws IOException { - for (int i = 0; i < cHeaderFilePaths.length; i++) { - parse(cHeaderFilePaths[i]); + public void setDebug(boolean v) { + debug = v; } - } - /** Parses the supplied C header file and adds the function - associations contained therein to the internal map. */ - public void parse(String cHeaderFilePath) throws IOException { - BufferedReader reader = new BufferedReader(new FileReader(cHeaderFilePath)); - String line, activeAssociation = null; - Matcher m = null; - while ((line = reader.readLine()) != null) { - int type = 0; // 1-define, 2-function - // see if we're inside a #ifndef GL_XXX block and matching a function - if (activeAssociation != null) { - String identifier = null; - if ((m = funcPattern.matcher(line)).matches()) { - identifier = m.group(funcIdentifierGroup).trim(); - type =2; - } else if ((m = definePattern.matcher(line)).matches()) { - identifier = m.group(defineIdentifierGroup).trim(); - type =1; - } else if (line.startsWith("#endif")) { - if(debug) { - System.err.println("END ASSOCIATION BLOCK: <" + activeAssociation + ">"); - } - activeAssociation = null; + /** Parses the supplied C header files and adds the function + associations contained therein to the internal map. */ + public void parse(String[] cHeaderFilePaths) throws IOException { + for (int i = 0; i < cHeaderFilePaths.length; i++) { + parse(cHeaderFilePaths[i]); } - if ((identifier != null) && - (activeAssociation != null) && - // Handles #ifndef GL_... #define GL_... - !identifier.equals(activeAssociation)) { - addAssociation(identifier, activeAssociation); - if(debug) { - System.err.println(" ADDING ASSOCIATION: <" + identifier + "> <" + activeAssociation + "> ; type "+type); - } + } + + /** Parses the supplied C header file and adds the function + associations contained therein to the internal map. */ + public void parse(String cHeaderFilePath) throws IOException { + BufferedReader reader = new BufferedReader(new FileReader(cHeaderFilePath)); + String line, activeAssociation = null; + Matcher m = null; + while ((line = reader.readLine()) != null) { + int type = 0; // 1-define, 2-function + // see if we're inside a #ifndef GL_XXX block and matching a function + if (activeAssociation != null) { + String identifier = null; + if ((m = funcPattern.matcher(line)).matches()) { + identifier = m.group(funcIdentifierGroup).trim(); + type = 2; + } else if ((m = definePattern.matcher(line)).matches()) { + identifier = m.group(defineIdentifierGroup).trim(); + type = 1; + } else if (line.startsWith("#endif")) { + if (debug) { + System.err.println("END ASSOCIATION BLOCK: <" + activeAssociation + ">"); + } + activeAssociation = null; + } + if ((identifier != null) + && (activeAssociation != null) + && // Handles #ifndef GL_... #define GL_... + !identifier.equals(activeAssociation)) { + addAssociation(identifier, activeAssociation); + if (debug) { + System.err.println(" ADDING ASSOCIATION: <" + identifier + "> <" + activeAssociation + "> ; type " + type); + } + } + } else if ((m = associationPattern.matcher(line)).matches()) { + // found a new #ifndef GL_XXX block + activeAssociation = m.group(1).trim(); + + if (debug) { + System.err.println("BEGIN ASSOCIATION BLOCK: <" + activeAssociation + ">"); + } + } } - } else if ((m = associationPattern.matcher(line)).matches()) { - // found a new #ifndef GL_XXX block - activeAssociation = m.group(1).trim(); - - if(debug) { - System.err.println("BEGIN ASSOCIATION BLOCK: <" + activeAssociation + ">"); + reader.close(); + } + + public void dump() { + for (String name : extensionToDeclarationMap.keySet()) { + Set decls = extensionToDeclarationMap.get(name); + System.out.println("<" + name + "> :"); + List l = new ArrayList(); + l.addAll(decls); + Collections.sort(l); + for (String str : l) { + System.out.println(" <" + str + ">"); + } } - } } - reader.close(); - } - public void dump() { - for (String name : extensionToDeclarationMap.keySet()) { - Set decls = extensionToDeclarationMap.get(name); - System.out.println("<"+name+"> :"); - List l = new ArrayList(); - l.addAll(decls); - Collections.sort(l); - for (String str : l) { - System.out.println(" <" + str + ">"); - } + public String getExtension(String identifier) { + return declarationToExtensionMap.get(identifier); } - } - public String getExtension(String identifier) { - return declarationToExtensionMap.get(identifier); - } - - public Set getDeclarations(String extension) { - return extensionToDeclarationMap.get(extension); - } + public Set getDeclarations(String extension) { + return extensionToDeclarationMap.get(extension); + } - public Set getExtensions() { - return extensionToDeclarationMap.keySet(); - } + public Set getExtensions() { + return extensionToDeclarationMap.keySet(); + } - public void emitJavaCode(PrintWriter output, String packageName) { - output.println("package " + packageName + ";"); - output.println(); - output.println("import java.util.*;"); - output.println(); - output.println("public final class StaticGLInfo"); - output.println("{"); + public void emitJavaCode(PrintWriter output, String packageName) { + output.println("package " + packageName + ";"); + output.println(); + output.println("import java.util.*;"); + output.println(); + output.println("public final class StaticGLInfo"); + output.println("{"); - output.println(" // maps function names to the extension string or OpenGL"); - output.println(" // specification version string to which they correspond."); - output.println(" private static HashMap funcToAssocMap;"); - output.println(); + output.println(" // maps function names to the extension string or OpenGL"); + output.println(" // specification version string to which they correspond."); + output.println(" private static HashMap funcToAssocMap;"); + output.println(); - output.println(" /**"); - output.println(" * Returns the OpenGL extension string or GL_VERSION string with which the"); - output.println(" * given function is associated.

"); - output.println(" *"); - output.println(" * If the"); - output.println(" * function is part of the OpenGL core, the returned value will be"); - output.println(" * GL_VERSION_XXX where XXX represents the OpenGL version of which the"); - output.println(" * function is a member (XXX will be of the form \"A\" or \"A_B\" or \"A_B_C\";"); - output.println(" * e.g., GL_VERSION_1_2_1 for OpenGL version 1.2.1)."); - output.println(" *"); - output.println(" * If the function is an extension function, the returned value will the"); - output.println(" * OpenGL extension string for the extension to which the function"); - output.println(" * corresponds. For example, if glLoadTransposeMatrixfARB is the argument,"); - output.println(" * GL_ARB_transpose_matrix will be the value returned."); - output.println(" * Please see http://oss.sgi.com/projects/ogl-sample/registry/index.html for"); - output.println(" * a list of extension names and the functions they expose."); - output.println(" *"); - output.println(" * If the function specified is not part of any known OpenGL core version or"); - output.println(" * extension, then NULL will be returned."); - output.println(" */"); - 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(" for(int i = 0; null==mappedName && i < funcNamePermNum; i++) {"); - output.println(" String tmp = com.jogamp.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutation(glFunctionName, i);"); - output.println(" try {"); - output.println(" mappedName = (String)funcToAssocMap.get(tmp);"); - output.println(" } catch (Exception e) { }"); - output.println(" }"); - output.println(" return mappedName;"); - output.println(" }"); - output.println(); + output.println(" /**"); + output.println(" * Returns the OpenGL extension string or GL_VERSION string with which the"); + output.println(" * given function is associated.

"); + output.println(" *"); + output.println(" * If the"); + output.println(" * function is part of the OpenGL core, the returned value will be"); + output.println(" * GL_VERSION_XXX where XXX represents the OpenGL version of which the"); + output.println(" * function is a member (XXX will be of the form \"A\" or \"A_B\" or \"A_B_C\";"); + output.println(" * e.g., GL_VERSION_1_2_1 for OpenGL version 1.2.1)."); + output.println(" *"); + output.println(" * If the function is an extension function, the returned value will the"); + output.println(" * OpenGL extension string for the extension to which the function"); + output.println(" * corresponds. For example, if glLoadTransposeMatrixfARB is the argument,"); + output.println(" * GL_ARB_transpose_matrix will be the value returned."); + output.println(" * Please see http://oss.sgi.com/projects/ogl-sample/registry/index.html for"); + output.println(" * a list of extension names and the functions they expose."); + output.println(" *"); + output.println(" * If the function specified is not part of any known OpenGL core version or"); + output.println(" * extension, then NULL will be returned."); + output.println(" */"); + 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(" for(int i = 0; null==mappedName && i < funcNamePermNum; i++) {"); + output.println(" String tmp = com.jogamp.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutation(glFunctionName, i);"); + output.println(" try {"); + output.println(" mappedName = (String)funcToAssocMap.get(tmp);"); + output.println(" } catch (Exception e) { }"); + output.println(" }"); + output.println(" return mappedName;"); + output.println(" }"); + output.println(); - output.println(" static"); - output.println(" {"); + output.println(" static"); + output.println(" {"); - // Compute max capacity - int maxCapacity = 0; - for (String name : declarationToExtensionMap.keySet()) { - if (!name.startsWith("GL")) { - ++maxCapacity; - } - } + // Compute max capacity + int maxCapacity = 0; + for (String name : declarationToExtensionMap.keySet()) { + if (!name.startsWith("GL")) { + ++maxCapacity; + } + } - output.println(" funcToAssocMap = new HashMap(" + maxCapacity + "); // approximate max capacity"); - output.println(" String group;"); - ArrayList sets = new ArrayList(extensionToDeclarationMap.keySet()); - Collections.sort(sets); - for (String groupName : sets) { - Set funcs = extensionToDeclarationMap.get(groupName); - List l = new ArrayList(); - l.addAll(funcs); - Collections.sort(l); - Iterator funcIter = l.iterator(); - boolean printedHeader = false; - while (funcIter.hasNext()) { - String funcName = funcIter.next(); - if (!funcName.startsWith("GL")) { - if (!printedHeader) { - output.println(); - output.println(" //----------------------------------------------------------------"); - output.println(" // " + groupName); - output.println(" //----------------------------------------------------------------"); - output.println(" group = \"" + groupName + "\";"); - printedHeader = true; - } + output.println(" funcToAssocMap = new HashMap(" + maxCapacity + "); // approximate max capacity"); + output.println(" String group;"); + ArrayList sets = new ArrayList(extensionToDeclarationMap.keySet()); + Collections.sort(sets); + for (String groupName : sets) { + Set funcs = extensionToDeclarationMap.get(groupName); + List l = new ArrayList(); + l.addAll(funcs); + Collections.sort(l); + Iterator funcIter = l.iterator(); + boolean printedHeader = false; + while (funcIter.hasNext()) { + String funcName = funcIter.next(); + if (!funcName.startsWith("GL")) { + if (!printedHeader) { + output.println(); + output.println(" //----------------------------------------------------------------"); + output.println(" // " + groupName); + output.println(" //----------------------------------------------------------------"); + output.println(" group = \"" + groupName + "\";"); + printedHeader = true; + } - output.println(" funcToAssocMap.put(\"" + funcName + "\", group);"); + output.println(" funcToAssocMap.put(\"" + funcName + "\", group);"); + } + } } - } + output.println(" }"); + output.println("} // end class StaticGLInfo"); } - output.println(" }"); - output.println("} // end class StaticGLInfo"); - } - //---------------------------------------------------------------------- - // Internals only below this point - // - - protected void addAssociation(String identifier, String association) { - declarationToExtensionMap.put(identifier, association); - Set identifiers = extensionToDeclarationMap.get(association); - if (identifiers == null) { - identifiers = new HashSet(); - extensionToDeclarationMap.put(association, identifiers); + //---------------------------------------------------------------------- + // Internals only below this point + // + protected void addAssociation(String identifier, String association) { + declarationToExtensionMap.put(identifier, association); + Set identifiers = extensionToDeclarationMap.get(association); + if (identifiers == null) { + identifiers = new HashSet(); + extensionToDeclarationMap.put(association, identifiers); + } + identifiers.add(identifier); } - identifiers.add(identifier); - } } diff --git a/src/java/com/sun/gluegen/opengl/GLConfiguration.java b/src/java/com/sun/gluegen/opengl/GLConfiguration.java index 6d08a10a2..d712e902d 100755 --- a/src/java/com/sun/gluegen/opengl/GLConfiguration.java +++ b/src/java/com/sun/gluegen/opengl/GLConfiguration.java @@ -36,7 +36,6 @@ * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ - package com.sun.gluegen.opengl; import java.io.*; @@ -47,30 +46,33 @@ import com.sun.gluegen.procaddress.*; import com.jogamp.gluegen.runtime.opengl.GLExtensionNames; public class GLConfiguration extends ProcAddressConfiguration { - // The following data members support ignoring an entire extension at a time - private List glHeaders = new ArrayList(); - private Set ignoredExtensions = new HashSet(); - private Set extensionsRenamedIntoCore = new HashSet(); - private BuildStaticGLInfo glInfo; - // Maps function names to the kind of buffer object it deals with - private Map bufferObjectKinds = new HashMap(); - private GLEmitter emitter; - private Set dropUniqVendorExtensions = new HashSet(); - // This directive is off by default but can help automatically - // indicate which extensions have been folded into the core OpenGL - // namespace, and if not, then why not - private boolean autoUnifyExtensions=false; - private boolean allowNonGLExtensions=false; - - public GLConfiguration(GLEmitter emitter) { - super(); - this.emitter = emitter; - try { - setProcAddressNameExpr("PFN $UPPERCASE({0}) PROC"); - } catch (NoSuchElementException e) { - throw new RuntimeException("Error configuring ProcAddressNameExpr", e); + + // The following data members support ignoring an entire extension at a time + private List glHeaders = new ArrayList(); + private Set ignoredExtensions = new HashSet(); + private Set extensionsRenamedIntoCore = new HashSet(); + private BuildStaticGLInfo glInfo; + + // Maps function names to the kind of buffer object it deals with + private Map bufferObjectKinds = new HashMap(); + private GLEmitter emitter; + private Set dropUniqVendorExtensions = new HashSet(); + + // This directive is off by default but can help automatically + // indicate which extensions have been folded into the core OpenGL + // namespace, and if not, then why not + private boolean autoUnifyExtensions = false; + private boolean allowNonGLExtensions = false; + + public GLConfiguration(GLEmitter emitter) { + super(); + this.emitter = emitter; + try { + setProcAddressNameExpr("PFN $UPPERCASE({0}) PROC"); + } catch (NoSuchElementException e) { + throw new RuntimeException("Error configuring ProcAddressNameExpr", e); + } } - } @Override protected void dispatch(String cmd, StringTokenizer tok, File file, String filename, int lineNo) throws IOException { @@ -97,199 +99,198 @@ public class GLConfiguration extends ProcAddressConfiguration { } } - protected void readBufferObjectKind(StringTokenizer tok, String filename, int lineNo) { - try { - String kindString = tok.nextToken(); - GLEmitter.BufferObjectKind kind = null; - String target = tok.nextToken(); - if (kindString.equalsIgnoreCase("UnpackPixel")) { - kind = GLEmitter.BufferObjectKind.UNPACK_PIXEL; - } else if (kindString.equalsIgnoreCase("PackPixel")) { - kind = GLEmitter.BufferObjectKind.PACK_PIXEL; - } else if (kindString.equalsIgnoreCase("Array")) { - kind = GLEmitter.BufferObjectKind.ARRAY; - } else if (kindString.equalsIgnoreCase("Element")) { - kind = GLEmitter.BufferObjectKind.ELEMENT; - } else { - throw new RuntimeException("Error parsing \"BufferObjectKind\" command at line " + lineNo + - " in file \"" + filename + "\": illegal BufferObjectKind \"" + - kindString + "\", expected one of UnpackPixel, PackPixel, Array, or Element"); - } - - bufferObjectKinds.put(target, kind); - } catch (NoSuchElementException e) { - throw new RuntimeException("Error parsing \"BufferObjectKind\" command at line " + lineNo + - " in file \"" + filename + "\"", e); - } - } - - /** Overrides javaPrologueForMethod in superclass and - automatically generates prologue code for functions associated - with buffer objects. */ - @Override - public List javaPrologueForMethod(MethodBinding binding, boolean forImplementingMethodCall, boolean eraseBufferAndArrayTypes) { - - List res = super.javaPrologueForMethod(binding, forImplementingMethodCall, eraseBufferAndArrayTypes); - GLEmitter.BufferObjectKind kind = getBufferObjectKind(binding.getName()); - if (kind != null) { - // Need to generate appropriate prologue based on both buffer - // object kind and whether this variant of the MethodBinding - // is the one accepting a "long" as argument - // - // NOTE we MUST NOT mutate the array returned from the super - // call! - ArrayList res2 = new ArrayList(); - if (res != null) { - res2.addAll(res); - } - res = res2; - - String prologue = "check"; - - if (kind == GLEmitter.BufferObjectKind.UNPACK_PIXEL) { - prologue = prologue + "UnpackPBO"; - } else if (kind == GLEmitter.BufferObjectKind.PACK_PIXEL) { - prologue = prologue + "PackPBO"; - } else if (kind == GLEmitter.BufferObjectKind.ARRAY) { - prologue = prologue + "ArrayVBO"; - } else if (kind == GLEmitter.BufferObjectKind.ELEMENT) { - prologue = prologue + "ElementVBO"; - } else { - throw new RuntimeException("Unknown BufferObjectKind " + kind); - } - - if (emitter.isBufferObjectMethodBinding(binding)) { - prologue = prologue + "Enabled"; - } else { - prologue = prologue + "Disabled"; - } - - prologue = prologue + "(true);"; - - res.add(0, prologue); - - // Must also filter out bogus rangeCheck directives for VBO/PBO - // variants - if (emitter.isBufferObjectMethodBinding(binding)) { - for (Iterator iter = res.iterator(); iter.hasNext(); ) { - String line = iter.next(); - if (line.indexOf("Buffers.rangeCheck") >= 0) { - iter.remove(); - } + protected void readBufferObjectKind(StringTokenizer tok, String filename, int lineNo) { + try { + String kindString = tok.nextToken(); + GLEmitter.BufferObjectKind kind = null; + String target = tok.nextToken(); + if (kindString.equalsIgnoreCase("UnpackPixel")) { + kind = GLEmitter.BufferObjectKind.UNPACK_PIXEL; + } else if (kindString.equalsIgnoreCase("PackPixel")) { + kind = GLEmitter.BufferObjectKind.PACK_PIXEL; + } else if (kindString.equalsIgnoreCase("Array")) { + kind = GLEmitter.BufferObjectKind.ARRAY; + } else if (kindString.equalsIgnoreCase("Element")) { + kind = GLEmitter.BufferObjectKind.ELEMENT; + } else { + throw new RuntimeException("Error parsing \"BufferObjectKind\" command at line " + lineNo + + " in file \"" + filename + "\": illegal BufferObjectKind \"" + + kindString + "\", expected one of UnpackPixel, PackPixel, Array, or Element"); + } + + bufferObjectKinds.put(target, kind); + } catch (NoSuchElementException e) { + throw new RuntimeException("Error parsing \"BufferObjectKind\" command at line " + lineNo + + " in file \"" + filename + "\"", e); } - } } - return res; - } + /** Overrides javaPrologueForMethod in superclass and + automatically generates prologue code for functions associated + with buffer objects. */ + @Override + public List javaPrologueForMethod(MethodBinding binding, boolean forImplementingMethodCall, boolean eraseBufferAndArrayTypes) { + + List res = super.javaPrologueForMethod(binding, forImplementingMethodCall, eraseBufferAndArrayTypes); + GLEmitter.BufferObjectKind kind = getBufferObjectKind(binding.getName()); + if (kind != null) { + // Need to generate appropriate prologue based on both buffer + // object kind and whether this variant of the MethodBinding + // is the one accepting a "long" as argument + // + // NOTE we MUST NOT mutate the array returned from the super + // call! + ArrayList res2 = new ArrayList(); + if (res != null) { + res2.addAll(res); + } + res = res2; + + String prologue = "check"; + + if (kind == GLEmitter.BufferObjectKind.UNPACK_PIXEL) { + prologue = prologue + "UnpackPBO"; + } else if (kind == GLEmitter.BufferObjectKind.PACK_PIXEL) { + prologue = prologue + "PackPBO"; + } else if (kind == GLEmitter.BufferObjectKind.ARRAY) { + prologue = prologue + "ArrayVBO"; + } else if (kind == GLEmitter.BufferObjectKind.ELEMENT) { + prologue = prologue + "ElementVBO"; + } else { + throw new RuntimeException("Unknown BufferObjectKind " + kind); + } + + if (emitter.isBufferObjectMethodBinding(binding)) { + prologue = prologue + "Enabled"; + } else { + prologue = prologue + "Disabled"; + } + + prologue = prologue + "(true);"; - @Override - public void dumpIgnores() { - System.err.println("GL Ignored extensions: "); - for (String str : ignoredExtensions) { - System.err.println("\t"+str); + res.add(0, prologue); + + // Must also filter out bogus rangeCheck directives for VBO/PBO + // variants + if (emitter.isBufferObjectMethodBinding(binding)) { + for (Iterator iter = res.iterator(); iter.hasNext();) { + String line = iter.next(); + if (line.indexOf("Buffers.rangeCheck") >= 0) { + iter.remove(); + } + } + } + } + + return res; + } + + @Override + public void dumpIgnores() { + System.err.println("GL Ignored extensions: "); + for (String str : ignoredExtensions) { + System.err.println("\t" + str); + } + super.dumpIgnores(); } - super.dumpIgnores(); - } - - protected boolean shouldIgnoreExtension(String symbol, boolean criteria) { - if (criteria && glInfo != null) { - String extension = glInfo.getExtension(symbol); - if (extension != null && - ignoredExtensions.contains(extension)) { - return true; - } - boolean isGLEnum = GLExtensionNames.isGLEnumeration(symbol); - boolean isGLFunc = GLExtensionNames.isGLFunction(symbol); - if(isGLFunc || isGLEnum) { - if(GLExtensionNames.isExtensionVEN(symbol, isGLFunc)) { - String extSuffix = GLExtensionNames.getExtensionSuffix(symbol, isGLFunc); - if( getDropUniqVendorExtensions(extSuffix) ) { - if(DEBUG_IGNORES) { - System.err.println("Ignore UniqVendorEXT: "+symbol+", vendor "+extSuffix); + + protected boolean shouldIgnoreExtension(String symbol, boolean criteria) { + if (criteria && glInfo != null) { + String extension = glInfo.getExtension(symbol); + if (extension != null + && ignoredExtensions.contains(extension)) { + return true; + } + boolean isGLEnum = GLExtensionNames.isGLEnumeration(symbol); + boolean isGLFunc = GLExtensionNames.isGLFunction(symbol); + if (isGLFunc || isGLEnum) { + if (GLExtensionNames.isExtensionVEN(symbol, isGLFunc)) { + String extSuffix = GLExtensionNames.getExtensionSuffix(symbol, isGLFunc); + if (getDropUniqVendorExtensions(extSuffix)) { + if (DEBUG_IGNORES) { + System.err.println("Ignore UniqVendorEXT: " + symbol + ", vendor " + extSuffix); + } + return true; + } + } } - return true; - } } - } + return false; + } + + @Override + public boolean shouldIgnoreInInterface(String symbol) { + return shouldIgnoreInInterface(symbol, true); + } + + public boolean shouldIgnoreInInterface(String symbol, boolean checkEXT) { + return shouldIgnoreExtension(symbol, checkEXT) || super.shouldIgnoreInInterface(symbol); + } + + @Override + public boolean shouldIgnoreInImpl(String symbol) { + return shouldIgnoreInImpl(symbol, true); + } + + public boolean shouldIgnoreInImpl(String symbol, boolean checkEXT) { + return shouldIgnoreExtension(symbol, checkEXT) || super.shouldIgnoreInImpl(symbol); + } + + /** Should we automatically ignore extensions that have already been + fully subsumed into the OpenGL core namespace, and if they have + not been, indicate which definition is not already in the core? */ + public boolean getAutoUnifyExtensions() { + return autoUnifyExtensions; + } + + /** If true, accept all non encapsulated defines and functions, + * as it is mandatory for GL declarations. */ + public boolean getAllowNonGLExtensions() { + return allowNonGLExtensions; } - return false; - } - - @Override - public boolean shouldIgnoreInInterface(String symbol) { - return shouldIgnoreInInterface(symbol, true); - } - - public boolean shouldIgnoreInInterface(String symbol, boolean checkEXT) { - return shouldIgnoreExtension(symbol, checkEXT) || super.shouldIgnoreInInterface(symbol); - } - - @Override - public boolean shouldIgnoreInImpl(String symbol) { - return shouldIgnoreInImpl(symbol, true); - } - - public boolean shouldIgnoreInImpl(String symbol, boolean checkEXT) { - return shouldIgnoreExtension(symbol, checkEXT) || super.shouldIgnoreInImpl(symbol); - } - - /** Should we automatically ignore extensions that have already been - fully subsumed into the OpenGL core namespace, and if they have - not been, indicate which definition is not already in the core? */ - public boolean getAutoUnifyExtensions() { - return autoUnifyExtensions; - } - - /** If true, accept all non encapsulated defines and functions, - * as it is mandatory for GL declarations. */ - public boolean getAllowNonGLExtensions() { - return allowNonGLExtensions; - } - - - /** shall the non unified (uniq) vendor extensions be dropped ? */ - public boolean getDropUniqVendorExtensions(String extName) { - return dropUniqVendorExtensions.contains(extName); - } - - /** Returns the kind of buffer object this function deals with, or - null if none. */ - GLEmitter.BufferObjectKind getBufferObjectKind(String name) { - return bufferObjectKinds.get(name); - } - - public boolean isBufferObjectFunction(String name) { - return (getBufferObjectKind(name) != null); - } - - /** Parses any GL headers specified in the configuration file for - the purpose of being able to ignore an extension at a time. */ - public void parseGLHeaders(GlueEmitterControls controls) throws IOException { - if (!glHeaders.isEmpty()) { - glInfo = new BuildStaticGLInfo(); - for (String file : glHeaders) { - String fullPath = controls.findHeaderFile(file); - if (fullPath == null) { - throw new IOException("Unable to locate header file \"" + file + "\""); + + /** shall the non unified (uniq) vendor extensions be dropped ? */ + public boolean getDropUniqVendorExtensions(String extName) { + return dropUniqVendorExtensions.contains(extName); + } + + /** Returns the kind of buffer object this function deals with, or + null if none. */ + GLEmitter.BufferObjectKind getBufferObjectKind(String name) { + return bufferObjectKinds.get(name); + } + + public boolean isBufferObjectFunction(String name) { + return (getBufferObjectKind(name) != null); + } + + /** Parses any GL headers specified in the configuration file for + the purpose of being able to ignore an extension at a time. */ + public void parseGLHeaders(GlueEmitterControls controls) throws IOException { + if (!glHeaders.isEmpty()) { + glInfo = new BuildStaticGLInfo(); + for (String file : glHeaders) { + String fullPath = controls.findHeaderFile(file); + if (fullPath == null) { + throw new IOException("Unable to locate header file \"" + file + "\""); + } + glInfo.parse(fullPath); + } } - glInfo.parse(fullPath); - } } - } - - /** Returns the information about the association between #defines, - function symbols and the OpenGL extensions they are defined - in. */ - public BuildStaticGLInfo getGLInfo() { - return glInfo; - } - - /** Returns the OpenGL extensions that should have all of their - constant definitions and functions renamed into the core - namespace; for example, glGenFramebuffersEXT to - glGenFramebuffers and GL_FRAMEBUFFER_EXT to GL_FRAMEBUFFER. */ - public Set getExtensionsRenamedIntoCore() { - return extensionsRenamedIntoCore; - } + + /** Returns the information about the association between #defines, + function symbols and the OpenGL extensions they are defined + in. */ + public BuildStaticGLInfo getGLInfo() { + return glInfo; + } + + /** Returns the OpenGL extensions that should have all of their + constant definitions and functions renamed into the core + namespace; for example, glGenFramebuffersEXT to + glGenFramebuffers and GL_FRAMEBUFFER_EXT to GL_FRAMEBUFFER. */ + public Set getExtensionsRenamedIntoCore() { + return extensionsRenamedIntoCore; + } } diff --git a/src/java/com/sun/gluegen/opengl/GLEmitter.java b/src/java/com/sun/gluegen/opengl/GLEmitter.java index e9ae750f8..006287e02 100644 --- a/src/java/com/sun/gluegen/opengl/GLEmitter.java +++ b/src/java/com/sun/gluegen/opengl/GLEmitter.java @@ -36,11 +36,9 @@ * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ - package com.sun.gluegen.opengl; import java.io.*; -import java.text.MessageFormat; import java.util.*; import com.sun.gluegen.*; import com.sun.gluegen.cgram.types.*; @@ -53,417 +51,405 @@ import com.jogamp.gluegen.runtime.opengl.GLExtensionNames; */ public class GLEmitter extends ProcAddressEmitter { - // Keeps track of which MethodBindings were created for handling - // Buffer Object variants. Used as a Set rather than a Map. - private Map bufferObjectMethodBindings = new IdentityHashMap(); - - static class BufferObjectKind { - - private BufferObjectKind() {} - - static final BufferObjectKind UNPACK_PIXEL = new BufferObjectKind(); - static final BufferObjectKind PACK_PIXEL = new BufferObjectKind(); - static final BufferObjectKind ARRAY = new BufferObjectKind(); - static final BufferObjectKind ELEMENT = new BufferObjectKind(); - } - - @Override - public void beginEmission(GlueEmitterControls controls) throws IOException { - getGLConfig().parseGLHeaders(controls); - renameExtensionsIntoCore(); - if (getGLConfig().getAutoUnifyExtensions()) { - unifyExtensions(controls); - } - super.beginEmission(controls); - } - - protected void renameExtensionsIntoCore() { - // This method handles renaming of entire extensions into the - // OpenGL core namespace. For example, it is used to move certain - // OpenGL ES (OES) extensions into the core namespace which are - // already in the core namespace in desktop OpenGL. It builds upon - // renaming mechanisms that are built elsewhere. - - GLConfiguration config = getGLConfig(); - Set extensionsRenamedIntoCore = config.getExtensionsRenamedIntoCore(); - BuildStaticGLInfo glInfo = config.getGLInfo(); - if(null==glInfo) { - if(extensionsRenamedIntoCore.size()>0) { - throw new RuntimeException("ExtensionRenamedIntoCore (num: "+extensionsRenamedIntoCore.size()+"), but no GLHeader"); + // Keeps track of which MethodBindings were created for handling + // Buffer Object variants. Used as a Set rather than a Map. + private Map bufferObjectMethodBindings = new IdentityHashMap(); + + enum BufferObjectKind { UNPACK_PIXEL, PACK_PIXEL, ARRAY, ELEMENT} + + @Override + public void beginEmission(GlueEmitterControls controls) throws IOException { + getGLConfig().parseGLHeaders(controls); + renameExtensionsIntoCore(); + if (getGLConfig().getAutoUnifyExtensions()) { + unifyExtensions(controls); } - return; + super.beginEmission(controls); } - for (String extension : extensionsRenamedIntoCore) { - Set declarations = glInfo.getDeclarations(extension); - if (declarations != null) { - for (Iterator i2 = declarations.iterator(); i2.hasNext(); ) { - String decl = (String) i2.next(); - boolean isGLFunction = GLExtensionNames.isGLFunction(decl); - boolean isGLEnumeration = false; - if (!isGLFunction) { - isGLEnumeration = GLExtensionNames.isGLEnumeration(decl); - } - if (isGLFunction || isGLEnumeration) { - String renamed = GLExtensionNames.normalize(decl, isGLFunction); - if(!renamed.equals(decl)) { - config.addJavaSymbolRename(decl, renamed); + + protected void renameExtensionsIntoCore() { + // This method handles renaming of entire extensions into the + // OpenGL core namespace. For example, it is used to move certain + // OpenGL ES (OES) extensions into the core namespace which are + // already in the core namespace in desktop OpenGL. It builds upon + // renaming mechanisms that are built elsewhere. + + GLConfiguration config = getGLConfig(); + Set extensionsRenamedIntoCore = config.getExtensionsRenamedIntoCore(); + BuildStaticGLInfo glInfo = config.getGLInfo(); + if (null == glInfo) { + if (extensionsRenamedIntoCore.size() > 0) { + throw new RuntimeException("ExtensionRenamedIntoCore (num: " + extensionsRenamedIntoCore.size() + "), but no GLHeader"); + } + return; + } + for (String extension : extensionsRenamedIntoCore) { + Set declarations = glInfo.getDeclarations(extension); + if (declarations != null) { + for (Iterator iterator = declarations.iterator(); iterator.hasNext();) { + String decl = iterator.next(); + boolean isGLFunction = GLExtensionNames.isGLFunction(decl); + boolean isGLEnumeration = false; + if (!isGLFunction) { + isGLEnumeration = GLExtensionNames.isGLEnumeration(decl); + } + if (isGLFunction || isGLEnumeration) { + String renamed = GLExtensionNames.normalize(decl, isGLFunction); + if (!renamed.equals(decl)) { + config.addJavaSymbolRename(decl, renamed); + } + } + } } - } } - } - } - } - - class ExtensionUnifier implements SymbolFilter { - private List constants; - private List functions; - - public void filterSymbols(List constants, - List functions) { - this.constants = constants; - this.functions = functions; - doWork(); - } - - public List getConstants() { - return constants; - } - - public List getFunctions() { - return functions; - } - - private void doWork() { - BuildStaticGLInfo glInfo = getGLConfig().getGLInfo(); - if (glInfo == null) { - return; - } - // Try to retain a "good" ordering for these symbols - Map constantMap = new LinkedHashMap(); - Map functionMap = new LinkedHashMap(); - for (Iterator iter = constants.iterator(); iter.hasNext(); ) { - ConstantDefinition def = (ConstantDefinition) iter.next(); - constantMap.put(def.getName(), def); - } - for (Iterator iter = functions.iterator(); iter.hasNext(); ) { - FunctionSymbol sym = (FunctionSymbol) iter.next(); - functionMap.put(sym.getName(), sym); - } - // Go through all of the declared extensions. - // For each extension, look at its #define and function symbols. - // If we find all of the extension's symbols in the core API under - // non-ARB (or whatever is the suffix) names, then remove this extension - // from the public API. If it turns out that we are running on hardware - // that doesn't support the core version of these APIs, the runtime - // will take care of looking up the extension version of these entry - // points. - Set extensionNames = glInfo.getExtensions(); - for (Iterator iter1 = extensionNames.iterator(); iter1.hasNext(); ) { - String extension = (String) iter1.next(); - Set declarations = glInfo.getDeclarations(extension); - boolean isExtension = true; - boolean shouldUnify = true; - String cause = null; - for (Iterator iter2 = declarations.iterator(); iter2.hasNext(); ) { - String decl = (String) iter2.next(); - boolean isFunc = !decl.startsWith("GL_"); - if (!GLExtensionNames.isExtension(decl, isFunc)) { - isExtension = false; - break; - } - // See whether we're emitting glue code for this - // entry point or definition at all - if (isFunc) { - if (!functionMap.containsKey(decl)) { - isExtension = false; - break; - } - } else { - if (!constantMap.containsKey(decl)) { - isExtension = false; - break; - } - } - cause = decl; - String unifiedName = GLExtensionNames.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 - // headers that actually contain the core entry - // point. Think of the case where we are parsing the - // GLES2 gl2.h, which contains certain desktop - // OpenGL extensions that have been moved into the - // core, but later generating the implementing glue - // code (not the interface) for the desktop gl.h / - // glext.h. - shouldUnify = (glInfo.getExtension(unifiedName) != null); - // if (isFunc) { - // shouldUnify = functionMap.containsKey(unifiedName); - // } else { - // shouldUnify = constantMap.containsKey(unifiedName); - // } - if (!shouldUnify) { - break; - } - } - if (isExtension) { - if (shouldUnify) { - for (Iterator iter2 = declarations.iterator(); iter2.hasNext(); ) { - String decl = (String) iter2.next(); - boolean isFunc = !decl.startsWith("GL_"); - if (isFunc) { - functionMap.remove(decl); - } else { - constantMap.remove(decl); - } - } - System.err.println("INFO: unified extension " + extension + " into core API"); - } else { - System.err.println("INFO: didn't unify extension " + extension + " into core API because of " + cause); - } - } - } - constants = new ArrayList(); - for (Iterator iter = constantMap.keySet().iterator(); iter.hasNext(); ) { - constants.add(constantMap.get(iter.next())); - } - functions = new ArrayList(); - for (Iterator iter = functionMap.keySet().iterator(); iter.hasNext(); ) { - functions.add(functionMap.get(iter.next())); - } - } - } - - private void unifyExtensions(GlueEmitterControls controls) { - controls.runSymbolFilter(new ExtensionUnifier()); - } - - protected JavaConfiguration createConfig() { - return new GLConfiguration(this); - } - - /** In order to implement Buffer Object variants of certain - functions we generate another MethodBinding which maps the void* - argument to a Java long. The generation of emitters then takes - place as usual. We do however need to keep track of the modified - MethodBinding object so that we can also modify the emitters - later to inform them that their argument has changed. We might - want to push this functionality down into the MethodBinding - (i.e., mutators for argument names). We also would need to - inform the CMethodBindingEmitter that it is overloaded in this - case (though we default to true currently). */ - protected List expandMethodBinding(MethodBinding binding) { - List bindings = super.expandMethodBinding(binding); - - if (!getGLConfig().isBufferObjectFunction(binding.getName())) { - return bindings; } - List newBindings = new ArrayList(); - newBindings.addAll(bindings); - - // Need to expand each one of the generated bindings to take a - // Java long instead of a Buffer for each void* argument - for (Iterator iter = bindings.iterator(); iter.hasNext(); ) { - MethodBinding cur = (MethodBinding) iter.next(); - - // Some of these routines (glBitmap) take strongly-typed - // primitive pointers as arguments which are expanded into - // non-void* arguments - // This test (rather than !signatureUsesNIO) is used to catch - // more unexpected situations - if (cur.signatureUsesJavaPrimitiveArrays()) { - continue; - } - - MethodBinding result = cur; - for (int i = 0; i < cur.getNumArguments(); i++) { - if (cur.getJavaArgumentType(i).isNIOBuffer()) { - result = result.replaceJavaArgumentType(i, JavaType.createForClass(Long.TYPE)); + class ExtensionUnifier implements SymbolFilter { + + private List constants; + private List functions; + + public void filterSymbols(List constants, + List functions) { + this.constants = constants; + this.functions = functions; + doWork(); } - } - if (result == cur) { - throw new RuntimeException("Error: didn't find any void* arguments for BufferObject function " + - binding.getName()); - } + public List getConstants() { + return constants; + } - newBindings.add(result); - // Now need to flag this MethodBinding so that we generate the - // correct flags in the emitters later - bufferObjectMethodBindings.put(result, result); + public List getFunctions() { + return functions; + } + + private void doWork() { + BuildStaticGLInfo glInfo = getGLConfig().getGLInfo(); + if (glInfo == null) { + return; + } + // Try to retain a "good" ordering for these symbols + Map constantMap = new LinkedHashMap(); + for (ConstantDefinition def : constants) { + constantMap.put(def.getName(), def); + } + Map functionMap = new LinkedHashMap(); + for (FunctionSymbol sym : functions) { + functionMap.put(sym.getName(), sym); + } + + // Go through all of the declared extensions. + // For each extension, look at its #define and function symbols. + // If we find all of the extension's symbols in the core API under + // non-ARB (or whatever is the suffix) names, then remove this extension + // from the public API. If it turns out that we are running on hardware + // that doesn't support the core version of these APIs, the runtime + // will take care of looking up the extension version of these entry + // points. + Set extensionNames = glInfo.getExtensions(); + + for (String extension : extensionNames) { + Set declarations = glInfo.getDeclarations(extension); + boolean isExtension = true; + boolean shouldUnify = true; + String cause = null; + for (String decl : declarations) { + boolean isFunc = !decl.startsWith("GL_"); + if (!GLExtensionNames.isExtension(decl, isFunc)) { + isExtension = false; + break; + } + // See whether we're emitting glue code for this + // entry point or definition at all + if (isFunc) { + if (!functionMap.containsKey(decl)) { + isExtension = false; + break; + } + } else { + if (!constantMap.containsKey(decl)) { + isExtension = false; + break; + } + } + cause = decl; + String unifiedName = GLExtensionNames.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 + // headers that actually contain the core entry + // point. Think of the case where we are parsing the + // GLES2 gl2.h, which contains certain desktop + // OpenGL extensions that have been moved into the + // core, but later generating the implementing glue + // code (not the interface) for the desktop gl.h / + // glext.h. + shouldUnify = (glInfo.getExtension(unifiedName) != null); + // if (isFunc) { + // shouldUnify = functionMap.containsKey(unifiedName); + // } else { + // shouldUnify = constantMap.containsKey(unifiedName); + // } + if (!shouldUnify) { + break; + } + } + if (isExtension) { + if (shouldUnify) { + for (String decl : declarations) { + boolean isFunc = !decl.startsWith("GL_"); + if (isFunc) { + functionMap.remove(decl); + } else { + constantMap.remove(decl); + } + } + System.err.println("INFO: unified extension " + extension + " into core API"); + } else { + System.err.println("INFO: didn't unify extension " + extension + " into core API because of " + cause); + } + } + } + constants = new ArrayList(constantMap.values()); + functions = new ArrayList(functionMap.values()); + } } - return newBindings; - } + private void unifyExtensions(GlueEmitterControls controls) { + controls.runSymbolFilter(new ExtensionUnifier()); + } - protected boolean needsModifiedEmitters(FunctionSymbol sym) { - if ((!needsProcAddressWrapper(sym) && !needsBufferObjectVariant(sym)) || - getConfig().isUnimplemented(sym.getName())) { - return false; + @Override + protected JavaConfiguration createConfig() { + return new GLConfiguration(this); } - return true; - } - - public boolean isBufferObjectMethodBinding(MethodBinding binding) { - return bufferObjectMethodBindings.containsKey(binding); - } - - public void emitDefine(ConstantDefinition def, String optionalComment) throws Exception { - BuildStaticGLInfo glInfo = getGLConfig().getGLInfo(); - if(null==glInfo) { - throw new Exception("No GLInfo for: "+def); - } - String symbolRenamed = def.getName(); - StringBuffer newComment = new StringBuffer(); - newComment.append("Part of "); - if(0==addExtensionsOfSymbols2Buffer(newComment, ", ", symbolRenamed, def.getAliasedNames())) { - if(def.isEnum()) { - String enumName = def.getEnumName(); - if(null!=enumName) { - newComment.append(enumName); - } else { - newComment.append("CORE ENUM"); - } - } else { - if(getGLConfig().getAllowNonGLExtensions()) { - newComment.append("CORE DEF"); - } else { - // Note: All GL defines must be contained within an extension marker ! - // #ifndef GL_EXT_lala - // #define GL_EXT_lala 1 - // ... - // #endif - if(JavaConfiguration.DEBUG_IGNORES) { - StringBuffer sb = new StringBuffer(); - JavaEmitter.addStrings2Buffer(sb, ", ", symbolRenamed, def.getAliasedNames()); - System.err.println("Dropping marker: "+sb.toString()); - } - return; - } + /** In order to implement Buffer Object variants of certain + functions we generate another MethodBinding which maps the void* + argument to a Java long. The generation of emitters then takes + place as usual. We do however need to keep track of the modified + MethodBinding object so that we can also modify the emitters + later to inform them that their argument has changed. We might + want to push this functionality down into the MethodBinding + (i.e., mutators for argument names). We also would need to + inform the CMethodBindingEmitter that it is overloaded in this + case (though we default to true currently). */ + @Override + protected List expandMethodBinding(MethodBinding binding) { + List bindings = super.expandMethodBinding(binding); + + if (!getGLConfig().isBufferObjectFunction(binding.getName())) { + return bindings; } - } - newComment.append(""); - if(null!=optionalComment) { - newComment.append("
"); - newComment.append(optionalComment); - } + List newBindings = new ArrayList(bindings); - super.emitDefine(def, newComment.toString()); - } + // Need to expand each one of the generated bindings to take a + // Java long instead of a Buffer for each void* argument - public int addExtensionsOfSymbols2Buffer(StringBuffer buf, String sep, String first, Collection col) { - BuildStaticGLInfo glInfo = getGLConfig().getGLInfo(); - if(null==glInfo) { - throw new RuntimeException("No GLInfo for: "+first); - } - int num = 0; - if(null==buf) buf=new StringBuffer(); - String extensionName; - - Iterator iter=col.iterator(); - if(null!=first) { - extensionName = glInfo.getExtension(first); - if(null!=extensionName) { - buf.append(extensionName); - if( iter.hasNext() ) { - buf.append(sep); + for (MethodBinding cur : bindings) { + + // Some of these routines (glBitmap) take strongly-typed + // primitive pointers as arguments which are expanded into + // non-void* arguments + // This test (rather than !signatureUsesNIO) is used to catch + // more unexpected situations + if (cur.signatureUsesJavaPrimitiveArrays()) { + continue; + } + + MethodBinding result = cur; + for (int i = 0; i < cur.getNumArguments(); i++) { + if (cur.getJavaArgumentType(i).isNIOBuffer()) { + result = result.replaceJavaArgumentType(i, JavaType.createForClass(Long.TYPE)); + } } - num++; + + if (result == cur) { + throw new RuntimeException("Error: didn't find any void* arguments for BufferObject function " + + binding.getName()); + } + + newBindings.add(result); + // Now need to flag this MethodBinding so that we generate the + // correct flags in the emitters later + bufferObjectMethodBindings.put(result, result); } + + return newBindings; + } + + @Override + protected boolean needsModifiedEmitters(FunctionSymbol sym) { + if ((!needsProcAddressWrapper(sym) && !needsBufferObjectVariant(sym)) + || getConfig().isUnimplemented(sym.getName())) { + return false; + } + + return true; + } + + public boolean isBufferObjectMethodBinding(MethodBinding binding) { + return bufferObjectMethodBindings.containsKey(binding); } - while( iter.hasNext() ) { - extensionName = glInfo.getExtension((String)iter.next()); - if(null!=extensionName) { - buf.append(extensionName); - if( iter.hasNext() ) { - buf.append(sep); + + @Override + public void emitDefine(ConstantDefinition def, String optionalComment) throws Exception { + BuildStaticGLInfo glInfo = getGLConfig().getGLInfo(); + if (null == glInfo) { + throw new Exception("No GLInfo for: " + def); + } + String symbolRenamed = def.getName(); + StringBuilder newComment = new StringBuilder(); + newComment.append("Part of "); + if (0 == addExtensionsOfSymbols2Buffer(newComment, ", ", symbolRenamed, def.getAliasedNames())) { + if (def.isEnum()) { + String enumName = def.getEnumName(); + if (null != enumName) { + newComment.append(enumName); + } else { + newComment.append("CORE ENUM"); + } + } else { + if (getGLConfig().getAllowNonGLExtensions()) { + newComment.append("CORE DEF"); + } else { + // Note: All GL defines must be contained within an extension marker ! + // #ifndef GL_EXT_lala + // #define GL_EXT_lala 1 + // ... + // #endif + if (JavaConfiguration.DEBUG_IGNORES) { + StringBuilder sb = new StringBuilder(); + JavaEmitter.addStrings2Buffer(sb, ", ", symbolRenamed, def.getAliasedNames()); + System.err.println("Dropping marker: " + sb.toString()); + } + return; + } } - num++; } + newComment.append(""); + + if (null != optionalComment) { + newComment.append("
"); + newComment.append(optionalComment); + } + + super.emitDefine(def, newComment.toString()); } - return num; - } - //---------------------------------------------------------------------- - // Internals only below this point - // + public int addExtensionsOfSymbols2Buffer(StringBuilder buf, String sep, String first, Collection col) { + BuildStaticGLInfo glInfo = getGLConfig().getGLInfo(); + if (null == glInfo) { + throw new RuntimeException("No GLInfo for: " + first); + } + int num = 0; + if (null == buf) { + buf = new StringBuilder(); + } + String extensionName; + + Iterator iter = col.iterator(); + if (null != first) { + extensionName = glInfo.getExtension(first); + if (null != extensionName) { + buf.append(extensionName); + if (iter.hasNext()) { + buf.append(sep); + } + num++; + } + } + while (iter.hasNext()) { + extensionName = glInfo.getExtension(iter.next()); + if (null != extensionName) { + buf.append(extensionName); + if (iter.hasNext()) { + buf.append(sep); + } + num++; + } + } + return num; + } - protected void generateModifiedEmitters(JavaMethodBindingEmitter baseJavaEmitter, List emitters) { - List superEmitters = new ArrayList(); - super.generateModifiedEmitters(baseJavaEmitter, superEmitters); + //---------------------------------------------------------------------- + // Internals only below this point + // + @Override + protected void generateModifiedEmitters(JavaMethodBindingEmitter baseJavaEmitter, List emitters) { + List superEmitters = new ArrayList(); + super.generateModifiedEmitters(baseJavaEmitter, superEmitters); - // See whether this is one of the Buffer Object variants - boolean bufferObjectVariant = bufferObjectMethodBindings.containsKey(baseJavaEmitter.getBinding()); + // See whether this is one of the Buffer Object variants + boolean bufferObjectVariant = bufferObjectMethodBindings.containsKey(baseJavaEmitter.getBinding()); - for (Iterator iter = superEmitters.iterator(); iter.hasNext(); ) { - JavaMethodBindingEmitter emitter = (JavaMethodBindingEmitter) iter.next(); - if (emitter instanceof ProcAddressJavaMethodBindingEmitter) { - emitter = new GLJavaMethodBindingEmitter((ProcAddressJavaMethodBindingEmitter) emitter, this, bufferObjectVariant); + for (FunctionEmitter emitter : superEmitters) { + if (emitter instanceof ProcAddressJavaMethodBindingEmitter) { + emitter = new GLJavaMethodBindingEmitter((ProcAddressJavaMethodBindingEmitter) emitter, this, bufferObjectVariant); + } + emitters.add(emitter); } - emitters.add(emitter); } - } - - protected boolean needsBufferObjectVariant(FunctionSymbol sym) { - return getGLConfig().isBufferObjectFunction(sym.getName()); - } - - protected GLConfiguration getGLConfig() { - return (GLConfiguration) getConfig(); - } - - protected void endProcAddressTable() throws Exception - { - PrintWriter w = tableWriter; - - w.println(" /**"); - w.println(" * This is a convenience method to get (by name) the native function"); - w.println(" * pointer for a given function. It lets you avoid having to"); - w.println(" * manually compute the "" + PROCADDRESS_VAR_PREFIX + " + "); - w.println(" * <functionName>" member variable name and look it up via"); - w.println(" * reflection; it also will throw an exception if you try to get the"); - w.println(" * address of an unknown function, or one that is statically linked"); - w.println(" * and therefore does not have a function pointer in this table."); - w.println(" *"); - w.println(" * @throws RuntimeException if the function pointer was not found in"); - w.println(" * this table, either because the function was unknown or because"); - w.println(" * it was statically linked."); - w.println(" */"); - w.println(" public long getAddressFor(String functionNameUsr) {"); - w.println(" String functionNameBase = com.jogamp.gluegen.runtime.opengl.GLExtensionNames.normalizeVEN(com.jogamp.gluegen.runtime.opengl.GLExtensionNames.normalizeARB(functionNameUsr, true), true);"); - w.println(" String addressFieldNameBase = " + getProcAddressConfig().gluegenRuntimePackage() + ".ProcAddressHelper.PROCADDRESS_VAR_PREFIX + functionNameBase;"); - w.println(" java.lang.reflect.Field addressField = null;"); - w.println(" int funcNamePermNum = com.jogamp.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutationNumber(functionNameBase);"); - w.println(" for(int i = 0; null==addressField && i < funcNamePermNum; i++) {"); - w.println(" String addressFieldName = com.jogamp.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutation(addressFieldNameBase, i);"); - w.println(" try {"); - w.println(" addressField = getClass().getField(addressFieldName);"); - w.println(" } catch (Exception e) { }"); - w.println(" }"); - w.println(""); - w.println(" if(null==addressField) {"); - w.println(" // The user is calling a bogus function or one which is not"); - w.println(" // runtime linked"); - w.println(" throw new RuntimeException("); - w.println(" \"WARNING: Address field query failed for \\\"\" + functionNameBase + \"\\\"/\\\"\" + functionNameUsr +"); - w.println(" \"\\\"; it's either statically linked or address field is not a known \" +"); - w.println(" \"function\");"); - w.println(" } "); - w.println(" try {"); - w.println(" return addressField.getLong(this);"); - w.println(" } catch (Exception e) {"); - w.println(" throw new RuntimeException("); - w.println(" \"WARNING: Address query failed for \\\"\" + functionNameBase + \"\\\"/\\\"\" + functionNameUsr +"); - w.println(" \"\\\"; it's either statically linked or is not a known \" +"); - w.println(" \"function\", e);"); - w.println(" }"); - w.println(" }"); - - w.println("} // end of class " + tableClassName); - w.flush(); - w.close(); - } + + protected boolean needsBufferObjectVariant(FunctionSymbol sym) { + return getGLConfig().isBufferObjectFunction(sym.getName()); + } + + protected GLConfiguration getGLConfig() { + return (GLConfiguration) getConfig(); + } + + @Override + protected void endProcAddressTable() throws Exception { + PrintWriter w = tableWriter; + + w.println(" /**"); + w.println(" * This is a convenience method to get (by name) the native function"); + w.println(" * pointer for a given function. It lets you avoid having to"); + w.println(" * manually compute the "" + PROCADDRESS_VAR_PREFIX + " + "); + w.println(" * <functionName>" member variable name and look it up via"); + w.println(" * reflection; it also will throw an exception if you try to get the"); + w.println(" * address of an unknown function, or one that is statically linked"); + w.println(" * and therefore does not have a function pointer in this table."); + w.println(" *"); + w.println(" * @throws RuntimeException if the function pointer was not found in"); + w.println(" * this table, either because the function was unknown or because"); + w.println(" * it was statically linked."); + w.println(" */"); + w.println(" public long getAddressFor(String functionNameUsr) {"); + w.println(" String functionNameBase = com.jogamp.gluegen.runtime.opengl.GLExtensionNames.normalizeVEN(com.jogamp.gluegen.runtime.opengl.GLExtensionNames.normalizeARB(functionNameUsr, true), true);"); + w.println(" String addressFieldNameBase = " + getProcAddressConfig().gluegenRuntimePackage() + ".ProcAddressHelper.PROCADDRESS_VAR_PREFIX + functionNameBase;"); + w.println(" java.lang.reflect.Field addressField = null;"); + w.println(" int funcNamePermNum = com.jogamp.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutationNumber(functionNameBase);"); + w.println(" for(int i = 0; null==addressField && i < funcNamePermNum; i++) {"); + w.println(" String addressFieldName = com.jogamp.gluegen.runtime.opengl.GLExtensionNames.getFuncNamePermutation(addressFieldNameBase, i);"); + w.println(" try {"); + w.println(" addressField = getClass().getField(addressFieldName);"); + w.println(" } catch (Exception e) { }"); + w.println(" }"); + w.println(""); + w.println(" if(null==addressField) {"); + w.println(" // The user is calling a bogus function or one which is not"); + w.println(" // runtime linked"); + w.println(" throw new RuntimeException("); + w.println(" \"WARNING: Address field query failed for \\\"\" + functionNameBase + \"\\\"/\\\"\" + functionNameUsr +"); + w.println(" \"\\\"; it's either statically linked or address field is not a known \" +"); + w.println(" \"function\");"); + w.println(" } "); + w.println(" try {"); + w.println(" return addressField.getLong(this);"); + w.println(" } catch (Exception e) {"); + w.println(" throw new RuntimeException("); + w.println(" \"WARNING: Address query failed for \\\"\" + functionNameBase + \"\\\"/\\\"\" + functionNameUsr +"); + w.println(" \"\\\"; it's either statically linked or is not a known \" +"); + w.println(" \"function\", e);"); + w.println(" }"); + w.println(" }"); + + w.println("} // end of class " + tableClassName); + w.flush(); + w.close(); + } } diff --git a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java index 33f94fb19..51182c153 100755 --- a/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java +++ b/src/java/com/sun/gluegen/opengl/GLJavaMethodBindingEmitter.java @@ -36,7 +36,6 @@ * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ - package com.sun.gluegen.opengl; import java.io.*; @@ -45,89 +44,80 @@ import com.sun.gluegen.cgram.types.*; import com.sun.gluegen.procaddress.*; /** A specialization of the proc address emitter which knows how to - change argument names to take into account Vertex Buffer Object / - Pixel Buffer Object variants. */ - +change argument names to take into account Vertex Buffer Object / +Pixel Buffer Object variants. */ public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmitter { - protected boolean bufferObjectVariant; - protected GLEmitter glEmitter; - protected CommentEmitter glCommentEmitter = new GLCommentEmitter(); - - public GLJavaMethodBindingEmitter(JavaMethodBindingEmitter methodToWrap, - boolean callThroughProcAddress, - String getProcAddressTableExpr, - boolean changeNameAndArguments, - boolean bufferObjectVariant, - GLEmitter emitter) { - super(methodToWrap, - callThroughProcAddress, - getProcAddressTableExpr, - changeNameAndArguments, - emitter); - this.bufferObjectVariant = bufferObjectVariant; - this.glEmitter=emitter; - setCommentEmitter(glCommentEmitter); - } - - public GLJavaMethodBindingEmitter(ProcAddressJavaMethodBindingEmitter methodToWrap, - GLEmitter emitter, - boolean bufferObjectVariant) { - super(methodToWrap); - this.bufferObjectVariant = bufferObjectVariant; - this.glEmitter=emitter; - setCommentEmitter(glCommentEmitter); - } - - public GLJavaMethodBindingEmitter(GLJavaMethodBindingEmitter methodToWrap) { - this(methodToWrap, methodToWrap.glEmitter, methodToWrap.bufferObjectVariant); - } - - @Override - protected String getArgumentName(int i) { - String name = super.getArgumentName(i); - - if (!bufferObjectVariant) { - return name; + + protected boolean bufferObjectVariant; + protected GLEmitter glEmitter; + protected CommentEmitter glCommentEmitter = new GLCommentEmitter(); + + public GLJavaMethodBindingEmitter(JavaMethodBindingEmitter methodToWrap, boolean callThroughProcAddress, + String getProcAddressTableExpr, boolean changeNameAndArguments, boolean bufferObjectVariant, GLEmitter emitter) { + + super(methodToWrap, callThroughProcAddress, getProcAddressTableExpr, changeNameAndArguments, emitter); + this.bufferObjectVariant = bufferObjectVariant; + this.glEmitter = emitter; + setCommentEmitter(glCommentEmitter); } - // Emitters for VBO/PBO-related routines change the outgoing - // argument name for the buffer - if (binding.getJavaArgumentType(i).isLong()) { - Type cType = binding.getCArgumentType(i); - if (cType.isPointer() && - (cType.asPointer().getTargetType().isVoid() || - cType.asPointer().getTargetType().isPrimitive())) { - return name + "_buffer_offset"; - } + public GLJavaMethodBindingEmitter(ProcAddressJavaMethodBindingEmitter methodToWrap, GLEmitter emitter, boolean bufferObjectVariant) { + super(methodToWrap); + this.bufferObjectVariant = bufferObjectVariant; + this.glEmitter = emitter; + setCommentEmitter(glCommentEmitter); } - return name; - } + public GLJavaMethodBindingEmitter(GLJavaMethodBindingEmitter methodToWrap) { + this(methodToWrap, methodToWrap.glEmitter, methodToWrap.bufferObjectVariant); + } - protected class GLCommentEmitter extends JavaMethodBindingEmitter.DefaultCommentEmitter { - @Override - protected void emitBindingCSignature(MethodBinding binding, PrintWriter writer) { - super.emitBindingCSignature(binding, writer); - - String symbolRenamed = binding.getName(); - StringBuffer newComment = new StringBuffer(); - newComment.append("
Part of "); - if(0==glEmitter.addExtensionsOfSymbols2Buffer(newComment, ", ", symbolRenamed, binding.getAliasedNames())) { - if(glEmitter.getGLConfig().getAllowNonGLExtensions()) { - newComment.append("CORE FUNC"); - } else { - StringBuffer sb = new StringBuffer(); - JavaEmitter.addStrings2Buffer(sb, ", ", symbolRenamed, binding.getAliasedNames()); - RuntimeException ex = new RuntimeException("Couldn't find extension to: "+binding+" ; "+sb.toString()); - ex.printStackTrace(); - glEmitter.getGLConfig().getGLInfo().dump(); - // glEmitter.getGLConfig().dumpRenames(); - throw ex; - } - } - newComment.append(""); - writer.print(newComment.toString()); + protected String getArgumentName(int i) { + String name = super.getArgumentName(i); + + if (!bufferObjectVariant) { + return name; + } + + // Emitters for VBO/PBO-related routines change the outgoing + // argument name for the buffer + if (binding.getJavaArgumentType(i).isLong()) { + Type cType = binding.getCArgumentType(i); + Type targetType = cType.asPointer().getTargetType(); + if (cType.isPointer() && (targetType.isVoid() || targetType.isPrimitive())) { + return name + "_buffer_offset"; + } + } + + return name; + } + + protected class GLCommentEmitter extends JavaMethodBindingEmitter.DefaultCommentEmitter { + + @Override + protected void emitBindingCSignature(MethodBinding binding, PrintWriter writer) { + + super.emitBindingCSignature(binding, writer); + + String symbolRenamed = binding.getName(); + StringBuilder newComment = new StringBuilder(); + + newComment.append("
Part of "); + if (0 == glEmitter.addExtensionsOfSymbols2Buffer(newComment, ", ", symbolRenamed, binding.getAliasedNames())) { + if (glEmitter.getGLConfig().getAllowNonGLExtensions()) { + newComment.append("CORE FUNC"); + } else { + StringBuilder sb = new StringBuilder(); + JavaEmitter.addStrings2Buffer(sb, ", ", symbolRenamed, binding.getAliasedNames()); + RuntimeException ex = new RuntimeException("Couldn't find extension to: " + binding + " ; " + sb.toString()); + glEmitter.getGLConfig().getGLInfo().dump(); + // glEmitter.getGLConfig().dumpRenames(); + throw ex; + } + } + newComment.append(""); + writer.print(newComment.toString()); + } } - } } -- cgit v1.2.3